#!/usr/bin/env python3 """Exhaust logical-immediate masks and compare emitted x86 with original ARM.""" import hashlib import json import multiprocessing from pathlib import Path import struct import subprocess import tempfile import time from capstone import Cs, CS_ARCH_ARM64, CS_MODE_ARM from unicorn import Uc, UcError, UC_ARCH_ARM64, UC_MODE_ARM, UC_ERR_EXCEPTION from unicorn import arm64_const as arm from differential import initialize_arm, capture_arm, state_dict, compiler_cli, ARM_REGISTERS, BASE, MASK, ROOT, State, native, reference, states from evidence import write_evidence RET = 0xd65f03c0 def encoding(width, opcode, n, rotation, size, destination, source): return ((width << 31) | (opcode << 29) | 0x12000000 | (n << 22) | (rotation << 16) | (size << 10) | (source << 5) | destination) def masks(width): """Independently enumerate valid encodings by constructing each bit.""" bits = 32 << width result = {} for element in (2, 4, 8, 16, 32, 64): if element > bits: continue for ones in range(1, element): for rotation in range(64): mask = sum(1 << bit for bit in range(bits) if (bit + rotation) % element < ones) key = (int(element == 64), rotation, ((-2 * element) | (ones - 1)) & 63) if key in result: raise AssertionError("Duplicate independent encoding") result[key] = mask return result def cases(): result = [] decoder = Cs(CS_ARCH_ARM64, CS_MODE_ARM) for width in (0, 1): entries = sorted(masks(width)) for opcode in range(4): # Every result survives in its own register. Source x29 is unchanged; # batches include aliases of rotations with ignored high bits. for offset in range(0, len(entries), 28): batch = entries[offset:offset + 28] words = [encoding(width, opcode, *key, destination, 29) for destination, key in enumerate(batch)] for word in words: decoded = next(decoder.disasm(struct.pack('= deadline: raise AssertionError(f'Logical-immediate worker failed/timed out: {process.exitcode}') result = receive.recv() process.join(timeout=2) if process.exitcode != 0 or 'error' in result: raise AssertionError(f'Logical-immediate suite failed: {result}, exit={process.exitcode}') return result finally: if process.is_alive(): process.kill() process.join() receive.close() def undefined_cases(): for width in (0, 1): # N=1/W32, reserved all-one elements, and invalid 0/1-bit # selectors, including extreme/high ignored rotation bits. for n, size in ((1, 0), (1, 62), (1, 63), (0, 31), (0, 47), (0, 55), (0, 59), (0, 61), (0, 62), (0, 63)): for rotation in (0, 1, 31, 63): if (n, rotation, size) not in masks_by_width[width]: for opcode in range(4): yield encoding(width, opcode, n, rotation, size, 0, 0) def verify_undefined(cli, directory): count = 0 for word in undefined_cases(): source = struct.pack('