From dd3b05ff5ec2f032decbd8e06f7233adf903bf49 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 15:04:57 +0000 Subject: [PATCH 1/7] cpu: translate recursion through direct calls in cpu_switch_aot A CALL may now close a call cycle, an export's call to its own entry included. A call into a function whose translation is in progress uses an assumed return width and argument demands, at first 8 bytes and none. The cycle is translated again from the meet of the assumed and computed summaries until no computed width is lower and no demand is higher, the fixed-point return_width proposed in #317. The functions of a cycle are declared before their definitions and kept once its first function is done. A tail jump that closes a cycle stays refused, because the original runs such a cycle in constant stack. cpu_aot_recursion translates four exports that reach self-recursion, two- and three-function cycles, a cycle inside a cycle and an export that calls its own entry, and compares them with the original and a Python reference over 484 inputs each. Four exports must be refused, and two of them only because the cycle is translated again. The direct-call controls for self- and mutual recursion now translate, and a call that closes a cycle with a tail jump replaces them as a refusal. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014uAfgrqe3XyeqvkJrdnUK6 --- CMakeLists.txt | 6 + docs/experiments.md | 8 +- tests/cpu/bare_calls_check.py | 3 +- tests/cpu/calls_check.py | 18 +- tests/cpu/recursion.asm | 332 ++++++++++++++++++++++++++++++++++ tests/cpu/recursion.def | 9 + tests/cpu/recursion_check.py | 221 ++++++++++++++++++++++ tools/cpu_switch_aot.py | 121 ++++++++++--- 8 files changed, 686 insertions(+), 32 deletions(-) create mode 100644 tests/cpu/recursion.asm create mode 100644 tests/cpu/recursion.def create mode 100644 tests/cpu/recursion_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index d3db3a2d94..a31ea05ffc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3431,6 +3431,12 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME cpu_aot_direct_calls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/calls_check.py" check "$" "$" "$") + cpu_asm_fixture(cpu_recursion recursion) + # The exports from tail_ping on exist only to be refused; the test translates each alone. + cpu_translation(cpu_recursion cpu_switch_aot sum_export,parity_export,walk_export,fold_export) + add_test(NAME cpu_aot_recursion COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/recursion_check.py" "$" + "$" "$") cpu_asm_fixture(cpu_call_entries call_entries) cpu_translation(cpu_call_entries cpu_switch_aot entry_caller,entry_tail) add_test(NAME cpu_aot_call_entries COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index a0a10299eb..c041801e84 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -2792,9 +2792,13 @@ A function may use its stack frame. A forward pass over the control-flow graph g `cpu_aot_stack_frames` builds [`frame.asm`](../tests/cpu/frame.asm), with the unwind directives each prologue needs, and translates nine exports. `push_loop` pushes and pops RBX and RSI and uses them in a loop. `spill_widths` allocates 24 bytes, stores 8, 4, 2 and 1 bytes, reads them back in overlapping pieces, adds to a slot in place, and uses `SETB` into the frame and `CMOVL` from it. `home_save` has the MSVC `/O2` shape: it saves RBX and RSI into home space with `MOV [RSP+8], RBX` and `MOV [RSP+10h], RSI` before `PUSH RDI` and `SUB RSP, 20h`, restores them with `MOV` on each of two returns, and carries the unwind codes MSVC writes for that prologue. `home_args` is the `cl /Od` output for a small C function that stores its arguments to home space, writes a local on both sides of a branch and reloads it. `two_paths` pushes RSI on one path and RDI on the other, rejoins at the same depth, and returns early on a third path after restoring RBX. `home_spill` spills two arguments into home space with no allocation of its own, and `loop_counter` keeps a counter and an accumulator in the frame across a loop's back edge. `realloc_slot` releases its allocation with `ADD RSP`, allocates the same bytes again and writes the slot before reading it. `frame_bound`, whose frame array is exactly 4,096 bytes, is translated and compiled but never called. Through the register probe, each original and translated export is compared with a Python reference over the direct-call input pairs, on the return value, the guarded trace, RBX and RSI, and every path of each export is taken. The probe shows that the original saves and restores RBX and RSI and that the translation leaves the caller's RBX and RSI intact. It does not show that the translation reproduces the original's save and restore: the generated locals are not the physical registers, and the host compiler saves and restores those itself. The test checks that the built source is the translation of the export list, that each frame array has the expected size, and that `rsp` appears nowhere in the generated C++. Thirty-two controls must be rejected. Twenty-six are copies of the image with one or two instructions replaced by others of the same length: an unbalanced `POP`, two paths that join at different depths, a loop that pushes on every iteration, a nonvolatile register not restored on one path, restored from another register's slot by `MOV` or by `POP`, or loaded into RAX from its save slot, a local written on one path only, home space never written, a 4-byte store removed under a later 8-byte read, a loop counter written only on the back edge, a stack argument at entry RSP + 40, a read and a write of the return address, `LEA RAX, [RSP+8]`, `MOV RAX, RSP`, `SUB RSP, RCX`, `SUB` and `ADD RSP` by 14h, `ADD RSP` at entry, a `JAE` left reading the flags of `SUB RSP`, an access below RSP, a frame of 4,112 bytes, `realloc_slot` without the store into its second allocation, `ADD RBX, RCX` on the caller's RBX, `PUSH RAX` and `PUSH 5`. The six others are exports rejected as written: a saved RBX whose slot is released by `ADD RSP` and allocated again before `POP RBX`; a slot that `POP` read and released, allocated again and read without a new store; a RIP-relative address spilled to the frame and reloaded, refused at the store as a read of an undefined register; RBX saved twice and reloaded from the 8 bytes that straddle the two copies; RBX pushed as data after only BL was written; and a register read after `POP` restored it. With MSVC 14.52 `cl`, `link` and `ml64` run under Wine on Linux, 1,992 calls per side matched and every control was rejected. The Windows job runs the same test. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_stack_frames$' -V`. -The same translator follows direct calls and tail jumps to other functions of the image ([#317](https://github.com/R0Y00/Xbox2Windows/issues/317), step 2). A `CALL rel32`, or a direct `JMP` that leaves the function's owned ranges, must target a function entry of this image: the first byte of a verified primary runtime function (an unchained `.pdata` record with version 1 or 2 unwind data and a non-empty interval in executable code), or a non-forwarded code export in an executable section that lies outside every runtime-function interval. The start of a chained secondary range, an interior label (exported or not), a record start with any other unwind header, a forwarded export and a data export are not entries, and the message says which of these the target is. Each callee is translated once into the same source, as a static function named `fn_` that takes RCX, RDX, R8 and R9, and is defined before its first caller. A call to the caller's own entry is rejected as self-recursion and any longer cycle as mutual recursion. A caller is rejected when any callee is, and the message names the callee's RVA and its reason. A callee records how many low bytes of each argument register it may read while that register may still hold its entry value, and the caller must have those bytes defined at the call. After a call, RAX has the callee's return width of defined bytes. RCX, RDX and R8 to R11, the flags and the callee's 32-byte home space at RSP are undefined. The return address the `CALL` pushes and the callee's own frame lie below RSP, where the frame proof already holds every byte unwritten, because the bytes that `ADD RSP` and `POP` leave below RSP become unwritten; so they stay undefined if RSP later falls back over them. Nonvolatile registers keep their state, because each callee is itself checked to restore every one, and so do the other frame bytes, including saves by `MOV` into the caller's own home space above entry RSP, which the callee's home space cannot reach. RSP must be 8 mod 16 from entry at a call, so the native call is aligned, and the callee's home space must lie below the return address. A tail jump is checked like a `RET`, with RSP at its entry value and every nonvolatile register restored, and contributes the callee's return width. The callee's frame is its own array, so no frame address crosses a call. A frame address passed to a callee (`LEA RCX, [RSP+20h]`), stack arguments, indirect calls, callees with no reachable normal return, import thunks, and targets with no unwind entry or export (such as leaves that MSVC emits without `.pdata`) unless the invoker binds them as described below, stay rejected. +The same translator follows direct calls and tail jumps to other functions of the image ([#317](https://github.com/R0Y00/Xbox2Windows/issues/317), step 2). A `CALL rel32`, or a direct `JMP` that leaves the function's owned ranges, must target a function entry of this image: the first byte of a verified primary runtime function (an unchained `.pdata` record with version 1 or 2 unwind data and a non-empty interval in executable code), or a non-forwarded code export in an executable section that lies outside every runtime-function interval. The start of a chained secondary range, an interior label (exported or not), a record start with any other unwind header, a forwarded export and a data export are not entries, and the message says which of these the target is. Each callee is translated once into the same source, as a static function named `fn_` that takes RCX, RDX, R8 and R9, and is defined before its first caller. A call may close a call cycle, as described below. A caller is rejected when any callee is, and the message names the callee's RVA and its reason. A callee records how many low bytes of each argument register it may read while that register may still hold its entry value, and the caller must have those bytes defined at the call. After a call, RAX has the callee's return width of defined bytes. RCX, RDX and R8 to R11, the flags and the callee's 32-byte home space at RSP are undefined. The return address the `CALL` pushes and the callee's own frame lie below RSP, where the frame proof already holds every byte unwritten, because the bytes that `ADD RSP` and `POP` leave below RSP become unwritten; so they stay undefined if RSP later falls back over them. Nonvolatile registers keep their state, because each callee is itself checked to restore every one, and so do the other frame bytes, including saves by `MOV` into the caller's own home space above entry RSP, which the callee's home space cannot reach. RSP must be 8 mod 16 from entry at a call, so the native call is aligned, and the callee's home space must lie below the return address. A tail jump is checked like a `RET`, with RSP at its entry value and every nonvolatile register restored, and contributes the callee's return width. The callee's frame is its own array, so no frame address crosses a call. A frame address passed to a callee (`LEA RCX, [RSP+20h]`), stack arguments, indirect calls, callees with no reachable normal return, import thunks, and targets with no unwind entry or export (such as leaves that MSVC emits without `.pdata`) unless the invoker binds them as described below, stay rejected. -`cpu_aot_direct_calls` builds [`calls.asm`](../tests/cpu/calls.asm) and translates seven exports, which reach three unexported callees placed below them. `call_leaf` calls a leaf from a frame and keeps the trace pointer in RBX across the call. `chain3` calls `mid_step`, which spills RDX into its own frame above the callee's home space, calls the same leaf and reloads it, so the leaf is shared. `narrow_call` calls a callee that defines only AL and widens it with `MOVZX`. `narrow_tail` tail-jumps to that callee and reports width 1, `tail_call` tail-jumps to the leaf, and `tail_after_frame` pops its frame before tail-jumping to `mid_step`. `home_save_call` has the MSVC `/O2` save shapes around a call: RBX saved by `MOV` into its own home space before `SUB RSP, 28h`, and RSI saved by `MOV` into the allocation above the callee's home space. Through the register probe, the original must match a Python reference, and the translation must match the original on the defined return bytes, the guarded trace, RBX and RSI over 545 input pairs per export. The test checks that each callee is defined exactly once and that the reported return widths are 8 except for `narrow_tail`. Twenty copies must be rejected with their stated reason: a call to the caller's own entry, a call from `mid_step` back to `chain3`, calls into an instruction interior and to an instruction boundary that is not an entry, a target outside the image and one in `.rdata`, reads of RCX, R8 and the full RAX after a call, a second call to the leaf whose RCX and RDX the first call left undefined, a `SETE` after a call, a stack-argument read in a callee and an unsupported instruction two levels down, a spill and a `MOV` save of RSI moved into the callee's home space and reloaded after the call, a call at entry RSP - 0x30 and one at entry RSP - 0x8, a tail jump with a frame still allocated, a tail jump with RBX not restored, and, as built, `below_call`, which stores a slot at entry RSP - 0x40, raises RSP for a call whose return address overwrites it, and reloads it after RSP falls back (natively it returns the return address). Removing the volatile clobber accepts the RCX control, keeping RAX fully defined after a call accepts the narrow control, keeping the callee's home space defined accepts the spill control, dropping the callees' argument demands accepts the second-call control, translating a shared callee again for each caller emits it five times (and the C++ fails with `C2084`), and naming the wrong callee at a call fails `chain3`. On Windows 11 build 26200 with MSVC 19.50 and ML64, all 3,815 calls matched and every control was rejected. The C++ generated for the existing jump-table, `addr32`, entry-order, narrow, fourth-argument and frame fixtures is unchanged. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_direct_calls$' -V`. +`cpu_aot_direct_calls` builds [`calls.asm`](../tests/cpu/calls.asm) and translates seven exports, which reach three unexported callees placed below them. `call_leaf` calls a leaf from a frame and keeps the trace pointer in RBX across the call. `chain3` calls `mid_step`, which spills RDX into its own frame above the callee's home space, calls the same leaf and reloads it, so the leaf is shared. `narrow_call` calls a callee that defines only AL and widens it with `MOVZX`. `narrow_tail` tail-jumps to that callee and reports width 1, `tail_call` tail-jumps to the leaf, and `tail_after_frame` pops its frame before tail-jumping to `mid_step`. `home_save_call` has the MSVC `/O2` save shapes around a call: RBX saved by `MOV` into its own home space before `SUB RSP, 28h`, and RSI saved by `MOV` into the allocation above the callee's home space. Through the register probe, the original must match a Python reference, and the translation must match the original on the defined return bytes, the guarded trace, RBX and RSI over 545 input pairs per export. The test checks that each callee is defined exactly once and that the reported return widths are 8 except for `narrow_tail`. A copy with a call to the caller's own entry and one with a call from `mid_step` back to `chain3` must translate with a declared call cycle. Nineteen copies must be rejected with their stated reason: a call from `mid_step` back to `tail_after_frame`, which closes a cycle with that function's tail jump, calls into an instruction interior and to an instruction boundary that is not an entry, a target outside the image and one in `.rdata`, reads of RCX, R8 and the full RAX after a call, a second call to the leaf whose RCX and RDX the first call left undefined, a `SETE` after a call, a stack-argument read in a callee and an unsupported instruction two levels down, a spill and a `MOV` save of RSI moved into the callee's home space and reloaded after the call, a call at entry RSP - 0x30 and one at entry RSP - 0x8, a tail jump with a frame still allocated, a tail jump with RBX not restored, and, as built, `below_call`, which stores a slot at entry RSP - 0x40, raises RSP for a call whose return address overwrites it, and reloads it after RSP falls back (natively it returns the return address). Removing the volatile clobber accepts the RCX control, keeping RAX fully defined after a call accepts the narrow control, keeping the callee's home space defined accepts the spill control, dropping the callees' argument demands accepts the second-call control, translating a shared callee again for each caller emits it five times (and the C++ fails with `C2084`), and naming the wrong callee at a call fails `chain3`. On Windows 11 build 26200 with MSVC 19.50 and ML64, all 3,815 calls matched and every control was rejected. The C++ generated for the existing jump-table, `addr32`, entry-order, narrow, fourth-argument and frame fixtures is unchanged. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_direct_calls$' -V`. + +A `CALL` may close a call cycle ([#317](https://github.com/R0Y00/Xbox2Windows/issues/317), the fixed-point `return_width` proposed there). An export's call to its own entry translates that entry a second time as an internal function. A call into a function whose translation is in progress uses an assumed summary, at first 8 defined RAX bytes and no argument demands. When a function of the cycle is done, its computed return width and demands are compared with the assumed ones: if the computed width is lower or a demand is higher, the cycle is translated again from the lower width and the higher demands. Both move one way through a finite set, so this ends. When no computed width is lower and no demand is higher, every return of the cycle defines the assumed bytes and the cycle reads no more argument bytes, by induction on the depth of the calls that have returned. The functions of a cycle are kept together once its first function is done, after a declaration of each, so each may call any other. A cycle inside another is kept when its own first function is done. A refusal under an assumed summary stands, because a lower width or a higher demand cannot remove it. A tail jump that closes a cycle is refused with `tail jump within a call cycle`: the original runs such a cycle in constant stack and the C++ call does not. The translation's recursion depth is bounded by the host stack, whose use per call differs from the original's, so a recursion that ends on the console can overflow the host stack, or the reverse. + +`cpu_aot_recursion` builds [`recursion.asm`](../tests/cpu/recursion.asm) and translates four exports. `sum_export` calls `sum_down`, which recurses through `CALL` up to 511 levels and keeps its arguments in RBX and RSI across the call. `parity_export` calls `is_even` and `is_odd`, which call each other. `is_even` defines only AL at its base case and `is_odd` all of RAX, so only the second translation of the cycle gives `is_odd` its 1-byte width. `walk_export` calls `walk_a`, which is in a cycle with `walk_b` and `walk_c`. Only `walk_a` reads R8, so only the second translation makes `walk_c` demand it; `walk_b` also calls `count_down`, whose own cycle is kept while the outer cycle is still being translated. `fold_export` calls its own exported entry up to 64 levels. Through the register probe, the original must match a Python reference, and the translation must match the original on the return value, the guarded trace, RBX and RSI over 484 input pairs per export. The test checks that each of the eight internal functions is declared once and defined once, that `is_even` and `is_odd` return 1 byte and the others 8, and that exactly `walk_a`, `walk_b`, `walk_c` and the internal `fold_export` demand R8. Four exports must be refused as written: `tail_ping` and `tail_pong`, a cycle of tail jumps; `wide_odd`, which reads all of RAX after `is_odd`; `lost_k`, which calls `walk_c` after another call left R8 undefined; and `bad_a`, in a cycle with `bad_b`, which executes `CPUID`. Keeping the first summary of each cycle instead of translating it again (the test replaces `at_least_as_good`) accepts `wide_odd` and `lost_k`, and the test fails unless it does. Before this change all four exports were refused, with `self-recursion` or `mutual recursion: call cycle`. Measured on Linux x86-64 with `llvm-ml` 18, `lld-link` and `clang++` at `-O0` and `-O2`, with the original image mapped in-process and called through a Windows x64 register probe: the original matched the reference and kept RBX and RSI, and 3,872 translated calls matched it. The C++ generated for 15 other `cpu_switch_aot` fixtures and for the `calls`, `chains` and `rsp` fuzz programs at their default seeds, `calls` at `0xBEEF` and `chains` at `0xCCD1` with 128 functions, is unchanged. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_recursion$' -V`. `cpu_aot_call_entries` builds [`call_entries.asm`](../tests/cpu/call_entries.asm), whose `.pdata` and `.xdata` are written explicitly so the image has a primary function continued by a chained secondary range. It also exports an interior label of a primary function, a `.data` variable as `DATA` and a forwarder to `kernel32.GetTickCount`. The test reads the image's own records and checks that the translator's entries are exactly the four primary runtime functions. A framed `CALL` and a tail `JMP` to the primary leaf translate and match the original and a Python reference over 249 input pairs each. Eight retargeted copies must be rejected with the reason that names the distinction: the call retargeted to the exported interior label, the chained range's start, the data export and the forwarder; the tail jump retargeted to the interior label and the chained start; and the leaf's unwind header patched from version 1 to version 3, for both the call and the tail jump. The translator before this rule refused the first six later and for unrelated reasons (`no unique function interval`, `not in an executable section`, `edge outside owned ranges`), and accepted the last two. Removing the version check, or accepting an export at the start of an unverified record, accepts the version controls. Counting interior exports or chained ranges as entries, or classifying forwarders and data exports as code, fails the check of the entry table. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_call_entries$' -V`. diff --git a/tests/cpu/bare_calls_check.py b/tests/cpu/bare_calls_check.py index dd20ac08b8..23421b14d1 100644 --- a/tests/cpu/bare_calls_check.py +++ b/tests/cpu/bare_calls_check.py @@ -196,7 +196,8 @@ def apply(manifest, rvas): "call in a function without unwind data"), ("call_bare", [("bare_mix", 0x00, "48 6b c9 05", "53 5b 90 90")], None, "stack change in a function without unwind data"), - ("call_bare", [("bare_mix", 0x00, "48 6b c9 05 48 8b c1", ("call", "bare_mix"))], None, "self-recursion"), + ("call_bare", [("bare_mix", 0x00, "48 6b c9 05 48 8b c1", ("call", "bare_mix"))], None, + "call in a function without unwind data"), ] diff --git a/tests/cpu/calls_check.py b/tests/cpu/calls_check.py index 444e250d90..06dd4fbbe5 100644 --- a/tests/cpu/calls_check.py +++ b/tests/cpu/calls_check.py @@ -9,6 +9,7 @@ import ctypes from pathlib import Path import random +import re import struct import sys @@ -173,9 +174,12 @@ def check(probe_path, original_path, lifted_path): # the callees' RVAs as {leaf}, {mid} and {low}. CALL = "e8 ?? ?? ?? ??" CONTROLS = [ - ("call_leaf", [("call_leaf", 0x08, CALL, ("call", "call_leaf"))], "self-recursion"), - ("chain3", [("mid", 0x0c, CALL, ("call", "chain3"))], - "callee at RVA {mid:#x} refused: mutual recursion: call cycle"), + # Recursion through CALL is translated (tests/cpu/recursion_check.py); a cycle that a tail jump + # closes is not. A reason of None means the patched copy must translate. + ("call_leaf", [("call_leaf", 0x08, CALL, ("call", "call_leaf"))], None), + ("chain3", [("mid", 0x0c, CALL, ("call", "chain3"))], None), + ("tail_after_frame", [("mid", 0x0c, CALL, ("call", "tail_after_frame"))], + "callee at RVA {mid:#x} refused: callee at RVA {tail_after_frame:#x} refused: tail jump within a call cycle"), ("call_leaf", [("call_leaf", 0x08, CALL, ("call", ("leaf", 1)))], "is not a function entry"), ("call_leaf", [("call_leaf", 0x08, CALL, ("call", ("leaf", 4)))], "is not a function entry"), ("call_leaf", [("call_leaf", 0x08, CALL, ("call", ("rva", "end")))], "call target outside the image"), @@ -236,7 +240,7 @@ def resolve(target): with TemporaryDirectory() as folder: path = Path(folder) / "control.dll" for name, patches, reason in CONTROLS: - reason = reason.format(**rvas) + reason = None if reason is None else reason.format(**rvas) damaged = bytearray(data) sites = [] for function, delta, before, after in patches: @@ -263,6 +267,12 @@ def resolve(target): raise AssertionError(f"unexpected encoding for control {reason!r} in {function}") damaged[at:at + len(after)] = after path.write_bytes(damaged) + if reason is None: + source, _ = aot.translate(path, [name]) + if not re.search(r"^static word fn_[0-9a-f]+\(word rcx, word rdx, word r8, word r9\);$", source, re.M): + raise AssertionError(f"{name} control ({', '.join(sites)}) has no declared call cycle") + print(f"control {name} ({', '.join(sites)}): translated with a declared call cycle") + continue try: aot.translate(path, [name]) except ValueError as error: diff --git a/tests/cpu/recursion.asm b/tests/cpu/recursion.asm new file mode 100644 index 0000000000..a2b272e769 --- /dev/null +++ b/tests/cpu/recursion.asm @@ -0,0 +1,332 @@ +; Source-owned differential fixture for recursion through direct calls in the jump-table translator. +; Each export is fn(x, y, trace) with x in RCX, y in RDX and a three-word trace in R8, and returns +; RAX. The recursive functions are not exported: each has its own runtime-function entry. The +; register probe seeds RBX and RSI, so a save or restore that the translation loses shows up as a +; changed sentinel. The exports from tail_ping on exist only to be refused. +.code + +; sum_down(n, k): the sum of i XOR k for i = n down to 1, by self-recursion through CALL. RBX and +; RSI keep n and k across the call. +sum_down PROC FRAME + push rbx + .pushreg rbx + push rsi + .pushreg rsi + sub rsp, 28h + .allocstack 28h + .endprolog + xor eax, eax + test rcx, rcx + jz sum_down_done + mov rbx, rcx + mov rsi, rdx + lea rcx, [rbx-1] + call sum_down + mov rcx, rbx + xor rcx, rsi + add rax, rcx +sum_down_done: + add rsp, 28h + pop rsi + pop rbx + ret +sum_down ENDP + +; is_even(n): AL = 1 when n is even, through is_odd. Only AL is defined at the base case. +is_even PROC FRAME + sub rsp, 28h + .allocstack 28h + .endprolog + test rcx, rcx + jnz is_even_step + mov al, 1 + add rsp, 28h + ret +is_even_step: + dec rcx + call is_odd + add rsp, 28h + ret +is_even ENDP + +; is_odd(n): AL = 1 when n is odd, through is_even. Its base case defines all of RAX, so only +; the cycle limits its return to AL. +is_odd PROC FRAME + sub rsp, 28h + .allocstack 28h + .endprolog + test rcx, rcx + jnz is_odd_step + xor eax, eax + add rsp, 28h + ret +is_odd_step: + dec rcx + call is_even + add rsp, 28h + ret +is_odd ENDP + +; count_down(n): the sum of i AND 3 for i = n down to 1. Its own cycle, reached only from walk_b. +count_down PROC FRAME + push rbx + .pushreg rbx + sub rsp, 20h + .allocstack 20h + .endprolog + xor eax, eax + test rcx, rcx + jz count_down_done + mov rbx, rcx + dec rcx + call count_down + and ebx, 3 + add rax, rbx +count_down_done: + add rsp, 20h + pop rbx + ret +count_down ENDP + +; walk_a(n, v, k): v XOR k when n = 0, otherwise walk_b(n - 1, v + n, k) + 1. The only read of k +; (R8) in the cycle walk_a -> walk_b -> walk_c -> walk_a is here. +walk_a PROC FRAME + sub rsp, 28h + .allocstack 28h + .endprolog + test rcx, rcx + jnz walk_a_step + mov rax, rdx + xor rax, r8 + add rsp, 28h + ret +walk_a_step: + add rdx, rcx + dec rcx + call walk_b + inc rax + add rsp, 28h + ret +walk_a ENDP + +; walk_b(n, v, k): v when n = 0, otherwise walk_c(n - 1, 3 * v, k) XOR count_down(n). +walk_b PROC FRAME + push rbx + .pushreg rbx + push rsi + .pushreg rsi + sub rsp, 28h + .allocstack 28h + .endprolog + mov rax, rdx + test rcx, rcx + jz walk_b_done + mov rbx, rcx + lea rdx, [rdx+rdx*2] + dec rcx + call walk_c + mov rsi, rax + mov rcx, rbx + call count_down + xor rax, rsi +walk_b_done: + add rsp, 28h + pop rsi + pop rbx + ret +walk_b ENDP + +; walk_c(n, v, k): v when n = 0, otherwise walk_a(n - 1, v + 5, k). It passes k on without +; reading it, so only the cycle makes it demand R8. +walk_c PROC FRAME + sub rsp, 28h + .allocstack 28h + .endprolog + mov rax, rdx + test rcx, rcx + jz walk_c_done + dec rcx + add rdx, 5 + call walk_a +walk_c_done: + add rsp, 28h + ret +walk_c ENDP + +; trace[0] = sum_down(x AND 1FFh, y); returns it plus x. +sum_export PROC FRAME + push rbx + .pushreg rbx + push rsi + .pushreg rsi + sub rsp, 28h + .allocstack 28h + .endprolog + mov rbx, r8 + mov rsi, rcx + and ecx, 1FFh + call sum_down + mov qword ptr [rbx], rax + add rax, rsi + add rsp, 28h + pop rsi + pop rbx + ret +sum_export ENDP + +; trace[1] = is_even(x AND 0FFh), trace[2] = is_odd(y AND 0FFh); returns their sum. Both +; results are AL only, which MOVZX widens. +parity_export PROC FRAME + push rbx + .pushreg rbx + push rsi + .pushreg rsi + sub rsp, 28h + .allocstack 28h + .endprolog + mov rbx, r8 + mov rsi, rdx + movzx ecx, cl + call is_even + movzx eax, al + mov qword ptr [rbx+8], rax + movzx ecx, sil + call is_odd + movzx eax, al + mov qword ptr [rbx+10h], rax + add rax, qword ptr [rbx+8] + add rsp, 28h + pop rsi + pop rbx + ret +parity_export ENDP + +; trace[2] = walk_a(x AND 3Fh, y, x XOR y). +walk_export PROC FRAME + push rbx + .pushreg rbx + sub rsp, 20h + .allocstack 20h + .endprolog + mov rbx, r8 + mov r8, rcx + xor r8, rdx + and ecx, 3Fh + call walk_a + mov qword ptr [rbx+10h], rax + add rsp, 20h + pop rbx + ret +walk_export ENDP + +; fold_export(x, y, trace): y when x = 0, with trace[2] = y; otherwise fold_export(x SHR 1, +; 2 * y + (x AND 1), trace) + (x AND 1). It calls its own exported entry. +fold_export PROC FRAME + push rbx + .pushreg rbx + sub rsp, 20h + .allocstack 20h + .endprolog + test rcx, rcx + jnz fold_step + mov qword ptr [r8+10h], rdx + mov rax, rdx + jmp fold_done +fold_step: + mov ebx, ecx + and ebx, 1 + lea rdx, [rbx+rdx*2] + shr rcx, 1 + call fold_export + add rax, rbx +fold_done: + add rsp, 20h + pop rbx + ret +fold_export ENDP + +; Refused: tail_ping and tail_pong form a cycle of tail jumps, which the original runs in +; constant stack. +tail_ping PROC FRAME + .endprolog + test rcx, rcx + jz tail_ping_done + dec rcx + jmp tail_pong +tail_ping_done: + mov rax, rdx + ret +tail_ping ENDP + +tail_pong PROC FRAME + .endprolog + add rdx, 3 + jmp tail_ping +tail_pong ENDP + +; Refused: after is_even, is_odd returns only AL, so the full read of RAX is undefined. +wide_odd PROC FRAME + push rbx + .pushreg rbx + sub rsp, 20h + .allocstack 20h + .endprolog + mov rbx, rcx + call is_even + mov rcx, rbx + call is_odd + add rax, rbx + add rsp, 20h + pop rbx + ret +wide_odd ENDP + +; Refused: after walk_a, walk_c is called with R8 undefined, and the cycle reads it. +lost_k PROC FRAME + push rbx + .pushreg rbx + sub rsp, 20h + .allocstack 20h + .endprolog + mov rbx, rcx + call walk_a + mov rcx, rbx + mov rdx, rax + call walk_c + add rsp, 20h + pop rbx + ret +lost_k ENDP + +; Refused: bad_b, in a cycle with bad_a, executes CPUID, which the translator does not lower. +bad_a PROC FRAME + sub rsp, 28h + .allocstack 28h + .endprolog + xor eax, eax + test rcx, rcx + jz bad_a_done + dec rcx + call bad_b +bad_a_done: + add rsp, 28h + ret +bad_a ENDP + +bad_b PROC FRAME + push rbx + .pushreg rbx + sub rsp, 20h + .allocstack 20h + .endprolog + mov rbx, rcx + xor eax, eax + cpuid + mov rcx, rbx + call bad_a + add rsp, 20h + pop rbx + ret +bad_b ENDP + +END diff --git a/tests/cpu/recursion.def b/tests/cpu/recursion.def new file mode 100644 index 0000000000..8ee23e1be5 --- /dev/null +++ b/tests/cpu/recursion.def @@ -0,0 +1,9 @@ +EXPORTS + sum_export + parity_export + walk_export + fold_export + tail_ping + wide_odd + lost_k + bad_a diff --git a/tests/cpu/recursion_check.py b/tests/cpu/recursion_check.py new file mode 100644 index 0000000000..fe144107fc --- /dev/null +++ b/tests/cpu/recursion_check.py @@ -0,0 +1,221 @@ +"""Differential checks for recursion through direct calls in the jump-table translator. + +Each export of tests/cpu/recursion.asm runs through the register probe. The source-built original +must match the Python reference, and the translation must match the original on the return value, +the guarded trace and the probe's RBX and RSI sentinels. The structure check reads the summaries +that the call cycles settle on. The refused exports must be refused with their stated reason, and +two of them must be accepted when the translator keeps the first summary of a cycle instead of +iterating, so the iteration is what refuses them. +""" + +import ctypes +from pathlib import Path +import random +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from direct_check import GUARDS, MASK, SENTINELS, observe, register_probe + +EXPORTS = ("sum_export", "parity_export", "walk_export", "fold_export") +# (export, expected refusal), translated alone. +REFUSED = ( + ("tail_ping", "callee at RVA {tail_pong:#x} refused: callee at RVA {tail_ping:#x} refused: " + "tail jump within a call cycle"), + ("wide_odd", "undefined register rax"), + ("lost_k", "callee argument r8 is undefined"), + ("bad_a", "callee at RVA {bad_b:#x} refused: unsupported instruction"), +) +# Refused only because a cycle's first summary is translated again. +ITERATED = ("wide_odd", "lost_k") + + +def trace(first=MASK, second=MASK, third=MASK): + return (GUARDS[0], first & MASK, second & MASK, third & MASK, GUARDS[1]) + + +def sum_down(n, k): + return sum(i ^ k for i in range(1, n + 1)) & MASK + + +def count_down(n): + return sum(i & 3 for i in range(1, n + 1)) + + +def walk_a(n, v, k): + return v ^ k if n == 0 else (walk_b(n - 1, (v + n) & MASK, k) + 1) & MASK + + +def walk_b(n, v, k): + return v if n == 0 else walk_c(n - 1, 3 * v & MASK, k) ^ count_down(n) + + +def walk_c(n, v, k): + return v if n == 0 else walk_a(n - 1, (v + 5) & MASK, k) + + +def sum_export(x, y): + value = sum_down(x & 0x1ff, y) + return (value + x) & MASK, trace(value) + + +def parity_export(x, y): + even, odd = int((x & 0xff) % 2 == 0), int((y & 0xff) % 2 == 1) + return even + odd, trace(second=even, third=odd) + + +def walk_export(x, y): + value = walk_a(x & 0x3f, y, x ^ y) + return value, trace(third=value) + + +def fold(x, y): + if x == 0: + return y, y + value, base = fold(x >> 1, (2 * y + (x & 1)) & MASK) + return (value + (x & 1)) & MASK, base + + +def fold_export(x, y): + value, base = fold(x, y) + return value, trace(third=base) + + +REFERENCES = {name: globals()[name] for name in EXPORTS} + + +def inputs(): + """Boundary words for both arguments, plus seeded random pairs.""" + edges = (0, 1, 2, 3, 0x3f, 0x40, 0xff, 0x100, 0x1ff, 0x200, 0x7fffffff, 0x80000000, 0xffffffff, + 0x100000000, 0x8000000000000000, MASK - 1, MASK, 0x0123456789abcdef) + rng = random.Random(1221) + pairs = [(x, y) for x in edges for y in edges] + pairs += [(rng.getrandbits(64), rng.getrandbits(64)) for _ in range(160)] + return pairs + + +def run(probe, library, prefix=""): + observed = {} + for name in EXPORTS: + function = ctypes.cast(getattr(library, prefix + name), ctypes.c_void_p).value + observed[name] = [observe(probe, function, x, y) for x, y in inputs()] + return observed + + +def verify_reference(observed, label): + for name in EXPORTS: + for (x, y), (returned, words, registers) in zip(inputs(), observed[name]): + want = REFERENCES[name](x, y) + if (returned, words) != want or registers != SENTINELS: + raise AssertionError(f"{label} {name}({x:#x}, {y:#x}): {returned:#x} {words} {registers} " + f"!= {want[0]:#x} {want[1]} {SENTINELS}") + + +def tools(): + sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) + import pefile + from cpu_leaf_aot import export_rva + import cpu_switch_aot + return pefile, export_rva, cpu_switch_aot + + +def layout(pe, export_rva, aot): + """RVAs of the exports and of the functions their direct calls and tail jumps reach.""" + from iced_x86 import Decoder, FlowControl + ends = dict(aot.runtime_functions(pe)) + rvas = {name: export_rva(pe, name) for name in EXPORTS + tuple(name for name, _ in REFUSED)} + + def targets(rva): + found = [] + for ins in Decoder(64, pe.get_data(rva, ends[rva] - rva), ip=rva): + if ins.flow_control == FlowControl.CALL or (ins.flow_control == FlowControl.UNCONDITIONAL_BRANCH + and ins.near_branch_target in ends): + found.append(ins.near_branch_target) + return found + + rvas["sum_down"], = targets(rvas["sum_export"]) + rvas["is_even"], rvas["is_odd"] = targets(rvas["parity_export"]) + rvas["walk_a"], = targets(rvas["walk_export"]) + rvas["walk_b"], = targets(rvas["walk_a"]) + rvas["walk_c"], rvas["count_down"] = targets(rvas["walk_b"]) + rvas["tail_pong"], = targets(rvas["tail_ping"]) + rvas["bad_b"], = targets(rvas["bad_a"]) + return rvas + + +def check(probe_path, original_path, lifted_path): + probe = register_probe(probe_path) + original = run(probe, ctypes.CDLL(str(original_path))) + verify_reference(original, "source fixture") + translated = run(probe, ctypes.CDLL(str(lifted_path)), "lifted_") + for name in EXPORTS: + for (x, y), want, got in zip(inputs(), original[name], translated[name]): + if got != want: + raise AssertionError(f"translation {name}({x:#x}, {y:#x}): {got} != {want}") + print(f"{len(EXPORTS)} exports x {len(inputs())} inputs: the source fixture matches the reference and the " + "translation matches it on the return value, guarded trace, RBX and RSI") + + +def check_structure(original_path): + pefile, export_rva, aot = tools() + with pefile.PE(str(original_path), fast_load=True) as pe: + pe.parse_data_directories() + rvas = layout(pe, export_rva, aot) + program = aot.Program(pe) + functions = [aot.lift(pe, name, program=program) for name in EXPORTS] + source = "\n".join(program.sources + [text for text, _ in functions]) + internal = ("sum_down", "is_even", "is_odd", "count_down", "walk_a", "walk_b", "walk_c", "fold_export") + declaration = "static word fn_{:x}(word rcx, word rdx, word r8, word r9)" + for name in internal: + text = declaration.format(rvas[name]) + if source.count(text + " {") != 1 or source.count(text + ";") != 1: + raise AssertionError(f"{name} at RVA {rvas[name]:#x} is not declared once and defined once") + if source.count("static word fn_") != 2 * len(internal): + raise AssertionError(f"expected {len(internal)} declared internal functions") + widths = {name: program.callees[rvas[name]].return_width for name in internal} + want = dict.fromkeys(internal, 8) | {"is_even": 1, "is_odd": 1} + if widths != want: + raise AssertionError(f"return widths {widths} != {want}") + r8 = aot.R.R8 + demands = {name: program.callees[rvas[name]].demands.get(r8, 0) for name in internal} + want = dict.fromkeys(internal, 0) | {"walk_a": 8, "walk_b": 8, "walk_c": 8, "fold_export": 8} + if demands != want: + raise AssertionError(f"R8 demands {demands} != {want}") + print(f"{len(internal)} recursive functions declared and defined once; return widths {widths}; R8 demands {demands}") + + +def check_refusals(original_path): + pefile, export_rva, aot = tools() + with pefile.PE(str(original_path), fast_load=True) as pe: + pe.parse_data_directories() + rvas = layout(pe, export_rva, aot) + for name, reason in REFUSED: + reason = reason.format(**rvas) + try: + aot.translate(original_path, [name]) + except ValueError as error: + if reason not in str(error): + raise AssertionError(f"{name} refused for another reason: {error}") from error + else: + raise AssertionError(f"{name} accepted: {reason}") + print(f"control {name}: {reason}") + # The planted fault: keep a cycle's first summary, however it compares with the assumption. + iterate = aot.at_least_as_good + aot.at_least_as_good = lambda computed, assumed: True + try: + for name in ITERATED: + try: + aot.translate(original_path, [name]) + except ValueError as error: + raise AssertionError(f"{name} is refused without the iteration: {error}") from error + print(f"control {name}: accepted when the first summary of a cycle is kept") + finally: + aot.at_least_as_good = iterate + print(f"{len(REFUSED)} recursion rejection controls passed") + + +if __name__ == "__main__": + if len(sys.argv) != 4: + raise SystemExit("usage: recursion_check.py PROBE ORIGINAL LIFTED") + check(*sys.argv[1:]) + check_structure(sys.argv[2]) + check_refusals(sys.argv[2]) diff --git a/tools/cpu_switch_aot.py b/tools/cpu_switch_aot.py index bab83ebe27..e0c47d2703 100644 --- a/tools/cpu_switch_aot.py +++ b/tools/cpu_switch_aot.py @@ -128,9 +128,8 @@ defined before its first caller. A target must be the first byte of a verified primary runtime function (unchained, version 1 or 2 unwind data, executable) or a non-forwarded code export that no other function's interval holds; chained -ranges, interior labels, forwarded and data exports are refused. A call -to the caller's own entry and any call cycle are refused, and a caller is -refused when any callee is. A callee records how many low bytes of each argument +ranges, interior labels, forwarded and data exports are refused. A caller +is refused when any callee is. A callee records how many low bytes of each argument register it may read before writing it, and the caller must define them at the call. After a call RAX holds the callee's return width of defined bytes; the other volatile registers, the flags and the callee's 32-byte home space at RSP @@ -144,6 +143,15 @@ width. The callee's frame is its own array, so no frame address crosses a call, and stack arguments stay refused. +A CALL may close a call cycle, an export's own entry included, which becomes an +internal function too. A call into a function whose translation is in progress +uses an assumed return width and demands, at first 8 bytes and none, and the +functions of the cycle are translated again from the meet of the assumed and +computed values until no computed width is lower and no demand higher. Each +function of a cycle is declared before the definitions. A tail jump that closes +a cycle is refused: the original runs such a cycle in constant stack. The host +stack bounds the depth of recursion, at a depth that differs from the original. + A target without unwind data or export is refused, with a message saying that a range binding is needed, unless the invoker supplies one: --bind-ranges names a JSON manifest of trusted [start, end) RVAs from the source labels of this @@ -526,8 +534,6 @@ def owns(self, ip): def callee(self, ins): """Validate the target of a direct CALL as the entry of another function in the image.""" target = ins.near_branch_target - if target == self.entry: - raise ValueError(f"self-recursion at RVA {ins.ip:#x}") if not 0 <= target < self.pe.OPTIONAL_HEADER.SizeOfImage: raise ValueError(f"call target outside the image at RVA {ins.ip:#x}") section = self.pe.get_section_by_rva(target) @@ -1820,9 +1826,30 @@ def demands(self): return dict(zip(ARGUMENT_REGISTERS, self.widths)) +class Assumed(NamedTuple): + """The summary that calls into a function still being translated use: its return width and + argument demands, assumed until its translation computes them.""" + entry: int + return_width: int + demands: dict + + +def at_least_as_good(computed, assumed): + """Whether a computed summary defines at least the assumed RAX bytes and demands no more.""" + return (computed.return_width >= assumed.return_width + and all(width <= assumed.demands.get(r, 0) for r, width in computed.demands.items())) + + class Program: """The functions of one image reached from the requested exports through direct calls and tail - jumps. Each callee is translated once, in internal mode, and its source precedes its callers'.""" + jumps. Each callee is translated once, in internal mode, and its source precedes its callers'. + + A call to an internal function whose translation is in progress closes a call cycle. It uses an + assumed summary, at first 8 defined RAX bytes and no demands. Each function of the cycle is + translated again with the meet of the assumed and computed summaries until each computed + summary defines at least the assumed bytes and demands no more. Its returns then define those + bytes and it reads no more, by induction on the depth of calls that return. The functions of a + cycle are kept once its first function is done, after declarations, so each may call any other.""" def __init__(self, pe, bindings=None, *, image_data=False, imports=None, host_cpu=False): self.pe = pe @@ -1830,41 +1857,81 @@ def __init__(self, pe, bindings=None, *, image_data=False, imports=None, host_cp self.host_cpu = host_cpu self.imports = imports or {} self.entries = Entries(pe, bindings) - self.active = [] + self.active = [] # (entry, internal) of each translation in progress, outermost first + self.lows = [] # per active translation: the lowest active depth it has used a summary from + self.assumed = {} + self.pending = [] # (entry, source, function, low) of cycle functions not yet kept self.callees = {} self.refused = {} self.sources = [] self.import_resolver = None def lift(self, entry, symbol, arguments, internal=False): - self.active.append(entry) + self.active.append((entry, internal)) + self.lows.append(len(self.active) - 1) try: return lift_function(self, entry, symbol, arguments, internal) finally: self.active.pop() + self.low = self.lows.pop() + if self.lows: + self.lows[-1] = min(self.lows[-1], self.low) + + def depends(self, depth): + self.lows[-1] = min(self.lows[-1], depth) + + def committed(self, callee): + return isinstance(callee, HostImport) or self.callees.get(callee.entry) is callee def callee(self, target, ip): if target in self.refused: raise ValueError(f"callee at RVA {target:#x} refused: {self.refused[target]}") if target in self.callees: return self.callees[target] - if target in self.active: - cycle = self.active[self.active.index(target):] + [target] - raise ValueError(f"mutual recursion: call cycle {' -> '.join(f'{rva:#x}' for rva in cycle)} " - f"at RVA {ip:#x}") - if len(self.callees) >= MAX_CALLEES: + for entry, _, function, low in self.pending: + if entry == target: + self.depends(low) + return function + depth = next((d for d, (entry, internal) in enumerate(self.active) if internal and entry == target), None) + if depth is not None: + self.depends(depth) + return self.assumed.setdefault(target, Assumed(target, 8, {})) + if len(self.callees) + len(self.pending) >= MAX_CALLEES: raise ValueError(f"callee limit reached at RVA {ip:#x}") - try: - source, function = self.lift(target, f"fn_{target:x}", ARGUMENT_REGISTERS, internal=True) - except ValueError as error: - self.refused[target] = str(error) - raise ValueError(f"callee at RVA {target:#x} refused: {error}") from None - if function.return_width is None: - error = "no reachable normal return" - self.refused[target] = error - raise ValueError(f"callee at RVA {target:#x} refused: {error}") - self.callees[target] = function - self.sources.append(source) + depth = len(self.active) + start = len(self.pending) + while True: + try: + source, function = self.lift(target, f"fn_{target:x}", ARGUMENT_REGISTERS, internal=True) + if function.return_width is None: + raise ValueError("no reachable normal return") + except ValueError as error: + del self.pending[start:] + self.assumed.pop(target, None) + self.refused[target] = str(error) + raise ValueError(f"callee at RVA {target:#x} refused: {error}") from None + assumed = self.assumed.get(target) + if assumed is None or at_least_as_good(function, assumed): + break + # Translate the cycle again from a summary that both bounds. + demands = {r: max(width, function.demands.get(r, 0)) + for r, width in assumed.demands.items()} | { + r: width for r, width in function.demands.items() if r not in assumed.demands} + self.assumed[target] = Assumed(target, min(assumed.return_width, function.return_width), demands) + del self.pending[start:] + if self.low < depth: + # Part of a cycle through a function below it on the stack, which keeps it when that is done. + self.pending.append((target, source, function, self.low)) + return function + members = [(entry, text, member) for entry, text, member, _ in self.pending[start:]] + [(target, source, function)] + del self.pending[start:] + cyclic = [self.assumed.pop(entry, None) for entry, _, _ in members] + if any(cyclic) or len(members) > 1: + self.sources.append("\n".join(f"static word fn_{entry:x}({', '.join(f'word {NAMES[r]}' for r in ARGUMENT_REGISTERS)});" + for entry, _, _ in sorted(members, key=lambda m: m[0]))) + for entry, text, member in members: + self.callees[entry] = member + self.sources.append(text) return function @@ -1932,7 +1999,11 @@ def lift_function(program, entry, symbol, arguments, internal): callees = {ip: (function.host_calls[ip] if ip in function.host_calls else program.callee(target, ip)) for ip, target in sorted({**function.calls, **function.tails}.items())} - loads = {sequence[0]: index for index, _, sequence, _, _, _ in function.dispatches.values()} + for ip in sorted(function.tails): + if not program.committed(callees[ip]): + # The original runs a cycle of tail jumps in constant stack; the host call does not. + raise ValueError(f"tail jump within a call cycle at RVA {ip:#x}") + loads ={sequence[0]: index for index, _, sequence, _, _, _ in function.dispatches.values()} skipped = {ip for _, _, sequence, _, _, _ in function.dispatches.values() for ip in sequence} body = {} effects = {} From dc111cbe5b30006bf31aa296defe4887438db92c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 15:15:52 +0000 Subject: [PATCH 2/7] cpu: keep a function that reuses a held cycle member in that cycle When a function of a call cycle goes on hold, the functions held during its translation still recorded its stack depth as their dependence. A later translation at the same depth that reused one of them was then kept on its own, with the summary first assumed for the cycle, and a tail jump to it was not seen to close the cycle. The held functions now take on the dependence of the function that goes on hold. stale_e in recursion.asm reaches that order and must be refused: its callee reads all of RAX after a function that returns only AL through the cycle. Before this change it was accepted with 8 bytes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014uAfgrqe3XyeqvkJrdnUK6 --- docs/experiments.md | 4 +-- tests/cpu/recursion.asm | 69 ++++++++++++++++++++++++++++++++++++ tests/cpu/recursion.def | 1 + tests/cpu/recursion_check.py | 2 ++ tools/cpu_switch_aot.py | 5 ++- 5 files changed, 78 insertions(+), 3 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index c041801e84..1bf0274d84 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -2796,9 +2796,9 @@ The same translator follows direct calls and tail jumps to other functions of th `cpu_aot_direct_calls` builds [`calls.asm`](../tests/cpu/calls.asm) and translates seven exports, which reach three unexported callees placed below them. `call_leaf` calls a leaf from a frame and keeps the trace pointer in RBX across the call. `chain3` calls `mid_step`, which spills RDX into its own frame above the callee's home space, calls the same leaf and reloads it, so the leaf is shared. `narrow_call` calls a callee that defines only AL and widens it with `MOVZX`. `narrow_tail` tail-jumps to that callee and reports width 1, `tail_call` tail-jumps to the leaf, and `tail_after_frame` pops its frame before tail-jumping to `mid_step`. `home_save_call` has the MSVC `/O2` save shapes around a call: RBX saved by `MOV` into its own home space before `SUB RSP, 28h`, and RSI saved by `MOV` into the allocation above the callee's home space. Through the register probe, the original must match a Python reference, and the translation must match the original on the defined return bytes, the guarded trace, RBX and RSI over 545 input pairs per export. The test checks that each callee is defined exactly once and that the reported return widths are 8 except for `narrow_tail`. A copy with a call to the caller's own entry and one with a call from `mid_step` back to `chain3` must translate with a declared call cycle. Nineteen copies must be rejected with their stated reason: a call from `mid_step` back to `tail_after_frame`, which closes a cycle with that function's tail jump, calls into an instruction interior and to an instruction boundary that is not an entry, a target outside the image and one in `.rdata`, reads of RCX, R8 and the full RAX after a call, a second call to the leaf whose RCX and RDX the first call left undefined, a `SETE` after a call, a stack-argument read in a callee and an unsupported instruction two levels down, a spill and a `MOV` save of RSI moved into the callee's home space and reloaded after the call, a call at entry RSP - 0x30 and one at entry RSP - 0x8, a tail jump with a frame still allocated, a tail jump with RBX not restored, and, as built, `below_call`, which stores a slot at entry RSP - 0x40, raises RSP for a call whose return address overwrites it, and reloads it after RSP falls back (natively it returns the return address). Removing the volatile clobber accepts the RCX control, keeping RAX fully defined after a call accepts the narrow control, keeping the callee's home space defined accepts the spill control, dropping the callees' argument demands accepts the second-call control, translating a shared callee again for each caller emits it five times (and the C++ fails with `C2084`), and naming the wrong callee at a call fails `chain3`. On Windows 11 build 26200 with MSVC 19.50 and ML64, all 3,815 calls matched and every control was rejected. The C++ generated for the existing jump-table, `addr32`, entry-order, narrow, fourth-argument and frame fixtures is unchanged. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_direct_calls$' -V`. -A `CALL` may close a call cycle ([#317](https://github.com/R0Y00/Xbox2Windows/issues/317), the fixed-point `return_width` proposed there). An export's call to its own entry translates that entry a second time as an internal function. A call into a function whose translation is in progress uses an assumed summary, at first 8 defined RAX bytes and no argument demands. When a function of the cycle is done, its computed return width and demands are compared with the assumed ones: if the computed width is lower or a demand is higher, the cycle is translated again from the lower width and the higher demands. Both move one way through a finite set, so this ends. When no computed width is lower and no demand is higher, every return of the cycle defines the assumed bytes and the cycle reads no more argument bytes, by induction on the depth of the calls that have returned. The functions of a cycle are kept together once its first function is done, after a declaration of each, so each may call any other. A cycle inside another is kept when its own first function is done. A refusal under an assumed summary stands, because a lower width or a higher demand cannot remove it. A tail jump that closes a cycle is refused with `tail jump within a call cycle`: the original runs such a cycle in constant stack and the C++ call does not. The translation's recursion depth is bounded by the host stack, whose use per call differs from the original's, so a recursion that ends on the console can overflow the host stack, or the reverse. +A `CALL` may close a call cycle ([#317](https://github.com/R0Y00/Xbox2Windows/issues/317), the fixed-point `return_width` proposed there). An export's call to its own entry translates that entry a second time as an internal function. A call into a function whose translation is in progress uses an assumed summary, at first 8 defined RAX bytes and no argument demands. When a function of the cycle is done, its computed return width and demands are compared with the assumed ones: if the computed width is lower or a demand is higher, the cycle is translated again from the lower width and the higher demands. Both move one way through a finite set, so this ends. When no computed width is lower and no demand is higher, every return of the cycle defines the assumed bytes and the cycle reads no more argument bytes, by induction on the depth of the calls that have returned. The functions of a cycle are kept together once its first function is done, after a declaration of each, so each may call any other. A cycle inside another is kept when its own first function is done. A function that goes on hold passes its dependence on to the functions held during its translation, so a later function that reuses one of them joins the same cycle. A refusal under an assumed summary stands, because a lower width or a higher demand cannot remove it. A tail jump that closes a cycle is refused with `tail jump within a call cycle`: the original runs such a cycle in constant stack and the C++ call does not. The translation's recursion depth is bounded by the host stack, whose use per call differs from the original's, so a recursion that ends on the console can overflow the host stack, or the reverse. -`cpu_aot_recursion` builds [`recursion.asm`](../tests/cpu/recursion.asm) and translates four exports. `sum_export` calls `sum_down`, which recurses through `CALL` up to 511 levels and keeps its arguments in RBX and RSI across the call. `parity_export` calls `is_even` and `is_odd`, which call each other. `is_even` defines only AL at its base case and `is_odd` all of RAX, so only the second translation of the cycle gives `is_odd` its 1-byte width. `walk_export` calls `walk_a`, which is in a cycle with `walk_b` and `walk_c`. Only `walk_a` reads R8, so only the second translation makes `walk_c` demand it; `walk_b` also calls `count_down`, whose own cycle is kept while the outer cycle is still being translated. `fold_export` calls its own exported entry up to 64 levels. Through the register probe, the original must match a Python reference, and the translation must match the original on the return value, the guarded trace, RBX and RSI over 484 input pairs per export. The test checks that each of the eight internal functions is declared once and defined once, that `is_even` and `is_odd` return 1 byte and the others 8, and that exactly `walk_a`, `walk_b`, `walk_c` and the internal `fold_export` demand R8. Four exports must be refused as written: `tail_ping` and `tail_pong`, a cycle of tail jumps; `wide_odd`, which reads all of RAX after `is_odd`; `lost_k`, which calls `walk_c` after another call left R8 undefined; and `bad_a`, in a cycle with `bad_b`, which executes `CPUID`. Keeping the first summary of each cycle instead of translating it again (the test replaces `at_least_as_good`) accepts `wide_odd` and `lost_k`, and the test fails unless it does. Before this change all four exports were refused, with `self-recursion` or `mutual recursion: call cycle`. Measured on Linux x86-64 with `llvm-ml` 18, `lld-link` and `clang++` at `-O0` and `-O2`, with the original image mapped in-process and called through a Windows x64 register probe: the original matched the reference and kept RBX and RSI, and 3,872 translated calls matched it. The C++ generated for 15 other `cpu_switch_aot` fixtures and for the `calls`, `chains` and `rsp` fuzz programs at their default seeds, `calls` at `0xBEEF` and `chains` at `0xCCD1` with 128 functions, is unchanged. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_recursion$' -V`. +`cpu_aot_recursion` builds [`recursion.asm`](../tests/cpu/recursion.asm) and translates four exports. `sum_export` calls `sum_down`, which recurses through `CALL` up to 511 levels and keeps its arguments in RBX and RSI across the call. `parity_export` calls `is_even` and `is_odd`, which call each other. `is_even` defines only AL at its base case and `is_odd` all of RAX, so only the second translation of the cycle gives `is_odd` its 1-byte width. `walk_export` calls `walk_a`, which is in a cycle with `walk_b` and `walk_c`. Only `walk_a` reads R8, so only the second translation makes `walk_c` demand it; `walk_b` also calls `count_down`, whose own cycle is kept while the outer cycle is still being translated. `fold_export` calls its own exported entry up to 64 levels. Through the register probe, the original must match a Python reference, and the translation must match the original on the return value, the guarded trace, RBX and RSI over 484 input pairs per export. The test checks that each of the eight internal functions is declared once and defined once, that `is_even` and `is_odd` return 1 byte and the others 8, and that exactly `walk_a`, `walk_b`, `walk_c` and the internal `fold_export` demand R8. Five exports must be refused as written: `tail_ping` and `tail_pong`, a cycle of tail jumps; `wide_odd`, which reads all of RAX after `is_odd`; `lost_k`, which calls `walk_c` after another call left R8 undefined; `bad_a`, in a cycle with `bad_b`, which executes `CPUID`; and `stale_e`, whose callee `stale_a` reads all of RAX after `stale_t`. `stale_t` is translated after `stale_s` and `stale_q` are on hold and reuses `stale_q`, so it is in their cycle and returns only AL; a translator that keeps `stale_t` on its own, with the 8 bytes first assumed for the cycle, accepts `stale_e`. Keeping the first summary of each cycle instead of translating it again (the test replaces `at_least_as_good`) accepts `wide_odd` and `lost_k`, and the test fails unless it does. Before this change all four exports were refused, with `self-recursion` or `mutual recursion: call cycle`. Measured on Linux x86-64 with `llvm-ml` 18, `lld-link` and `clang++` at `-O0` and `-O2`, with the original image mapped in-process and called through a Windows x64 register probe: the original matched the reference and kept RBX and RSI, and 3,872 translated calls matched it. The C++ generated for 15 other `cpu_switch_aot` fixtures and for the `calls`, `chains` and `rsp` fuzz programs at their default seeds, `calls` at `0xBEEF` and `chains` at `0xCCD1` with 128 functions, is unchanged. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_recursion$' -V`. `cpu_aot_call_entries` builds [`call_entries.asm`](../tests/cpu/call_entries.asm), whose `.pdata` and `.xdata` are written explicitly so the image has a primary function continued by a chained secondary range. It also exports an interior label of a primary function, a `.data` variable as `DATA` and a forwarder to `kernel32.GetTickCount`. The test reads the image's own records and checks that the translator's entries are exactly the four primary runtime functions. A framed `CALL` and a tail `JMP` to the primary leaf translate and match the original and a Python reference over 249 input pairs each. Eight retargeted copies must be rejected with the reason that names the distinction: the call retargeted to the exported interior label, the chained range's start, the data export and the forwarder; the tail jump retargeted to the interior label and the chained start; and the leaf's unwind header patched from version 1 to version 3, for both the call and the tail jump. The translator before this rule refused the first six later and for unrelated reasons (`no unique function interval`, `not in an executable section`, `edge outside owned ranges`), and accepted the last two. Removing the version check, or accepting an export at the start of an unverified record, accepts the version controls. Counting interior exports or chained ranges as entries, or classifying forwarders and data exports as code, fails the check of the entry table. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_call_entries$' -V`. diff --git a/tests/cpu/recursion.asm b/tests/cpu/recursion.asm index a2b272e769..7ad54dfb49 100644 --- a/tests/cpu/recursion.asm +++ b/tests/cpu/recursion.asm @@ -329,4 +329,73 @@ bad_b PROC FRAME ret bad_b ENDP + +; Refused: stale_a reads all of RAX after stale_t, which returns only AL through the cycle +; stale_a -> stale_s -> stale_q -> stale_s -> stale_a. stale_t is translated after stale_s and +; stale_q are pending and reuses stale_q, so it is in the same cycle and must not be kept on its own. +stale_a PROC FRAME + sub rsp, 28h + .allocstack 28h + .endprolog + test rcx, rcx + jnz stale_a_step + mov al, 1 + add rsp, 28h + ret +stale_a_step: + dec rcx + jz stale_a_t + call stale_s + add rsp, 28h + ret +stale_a_t: + call stale_t + inc rax + add rsp, 28h + ret +stale_a ENDP + +stale_s PROC FRAME + sub rsp, 28h + .allocstack 28h + .endprolog + test rcx, rcx + jz stale_s_a + call stale_q + add rsp, 28h + ret +stale_s_a: + call stale_a + add rsp, 28h + ret +stale_s ENDP + +stale_q PROC FRAME + sub rsp, 28h + .allocstack 28h + .endprolog + dec rcx + call stale_s + add rsp, 28h + ret +stale_q ENDP + +stale_t PROC FRAME + sub rsp, 28h + .allocstack 28h + .endprolog + call stale_q + add rsp, 28h + ret +stale_t ENDP + +stale_e PROC FRAME + sub rsp, 28h + .allocstack 28h + .endprolog + call stale_a + add rsp, 28h + ret +stale_e ENDP + END diff --git a/tests/cpu/recursion.def b/tests/cpu/recursion.def index 8ee23e1be5..70833bb20a 100644 --- a/tests/cpu/recursion.def +++ b/tests/cpu/recursion.def @@ -7,3 +7,4 @@ EXPORTS wide_odd lost_k bad_a + stale_e diff --git a/tests/cpu/recursion_check.py b/tests/cpu/recursion_check.py index fe144107fc..35b85251e6 100644 --- a/tests/cpu/recursion_check.py +++ b/tests/cpu/recursion_check.py @@ -24,6 +24,7 @@ ("wide_odd", "undefined register rax"), ("lost_k", "callee argument r8 is undefined"), ("bad_a", "callee at RVA {bad_b:#x} refused: unsupported instruction"), + ("stale_e", "callee at RVA {stale_a:#x} refused: undefined register rax"), ) # Refused only because a cycle's first summary is translated again. ITERATED = ("wide_odd", "lost_k") @@ -139,6 +140,7 @@ def targets(rva): rvas["walk_c"], rvas["count_down"] = targets(rvas["walk_b"]) rvas["tail_pong"], = targets(rvas["tail_ping"]) rvas["bad_b"], = targets(rvas["bad_a"]) + rvas["stale_a"], = targets(rvas["stale_e"]) return rvas diff --git a/tools/cpu_switch_aot.py b/tools/cpu_switch_aot.py index e0c47d2703..a1a2227c9a 100644 --- a/tools/cpu_switch_aot.py +++ b/tools/cpu_switch_aot.py @@ -1921,6 +1921,9 @@ def callee(self, target, ip): del self.pending[start:] if self.low < depth: # Part of a cycle through a function below it on the stack, which keeps it when that is done. + # The functions pending from its translation now depend on what it depends on: a later + # translation at this depth that reuses one is in the same cycle. + self.pending[start:] = [(e, t, f, min(l, self.low)) for e, t, f, l in self.pending[start:]] self.pending.append((target, source, function, self.low)) return function members = [(entry, text, member) for entry, text, member, _ in self.pending[start:]] + [(target, source, function)] @@ -2003,7 +2006,7 @@ def lift_function(program, entry, symbol, arguments, internal): if not program.committed(callees[ip]): # The original runs a cycle of tail jumps in constant stack; the host call does not. raise ValueError(f"tail jump within a call cycle at RVA {ip:#x}") - loads ={sequence[0]: index for index, _, sequence, _, _, _ in function.dispatches.values()} + loads = {sequence[0]: index for index, _, sequence, _, _, _ in function.dispatches.values()} skipped = {ip for _, _, sequence, _, _, _ in function.dispatches.values() for ip in sequence} body = {} effects = {} From 9e8d90905d275e333da1bba4219d096491f28158 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 15:41:36 +0000 Subject: [PATCH 3/7] cpu: keep Program.active a list of entry RVAs The call-cycle change stored (entry, internal) pairs in Program.active. The planted call-retarget fault of cpu_aot_fuzz_calls compares Program.active[-1] with an export's RVA, so it no longer planted, and the test would report the fault as not detected. Program.active holds the entries again, and a parallel list says which ones are internal. The clean and planted translations of every fuzz area that llvm-ml assembles, at the CMake default seeds, are byte-identical to main. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014uAfgrqe3XyeqvkJrdnUK6 --- tools/cpu_switch_aot.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/tools/cpu_switch_aot.py b/tools/cpu_switch_aot.py index a1a2227c9a..f6df36601c 100644 --- a/tools/cpu_switch_aot.py +++ b/tools/cpu_switch_aot.py @@ -1857,7 +1857,8 @@ def __init__(self, pe, bindings=None, *, image_data=False, imports=None, host_cp self.host_cpu = host_cpu self.imports = imports or {} self.entries = Entries(pe, bindings) - self.active = [] # (entry, internal) of each translation in progress, outermost first + self.active = [] # entry of each translation in progress, outermost first + self.internal = [] # whether each of those is an internal function self.lows = [] # per active translation: the lowest active depth it has used a summary from self.assumed = {} self.pending = [] # (entry, source, function, low) of cycle functions not yet kept @@ -1867,12 +1868,14 @@ def __init__(self, pe, bindings=None, *, image_data=False, imports=None, host_cp self.import_resolver = None def lift(self, entry, symbol, arguments, internal=False): - self.active.append((entry, internal)) + self.active.append(entry) + self.internal.append(internal) self.lows.append(len(self.active) - 1) try: return lift_function(self, entry, symbol, arguments, internal) finally: self.active.pop() + self.internal.pop() self.low = self.lows.pop() if self.lows: self.lows[-1] = min(self.lows[-1], self.low) @@ -1892,7 +1895,8 @@ def callee(self, target, ip): if entry == target: self.depends(low) return function - depth = next((d for d, (entry, internal) in enumerate(self.active) if internal and entry == target), None) + depth = next((d for d, (entry, internal) in enumerate(zip(self.active, self.internal)) + if internal and entry == target), None) if depth is not None: self.depends(depth) return self.assumed.setdefault(target, Assumed(target, 8, {})) From a9072de14f9a62f31335bcf1574b98afb4815ae8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 15:25:56 +0000 Subject: [PATCH 4/7] cpu: pass stack arguments to internal callees in cpu_switch_aot An internal callee may now read and write up to eight stack arguments, the 8-byte slots from entry RSP + 40, each access inside one slot. Its frame array extends over them, copied at entry from one C++ parameter per slot after R9, and it records how many low bytes of each slot some read reaches. Each caller's frame proof must show those bytes written at RSP + 32 + 8 * slot when the CALL executes, below its own return address, and the slots are undefined after the call because the callee may write them. Slot demands join the call-cycle iteration. A tail jump to a function with stack arguments stays refused, and exports still take none. cpu_aot_stack_arguments compares five exports that reach callees with five to eight arguments, 1-, 2-, 4- and 8-byte slot reads, forwarded and modified slots and recursion with a stack argument, with the original and a Python reference over 449 inputs each, and checks eight refusal controls. Three of them are accepted when the frame proof ignores the slots of calls. The direct-call control whose callee reads its fifth argument is now refused because that slot holds the caller's saved RSI. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014uAfgrqe3XyeqvkJrdnUK6 --- CMakeLists.txt | 6 + docs/experiments.md | 10 +- tests/cpu/calls_check.py | 7 +- tests/cpu/stack_args.asm | 314 ++++++++++++++++++++++++++++++++++ tests/cpu/stack_args.def | 14 ++ tests/cpu/stack_args_check.py | 215 +++++++++++++++++++++++ tools/cpu_switch_aot.py | 114 +++++++++--- 7 files changed, 652 insertions(+), 28 deletions(-) create mode 100644 tests/cpu/stack_args.asm create mode 100644 tests/cpu/stack_args.def create mode 100644 tests/cpu/stack_args_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index a31ea05ffc..dd46649185 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3437,6 +3437,12 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME cpu_aot_recursion COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/recursion_check.py" "$" "$" "$") + cpu_asm_fixture(cpu_stack_args stack_args) + # The exports from unset_slot on exist only to be refused; the test translates each alone. + cpu_translation(cpu_stack_args cpu_switch_aot call_six,call_seven,call_scratch,call_rec,call_eight) + add_test(NAME cpu_aot_stack_arguments COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/stack_args_check.py" "$" + "$" "$") cpu_asm_fixture(cpu_call_entries call_entries) cpu_translation(cpu_call_entries cpu_switch_aot entry_caller,entry_tail) add_test(NAME cpu_aot_call_entries COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index 1bf0274d84..9f1971cfb9 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -2744,7 +2744,7 @@ cmake --build --preset dev --target cpu_switch_bswap_lifted cpu_register_probe ctest --preset dev --no-tests=error -R '^cpu_aot_switch_bswap$' -V ``` -The supported functions take three integer words in RCX, RDX and R8 and return RAX, of which only the low bytes described below are compared. An entry can instead be translated with a fourth integer word in R9, as described below. Stack arguments (the fifth and later) and floating-point arguments are not supported. A leaf function without a `.pdata` entry is bounded by its executable section. Its walk may not enter an interval owned by another function's unwind entry. +The supported functions take three integer words in RCX, RDX and R8 and return RAX, of which only the low bytes described below are compared. An entry can instead be translated with a fourth integer word in R9, as described below. An export's stack arguments (the fifth and later) and floating-point arguments are not supported; an internal callee may take stack arguments, as described below. A leaf function without a `.pdata` entry is bounded by its executable section. Its walk may not enter an interval owned by another function's unwind entry. The [source fixture](../tests/cpu/switch.asm) exports seven functions. `select_rva` uses the MSVC layout, and `select_rel` computes the same function through the LLVM layout. Both have seven cases, including two selectors that share a target, a case that falls through into the next, and a default path. `run_ops` runs a byte program in a loop and dispatches every byte through a five-entry table. It stops at the first opcode above 4. Through the register probe, the test compares each original export with the matching lifted function, a reference written in Python, and RBX/RSI sentinels. It runs 600 selector and operand pairs per layout and 138 programs. Half of the pairs carry nonzero upper register halves that must not reach the table index. A control assembles the same source with two entries swapped in each table, and its translation must follow the swapped reference. `shift_narrow` dispatches through a six-entry LLVM-layout table to byte and word `SHL`, `SHR` and `SAR` of a memory destination by `CL`. x86 masks the count to five bits for 8- and 16-bit operands as well, so counts of 8 to 31 still shift (a byte holding 1 shifted left by 8 becomes 0). The translator performs these shifts in 64 bits and truncates the stored result; 4,608 inputs, covering every count from 0 to 31 and count bytes above 31, match the original and the reference. `flag_select` dispatches through an eight-entry LLVM-layout table to `SETL`, `SETBE`, `SETG` into a memory byte, `SETNE` after a 16-bit compare, and `CMOVA`, `CMOVNS` (64-bit, after `TEST`), `CMOVGE` from memory with a `MOV` between compare and consumer, and `CMOVE` after `TEST` with an immediate. It compares EDX with bits 32 to 63 of RDX and returns RAX whole. A 32-bit `CMOVcc` therefore shows that it clears bits 32 to 63 even when the condition is false, and a byte `SETcc` shows that it keeps them. The translation reads a memory source of `CMOVcc` on both outcomes, as the processor does. 4,000 inputs at the signed, unsigned and 16-bit boundaries must match the original and the reference. The swapped-table build exchanges the `SETL` and `CMOVA` entries and must follow the swapped reference. `cmov_read` executes `CMOVNE` after `CMP ECX, ECX`, which never moves but still reads its memory source: called with a null R8 it must fault in the original and in the translation. The translator therefore performs every read of guest memory through a `volatile` load; with an ordinary load, an optimized MSVC Release build drops a read whose value is unused and the null call returns. Each instruction's memory operand is read once, at its own width, into a local declared before the rest of the statement, and every use of the operand names that local: an `ADD` whose result and flags both come from one operand performs one read. Reads of the function's own frame array, which cannot fault, stay ordinary loads. The [dead-read fixture](../tests/cpu/dead_read.asm) stores 1 to the trace before each read and 2 after it. Its exports read a value that is overwritten, compare memory with flags that are never read, read one byte, read two operands whose sum is cleared, return the value read, skip the read on a branch, and take a sum and its zero flag from one read, into a register and in place. `cpu_aot_dead_reads` builds the translation with the project's build and again with a separate `cl /O2` command, calls the original and each translation inside `__try` with fresh trace words and a fresh page, and compares the structured exception code, the return value, the trace and the page. For a readable operand all three return the reference. For a null operand, and for an operand whose read crosses into an inaccessible page, the original raises an access violation after the first marker and before the second, and both translations must do the same; an operand that ends exactly at the page boundary returns, at each width, and the second read of the pair faults when only the first is readable. On the branch that skips the read, the same inaccessible addresses return normally with the first and third markers written. A source control checks that each memory operand is read once through the `volatile` load and that the shared reads are used twice. An unoptimized build performs an ordinary load as well, so the `/O2` builds are the ones that show the difference. Stores are unchanged. @@ -2792,14 +2792,18 @@ A function may use its stack frame. A forward pass over the control-flow graph g `cpu_aot_stack_frames` builds [`frame.asm`](../tests/cpu/frame.asm), with the unwind directives each prologue needs, and translates nine exports. `push_loop` pushes and pops RBX and RSI and uses them in a loop. `spill_widths` allocates 24 bytes, stores 8, 4, 2 and 1 bytes, reads them back in overlapping pieces, adds to a slot in place, and uses `SETB` into the frame and `CMOVL` from it. `home_save` has the MSVC `/O2` shape: it saves RBX and RSI into home space with `MOV [RSP+8], RBX` and `MOV [RSP+10h], RSI` before `PUSH RDI` and `SUB RSP, 20h`, restores them with `MOV` on each of two returns, and carries the unwind codes MSVC writes for that prologue. `home_args` is the `cl /Od` output for a small C function that stores its arguments to home space, writes a local on both sides of a branch and reloads it. `two_paths` pushes RSI on one path and RDI on the other, rejoins at the same depth, and returns early on a third path after restoring RBX. `home_spill` spills two arguments into home space with no allocation of its own, and `loop_counter` keeps a counter and an accumulator in the frame across a loop's back edge. `realloc_slot` releases its allocation with `ADD RSP`, allocates the same bytes again and writes the slot before reading it. `frame_bound`, whose frame array is exactly 4,096 bytes, is translated and compiled but never called. Through the register probe, each original and translated export is compared with a Python reference over the direct-call input pairs, on the return value, the guarded trace, RBX and RSI, and every path of each export is taken. The probe shows that the original saves and restores RBX and RSI and that the translation leaves the caller's RBX and RSI intact. It does not show that the translation reproduces the original's save and restore: the generated locals are not the physical registers, and the host compiler saves and restores those itself. The test checks that the built source is the translation of the export list, that each frame array has the expected size, and that `rsp` appears nowhere in the generated C++. Thirty-two controls must be rejected. Twenty-six are copies of the image with one or two instructions replaced by others of the same length: an unbalanced `POP`, two paths that join at different depths, a loop that pushes on every iteration, a nonvolatile register not restored on one path, restored from another register's slot by `MOV` or by `POP`, or loaded into RAX from its save slot, a local written on one path only, home space never written, a 4-byte store removed under a later 8-byte read, a loop counter written only on the back edge, a stack argument at entry RSP + 40, a read and a write of the return address, `LEA RAX, [RSP+8]`, `MOV RAX, RSP`, `SUB RSP, RCX`, `SUB` and `ADD RSP` by 14h, `ADD RSP` at entry, a `JAE` left reading the flags of `SUB RSP`, an access below RSP, a frame of 4,112 bytes, `realloc_slot` without the store into its second allocation, `ADD RBX, RCX` on the caller's RBX, `PUSH RAX` and `PUSH 5`. The six others are exports rejected as written: a saved RBX whose slot is released by `ADD RSP` and allocated again before `POP RBX`; a slot that `POP` read and released, allocated again and read without a new store; a RIP-relative address spilled to the frame and reloaded, refused at the store as a read of an undefined register; RBX saved twice and reloaded from the 8 bytes that straddle the two copies; RBX pushed as data after only BL was written; and a register read after `POP` restored it. With MSVC 14.52 `cl`, `link` and `ml64` run under Wine on Linux, 1,992 calls per side matched and every control was rejected. The Windows job runs the same test. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_stack_frames$' -V`. -The same translator follows direct calls and tail jumps to other functions of the image ([#317](https://github.com/R0Y00/Xbox2Windows/issues/317), step 2). A `CALL rel32`, or a direct `JMP` that leaves the function's owned ranges, must target a function entry of this image: the first byte of a verified primary runtime function (an unchained `.pdata` record with version 1 or 2 unwind data and a non-empty interval in executable code), or a non-forwarded code export in an executable section that lies outside every runtime-function interval. The start of a chained secondary range, an interior label (exported or not), a record start with any other unwind header, a forwarded export and a data export are not entries, and the message says which of these the target is. Each callee is translated once into the same source, as a static function named `fn_` that takes RCX, RDX, R8 and R9, and is defined before its first caller. A call may close a call cycle, as described below. A caller is rejected when any callee is, and the message names the callee's RVA and its reason. A callee records how many low bytes of each argument register it may read while that register may still hold its entry value, and the caller must have those bytes defined at the call. After a call, RAX has the callee's return width of defined bytes. RCX, RDX and R8 to R11, the flags and the callee's 32-byte home space at RSP are undefined. The return address the `CALL` pushes and the callee's own frame lie below RSP, where the frame proof already holds every byte unwritten, because the bytes that `ADD RSP` and `POP` leave below RSP become unwritten; so they stay undefined if RSP later falls back over them. Nonvolatile registers keep their state, because each callee is itself checked to restore every one, and so do the other frame bytes, including saves by `MOV` into the caller's own home space above entry RSP, which the callee's home space cannot reach. RSP must be 8 mod 16 from entry at a call, so the native call is aligned, and the callee's home space must lie below the return address. A tail jump is checked like a `RET`, with RSP at its entry value and every nonvolatile register restored, and contributes the callee's return width. The callee's frame is its own array, so no frame address crosses a call. A frame address passed to a callee (`LEA RCX, [RSP+20h]`), stack arguments, indirect calls, callees with no reachable normal return, import thunks, and targets with no unwind entry or export (such as leaves that MSVC emits without `.pdata`) unless the invoker binds them as described below, stay rejected. +The same translator follows direct calls and tail jumps to other functions of the image ([#317](https://github.com/R0Y00/Xbox2Windows/issues/317), step 2). A `CALL rel32`, or a direct `JMP` that leaves the function's owned ranges, must target a function entry of this image: the first byte of a verified primary runtime function (an unchained `.pdata` record with version 1 or 2 unwind data and a non-empty interval in executable code), or a non-forwarded code export in an executable section that lies outside every runtime-function interval. The start of a chained secondary range, an interior label (exported or not), a record start with any other unwind header, a forwarded export and a data export are not entries, and the message says which of these the target is. Each callee is translated once into the same source, as a static function named `fn_` that takes RCX, RDX, R8 and R9, and is defined before its first caller. A call may close a call cycle, as described below. A caller is rejected when any callee is, and the message names the callee's RVA and its reason. A callee records how many low bytes of each argument register it may read while that register may still hold its entry value, and the caller must have those bytes defined at the call. After a call, RAX has the callee's return width of defined bytes. RCX, RDX and R8 to R11, the flags and the callee's 32-byte home space at RSP are undefined. The return address the `CALL` pushes and the callee's own frame lie below RSP, where the frame proof already holds every byte unwritten, because the bytes that `ADD RSP` and `POP` leave below RSP become unwritten; so they stay undefined if RSP later falls back over them. Nonvolatile registers keep their state, because each callee is itself checked to restore every one, and so do the other frame bytes, including saves by `MOV` into the caller's own home space above entry RSP, which the callee's home space cannot reach. RSP must be 8 mod 16 from entry at a call, so the native call is aligned, and the callee's home space must lie below the return address. A tail jump is checked like a `RET`, with RSP at its entry value and every nonvolatile register restored, and contributes the callee's return width. The callee's frame is its own array, so no frame address crosses a call. A frame address passed to a callee (`LEA RCX, [RSP+20h]`), indirect calls, callees with no reachable normal return, import thunks, and targets with no unwind entry or export (such as leaves that MSVC emits without `.pdata`) unless the invoker binds them as described below, stay rejected. -`cpu_aot_direct_calls` builds [`calls.asm`](../tests/cpu/calls.asm) and translates seven exports, which reach three unexported callees placed below them. `call_leaf` calls a leaf from a frame and keeps the trace pointer in RBX across the call. `chain3` calls `mid_step`, which spills RDX into its own frame above the callee's home space, calls the same leaf and reloads it, so the leaf is shared. `narrow_call` calls a callee that defines only AL and widens it with `MOVZX`. `narrow_tail` tail-jumps to that callee and reports width 1, `tail_call` tail-jumps to the leaf, and `tail_after_frame` pops its frame before tail-jumping to `mid_step`. `home_save_call` has the MSVC `/O2` save shapes around a call: RBX saved by `MOV` into its own home space before `SUB RSP, 28h`, and RSI saved by `MOV` into the allocation above the callee's home space. Through the register probe, the original must match a Python reference, and the translation must match the original on the defined return bytes, the guarded trace, RBX and RSI over 545 input pairs per export. The test checks that each callee is defined exactly once and that the reported return widths are 8 except for `narrow_tail`. A copy with a call to the caller's own entry and one with a call from `mid_step` back to `chain3` must translate with a declared call cycle. Nineteen copies must be rejected with their stated reason: a call from `mid_step` back to `tail_after_frame`, which closes a cycle with that function's tail jump, calls into an instruction interior and to an instruction boundary that is not an entry, a target outside the image and one in `.rdata`, reads of RCX, R8 and the full RAX after a call, a second call to the leaf whose RCX and RDX the first call left undefined, a `SETE` after a call, a stack-argument read in a callee and an unsupported instruction two levels down, a spill and a `MOV` save of RSI moved into the callee's home space and reloaded after the call, a call at entry RSP - 0x30 and one at entry RSP - 0x8, a tail jump with a frame still allocated, a tail jump with RBX not restored, and, as built, `below_call`, which stores a slot at entry RSP - 0x40, raises RSP for a call whose return address overwrites it, and reloads it after RSP falls back (natively it returns the return address). Removing the volatile clobber accepts the RCX control, keeping RAX fully defined after a call accepts the narrow control, keeping the callee's home space defined accepts the spill control, dropping the callees' argument demands accepts the second-call control, translating a shared callee again for each caller emits it five times (and the C++ fails with `C2084`), and naming the wrong callee at a call fails `chain3`. On Windows 11 build 26200 with MSVC 19.50 and ML64, all 3,815 calls matched and every control was rejected. The C++ generated for the existing jump-table, `addr32`, entry-order, narrow, fourth-argument and frame fixtures is unchanged. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_direct_calls$' -V`. +`cpu_aot_direct_calls` builds [`calls.asm`](../tests/cpu/calls.asm) and translates seven exports, which reach three unexported callees placed below them. `call_leaf` calls a leaf from a frame and keeps the trace pointer in RBX across the call. `chain3` calls `mid_step`, which spills RDX into its own frame above the callee's home space, calls the same leaf and reloads it, so the leaf is shared. `narrow_call` calls a callee that defines only AL and widens it with `MOVZX`. `narrow_tail` tail-jumps to that callee and reports width 1, `tail_call` tail-jumps to the leaf, and `tail_after_frame` pops its frame before tail-jumping to `mid_step`. `home_save_call` has the MSVC `/O2` save shapes around a call: RBX saved by `MOV` into its own home space before `SUB RSP, 28h`, and RSI saved by `MOV` into the allocation above the callee's home space. Through the register probe, the original must match a Python reference, and the translation must match the original on the defined return bytes, the guarded trace, RBX and RSI over 545 input pairs per export. The test checks that each callee is defined exactly once and that the reported return widths are 8 except for `narrow_tail`. A copy with a call to the caller's own entry and one with a call from `mid_step` back to `chain3` must translate with a declared call cycle. Nineteen copies must be rejected with their stated reason: a call from `mid_step` back to `tail_after_frame`, which closes a cycle with that function's tail jump, calls into an instruction interior and to an instruction boundary that is not an entry, a target outside the image and one in `.rdata`, reads of RCX, R8 and the full RAX after a call, a second call to the leaf whose RCX and RDX the first call left undefined, a `SETE` after a call, a stack-argument read in a callee, where its caller saved RSI, and an unsupported instruction two levels down, a spill and a `MOV` save of RSI moved into the callee's home space and reloaded after the call, a call at entry RSP - 0x30 and one at entry RSP - 0x8, a tail jump with a frame still allocated, a tail jump with RBX not restored, and, as built, `below_call`, which stores a slot at entry RSP - 0x40, raises RSP for a call whose return address overwrites it, and reloads it after RSP falls back (natively it returns the return address). Removing the volatile clobber accepts the RCX control, keeping RAX fully defined after a call accepts the narrow control, keeping the callee's home space defined accepts the spill control, dropping the callees' argument demands accepts the second-call control, translating a shared callee again for each caller emits it five times (and the C++ fails with `C2084`), and naming the wrong callee at a call fails `chain3`. On Windows 11 build 26200 with MSVC 19.50 and ML64, all 3,815 calls matched and every control was rejected. The C++ generated for the existing jump-table, `addr32`, entry-order, narrow, fourth-argument and frame fixtures is unchanged. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_direct_calls$' -V`. A `CALL` may close a call cycle ([#317](https://github.com/R0Y00/Xbox2Windows/issues/317), the fixed-point `return_width` proposed there). An export's call to its own entry translates that entry a second time as an internal function. A call into a function whose translation is in progress uses an assumed summary, at first 8 defined RAX bytes and no argument demands. When a function of the cycle is done, its computed return width and demands are compared with the assumed ones: if the computed width is lower or a demand is higher, the cycle is translated again from the lower width and the higher demands. Both move one way through a finite set, so this ends. When no computed width is lower and no demand is higher, every return of the cycle defines the assumed bytes and the cycle reads no more argument bytes, by induction on the depth of the calls that have returned. The functions of a cycle are kept together once its first function is done, after a declaration of each, so each may call any other. A cycle inside another is kept when its own first function is done. A function that goes on hold passes its dependence on to the functions held during its translation, so a later function that reuses one of them joins the same cycle. A refusal under an assumed summary stands, because a lower width or a higher demand cannot remove it. A tail jump that closes a cycle is refused with `tail jump within a call cycle`: the original runs such a cycle in constant stack and the C++ call does not. The translation's recursion depth is bounded by the host stack, whose use per call differs from the original's, so a recursion that ends on the console can overflow the host stack, or the reverse. `cpu_aot_recursion` builds [`recursion.asm`](../tests/cpu/recursion.asm) and translates four exports. `sum_export` calls `sum_down`, which recurses through `CALL` up to 511 levels and keeps its arguments in RBX and RSI across the call. `parity_export` calls `is_even` and `is_odd`, which call each other. `is_even` defines only AL at its base case and `is_odd` all of RAX, so only the second translation of the cycle gives `is_odd` its 1-byte width. `walk_export` calls `walk_a`, which is in a cycle with `walk_b` and `walk_c`. Only `walk_a` reads R8, so only the second translation makes `walk_c` demand it; `walk_b` also calls `count_down`, whose own cycle is kept while the outer cycle is still being translated. `fold_export` calls its own exported entry up to 64 levels. Through the register probe, the original must match a Python reference, and the translation must match the original on the return value, the guarded trace, RBX and RSI over 484 input pairs per export. The test checks that each of the eight internal functions is declared once and defined once, that `is_even` and `is_odd` return 1 byte and the others 8, and that exactly `walk_a`, `walk_b`, `walk_c` and the internal `fold_export` demand R8. Five exports must be refused as written: `tail_ping` and `tail_pong`, a cycle of tail jumps; `wide_odd`, which reads all of RAX after `is_odd`; `lost_k`, which calls `walk_c` after another call left R8 undefined; `bad_a`, in a cycle with `bad_b`, which executes `CPUID`; and `stale_e`, whose callee `stale_a` reads all of RAX after `stale_t`. `stale_t` is translated after `stale_s` and `stale_q` are on hold and reuses `stale_q`, so it is in their cycle and returns only AL; a translator that keeps `stale_t` on its own, with the 8 bytes first assumed for the cycle, accepts `stale_e`. Keeping the first summary of each cycle instead of translating it again (the test replaces `at_least_as_good`) accepts `wide_odd` and `lost_k`, and the test fails unless it does. Before this change all four exports were refused, with `self-recursion` or `mutual recursion: call cycle`. Measured on Linux x86-64 with `llvm-ml` 18, `lld-link` and `clang++` at `-O0` and `-O2`, with the original image mapped in-process and called through a Windows x64 register probe: the original matched the reference and kept RBX and RSI, and 3,872 translated calls matched it. The C++ generated for 15 other `cpu_switch_aot` fixtures and for the `calls`, `chains` and `rsp` fuzz programs at their default seeds, `calls` at `0xBEEF` and `chains` at `0xCCD1` with 128 functions, is unchanged. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_recursion$' -V`. +An internal callee may take stack arguments, the fifth to the twelfth: the 8-byte slots from its entry RSP + 0x28, which the Windows x64 calling convention places above the caller's home space. Each access must lie inside one slot. The callee's frame array extends over the slots it accesses, each copied at entry from one more C++ parameter after R9, and the callee records how many low bytes of each slot some read reaches. This counts reads after the callee's own writes too, so it can demand more than it needs, never less. At each call the caller's frame proof must show those bytes written as data at RSP + 0x20 + 8 * slot, below the caller's return address, and the call passes the 8 bytes of each slot from the caller's frame array. After the call those slots are undefined, like the callee's home space, because the callee may write them. A call in a cycle passes the slots of the assumed summary, and the iteration above covers the slot demands too. A tail jump to a function with stack arguments is refused, because the slots would be the ones the caller's own caller wrote. An export still takes no stack arguments, because its host call passes none. + +`cpu_aot_stack_arguments` builds [`stack_args.asm`](../tests/cpu/stack_args.asm) and translates five exports. `call_six` calls `six_mix`, a frameless leaf with six arguments whose sixth is read as a doubleword, written as one. `call_seven` calls `seven_fwd`, which reads three stack arguments (8, 8 and 1 bytes) through its own `PUSH` and allocation and passes two of them swapped to `six_mix` as its fifth and sixth. `call_scratch` calls `scratch_five`, which adds to its own fifth-argument slot, twice, writing the slot again before the second call. `call_rec` calls `rec_five`, which passes a new fifth argument to itself up to 31 levels. `call_eight` calls `eight_sum`, with eight arguments, the last a word. Through the register probe, the original must match a Python reference, and the translation must match the original on the return value, the guarded trace, RBX and RSI over 449 input pairs per export. The test checks the demanded bytes per slot, (8, 4) for `six_mix`, (8, 8, 1) for `seven_fwd`, (8) for `scratch_five` and `rec_five` and (8, 8, 8, 2) for `eight_sum`, and that each callee is defined with that many stack parameters. Eight exports must be refused as written: `unset_slot` leaves the sixth argument of `six_mix` unwritten, `narrow_slot` writes only 4 bytes of its 8-byte fifth argument, `reread_slot` reads its slot after `scratch_five` may have changed it, `tail_six` tail-jumps to `six_mix`, `export_fifth` is an export that reads a fifth argument, `far_slot` calls a callee that reads the thirteenth, `straddle_slot` one that reads 8 bytes across the end of its home space, and `high_slots` calls `six_mix` with RSP at entry RSP - 0x28, so its two slots would be its own return address and the slot above it. A frame proof that ignores the slots of calls (the test replaces `prove_frame`) accepts the first three, and the test fails unless it does. The direct-call control that patches `mid_step` to read its fifth-argument slot is now refused because that slot holds the RSI that `chain3` pushed. Before this change all five exports were refused with `unsupported stack argument`. Measured on Linux x86-64 with `llvm-ml` 18, `lld-link` and `clang++` at `-O0` and `-O2`, with the original image mapped in-process and called through a Windows x64 register probe: the original matched the reference and kept RBX and RSI, and 4,490 translated calls matched it. The C++ generated for the other `cpu_switch_aot` fixtures, `recursion.asm` included, and for the fuzz programs listed above is unchanged. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_stack_arguments$' -V`. + `cpu_aot_call_entries` builds [`call_entries.asm`](../tests/cpu/call_entries.asm), whose `.pdata` and `.xdata` are written explicitly so the image has a primary function continued by a chained secondary range. It also exports an interior label of a primary function, a `.data` variable as `DATA` and a forwarder to `kernel32.GetTickCount`. The test reads the image's own records and checks that the translator's entries are exactly the four primary runtime functions. A framed `CALL` and a tail `JMP` to the primary leaf translate and match the original and a Python reference over 249 input pairs each. Eight retargeted copies must be rejected with the reason that names the distinction: the call retargeted to the exported interior label, the chained range's start, the data export and the forwarder; the tail jump retargeted to the interior label and the chained start; and the leaf's unwind header patched from version 1 to version 3, for both the call and the tail jump. The translator before this rule refused the first six later and for unrelated reasons (`no unique function interval`, `not in an executable section`, `edge outside owned ranges`), and accepted the last two. Removing the version check, or accepting an export at the start of an unverified record, accepts the version controls. Counting interior exports or chained ranges as entries, or classifying forwarders and data exports as code, fails the check of the entry table. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_call_entries$' -V`. On a Release (`/O2`) build of this change with MSVC 19.50, every `.pdata` entry of the 96 readable non-generated images was translated with four arguments, each unique function body once. Of 2,343 unique functions, 78 translated with the frame translator before this change and 97 after it, and none was lost. Of the 19 new ones, 8 are in `calls.asm`, 2 in `call_entries.asm`, 8 are callers in the other MASM call fixtures and 1 is MSVC output, a tail jump in `cpu_life_a.dll`, which is translated but not run. The most common first refusals are now a call target with no unwind entry or export (806 functions), mostly MSVC leaves without `.pdata` and import thunks, and a refused callee (299). Among refused callees, the innermost reason is an indirect transfer (`unsupported control flow`) in 186 and again a target with no unwind entry in 102. A frame address passed to a callee is the first refusal of 32. diff --git a/tests/cpu/calls_check.py b/tests/cpu/calls_check.py index 06dd4fbbe5..b0e390f814 100644 --- a/tests/cpu/calls_check.py +++ b/tests/cpu/calls_check.py @@ -122,6 +122,9 @@ def first_call(name): raise AssertionError(f"no call in {name}") rvas.update(leaf=first_call("call_leaf"), mid=first_call("chain3"), low=first_call("narrow_call")) + data = pe.get_data(rvas["chain3"], 64) + rvas["chain3_call"] = next(ins.ip for ins in Decoder(64, data, ip=rvas["chain3"]) + if ins.flow_control == FlowControl.CALL) return rvas @@ -193,9 +196,9 @@ def check(probe_path, original_path, lifted_path): # first call left undefined. ("call_leaf", [("call_leaf", 0x0d, "48 89 03 48 83 c0 01", ("call", "leaf"))], "callee argument rcx is undefined"), ("narrow_call", [("narrow_call", 0x0d, "0f b6 c0", "0f 94 c0")], "flags clobbered by the call"), - # mid_step reads the fifth-argument slot above its caller's home area. + # mid_step reads the fifth-argument slot above its caller's home area, where chain3 pushed RSI. ("chain3", [("mid", 0x11, "48 03 44 24 20", "48 03 44 24 50")], - "callee at RVA {mid:#x} refused: unsupported stack argument"), + "stack argument 5 of the call at RVA {chain3_call:#x} holds a saved register"), # An unsupported instruction in leaf_mix refuses mid_step and with it chain3. ("chain3", [("leaf", 0x04, "48 03 c2", "0f a2 90")], "callee at RVA {mid:#x} refused: callee at RVA {leaf:#x} refused: unsupported instruction"), diff --git a/tests/cpu/stack_args.asm b/tests/cpu/stack_args.asm new file mode 100644 index 0000000000..82e6cec7c1 --- /dev/null +++ b/tests/cpu/stack_args.asm @@ -0,0 +1,314 @@ +; Source-owned differential fixture for stack arguments (the fifth and later) of internal callees +; in the jump-table translator. Each export is fn(x, y, trace) with x in RCX, y in RDX and a +; three-word trace in R8, and returns RAX. The callees are not exported: each has its own +; runtime-function entry. A caller writes the stack arguments above the callee's home space, at +; RSP+20h and up when the CALL executes, and the callee reads them at entry RSP+28h and up. The +; register probe seeds RBX and RSI. The exports from unset_slot on exist only to be refused. +.code + +; six_mix(a, b, c, d, e, f) = a + 2b + 3c + 4d + 5e + 6f, with e a quadword and f a doubleword. +six_mix PROC FRAME + .endprolog + lea rax, [rcx+rdx*2] + lea rdx, [r8+r8*2] + add rax, rdx + lea rax, [rax+r9*4] + mov rdx, qword ptr [rsp+28h] + lea rdx, [rdx+rdx*4] + add rax, rdx + mov edx, dword ptr [rsp+30h] + imul rdx, rdx, 6 + add rax, rdx + ret +six_mix ENDP + +; seven_fwd(a, b, c, d, e, f, g) = six_mix(a, b, c, d, f, e) + 7 * g, with g a byte. RSI keeps g +; across the call, and e and f are forwarded swapped as the callee's fifth and sixth arguments. +seven_fwd PROC FRAME + push rsi + .pushreg rsi + sub rsp, 30h + .allocstack 30h + .endprolog + movzx esi, byte ptr [rsp+70h] + mov rax, qword ptr [rsp+68h] + mov qword ptr [rsp+20h], rax + mov rax, qword ptr [rsp+60h] + mov dword ptr [rsp+28h], eax + call six_mix + imul rsi, rsi, 7 + add rax, rsi + add rsp, 30h + pop rsi + ret +seven_fwd ENDP + +; scratch_five(a, b, c, d, e): adds a to its own fifth-argument slot and returns e + a XOR b. +scratch_five PROC FRAME + .endprolog + add qword ptr [rsp+28h], rcx + mov rax, qword ptr [rsp+28h] + xor rax, rdx + ret +scratch_five ENDP + +; rec_five(n, acc, c, d, step): acc when n = 0, otherwise rec_five(n - 1, acc + step, c, d, 3 * step). +rec_five PROC FRAME + sub rsp, 38h + .allocstack 38h + .endprolog + mov rax, rdx + test rcx, rcx + jz rec_five_done + mov rax, qword ptr [rsp+60h] + add rdx, rax + lea rax, [rax+rax*2] + mov qword ptr [rsp+20h], rax + dec rcx + call rec_five +rec_five_done: + add rsp, 38h + ret +rec_five ENDP + +; eight_sum(a, ..., h) = a + 3b + 5c + 7d + 9e + 11f + 13g + 15h, h a word. +eight_sum PROC FRAME + .endprolog + lea rax, [rdx+rdx*2] + add rax, rcx + lea rcx, [r8+r8*4] + add rax, rcx + imul rcx, r9, 7 + add rax, rcx + imul rcx, qword ptr [rsp+28h], 9 + add rax, rcx + imul rcx, qword ptr [rsp+30h], 11 + add rax, rcx + imul rcx, qword ptr [rsp+38h], 13 + add rax, rcx + movzx ecx, word ptr [rsp+40h] + imul rcx, rcx, 15 + add rax, rcx + ret +eight_sum ENDP + +; trace[0] = six_mix(x, y, x XOR y, y + 1, x, y AND 0FFFFFFFFh); returns it. Only the low +; doubleword of the sixth argument is written. +call_six PROC FRAME + push rbx + .pushreg rbx + sub rsp, 30h + .allocstack 30h + .endprolog + mov rbx, r8 + mov qword ptr [rsp+20h], rcx + mov dword ptr [rsp+28h], edx + mov r8, rcx + xor r8, rdx + lea r9, [rdx+1] + call six_mix + mov qword ptr [rbx], rax + add rsp, 30h + pop rbx + ret +call_six ENDP + +; trace[1] = seven_fwd(y, x, 5, x + y, y, x, x SHR 8 AND 0FFh); returns it plus y. The seventh +; argument is one byte, written over a slot that held an earlier quadword. +call_seven PROC FRAME + push rbx + .pushreg rbx + push rsi + .pushreg rsi + sub rsp, 38h + .allocstack 38h + .endprolog + mov rbx, r8 + mov rsi, rdx + mov qword ptr [rsp+30h], rcx + mov qword ptr [rsp+20h], rdx + mov qword ptr [rsp+28h], rcx + mov rax, rcx + shr rax, 8 + mov byte ptr [rsp+30h], al + lea r9, [rcx+rdx] + mov r8d, 5 + mov rdx, rcx + mov rcx, rsi + call seven_fwd + mov qword ptr [rbx+8], rax + add rax, rsi + add rsp, 38h + pop rsi + pop rbx + ret +call_seven ENDP + +; trace[2] = scratch_five(x, y, 0, 0, y * 2); returns it XOR x. The slot the callee modifies is +; written again before a second call, which uses x as both a and e. +call_scratch PROC FRAME + push rbx + .pushreg rbx + push rsi + .pushreg rsi + sub rsp, 28h + .allocstack 28h + .endprolog + mov rbx, r8 + mov rsi, rcx + lea rax, [rdx+rdx] + mov qword ptr [rsp+20h], rax + xor r8d, r8d + xor r9d, r9d + call scratch_five + mov qword ptr [rbx+10h], rax + mov qword ptr [rsp+20h], rsi + mov rcx, rsi + mov rdx, rax + xor r8d, r8d + xor r9d, r9d + call scratch_five + xor rax, rsi + add rsp, 28h + pop rsi + pop rbx + ret +call_scratch ENDP + +; trace[0] = rec_five(x AND 1Fh, y, 0, 0, x); returns it. +call_rec PROC FRAME + push rbx + .pushreg rbx + sub rsp, 30h + .allocstack 30h + .endprolog + mov rbx, r8 + mov qword ptr [rsp+20h], rcx + and ecx, 1Fh + xor r8d, r8d + xor r9d, r9d + call rec_five + mov qword ptr [rbx], rax + add rsp, 30h + pop rbx + ret +call_rec ENDP + +; trace[1] = eight_sum(x, y, x + y, x - y, y, x, x XOR y, y AND 0FFFFh); returns it. +call_eight PROC FRAME + push rbx + .pushreg rbx + sub rsp, 40h + .allocstack 40h + .endprolog + mov rbx, r8 + mov qword ptr [rsp+20h], rdx + mov qword ptr [rsp+28h], rcx + mov rax, rcx + xor rax, rdx + mov qword ptr [rsp+30h], rax + mov word ptr [rsp+38h], dx + lea r8, [rcx+rdx] + mov r9, rcx + sub r9, rdx + call eight_sum + mov qword ptr [rbx+8], rax + add rsp, 40h + pop rbx + ret +call_eight ENDP + +; Refused: the sixth argument of six_mix is never written. +unset_slot PROC FRAME + sub rsp, 38h + .allocstack 38h + .endprolog + mov qword ptr [rsp+20h], rcx + xor r9d, r9d + call six_mix + add rsp, 38h + ret +unset_slot ENDP + +; Refused: only the low doubleword of the fifth argument is written, and six_mix reads all 8 bytes. +narrow_slot PROC FRAME + sub rsp, 38h + .allocstack 38h + .endprolog + mov dword ptr [rsp+20h], ecx + mov dword ptr [rsp+28h], edx + xor r9d, r9d + call six_mix + add rsp, 38h + ret +narrow_slot ENDP + +; Refused: scratch_five may change its stack argument, so the slot is undefined after the call. +reread_slot PROC FRAME + sub rsp, 38h + .allocstack 38h + .endprolog + mov qword ptr [rsp+20h], rcx + call scratch_five + add rax, qword ptr [rsp+20h] + add rsp, 38h + ret +reread_slot ENDP + +; Refused: a tail jump to six_mix would pass this function's own stack arguments. +tail_six PROC FRAME + .endprolog + jmp six_mix +tail_six ENDP + +; Refused: an export reads a fifth argument, which its host call does not pass. +export_fifth PROC FRAME + .endprolog + mov rax, qword ptr [rsp+28h] + ret +export_fifth ENDP + +; Refused: far_ninth reads the thirteenth argument, above the eight stack arguments supported. +far_slot PROC FRAME + sub rsp, 28h + .allocstack 28h + .endprolog + call far_ninth + add rsp, 28h + ret +far_slot ENDP + +far_ninth PROC FRAME + .endprolog + mov rax, qword ptr [rsp+68h] + ret +far_ninth ENDP + +; Refused: straddle reads 8 bytes across the end of its home space and the fifth argument. +straddle_slot PROC FRAME + sub rsp, 28h + .allocstack 28h + .endprolog + call straddle + add rsp, 28h + ret +straddle_slot ENDP + +straddle PROC FRAME + .endprolog + mov rax, qword ptr [rsp+24h] + ret +straddle ENDP + +; Refused: with RSP at entry RSP - 28h, the two stack arguments of six_mix would be this +; function's return address and the slot above it. +high_slots PROC FRAME + sub rsp, 28h + .allocstack 28h + .endprolog + call six_mix + add rsp, 28h + ret +high_slots ENDP + +END diff --git a/tests/cpu/stack_args.def b/tests/cpu/stack_args.def new file mode 100644 index 0000000000..c8d0e11140 --- /dev/null +++ b/tests/cpu/stack_args.def @@ -0,0 +1,14 @@ +EXPORTS + call_six + call_seven + call_scratch + call_rec + call_eight + unset_slot + narrow_slot + reread_slot + tail_six + export_fifth + far_slot + straddle_slot + high_slots diff --git a/tests/cpu/stack_args_check.py b/tests/cpu/stack_args_check.py new file mode 100644 index 0000000000..2b8e2cb9b2 --- /dev/null +++ b/tests/cpu/stack_args_check.py @@ -0,0 +1,215 @@ +"""Differential checks for stack arguments of internal callees in the jump-table translator. + +Each export of tests/cpu/stack_args.asm runs through the register probe. The source-built original +must match the Python reference, and the translation must match the original on the return value, +the guarded trace and the probe's RBX and RSI sentinels. The structure check reads the stack +argument bytes each callee demands. The refused exports must be refused with their stated reason. +""" + +import ctypes +from pathlib import Path +import random +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from direct_check import GUARDS, MASK, SENTINELS, observe, register_probe + +MASK32 = 0xffffffff +EXPORTS = ("call_six", "call_seven", "call_scratch", "call_rec", "call_eight") +# (export, expected refusal), translated alone. +REFUSED = ( + ("unset_slot", "stack argument 6 of the call at RVA {unset_slot_call:#x} is undefined at entry RSP-0x10"), + ("narrow_slot", "stack argument 5 of the call at RVA {narrow_slot_call:#x} is undefined at entry RSP-0x14"), + ("reread_slot", "undefined stack byte at entry RSP-0x18"), + ("tail_six", "tail jump to a function with stack arguments"), + ("export_fifth", "unsupported stack argument at RVA {export_fifth:#x}: entry RSP+0x28"), + ("far_slot", "callee at RVA {far_ninth:#x} refused: unsupported stack argument"), + ("straddle_slot", "callee at RVA {straddle:#x} refused: unsupported stack argument"), + ("high_slots", "stack arguments of the call at RVA {high_slots_call:#x} reach the return address"), +) + +# Refused only because the frame proof follows the stack arguments of each call. +UNPROVEN = ("unset_slot", "narrow_slot", "reread_slot") + + +def trace(first=MASK, second=MASK, third=MASK): + return (GUARDS[0], first & MASK, second & MASK, third & MASK, GUARDS[1]) + + +def six_mix(a, b, c, d, e, f): + return (a + 2 * b + 3 * c + 4 * d + 5 * e + 6 * (f & MASK32)) & MASK + + +def seven_fwd(a, b, c, d, e, f, g): + return (six_mix(a, b, c, d, f, e) + 7 * (g & 0xff)) & MASK + + +def scratch_five(a, b, e): + return ((e + a) & MASK) ^ b + + +def rec_five(n, acc, step): + return acc if n == 0 else rec_five(n - 1, (acc + step) & MASK, 3 * step & MASK) + + +def eight_sum(a, b, c, d, e, f, g, h): + return (a + 3 * b + 5 * c + 7 * d + 9 * e + 11 * f + 13 * g + 15 * (h & 0xffff)) & MASK + + +def call_six(x, y): + value = six_mix(x, y, x ^ y, (y + 1) & MASK, x, y) + return value, trace(value) + + +def call_seven(x, y): + value = seven_fwd(y, x, 5, (x + y) & MASK, y, x, x >> 8) + return (value + y) & MASK, trace(second=value) + + +def call_scratch(x, y): + first = scratch_five(x, y, 2 * y & MASK) + return scratch_five(x, first, x) ^ x, trace(third=first) + + +def call_rec(x, y): + value = rec_five(x & 0x1f, y, x) + return value, trace(value) + + +def call_eight(x, y): + value = eight_sum(x, y, (x + y) & MASK, (x - y) & MASK, y, x, x ^ y, y) + return value, trace(second=value) + + +REFERENCES = {name: globals()[name] for name in EXPORTS} + + +def inputs(): + """Boundary words for both arguments, plus seeded random pairs.""" + edges = (0, 1, 2, 0x1f, 0x20, 0xff, 0x100, 0xffff, 0x10000, 0x7fffffff, 0x80000000, MASK32, + 0x100000000, 0x8000000000000000, MASK - 1, MASK, 0x0123456789abcdef) + rng = random.Random(1205) + pairs = [(x, y) for x in edges for y in edges] + pairs += [(rng.getrandbits(64), rng.getrandbits(64)) for _ in range(160)] + return pairs + + +def run(probe, library, prefix=""): + observed = {} + for name in EXPORTS: + function = ctypes.cast(getattr(library, prefix + name), ctypes.c_void_p).value + observed[name] = [observe(probe, function, x, y) for x, y in inputs()] + return observed + + +def verify_reference(observed, label): + for name in EXPORTS: + for (x, y), (returned, words, registers) in zip(inputs(), observed[name]): + want = REFERENCES[name](x, y) + if (returned, words) != want or registers != SENTINELS: + raise AssertionError(f"{label} {name}({x:#x}, {y:#x}): {returned:#x} {words} {registers} " + f"!= {want[0]:#x} {want[1]} {SENTINELS}") + + +def tools(): + sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) + import pefile + from cpu_leaf_aot import export_rva + import cpu_switch_aot + return pefile, export_rva, cpu_switch_aot + + +def layout(pe, export_rva, aot): + """RVAs of the exports, the callees their calls reach and each refused export's call.""" + from iced_x86 import Decoder, FlowControl + ends = dict(aot.runtime_functions(pe)) + rvas = {name: export_rva(pe, name) for name in EXPORTS + tuple(name for name, _ in REFUSED)} + + def calls(rva): + return [(ins.ip, ins.near_branch_target) for ins in Decoder(64, pe.get_data(rva, ends[rva] - rva), ip=rva) + if ins.flow_control in (FlowControl.CALL, FlowControl.UNCONDITIONAL_BRANCH)] + + (_, rvas["six_mix"]), = calls(rvas["call_six"]) + (_, rvas["seven_fwd"]), = calls(rvas["call_seven"]) + (_, rvas["scratch_five"]), _ = calls(rvas["call_scratch"]) + (_, rvas["rec_five"]), = calls(rvas["call_rec"]) + (_, rvas["eight_sum"]), = calls(rvas["call_eight"]) + (_, rvas["far_ninth"]), = calls(rvas["far_slot"]) + (_, rvas["straddle"]), = calls(rvas["straddle_slot"]) + for name in ("unset_slot", "narrow_slot", "high_slots"): + (rvas[f"{name}_call"], _), = calls(rvas[name]) + return rvas + + +def check(probe_path, original_path, lifted_path): + probe = register_probe(probe_path) + original = run(probe, ctypes.CDLL(str(original_path))) + verify_reference(original, "source fixture") + translated = run(probe, ctypes.CDLL(str(lifted_path)), "lifted_") + for name in EXPORTS: + for (x, y), want, got in zip(inputs(), original[name], translated[name]): + if got != want: + raise AssertionError(f"translation {name}({x:#x}, {y:#x}): {got} != {want}") + print(f"{len(EXPORTS)} exports x {len(inputs())} inputs: the source fixture matches the reference and the " + "translation matches it on the return value, guarded trace, RBX and RSI") + + +def check_structure(original_path): + pefile, export_rva, aot = tools() + with pefile.PE(str(original_path), fast_load=True) as pe: + pe.parse_data_directories() + rvas = layout(pe, export_rva, aot) + program = aot.Program(pe) + for name in EXPORTS: + aot.lift(pe, name, program=program) + # Low bytes of each stack argument that some read of the callee reaches. + want = {"six_mix": (8, 4), "seven_fwd": (8, 8, 1), "scratch_five": (8,), "rec_five": (8,), + "eight_sum": (8, 8, 8, 2)} + stacks = {name: program.callees[rvas[name]].stack for name in want} + if stacks != want: + raise AssertionError(f"stack argument demands {stacks} != {want}") + source = "\n".join(program.sources) + for name, stack in want.items(): + parameters = ", ".join(["word rcx", "word rdx", "word r8", "word r9"] + + [f"word arg{5 + slot}" for slot in range(len(stack))]) + if f"static word fn_{rvas[name]:x}({parameters}) {{" not in source: + raise AssertionError(f"{name} is not defined with {len(stack)} stack argument parameter(s)") + print(f"{len(want)} callees take their stack arguments as parameters; demands {stacks}") + + +def check_refusals(original_path): + pefile, export_rva, aot = tools() + with pefile.PE(str(original_path), fast_load=True) as pe: + pe.parse_data_directories() + rvas = layout(pe, export_rva, aot) + for name, reason in REFUSED: + reason = reason.format(**rvas) + try: + aot.translate(original_path, [name]) + except ValueError as error: + if reason not in str(error): + raise AssertionError(f"{name} refused for another reason: {error}") from error + else: + raise AssertionError(f"{name} accepted: {reason}") + print(f"control {name}: {reason}") + # The planted fault: the frame proof ignores the stack arguments of calls. + prove = aot.prove_frame + aot.prove_frame = lambda function, order, effects, frame, stacks=None: prove(function, order, effects, frame) + try: + for name in UNPROVEN: + try: + aot.translate(original_path, [name]) + except ValueError as error: + raise AssertionError(f"{name} is refused without the stack argument proof: {error}") from error + print(f"control {name}: accepted when the frame proof ignores stack arguments") + finally: + aot.prove_frame = prove + print(f"{len(REFUSED)} stack argument rejection controls passed") + + +if __name__ == "__main__": + if len(sys.argv) != 4: + raise SystemExit("usage: stack_args_check.py PROBE ORIGINAL LIFTED") + check(*sys.argv[1:]) + check_structure(sys.argv[2]) + check_refusals(sys.argv[2]) diff --git a/tools/cpu_switch_aot.py b/tools/cpu_switch_aot.py index f6df36601c..b0f99b54c2 100644 --- a/tools/cpu_switch_aot.py +++ b/tools/cpu_switch_aot.py @@ -20,8 +20,9 @@ "name:3" take three, and R9 is a scratch register that must be written before it is read; any other count is rejected. The count is chosen by whoever invokes the translator, not derived from the machine code, and the host must call the -translated function with the same number of arguments. Stack arguments (the -fifth and later) and floating-point arguments are not supported. +translated function with the same number of arguments. An export's stack +arguments (the fifth and later) and floating-point arguments are not supported; +an internal callee may take stack arguments, as described below. Flags are modeled only between a producer and its consumers (Jcc, SETcc, CMOVcc) in one straight-line run that no edge enters. Overflow and low-byte @@ -111,8 +112,8 @@ byte array per call, from the lowest RSP up to the end of the caller's 32-byte home space at entry RSP + 40, at most MAX_FRAME bytes, and each RSP-based operand a load or store at a constant index into it. An access below the -current RSP (Windows x64 has no red zone), of the return address or at or -above entry RSP + 40 (a stack argument) is rejected. A second pass follows +current RSP (Windows x64 has no red zone), of the return address or, in an +export, at or above entry RSP + 40 (a stack argument) is rejected. A second pass follows every stack byte: a read needs each byte written on every path, so home space must be written before it is read. RBX, RBP, RSI, RDI and R12-R15 may be used when every RET is reached with each one holding its entry value again, saved @@ -140,8 +141,16 @@ leave below RSP. RSP must be 8 mod 16 from entry at a call, with the callee's home space below the return address. A tail jump is checked as a RET and contributes the callee's return -width. The callee's frame is its own array, so no frame address crosses a call, -and stack arguments stay refused. +width. The callee's frame is its own array, so no frame address crosses a call. + +An internal function may read and write up to MAX_STACK_ARGUMENTS stack +arguments, the 8-byte slots from entry RSP + 40, each access inside one slot. Its +frame array extends over them, copied at entry from one parameter per slot after +R9, and it records how many low bytes of each slot some read reaches. A caller +must have those bytes written at RSP + 32 + 8 * slot when the CALL executes, below +its own return address, and passes the 8 bytes of each slot. Afterwards the slots +are undefined, like the callee's home space, because the callee may write them. +A tail jump to a function with stack arguments is refused. A CALL may close a call cycle, an export's own entry included, which becomes an internal function too. A call into a function whose translation is in progress @@ -225,6 +234,8 @@ MAX_FRAME = 4096 # The home space a callee may write: the 32 bytes at RSP when the CALL executes. HOME_SIZE = 32 +# Stack arguments an internal function may take: the fifth to the twelfth, 8 bytes each from entry RSP + 40. +MAX_STACK_ARGUMENTS = 8 HIGH_BYTES = {R.AH, R.BH, R.CH, R.DH} # Flow that continues at the next instruction (a direct call does once its callee returns). STRAIGHT = (FlowControl.NEXT, FlowControl.CONDITIONAL_BRANCH, FlowControl.CALL, FlowControl.INDIRECT_CALL) @@ -1489,7 +1500,10 @@ class Frame: frame_limit = MAX_FRAME incoming_end = HOME_END - def __init__(self, function, edges): + def __init__(self, function, edges, internal=False): + if internal: + # An internal function may read the stack arguments its callers write above its home space. + self.incoming_end = HOME_END + 8 * MAX_STACK_ARGUMENTS self.offsets, self.accesses, self.adjustments, self.released = {function.entry: 0}, {}, set(), {} self.output_calls = {} self.output_addresses = {} @@ -1547,9 +1561,17 @@ def __init__(self, function, edges): if offset < self.offsets[ip] + HOME_SIZE or offset % width: raise ValueError(f"misaligned stack output or overlap with callee home space at RVA {ip:#x}") self.outputs[ip] = (offset, width) + # Per stack argument slot: the low bytes that some read reaches, 0 for a slot only written. + slots = {} + for offset, width, reads, _ in self.accesses.values(): + if offset >= HOME_END: + slot = (offset - HOME_END) // 8 + slots[slot] = max(slots.get(slot, 0), offset + width - HOME_END - 8 * slot if reads else 0) + self.stack = tuple(slots.get(slot, 0) for slot in range(max(slots, default=-1) + 1)) low = min(self.offsets.values()) self.start = low - (low + 8) % 16 - self.size = HOME_END - self.start + self.end = HOME_END + 8 * len(self.stack) + self.size = self.end - self.start if self.size > self.frame_limit: raise ValueError(f"frame of {self.size} bytes exceeds the {self.frame_limit}-byte bound") @@ -1558,7 +1580,8 @@ def access(self, ins, rsp, offset, width, reads, writes): raise ValueError(f"stack access below RSP at RVA {ins.ip:#x}") if offset < 8 and offset + width > 0: raise ValueError(f"return address slot accessed at RVA {ins.ip:#x}") - if offset + width > self.incoming_end: + if offset + width > HOME_END and (offset + width > self.incoming_end or offset < HOME_END + or (offset - HOME_END) // 8 != (offset + width - 1 - HOME_END) // 8): raise ValueError(f"unsupported stack argument at RVA {ins.ip:#x}: entry RSP{offset:+#x}") self.accesses[ins.ip] = (offset, width, reads, writes) @@ -1662,7 +1685,7 @@ def slot_register(ins): return None -def prove_frame(function, order, effects, frame): +def prove_frame(function, order, effects, frame, stacks=None): """Check that every stack byte is written before it is read and that every RET is reached with each nonvolatile register holding its entry value, on every path. @@ -1675,6 +1698,8 @@ def prove_frame(function, order, effects, frame): as data, so its register read is removed from effects before the register pass.""" instructions = function.instructions saved = {register: bytes(range(2 + 8 * i, 10 + 8 * i)) for i, register in enumerate(NONVOLATILE)} + # Per call: the low bytes of each stack argument that the callee may read. + stacks = stacks or {} def step(ip, status, data): if ip in function.calls: @@ -1682,8 +1707,10 @@ def step(ip, status, data): # callee's frame lie below RSP, where every byte is already 0: no access is below RSP, and the # bytes that ADD RSP and POP leave below RSP become 0. The rest of the frame, including this # function's own home space above entry RSP, is kept. + # It may also write the stack arguments above that home space. index = frame.offsets[ip] - frame.start - data = data[:index] + bytes(HOME_SIZE) + data[index + HOME_SIZE:] + size = HOME_SIZE + 8 * len(stacks.get(ip, ())) + data = data[:index] + bytes(size) + data[index + size:] if ip in frame.outputs: offset, width = frame.outputs[ip] index = offset - frame.start @@ -1706,7 +1733,9 @@ def step(ip, status, data): status[register] = "entry" if register == restored else "written" return tuple(status.values()), data - state = {function.entry: (("entry",) * len(NONVOLATILE), bytes(frame.size))} + # The caller writes the stack arguments before the call. + state = {function.entry: (("entry",) * len(NONVOLATILE), + bytes(HOME_END - frame.start) + b"\1" * (frame.end - HOME_END))} work = [function.entry] while work: ip = work.pop() @@ -1728,6 +1757,14 @@ def step(ip, status, data): if status.get(read, "written") != "written": raise ValueError(f"nonvolatile register {NAMES[read]} may hold the caller's value where RVA " f"{ip:#x} reads it") + for slot, needed in enumerate(stacks.get(ip, ())): + index = frame.offsets[ip] + HOME_SIZE + 8 * slot - frame.start + passed = data[index:index + needed] + if passed != b"\1" * needed: + at = index + frame.start + (passed.index(0) if 0 in passed else 0) + raise ValueError(f"stack argument {5 + slot} of the call at RVA {ip:#x} is undefined at entry " + f"RSP{at:+#x}" if 0 in passed else + f"stack argument {5 + slot} of the call at RVA {ip:#x} holds a saved register") got = data[offset - frame.start:offset - frame.start + width] if loads and got != b"\1" * width and not (register is not None and got == saved[register]): if 0 in got: @@ -1827,17 +1864,25 @@ def demands(self): class Assumed(NamedTuple): - """The summary that calls into a function still being translated use: its return width and - argument demands, assumed until its translation computes them.""" + """The summary that calls into a function still being translated use: its return width, + argument demands and stack argument demands, assumed until its translation computes them.""" entry: int return_width: int demands: dict + stack: tuple = () + + +def parameters(registers, stack=()): + """The C++ parameters of a function: its argument registers, then one word per stack argument.""" + return ", ".join([f"word {NAMES[r]}" for r in registers] + [f"word arg{5 + slot}" for slot in range(len(stack))]) def at_least_as_good(computed, assumed): """Whether a computed summary defines at least the assumed RAX bytes and demands no more.""" return (computed.return_width >= assumed.return_width - and all(width <= assumed.demands.get(r, 0) for r, width in computed.demands.items())) + and all(width <= assumed.demands.get(r, 0) for r, width in computed.demands.items()) + and len(computed.stack) <= len(assumed.stack) + and all(width <= assumed.stack[slot] for slot, width in enumerate(computed.stack))) class Program: @@ -1921,7 +1966,10 @@ def callee(self, target, ip): demands = {r: max(width, function.demands.get(r, 0)) for r, width in assumed.demands.items()} | { r: width for r, width in function.demands.items() if r not in assumed.demands} - self.assumed[target] = Assumed(target, min(assumed.return_width, function.return_width), demands) + slots = max(len(assumed.stack), len(function.stack)) + stack = tuple(max(assumed.stack[slot] if slot < len(assumed.stack) else 0, + function.stack[slot] if slot < len(function.stack) else 0) for slot in range(slots)) + self.assumed[target] = Assumed(target, min(assumed.return_width, function.return_width), demands, stack) del self.pending[start:] if self.low < depth: # Part of a cycle through a function below it on the stack, which keeps it when that is done. @@ -1934,8 +1982,8 @@ def callee(self, target, ip): del self.pending[start:] cyclic = [self.assumed.pop(entry, None) for entry, _, _ in members] if any(cyclic) or len(members) > 1: - self.sources.append("\n".join(f"static word fn_{entry:x}({', '.join(f'word {NAMES[r]}' for r in ARGUMENT_REGISTERS)});" - for entry, _, _ in sorted(members, key=lambda m: m[0]))) + self.sources.append("\n".join(f"static word fn_{entry:x}({parameters(ARGUMENT_REGISTERS, member.stack)});" + for entry, _, member in sorted(members, key=lambda m: m[0]))) for entry, text, member in members: self.callees[entry] = member self.sources.append(text) @@ -1988,7 +2036,7 @@ def lift_function(program, entry, symbol, arguments, internal): bases = {(base, anchor) for *_, (_, _, base, anchor) in function.dispatches.values()} order = sorted(function.instructions) instructions = function.instructions - frame = Frame(function, edges) + frame = Frame(function, edges, internal) if internal and not function.unwound: # Without unwind data a function may not move RSP, so it cannot push, allocate or call. moved = sorted(ip for ip, offset in frame.offsets.items() if offset or ip in function.calls) @@ -2010,6 +2058,14 @@ def lift_function(program, entry, symbol, arguments, internal): if not program.committed(callees[ip]): # The original runs a cycle of tail jumps in constant stack; the host call does not. raise ValueError(f"tail jump within a call cycle at RVA {ip:#x}") + # Per call: the low bytes of each stack argument that the callee may read. + stacks = {ip: callee.stack for ip, callee in callees.items() if getattr(callee, "stack", ())} + for ip, stack in sorted(stacks.items()): + if ip in function.tails: + # The stack arguments would be this function's own, which its caller wrote. + raise ValueError(f"tail jump to a function with stack arguments at RVA {ip:#x}") + if frame.offsets[ip] + HOME_SIZE + 8 * len(stack) > 0: + raise ValueError(f"stack arguments of the call at RVA {ip:#x} reach the return address") loads = {sequence[0]: index for index, _, sequence, _, _, _ in function.dispatches.values()} skipped = {ip for _, _, sequence, _, _, _ in function.dispatches.values() for ip in sequence} body = {} @@ -2027,7 +2083,11 @@ def lift_function(program, entry, symbol, arguments, internal): for r in callee.demands] call = f"{callee.symbol}({', '.join(call_args)})" else: - call = f"fn_{callee.entry:x}({', '.join(lifter.reg(r) for r in ARGUMENT_REGISTERS)})" + # Stack arguments are passed by value from the bytes above the callee's home space. + passed = [lifter.reg(r) for r in ARGUMENT_REGISTERS] + [ + f"load(reinterpret_cast(frame + {frame.offsets[ip] + HOME_SIZE + 8 * slot - frame.start}))" + for slot in range(len(stacks.get(ip, ())))] + call = f"fn_{callee.entry:x}({', '.join(passed)})" # A tail jump returns the callee's RAX; a call leaves it in RAX. if isinstance(callee, HostImport) and callee.return_width == 0: body[ip] = f"{call}; return 0;" if ip in function.tails else f"{call};" @@ -2082,7 +2142,7 @@ def lift_function(program, entry, symbol, arguments, internal): for ip, ins in instructions.items() if ins.mnemonic == M.MOV and ins.op0_kind == ins.op1_kind == OpKind.REGISTER and RegisterExt.size(ins.op0_register) >= 4 and full(ins.op0_register) in effects[ip][1]} - prove_frame(function, order, effects, frame) + prove_frame(function, order, effects, frame, stacks) # Per register: (low bytes defined on every path: 0, 1, 2 or 8; may hold a guest address that # the translation does not reproduce). Arguments are defined at entry; joins meet as (min, or). @@ -2139,6 +2199,11 @@ def lift_function(program, entry, symbol, arguments, internal): # Consecutive low RAX bytes defined at every reachable RET or tail jump; None when there is none. function.return_width = min(widths) if widths else None function.demands = argument_demands(function, order, effects) + # Calls in a cycle pass the stack arguments the assumed summary names; the definition takes them all. + assumed = program.assumed.get(entry) if internal else None + stack = frame.stack + (0,) * max(0, len(assumed.stack) - len(frame.stack)) if assumed else frame.stack + function.stack = tuple(max(width, assumed.stack[slot] if assumed and slot < len(assumed.stack) else 0) + for slot, width in enumerate(stack)) labels = set(edges) if order[0] != entry: @@ -2162,7 +2227,10 @@ def lift_function(program, entry, symbol, arguments, internal): declarations.append("word fa = 0, fb = 0;") if lifter.frame: declarations.append(f"alignas(16) std::uint8_t frame[{frame.size}] = {{}}; " - f"// entry RSP{frame.start:+#x} to entry RSP+{HOME_END:#x}") + f"// entry RSP{frame.start:+#x} to entry RSP+{frame.end:#x}") + for slot, width in enumerate(frame.stack): + if width: + declarations.append(f"std::memcpy(frame + {HOME_END + 8 * slot - frame.start}, &arg{5 + slot}, 8);") text = [f" goto loc_{entry:x};"] if order[0] != entry else [] for position, ip in enumerate(order): if ip in labels: @@ -2174,7 +2242,7 @@ def lift_function(program, entry, symbol, arguments, internal): if ins.flow_control in STRAIGHT and function.successors[ip] and following != ins.next_ip: text.append(f" goto loc_{ins.next_ip:x};") linkage = "static" if internal else 'extern "C" __declspec(dllexport)' - signature = f'{linkage} word {symbol}({", ".join(f"word {NAMES[r]}" for r in function.arguments)})' + signature = f'{linkage} word {symbol}({parameters(function.arguments, function.stack)})' comment = [] if function.return_width is None: comment = ["// RAX: no reachable normal return"] From cff5b6d822936b3cabaf8b2a31fc7e84af34131d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 15:42:48 +0000 Subject: [PATCH 5/7] cpu: pass 0 for stack slots a callee only writes, and fix the stale_rsp fault A callee that only writes a stack-argument slot demands none of its bytes, so its caller may have no frame array, but the call still loaded the slot from one and the C++ did not compile. Such a slot is passed as 0. The planted stale_rsp fault of cpu_aot_fuzz_rsp replaced Frame.__init__ with the old signature and failed to translate; it now passes the internal flag on. stack_args.asm adds a caller with no stack byte of its own for a write-only slot, two calls whose last slot ends exactly at the return address, an accepted twelfth argument, and a self-call that leaves the fifth argument it reads unwritten, which is refused only because the cycle is translated again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014uAfgrqe3XyeqvkJrdnUK6 --- docs/experiments.md | 4 +- tests/cpu/stack_args.asm | 82 +++++++++++++++++++++++++++++++++++ tests/cpu/stack_args.def | 4 ++ tests/cpu/stack_args_check.py | 42 ++++++++++++++++-- tools/cpu_switch_aot.py | 5 ++- tools/fuzz_cpu.py | 4 +- 6 files changed, 131 insertions(+), 10 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 9f1971cfb9..08322651ef 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -2800,9 +2800,9 @@ A `CALL` may close a call cycle ([#317](https://github.com/R0Y00/Xbox2Windows/is `cpu_aot_recursion` builds [`recursion.asm`](../tests/cpu/recursion.asm) and translates four exports. `sum_export` calls `sum_down`, which recurses through `CALL` up to 511 levels and keeps its arguments in RBX and RSI across the call. `parity_export` calls `is_even` and `is_odd`, which call each other. `is_even` defines only AL at its base case and `is_odd` all of RAX, so only the second translation of the cycle gives `is_odd` its 1-byte width. `walk_export` calls `walk_a`, which is in a cycle with `walk_b` and `walk_c`. Only `walk_a` reads R8, so only the second translation makes `walk_c` demand it; `walk_b` also calls `count_down`, whose own cycle is kept while the outer cycle is still being translated. `fold_export` calls its own exported entry up to 64 levels. Through the register probe, the original must match a Python reference, and the translation must match the original on the return value, the guarded trace, RBX and RSI over 484 input pairs per export. The test checks that each of the eight internal functions is declared once and defined once, that `is_even` and `is_odd` return 1 byte and the others 8, and that exactly `walk_a`, `walk_b`, `walk_c` and the internal `fold_export` demand R8. Five exports must be refused as written: `tail_ping` and `tail_pong`, a cycle of tail jumps; `wide_odd`, which reads all of RAX after `is_odd`; `lost_k`, which calls `walk_c` after another call left R8 undefined; `bad_a`, in a cycle with `bad_b`, which executes `CPUID`; and `stale_e`, whose callee `stale_a` reads all of RAX after `stale_t`. `stale_t` is translated after `stale_s` and `stale_q` are on hold and reuses `stale_q`, so it is in their cycle and returns only AL; a translator that keeps `stale_t` on its own, with the 8 bytes first assumed for the cycle, accepts `stale_e`. Keeping the first summary of each cycle instead of translating it again (the test replaces `at_least_as_good`) accepts `wide_odd` and `lost_k`, and the test fails unless it does. Before this change all four exports were refused, with `self-recursion` or `mutual recursion: call cycle`. Measured on Linux x86-64 with `llvm-ml` 18, `lld-link` and `clang++` at `-O0` and `-O2`, with the original image mapped in-process and called through a Windows x64 register probe: the original matched the reference and kept RBX and RSI, and 3,872 translated calls matched it. The C++ generated for 15 other `cpu_switch_aot` fixtures and for the `calls`, `chains` and `rsp` fuzz programs at their default seeds, `calls` at `0xBEEF` and `chains` at `0xCCD1` with 128 functions, is unchanged. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_recursion$' -V`. -An internal callee may take stack arguments, the fifth to the twelfth: the 8-byte slots from its entry RSP + 0x28, which the Windows x64 calling convention places above the caller's home space. Each access must lie inside one slot. The callee's frame array extends over the slots it accesses, each copied at entry from one more C++ parameter after R9, and the callee records how many low bytes of each slot some read reaches. This counts reads after the callee's own writes too, so it can demand more than it needs, never less. At each call the caller's frame proof must show those bytes written as data at RSP + 0x20 + 8 * slot, below the caller's return address, and the call passes the 8 bytes of each slot from the caller's frame array. After the call those slots are undefined, like the callee's home space, because the callee may write them. A call in a cycle passes the slots of the assumed summary, and the iteration above covers the slot demands too. A tail jump to a function with stack arguments is refused, because the slots would be the ones the caller's own caller wrote. An export still takes no stack arguments, because its host call passes none. +An internal callee may take stack arguments, the fifth to the twelfth: the 8-byte slots from its entry RSP + 0x28, which the Windows x64 calling convention places above the caller's home space. Each access must lie inside one slot. The callee's frame array extends over the slots it accesses, each copied at entry from one more C++ parameter after R9, and the callee records how many low bytes of each slot some read reaches. This counts reads after the callee's own writes too, so it can demand more than it needs, never less. At each call the caller's frame proof must show those bytes written as data at RSP + 0x20 + 8 * slot, below the caller's return address, and the call passes the 8 bytes of each slot from the caller's frame array, or 0 for a slot the callee only writes. After the call those slots are undefined, like the callee's home space, because the callee may write them. A call in a cycle passes the slots of the assumed summary, and the iteration above covers the slot demands too. A tail jump to a function with stack arguments is refused, because the slots would be the ones the caller's own caller wrote. An export still takes no stack arguments, because its host call passes none. -`cpu_aot_stack_arguments` builds [`stack_args.asm`](../tests/cpu/stack_args.asm) and translates five exports. `call_six` calls `six_mix`, a frameless leaf with six arguments whose sixth is read as a doubleword, written as one. `call_seven` calls `seven_fwd`, which reads three stack arguments (8, 8 and 1 bytes) through its own `PUSH` and allocation and passes two of them swapped to `six_mix` as its fifth and sixth. `call_scratch` calls `scratch_five`, which adds to its own fifth-argument slot, twice, writing the slot again before the second call. `call_rec` calls `rec_five`, which passes a new fifth argument to itself up to 31 levels. `call_eight` calls `eight_sum`, with eight arguments, the last a word. Through the register probe, the original must match a Python reference, and the translation must match the original on the return value, the guarded trace, RBX and RSI over 449 input pairs per export. The test checks the demanded bytes per slot, (8, 4) for `six_mix`, (8, 8, 1) for `seven_fwd`, (8) for `scratch_five` and `rec_five` and (8, 8, 8, 2) for `eight_sum`, and that each callee is defined with that many stack parameters. Eight exports must be refused as written: `unset_slot` leaves the sixth argument of `six_mix` unwritten, `narrow_slot` writes only 4 bytes of its 8-byte fifth argument, `reread_slot` reads its slot after `scratch_five` may have changed it, `tail_six` tail-jumps to `six_mix`, `export_fifth` is an export that reads a fifth argument, `far_slot` calls a callee that reads the thirteenth, `straddle_slot` one that reads 8 bytes across the end of its home space, and `high_slots` calls `six_mix` with RSP at entry RSP - 0x28, so its two slots would be its own return address and the slot above it. A frame proof that ignores the slots of calls (the test replaces `prove_frame`) accepts the first three, and the test fails unless it does. The direct-call control that patches `mid_step` to read its fifth-argument slot is now refused because that slot holds the RSI that `chain3` pushed. Before this change all five exports were refused with `unsupported stack argument`. Measured on Linux x86-64 with `llvm-ml` 18, `lld-link` and `clang++` at `-O0` and `-O2`, with the original image mapped in-process and called through a Windows x64 register probe: the original matched the reference and kept RBX and RSI, and 4,490 translated calls matched it. The C++ generated for the other `cpu_switch_aot` fixtures, `recursion.asm` included, and for the fuzz programs listed above is unchanged. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_stack_arguments$' -V`. +`cpu_aot_stack_arguments` builds [`stack_args.asm`](../tests/cpu/stack_args.asm) and translates five exports. `call_six` calls `six_mix`, a frameless leaf with six arguments whose sixth is read as a doubleword, written as one. `call_seven` calls `seven_fwd`, which reads three stack arguments (8, 8 and 1 bytes) through its own `PUSH` and allocation and passes two of them swapped to `six_mix` as its fifth and sixth. `call_scratch` calls `scratch_five`, which adds to its own fifth-argument slot, twice, writing the slot again before the second call. `call_rec` calls `rec_five`, which passes a new fifth argument to itself up to 31 levels. `call_eight` calls `eight_sum`, with eight arguments, the last a word. `call_fill` writes no stack byte and calls `fill_five`, which only writes its fifth-argument slot, and `call_edge` passes `scratch_five` its slot; in both the slot ends exactly at the caller's return address. `call_twelfth` writes only the twelfth argument, the last supported slot, for `twelfth`. Through the register probe, the original must match a Python reference, and the translation must match the original on the return value, the guarded trace, RBX and RSI over 449 input pairs per export. The test checks the demanded bytes per slot, (8, 4) for `six_mix`, (8, 8, 1) for `seven_fwd`, (8) for `scratch_five` and `rec_five`, (8, 8, 8, 2) for `eight_sum`, (0) for `fill_five` and seven zeros and an 8 for `twelfth`, and that each callee is defined with that many stack parameters. Nine exports must be refused as written: `unset_slot` leaves the sixth argument of `six_mix` unwritten, `narrow_slot` writes only 4 bytes of its 8-byte fifth argument, `reread_slot` reads its slot after `scratch_five` may have changed it, `tail_six` tail-jumps to `six_mix`, `export_fifth` is an export that reads a fifth argument, `far_slot` calls a callee that reads the thirteenth, `straddle_slot` one that reads 8 bytes across the end of its home space, and `high_slots` calls `six_mix` with RSP at entry RSP - 0x28, so its two slots would be its own return address and the slot above it, and `lost_slot` calls `rec_lost`, which calls itself without writing the fifth argument it reads. A frame proof that ignores the slots of calls (the test replaces `prove_frame`) accepts the first three, keeping the first summary of each cycle accepts `lost_slot`, and the test fails unless they are accepted. The direct-call control that patches `mid_step` to read its fifth-argument slot is now refused because that slot holds the RSI that `chain3` pushed. Before this change all five exports were refused with `unsupported stack argument`. Measured on Linux x86-64 with `llvm-ml` 18, `lld-link` and `clang++` at `-O0` and `-O2`, with the original image mapped in-process and called through a Windows x64 register probe: the original matched the reference and kept RBX and RSI, and 7,184 translated calls matched it. The C++ generated for the other `cpu_switch_aot` fixtures, `recursion.asm` included, and for the fuzz programs listed above is unchanged, and so are the clean and planted translations of every fuzz area that `llvm-ml` assembles, at the CMake default seeds; the planted `stale_rsp` fault of `cpu_aot_fuzz_rsp` passes the new `Frame` argument on. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_stack_arguments$' -V`. `cpu_aot_call_entries` builds [`call_entries.asm`](../tests/cpu/call_entries.asm), whose `.pdata` and `.xdata` are written explicitly so the image has a primary function continued by a chained secondary range. It also exports an interior label of a primary function, a `.data` variable as `DATA` and a forwarder to `kernel32.GetTickCount`. The test reads the image's own records and checks that the translator's entries are exactly the four primary runtime functions. A framed `CALL` and a tail `JMP` to the primary leaf translate and match the original and a Python reference over 249 input pairs each. Eight retargeted copies must be rejected with the reason that names the distinction: the call retargeted to the exported interior label, the chained range's start, the data export and the forwarder; the tail jump retargeted to the interior label and the chained start; and the leaf's unwind header patched from version 1 to version 3, for both the call and the tail jump. The translator before this rule refused the first six later and for unrelated reasons (`no unique function interval`, `not in an executable section`, `edge outside owned ranges`), and accepted the last two. Removing the version check, or accepting an export at the start of an unverified record, accepts the version controls. Counting interior exports or chained ranges as entries, or classifying forwarders and data exports as code, fails the check of the entry table. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_call_entries$' -V`. diff --git a/tests/cpu/stack_args.asm b/tests/cpu/stack_args.asm index 82e6cec7c1..fcad250dbd 100644 --- a/tests/cpu/stack_args.asm +++ b/tests/cpu/stack_args.asm @@ -92,6 +92,38 @@ eight_sum PROC FRAME ret eight_sum ENDP +; fill_five(a, b, c, d, e): writes a to its fifth-argument slot without reading it; returns 3a. +fill_five PROC FRAME + .endprolog + mov qword ptr [rsp+28h], rcx + lea rax, [rcx+rcx*2] + ret +fill_five ENDP + +; twelfth(a, ..., l) = a XOR l: the twelfth argument, in the last supported slot. +twelfth PROC FRAME + .endprolog + mov rax, qword ptr [rsp+60h] + xor rax, rcx + ret +twelfth ENDP + +; rec_lost(n, b, c, d, e): e when n = 0, otherwise rec_lost(n - 1, ...) without writing its fifth +; argument. Refused through lost_slot below. +rec_lost PROC FRAME + sub rsp, 38h + .allocstack 38h + .endprolog + mov rax, qword ptr [rsp+60h] + test rcx, rcx + jz rec_lost_done + dec rcx + call rec_lost +rec_lost_done: + add rsp, 38h + ret +rec_lost ENDP + ; trace[0] = six_mix(x, y, x XOR y, y + 1, x, y AND 0FFFFFFFFh); returns it. Only the low ; doubleword of the sixth argument is written. call_six PROC FRAME @@ -218,6 +250,56 @@ call_eight PROC FRAME ret call_eight ENDP +; Returns fill_five(x, ...) = 3x. fill_five reads none of its stack arguments, so this caller +; writes no stack byte, and its one slot ends exactly at this function's return address. +call_fill PROC FRAME + sub rsp, 28h + .allocstack 28h + .endprolog + call fill_five + add rsp, 28h + ret +call_fill ENDP + +; Returns scratch_five(y, x, 0, 0, x) = (x + y) XOR x, with its slot ending exactly at the return address. +call_edge PROC FRAME + sub rsp, 28h + .allocstack 28h + .endprolog + mov qword ptr [rsp+20h], rcx + mov rax, rcx + mov rcx, rdx + mov rdx, rax + xor r8d, r8d + xor r9d, r9d + call scratch_five + add rsp, 28h + ret +call_edge ENDP + +; Returns twelfth(x, ..., y) = x XOR y; only the twelfth argument is written. +call_twelfth PROC FRAME + sub rsp, 68h + .allocstack 68h + .endprolog + mov qword ptr [rsp+58h], rdx + call twelfth + add rsp, 68h + ret +call_twelfth ENDP + +; Refused: rec_lost calls itself without writing the fifth argument it reads. +lost_slot PROC FRAME + sub rsp, 38h + .allocstack 38h + .endprolog + mov qword ptr [rsp+20h], rdx + xor r9d, r9d + call rec_lost + add rsp, 38h + ret +lost_slot ENDP + ; Refused: the sixth argument of six_mix is never written. unset_slot PROC FRAME sub rsp, 38h diff --git a/tests/cpu/stack_args.def b/tests/cpu/stack_args.def index c8d0e11140..4e56c10ae4 100644 --- a/tests/cpu/stack_args.def +++ b/tests/cpu/stack_args.def @@ -4,6 +4,10 @@ EXPORTS call_scratch call_rec call_eight + call_fill + call_edge + call_twelfth + lost_slot unset_slot narrow_slot reread_slot diff --git a/tests/cpu/stack_args_check.py b/tests/cpu/stack_args_check.py index 2b8e2cb9b2..faf84a1c96 100644 --- a/tests/cpu/stack_args_check.py +++ b/tests/cpu/stack_args_check.py @@ -15,7 +15,7 @@ from direct_check import GUARDS, MASK, SENTINELS, observe, register_probe MASK32 = 0xffffffff -EXPORTS = ("call_six", "call_seven", "call_scratch", "call_rec", "call_eight") +EXPORTS = ("call_six", "call_seven", "call_scratch", "call_rec", "call_eight", "call_fill", "call_edge", "call_twelfth") # (export, expected refusal), translated alone. REFUSED = ( ("unset_slot", "stack argument 6 of the call at RVA {unset_slot_call:#x} is undefined at entry RSP-0x10"), @@ -23,10 +23,16 @@ ("reread_slot", "undefined stack byte at entry RSP-0x18"), ("tail_six", "tail jump to a function with stack arguments"), ("export_fifth", "unsupported stack argument at RVA {export_fifth:#x}: entry RSP+0x28"), - ("far_slot", "callee at RVA {far_ninth:#x} refused: unsupported stack argument"), - ("straddle_slot", "callee at RVA {straddle:#x} refused: unsupported stack argument"), + ("far_slot", "callee at RVA {far_ninth:#x} refused: unsupported stack argument at RVA {far_ninth:#x}: " + "entry RSP+0x68"), + ("straddle_slot", "callee at RVA {straddle:#x} refused: unsupported stack argument at RVA {straddle:#x}: " + "entry RSP+0x24"), ("high_slots", "stack arguments of the call at RVA {high_slots_call:#x} reach the return address"), + ("lost_slot", "callee at RVA {rec_lost:#x} refused: stack argument 5 of the call at RVA {rec_lost_call:#x} " + "is undefined at entry RSP-0x18"), ) +# Refused only because a cycle's first summary is translated again. +ITERATED = ("lost_slot",) # Refused only because the frame proof follows the stack arguments of each call. UNPROVEN = ("unset_slot", "narrow_slot", "reread_slot") @@ -81,6 +87,18 @@ def call_eight(x, y): return value, trace(second=value) +def call_fill(x, y): + return 3 * x & MASK, trace() + + +def call_edge(x, y): + return scratch_five(y, x, x), trace() + + +def call_twelfth(x, y): + return x ^ y, trace() + + REFERENCES = {name: globals()[name] for name in EXPORTS} @@ -136,6 +154,10 @@ def calls(rva): (_, rvas["eight_sum"]), = calls(rvas["call_eight"]) (_, rvas["far_ninth"]), = calls(rvas["far_slot"]) (_, rvas["straddle"]), = calls(rvas["straddle_slot"]) + (_, rvas["fill_five"]), = calls(rvas["call_fill"]) + (_, rvas["twelfth"]), = calls(rvas["call_twelfth"]) + (_, rvas["rec_lost"]), = calls(rvas["lost_slot"]) + (rvas["rec_lost_call"], _), = calls(rvas["rec_lost"]) for name in ("unset_slot", "narrow_slot", "high_slots"): (rvas[f"{name}_call"], _), = calls(rvas[name]) return rvas @@ -164,7 +186,7 @@ def check_structure(original_path): aot.lift(pe, name, program=program) # Low bytes of each stack argument that some read of the callee reaches. want = {"six_mix": (8, 4), "seven_fwd": (8, 8, 1), "scratch_five": (8,), "rec_five": (8,), - "eight_sum": (8, 8, 8, 2)} + "eight_sum": (8, 8, 8, 2), "fill_five": (0,), "twelfth": (0,) * 7 + (8,)} stacks = {name: program.callees[rvas[name]].stack for name in want} if stacks != want: raise AssertionError(f"stack argument demands {stacks} != {want}") @@ -204,6 +226,18 @@ def check_refusals(original_path): print(f"control {name}: accepted when the frame proof ignores stack arguments") finally: aot.prove_frame = prove + # The planted fault: keep a cycle's first summary, however it compares with the assumption. + iterate = aot.at_least_as_good + aot.at_least_as_good = lambda computed, assumed: True + try: + for name in ITERATED: + try: + aot.translate(original_path, [name]) + except ValueError as error: + raise AssertionError(f"{name} is refused without the iteration: {error}") from error + print(f"control {name}: accepted when the first summary of a cycle is kept") + finally: + aot.at_least_as_good = iterate print(f"{len(REFUSED)} stack argument rejection controls passed") diff --git a/tools/cpu_switch_aot.py b/tools/cpu_switch_aot.py index b0f99b54c2..8766685091 100644 --- a/tools/cpu_switch_aot.py +++ b/tools/cpu_switch_aot.py @@ -2083,10 +2083,11 @@ def lift_function(program, entry, symbol, arguments, internal): for r in callee.demands] call = f"{callee.symbol}({', '.join(call_args)})" else: - # Stack arguments are passed by value from the bytes above the callee's home space. + # Stack arguments are passed by value from the bytes above the callee's home space. A slot + # that the callee never reads is passed as 0; the caller then need not have a frame. passed = [lifter.reg(r) for r in ARGUMENT_REGISTERS] + [ f"load(reinterpret_cast(frame + {frame.offsets[ip] + HOME_SIZE + 8 * slot - frame.start}))" - for slot in range(len(stacks.get(ip, ())))] + if width else "0" for slot, width in enumerate(stacks.get(ip, ()))] call = f"fn_{callee.entry:x}({', '.join(passed)})" # A tail jump returns the callee's RAX; a call leaves it in RAX. if isinstance(callee, HostImport) and callee.return_width == 0: diff --git a/tools/fuzz_cpu.py b/tools/fuzz_cpu.py index cbba66a981..cc659c2e92 100644 --- a/tools/fuzz_cpu.py +++ b/tools/fuzz_cpu.py @@ -1879,8 +1879,8 @@ def plant_stale_rsp(cpu_switch_aot, image, functions): shifts = {} # RVA -> (RSP at the instruction minus RSP after the prologue, bytes of the frame array) original_frame = cpu_switch_aot.Frame.__init__ - def frame_init(self, function, edges): - original_frame(self, function, edges) + def frame_init(self, function, edges, internal=False): + original_frame(self, function, edges, internal) if self.adjustments: floor = self.offsets[function.instructions[min(self.adjustments)].next_ip] for ip, offset in self.offsets.items(): From ec40e7fc2cfccc6b7a097a9484553ed3c48766cc Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 20:39:37 +0000 Subject: [PATCH 6/7] cpu: translate the three new stack-argument exports in the build cpu_aot_stack_arguments compares call_fill, call_edge and call_twelfth, but the CMake translation step still named only the first five exports, so the lifted DLL did not export them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014uAfgrqe3XyeqvkJrdnUK6 --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index dd46649185..e25642b452 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3439,7 +3439,7 @@ if(EXISTS "${INTAKE_PYTHON}") "$" "$") cpu_asm_fixture(cpu_stack_args stack_args) # The exports from unset_slot on exist only to be refused; the test translates each alone. - cpu_translation(cpu_stack_args cpu_switch_aot call_six,call_seven,call_scratch,call_rec,call_eight) + cpu_translation(cpu_stack_args cpu_switch_aot call_six,call_seven,call_scratch,call_rec,call_eight,call_fill,call_edge,call_twelfth) add_test(NAME cpu_aot_stack_arguments COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/stack_args_check.py" "$" "$" "$") From 172c07fae2e22e4806b8b2724a78d12db79875c8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 23:12:51 +0000 Subject: [PATCH 7/7] docs: count the eight stack-argument exports cpu_aot_stack_arguments translates eight exports since call_fill, call_edge and call_twelfth were added; the paragraph still said five. All eight are refused before this change, and call_rec is refused for self-recursion first when the recursion change is absent. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014uAfgrqe3XyeqvkJrdnUK6 --- docs/experiments.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/experiments.md b/docs/experiments.md index 08322651ef..187b68beb6 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -2802,7 +2802,7 @@ A `CALL` may close a call cycle ([#317](https://github.com/R0Y00/Xbox2Windows/is An internal callee may take stack arguments, the fifth to the twelfth: the 8-byte slots from its entry RSP + 0x28, which the Windows x64 calling convention places above the caller's home space. Each access must lie inside one slot. The callee's frame array extends over the slots it accesses, each copied at entry from one more C++ parameter after R9, and the callee records how many low bytes of each slot some read reaches. This counts reads after the callee's own writes too, so it can demand more than it needs, never less. At each call the caller's frame proof must show those bytes written as data at RSP + 0x20 + 8 * slot, below the caller's return address, and the call passes the 8 bytes of each slot from the caller's frame array, or 0 for a slot the callee only writes. After the call those slots are undefined, like the callee's home space, because the callee may write them. A call in a cycle passes the slots of the assumed summary, and the iteration above covers the slot demands too. A tail jump to a function with stack arguments is refused, because the slots would be the ones the caller's own caller wrote. An export still takes no stack arguments, because its host call passes none. -`cpu_aot_stack_arguments` builds [`stack_args.asm`](../tests/cpu/stack_args.asm) and translates five exports. `call_six` calls `six_mix`, a frameless leaf with six arguments whose sixth is read as a doubleword, written as one. `call_seven` calls `seven_fwd`, which reads three stack arguments (8, 8 and 1 bytes) through its own `PUSH` and allocation and passes two of them swapped to `six_mix` as its fifth and sixth. `call_scratch` calls `scratch_five`, which adds to its own fifth-argument slot, twice, writing the slot again before the second call. `call_rec` calls `rec_five`, which passes a new fifth argument to itself up to 31 levels. `call_eight` calls `eight_sum`, with eight arguments, the last a word. `call_fill` writes no stack byte and calls `fill_five`, which only writes its fifth-argument slot, and `call_edge` passes `scratch_five` its slot; in both the slot ends exactly at the caller's return address. `call_twelfth` writes only the twelfth argument, the last supported slot, for `twelfth`. Through the register probe, the original must match a Python reference, and the translation must match the original on the return value, the guarded trace, RBX and RSI over 449 input pairs per export. The test checks the demanded bytes per slot, (8, 4) for `six_mix`, (8, 8, 1) for `seven_fwd`, (8) for `scratch_five` and `rec_five`, (8, 8, 8, 2) for `eight_sum`, (0) for `fill_five` and seven zeros and an 8 for `twelfth`, and that each callee is defined with that many stack parameters. Nine exports must be refused as written: `unset_slot` leaves the sixth argument of `six_mix` unwritten, `narrow_slot` writes only 4 bytes of its 8-byte fifth argument, `reread_slot` reads its slot after `scratch_five` may have changed it, `tail_six` tail-jumps to `six_mix`, `export_fifth` is an export that reads a fifth argument, `far_slot` calls a callee that reads the thirteenth, `straddle_slot` one that reads 8 bytes across the end of its home space, and `high_slots` calls `six_mix` with RSP at entry RSP - 0x28, so its two slots would be its own return address and the slot above it, and `lost_slot` calls `rec_lost`, which calls itself without writing the fifth argument it reads. A frame proof that ignores the slots of calls (the test replaces `prove_frame`) accepts the first three, keeping the first summary of each cycle accepts `lost_slot`, and the test fails unless they are accepted. The direct-call control that patches `mid_step` to read its fifth-argument slot is now refused because that slot holds the RSI that `chain3` pushed. Before this change all five exports were refused with `unsupported stack argument`. Measured on Linux x86-64 with `llvm-ml` 18, `lld-link` and `clang++` at `-O0` and `-O2`, with the original image mapped in-process and called through a Windows x64 register probe: the original matched the reference and kept RBX and RSI, and 7,184 translated calls matched it. The C++ generated for the other `cpu_switch_aot` fixtures, `recursion.asm` included, and for the fuzz programs listed above is unchanged, and so are the clean and planted translations of every fuzz area that `llvm-ml` assembles, at the CMake default seeds; the planted `stale_rsp` fault of `cpu_aot_fuzz_rsp` passes the new `Frame` argument on. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_stack_arguments$' -V`. +`cpu_aot_stack_arguments` builds [`stack_args.asm`](../tests/cpu/stack_args.asm) and translates eight exports. `call_six` calls `six_mix`, a frameless leaf with six arguments whose sixth is read as a doubleword, written as one. `call_seven` calls `seven_fwd`, which reads three stack arguments (8, 8 and 1 bytes) through its own `PUSH` and allocation and passes two of them swapped to `six_mix` as its fifth and sixth. `call_scratch` calls `scratch_five`, which adds to its own fifth-argument slot, twice, writing the slot again before the second call. `call_rec` calls `rec_five`, which passes a new fifth argument to itself up to 31 levels. `call_eight` calls `eight_sum`, with eight arguments, the last a word. `call_fill` writes no stack byte and calls `fill_five`, which only writes its fifth-argument slot, and `call_edge` passes `scratch_five` its slot; in both the slot ends exactly at the caller's return address. `call_twelfth` writes only the twelfth argument, the last supported slot, for `twelfth`. Through the register probe, the original must match a Python reference, and the translation must match the original on the return value, the guarded trace, RBX and RSI over 449 input pairs per export. The test checks the demanded bytes per slot, (8, 4) for `six_mix`, (8, 8, 1) for `seven_fwd`, (8) for `scratch_five` and `rec_five`, (8, 8, 8, 2) for `eight_sum`, (0) for `fill_five` and seven zeros and an 8 for `twelfth`, and that each callee is defined with that many stack parameters. Nine exports must be refused as written: `unset_slot` leaves the sixth argument of `six_mix` unwritten, `narrow_slot` writes only 4 bytes of its 8-byte fifth argument, `reread_slot` reads its slot after `scratch_five` may have changed it, `tail_six` tail-jumps to `six_mix`, `export_fifth` is an export that reads a fifth argument, `far_slot` calls a callee that reads the thirteenth, `straddle_slot` one that reads 8 bytes across the end of its home space, and `high_slots` calls `six_mix` with RSP at entry RSP - 0x28, so its two slots would be its own return address and the slot above it, and `lost_slot` calls `rec_lost`, which calls itself without writing the fifth argument it reads. A frame proof that ignores the slots of calls (the test replaces `prove_frame`) accepts the first three, keeping the first summary of each cycle accepts `lost_slot`, and the test fails unless they are accepted. The direct-call control that patches `mid_step` to read its fifth-argument slot is now refused because that slot holds the RSI that `chain3` pushed. Before this change all eight exports were refused with `unsupported stack argument`; on a translator without the recursion change, `call_rec` is refused first with `self-recursion`. Measured on Linux x86-64 with `llvm-ml` 18, `lld-link` and `clang++` at `-O0` and `-O2`, with the original image mapped in-process and called through a Windows x64 register probe: the original matched the reference and kept RBX and RSI, and 7,184 translated calls matched it. The C++ generated for the other `cpu_switch_aot` fixtures, `recursion.asm` included, and for the fuzz programs listed above is unchanged, and so are the clean and planted translations of every fuzz area that `llvm-ml` assembles, at the CMake default seeds; the planted `stale_rsp` fault of `cpu_aot_fuzz_rsp` passes the new `Frame` argument on. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_stack_arguments$' -V`. `cpu_aot_call_entries` builds [`call_entries.asm`](../tests/cpu/call_entries.asm), whose `.pdata` and `.xdata` are written explicitly so the image has a primary function continued by a chained secondary range. It also exports an interior label of a primary function, a `.data` variable as `DATA` and a forwarder to `kernel32.GetTickCount`. The test reads the image's own records and checks that the translator's entries are exactly the four primary runtime functions. A framed `CALL` and a tail `JMP` to the primary leaf translate and match the original and a Python reference over 249 input pairs each. Eight retargeted copies must be rejected with the reason that names the distinction: the call retargeted to the exported interior label, the chained range's start, the data export and the forwarder; the tail jump retargeted to the interior label and the chained start; and the leaf's unwind header patched from version 1 to version 3, for both the call and the tail jump. The translator before this rule refused the first six later and for unrelated reasons (`no unique function interval`, `not in an executable section`, `edge outside owned ranges`), and accepted the last two. Removing the version check, or accepting an export at the start of an unverified record, accepts the version controls. Counting interior exports or chained ranges as entries, or classifying forwarders and data exports as code, fails the check of the entry table. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_call_entries$' -V`.