"""Check the compiled stale-receipt construction and consumption paths. All execution here uses explicit host fixtures. Actual process wake rejection and actual guest elapsed time still require the separately captured guest run. """ from pathlib import Path import hashlib import importlib.util import json import re import shutil 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 out = Path(tempfile.mkdtemp(prefix='K2100-native-receipt-proof-', dir='reports/os-implementation')) shutil.copyfile(__file__, out / 'harness.py.txt') shutil.copyfile(machine_path, out / 'machine.py.txt') def artifact(path): path = Path(path) return dict(path=str(path), sha256=hashlib.sha256(path.read_bytes()).hexdigest()) def checked(a): assert artifact(a['path'])['sha256'] == a['sha256'] return Path(a['path']).read_bytes() def pack(values): return b''.join(int(v).to_bytes(8, 'little') for v in values) try: preflight_path = Path(sys.argv[1]) pre = json.loads(preflight_path.read_text()) assert pre['status'] == 'NATIVE_MODELS_COMPILED' image = checked(pre['artifacts']['image']) checked(pre['artifacts']['elf']) symbol_rows = [] for line in checked(pre['artifacts']['nm']).decode().splitlines(): a = line.split() if len(a) == 4: symbol_rows.append(dict(address=int(a[0], 16), size=int(a[1], 16), kind=a[2], name=a[3])) def pick(part, exact=False): rows = [s for s in symbol_rows if (s['name'] == part if exact else part in s['name']) and s['size'] and not s['name'].startswith('_RNC')] assert len(rows) == 1, (part, len(rows)) return rows[0] base = next(s['address'] for s in symbol_rows if s['name'] == '_image_start') bss_end = next(s['address'] for s in symbol_rows if s['name'] == '__bss_end') initial = bytearray(max(len(image), bss_end - base)) initial[:len(image)] = image selected = {key: pick(fragment) for key, fragment in [('constructor', '8duration5stale'), ('consumer', '8duration9take_wake')]} 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 = {} decoded_functions = {} def decode(symbol): address, size = symbol['address'], symbol['size'] if address in decoded_functions: return text = subprocess.check_output([objdump, '-d', '--start-address=' + str(address), '--stop-address=' + str(address + size), pre['artifacts']['elf']['path']], text=True) path = out / (hex(address) + '.txt') path.write_text(text) local = {} 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 pc, raw = int(m[1], 16), int(m[2], 16) assert raw == int.from_bytes(image[pc - base:pc - base + 4], 'little') local[pc] = (m[3], re.sub(r'<[^>]*>', '', m[4].split('//', 1)[0]).strip()) assert len(local) * 4 == size assert not instructions.keys() & local.keys() instructions.update(local) decoded_functions[address] = {**symbol, 'disassembly': artifact(path)} for pc in local: raw = int.from_bytes(image[pc - base:pc - base + 4], 'little') if raw & 0x7c000000 != 0x14000000: continue immediate = raw & 0x3ffffff if immediate & (1 << 25): immediate -= 1 << 26 target = pc + immediate * 4 if address <= target < address + size: continue # Outliner labels can be duplicated across LLVM codegen units. # Resolve the actual call target address, never a name-keyed map. targets = [s for s in symbol_rows if s['address'] == target and s['size'] and s['kind'] in ('t', 'T')] assert targets and len({s['size'] for s in targets}) == 1, (hex(target), targets) decode(targets[0]) for symbol in selected.values(): decode(symbol) pending = pick('8duration12PENDING_WAKE')['address'] resources = pick('8duration9RESOURCES')['address'] monitor = pick('OS_K2100_WORKLOAD_MONITOR', True)['address'] summary = pick('OS_K2100_WORKLOAD_SUMMARY', True)['address'] stale = pick('OS_K2100_WORKLOAD_STALE', True)['address'] process_owner = pick('OS_K2100_PROCESS_OWNER', True)['address'] profile_cpus = pick('OS_K2100_PROFILE_CPUS', True)['address'] stack = 0x70000000 return_pc = stack + 0x20000 visited = set() cases = [] def hardware(**extra): result = dict(mpidr_el1=0, daif=960, currentel=4, ttbr0_el1=0x40000000, tcr_el1=0, sctlr_el1=0, spsel=1, cntpct_el0=300) result.update(extra) return result def new_machine(h): m = Machine(instructions, [(base, initial), (stack, bytes(65536))], h) m.sp = stack + 65520 m.assign('x30', return_pc) return m def bytes_at(m, address, size): data, offset = m.locate(address, size) return bytes(data[offset:offset + size]) def write_bytes(m, address, data): for i, value in enumerate(data): m.write(address + i, 1, value) def constructor(label, cpu=0, owner=None, count=4, present=False, resource_present=True, authorized=100, hardware_changes=None): h = hardware(mpidr_el1=cpu, **(hardware_changes or {})) m = new_machine(h) owner = cpu if owner is None else owner before_pending = b'\xa5' * 80 + bytes([1 if present else 2]) + b'\x5a' * 7 before_stale = b'\xa7' * 192 write_bytes(m, pending, before_pending) write_bytes(m, stale, before_stale) write_bytes(m, resources, pack([1 if resource_present else 0, 100, count, count])) m.write(process_owner, 8, owner) m.write(profile_cpus, 8, count) old, current, thread, epoch = [7, 0, 1], [7, 0, 2], [9, 1, 4], 3 audit = [256, 0, 156, authorized, 70, 10, 20] for address, values in [(stack + 128, old), (stack + 160, current), (stack + 192, thread), (stack + 224, audit)]: write_bytes(m, address, pack(values)) for reg, value in [('x0', stack + 128), ('x1', stack + 160), ('x2', stack + 192), ('x3', epoch), ('x4', stack + 224)]: m.assign(reg, value) m.writes.clear() m.run(selected['constructor']['address'], return_pc) actual_cpu = (h['mpidr_el1'] & 0xffffff) | (((h['mpidr_el1'] >> 32) & 255) << 24) valid = actual_cpu == owner and actual_cpu < count and h['daif'] == 960 and h['currentel'] == 4 and not present and resource_present and authorized == 100 assert (m.value('x0') == 0) == valid, label expected_pending = pack(old + current + [h['cntpct_el0'], 100, count, count]) + b'\x01' + b'\x5a' * 7 if valid else before_pending expected_stale = pack([2100, actual_cpu] + old + [current[2], h['cntpct_el0'], authorized, 20, 10, 70, count, count, 1] + thread + [epoch] + [0] * 6) if valid else before_stale assert bytes_at(m, pending, 88) == expected_pending, (label, 'pending receipt') assert bytes_at(m, stale, 192) == expected_stale, (label, 'physical receipt') for address, size in m.writes: assert pending <= address and address + size <= pending + 88 or stale <= address and address + size <= stale + 192, ('constructor write', hex(address), size) visited.update(m.trace) cases.append(dict(kind='constructor', label=label, accepted=valid, instructions=len(m.trace))) for count in [1, 2, 4]: for cpu in range(4): constructor('CPU/count %d/%d' % (cpu, count), cpu=cpu, count=count) constructor('different expected owner', cpu=1, owner=0) constructor('upper affinity', cpu=1 << 32, owner=0) constructor('pending receipt retained', present=True) constructor('missing resources', resource_present=False) constructor('wrong authorized pages', authorized=101) for key, value in [('daif', 0), ('currentel', 0), ('currentel', 8)]: constructor('hardware ' + key + str(value), hardware_changes={key: value}) def consume(label, receipt=None, pending_none=False, late_window=0, count=1, closed=0, last_stale=150, previous=200, hardware_changes=None, unchanged=True): h = hardware(**(hardware_changes or {})) m = new_machine(h) # Full private representation, including its seven padding bytes, must # survive a refusal. The actual compiler copies those bytes on rollback. values = [7, 0, 1, 7, 0, 2, 250, 100, 4, 4] values = values if receipt is None else receipt before_pending = pack(values) + bytes([2 if pending_none else int(unchanged)]) + bytes(range(91, 98)) before_monitor = [0] * 53 before_monitor[:5] = [0x40000000, 1, 4, 100, previous] before_monitor[45:53] = [100, 4, 4, 0, 3, count, last_stale, closed] before_summary = [0] * 32 before_summary[4], before_summary[8], before_summary[9], before_summary[10] = 7300, late_window, 7300 if late_window else 0, count write_bytes(m, pending, before_pending) write_bytes(m, monitor, pack(before_monitor)) write_bytes(m, summary, pack(before_summary)) write_bytes(m, stale, pack([0] * 6 + [values[6]] + [0] * 17)) initial_context = h['mpidr_el1'] & 0xff00ffffff == 0 and h['daif'] == 960 and h['currentel'] == 4 and h['spsel'] == 1 gate = initial_context and h['ttbr0_el1'] == before_monitor[0] and closed == 0 and h['cntpct_el0'] >= previous valid_receipt = values[0] > 0 and values[0] == values[3] and values[1] == values[4] and 0 < values[2] < values[5] valid_receipt = valid_receipt and unchanged and values[7:] == [100, 4, 4] and previous <= values[6] <= h['cntpct_el0'] and values[6] > last_stale and count < (1 << 64) - 1 success = initial_context and not pending_none and (late_window > 0 or gate and valid_receipt) m.writes.clear() m.run(selected['consumer']['address'], return_pc) assert (m.value('x0') == 0) == success, label expected_monitor = list(before_monitor) expected_summary = list(before_summary) expected_pending = bytearray(before_pending) if success: expected_pending[80] = 2 if late_window == 0: expected_monitor[50] += 1 expected_monitor[51] = values[6] if values[6] >= 7300: expected_summary[8] = 4 expected_summary[9] = values[6] expected_summary[10] = expected_monitor[50] assert bytes_at(m, pending, 88) == expected_pending, (label, 'nonclone receipt preserved on refusal') assert bytes_at(m, monitor, 424) == pack(expected_monitor), (label, 'complete Monitor transition') assert bytes_at(m, summary, 256) == pack(expected_summary), (label, 'first late boundary') for address, size in m.writes: assert stack <= address and address + size <= stack + 65536 or pending <= address and address + size <= pending + 88 or monitor <= address and address + size <= monitor + 424 or summary <= address and address + size <= summary + 256, ('consumer write', hex(address), size) visited.update(m.trace) cases.append(dict(kind='consumer', label=label, accepted=success, instructions=len(m.trace))) consume('normal early refusal') consume('missing receipt', pending_none=True) consume('owner state changed', unchanged=False) for index, value in [(0, 0), (3, 8), (4, 1), (2, 0), (2, 2), (2, 3), (7, 101), (8, 3), (9, 3), (6, 199), (6, 301)]: values = [7, 0, 1, 7, 0, 2, 250, 100, 4, 4] values[index] = value consume('receipt field %d=%d' % (index, value), receipt=values) consume('equal previous observation', receipt=[7, 0, 1, 7, 0, 2, 200, 100, 4, 4]) consume('replayed receipt counter', last_stale=250) consume('refusal count exhausted', count=(1 << 64) - 1) consume('closed Monitor', closed=1) for key, value in [('mpidr_el1', 1), ('mpidr_el1', 1 << 32), ('ttbr0_el1', 0), ('daif', 0), ('currentel', 0), ('spsel', 0), ('cntpct_el0', 199)]: consume('hardware ' + key, hardware_changes={key: value}) for counter in [7299, 7300, 7301]: consume('late boundary ' + str(counter), receipt=[7, 0, 1, 7, 0, 2, counter, 100, 4, 4], hardware_changes={'cntpct_el0': counter + 1}) consume('later receipt consumed without moving first late boundary', late_window=4, count=9, last_stale=7300, previous=7350, receipt=[7, 0, 1, 7, 0, 2, 7400, 100, 4, 4], hardware_changes={'cntpct_el0': 7450}) coverage = {key: dict(instructions=s['size'] // 4, visited=sum(pc in visited for pc in range(s['address'], s['address'] + s['size'], 4))) for key, s in selected.items()} assert all(row['instructions'] == row['visited'] for row in coverage.values()), coverage report = dict(status='NATIVE_RECEIPT_CONTROL_FLOW_COMPONENT_PASSED', guestAccepted=False, productAccepted=False, scope='Actual Image instruction bytes for receipt construction and consumption are interpreted with explicit host fixtures. Complete selected-function instruction coverage checks real-counter transfer into both receipt representations, CPU/context/owner checks, nonclone receipt restoration on refusal, Monitor resource/identity/time gates, overflow refusal, and pinning the first late boundary. This is not a real stale-PID operation or elapsed guest run; the original wake path and all guest evidence remain separate obligations.', preflight=artifact(preflight_path), image=pre['artifacts']['image'], functions=selected, decodedFunctions=list(decoded_functions.values()), coverage=coverage, cases=cases, harness=artifact(out / 'harness.py.txt'), interpreter=artifact(out / 'machine.py.txt')) (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: import traceback detail = traceback.format_exc() (out / 'report.json').write_text(json.dumps(dict(status='NATIVE_RECEIPT_CONTROL_FLOW_COMPONENT_FAILED', guestAccepted=False, productAccepted=False, error=detail), indent=2) + '\n') print(str(out / 'report.json'), file=sys.stderr) print(detail, file=sys.stderr) sys.exit(1)