"""Execute selected compiled resource gates, with explicit host boundary inputs. Earlier allocator audit/BootOnline validation are outside this slice. Secondary stack bytes come from the archived short run. Primary canaries and guard-helper return values are modeled inputs, since the intermediate capture omitted them. """ 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-resource-gates-proof-', dir='reports/os-implementation')) shutil.copyfile(__file__, out/'harness.py.txt') shutil.copyfile(machine_path, out/'machine.py.txt') def art(p): p = Path(p) return dict(path=str(p), sha256=hashlib.sha256(p.read_bytes()).hexdigest()) def checked(a): assert art(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) def unpack(data): return [int.from_bytes(data[i:i+8], 'little') for i in range(0, len(data), 8)] try: prepath, reviewpath = map(Path, sys.argv[1:3]) pre = json.loads(prepath.read_text()) assert pre['status'] == 'NATIVE_MODELS_COMPILED' image = checked(pre['artifacts']['image']) checked(pre['artifacts']['elf']) rows = [] for line in checked(pre['artifacts']['nm']).decode().splitlines(): a = line.split() if len(a) == 4: rows.append(dict(address=int(a[0],16), size=int(a[1],16), kind=a[2], name=a[3])) def pick(fragment, exact=False): found = [r for r in rows if (r['name'] == fragment if exact else fragment in r['name']) and r['size'] and not r['name'].startswith('_RNC')] assert len(found) == 1, (fragment, len(found)) return found[0] body = pick('8duration9resources') base = next(r['address'] for r in rows if r['name'] == '_image_start') bss_end = next(r['address'] for r in rows if r['name'] == '__bss_end') initial = bytearray(max(len(image), bss_end-base)) initial[:len(image)] = image 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, disassembly = {}, [] def decode(s): address,size = s['address'],s['size'] text = subprocess.check_output([objdump,'-d','--start-address='+str(address),'--stop-address='+str(address+size),pre['artifacts']['elf']['path']],text=True) p=out/(hex(address)+'.txt');p.write_text(text);disassembly.append(art(p)) local = {} 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') 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) decode(body) # Use real addresses, because LLVM outline labels are not globally unique. for target in [0x402c31c0,0x402bdd48,0x402e8cbc]: matches=[r for r in rows if r['address']==target and r['size'] and r['kind'] in ('t','T')] assert matches and len({r['size'] for r in matches}) == 1 decode(matches[0]) assert instructions[0x40242d14] == ('bl','0x402c31c0') assert instructions[0x40242d84] == ('bl','0x402e8cbc') assert instructions[0x40242de8] == ('bl','0x402c31c0') assert instructions[0x40242edc] == ('cmp','x14, #0x4, lsl #12') review=json.loads(reviewpath.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] raw={k:checked(v) for k,v in first['dumps'].items()} captures={c['name']:c for c in first['captures']} life=unpack(raw['lifecycle']) assert life[2]==4 and life[5]==1 bindings=unpack(raw['OS_K2100_WORKLOAD_BINDINGS']) assert bindings[:4]==[life[0],life[1],0,life[14]] locations={name:pick(name,True)['address'] for name in ['OS_K2100_WORKLOAD_BINDINGS','OS_K2100_WORKER_RECORDS','OS_K2045_PRIMARY_STACK']} for name in locations: if name in captures: assert captures[name]['val']==locations[name] profile_count=0x406e1408 assert any(r['address']==profile_count and r['size']==8 for r in rows) stack=0x70000000 cases=[];visited=set() def write_bytes(m,address,data): region,at=m.locate(address,len(data));region[at:at+len(data)]=data def fresh(): # Merge identical L3 captures by address, reject conflicting aliases. extras={} for name in ['stackPages1','stackPages2','stackPages3','stackL31','stackL32','stackL33']: address=captures[name]['val'];data=raw[name] assert address not in extras or extras[address]==data extras[address]=data m=Machine(instructions,[(base,initial),(stack,bytes(65536))]+list(extras.items()),{}) m.sp=stack+0x2000 write_bytes(m,locations['OS_K2100_WORKLOAD_BINDINGS'],raw['OS_K2100_WORKLOAD_BINDINGS']) write_bytes(m,locations['OS_K2100_WORKER_RECORDS'],raw['OS_K2100_WORKER_RECORDS']) return m def finish(m,label,start,stops,accepted,expect): m.writes.clear();end=m.run(start,stops,maximum=10000) assert (end==accepted)==expect,(label,hex(end)) # These slices may write their private stack but no global state. for a,n in m.writes: assert stack<=a and a+n<=stack+65536,(label,'unexpected global mutation',hex(a),n) visited.update(m.trace);cases.append(dict(label=label,accepted=expect,instructions=len(m.trace),stop=end)) def lifecycle(count,label,mutation=None,expect=False): m=fresh();m.assign('x20',count);m.assign('x23',life[0]);m.assign('x24',life[1]);m.assign('x28',1) # Entry is after real audit and BootOnline return checks, before loads # and comparisons of the binding/lifecycle snapshot. write_bytes(m,m.sp+0x68,raw['lifecycle'][88:536]) write_bytes(m,m.sp+0x30,pack(bindings[:4])) all_bindings=bindings[:count*4]+[0]*((4-count)*4) write_bytes(m,locations['OS_K2100_WORKLOAD_BINDINGS'],pack(all_bindings));m.write(profile_count,8,count) if mutation: mutation(m) finish(m,label,0x40242c74,{0x40242dfc,0x40242d2c,0x40242f24,0x40242f38},0x40242dfc,expect) for count in [1,2,4]: lifecycle(count,f'{count} CPU matching retained lifecycle',expect=True) lifecycle(count,f'{count} CPU lifecycle count drift',lambda m:m.assign('x20',count+1)) lifecycle(count,f'{count} CPU lifecycle phase drift',lambda m:m.assign('x28',2)) for field in range(4): lifecycle(count,f'{count} CPU primary binding field {field}',lambda m,i=field:m.write(m.sp+0x30+8*i,8,bindings[i]+1)) for cpu in range(count): for field in range(4): address=locations['OS_K2100_WORKLOAD_BINDINGS']+(cpu*4+field)*8 lifecycle(count,f'{count} CPU {cpu} retained binding field {field}',lambda m,a=address:m.write(a,8,m.read(a,8)+1)) # Each record is 56 bytes, phase at +16 and generation at +24. lifecycle(count,f'{count} CPU {cpu} not Online',lambda m,c=cpu:m.write(m.sp+0x68+c*56+16,8,3)) lifecycle(count,f'{count} CPU {cpu} zero generation',lambda m,c=cpu:(m.write(m.sp+0x68+c*56+24,8,0),m.write(locations['OS_K2100_WORKLOAD_BINDINGS']+(c*4+3)*8,8,0),m.write(m.sp+0x30+24,8,0) if c==0 else None)) for cpu in range(count,4): for field in range(4): lifecycle(count,f'{count} CPU inactive {cpu} nonzero field {field}',lambda m,c=cpu,f=field:m.write(locations['OS_K2100_WORKLOAD_BINDINGS']+(c*4+f)*8,8,1)) def primary(label,guard=1,low=0x20455052494d4c4f,high=0x20455052494d4849,expect=False): m=fresh();m.assign('x0',guard) address=locations['OS_K2045_PRIMARY_STACK'];m.write(address+4096,8,low);m.write(address+69624,8,high) finish(m,label,0x40242e0c,{0x40242e4c,0x40242e84},0x40242e4c,expect) primary('modeled primary guard and canaries match',expect=True) primary('primary guard helper refuses',guard=0) primary('primary low canary differs',low=0) primary('primary high canary differs',high=0) records=unpack(raw['OS_K2100_WORKER_RECORDS']) for count in [1,2,4]: def worker(label,mutation=None,expect=False): m=fresh();m.assign('x20',count) if mutation:mutation(m) finish(m,label,0x40242e4c,{0x40242e5c,0x40242d2c},0x40242e5c,expect) worker(f'{count} CPU captured worker guard inputs',expect=True) for cpu in range(1,count): row=locations['OS_K2100_WORKER_RECORDS']+cpu*256 base_address=records[cpu*32+6];pte=records[cpu*32+23] for label,address,value in [('wrong stack size',row+7*8,8192),('unaligned stack',row+6*8,base_address+8),('missing guard PTE',row+23*8,0),('mapped guard',pte,3),('low canary',base_address,0),('high canary',base_address+16384-8,0)]: worker(f'{count} CPU worker {cpu} {label}',lambda m,a=address,v=value:m.write(a,8,v)) report=dict(status='NATIVE_RESOURCE_GATES_COMPONENT_PASSED',guestAccepted=False,productAccepted=False, scope='Selected actual Image instruction slices validate retained lifecycle count/phase/bindings, nonzero Online generations, inactive rows, primary guard-helper result and canaries, and every secondary worker stack size/alignment/guard PTE/canary. Fixtures for 1/2 CPU slice the four-CPU short-run snapshot and are host models. Primary canaries/helper result are explicit modeled inputs. Earlier allocator audit/BootOnline validation, MMU helper semantics, whole-kernel execution and actual elapsed time are separate obligations. No guest evidence is changed.', preflight=art(prepath),review=art(reviewpath),image=pre['artifacts']['image'],function=body,cases=cases, selectedVisitedInstructions=len(visited),disassembly=disassembly,harness=art(out/'harness.py.txt'),interpreter=art(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),visited=len(visited)))) except Exception: import traceback (out/'report.json').write_text(json.dumps(dict(status='NATIVE_RESOURCE_GATES_COMPONENT_FAILED',guestAccepted=False,productAccepted=False,error=traceback.format_exc()),indent=2)+'\n') print(out/'report.json',file=sys.stderr) raise