Files
nvdriver/tools/generate_pf_rom_source_oracle.py

75 lines
6.8 KiB
Python

#!/usr/bin/env python3
"""Original source-policy060180 and caller state commit in isolated RAM."""
from pathlib import Path
import argparse,hashlib,itertools,json,struct,warnings
warnings.filterwarnings('ignore',category=UserWarning,module='unicorn')
from elftools.elf.elffile import ELFFile
from unicorn import Uc,UC_ARCH_X86,UC_MODE_64,UC_HOOK_CODE
from unicorn.x86_const import *
R=Path(__file__).resolve().parents[1]
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--check',action='store_true',help='compare generated Rust vectors without rewriting them; refresh JSON evidence')
args=parser.parse_args()
P=Path('/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/nv-kernel.o_binary')
SHA='5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b';assert hashlib.sha256(P.read_bytes()).hexdigest()==SHA
TEXT=0x10000000;DATA=0x30000000;STACK=0x40000000;RODATA=0x50000000;STOP=0x60000000
names=['_nv059933rm', '_nv060180rm', '_nv060173rm', '_nv006018rm', '_nv005963rm', '_nv006019rm', '_nv060357rm', '_nv060341rm', '_nv060376rm', '_nv060374rm', '_nv060344rm', '_nv024179rm', '_nv024177rm', '_nv024175rm', '_nv023283rm', '_nv023282rm', '_nv023281rm', '_nv023280rm', '_nv023279rm']
with P.open('rb') as f:
e=ELFFile(f);symbols=list(e.get_section_by_name('.symtab').iter_symbols());syms={s.name:s for s in symbols};text=bytearray(e.get_section_by_name('.text').data());rodata=e.get_section_by_name('.rodata').data();tx=e.get_section_index('.text');rd=e.get_section_index('.rodata')
spans=[(syms[n]['st_value'],syms[n]['st_size']) for n in names]
for rel in e.get_section_by_name('.rela.text').iter_relocations():
off=rel['r_offset']
if not any(a<=off<a+size for a,size in spans):continue
sym=symbols[rel['r_info_sym']]
if sym.name=='__x86_indirect_thunk_rax':value=STOP+0x100+rel['r_addend']
else:
assert sym['st_shndx'] in (tx,rd,e.get_section_index('.bss')),(sym.name,sym['st_shndx'])
value=(TEXT if sym['st_shndx']==tx else RODATA if sym['st_shndx']==rd else 0x70000000)+sym['st_value']+rel['r_addend']
if rel['r_info_type']==2:
value-=TEXT+off
else:assert rel['r_info_type']==11
struct.pack_into('<i',text,off,value)
uc=Uc(UC_ARCH_X86,UC_MODE_64);uc.mem_map(TEXT,(len(text)+4095)&~4095);uc.mem_write(TEXT,bytes(text));uc.mem_map(RODATA,(len(rodata)+4095)&~4095);uc.mem_write(RODATA,rodata)
uc.mem_map(DATA,0x400000);uc.mem_map(STACK,0x10000);uc.mem_map(STOP,4096)
address=lambda n:TEXT+syms[n]['st_value']
def w32(a,v):uc.mem_write(a,struct.pack('<I',v))
def w64(a,v):uc.mem_write(a,struct.pack('<Q',v))
def ret(value):
rsp=uc.reg_read(UC_X86_REG_RSP);rip=struct.unpack('<Q',uc.mem_read(rsp,8))[0]
uc.reg_write(UC_X86_REG_RAX,value);uc.reg_write(UC_X86_REG_RSP,rsp+8);uc.reg_write(UC_X86_REG_RIP,rip)
BSS=0x70000000;uc.mem_map(BSS,0x10000)
vbios=DATA+0x20000;display=DATA+0x30000;child=DATA+0x40000;chip=DATA+0x50000;rm=DATA+0x51000;runtime=DATA+0x60000;interface=DATA+0x61000;vtable=DATA+0x62000
trace=[];current=None;stop=TEXT+(0x63ccfc9-0x616f810)
def hook(uc,pc,size,user):
if pc==STOP+0x100:uc.reg_write(UC_X86_REG_RIP,uc.reg_read(UC_X86_REG_RAX))
elif pc==address('_nv053907rm'):
offset=uc.reg_read(UC_X86_REG_RCX);assert offset==0x1580;trace.append([1,offset]);ret(current[6])
elif pc==STOP+0x200:
offset=uc.reg_read(UC_X86_REG_RSI);trace.append([2,offset]);assert offset in [0x80,0x625480,0x610490,0x610630],hex(offset);ret(current[7] if offset in [0x80,0x625480] else current[8])
elif pc==stop:uc.emu_stop()
uc.hook_add(UC_HOOK_CODE,hook)
def call(name,args):
for reg,value in zip([UC_X86_REG_RDI,UC_X86_REG_RSI,UC_X86_REG_RDX],args):uc.reg_write(reg,value)
uc.reg_write(UC_X86_REG_RSP,STACK+0xffe8);uc.reg_write(UC_X86_REG_RBP,STACK+0x8000);w64(STACK+0xffe8,STOP);uc.emu_start(address(name),STOP,count=50000);assert uc.reg_read(UC_X86_REG_RIP)==STOP
base=[0,0,1,0,1,9,1,0x100,7<<16];specs=[]
for i,vals in [(0,[0,1]),(1,[0,1,2,0xa5,0xff]),(2,[0,1]),(3,[0,1,2]),(4,[0,1]),(5,range(64)),(6,[0,1,2,3,0xffffffff]),(7,[0,1,0x100,0x200,0xffff0100]),(8,[0,5<<16,7<<16,0x1f<<16,0xffffffff])]:
for value in vals:c=base.copy();c[i]=value;specs.append(c)
for ip in [3,8,9,10,14,18,20,63]:
for strap in [0,1,2,3]:
for cap in [0,0x100]:
for ctl in [5<<16,7<<16]:c=base.copy();c[5:]=[ip,strap,cap,ctl];specs.append(c)
for cached in [0,1,2,0xa5,0xff]:
c=base.copy();c[0]=1;c[1]=cached;specs.append(c)
rows=[]
for current in specs:
initialized,cached,present,disabled,haschild,ip,strap,cap,ctl=current;uc.mem_write(DATA,bytes(0x70000));w32(chip+0x10,35);w32(rm+0x10,2);uc.mem_write(rm+0x12,struct.pack('<H',ip));call('_nv006018rm',[vbios,chip]);call('_nv005963rm',[display,rm,chip]);call('_nv006019rm',[child,chip,rm]);w64(DATA+0x1f70,display if present else 0);uc.mem_write(display+0x190a,bytes([disabled]));w64(display+0x1a70,child if haschild else 0);w64(display+0x3d38,runtime);w64(runtime+0x50,interface);w64(interface,vtable);w64(vtable+0x28,STOP+0x200);uc.mem_write(vbios+0x1728,bytes([initialized]));uc.mem_write(DATA+0x929,bytes([cached]));trace.clear()
frame=STACK+0x8000;uc.mem_write(frame+0x23,b'\x00');uc.reg_write(UC_X86_REG_RBP,frame);uc.reg_write(UC_X86_REG_RSP,STACK+0xf000);uc.reg_write(UC_X86_REG_R12,DATA);uc.reg_write(UC_X86_REG_R13,vbios);uc.emu_start(TEXT+(0x63ccf98-0x616f810),STOP,count=50000);assert uc.reg_read(UC_X86_REG_RIP)==stop
rows.append(dict(spec=list(current),queried=uc.mem_read(frame+0x23,1)[0],gpu929=uc.mem_read(DATA+0x929,1)[0],initialized=uc.mem_read(vbios+0x1728,1)[0],trace=list(trace)))
lines=['// Actual original060180/060173 + selected display/child methods and parent state commit.','const SOURCE_CASES: &[Case] = &[']
for c in rows:lines.append('Case { spec: '+str(c['spec'])+', queried: '+str(c['queried'])+', gpu929: '+str(c['gpu929'])+', initialized: '+str(c['initialized']).lower()+', count: '+str(len(c['trace']))+', trace: '+str(c['trace']+[[0,0]]*(3-len(c['trace'])))+' },')
lines.append('];');path=R/'src/nvidia/src/gpu/rom_source_vectors.rs';generated=('\n'.join(lines)+'\n').encode();matches=path.is_file() and path.read_bytes()==generated
if not args.check:path.write_bytes(generated)
(R/'reports/gpu-pf-rom-source-oracle.json').write_text(json.dumps(dict(artifact_sha256=SHA,functions=names,cases=len(rows),rows=rows,interceptions=['Two real register interfaces supplied values and exact ordered read addresses','No capability/map/policy/binding/parent decisions intercepted'],limits=['Exact original063ccf98..63ccfc9 caller window; source winner prefix outside this policy not executed','Actual binders and selected child/display callbacks execute for supplied factory-owned facts','Display interface callback is not claimed to be rawBAR0; actual ownership/interface mapping remains required','No native or physicalGPU execution']),indent=2)+'\n');print(len(rows),'original source-policy cases')
if args.check and not matches:raise SystemExit('Rust source policy vectors differ')