"""Check selected native service call prerequisites in the actual Image CFG. Calls are conservative fallthrough edges; their semantics are separate proofs. Explicit Shared wrappers have one outward tail, to the real CPU service. Every address and branch instruction is checked against both Image and ELF bytes. """ from pathlib import Path import hashlib,json,re,shutil,subprocess,sys,tempfile out=Path(tempfile.mkdtemp(prefix='K2100-native-service-path-proof-',dir='reports/os-implementation')) shutil.copyfile(__file__,out/'harness.py.txt') def art(p): p=Path(p);return dict(path=str(p),sha256=hashlib.sha256(p.read_bytes()).hexdigest()) try: prepath=Path(sys.argv[1]);pre=json.loads(prepath.read_text());assert pre['status']=='NATIVE_MODELS_COMPILED' for a in pre['artifacts'].values():assert art(a['path'])['sha256']==a['sha256'] image=Path(pre['artifacts']['image']['path']).read_bytes();rows=[] for l in Path(pre['artifacts']['nm']['path']).read_text().splitlines(): a=l.split() if len(a)==4:rows.append(dict(address=int(a[0],16),size=int(a[1],16),kind=a[2],name=a[3])) base=next(r['address']for r in rows if r['name']=='_image_start') 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' functions={};disassembly=[] for key,address in [('primary',0x402402ac),('secondary',0x4027bfdc),('primaryCustody',0x400aa448),('secondaryCustody',0x400aa3dc),('service',0x400f5a18),('network',0x4022bf08),('round',0x400fade8),('stackSwitch',0x4009ba60),('process',0x40279b08)]: matches=[r for r in rows if r['address']==address and r['size'] and r['kind']in('t','T')];assert matches and len({r['size']for r in matches})==1;s=matches[0] text=subprocess.check_output([objdump,'-d','--start-address='+str(address),'--stop-address='+str(address+s['size']),pre['artifacts']['elf']['path']],text=True);p=out/(key+'.txt');p.write_text(text);disassembly.append(art(p));ins={};words={} for line in text.splitlines(): m=re.match(r'^\s*([0-9a-f]+):\s+([0-9a-f]{8})\s+(\S+)(.*)$',line) if m: pc,raw=int(m[1],16),int(m[2],16);assert raw==int.from_bytes(image[pc-base:pc-base+4],'little');ins[pc]=(m[3],re.sub(r'<[^>]*>','',m[4].split('//',1)[0]).strip());words[pc]=raw assert len(ins)*4==s['size'] graph={};tails=[] for pc,(op,arg)in ins.items(): assert op not in ('br','blr'),(key,'indirect transfer needs a separate proof',hex(pc)) if op=='ret':successors=[] elif op=='b': destination=int(arg,0);successors=[destination]if destination in ins else [] if not successors: assert any(r['address']==destination and r['size']for r in rows);tails.append((pc,destination)) elif op.startswith('b.')or op in('cbz','cbnz','tbz','tbnz'): destination=int(arg.split(',')[-1].strip(),0);assert destination in ins;successors=[destination,pc+4] else:successors=[pc+4] assert all(x in ins for x in successors),(key,hex(pc),successors) graph[pc]=successors functions[key]=dict(symbol=s,instructions=ins,words=words,graph=graph,tails=tails) def reaches(f,start,target,removed=None): seen=set();todo=[start] while todo: pc=todo.pop() if pc==removed or pc in seen:continue if pc==target:return True seen.add(pc);todo.extend(f['graph'][pc]) return False def call(f,pc,target): assert f['instructions'][pc]==('bl',hex(target)),(hex(pc),f['instructions'][pc],hex(target)) raw=f['words'][pc];assert raw&0xfc000000==0x94000000 offset=raw&0x3ffffff if offset&(1<<25):offset-=1<<26 assert pc+offset*4==target dependencies=[];gates=[] def prerequisite(key,first,target,repeat=False): f=functions[key];entry=f['symbol']['address'];assert reaches(f,entry,target) assert not reaches(f,entry,target,removed=first),(key,'prerequisite can be bypassed',hex(first),hex(target)) if repeat: assert reaches(f,target+4,target),'repeat reachability must be real' assert not reaches(f,target+4,target,removed=first),(key,'new iteration can reuse old service',hex(first),hex(target)) dependencies.append(dict(function=key,requiredCall=first,target=target,everyIteration=repeat)) def success_gate(key,callsite,target): f=functions[key];pc=callsite+4;op,arg=f['instructions'][pc];assert op=='cbnz' and arg.startswith('x0, '),(key,hex(pc),op,arg) refused=int(arg.split(',')[1].strip(),0);assert reaches(f,pc+4,target);assert not reaches(f,refused,target),(key,'callee error can reach success') assert not reaches(f,f['symbol']['address'],target,removed=pc) gates.append(dict(function=key,branch=pc,returnRegister='x0',accepted=0,refusedValues='every nonzero u64',successTarget=target)) # Primary completion requires a new real CPU service on every loop, then a # consumed wake receipt, observed complete window and exact host window ACK. primary=functions['primary'] primary_calls=[(0x402409b0,0x400aa448),(0x402409b8,0x40241e2c),(0x402409c0,0x40242f44),(0x402409cc,0x402426fc),(0x40240a34,0x4024226c),(0x40240a40,0x40242970)] for pc,target in primary_calls:call(primary,pc,target) for (first,_),(target,_)in zip(primary_calls,primary_calls[1:]): prerequisite('primary',first,target,repeat=True);success_gate('primary',first,target) prerequisite('primary',primary_calls[0][0],primary_calls[-1][0],repeat=True) secondary=functions['secondary'] secondary_calls=[(0x4027c480,0x40241190),(0x4027c4d0,0x400aa3dc),(0x4027c4dc,0x40241e2c)] for pc,target in secondary_calls:call(secondary,pc,target) for(first,_),(target,_)in zip(secondary_calls,secondary_calls[1:]): prerequisite('secondary',first,target,repeat=True);success_gate('secondary',first,target) for key in ['primaryCustody','secondaryCustody']: f=functions[key];assert not any(op=='ret'for op,arg in f['instructions'].values());assert len(f['tails'])==1 and f['tails'][0][1]==0x400f5a18 assert reaches(f,f['symbol']['address'],f['tails'][0][0]);dependencies.append(dict(function=key,onlyReturningTail=f['tails'][0],otherOutcomes='nonreturning custody refusal loops')) service=functions['service'];call(service,0x400f5bac,0x4022bf08) # Publication starts at this decoded load/address calculation after all the # CPU/process/EL0/network identity and complete before/after audit gates. assert service['instructions'][0x400f6484]==('ldr','x19, [sp, #0x448]') assert service['instructions'][0x400f64a0]==('stp','x10, x9, [x8, #0x10]') prerequisite('service',0x400f5bac,0x400f6484);success_gate('service',0x400f5bac,0x400f6484) network=functions['network'];network_calls=[(0x4022c1fc,0x4022d1f0),(0x4022c208,0x400fade8),(0x4022c218,0x4022c334)] for pc,target in network_calls:call(network,pc,target) for(first,_),(target,_)in zip(network_calls,network_calls[1:]): prerequisite('network',first,target);success_gate('network',first,target) assert network['instructions'][0x4022c320]==('mov','x0, xzr') prerequisite('network',0x4022c218,0x4022c320);success_gate('network',0x4022c218,0x4022c320) call(functions['round'],0x400faf54,0x4009ba60) call(functions['stackSwitch'],0x4009ba6c,0x40279b08) body=functions['process'] body_calls=[(0x4027a050,0x400f0c6c),(0x4027a15c,0x4021fda8),(0x4027a434,0x40242318),(0x4027a46c,0x4021fda8),(0x4027a530,0x400fb074)] for pc,target in body_calls:call(body,pc,target) for(first,_),(target,_)in zip(body_calls,body_calls[1:]):prerequisite('process',first,target) success_gate('process',0x4027a050,0x4027a15c) report=dict(status='NATIVE_SERVICE_PATH_PREREQUISITES_PASSED',guestAccepted=False,productAccepted=False, scope='Selected actual compiled CFGs require new service and secondary timer calls before each progress update; primary receipt/window/ACK gates precede close on every iteration. Shared wrappers return only through the real CPU service. Network RX precedes process execution, which precedes TX and normal completion. The process timer wait dominates actual stale-PID wake, receipt construction, current wake and service execution. Calls are treated conservatively as fallthrough; full callee semantics, MMIO interrupts and runtime ownership still require the separate native and physical evidence. This is not elapsed guest time or whole-kernel verification.', preflight=art(prepath),image=pre['artifacts']['image'],functions={k:v['symbol']for k,v in functions.items()},dependencies=dependencies,returnGates=gates,disassembly=disassembly,harness=art(out/'harness.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'),prerequisites=len(dependencies),returnGates=len(gates)))) except Exception: import traceback (out/'report.json').write_text(json.dumps(dict(status='NATIVE_SERVICE_PATH_PREREQUISITES_FAILED',guestAccepted=False,productAccepted=False,error=traceback.format_exc()),indent=2)+'\n');print(out/'report.json',file=sys.stderr);raise