#!/usr/bin/env python3 """Execute original Stela ARM tasks on the freestanding x86 QEMU debug machine. Host page-fault retry and PIT delivery are exercised inside actual translated code. This does not implement ARM EL1 exception delivery or an ARM MMU. """ import argparse import hashlib import json import os import re from pathlib import Path import shutil import socket import struct import subprocess import time import vm from evidence import write_evidence ROOT = Path(__file__).resolve().parents[1] GUEST_BASE = 0x100000 STATE_BYTES = 784 STATE_A = 0x6000 STATE_B = 0x6400 TASK_DATA = (0x8000, 0x8010) TIMER_TICKS = 0x8040 TRACE = 0x9000 FAULT_STATE = 0xB000 FAULT_RAM = 0xB400 FAULT_ADDRESS = 0x200000 NATIVE_BASE = 0x10000 MINIMUM_NATIVE_IRQS = 4 INITIAL_X3 = 0xDEADBEEF PAGE_FAULT_WORD_INDEX = 5 LOOP_WORDS = 12 INITIAL_NZCV = 0xB0000000 NZCV_OFFSET = 256 GPR_COUNT = 32 BLOCK_ABI = "x86_64-sysv-guest-state-v2-block-exit-direct-ram" def sha256(data): return hashlib.sha256(data).hexdigest() def task_words(): """Named A64 encodings for an original two-task polling/fault fixture.""" mov_register = 0xAA0003E0 ldr_unsigned_x = 0xF9400000 str_unsigned_x = 0xF9000000 add_immediate_x = 0x91000000 movz_x = 0xD2800000 cmp_immediate_x = 0xF100001F branch_condition = 0x54000000 condition_carry_clear = 3 brk = 0xD4200000 branch_word_index = LOOP_WORDS - 1 backward_word_offset = (-branch_word_index) & ((1 << 19) - 1) return [ mov_register | (5 << 16), # MOV X0,X5 ldr_unsigned_x | 1, # LDR X1,[X0] add_immediate_x | (1 << 10) | (1 << 5) | 1, # ADD X1,X1,#1 str_unsigned_x | 1, # STR X1,[X0] movz_x | (1 << 21) | (0x20 << 5) | 2, # MOV X2,#0x200000 ldr_unsigned_x | (2 << 5) | 3, # LDR X3,[X2] add_immediate_x | (7 << 10) | (3 << 5) | 3, # ADD X3,X3,#7 str_unsigned_x | (1 << 10) | 3, # STR X3,[X0,#8] movz_x | (TIMER_TICKS << 5) | 4, # MOV X4,#timer ldr_unsigned_x | (4 << 5) | 4, # LDR X4,[X4] cmp_immediate_x | (MINIMUM_NATIVE_IRQS << 10) | (4 << 5), branch_condition | (backward_word_offset << 5) | condition_carry_clear, brk | (0x10 << 5), ] def initial_state(task): registers = [0x0123456700000000 + task * 0x10000 + index for index in range(GPR_COUNT)] registers[3] = INITIAL_X3 registers[5] = TASK_DATA[task] registers[31] = 0x700000 + task * 0x1000 vectors = bytes((index * 13 + task * 7 + 1) & 0xFF for index in range(512)) return struct.pack("<32QII", *registers, INITIAL_NZCV, 0x11223344) + vectors + struct.pack(" ticks: raise RuntimeError("Fault snapshot RAM prefix differs") return {"dispatches": dispatches, "tasks": states, "fault": { "count": faults, "address": address, "error": error, "native_rip": rip, "native_offset": fault_offset, "source_pc": fault_pc, "snapshot_sha256": sha256(fault_state), "destination_before": before_x3, "ticks_at_fault": fault_ram[8], "retry": "unchanged native RIP; #PF handler installs identity page then IRETQ", }, "pit": {"total_interrupts": all_irqs, "translated_interrupts": ticks, "native_rip": irq_rip, "native_offset": irq_offset, "source_pc": irq_pc}} def run(stela, directory, assembly, qmp_port, gdb_port): owned_sources = (Path(__file__), assembly, ROOT / "dev/vm.py", ROOT / "dev/vm/boot.S") source_hashes = {str(path.relative_to(ROOT)): sha256(path.read_bytes()) for path in owned_sources} cli_sha256 = sha256(stela.read_bytes()) source, manifests = compile_tasks(stela, directory) native, symbols = build_payload(directory, assembly) vm.STATE = directory / "vm" vm.QMP_PORT, vm.GDB_PORT = qmp_port, gdb_port args = vm.command(paused=True, native=native) for port in (qmp_port, gdb_port): with socket.socket() as probe: probe.bind(("127.0.0.1", port)) (vm.STATE / "debug.log").write_text("") monitor = None with (directory / "qemu.stderr").open("w") as log: process = subprocess.Popen(args, stdout=log, stderr=log) launch = {"pid": process.pid, "started_unix_ns": time.time_ns(), "command": args} (directory / "launch.json").write_text(json.dumps(launch, indent=2) + "\n") print(json.dumps({"qemu_pid": process.pid, "output_dir": str(directory)}), flush=True) try: deadline = time.monotonic() + 30 while time.monotonic() < deadline: if process.poll() is not None: raise RuntimeError("QEMU exited before monitor connection") try: monitor = vm.Monitor() break except OSError: time.sleep(0.05) if monitor is None: raise RuntimeError("QMP did not start") with socket.create_connection(("127.0.0.1", gdb_port), timeout=5) as debug: debug.sendall(b"$?#3f") reply = b"" while b"#" not in reply: chunk = debug.recv(4096) if not chunk: raise RuntimeError("GDB stub disconnected") reply += chunk if b"$T" not in reply and b"$S" not in reply: raise RuntimeError("GDB stub did not report stopped CPU") debug.sendall(b"+") monitor.execute("cont") while time.monotonic() < deadline: output = (vm.STATE / "debug.log").read_text() if "OK\n" in output or "E" in output: break if process.poll() is not None: raise RuntimeError("QEMU stopped while executing fixture") time.sleep(0.01) monitor.execute("stop") registers = monitor.human("info registers") (directory / "registers.txt").write_text(registers) inspect_memory(monitor, directory) if "OK\n" not in (vm.STATE / "debug.log").read_text(): raise RuntimeError("Translated system fixture did not complete") match = re.search(r"RIP=([0-9a-fA-F]+)", registers) if match is None or not symbols["completed"] <= int(match.group(1), 16) < symbols["completed"] + 3: raise RuntimeError("Stopped native RIP is outside the completion halt loop") observations = verify(monitor, directory, manifests, symbols) if source_hashes != {str(path.relative_to(ROOT)): sha256(path.read_bytes()) for path in owned_sources} or cli_sha256 != sha256(stela.read_bytes()): raise RuntimeError("Sources or frozen compiler changed during execution") report = { "schema_version": 1, "kind": "translated_x86_platform_boundaries", "passed": True, "original_arm_sha256": sha256(source), "original_inspection_sha256": sha256((directory / "original-inspection.json").read_bytes()), "stela_sha256": cli_sha256, "compiler_source_sha256": manifests[0]["compiler_source_sha256"], "native_payload_sha256": sha256(native.read_bytes()), "block_manifests": manifests, "native_inspection_sha256": {name: sha256((directory / f"{name}-native-inspection.json").read_bytes()) for name in ("loop", "trap")}, "boot_image_sha256": sha256((vm.STATE / "boot.img").read_bytes()), "boot_elf_sha256": sha256((vm.STATE / "boot.elf").read_bytes()), "source_sha256": source_hashes, "initial_state_sha256": [sha256(initial_state(task)) for task in (0, 1)], "qemu_sha256": sha256(Path(vm.qemu_binary()).read_bytes()), "symbols": {key: symbols[key] for key in ("_start", "page_fault", "timer_irq", "loop_native", "loop_native_end", "trap_native", "completed")}, "qemu": subprocess.check_output([vm.qemu_binary(), "--version"], text=True).splitlines()[0], "qemu_command": args, "gdb_stub": "initial stopped-state handshake passed", "observations": observations, "limits": ["Host x86 page-fault retry and PIT IRQ; no ARM architectural exception delivery", "Fixed identity direct-RAM profile; no ARM MMU, TLB or device emulation", "Two serialized guest states, not ARM preemptive task scheduling", "AOT block execution only; runtime compilation/cache not linked in freestanding image", "No macOS boot or application acceptance; QEMU TCG timing is not native performance"], } monitor.execute("quit") process.wait(timeout=5) report["process"] = {**launch, "returncode": process.returncode, "finished_unix_ns": time.time_ns()} if process.returncode != 0: raise RuntimeError("QEMU did not exit cleanly after successful observations") write_evidence(directory / "receipt.json", report) return report finally: if monitor: monitor.close() if process.poll() is None: process.terminate() try: process.wait(timeout=5) except subprocess.TimeoutExpired: process.kill() process.wait() launch.update({"returncode": process.returncode, "finished_unix_ns": time.time_ns()}) (directory / "launch.json").write_text(json.dumps(launch, indent=2) + "\n") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--stela", type=Path, required=True, help="Existing frozen Stela compiler executable") parser.add_argument("--output-dir", type=Path, required=True, help="Fresh ignored evidence directory") parser.add_argument("--qmp-port", type=int, default=4447) parser.add_argument("--gdb-port", type=int, default=1237) arguments = parser.parse_args() directory = arguments.output_dir.resolve() ignored_root = (ROOT / ".stela").resolve() if not directory.is_relative_to(ignored_root): parser.error("output directory must be under ignored .stela/") if not all(1 <= port <= 65535 for port in (arguments.qmp_port, arguments.gdb_port)) or arguments.qmp_port == arguments.gdb_port: parser.error("QMP/GDB ports must be distinct and in 1..65535") directory.mkdir(parents=True, exist_ok=False) assembly = ROOT / "dev/vm/x86_64_boot.S" report = run(arguments.stela.resolve(), directory, assembly, arguments.qmp_port, arguments.gdb_port) print(json.dumps({"passed": report["passed"], "receipt": str(directory / "receipt.json"), "observations": report["observations"]}, indent=2)) if __name__ == "__main__": main()