"""Independent encoding/coverage and SIMD byte-oracle regression checks.""" import ctypes from contextlib import nullcontext import importlib import json from pathlib import Path import struct import tempfile import unittest from unittest.mock import Mock, patch from capstone import Cs, CS_ARCH_ARM64, CS_MODE_ARM from differential import State, state_dict, seed_extended_state suite = importlib.import_module('simd-differential') class SimdDifferentialTests(unittest.TestCase): def test_complex_encodings_cover_all_forms_widths_rotations_indices_and_aliases(self): functions = suite.complex_functions() facts = {row['id']: row for row in json.loads((suite.ROOT / 'tests/isa/a64-documented-checklist.json').read_bytes())['forms']} self.assertEqual((len(functions), len({op['word'] for op in functions})), (372, 372)) self.assertEqual(len({op['canonical_id'] for op in functions}), 3) self.assertEqual(len({suite.complex_shape(op) for op in functions}), 13) self.assertEqual(len({(suite.complex_shape(op), op['rotation'], op['index']) for op in functions}), 62) decoder = Cs(CS_ARCH_ARM64, CS_MODE_ARM) for op in functions: fact = facts[op['canonical_id']] self.assertEqual(op['word'] & int(fact['encoding_mask'], 0), int(fact['encoding_value'], 0)) self.assertEqual([i.mnemonic for i in decoder.disasm(struct.pack('> 32) & 0xffff, 0x7c05) self.assertEqual(triples['cancel_negative'], (0xbf800000, 0x3c01, 0x3bfe)) def test_widening_mnemonics_reach_mocked_compiler_for_every_layout(self): with tempfile.TemporaryDirectory() as temporary: with patch.object(suite.subprocess, 'check_output', side_effect=RuntimeError('reached mocked compiler')) as compile_call: for index, op in enumerate(suite.widening_functions()): with self.assertRaisesRegex(RuntimeError, 'reached mocked compiler'): suite.compile_batch(Path('mock-stela'), Path(temporary), [{'operations': [op]}], index, block=True) self.assertEqual(compile_call.call_count, 496) def test_widening_optional_fma_still_requires_exact_opcode_and_capability(self): family = suite.FULL_FRAME_NUMERICAL_COHORTS[suite.WIDENING_NUMERICAL_FOCUS] for name, mnemonic in (('fmlal', 'vfmadd132ps'), ('fmlsl2', 'vfnmadd132ps')): op = suite.widening_operation(name, 16) for target in ('x86_64-baseline', 'x86_64-baseline+f16c'): self.assertTrue(suite.numerical_fma_accounting_matches(op, target, {}, family)) self.assertFalse(suite.numerical_fma_accounting_matches(op, target, {mnemonic: 1}, family)) for target in ('x86_64-baseline+fma', 'x86_64-baseline+f16c+fma'): self.assertTrue(suite.numerical_fma_accounting_matches(op, target, {}, family)) self.assertTrue(suite.numerical_fma_accounting_matches(op, target, {mnemonic: 1}, family)) self.assertFalse(suite.numerical_fma_accounting_matches(op, target, {mnemonic: 2}, family)) self.assertFalse(suite.numerical_fma_accounting_matches(op, target, {'vfmadd213ps': 1}, family)) old = suite.FULL_FRAME_NUMERICAL_COHORTS[suite.FUSED_NUMERICAL_FOCUS] op = suite.fused_numerical_operation('fmadd', 4, 4, True, 0, 1, 2, 3) self.assertFalse(suite.numerical_fma_accounting_matches(op, 'x86_64-baseline+fma', {}, old)) self.assertNotIn('accepts_enabled_control', family) self.assertNotIn('profile_expectation', family) def test_widening_cache_helper_is_a_quiet_nan_fixed_point(self): functions, cases = suite.widening_corpus() records = [dict(case, operation=functions[case['function']]) for case in cases] helpers = suite.widening_helpers(records) self.assertEqual(len(helpers), 16) for record in helpers: op = record['operation'] initial = State.from_buffer_copy(record['initial']) self.assertEqual(record['label'], 'directed_addend_qnan_positive') self.assertEqual((op['d'], op['n'], op['m']), (0, 1, 2)) self.assertEqual((initial.fpcr, initial.fpsr), (0, 0)) accumulator = struct.unpack('<4I', struct.pack('<2Q', *initial.v[op['d']])) self.assertEqual(accumulator[:op['source_lane_count']], (0x7fc00003,) * op['source_lane_count']) for register in (op['n'], op['m']): source = struct.unpack('<8H', struct.pack('<2Q', *initial.v[register])) positions = [op['index']] if register == op['m'] and op['index'] is not None else range(op['source_lane_offset'], op['source_lane_offset'] + op['source_lane_count']) self.assertTrue(all(source[position] == 0x3c00 for position in positions)) # A sole quiet Single NaN plus normal Half multiplicands preserves # its original payload/status forever. The first Q0 commit clears # upper64, and every following commit leaves the full state fixed. self.assertEqual(op['merge'], 'none') if op['bytes'] == 8: self.assertNotEqual(initial.v[op['d']][1], 0) def test_widening_corpus_and_runtime_are_bounded_and_all_enables_refuse(self): functions, cases = suite.widening_corpus() self.assertEqual(len(cases), 21256) self.assertEqual({case['function'] for case in cases}, set(range(496))) imported = [dict(case, operation=functions[case['function']]) for case in cases] self.assertEqual(sum(bool(State.from_buffer_copy(case['initial']).fpcr & suite.NUMERICAL_TRAP_ENABLE_MASK) for case in cases), 168) self.assertEqual(len(suite.widening_runtime_cases(imported)), 216) self.assertEqual(len(suite.widening_helpers(imported)), 16) self.assertEqual(suite.widening_helpers(imported, set()), []) self.assertLessEqual(len(suite.widening_runtime_cases(imported)) + 6 * len(suite.widening_helpers(imported)), 425) def test_remaining_binary_forms_reach_compiler_after_independent_decode(self): with tempfile.TemporaryDirectory() as temporary: directory = Path(temporary) with patch.object(suite.subprocess, 'check_output', side_effect=RuntimeError('reached mocked compiler')) as compile_call: for index, op in enumerate(suite.binary_remaining_functions()): with self.assertRaisesRegex(RuntimeError, 'reached mocked compiler'): suite.compile_batch(Path('mock-stela'), directory, [{'operations': [op]}], index, block=True) self.assertEqual(compile_call.call_count, 636) def test_remaining_binary_encodings_cover_every_form_width_index_and_alias(self): facts = {row['id']: row for row in json.loads((suite.ROOT / 'tests/isa/a64-documented-checklist.json').read_bytes())['forms']} decoder = Cs(CS_ARCH_ARM64, CS_MODE_ARM) functions = suite.binary_remaining_functions() self.assertEqual((len(functions), len({op['word'] for op in functions})), (636, 636)) self.assertEqual(len({op['canonical_id'] for op in functions}), 23) self.assertEqual(len({suite.binary_remaining_shape(op) for op in functions}), 43) self.assertEqual(len({(suite.binary_remaining_shape(op), op['index']) for op in functions}), 107) for op in functions: fact = facts[op['canonical_id']] self.assertEqual(op['word'] & int(fact['encoding_mask'], 0), int(fact['encoding_value'], 0)) decoded = list(decoder.disasm(struct.pack('> 32, 0) indexed = suite.binary_remaining_operation('fmul', 4, 8, False, index=3) state = suite.binary_remaining_state(indexed, 2, [(0x3f800000, 0x40000000), (0x40400000, 0x40000000)]) self.assertEqual(state.v[1][0], 0x404000003f800000) self.assertEqual(state.v[2][1] >> 32, 0x40000000) self.assertNotEqual(state.v[2][0] & 0xffffffff, 0x40000000) def test_remaining_binary_scalar_nep_merges_left_but_pair_clears(self): for name, m in (('fnmul', 2), ('fabd', 2), ('faddp', None)): op = suite.binary_remaining_operation(name, 4, 4, True, m=m) initial = suite.binary_remaining_state(op, 0, [(0x3f800000, 0x40000000)], suite.NUMERICAL_NEP) original = State.from_buffer_copy(initial) original.v[0][:] = initial.v[1] if name != 'faddp' else (0, 0) original.v[0][0] = original.v[0][0] & ~0xffffffff | 0x40400000 suite.validate_binary_remaining_original_effects(initial, original, op) original.v[0][1] ^= 1 with self.assertRaises(AssertionError): suite.validate_binary_remaining_original_effects(initial, original, op) descriptor = suite.FULL_FRAME_NUMERICAL_COHORTS[suite.BINARY_REMAINING_FOCUS] self.assertNotIn('accepts_enabled_control', descriptor) self.assertNotIn('profile_expectation', descriptor) self.assertNotIn('native_fma_operations', descriptor) def test_remaining_binary_corpus_and_runtime_stay_within_approved_budget(self): functions, cases = suite.binary_remaining_corpus() self.assertEqual(len(cases), 33518) imported = [dict(case, operation=functions[case['function']]) for case in cases] self.assertEqual(sum(bool(State.from_buffer_copy(case['initial']).fpcr & suite.NUMERICAL_TRAP_ENABLE_MASK) for case in cases), 462) self.assertEqual({case['function'] for case in cases}, set(range(636))) self.assertEqual(len(suite.binary_remaining_runtime_cases(imported)), 363) self.assertEqual(len(suite.binary_remaining_helpers(imported)), 43) self.assertEqual(suite.binary_remaining_helpers(imported, set()), []) self.assertLessEqual(len(suite.binary_remaining_runtime_cases(imported)) + 6 * len(suite.binary_remaining_helpers(imported)), 621) def test_fullframe_fma_expectations_follow_family_and_independent_host_capability(self): families = suite.FULL_FRAME_NUMERICAL_COHORTS fused = families[suite.FUSED_NUMERICAL_FOCUS]['native_fma_operations'] refinement = families[suite.REFINEMENT_NUMERICAL_FOCUS]['native_fma_operations'] self.assertIs(fused, suite.FUSED_NATIVE_OPERATIONS) self.assertEqual(refinement, {'frecps': 'vfnmadd', 'frsqrts': 'vfnmadd'}) single = suite.refinement_operation('frecps', 4, 4, True) double = suite.refinement_operation('frsqrts', 8, 16, False) half = suite.refinement_operation('frecps', 2, 2, True) self.assertEqual(suite.numerical_fma_expectation(single, 'x86_64-baseline+fma', refinement), {'vfnmadd132ss': 1}) self.assertEqual(suite.numerical_fma_expectation(double, 'x86_64-baseline+fma', refinement), {'vfnmadd132pd': 1}) self.assertEqual(suite.numerical_fma_expectation(half, 'x86_64-baseline+fma+f16c', refinement), {}) self.assertEqual(suite.numerical_fma_expectation(single, 'x86_64-baseline+f16c', refinement), {}) self.assertEqual(suite.numerical_fma_expectation(single, 'x86_64-baseline', refinement), {}) estimate = families[suite.ESTIMATE_NUMERICAL_FOCUS].get('native_fma_operations') self.assertIsNone(estimate) self.assertEqual(suite.numerical_fma_expectation(single, 'x86_64-baseline+fma', estimate), {}) def test_estimate_and_refinement_words_match_all_reviewed_forms(self): facts = {row['id']: row for row in json.loads((suite.ROOT / 'tests/isa/a64-documented-checklist.json').read_bytes())['forms']} decoder = Cs(CS_ARCH_ARM64, CS_MODE_ARM) for functions, words, forms, arrangements in ((suite.estimate_functions(), 92, 12, 23), (suite.refinement_functions(), 96, 8, 16)): self.assertEqual((len(functions), len({op['word'] for op in functions})), (words, words)) self.assertEqual(len({op['canonical_id'] for op in functions}), forms) self.assertEqual(len({suite.numerical_unary_shape(op) for op in functions}), arrangements) for op in functions: fact = facts[op['canonical_id']] self.assertEqual(op['word'] & int(fact['encoding_mask'], 0), int(fact['encoding_value'], 0)) decoded = list(decoder.disasm(struct.pack('> 5 & 31), (op['d'], op['n'])) for arguments in ((8, 8, False), (4, 16, True), (2, 4, False), (4, 4, True, 32)): with self.assertRaises(ValueError): suite.sqrt_numerical_operation(*arguments) def test_sqrt_near_midpoint_inputs_straddle_exact_squared_boundaries(self): for lane, fraction, bias in ((2, 10, 15), (4, 23, 127), (8, 52, 1023)): values = dict(suite.sqrt_numerical_values(lane)) self.assertEqual((len(values), len(set(values.values()))), (72, 72)) self.assertEqual(values['four_below_positive'] + 1, values['four_positive']) self.assertEqual(values['four_above_positive'] - 1, values['four_positive']) midpoints = suite.sqrt_numerical_midpoints(lane) roots = (1 << fraction, (1 << fraction) + 1, 3 << (fraction - 1), (1 << (fraction + 1)) - 2) for index, root in enumerate(roots): lower, upper = midpoints[index * 2][1], midpoints[index * 2 + 1][1] self.assertEqual(upper, lower + 1) scaled = [] for raw in (lower, upper): significand = (1 << fraction) | raw & ((1 << fraction) - 1) exponent = (raw >> fraction) - bias scaled.append(significand << (exponent + fraction + 2)) midpoint_squared = (2 * root + 1) ** 2 self.assertLess(scaled[0], midpoint_squared) self.assertGreater(scaled[1], midpoint_squared) def test_sqrt_reuses_unary_old_destination_merge_and_inactive_lane_contract(self): scalar = suite.sqrt_numerical_operation(2, 2, True) initial = suite.numerical_unary_state(scalar, 0, [1], suite.NUMERICAL_NEP) result = State.from_buffer_copy(initial) result.v[0][0] = result.v[0][0] & ~0xffff | 0x0c00 suite.validate_numerical_unary_original_effects(initial, result, scalar) result.v[0][1] = initial.v[1][1] with self.assertRaises(AssertionError): suite.validate_numerical_unary_original_effects(initial, result, scalar) vector = suite.sqrt_numerical_operation(4, 8, False) source = suite.numerical_unary_state(vector, 0, [0x3f800000, 0x40000000]) self.assertEqual(source.v[1][1], 0xff800005ff800005) cleared = State.from_buffer_copy(source) cleared.v[0][:] = [0, 0] suite.validate_numerical_unary_original_effects(source, cleared, vector) cleared.v[0][1] = 1 with self.assertRaises(AssertionError): suite.validate_numerical_unary_original_effects(source, cleared, vector) def test_sqrt_corpus_controls_precise_enables_and_runtime_budget_are_bounded(self): functions, records = suite.sqrt_numerical_corpus() self.assertEqual(len(records), 11123) enables, modes, imported = set(), set(), [] for index, record in enumerate(records): op = functions[record['function']] initial = State.from_buffer_copy(record['initial']) unsupported = bool(initial.fpcr & suite.NUMERICAL_TRAP_ENABLE_MASK) imported.append(dict(record, operation=op, unsupported=unsupported)) if unsupported: enables.add((op['canonical_id'], initial.fpcr)) if record['label'] == 'control_minsubnormal_negative': modes.add((suite.numerical_unary_shape(op), initial.fpcr)) self.assertEqual(record['case'], index) self.assertEqual(record['initial_state_sha256'], suite.digest(record['initial'])) self.assertEqual(len(enables), 35) self.assertEqual(len(modes), 8 * 12 * 4) selected = suite.sqrt_numerical_runtime_cases(imported) self.assertEqual(len(selected), 243) self.assertLessEqual(len(selected) + len(suite.sqrt_numerical_helpers(imported)) * 6, 425) self.assertEqual(suite.sqrt_numerical_helpers(imported, set()), []) self.assertIn('control_minsubnormal_positive', {r['label'] for r in selected}) self.assertIn('control_minsubnormal_negative', {r['label'] for r in selected}) def test_sqrt_descriptor_declares_own_scope_and_unary_refactor_preserves_frint_inputs(self): family = suite.FULL_FRAME_NUMERICAL_COHORTS[suite.SQRT_NUMERICAL_FOCUS] self.assertEqual(family['forms'], 5) self.assertIs(family['loader'], suite.load_sqrt_numerical_oracle) self.assertIn('H/S/D square root', family['limits']) self.assertNotIn('integral rounding', family['limits']) _, records = suite.round_integral_corpus() inputs = b''.join(struct.pack('> 5 & 31), (op['d'], op['n'])) if op['bounded_bits']: self.assertNotEqual(op['lane'], 2) for arguments in (('frint32z', 2, 2, True), ('frintn', 8, 8, False), ('frintx', 4, 16, True), ('frintn', 4, 4, True, 32)): with self.assertRaises(ValueError): suite.round_integral_operation(*arguments) def test_round_integral_exact_values_cover_post_round_range_and_signed_neighbors(self): for lane in (2, 4, 8): values = dict(suite.numerical_unary_values(lane)) self.assertEqual((len(values), len(set(values.values()))), (54, 54)) sign = 1 << (lane * 8 - 1) self.assertEqual(values['zero_negative'], sign) self.assertEqual(values['half_negative'], values['half_positive'] | sign) self.assertEqual(values['half_below_positive'] + 1, values['half_positive']) self.assertEqual(values['half_above_positive'] - 1, values['half_positive']) for name in ('frint32x', 'frint64z'): for lane in (4, 8): op = suite.round_integral_operation(name, lane, lane, True) bounds = dict(suite.round_integral_bound_values(op)) expected = 12 if name.startswith('frint32') and lane == 8 else 6 self.assertEqual(len(bounds), expected) self.assertEqual(bounds['bound_below_positive'] + 1, bounds['bound_exact_positive']) self.assertEqual(bounds['bound_above_positive'] - 1, bounds['bound_exact_positive']) if expected == 12: self.assertIn('bound_half_below_negative', bounds) self.assertIn('bound_half_above_positive', bounds) def test_round_integral_scalar_merges_old_destination_and_vector64_clears_upper(self): op = suite.round_integral_operation('frintx', 4, 4, True) initial = State() initial.fpcr = suite.NUMERICAL_NEP initial.v[0][:] = [0x1234567800000000, 0x1234] initial.v[1][:] = [0xabcdef0000000000, 0xabcd] original = State.from_buffer_copy(initial) original.v[0][0] |= 0x3f800000 suite.validate_numerical_unary_original_effects(initial, original, op) original.v[0][1] = initial.v[1][1] with self.assertRaises(AssertionError): suite.validate_numerical_unary_original_effects(initial, original, op) initial.fpcr = 0 original.v[0][:] = [0x3f800000, 0] suite.validate_numerical_unary_original_effects(initial, original, op) vector = suite.round_integral_operation('frintn', 4, 8, False) original.v[0][1] = 1 with self.assertRaises(AssertionError): suite.validate_numerical_unary_original_effects(initial, original, vector) def test_round_integral_corpus_keeps_controls_enables_sticky_and_mixed_status_scope(self): functions, records = suite.round_integral_corpus() self.assertEqual(len(records), 27281) imported, enable_forms = [], set() for index, record in enumerate(records): op = functions[record['function']] initial = State.from_buffer_copy(record['initial']) unsupported = bool(initial.fpcr & suite.NUMERICAL_TRAP_ENABLE_MASK) imported.append(dict(record, case=index, operation=op, unsupported=unsupported)) if unsupported: enable_forms.add((op['canonical_id'], initial.fpcr)) if record['label'] == 'mixed_3_0' and op['bounded_bits']: raw = struct.pack('<2Q', *initial.v[op['n']]) values = dict(suite.numerical_unary_values(op['lane'])) self.assertEqual(int.from_bytes(raw[:op['lane']], 'little'), values['infinity_positive']) self.assertEqual(int.from_bytes(raw[op['lane']:2 * op['lane']], 'little'), values['half_positive']) self.assertEqual(len(enable_forms), 47 * 7) selected = suite.round_integral_runtime_cases(imported) self.assertEqual(len(selected), 714) self.assertEqual(suite.round_integral_helpers(imported, set()), []) self.assertLessEqual(len(suite.round_integral_helpers(imported)), 26) selected_labels = {record['label'] for record in selected} self.assertIn('ah_round_half_negative', selected_labels) self.assertIn('round_bound_half_below_negative', selected_labels) self.assertIn('value_bound_exact_negative', selected_labels) self.assertEqual({State.from_buffer_copy(r['initial']).fpsr for r in records if r['label'] == 'sticky_status'}, {1, 1 << 4, 1 << 27, suite.FP_REGISTER_MASKS['fpsr']}) def test_fullframe_family_limits_identify_integral_rounding_scope(self): families = suite.FULL_FRAME_NUMERICAL_COHORTS self.assertTrue(all(isinstance(family['limits'], str) and family['limits'] for family in families.values())) self.assertEqual(len({family['limits'] for family in families.values()}), len(families)) limits = families[suite.ROUND_INTEGRAL_FOCUS]['limits'] self.assertIn('H/S/D integral rounding', limits) self.assertIn('bounded 32/64-bit rounding', limits) self.assertIn('retained-enable refusals', limits) self.assertNotIn('JSCVT', limits) self.assertNotIn('conversion', limits) def test_round_integral_fullframe_descriptor_and_frozen_serialization_are_reused(self): family = suite.FULL_FRAME_NUMERICAL_COHORTS[suite.ROUND_INTEGRAL_FOCUS] self.assertEqual(family['forms'], 47) self.assertIs(family['loader'], suite.load_round_integral_oracle) op = suite.round_integral_operation('frintn', 4, 4, True) initial = suite.numerical_unary_state(op, 0, [dict(suite.numerical_unary_values(4))['half_positive']]) record = {'function': 0, 'function_index': 0, 'label': 'half', 'initial': bytes(initial), 'initial_state_sha256': suite.digest(bytes(initial))} with tempfile.TemporaryDirectory() as temporary: directory = Path(temporary) def write_plan(path, value): path.write_text(json.dumps(value)) return path with patch.object(suite, 'write_evidence', side_effect=write_plan), patch.object(suite, 'ROOT', directory): suite.prepare_full_frame_numerical_oracle(directory, [op], [record], suite.ROUND_INTEGRAL_FOCUS) frozen = (directory / 'inputs.bin').read_bytes() self.assertEqual(len(frozen), 800) self.assertEqual(frozen[8:792], bytes(initial)) suite.prepare_full_frame_numerical_oracle(directory, [op], [record], suite.ROUND_INTEGRAL_FOCUS) changed = dict(record, initial=bytes(784)) with self.assertRaises(AssertionError): suite.prepare_full_frame_numerical_oracle(directory, [op], [changed], suite.ROUND_INTEGRAL_FOCUS) def test_comparison_minmax_forms_shapes_and_fixed_encodings_are_complete(self): functions = suite.comparison_minmax_functions() self.assertEqual(len(functions), 2590) self.assertEqual(len({op['word'] for op in functions}), 2590) self.assertEqual(len({op['canonical_id'] for op in functions}), 102) self.assertEqual(len({suite.comparison_minmax_shape(op) for op in functions}), 174) checklist = json.loads((suite.ROOT / 'tests/isa/a64-documented-checklist.json').read_bytes()) facts = {row['id']: row for row in checklist['forms']} decoder = Cs(CS_ARCH_ARM64, CS_MODE_ARM) for operation in functions: fact = facts[operation['canonical_id']] self.assertEqual(operation['word'] & int(fact['encoding_mask'], 0), int(fact['encoding_value'], 0)) instruction, = decoder.disasm(struct.pack('> 5 & 31, operation['n']) self.assertTrue(any(op['name'] == 'fjcvtzs' for op in functions)) def test_conversion_fixed_scales_and_returns_preserve_source_and_destination_gprs(self): for operation in suite.conversion_numerical_functions(): bits = operation['integer_bits'] if operation['fracbits']: self.assertIn(operation['fracbits'], (1, bits // 2, bits)) used = {operation[role] for bank, role in (('source_bank', 'n'), ('destination_bank', 'd')) if operation[bank] == 'general' and operation[role] != 31} self.assertNotIn(operation['return_register'], used) word = suite.numerical_return_word(operation) instruction, = Cs(CS_ARCH_ARM64, CS_MODE_ARM).disasm(struct.pack('> 5 & 31, operation['return_register']) self.assertEqual(suite.numerical_return_word({}), suite.RET) with self.assertRaises(ValueError): suite.numerical_return_word({'return_register': 31}) def test_conversion_rejects_unallocated_shapes_widths_and_fixed_modes(self): invalid = (('fcvt', 4, 4, 'scalar', 0, 1), ('fcvtl', 4, 2, 'vector', 0, 1), ('fcvtxn', 4, 2, 'vector', 0, 1), ('fcvtn', 8, 4, 'scalar', 0, 1), ('fcvtzs', 8, 8, 'vector64', 0, 1), ('fcvtzs', 4, 4, 'general', 0, 1, 64), ('fcvtns', 4, 4, 'general', 0, 1, 32, 1), ('ucvtf', 4, 4, 'general', 0, 1, 32, 0, False), ('fjcvtzs', 4, 4, 'general', 0, 1, 32)) for arguments in invalid: with self.assertRaises(ValueError): suite.conversion_numerical_operation(*arguments) def test_conversion_exact_dyadic_inputs_cover_half_overflow_and_normal_ties(self): self.assertEqual(suite.conversion_exact_positive_bits(4, 131040, 0), 0x47fff000) self.assertEqual(suite.conversion_exact_positive_bits(8, 131040, 0), 0x40fffe0000000000) self.assertIsNone(suite.conversion_exact_positive_bits(2, 131040, 0)) self.assertEqual(suite.conversion_exact_positive_bits(2, 1, -24), 1) self.assertIsNone(suite.conversion_exact_positive_bits(2, 1, -25)) operation = suite.conversion_numerical_operation('fcvt', 8, 2, 'scalar', 0, 1) values = dict(suite.conversion_numerical_values(operation)) self.assertEqual(values['alternative_half_overflow_tie'], 0x40fffe0000000000) self.assertEqual(values['target_overflow_tie'], 0x40effe0000000000) def test_conversion_source_halves_inactive_poison_and_general_w_input(self): for part in (0, 1): operation = suite.conversion_numerical_operation('fcvtl', 2, 4, 'vector', 0, 1, part=part) state = suite.conversion_numerical_state(operation, 17, [1, 2, 3, 4]) packed = state.v[1][0] | state.v[1][1] << 64 self.assertEqual([(packed >> ((part * 4 + index) * 16)) & 65535 for index in range(4)], [1, 2, 3, 4]) poison = dict(suite.conversion_numerical_values(operation))['snan'] self.assertEqual([(packed >> (((1 - part) * 4 + index) * 16)) & 65535 for index in range(4)], [poison] * 4) operation = suite.conversion_numerical_operation('scvtf', 4, 8, 'general', 0, 30, 32) state = suite.conversion_numerical_state(operation, 17, [0x80000001]) self.assertEqual(state.x[30] & 0xffffffff, 0x80000001) self.assertNotEqual(state.x[30] >> 32, 0) self.assertEqual(operation['return_register'], 29) def test_conversion_supplementary_unicorn_difference_is_exact_flushed_subnormal_z_only(self): operation = suite.conversion_numerical_operation('fjcvtzs', 8, 4, 'general', 0, 1, 32) initial = State() initial.fpcr, initial.v[1][0] = suite.NUMERICAL_FZ, 1 expected = State.from_buffer_copy(initial) observed = State.from_buffer_copy(expected) observed.nzcv = 0x40000000 self.assertTrue(suite.conversion_unicorn_flushed_javascript_difference(operation, initial, observed, expected)) initial.v[1][0] |= 1 << 63 self.assertTrue(suite.conversion_unicorn_flushed_javascript_difference(operation, initial, observed, expected)) observed.x[7] = 1 self.assertFalse(suite.conversion_unicorn_flushed_javascript_difference(operation, initial, observed, expected)) observed.x[7], initial.v[1][0] = 0, 0 self.assertFalse(suite.conversion_unicorn_flushed_javascript_difference(operation, initial, observed, expected)) initial.v[1][0], initial.fpcr = 1, suite.NUMERICAL_FZ | suite.NUMERICAL_AH self.assertFalse(suite.conversion_unicorn_flushed_javascript_difference(operation, initial, observed, expected)) def test_conversion_supplementary_fixed_half_difference_only_allows_exact_upper16_extension(self): operation = suite.conversion_numerical_operation('fcvtzs', 2, 2, 'scalar', 0, 1, fracbits=1) initial = State() expected = State.from_buffer_copy(initial) expected.v[0][0] = 0xfffe observed = State.from_buffer_copy(expected) observed.v[0][0] = 0xfffffffe self.assertIsNotNone(suite.conversion_unicorn_difference(operation, initial, observed, expected)) observed.fpsr = 1 self.assertIsNone(suite.conversion_unicorn_difference(operation, initial, observed, expected)) observed.fpsr, observed.v[0][0] = 0, 0xffff7fff expected.v[0][0] = 0x7fff self.assertIsNone(suite.conversion_unicorn_difference(operation, initial, observed, expected)) initial.fpcr, expected.v[0][0], observed.v[0][0] = suite.NUMERICAL_NEP, 0xfffe, 0xfffffffe self.assertIsNone(suite.conversion_unicorn_difference(operation, initial, observed, expected)) def test_conversion_effect_validation_enforces_old_destination_nep_and_narrow2(self): initial = State() initial.v[0][:] = [0x123456789abcdef0, 0xfedcba9876543210] initial.fpcr = suite.NUMERICAL_NEP operation = suite.conversion_numerical_operation('fcvt', 8, 4, 'scalar', 0, 1) original = State.from_buffer_copy(initial) original.v[0][0] = original.v[0][0] & ~0xffffffff | 0x3f800000 suite.validate_conversion_original_effects(initial, original, operation) original.v[0][1] ^= 1 with self.assertRaises(AssertionError): suite.validate_conversion_original_effects(initial, original, operation) operation = suite.conversion_numerical_operation('fcvtn', 8, 4, 'vector', 0, 1, part=1) original = State.from_buffer_copy(initial) original.v[0][1] = 0 suite.validate_conversion_original_effects(initial, original, operation) original.v[0][0] ^= 1 with self.assertRaises(AssertionError): suite.validate_conversion_original_effects(initial, original, operation) operation = suite.conversion_numerical_operation('fcvtzs', 8, 4, 'general', 0, 1, 32) original = State.from_buffer_copy(initial) original.x[0] = 1 << 32 with self.assertRaises(AssertionError): suite.validate_conversion_original_effects(initial, original, operation) def test_conversion_corpus_scope_keeps_all_controls_precise_enables_and_lr_operands(self): functions, records = suite.conversion_numerical_corpus() self.assertEqual(len(records), 33380) self.assertEqual({record['function'] for record in records}, set(range(1416))) imported = [{**record, 'operation': functions[record['function']], 'unsupported': bool(State.from_buffer_copy(record['initial']).fpcr & suite.NUMERICAL_TRAP_ENABLE_MASK)} for record in records] selected = suite.conversion_numerical_runtime_cases(imported) self.assertEqual(len(selected), 867) self.assertEqual(len({record['operation']['canonical_id'] for record in selected}), 163) self.assertEqual({State.from_buffer_copy(record['initial']).fpcr for record in selected if record['unsupported']}, {*(1 << bit for bit in (8, 9, 10, 11, 12, 15)), suite.NUMERICAL_TRAP_ENABLE_MASK}) self.assertTrue(any(record['operation']['return_register'] == 29 for record in selected)) self.assertEqual(len(suite.conversion_numerical_helpers(imported)), 26) def test_fused_encodings_cover_all_modes_register_roles_and_indexed_selectors(self): functions = suite.fused_numerical_functions() self.assertEqual(len(functions), 648) self.assertEqual(len({op['word'] for op in functions}), len(functions)) self.assertEqual(len({suite.fused_numerical_form(op) for op in functions}), 24) decoder = Cs(CS_ARCH_ARM64, CS_MODE_ARM) for operation in functions: instruction, = decoder.disasm(struct.pack('> (index * bits) & mask, 13) poison = next(triple[1] for triple in suite.fused_numerical_triples(lane) if triple[0] == 'snan_addend') self.assertEqual([right >> (element * bits) & mask for element in range(16 // lane) if element != index], [poison] * (16 // lane - 1)) self.assertEqual(initial.fpcr, suite.NUMERICAL_NEP) self.assertEqual(initial.fpsr, suite.FP_REGISTER_MASKS['fpsr']) self.assertNotEqual(initial.v[0][1], 0) def test_fused_single_round_residual_fixture_is_nonzero_exact_arithmetic(self): from fractions import Fraction for lane, fraction in ((2, 10), (4, 23), (8, 52)): label, a, n, m = suite.fused_numerical_triples(lane)[2] self.assertEqual(label, 'single_round_residual') ulp = Fraction(1, 1 << fraction) self.assertEqual((1 + ulp) * (1 - ulp) - 1, -ulp * ulp) self.assertEqual(n & ((1 << fraction) - 1), 1) self.assertEqual(a ^ (1 << (lane * 8 - 1)), n - 1) self.assertEqual(m, n - 3) def test_fused_corpus_and_runtime_scope_include_controls_status_aliases_and_precise_declines(self): functions, records = suite.fused_numerical_corpus() self.assertEqual(len(records), 18402) self.assertEqual({record['function'] for record in records}, set(range(len(functions)))) imported = [{**record, 'operation': functions[record['function']], 'unsupported': bool(State.from_buffer_copy(record['initial']).fpcr & suite.NUMERICAL_TRAP_ENABLE_MASK)} for record in records] selected = suite.fused_numerical_runtime_cases(imported) self.assertEqual(len(selected), 326) self.assertEqual(len({suite.fused_numerical_form(record['operation']) for record in selected}), 24) declines = [record for record in selected if record['unsupported']] self.assertEqual(len(declines), 42) self.assertEqual({State.from_buffer_copy(record['initial']).fpcr for record in declines}, {*(1 << bit for bit in (8, 9, 10, 11, 12, 15)), suite.NUMERICAL_TRAP_ENABLE_MASK}) self.assertEqual(len(suite.fused_numerical_helpers(imported)), 12) self.assertTrue(any(record['label'].startswith('active_snan_addend_') for record in selected)) self.assertEqual({State.from_buffer_copy(record['initial']).fpcr for record in selected if record['label'] == 'single_round_residual'}, {*suite.FUSED_ROUNDING_CONTROLS, suite.NUMERICAL_AH, suite.NUMERICAL_NEP}) def test_vector_numerical_encodings_cover_arrangements_aliases_and_v31(self): functions = suite.vector_numerical_functions() words = [operation['word'] for operation in functions] decoded = list(Cs(CS_ARCH_ARM64, CS_MODE_ARM).disasm(struct.pack('<140I', *words), 0)) self.assertEqual(len(set(words)), 140) self.assertEqual(len(decoded), 140) for operation, instruction in zip(functions, decoded): self.assertEqual(instruction.mnemonic, operation['name']) arrangement = str(operation['bytes'] // operation['lane']) + {2: 'h', 4: 's', 8: 'd'}[operation['lane']] self.assertEqual(instruction.op_str, ', '.join(f'v{operation[role]}.{arrangement}' for role in ('d', 'n', 'm'))) self.assertEqual({(op['lane'], op['bytes']) for op in functions}, set(suite.VECTOR_NUMERICAL_SHAPES)) for arguments in (('fmax', 4, 16, 0, 1, 2), ('fadd', 8, 8, 0, 1, 2), ('fadd', 4, 16, -1, 1, 2), ('fadd', 2, 8, 0, 1, 32)): with self.assertRaises(ValueError): suite.vector_numerical_operation(*arguments) def test_vector_numerical_inputs_poison_inactive_lanes_without_changing_active_pairs(self): for lane, width in suite.VECTOR_NUMERICAL_SHAPES: operation = suite.vector_numerical_operation('fdiv', lane, width, 0, 1, 2) pairs = [(element + 1, element + 17) for element in range(width // lane)] state = suite.vector_numerical_state(operation, 7, pairs, suite.NUMERICAL_NEP, True) bits, mask = lane * 8, (1 << (lane * 8)) - 1 for register, side in ((1, 0), (2, 1)): value = state.v[register][0] | state.v[register][1] << 64 self.assertEqual([(value >> (element * bits)) & mask for element in range(width // lane)], [pair[side] for pair in pairs]) if width == 8: self.assertNotEqual(state.v[register][1], 0) self.assertEqual((state.fpcr, state.fpsr, state.reserved), (suite.NUMERICAL_NEP, suite.FP_REGISTER_MASKS['fpsr'], suite.VECTOR_NUMERICAL_CANARY)) with self.assertRaises(ValueError): suite.vector_numerical_state(operation, 7, pairs[:-1]) def test_vector_original_frame_imports_every_architectural_field_keeps_metadata_canary(self): initial = State() initial.reserved = suite.VECTOR_NUMERICAL_CANARY initial.x[:] = [99] * 31 snapshot = bytearray(suite.FP_REGISTER_RECORD_BYTES) registers = [0x1000000000000000 + register for register in range(31)] vectors = [0x8000000000000000 + limb for limb in range(64)] struct.pack_into('<31Q', snapshot, 0, *registers) struct.pack_into('<4Q', snapshot, suite.VECTOR_NUMERICAL_STATUS_OFFSET, 0x48010100, 0xa0000005, suite.NUMERICAL_NEP, 0x08000012) struct.pack_into('<64Q', snapshot, suite.VECTOR_NUMERICAL_VECTORS_OFFSET, *vectors) observed = suite.full_frame_numerical_original_state(initial, snapshot) self.assertEqual(list(observed.x), registers) self.assertEqual((observed.sp, observed.nzcv, observed.fpcr, observed.fpsr), (0x48010100, 0xa0000000, suite.NUMERICAL_NEP, 0x08000012)) self.assertEqual([limb for vector in observed.v for limb in vector], vectors) self.assertEqual(observed.reserved, initial.reserved) for invalid in (snapshot[:-1], snapshot + bytes(1)): with self.assertRaises(AssertionError): suite.full_frame_numerical_original_state(initial, invalid) def test_vector_runtime_selection_keeps_both_widths_semantic_lanes_aliases_and_traps(self): records = [] for function, operation in enumerate(suite.vector_numerical_functions()): for control, label, unsupported in ((0, 'directed_pack_0', False), (suite.NUMERICAL_NEP, 'alias_pattern_0', False), (suite.NUMERICAL_AH, 'active_snan_left_0', False), (suite.NUMERICAL_TRAP_ENABLE_MASK, 'trap_enable_readback_only', True)): initial = State() initial.fpcr, initial.fpsr = control, 0 records.append({'function': function, 'operation': operation, 'case': len(records), 'initial': bytes(initial), 'label': label, 'unsupported': unsupported}) selected = suite.vector_numerical_runtime_cases(records) self.assertEqual(len(selected), 200) aliases = [record for record in selected if State.from_buffer_copy(record['initial']).fpcr == suite.NUMERICAL_NEP] self.assertEqual({record['function'] for record in aliases}, set(range(140))) semantic = [record for record in selected if record['label'] == 'active_snan_left_0'] self.assertEqual(len(semantic), 20) self.assertEqual({(record['operation']['lane'], record['operation']['bytes']) for record in semantic}, set(suite.VECTOR_NUMERICAL_SHAPES)) self.assertEqual(sum(record['unsupported'] for record in selected), 20) def test_fp_register_encodings_cover_exactly_all_four_operands_and_all_rt(self): functions = suite.fp_register_functions() words = [function['operations'][0]['word'] for function in functions] self.assertEqual(len(set(words)), 128) decoded = list(Cs(CS_ARCH_ARM64, CS_MODE_ARM).disasm(struct.pack('<128I', *words), 0)) self.assertEqual(len(decoded), 128) self.assertEqual([instruction.mnemonic for instruction in decoded], ['mrs'] * 32 + ['msr'] * 32 + ['mrs'] * 32 + ['msr'] * 32) self.assertEqual([instruction.op_str for instruction in decoded if 'xzr' in instruction.op_str], ['xzr, fpcr', 'fpcr, xzr', 'xzr, fpsr', 'fpsr, xzr']) for name in suite.FP_REGISTER_WORDS: for rt in (-1, 32): with self.assertRaises(ValueError): suite.fp_register_operation(name, rt) def test_fp_register_reads_zero_extend_without_normalizing_imported_storage(self): initial = State.from_buffer_copy(suite.states()[0]) initial.fpcr, initial.fpsr, initial.nzcv = 0xffffffff, 0xffffffff, 0xf0000000 for register, mask in suite.FP_REGISTER_MASKS.items(): for rt in (0, 30, 31): actual = suite.fp_register_expected(suite.fp_register_operation('mrs_' + register, rt), initial) expected = State.from_buffer_copy(initial) if rt != 31: expected.x[rt] = mask self.assertEqual(bytes(actual), bytes(expected)) self.assertEqual(getattr(actual, register), 0xffffffff) def test_fp_register_writes_replace_all_storage_keep_enables_and_separate_status(self): initial = State.from_buffer_copy(suite.states()[0]) initial.fpcr, initial.fpsr, initial.nzcv = 0xffffffff, 0xffffffff, 0x90000000 for register, mask in suite.FP_REGISTER_MASKS.items(): for rt in (0, 30, 31): for value in (0, (1 << 64) - 1, 0xfeedface00009f00, 1 << 27): initial.x[0 if rt == 31 else rt] = value actual = suite.fp_register_expected(suite.fp_register_operation('msr_' + register, rt), initial) expected = State.from_buffer_copy(initial) setattr(expected, register, 0 if rt == 31 else value & mask) self.assertEqual(bytes(actual), bytes(expected)) self.assertEqual(suite.FP_REGISTER_MASKS['fpcr'] & suite.NUMERICAL_TRAP_ENABLE_MASK, suite.NUMERICAL_TRAP_ENABLE_MASK) def test_fp_register_policy_cases_cover_raw_imports_every_bit_and_128_roles(self): records = suite.fp_register_policy_cases() self.assertEqual(len(records), 640) self.assertEqual({record['function'] for record in records}, set(range(128))) for index in (32, 96): self.assertEqual({record['bit'] for record in records if record['function'] == index and 'bit' in record}, set(range(64))) self.assertTrue(any(State.from_buffer_copy(record['initial']).fpcr & ~suite.FP_REGISTER_MASKS['fpcr'] for record in records)) self.assertTrue(any(State.from_buffer_copy(record['initial']).fpsr & ~suite.FP_REGISTER_MASKS['fpsr'] for record in records)) def test_fp_register_runtime_chain_exposes_status_then_clears_before_repeat_and_ret(self): initial = State.from_buffer_copy(suite.states()[0]) initial.fpcr, initial.fpsr, initial.x[30] = suite.NUMERICAL_NEP, 0, suite.STOP expected = State.from_buffer_copy(initial) expected.fpsr = 0x12 record = {'initial': bytes(initial), 'expected': bytes(expected), 'operation': {'word': 0x1e221820}} code, entered, intermediate, final = suite.fp_register_chain(record) decoded = list(Cs(CS_ARCH_ARM64, CS_MODE_ARM).disasm(code, 0)) self.assertEqual([instruction.mnemonic for instruction in decoded], ['msr', 'msr', 'fdiv', 'mrs', 'msr', 'mrs', 'fdiv', 'mrs', 'msr', 'mrs', 'ret']) self.assertEqual(entered.fpsr, suite.FP_REGISTER_MASKS['fpsr']) self.assertNotEqual(entered.fpcr, intermediate.fpcr) self.assertEqual((intermediate.fpcr, intermediate.fpsr), (suite.NUMERICAL_NEP, 0x12)) self.assertEqual((final.x[3], final.x[4], final.x[5], final.x[6], final.fpsr), (0x12, 0, 0x12, 0, 0)) def test_block_manifest_binds_only_its_consumed_prefix_without_losing_original_input(self): source = struct.pack('=14 or ((bool(flags&4)) if condition==0 else not bool(flags&4)) expected=suite.floating_bit_mathematical([operation],initial) self.assertEqual(expected['v'][0],[initial.v[1 if left else 2][0]&mask,0]) def test_floating_qemu_fixture_keeps_original_words_and_cases_cover_control_modes(self): programs=suite.floating_bit_programs() shapes={(op['name'],op['lane'],op['bytes'],op['scalar']) for f in programs for op in f['operations']} self.assertEqual(len(shapes),19) self.assertTrue(any(op['d']==op['n']==31 for f in programs for op in f['operations'])) subset=[next(f for f in programs if len(f['operations'])==1 and f['operations'][0]['name']=='fabs')] cases=list(suite.floating_bit_cases(subset,exhaustive_half=False)) self.assertEqual({s.fpcr&7 for _,s in cases},set(range(8))) self.assertEqual({bool(s.fpcr&(1<<26)) for _,s in cases},{False,True}) source=suite.floating_qemu_source(subset,len(cases)) self.assertIn(f'.inst 0x{subset[0]["operations"][0]["word"]:08x}',source) self.assertIn('mrs x0,fpcr',source) self.assertIn('mrs x0,fpsr',source) def test_native_binary_accounting_partitions_guest_bodies_and_ret(self): operation={'name':'fixture','lane':8,'bytes':8,'word':0} batch={'native':bytes.fromhex('31c0c3'),'source':struct.pack('>8,0) self.assertTrue({0x80,0x7f,0xc0,0x40,0xff,0}.issubset(seen)) def test_immediate_doubling_seeds_hit_exact_saturation_thresholds(self): for signed, unsigned, expected_qc in [(True,False,[False,True,False,True]), (False,True,[False,True,True,False]),(True,True,[True,True,False,False])]: for lane in (1,2,4,8): operation=next(p['operations'][0] for p in suite.register_shift_programs() if all(p['operations'][0].get(k)==v for k,v in {'immediate':True,'amount':1,'signed':signed,'unsigned_result':unsigned, 'lane':lane,'d':0,'n':1}.items())) self.assertEqual(suite.register_shift_pattern_count([operation]),12) for pattern,qc in zip(range(6,10),expected_qc): initial=State();suite.register_shift_seed(initial,[operation],pattern,0) expected=suite.register_shift_mathematical([operation],initial) self.assertEqual(bool(expected['fpsr']&(1<<27)),qc,(signed,unsigned,lane,pattern)) def test_shift_oracle_full_width_rounding_boundaries(self): initial=State() initial.v[1][:]=[suite.MASK,suite.MASK] base={'d':0,'n':1,'lane':8,'output_lane':8,'bytes':8,'amount':64,'upper':False} self.assertEqual(suite.shift_mathematical([{**base,'name':'urshr'}],initial)['v'][0],[1,0]) self.assertEqual(suite.shift_mathematical([{**base,'name':'srshr'}],initial)['v'][0],[0,0]) self.assertEqual(suite.shift_mathematical([{**base,'name':'sshr'}],initial)['v'][0],[suite.MASK,0]) def test_table_corpus_contains_register_wrapping_and_both_widths(self): operations=[o for p in suite.rearrange_programs() for o in p['operations']] for name in ('tbl','tbx'): tables=[o for o in operations if o['name']==name] self.assertEqual({o['registers'] for o in tables},{1,2,3,4}) self.assertEqual({o['bytes'] for o in tables},{8,16}) self.assertTrue(any(o['n']==31 and o['d']==o['m'] for o in tables)) def test_lane_oracle_has_independent_signed_width_zero_and_preserved_lane_rules(self): initial=State() initial.v[31][:]=[0x80,0xffffffffffffffff] operation={'name':'smov','d':0,'n':31,'m':0,'lane':1,'bytes':8,'index':0} observed=suite.rearrange_mathematical([operation],initial) self.assertEqual(observed['x'][0],0xffffff80) # signed W write still clears X high half operation['bytes']=16 self.assertEqual(suite.rearrange_mathematical([operation],initial)['x'][0],0xffffffffffffff80) ins={'name':'insg','d':31,'n':31,'m':0,'lane':1,'bytes':16,'index':7} observed=suite.rearrange_mathematical([ins],initial) self.assertEqual(observed['v'][31],[0x80,0xffffffffffffffff]) def test_known_original_words_decode_to_expected_reviewed_operands(self): self.assertEqual(suite.memory_encoding(8, True, 0, 8, 1504, 'unsigned'), 0xfd42f100) self.assertEqual(suite.memory_encoding(16, True, 0, 29, -88, 'unscaled'), 0x3cda83a0) self.assertEqual(suite.movi_encoding(True, 0, 0), 0x6f00e400) self.assertEqual(suite.movi_encoding(False, 255, 31), 0x2f07e7ff) def test_every_emitted_operation_has_an_independent_simd_decode(self): leaves, blocks = suite.programs() decoder = Cs(CS_ARCH_ARM64, CS_MODE_ARM) for program in leaves + blocks: for operation in program['operations']: decoded = list(decoder.disasm(struct.pack('> 64]) self.assertEqual(expected.x[0], initial.x[0] + (16 if mode in ('pre', 'post') else 0)) self.assertEqual(observed, memory) for register in range(1, 31): self.assertEqual(list(expected.v[register]), list(initial.v[register])) self.assertEqual((expected.fpcr, expected.fpsr, expected.nzcv, expected.reserved), (initial.fpcr, initial.fpsr, initial.nzcv, initial.reserved)) def test_duplicate_pair_stores_preserve_both_elements_and_duplicate_loads_decline_math(self): for width in suite.PAIR_WIDTHS: for register in (0, 31): state = State() state.x[0] = 0x8800 state.v[register][:] = [0x0123456789abcdef, 0xfedcba9876543210] memory = b'\xa5' * 4096 expected, observed = suite.mathematical([suite.pair_op(width, False, register, register, 0, 0, 'offset')], state, memory, 0x8000) element = struct.pack('<2Q', *state.v[register])[:width] self.assertEqual(observed, memory[:0x800] + element * 2 + memory[0x800 + 2 * width:]) self.assertEqual(bytes(expected), bytes(state)) with self.assertRaises(ValueError): suite.mathematical([suite.pair_op(width, True, register, register, 0, 0, 'offset')], state, memory, 0x8000) self.assertEqual(len(suite.declined_pair_encodings()), 33) for register in (0, 7, 31): self.assertTrue(any(case['reason'] == 'constrained_duplicate_load' and case['word'] & 31 == register for case in suite.declined_pair_encodings())) def test_pair_fault_profiles_require_sp_for_sp_policy_and_complete_first_elements(self): cases = suite.pair_fault_cases() self.assertEqual(len(cases), 122) for case in cases: self.assertFalse(case['protection'] == 'crossing') if case['protection'] == 'sp_alignment': self.assertEqual(case['rn'], 31) if case['protection'] == 'pair_readonly': self.assertFalse(case['loading']) if case['protection'] in ('pair_second', 'pair_readonly') and case['rn'] == 31: target = 0x9000 - case['width'] base = target - (case['offset'] if case['mode'] != 'post' else 0) self.assertEqual(base % 16, 0) def test_bad_encoding_inputs_and_invalid_oracle_accesses_decline(self): for args in [(3, True, 0, 0, 0, 'unsigned'), (16, True, 32, 0, 0, 'unsigned'), (8, True, 0, 0, 1, 'unsigned'), (8, True, 0, 0, -1, 'unsigned'), (16, True, 0, 0, 65536, 'unsigned'), (16, True, 0, 0, 256, 'pre')]: with self.assertRaises(ValueError): suite.memory_encoding(*args) state = State() state.sp = 0x8001 with self.assertRaises(ValueError): suite.mathematical([suite.memory_op(16, True, 0, 31, 0, 'unsigned')], state, bytes(4096), 0x8000) state.x[0] = 0x9000 with self.assertRaises(ValueError): suite.mathematical([suite.memory_op(16, True, 0, 0, 0, 'unsigned')], state, bytes(4096), 0x8000) def test_pair_fault_classification_keeps_exact_unicorn_difference_and_rejects_other_changes(self): for width in suite.PAIR_WIDTHS: case = {'loading': True, 'protection': 'pair_second', 'width': width, 'rt': 0} initial = State() native = State.from_buffer_copy(initial) native.x[7] = 99 original = State.from_buffer_copy(native) value = int.from_bytes(b'\xa5' * width, 'little') original.v[0][:] = [value & suite.MASK, value >> 64] self.assertEqual(suite.validate_pair_fault_state(case, initial, native, original, b'\xa5' * width), 'unicorn_second_load_divergence') wrong = State.from_buffer_copy(original) wrong.v[31][0] ^= 1 with self.assertRaises(AssertionError): suite.validate_pair_fault_state(case, initial, native, wrong, b'\xa5' * width) wrong = State.from_buffer_copy(native) wrong.x[0] ^= 1 with self.assertRaises(AssertionError): suite.validate_pair_fault_state(case, initial, wrong, original, b'\xa5' * width) case['protection'] = 'guard' self.assertEqual(suite.validate_pair_fault_state(case, initial, native, native, b'\xa5' * width), 'original_native_full_state_equal') with self.assertRaises(AssertionError): suite.validate_pair_fault_state(case, initial, native, original, b'\xa5' * width) case['protection'] = 'sp_alignment' self.assertEqual(suite.validate_pair_fault_state(case, initial, native, None, b'\xa5' * width), 'sp_policy_only') with self.assertRaises(AssertionError): suite.validate_pair_fault_state(case, initial, native, native, b'\xa5' * width) if __name__ == '__main__': unittest.main()