Files
nvdriver/tools/check_gpu_clock_preinit_binary.py

81 lines
6.4 KiB
Python

#!/usr/bin/env python3
"""Execute actual original017001 and020551 instructions in private Unicorn RAM.
Only OS allocation/memset/registry/diagnostics/register leaf services scripted.
No physical GPU access or original-driver heap is consumed by Rust production.
"""
from pathlib import Path
from _binary_path import resolve_580_binary
import argparse,hashlib,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 *
p=argparse.ArgumentParser();p.add_argument('--check',action='store_true');options=p.parse_args()
R=Path(__file__).resolve().parents[1];P=resolve_580_binary()
TEXT=0x10000000;RO=0x18000000;DATA=0x24000000;STACK=0x40000000;STUB=0x50000000;STOP=0x60000000
names=['_nv017001rm','_nv020551rm','_nv029329rm']
with P.open('rb') as f:
e=ELFFile(f);symbols=list(e.get_section_by_name('.symtab').iter_symbols());defined={s.name:s for s in symbols};text=bytearray(e.get_section_by_name('.text').data());rodata=bytearray(e.get_section_by_name('.rodata').data());functions={n:(defined[n]['st_value'],defined[n]['st_size']) for n in names};maps={e.get_section_index('.text'):TEXT,e.get_section_index('.rodata'):RO,e.get_section_index('.data'):0x21000000,e.get_section_index('.bss'):0x22000000};undefined={};hooks={}
for name in ['_nv052687rm','_nv052701rm','_nv052705rm','_nv047869rm','_nv047868rm','_nv046745rm','_nv049786rm','_nv050291rm','_nv053907rm']:hooks[TEXT+defined[name]['st_value']]=name
for rel in e.get_section_by_name('.rela.text').iter_relocations():
off=rel['r_offset']
if not any(start<=off<start+size for start,size in functions.values()):continue
symbol=symbols[rel['r_info_sym']];kind=rel['r_info_type'];target=maps.get(symbol['st_shndx'])
if target is not None:target+=symbol['st_value']
elif symbol['st_shndx']=='SHN_UNDEF':target=undefined.setdefault(symbol.name,STUB+0x100+len(undefined)*16);hooks[target]=symbol.name
else:raise AssertionError(symbol.name)
value=target+rel['r_addend']-(TEXT+off) if kind in(2,4) else target+rel['r_addend']
if kind==1:struct.pack_into('<Q',text,off,value)
elif kind in(2,4,10,11):struct.pack_into('<I',text,off,value&0xffffffff)
else:raise AssertionError(kind)
uc=Uc(UC_ARCH_X86,UC_MODE_64)
for base,size in [(TEXT,len(text)),(RO,len(rodata)),(0x21000000,0x400000),(0x22000000,0x400000),(DATA,0x100000),(STACK,0x10000),(STUB,0x10000),(STOP,4096)]:uc.mem_map(base,(size+4095)&~4095)
uc.mem_write(TEXT,bytes(text));uc.mem_write(RO,bytes(rodata))
GPU=DATA;CLOCK=DATA+0x10000;MEMORY=DATA+0x20000;DISPLAY=DATA+0x30000;CHILD=DATA+0x40000;ARENA=DATA+0x50000
def put(address,value,width=8):uc.mem_write(address,value.to_bytes(width,'little'))
def ret(value=0):
sp=uc.reg_read(UC_X86_REG_RSP);target=int.from_bytes(uc.mem_read(sp,8),'little');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):
global next_alloc,allocations
if address==STOP:emu.emu_stop();return
name=hooks.get(address)
if name is None:return
args=[emu.reg_read(r) for r in [UC_X86_REG_RDI,UC_X86_REG_RSI,UC_X86_REG_RDX,UC_X86_REG_RCX,UC_X86_REG_R8]]
if name.startswith('__x86_indirect_thunk_'):emu.reg_write(UC_X86_REG_RIP,emu.reg_read(globals()['UC_X86_REG_'+name.split('_')[-1].upper()]));return
if name=='_nv052687rm':
index=allocations;allocations+=1
if index==fail_at:ret(0);return
result=next_alloc;next_alloc+=(args[0]+15)&~15;assert next_alloc<ARENA+0x30000;ret(result);return
if name=='_nv052701rm':ret();return
if name=='_nv052705rm':emu.mem_write(args[0],bytes([args[1]&255])*args[2]);ret(args[0]);return
if name=='_nv049786rm':
data=bytes(emu.mem_read(args[1],32)).split(b'\0')[0];index=[b'RmIsoHubMCLKSwitch',b'RMFBTrainingCMOS',b'RMFBTrainingCML'].index(data)
if missing&(1<<index):ret(0x51)
else:put(args[2],values[index],4);ret()
return
if name=='_nv053907rm':assert args[3]==0x1078;ret(strap);return
if name=='_nv050291rm':assert args[:4]==[GPU,0x12345678,4,1];ret();return
if name in ['_nv047869rm','_nv047868rm','_nv046745rm']:ret();return
raise AssertionError((name,args))
uc.hook_add(UC_HOOK_CODE,on_code)
rows=[]
for case in range(384):
pattern=0xa5 if case&1 else 0;fail_at=case%8 if case<64 else 99;missing=(case//8)%8;kind=[0,8,16,13][case%4];display_mode=(case//4)%3;mode=(case>>2)&1;skip=(case>>4)&1;strap=0x20 if case&32 else 0;count=case%4
values=[((case%16)|((case&3)<<4)|(((case*7)&255)<<8)|(((case*13)&255)<<16)),[0,0x200,0x400,0x800,0xe00][case%5],case*0x9e3779b9&0xffffffff]
uc.mem_write(DATA,bytes([pattern])*0x100000);uc.mem_write(STACK,bytes(0x10000));put(CLOCK+0x800,0);put(GPU+0x1ec0,MEMORY);put(GPU+0x2068,0x12345678);put(GPU+0x1f70,DISPLAY if display_mode else 0);put(DISPLAY+0x1ed8,CHILD if display_mode==2 else 0);put(MEMORY+0x4384,kind,4);put(MEMORY+0x4394,count,4);put(CLOCK+0x7e0,mode,1);put(GPU+0x921,skip,1)
next_alloc=ARENA;allocations=0
for reg in [UC_X86_REG_RAX,UC_X86_REG_RBX,UC_X86_REG_RCX,UC_X86_REG_RDX,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_RDI,GPU);uc.reg_write(UC_X86_REG_RSI,CLOCK);uc.reg_write(UC_X86_REG_RBP,STACK+0x8000);uc.reg_write(UC_X86_REG_RSP,STACK+0xfff8);put(STACK+0xfff8,STOP)
uc.emu_start(TEXT+functions['_nv020551rm'][0],STOP,count=100000);assert uc.reg_read(UC_X86_REG_RIP)==STOP
image=b''.join(bytes(uc.mem_read(base,length)) for base,length in [(GPU,0x2070),(CLOCK,0x1ec8),(MEMORY,0x5000),(DISPLAY,0x2000),(CHILD,0x500),(ARENA,0x30000)])
fnv=14695981039346656037
for byte in image:fnv=((fnv^byte)*1099511628211)&0xffffffffffffffff
rows.append((case,fnv,uc.reg_read(UC_X86_REG_RAX),allocations))
code='// Actual original020551/017001/029329 instructions, OS leaves scripted.\n#[rustfmt::skip]\nconst ORIGINAL_VECTORS:&[(u32,u64,u32,u32)]=&[\n'+''.join(f'({case},{h},{status},{allocations}),\n' for case,h,status,allocations in rows)+'];\n'
dest=R/'src/nvidia/src/gpu/clock_preinit_original_vectors.rs'
if options.check:assert dest.read_text()==code,'Original preinit vectors changed'
else:dest.write_text(code)
(R/'reports/gpu-clock-preinit-binary.json').write_text(json.dumps({'artifact_sha256':hashlib.sha256(P.read_bytes()).hexdigest(),'original_instruction_executions':len(rows),'actual_functions':names,'scripted_leaves':list(hooks.values()),'physical_gpu_access':False,'cases':rows},indent=2)+'\n')
print(len(rows),'actual original preinit executions')