#!/usr/bin/env python3 """Linked own Mach-O data/BSS entry versus original ARM and native dispatch. Uses an unchanged Apple-linker executable with LC_MAIN, dyld and libSystem requirements retained. Its chained-fixup payload has no imports or chains. This is an explicitly supplied entry ABI, not macOS process launch. """ import argparse import hashlib import json from pathlib import Path import platform import struct import subprocess import tempfile from capstone import Cs, CS_ARCH_ARM64, CS_MODE_ARM from unicorn import Uc, UC_ARCH_ARM64, UC_MODE_ARM, UC_HOOK_CODE from unicorn import arm64_const as arm from differential import capture_arm, initialize_arm, state_dict as complete_state from differential import ROOT, ARM_REGISTERS, MASK, State, states from evidence import write_evidence STOP = 0xffff0000 SEED = 0x9e3779b97f4a7c15 PAGE = 16384 STACK_BASE = 0x70000000000 STACK_BYTES = 65536 STACK_TOP = STACK_BASE + STACK_BYTES LC_SEGMENT_64 = 0x19 LC_SYMTAB = 2 LC_UNIXTHREAD = 5 LC_MAIN = 0x80000028 FIXTURE = ROOT / 'tests/fixtures/mapped-image-arm64.S' def require(condition, detail): if not condition: raise AssertionError(detail) def digest(data): return hashlib.sha256(data).hexdigest() def snapshot(state): return complete_state(state) def commands(data): require(len(data) >= 32 and data[:4] == bytes.fromhex('cffaedfe'), 'expected thin 64-bit little-endian Mach-O') _, cpu, subtype, kind, count, size, flags, reserved = struct.unpack_from('<8I', data) require(cpu == 0x100000c and subtype == 0 and kind == 2 and not reserved, 'unexpected linked fixture architecture/type') end = 32 + size require(end <= len(data), 'truncated load commands') offset, result = 32, [] for _ in range(count): require(offset + 8 <= end, 'missing load-command header') command, length = struct.unpack_from('= 8 and length % 8 == 0 and offset + length <= end, 'bad load-command length') result.append((offset, command, bytes(data[offset:offset + length]))) offset += length require(offset == end, 'load-command size mismatch') return result def layout(data): segments, symbols, sections, entry = [], {}, {}, None table = None for offset, command, body in commands(data): if command == LC_SEGMENT_64: require(len(body) >= 72, 'truncated segment') _, _, name, address, size, fileoff, filesize, maximum, protection, count, flags = struct.unpack_from('= 28, 'truncated chained-fixup header') payload = data[fileoff:fileoff + length] version, starts, imports, strings, count, import_format, symbol_format = struct.unpack_from('<7I', payload) require(version == 0 and count == 0 and import_format == 1 and symbol_format == 0, 'fixture must have no chained imports') require(starts + 4 <= length, 'missing fixup segment table') segment_count = struct.unpack_from('= segment['file_bytes'] and output + 16 <= segment['bytes'], 'observed BSS output must lie in actual segment zero-fill tail') require(not any(memory[8:]), 'initial BSS/padding was not zero') struct.pack_into('= segment['bytes'], 'owned segment extent mismatch') require(region['initial_bytes'] == segment['file_bytes'], 'owned segment file initialization extent mismatch') require((region['readable'], region['writable'], region['executable']) == tuple(bool(segment['protection'] & bit) for bit in (1, 2, 4)), 'mapped guest permissions differ from linked segment') def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--cli', type=Path, default=ROOT / 'target/debug/stela') parser.add_argument('--output', type=Path, default=ROOT / '.stela/mapped-image-differential.json') arguments = parser.parse_args() require(platform.machine() == 'x86_64', 'native execution requires an x86_64 host') arguments.output.parent.mkdir(parents=True, exist_ok=True) cli_hash = digest(arguments.cli.read_bytes()) source_paths = [Path(__file__), FIXTURE, ROOT / 'dev/differential.py', ROOT / 'dev/evidence.py', ROOT / 'src/main.rs', ROOT / 'crates/stela-runtime/Cargo.toml', ROOT / 'Cargo.lock'] source_paths.extend(sorted((ROOT / 'src/macho').rglob('*.rs'))) source_paths.extend(sorted((ROOT / 'crates/stela-runtime/src').rglob('*.rs'))) source_hashes = {str(path.relative_to(ROOT)): digest(path.read_bytes()) for path in source_paths} with tempfile.TemporaryDirectory(prefix='mapped-image-', dir=arguments.output.parent) as temporary: work = Path(temporary) image, info, provenance = build_fixture(work) data = image.read_bytes() memory_segment = next(segment for segment in info['segments'] if segment['name'] == '__DATA') require(memory_segment['bytes'] > memory_segment['file_bytes'], 'fixture requires real segment zero tail') preflight = invoke(arguments.cli, 'plan-executable', image, '--architecture', 'arm64') require(preflight['container_sha256'] == digest(data), 'preflight input hash differs from linked fixture') require(preflight['plan']['entry']['guest_address'] == info['symbols']['_mapped_entry'], 'planned LC_MAIN entry differs from linked entry symbol') require(preflight['plan']['dylinker'] == '/usr/lib/dyld' and any(item['name'] == '/usr/lib/libSystem.B.dylib' for item in preflight['plan']['dependencies']), 'actual dynamic loader/library dependencies must remain recorded') require(preflight['plan']['execution_supported'] is False and preflight['plan']['unresolved_requirements'], 'entry fixture must not imply complete process loading') rows = [] for index, initial in enumerate(states(all_flags=True)): initial.sp = STACK_TOP initial.reserved = 0xa5c39e71 initial.x[30] = STOP expected, pc, memory, frame, trace = original(data, info, initial) require((expected, pc, memory, frame) == fixture_oracle(data, info, initial), 'original ARM differs from independent fixture oracle') state_path = work / 'state.json' state_path.write_text(json.dumps(snapshot(initial)) + '\n') native = invoke(arguments.cli, 'run-mapped-image', image, '--architecture', 'arm64', '--state', state_path, '--stop-pc', hex(STOP), '--block-budget', '8', '--cache-dir', work / 'cache', '--read-memory', f"{memory_segment['address']:#x}:{memory_segment['bytes']}", '--read-memory', f'{STACK_TOP - 16:#x}:16') require(native['complete_binary_verified'] is False, 'invalid complete-binary claim') require(native['initial_state'] == snapshot(initial), 'actual mapped entry state differs from supplied ABI') validate_regions(native, info) require(native['state'] == expected and native['pc'] == pc, f'state/PC mismatch in case {index}') require(native['outcome']['reason'] == {'kind': 'stop_address'}, 'native fixture did not stop at supplied return') require(native['outcome']['blocks_executed'] == 3 and native['outcome']['last_exit'] == [STOP, 4], 'native call/return dispatch was not exercised') require(native['outcome']['compiled_blocks'] == (3 if index == 0 else 0), 'unexpected cold/warm translation count') require(native['outcome']['disk_cache_hits'] == (0 if index == 0 else 3), 'unexpected cold/warm disk-cache count') require(native['plan'] == preflight['plan'], 'load plan changed between preflight and execution') require(native['memory'] == [{'address': memory_segment['address'], 'bytes_hex': memory.hex()}, {'address': STACK_TOP - 16, 'bytes_hex': frame.hex()}], 'complete mapped data/BSS or guest-stack frame snapshot differs') rows.append({'initial': snapshot(initial), 'original_state': expected, 'original_pc': pc, 'original_trace': trace, 'original_data_sha256': digest(memory), 'original_stack_frame_hex': frame.hex(), 'native': native}) require(cli_hash == digest(arguments.cli.read_bytes()), 'CLI changed during mapped-image probes') require(source_hashes == {str(path.relative_to(ROOT)): digest(path.read_bytes()) for path in source_paths}, 'harness/runtime source changed during mapped-image probes') report = {'kind': 'own_mapped_macho_entry_differential', 'schema_version': 1, 'passed': True, 'complete_binary_verified': False, 'complete_binaries_verified': 0, 'compiler_source_sha256': rows[0]['native']['compiler_source_sha256'], 'cli_sha256': cli_hash, 'harness_source_sha256': digest(Path(__file__).read_bytes()), 'source_sha256': source_hashes, 'fixture': provenance, 'layout': info, 'preflight': preflight, 'full_state_comparisons': len(rows), 'mapped_data_bytes_per_comparison': memory_segment['bytes'], 'stack_frame_bytes_per_comparison': 16, 'comparisons': rows, 'tested_state': ['x0..x30', 'sp', 'nzcv', 'reserved', 'actual RET PC', 'complete __DATA mapping including BSS and zero-fill tail', 'owned guest-stack FP/LR frame and restored SP/X29/LR'], 'limits': 'Own unchanged Apple-linker fixture with explicitly supplied entry ABI and unresolved dyld/libSystem dependencies. No full macOS process loading, dyld, imports, fixups, signatures, PAC, syscalls or macOS boot. Original/reference execution is Unicorn; native execution uses Stela mapped-image dispatcher.'} archive = write_evidence(arguments.output, report) print(json.dumps({'passed': True, 'full_state_comparisons': len(rows), 'data_bytes_per_comparison': memory_segment['bytes'], 'complete_binaries_verified': 0, 'report': str(arguments.output), 'snapshot': str(archive)}, indent=2)) if __name__ == '__main__': main()