"""Interpret the actual compiled admission functions with explicit host inputs. This checks selected integer control flow; it neither advances guest time nor accepts a workload. Real, independently timed guest runs remain mandatory. """ from pathlib import Path import hashlib import importlib.util import itertools import json import re import shutil import struct import subprocess import sys import tempfile machine_path = Path(__file__).with_name('k2100-aarch64-admission-machine.py') spec = importlib.util.spec_from_file_location('admission_machine', machine_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) Machine = module.AdmissionMachine preflight_path = Path(sys.argv[1]) out = Path(tempfile.mkdtemp(prefix='K2100-native-admission-proof-', dir='reports/os-implementation')) shutil.copyfile(__file__, out / 'harness.py.txt') shutil.copyfile(machine_path, out / 'machine.py.txt') def artifact(p): p = Path(p) return dict(path=str(p), sha256=hashlib.sha256(p.read_bytes()).hexdigest()) def checked(a): assert artifact(a['path'])['sha256'] == a['sha256'] return Path(a['path']).read_bytes() try: pre = json.loads(preflight_path.read_text()) assert pre['status'] == 'NATIVE_MODELS_COMPILED' image = checked(pre['artifacts']['image']) checked(pre['artifacts']['elf']) symbols = {} for line in checked(pre['artifacts']['nm']).decode().splitlines(): a = line.split() if len(a) == 4: symbols[a[3]] = dict(address=int(a[0], 16), size=int(a[1], 16), name=a[3]) base = symbols['_image_start']['address'] def pick(part): found = [s for n, s in symbols.items() if part in n and s['size'] and not n.startswith('_RNC')] assert len(found) == 1, (part, len(found)) return found[0] selected = {k: pick(p) for k, p in [('gate', '7Monitor4gate'), ('close', '7Monitor5close'), ('finish', '8duration8may_stop')]} sysroot = subprocess.check_output(['rustc', '--print', 'sysroot'], text=True).strip() host = next(l[6:] for l in subprocess.check_output(['rustc', '-vV'], text=True).splitlines() if l.startswith('host: ')) objdump = sysroot + '/lib/rustlib/' + host + '/bin/llvm-objdump' instructions = {} for key, symbol in selected.items(): text = subprocess.check_output([objdump, '-d', '--start-address=' + str(symbol['address']), '--stop-address=' + str(symbol['address'] + symbol['size']), pre['artifacts']['elf']['path']], text=True) (out / (key + '.txt')).write_text(text) count = 0 for line in text.splitlines(): m = re.match(r'^\s*([0-9a-f]+):\s+([0-9a-f]{8})\s+(\S+)(.*)$', line) if not m: continue address = int(m[1], 16) raw = int(m[2], 16) assert raw == int.from_bytes(image[address - base:address - base + 4], 'little'), 'ELF/Image instruction binding' args = re.sub(r'<[^>]*>', '', m[4].split('//', 1)[0]).strip() assert address not in instructions instructions[address] = (m[3], args) count += 1 assert count * 4 == symbol['size'], ('complete function decoding', key) monitor_address = symbols['OS_K2100_WORKLOAD_MONITOR']['address'] summary_address = symbols['OS_K2100_WORKLOAD_SUMMARY']['address'] control_address = symbols['OS_K2100_HOST_DURATION_CONTROL']['address'] bss_end = symbols['__bss_end']['address'] assert bss_end - base <= 8 * 1024 * 1024 initial = bytearray(max(len(image), bss_end - base)) initial[:len(image)] = image stack_base = 0x70000000 return_pc = 0x70020000 result_address = stack_base + 128 visited = set() cases = [] test_inputs = [] def pack(values): return b''.join(v.to_bytes(8, 'little') for v in values) def state(frequency=24_000_000, elapsed=1, windows=3, refusals=1, late=0, closed=0, cpu=0, root=0x40000000, daif=960, currentel=4, spsel=1, clock_delta=1): started = 1_000_000_000 deadline = started + frequency * 7200 previous = deadline + elapsed m = [0] * 53 m[:5] = [0x40000000, frequency, 4, started, previous] m[45:53] = [63663, 4, 4, 0, windows, refusals, deadline + late, closed] h = dict(mpidr_el1=cpu, ttbr0_el1=root, daif=daif, currentel=currentel, spsel=spsel, cntpct_el0=previous + clock_delta, tcr_el1=0, sctlr_el1=0) return m, h def expected_close(m, h): cpu = h['mpidr_el1'] & 0xff00ffffff if cpu != 0 or h['ttbr0_el1'] != m[0] or h['daif'] != 960 or h['currentel'] != 4 or h['spsel'] != 1: return 2 if m[52]: return 10 if h['cntpct_el0'] < m[4]: return 3 deadline = m[3] + m[1] * 7200 if m[4] < deadline or m[49] < 3 or m[50] == 0 or m[51] < deadline or m[51] >= m[4]: return 9 return 0 def execute(kind, m, h, control=0, late_window=0, decoded=None, collect=True): machine = Machine(instructions if decoded is None else decoded, [(base, initial), (stack_base, bytes(65536))], h) for i, value in enumerate(m): machine.write(monitor_address + i * 8, 8, value) machine.write(control_address, 8, control) machine.write(summary_address + 8 * 8, 8, late_window) machine.write(summary_address + 12 * 8, 8, 0) machine.sp = stack_base + 65520 original_sp = machine.sp machine.assign('x30', return_pc) machine.assign('x8', result_address) machine.writes.clear() machine.run(selected[kind]['address'], return_pc) assert machine.sp == original_sp if collect: visited.update(machine.trace) after = [machine.read(monitor_address + i * 8, 8) for i in range(53)] expected = list(m) code = expected_close(m, h) if kind == 'close': assert machine.value('x0') == code if code == 0: expected[52] = 1 else: invalid_context = bool(h['mpidr_el1'] & 0xff00ffffff) or h['daif'] != 960 or h['currentel'] != 4 or h['spsel'] != 1 error = invalid_context or control > 2 stopped = False phase = 0 if not error and control == 2 and m[49] >= 3: if code == 0: expected[52] = 1 error = code != 9 stopped = not error phase = 2 if stopped else 0 elif not error and control == 1 and late_window > 0 and m[49] > late_window: error = code != 0 stopped = not error if stopped: expected[52] = 1 phase = 1 actual_error = machine.read(result_address, 8) != 0 assert actual_error == error, (control, late_window, code, 'Result') if not error: assert machine.read(result_address + 8, 1) == stopped assert machine.read(summary_address + 12 * 8, 8) == phase assert after == expected, 'complete Monitor transition including unchanged refusal' for address, size in machine.writes: assert stack_base <= address and address + size <= stack_base + 65536 or (address, size) in [(monitor_address + 52 * 8, 8), (summary_address + 12 * 8, 8)], ('unexpected native write', hex(address), size) if collect: cases.append(dict(kind=kind, expectedClose=code, control=control, lateWindow=late_window, instructions=len(machine.trace))) test_inputs.append((kind, list(m), dict(h), control, late_window)) for frequency, elapsed, windows, refusals, late, closed in itertools.product( [1, 100, 24_000_000], [-1, 0, 1, 2], [0, 2, 3, 4], [0, 1], [-1, 0, 1, 2], [0, 1]): m, h = state(frequency=frequency, elapsed=elapsed, windows=windows, refusals=refusals, late=late, closed=closed) execute('close', m, h) for key, values in [('cpu', [1, 2, 3, 1 << 8, 1 << 16, 1 << 32, 1 << 24]), ('root', [0, 0x40001000]), ('daif', [0, 128, 832]), ('currentel', [0, 8]), ('spsel', [0]), ('clock_delta', [-1, 0, 1])]: for value in values: m, h = state(**{key: value}) execute('close', m, h) for control, elapsed, windows, late_window, late, closed in itertools.product( [0, 1, 2, 3, 0xffffffffffffffff], [-1, 0, 1, 2], [0, 2, 3, 4], [0, 2, 3, 4], [-1, 0, 1, 2], [0, 1]): m, h = state(elapsed=elapsed, windows=windows, late=late, closed=closed) execute('finish', m, h, control=control, late_window=late_window) for key, value in [('cpu', 1), ('cpu', 1 << 32), ('daif', 0), ('currentel', 0), ('spsel', 0), ('root', 0), ('clock_delta', -1)]: for control in [0, 1, 2, 3]: m, h = state(**{key: value}) execute('finish', m, h, control=control, late_window=2) (out / 'cases.json').write_text(json.dumps(cases, separators=(',', ':')) + '\n') coverage = {name: dict(instructions=s['size'] // 4, visited=sum(address in visited for address in range(s['address'], s['address'] + s['size'], 4))) for name, s in selected.items()} assert all(c['visited'] == c['instructions'] for c in coverage.values()), coverage # Patch actual AArch64 instruction bytes in both ELF and Image views. LLVM # decodes each mutant afresh; a changed source-level predicate is not used # as a substitute for testing the selected compiled branches. elf_bytes = checked(pre['artifacts']['elf']) assert elf_bytes[:6] == b'\x7fELF\x02\x01' phoff = struct.unpack_from(']*>', '', op[4].split('//', 1)[0]).strip()) rejected_case = None for case_index, (kind, m, h, control, late_window) in enumerate(test_inputs): try: execute(kind, m, h, control, late_window, decoded=decoded, collect=False) except AssertionError as error: assert 'unsupported instruction' not in str(error), str(error) rejected_case = case_index break assert rejected_case is not None, ('instruction mutant survived', name) rejected.append(dict(name=name, address=pc, original=hex(raw_at(pc)), changed=hex(changed), firstRejectedCase=rejected_case, elf=artifact(mutant_path))) report = dict(status='NATIVE_ADMISSION_CONTROL_FLOW_COMPONENT_PASSED', guestAccepted=False, productAccepted=False, scope='Complete decoded instruction coverage of the selected actual Image functions Monitor::gate, Monitor::close and duration::may_stop under bounded host interpretation. Hardware register values and counter observations are explicit host test inputs. This does not emulate concurrency, replace the real two-hour guest run, or prove the other native service/resource paths.', preflight=artifact(preflight_path), image=pre['artifacts']['image'], elf=pre['artifacts']['elf'], nm=pre['artifacts']['nm'], functions=selected, coverage=coverage, cases=len(cases), outcomes={str(code): sum(c['expectedClose'] == code for c in cases) for code in [0, 2, 3, 9, 10]}, compiledInstructionMutantsRejected=rejected, harness=artifact(out / 'harness.py.txt'), interpreter=artifact(out / 'machine.py.txt'), casesArtifact=artifact(out / 'cases.json'), disassembly=[artifact(out / (k + '.txt')) for k in selected]) (out / 'report.json').write_text(json.dumps(report, indent=2) + '\n') print(json.dumps(dict(status=report['status'], report=str(out / 'report.json'), cases=len(cases), coverage=coverage))) except BaseException as error: import traceback detail = traceback.format_exc() (out / 'report.json').write_text(json.dumps(dict(status='NATIVE_ADMISSION_CONTROL_FLOW_COMPONENT_FAILED', guestAccepted=False, productAccepted=False, preflight=str(preflight_path), error=detail), indent=2) + '\n') print(str(out / 'report.json'), file=sys.stderr) print(detail, file=sys.stderr) sys.exit(1)