"""Shared full-state adapter for pure integer and crypto SIMD fixtures. The CLI supplies its existing compiler, original snapshot reader, artifact/map checks and MXCSR wrapper explicitly. Family modules own only words, inputs and independent integer models. Historical cohort engines remain unchanged. """ from collections import Counter from contextlib import ExitStack import ctypes import importlib import hashlib import json from pathlib import Path import struct import sys import subprocess import tempfile import time from differential import ROOT, BASE, State, state_dict from evidence import write_evidence from simd_fixtures import FAMILIES import simd_original BATCH_FUNCTIONS = 512 MAXIMUM_RUNTIME_CASES = 96 CACHE_LOOP_ITERATIONS = 3 BRANCH_NEXT_INSTRUCTION = 0x14000001 MAXIMUM_MIXED_OPERATIONS = 8 ORIGINAL_INPUT_HEADER = 8 ORIGINAL_INPUT_STRIDE = 800 ORIGINAL_RECORD_BYTES = 1024 ORIGINAL_STATE_BYTES = 784 RETURN_REGISTER = 30 UNDEFINED_INSTRUCTION_ESR = 0x02000000 VECTOR_REGISTER_BITS = 5 VECTOR_LEFT_SHIFT = 5 VECTOR_LEFT_MASK = ((1 << VECTOR_REGISTER_BITS) - 1) << VECTOR_LEFT_SHIFT def family_module(focus): if focus not in FAMILIES: raise ValueError('Unknown SIMD fixture family') return importlib.import_module('simd_fixtures.' + focus) def fixture_corpus(family): operations, cases = family.corpus() if operations != family.functions() or not operations or not cases: raise AssertionError('Fixture functions/corpus disagree or are empty') if len({op['word'] for op in operations}) != len(operations): raise AssertionError('Each original word needs one fixture function') if {op['canonical_id'] for op in operations} != set(family.CANONICAL_FORMS): raise AssertionError('Fixture canonical form inventory differs') operations = [dict(op) if op.get('output_kind') == 'gpr' else dict(op, merge=op.get('merge', 'none')) for op in operations] records = [] for index, case in enumerate(cases): initial = case['initial'] if len(initial) != ORIGINAL_STATE_BYTES or not 0 <= case['function'] < len(operations): raise AssertionError('Fixture input/state framing differs') records.append({**case, 'case': index, 'function_index': case['function']}) runtime = [case for case in records if case.get('runtime')] if not 0 < len(runtime) <= MAXIMUM_RUNTIME_CASES: raise AssertionError('Fixture runtime selection exceeds its bounded budget') if {operations[case['function']]['canonical_id'] for case in runtime} != set(family.CANONICAL_FORMS): raise AssertionError('Runtime selection omits a canonical form') return operations, records def dependencies(engine, family): paths = [Path(engine.__file__), Path(__file__), Path(family.__file__), Path(family.__file__).parent / '__init__.py', Path(simd_original.__file__), ROOT / 'dev/differential.py', ROOT / 'dev/evidence.py'] guards = Path(__file__).parent / 'test_simd_fixtures.py' if guards.exists(): paths.append(guards) return {str(path.relative_to(ROOT)): engine.digest(path.read_bytes()) for path in paths} def oracle_path(focus): return ROOT / '.stela/research/integer-crypto-harness' / focus / 'oracle/receipt.json' def prepare_original(engine, family, directory): """Freeze input/source bindings for the separately invoked shared observer.""" operations, records = fixture_corpus(family) directory = Path(directory) directory.mkdir(parents=True, exist_ok=True) sources = dependencies(engine, family) binding_path = directory / 'source-bindings.json' data = (json.dumps(sources, indent=2) + '\n').encode() if binding_path.exists() and binding_path.read_bytes() != data: raise AssertionError('Frozen original source bindings changed') if not binding_path.exists(): binding_path.write_bytes(data) plan = engine.prepare_full_frame_numerical_oracle(directory, operations, records, family.FOCUS) return {**plan, 'observer_sha256': engine.digest(Path(simd_original.__file__).read_bytes()), 'fixture_sources_sha256':sources, 'capture_command':[sys.executable, str(Path(simd_original.__file__)), '--directory', str(directory), '--focus', family.FOCUS, '--source-bindings', str(binding_path), '--capture']} def expected_state(family, operation, initial): expected = family.expected(operation, State.from_buffer_copy(initial)) if not isinstance(expected, State): raise AssertionError('Fixture model must return a complete State') untouched = State.from_buffer_copy(expected) if operation.get('output_kind', 'vector') == 'gpr': written = operation.get('written_gprs') if (not isinstance(written, list) or any(type(index) is not int or not 0 <= index < RETURN_REGISTER + 1 for index in written) or len(written) != len(set(written)) or type(operation.get('writes_sp')) is not bool or type(operation.get('writes_nzcv')) is not bool): raise AssertionError('Invalid register fixture destination metadata') if hasattr(family, 'validate_effects'): family.validate_effects(operation) for index in written: untouched.x[index] = initial.x[index] if operation['writes_sp']: untouched.sp = initial.sp if operation['writes_nzcv']: untouched.nzcv = initial.nzcv else: untouched.v[operation['d']][:] = initial.v[operation['d']] if bytes(untouched) != bytes(initial): raise AssertionError('Integer crypto model changed fields outside its destination') return expected def load_original(engine, family, pointer_path): pointer, pointer_sha = engine.numerical_json(pointer_path) producer, receipt_sha = engine.numerical_json(ROOT / pointer['receipt']['path'], pointer['receipt']['sha256']) operations, cases = fixture_corpus(family) if (not producer.get('passed_transport_and_architectural_frame_checks') or producer['cases'] != len(cases) or pointer['directory'] != producer['directory']): raise AssertionError('Passing complete original capture required') directory = ROOT / producer['directory'] for name, identity in producer['files'].items(): if Path(name).name != name: raise AssertionError('Original evidence name escapes capture directory') data = (directory / name).read_bytes() if engine.digest(data) != identity['sha256'] or len(data) != identity['bytes']: raise AssertionError('Original capture file changed: ' + name) functions = json.loads((directory / 'functions.json').read_bytes()) expected_functions = [{**op, 'source_hex':struct.pack('> 26 != engine.FP_REGISTER_EC_SVC or current_el != 4 or cpacr != engine.VECTOR_NUMERICAL_CPACR_FPEN or marker != engine.VECTOR_NUMERICAL_ORIGINAL_MARKER or engine.fp_register_elf_word(elf, subject_pc) != op['word'] or engine.fp_register_elf_word(elf, subject_pc + 4) != engine.FP_REGISTER_SVC or fpcr != initial.fpcr & engine.FP_REGISTER_QEMU_MASKS['fpcr'] or fpsr != initial.fpsr & engine.FP_REGISTER_QEMU_MASKS['fpsr']): raise AssertionError('Original subject/access/control evidence differs') mathematical = expected_state(family, op, initial) observed_controls = State.from_buffer_copy(initial if undefined else mathematical) observed_controls.fpcr, observed_controls.fpsr = fpcr, fpsr if bytes(original) != bytes(observed_controls): raise AssertionError(json.dumps({'case':index, 'operation':op, 'primary':state_dict(original), 'expected_observed_controls':state_dict(observed_controls), 'initial':state_dict(initial)})) if undefined: undefined_cases.append(index) policy = (fpcr, fpsr) != (initial.fpcr, initial.fpsr) if op.get('output_kind', 'vector') != 'gpr': initial.x[RETURN_REGISTER] = original.x[RETURN_REGISTER] = mathematical.x[RETURN_REGISTER] = engine.STOP records.append({**case, 'initial':bytes(initial), 'expected':bytes(mathematical), 'primary_expected':bytes(original), 'operation':op, 'equality_basis':('soft_fixed_execute_as_policy' if undefined else 'requested_storage_policy' if policy else 'direct_original')}) readbacks[(case['initial'][-8:].hex(), fpcr, fpsr)] += 1 if undefined_cases != [row['case_index'] for row in producer.get('tag_soft_fixed_undefined_cases', [])]: raise AssertionError('Original soft-fixed UNDEF observations differ from producer receipt') return {'functions':operations, 'records':records, 'producer':producer, 'receipt_sha256':receipt_sha, 'pointer_sha256':pointer_sha, 'control_readbacks':[{'requested_storage_hex':requested, 'fpcr':fpcr, 'fpsr':fpsr, 'cases':count} for (requested, fpcr, fpsr), count in sorted(readbacks.items())]} def execute_batches(engine, batches): family = family_module(batches[0]['cohort']) oracle = load_original(engine, family, batches[0]['oracle_path']) counts, digest = Counter(), hashlib.sha256() examples = {} with ExitStack() as mappings: functions = {} for batch in batches: address = mappings.enter_context(engine.executable(batch['native'])) for local, offset in enumerate(batch['offsets']): functions[batch['function_base'] + local] = address + offset address = mappings.enter_context(engine.executable(engine.NUMERICAL_MXCSR_WRAPPER)) wrapper = ctypes.CFUNCTYPE(None, ctypes.POINTER(State), ctypes.c_void_p, ctypes.c_uint32, ctypes.POINTER(engine.NumericalNativeExit))(address) guard = ctypes.create_string_buffer(engine.NUMERICAL_GUARD_BYTES * 2 + ctypes.sizeof(State)) state_address = ctypes.addressof(guard) + engine.NUMERICAL_GUARD_BYTES state_pointer = ctypes.cast(state_address, ctypes.POINTER(State)) def invoke(record, mxcsr): ctypes.memmove(guard, engine.NUMERICAL_GUARD + record['initial'] + engine.NUMERICAL_GUARD, len(guard)) observed = engine.NumericalNativeExit() wrapper(state_pointer, functions[record['function']], mxcsr, ctypes.byref(observed)) # Leaf functions return void: BlockExit scratch is deliberately not interpreted. if observed.mxcsr_before != mxcsr or observed.mxcsr_after != mxcsr: raise AssertionError('Integer crypto changed caller MXCSR') if guard.raw[:engine.NUMERICAL_GUARD_BYTES] != engine.NUMERICAL_GUARD or guard.raw[-engine.NUMERICAL_GUARD_BYTES:] != engine.NUMERICAL_GUARD: raise AssertionError('Integer crypto changed owned RAM canaries') actual = ctypes.string_at(state_address, ctypes.sizeof(State)) if actual != record['expected']: raise AssertionError(json.dumps({'case':record['case'], 'operation':record['operation'], 'actual':state_dict(State.from_buffer_copy(actual)), 'expected':state_dict(State.from_buffer_copy(record['expected']))})) for record in oracle['records']: invoke(record, engine.NUMERICAL_MXCSR_ALL_MASKS) counts[record['equality_basis']] += 1 digest.update(struct.pack('