Files
nvdriver/tools/check_channel_binary_oracle.py

112 lines
8.2 KiB
Python
Executable File

#!/usr/bin/env python3
"""Emulate original exact580 channel predicates with register/lookup/log calls intercepted.
No GPU or native target execution. Relocations are linked into an isolated Unicorn memory image.
"""
import hashlib,json,struct,warnings
from pathlib import Path
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];P=Path('/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/nv-kernel.o_binary')
TEXT=0x10000000;DATA=0x30000000;STACK=0x40000000;STUB=0x50000000;STOP=0x60000000
names=['_nv027717rm','_nv028059rm','_nv028037rm','_nv018613rm','_nv040880rm','_nv040884rm'];functions={};hooks={};input_raw=0;reads=[];read_values=None;timeout_status=0;remove_on_timeout=False;helper_calls=[];writes=[]
with P.open('rb') as f:
e=ELFFile(f);sym=e.get_section_by_name('.symtab');symbols=list(sym.iter_symbols());text=bytearray(e.get_section_by_name('.text').data());section_index=e.get_section_index('.text');defined={s.name:s for s in symbols};at={TEXT+s['st_value']:s.name for s in symbols if s['st_info']['type']=='STT_FUNC' and s['st_shndx']==section_index};undef={}
for name in names:
s=defined[name];functions[name]=(s['st_value'],s['st_size'])
selected=lambda off:any(start<=off<start+size for start,size in functions.values())
for rel in e.get_section_by_name('.rela.text').iter_relocations():
off=rel['r_offset']
if not selected(off):continue
s=symbols[rel['r_info_sym']];kind=rel['r_info_type']
if s['st_shndx']==section_index:target=TEXT+s['st_value']
elif s['st_shndx']=='SHN_UNDEF':
target=undef.setdefault(s.name,STUB+0x100+len(undef)*16);hooks[target]=s.name
else:target=STUB+0x8000 # Non-dereferenced diagnostic data relocation.
assert kind in [2,4,11],(off,kind,s.name)
displacement=target+rel['r_addend']-(TEXT+off) if kind in [2,4] else target+rel['r_addend'];struct.pack_into('<i',text,off,displacement)
for address,name in at.items():
if name in ['_nv053907rm','_nv053912rm','_nv030608rm','_nv047869rm','_nv046745rm','_nv046764rm','_nv059492rm','_nv059509rm','_nv059505rm']:hooks[address]=name
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(DATA,0x60000);uc.mem_map(STACK,0x10000);uc.mem_map(STUB,0x10000);uc.mem_map(STOP,4096)
VIRTUAL=STUB+0x10
hooks[VIRTUAL]='resolve_engine'
hooks[STUB+0x20]='recover_gpu'
def ret(value):
sp=uc.reg_read(UC_X86_REG_RSP);target=struct.unpack('<Q',uc.mem_read(sp,8))[0];uc.reg_write(UC_X86_REG_RAX,value);uc.reg_write(UC_X86_REG_RSP,sp+8);uc.reg_write(UC_X86_REG_RIP,target)
def on_code(emu,address,size,user):
if address==STOP:emu.emu_stop();return
name=hooks.get(address)
if not name:return
if name.startswith('__x86_indirect_thunk_'):
assert name=='__x86_indirect_thunk_rax',name;emu.reg_write(UC_X86_REG_RIP,emu.reg_read(UC_X86_REG_RAX));return
if name=='_nv053907rm':
reads.append(emu.reg_read(UC_X86_REG_RCX));ret(input_raw if read_values is None else read_values[min(len(reads)-1,len(read_values)-1)])
elif name=='_nv053912rm':writes.append((emu.reg_read(UC_X86_REG_RCX),emu.reg_read(UC_X86_REG_R8)));ret(0)
elif name in ['_nv059492rm','_nv059509rm','_nv059505rm','recover_gpu']:
helper_calls.append(name)
if name=='_nv059505rm' and remove_on_timeout:emu.mem_write(DATA+0x915,b'\x00')
ret(timeout_status if name=='_nv059505rm' else 0)
elif name=='_nv030608rm':ret(DATA+0x10000)
elif name=='resolve_engine':emu.mem_write(emu.reg_read(UC_X86_REG_R9),struct.pack('<I',0));ret(0)
elif name in ['_nv047869rm','_nv046745rm','_nv046764rm']:ret(0)
else:raise AssertionError('Unexpected original call '+name)
uc.hook_add(UC_HOOK_CODE,on_code)
def put(offset,value):uc.mem_write(DATA+offset,struct.pack('<Q',value))
put(0x20000+0x470,DATA+0x30000);put(0x30000+0x274,7);put(0x20000+0x398,DATA+0x40000);put(0x40000+0x128,42);put(0x20000+0x128,42);put(0x10000+0x1b8,VIRTUAL)
def run(name,raw,args):
global input_raw,reads
input_raw=raw;reads=[]
for reg in [UC_X86_REG_RAX,UC_X86_REG_RBX,UC_X86_REG_RCX,UC_X86_REG_RDX,UC_X86_REG_RSI,UC_X86_REG_RDI,UC_X86_REG_R8,UC_X86_REG_R9,UC_X86_REG_R10,UC_X86_REG_R11,UC_X86_REG_R12,UC_X86_REG_R13,UC_X86_REG_R14,UC_X86_REG_R15]:uc.reg_write(reg,0)
uc.reg_write(UC_X86_REG_RSP,STACK+0xfff8);uc.mem_write(STACK+0xfff8,struct.pack('<Q',STOP));uc.reg_write(UC_X86_REG_RBP,STACK+0x8000)
for reg,value in zip([UC_X86_REG_RDI,UC_X86_REG_RSI,UC_X86_REG_RDX,UC_X86_REG_RCX,UC_X86_REG_R8],args):uc.reg_write(reg,value)
try:uc.emu_start(TEXT+functions[name][0],STOP,count=1000)
except Exception as error:raise RuntimeError((name,hex(uc.reg_read(UC_X86_REG_RIP)),hex(uc.reg_read(UC_X86_REG_RSP)),reads,writes,helper_calls)) from error
assert uc.reg_read(UC_X86_REG_RIP)==STOP
if name in names[:3]:assert reads==[{'_nv027717rm':0x800004+7*8,'_nv028059rm':0x3080+3*4,'_nv028037rm':0x2640}[name]],reads
return uc.reg_read(UC_X86_REG_RAX)&255
rows=[]
for state in range(16):
for bits in range(8):
raw=state<<24|(bits&1)|((bits>>1)&1)<<1|((bits>>2)&1)<<28
for mask in [0,1,2,4,8,16,32,64,127]:
for all_bits in [0,1]:rows.append((0,raw,mask,all_bits,run(names[0],raw,[DATA,0,DATA+0x20000,mask,all_bits])))
for state in range(8):
for is_tsg in range(2):
for next_valid in range(2):
for current_match in range(2):
for next_match in range(2):
raw=state<<13|is_tsg<<12|next_valid<<28|(42 if current_match else 43)|(42 if next_match else 43)<<16
rows.append((1,raw,0,0,run(names[1],raw,[DATA,0,3,DATA+0x20000])))
for state in range(8):
for is_tsg in range(2):
for current_match in range(2):
for next_match in range(2):
wanted=42 if is_tsg else 7;raw=state<<13|is_tsg<<12|(wanted if current_match else wanted+1)|(wanted if next_match else wanted+1)<<16
rows.append((2,raw,0,0,run(names[2],raw,[DATA,0,0x123400,DATA+0x20000])))
fault_pointer_vectors=[]
put(0x1f88,DATA+0x49000);put(0x49000+0x8e0,0x200)
for method,offset in [('_nv040880rm',0x100e2c),('_nv040884rm',0x100e30)]:
for queue in range(2):
for raw in [0,1,0xfffff,0xc0000005,0xffffffff]:
status=run(method,raw,[DATA,0,queue,DATA+0x48000]);pointer=struct.unpack('<I',uc.mem_read(DATA+0x48000,4))[0]
assert status==0 and pointer==raw&0xfffff and reads==[offset+0x200+queue*20]
fault_pointer_vectors.append({'method':method,'queue':queue,'raw':raw,'pointer':pointer,'register_offset':reads[0]})
# Original FB-flush trigger/wait control flow, with deterministic register/timer mocks.
fb_cases=[]
for label,values,expired,attached,remove in [
('clear',[0],0,True,False),('pending_then_clear',[1,2,0],0,True,False),
('expiry_then_clear',[1,0],0x65,True,False),('expiry_still_busy',[1],0x65,True,False),
('initial_detached',[1],0,False,False),('detached_during_wait',[1],0,True,True)]:
uc.mem_write(DATA+0x915,bytes([int(attached)]));put(0x1a0,STUB+0x20)
read_values=values;timeout_status=expired;remove_on_timeout=remove;helper_calls=[];writes=[]
result=run('_nv018613rm',0,[DATA]);assert writes==[(0x70000,1)]
assert helper_calls[:2]==['_nv059492rm','_nv059509rm']
fb_cases.append({'case':label,'status':result,'register_reads':reads,'register_writes':writes,'helper_calls':helper_calls})
assert [c['status'] for c in fb_cases]==[0,0,0,0x65,0,0]
assert [len(c['register_reads']) for c in fb_cases]==[1,3,2,4,0,2]
read_values=None
lines=['// Original machine instructions executed only in isolated Unicorn emulator.','pub type Vector = (u8, u32, u32, u8, bool);','#[rustfmt::skip]','pub const VECTORS:&[Vector]=&[']+[f'({k},{raw},{mask},{all_bits},{str(bool(out)).lower()}),' for k,raw,mask,all_bits,out in rows]+['];']
(R/'src/nvidia/src/mmu/channel_oracle_vectors.rs').write_text('\n'.join(lines)+'\n')
(R/'reports/channel-binary-oracle.json').write_text(json.dumps({'passed':True,'vectors':len(rows),'artifact_sha256':hashlib.sha256(P.read_bytes()).hexdigest(),'functions':{n:{'text_offset':hex(a),'bytes':size} for n,(a,size) in functions.items()},'FB_flush_cases':fb_cases,'fault_pointer_vectors':fault_pointer_vectors,'execution':'Isolated Unicorn x86_64 instruction emulation only; original register read, KernelFifo lookup, engine resolution, and diagnostics intercepted with mocks; no native target code or GPU executed'},indent=2)+'\n');print(len(rows),'original instruction-emulated channel vectors')