#!/usr/bin/env python3 """Run pinned Rosetta code generation and compare its output on our own x86 fixtures. The Apple compiler runs only inside ARM Unicorn with explicit host-call models. Generated runtime helpers are mapped to traps, never successful substitutes. Only reviewed register-only SysV fixtures execute as native host x86 code. """ import ctypes from collections import Counter import hashlib import json import multiprocessing from pathlib import Path import random import struct import subprocess import tempfile from capstone import Cs, CS_ARCH_X86, CS_ARCH_ARM64, CS_MODE_64, CS_MODE_ARM, CS_OP_MEM, CS_OP_IMM from unicorn import Uc, UC_ARCH_ARM64, UC_ARCH_X86, UC_MODE_ARM, UC_MODE_64, UC_HOOK_CODE, UC_PROT_READ, UC_PROT_WRITE, UC_PROT_EXEC from unicorn import arm64_const as arm, x86_const as intel from differential import ROOT, executable from evidence import write_evidence from rosetta_execution import Harness, P, PINNED_SHA256 ARM_CODE = 0x60000000 RUNTIME = 0x60010000 ARM_STOP = 0x61000000 X86_CODE = 0x100000000 X86_STOP = 0x40000000 RAM = 0x80000000 RAM_SIZE = 0x10000 GPRS = ("RAX", "RCX", "RDX", "RBX", "RSP", "RBP", "RSI", "RDI", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15") X86_REGS = [getattr(intel, "UC_X86_REG_" + name) for name in GPRS] ARM_REGS = [getattr(arm, "UC_ARM64_REG_X" + str(index)) for index in range(16)] CODEGEN_CONTEXT = { "schema_version": 1, "library_sha256": PINNED_SHA256, "code_base": ARM_CODE, "runtime_base": RUNTIME, "runtime_offset_stride": 16, "guest_image_base": X86_CODE, "ir_flags": 0, "entry_offsets": [0], "data_in_code_entries": [], "invocation_profile": "synthetic-register-only-leaf-v1", } def artifact_identity(source): identity = dict(CODEGEN_CONTEXT, source_sha256=hashlib.sha256(source).hexdigest()) key = hashlib.sha256(json.dumps(identity, sort_keys=True, separators=(",", ":")).encode()).hexdigest() return key, identity def requires_reserved_nzcv_bits(generated): """Recognize the observed adjacent MRS/UBFX Apple flag-assist sequence.""" decoder = Cs(CS_ARCH_ARM64, CS_MODE_ARM) decoder.detail = True instructions = list(decoder.disasm(generated, ARM_CODE)) for first, second in zip(instructions, instructions[1:]): if first.mnemonic != "mrs" or not first.op_str.endswith(", nzcv") or second.mnemonic != "ubfx": continue operands = second.operands if len(operands) != 4 or operands[2].imm not in (26, 27) or operands[3].imm != 1: continue # MRS writes Xn; UBFX can consume its Wn view. written = first.reg_name(first.operands[0].reg).lstrip("xw") consumed = second.reg_name(operands[1].reg).lstrip("xw") if written == consumed: return True return False def reviewed_source(code): decoder = Cs(CS_ARCH_X86, CS_MODE_64) decoder.detail = True instructions = list(decoder.disasm(code, 0)) if not instructions or sum(i.size for i in instructions) != len(code) or instructions[-1].mnemonic != "ret": raise ValueError("Expected complete fixture ending in RET") allowed = {"mov", "movabs", "xor", "add", "adc", "shl", "inc", "test", "cmp", "je", "jb", "setb", "setl", "seto", "setp", "ret"} callee_saved = {"rbx", "ebx", "bx", "bl", "bh", "rsp", "esp", "sp", "spl", "rbp", "ebp", "bp", "bpl"} callee_saved.update(f"r{index}{suffix}" for index in range(12, 16) for suffix in ("", "d", "w", "b")) addresses = {i.address for i in instructions} for instruction in instructions: if instruction.mnemonic not in allowed or any(op.type == CS_OP_MEM for op in instruction.operands): raise ValueError("Unreviewed fixture instruction") if instruction.mnemonic == "ret": if instruction.operands: raise ValueError("Only plain RET is allowed") continue _, written = instruction.regs_access() if any(instruction.reg_name(reg) in callee_saved for reg in written): raise ValueError("Fixture violates native SysV callee-save/stack rules") if instruction.mnemonic.startswith("j"): if len(instruction.operands) != 1 or instruction.operands[0].type != CS_OP_IMM or instruction.operands[0].imm not in addresses: raise ValueError("Fixture branch leaves reviewed source") return instructions def native_worker(pipe, code, arguments): try: with executable(code) as address: function = ctypes.CFUNCTYPE(ctypes.c_uint64, ctypes.c_uint64, ctypes.c_uint64)(address) pipe.send([function(first, second) for first, second in arguments]) except BaseException as error: pipe.send({"error": repr(error)}) finally: pipe.close() def native_results(code, arguments): reviewed_source(code) context = multiprocessing.get_context("spawn") receive, send = context.Pipe(duplex=False) process = context.Process(target=native_worker, args=(send, code, arguments)) process.start() send.close() try: if not receive.poll(10): raise AssertionError("Native source fixture timed out") results = receive.recv() process.join(timeout=2) if process.exitcode != 0 or isinstance(results, dict): raise AssertionError(f"Native fixture failed: {results}, exit={process.exitcode}") return results finally: if process.is_alive(): process.kill() process.join() receive.close() def execute(source, generated, registers): memory = bytearray(RAM_SIZE) struct.pack_into("