"""Check compiled service completion updates against actual captured inputs. 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-service-progress-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 [('progress', '8duration12service_done')]} 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) review_path = Path(sys.argv[2]) review = json.loads(review_path.read_text()) assert review['status'] == 'DURATION_COMPONENT_GUEST_RETURNED' candidate = json.loads(checked(review['candidate'])) assert candidate['artifacts']['image'] == pre['artifacts']['image'] physical = json.loads(checked(review['physical'])) first = physical['windowCheckpoints'][0] captured = {k: checked(v) for k, v in first['dumps'].items()} timer_path = Path(review['physical']['path']).parent / 'OS_K2100_TIMER_EVIDENCE.bin' # The final primary timer receipt is from this same short image/run. The # per-window CPU0 timer object was not part of the worker snapshot set. primary_timer = timer_path.read_bytes() assert len(primary_timer) == 384 global_names = ['OS_K2100_PROCESS_EVIDENCE', 'OS_K2100_SERVICE_EVIDENCE', 'OS_K2100_EL0_EVIDENCE', 'OS_K2100_NETWORK_EVIDENCE', 'OS_K2100_TIMER_EVIDENCE', 'OS_K2100_SECONDARY_TIMERS', 'OS_K2100_WORKLOAD_PROGRESS', 'OS_K2100_PROCESS_OWNER'] locations = {name: pick(name, True)['address'] for name in global_names} stack = 0x70000000 return_pc = stack + 0x20000 visited = set() cases = [] def raw_at(machine, address, size): data, at = machine.locate(address, size) return bytes(data[at:at+size]) def write_bytes(machine, address, data): region, at = machine.locate(address, len(data)) region[at:at+len(data)] = data def execute(cpu, label, mutation=None, valid=True, hardware_cpu=None, owner=None, overflow=None): h = dict(mpidr_el1=cpu if hardware_cpu is None else hardware_cpu, daif=960, currentel=4, ttbr0_el1=0x40000000, tcr_el1=0, sctlr_el1=0, spsel=1, cntpct_el0=300) machine = Machine(instructions, [(base, initial), (stack, bytes(65536))], h) machine.sp = stack+65520 machine.assign('x30', return_pc) machine.assign('x0', cpu) sources = { 'OS_K2100_PROCESS_EVIDENCE': captured['OS_K2100_CPU_PROCESS'][cpu*256:(cpu+1)*256], 'OS_K2100_SERVICE_EVIDENCE': captured['OS_K2100_CPU_SERVICE'][cpu*256:(cpu+1)*256], 'OS_K2100_EL0_EVIDENCE': captured['OS_K2100_CPU_EL0'][cpu*256:(cpu+1)*256], 'OS_K2100_NETWORK_EVIDENCE': captured['OS_K2100_CPU_NETWORK'][cpu*512:(cpu+1)*512], 'OS_K2100_TIMER_EVIDENCE': primary_timer, 'OS_K2100_SECONDARY_TIMERS': captured['OS_K2100_SECONDARY_TIMERS'], } progress = [0]*24 progress[cpu*6:cpu*6+6] = [30,20,10,10,10,10] if overflow is not None: progress[cpu*6+overflow] = (1<<64)-1 sources['OS_K2100_WORKLOAD_PROGRESS'] = pack(progress) sources['OS_K2100_PROCESS_OWNER'] = pack([cpu if owner is None else owner]) for name, data in sources.items(): write_bytes(machine, locations[name], data) if mutation: name, word_index, value = mutation machine.write(locations[name]+word_index*8, 8, value) machine.writes.clear() machine.run(selected['progress']['address'], return_pc) assert (machine.value('x0') == 0) == valid, (cpu,label) expected = list(progress) if valid: for i, increment in enumerate([3,2,1,1,1,1]): expected[cpu*6+i] += increment assert raw_at(machine, locations['OS_K2100_WORKLOAD_PROGRESS'], 192) == pack(expected), (label,'transactional whole-CPU progress') for address,size in machine.writes: assert stack <= address and address+size <= stack+65536 or locations['OS_K2100_WORKLOAD_PROGRESS']+cpu*48 <= address and address+size <= locations['OS_K2100_WORKLOAD_PROGRESS']+(cpu+1)*48, ('unexpected progress write',hex(address),size) visited.update(machine.trace) cases.append(dict(cpu=cpu,label=label,accepted=valid,instructions=len(machine.trace))) for cpu in range(4): execute(cpu,'actual captured service inputs') execute(cpu,'wrong hardware CPU',hardware_cpu=(cpu+1)%4,valid=False) execute(cpu,'wrong Shared process owner',owner=(cpu+1)%4,valid=False) for service in range(6): execute(cpu,'overflow service '+str(service),overflow=service,valid=False) mutations = [ ('process marker','OS_K2100_PROCESS_EVIDENCE',0,0), ('process CPU','OS_K2100_PROCESS_EVIDENCE',16,(cpu+1)%4), ('service CPU','OS_K2100_SERVICE_EVIDENCE',17,(cpu+1)%4), ('EL0 CPU','OS_K2100_EL0_EVIDENCE',20,(cpu+1)%4), ('EL0 call count','OS_K2100_EL0_EVIDENCE',2,4), ('EL0 completion','OS_K2100_EL0_EVIDENCE',19,0), ('network CPU','OS_K2100_NETWORK_EVIDENCE',39,(cpu+1)%4), ('network completion','OS_K2100_NETWORK_EVIDENCE',38,0), ('process work','OS_K2100_PROCESS_EVIDENCE',14,1), ('child process work','OS_K2100_SERVICE_EVIDENCE',13,0), ('IPC work','OS_K2100_SERVICE_EVIDENCE',8,1), ('VFS work','OS_K2100_SERVICE_EVIDENCE',10,0), ('shell work','OS_K2100_SERVICE_EVIDENCE',9,0), ] for label,index,value in [('timer marker',0,0),('timer delivery',1,0),('timer operation',13,0), ('timer INTID',22,29),('timer pending',23,1),('timer active',24,1)]: mutations.append((label,'OS_K2100_TIMER_EVIDENCE' if cpu==0 else 'OS_K2100_SECONDARY_TIMERS',index if cpu==0 else cpu*128+64+index,value)) for label,name,index,value in mutations: execute(cpu,label,mutation=(name,index,value),valid=False) function = selected['progress'] coverage = dict(instructions=function['size']//4,visited=sum(pc in visited for pc in range(function['address'],function['address']+function['size'],4))) assert coverage['instructions']==coverage['visited'], coverage report = dict(status='NATIVE_SERVICE_PROGRESS_CONTROL_FLOW_PASSED',guestAccepted=False,productAccepted=False, scope='Actual compiled service_done function interpreted against the same run captured per-CPU service rows and timer receipts. All six counter updates require expected actual CPU/owner, process/EL0/network/timer evidence and exact service units. Every counter overflow leaves the complete global progress array unchanged. CPU0 timer input is the final same-run receipt, since intermediate worker snapshots omitted that object. This is a host control-flow component, not a new guest run or standalone proof of the underlying services.', preflight=artifact(preflight_path),review=artifact(review_path),image=pre['artifacts']['image'],function=function, decodedFunctions=list(decoded_functions.values()),coverage=coverage,cases=cases,primaryTimer=artifact(timer_path), 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_SERVICE_PROGRESS_CONTROL_FLOW_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)