Files
nvdriver/tools/check_mmu_initialization_binary.py

100 lines
7.4 KiB
Python

#!/usr/bin/env python3
"""Original selected format/levels/default getter and complete BAR2 instance bytes.
Private Unicorn execution only. Address/aperture/volatility getters are explicit
owned-descriptor models; no native driver, MMIO, root bind or TLB runs.
"""
import argparse,hashlib,json,struct,warnings
from _binary_path import resolve_580_binary
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 *
parser=argparse.ArgumentParser();parser.add_argument('--check',action='store_true');options=parser.parse_args()
R=Path(__file__).resolve().parents[1]
P=resolve_580_binary()
TEXT=0x10000000;RO=0x18000000;DATA=0x30000000;STACK=0x40000000;STUB=0x50000000;STOP=0x60000000
GPU=DATA;MMU=DATA+0x10000;FAMILY=DATA+0x20000;BUS=DATA+0x30000;INSTANCE=DATA+0x40000;LEVELS=DATA+0x50000;DESC=DATA+0x60000;FMT64=DATA+0x70000;FMT128=DATA+0x71000
names=['_nv040636rm','_nv040666rm','_nv040678rm','_nv005794rm','_nv040785rm','_nv054326rm','_nv030933rm','_nv031281rm'];hooks={}
with P.open('rb') as stream:
elf=ELFFile(stream);syms=list(elf.get_section_by_name('.symtab').iter_symbols());defined={s.name:s for s in syms}
text=bytearray(elf.get_section_by_name('.text').data());ro=elf.get_section_by_name('.rodata').data();ti=elf.get_section_index('.text');ri=elf.get_section_index('.rodata')
functions={n:(defined[n]['st_value'],defined[n]['st_size']) for n in names};undefined={}
for rel in elf.get_section_by_name('.rela.text').iter_relocations():
offset=rel['r_offset']
if not any(start<=offset<start+size for start,size in functions.values()):continue
symbol=syms[rel['r_info_sym']];kind=rel['r_info_type']
if symbol['st_shndx']==ti:target=TEXT+symbol['st_value']
elif symbol['st_shndx']==ri:target=RO+symbol['st_value']
elif symbol['st_shndx']=='SHN_UNDEF':
target=undefined.setdefault(symbol.name,STUB+0x100+len(undefined)*16);hooks[target]=symbol.name
else:target=STUB+0x8000
assert kind in(2,4,11)
value=target+rel['r_addend']-(TEXT+offset) if kind in(2,4) else target+rel['r_addend'];struct.pack_into('<i',text,offset,value)
for name in ['_nv047869rm','_nv047868rm','_nv046745rm','_nv046747rm','_nv040763rm','_nv040773rm','_nv052687rm','_nv052705rm','_nv040782rm','_nv043742rm','_nv049786rm']:
hooks[TEXT+defined[name]['st_value']]=name
u=Uc(UC_ARCH_X86,UC_MODE_64)
for base,size in [(TEXT,len(text)),(RO,len(ro)),(DATA,0x80000),(STACK,0x10000),(STUB,0x10000),(STOP,4096)]:u.mem_map(base,(size+4095)&~4095)
u.mem_write(TEXT,bytes(text));u.mem_write(RO,ro)
descriptor_address=0;descriptor_aperture=0;descriptor_volatile=0
def put(address,value):u.mem_write(address,struct.pack('<Q',value))
def ret(value):
sp=u.reg_read(UC_X86_REG_RSP);ip=struct.unpack('<Q',u.mem_read(sp,8))[0];u.reg_write(UC_X86_REG_RSP,sp+8);u.reg_write(UC_X86_REG_RAX,value);u.reg_write(UC_X86_REG_RIP,ip)
def hook(_,address,size,user):
name=hooks.get(address)
if not name:return
if name=='__x86_indirect_thunk_rax':u.reg_write(UC_X86_REG_RIP,u.reg_read(UC_X86_REG_RAX));return
if name=='_nv052687rm':assert u.reg_read(UC_X86_REG_RDI)==0x530;ret(FAMILY)
elif name=='_nv052705rm':u.mem_write(u.reg_read(UC_X86_REG_RDI),bytes(u.reg_read(UC_X86_REG_RDX)));ret(0)
elif name=='_nv049786rm':
a=u.reg_read(UC_X86_REG_RSI);raw=bytes(u.mem_read(a,80));key=raw.split(b'\x00')[0].decode();lookups.append(key)
status,value=registry.get(key,(0x40,0))
if status==0:u.mem_write(u.reg_read(UC_X86_REG_RDX),struct.pack('<I',value))
ret(status)
elif name in ['_nv047869rm','_nv047868rm','_nv046745rm','_nv046747rm']:ret(0)
elif name in ['_nv040763rm','_nv040773rm','_nv040782rm','_nv043742rm']:ret(0)
else:raise AssertionError('unexpected external '+name)
u.hook_add(UC_HOOK_CODE,hook)
def call(name,args):
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_R12,UC_X86_REG_R13,UC_X86_REG_R14,UC_X86_REG_R15]:u.reg_write(reg,0)
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,UC_X86_REG_R9],args):u.reg_write(reg,value)
u.reg_write(UC_X86_REG_RSP,STACK+0xfff8);put(STACK+0xfff8,STOP);u.reg_write(UC_X86_REG_RBP,STACK+0x8000)
u.emu_start(TEXT+functions[name][0],STOP,count=10000);assert u.reg_read(UC_X86_REG_RIP)==STOP
return u.reg_read(UC_X86_REG_RAX)
u.mem_write(STUB+0x9000,bytes.fromhex('31c0c3'))
policies=[]
for size in [0,127<<20,128<<20,249<<20,250<<20,16<<30,32<<30,1<<52,0xffffffffffffffff]:
for override in [0,65536,131072]:
for enabled in [0,1]:
for supported in [0,1]:
for per_address in [0,1]:
u.mem_write(DATA,bytes(0x80000));put(GPU+0x1ed0,INSTANCE);put(INSTANCE+0x820,size);put(MMU+0x4e0,override)
u.mem_write(GPU+0x92c,bytes([enabled]));u.mem_write(GPU+0x965,bytes([supported]));u.mem_write(MMU+0x4e8,bytes([per_address]))
registry={};lookups=[];assert call('_nv040636rm',[GPU,MMU])==0
big=struct.unpack('<Q',u.mem_read(MMU+0x498,8))[0];selected=u.mem_read(GPU+0x92c,1)[0]
policies.append([size,override,enabled,supported,per_address,big,selected])
registries=[]
for optimize in [0,1,2,3]:
for setting in [None,0,65536,131072,4096]:
for flags in [0,1,2,3,4,5,6,7]:
u.mem_write(DATA,bytes(0x80000));put(GPU+0x1ed0,INSTANCE);put(GPU+0x1e60,BUS)
u.mem_write(DATA+0x20000+16,struct.pack('<H',0x23));u.mem_write(GPU+0xd00,struct.pack('<II',0x140,0));u.mem_write(GPU+0x5318,struct.pack('<I',optimize))
u.mem_write(GPU+0x90e,bytes([bool(flags&1)]));u.mem_write(GPU+0x4de2,bytes([bool(flags&2)]));u.mem_write(BUS+0x54,bytes([bool(flags&4)]))
call('_nv005794rm',[MMU,DATA+0x20000]);put(MMU+0x1b0,TEXT+functions['_nv040785rm'][0])
for offset in [0x1c0,0x1a8,0x1a0,0x188,0x1c8]:put(MMU+offset,STUB+0x9000)
registry={'RmDisableBigPagePerAddressSpace':(0,0),'RmDisableMmuInvalidate':(0,1),'RmDisableHwFaultBuffer':(0,0x102),'RmForceFullSizeNRFaultBuffer':(0,1)}
if setting is not None:registry['RMFermiBigPageSize']=(0,setting)
lookups=[];assert call('_nv040666rm',[GPU,MMU])==0
def q(off):return struct.unpack('<Q',u.mem_read(MMU+off,8))[0]
registries.append([optimize,-1 if setting is None else setting,flags,q(0x4e0),u.mem_read(MMU+0x4e8,1)[0],u.mem_read(MMU+0x4e9,1)[0],u.mem_read(MMU+0x469,1)[0],u.mem_read(MMU+0x46b,1)[0],len(lookups),lookups])
report={'passed':True,'artifact_sha256':hashlib.sha256(P.read_bytes()).hexdigest(),'policies':policies,'registry_cases':registries,'scope':'Whole original040636 arithmetic/side effects; whole040666 registry policy with original005794/054326/030933/031281/040678/040785 and explicit allocation/aperture/format-construction callbacks. Format metadata algorithms independently covered by BAR2 format oracle. No physical GPU.'}
lines=['// Exact original MMU policy and constructor registry cases.','#[rustfmt::skip]','pub const POLICY: &[[u64;7]] = &[']
lines += [str(row)+',' for row in policies];lines+= ['];','#[rustfmt::skip]','pub const REGISTRY: &[[i64;9]] = &['];lines += [str(row[:9])+',' for row in registries];lines += ['];']
outputs={R/'reports/mmu-initialization-binary.json':json.dumps(report,indent=2)+'\n',R/'src/nvidia/src/mmu/init_vectors.rs':'\n'.join(lines)+'\n'}
for path,content in outputs.items():
if options.check:
if not path.exists() or path.read_text()!=content:raise SystemExit('Generated output differs: '+str(path))
else:path.write_text(content)
print(len(policies),'original MMU page policies and',len(registries),'constructor registry cases passed')