Files
nvdriver/tools/check_gpu_timer_init_binary.py

103 lines
7.8 KiB
Python

#!/usr/bin/env python3
"""Run original proprietary timer init; intercept only OS/MMIO/diagnostic leaves."""
import argparse,hashlib,itertools,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()
SHA='5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b'
assert hashlib.sha256(P.read_bytes()).hexdigest()==SHA
TEXT,DATA,STACK,STOP,RODATA=0x10000000,0x30000000,0x40000000,0x50000000,0x60000000
names=['_nv059663rm','_nv059661rm','_nv049684rm'];undefined={};bindings=[]
with P.open('rb') as stream:
e=ELFFile(stream);symbols=list(e.get_section_by_name('.symtab').iter_symbols());syms={s.name:s for s in symbols}
for n in names+['_nv006696rm','_nv059665rm','_nv003164rm']:
assert len([s for s in symbols if s.name==n])==1,('ambiguous symbol',n)
text=bytearray(e.get_section_by_name('.text').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]
# Prove static table identity from the real constructor's relocation, not
# the unrelated per-instance HAL slot offsets or the public GSP vtable.
rorels={r['r_offset']:r for r in e.get_section_by_name('.rela.rodata').iter_relocations()}
ctor=syms['_nv006696rm'];tables=[]
for rel in e.get_section_by_name('.rela.text').iter_relocations():
off=rel['r_offset'];symbol=symbols[rel['r_info_sym']]
if ctor['st_value']<=off<ctor['st_value']+ctor['st_size'] and symbol['st_shndx']==rd:
table=symbol['st_value']+rel['r_addend'];first=rorels.get(table)
if first and symbols[first['r_info_sym']].name=='_nv003164rm':
tables.append(table)
for slot,target in [(0x168,'_nv059663rm'),(0x178,'_nv059665rm')]:
record=rorels[table+slot];actual=symbols[record['r_info_sym']]
assert actual.name==target and record['r_addend']==0
bindings.append({'constructor':'_nv006696rm','relocation_text_offset':hex(off),'table_rodata_offset':hex(table),'slot':hex(slot),'target':target,'target_text_offset':hex(actual['st_value'])})
if not any(start<=off<start+size for start,size in spans):continue
if symbol['st_shndx']==tx:target=TEXT+symbol['st_value']
elif symbol['st_shndx']==rd:target=RODATA+symbol['st_value']
elif symbol['st_shndx']=='SHN_UNDEF':target=undefined.setdefault(symbol.name,STOP+0x100+len(undefined)*16)
else:raise AssertionError((symbol.name,symbol['st_shndx']))
value=target+rel['r_addend']
if rel['r_info_type'] in (2,4):value-=TEXT+off
else:assert rel['r_info_type']==11
struct.pack_into('<i',text,off,value)
assert len(tables)==1
uc=Uc(UC_ARCH_X86,UC_MODE_64)
for address,size in [(TEXT,(len(text)+4095)&~4095),(DATA,0x20000),(STACK,0x10000),(STOP,4096)]:uc.mem_map(address,size)
uc.mem_write(TEXT,bytes(text));GPU=DATA;TIMER=DATA+0x10000
hooks={TEXT+syms[n]['st_value']:n for n in ['_nv053907rm','_nv053912rm','_nv047869rm','_nv046745rm']}
hooks.update({address:name for name,address in undefined.items()})
events=[];time=(0,0);control=0;operation=0;busy_observations=[]
def w32(address,value):uc.mem_write(address,struct.pack('<I',value))
def w64(address,value):uc.mem_write(address,struct.pack('<Q',value))
def r32(address):return struct.unpack('<I',uc.mem_read(address,4))[0]
def ret(value):
sp=uc.reg_read(UC_X86_REG_RSP);pc=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,pc)
def hook(emu,pc,size,user):
if pc==STOP:emu.emu_stop();return
name=hooks.get(pc)
if name is None:return
if name=='__x86_indirect_thunk_rax':emu.reg_write(UC_X86_REG_RIP,emu.reg_read(UC_X86_REG_RAX));return
a,b,c,d,x,y=[emu.reg_read(reg) for reg in (UC_X86_REG_RDI,UC_X86_REG_RSI,UC_X86_REG_RDX,UC_X86_REG_RCX,UC_X86_REG_R8,UC_X86_REG_R9)]
busy_observations.append(r32(TIMER+0x2518))
if operation==1:assert busy_observations[-1]==1
if name=='_nv053907rm':
assert (a,b,c,d,x)==(GPU+0x4120,0,0,0x9430,0)
events.append((0,d,control));ret(control)
elif name=='_nv053912rm':
assert (a,b,c,y)==(GPU+0x4120,0,0,0)
assert d in (0x9410,0x9400);events.append((2,d,x&0xffffffff));ret(0x56)
elif name=='os_get_system_time':
w32(a,time[0]);w32(b,time[1]);events.append((1,*time));ret(0x56)
elif name=='_nv047869rm':
assert b in (0x4e0000,0x500000);events.append((3,b,0));ret(0)
elif name=='_nv046745rm':assert a==0x50;events.append((3,a,0));ret(0)
else:raise AssertionError(('unexpected helper',name))
uc.hook_add(UC_HOOK_CODE,hook)
times=[(0,0),(1,999999),(0xffffffff,999999),(0xffffffff,0xffffffff),(0x80000000,1)]
inputs=[(0,0,0,0,sec,usec,ctrl) for (sec,usec),ctrl in itertools.product(times,[0,16,0xffffffff])]
inputs += [(1,bits,mode,busy,sec,usec,ctrl) for bits,mode,busy,(sec,usec),ctrl in itertools.product(range(16),[0,4,5],[0,1,0xffffffff],times,[0,16,0xffffffff])]
rows=[]
for operation,bits,mode,busy,sec,usec,control in inputs:
events=[];busy_observations=[];time=(sec,usec)
uc.mem_write(DATA,bytes(0x20000));uc.mem_write(GPU+0x90b,bytes([bool(bits&1)]));uc.mem_write(GPU+0x998,bytes([bool(bits&4)]));w32(GPU+0x69e4,mode);uc.mem_write(GPU+0xe01,bytes([bool(bits&8)]));uc.mem_write(TIMER+0x24e,bytes([bool(bits&2)]));w32(TIMER+0x2518,busy);w64(TIMER+0x190,TEXT+syms['_nv059661rm']['st_value'])
uc.reg_write(UC_X86_REG_RDI,GPU);uc.reg_write(UC_X86_REG_RSI,TIMER);uc.reg_write(UC_X86_REG_RSP,STACK+0xfff8);uc.reg_write(UC_X86_REG_RBP,STACK+0x8000);w64(STACK+0xfff8,STOP)
entry=TEXT+syms[names[0 if operation else 1]]['st_value'];uc.emu_start(entry,STOP,count=2000);assert uc.reg_read(UC_X86_REG_RIP)==STOP
status=uc.reg_read(UC_X86_REG_RAX)&0xffffffff;final_busy=r32(TIMER+0x2518)
rows.append({'operation':operation,'bits':bits,'mode':mode,'initial_busy':busy,'seconds':sec,'microseconds':usec,'control':control,'status':status,'busy':final_busy,'events':events,'observed_busy_at_primitives':busy_observations})
assert len(rows)==2175
lines=['// Original timer StateInitLocked/program instructions and static vtable.','#[rustfmt::skip]','const CASES:&[Case]=&[']
for row in rows:
fields=', '.join(f'{key}: {row[key]}' for key in ['operation','bits','mode','initial_busy','seconds','microseconds','control','status','busy'])
ev=','.join('('+','.join(map(str,v))+')' for v in row['events'])
lines.append('Case { '+fields+', events:&['+ev+'] },')
generated='\n'.join(lines+["];",''])
path=R/'src/nvidia/src/gpu/timer/init_vectors.rs'
if options.check:assert path.read_text()==generated,'Original timer init vectors changed'
else:path.write_text(generated)
report={'passed':True,'artifact_sha256':SHA,'cases':len(rows),'bindings':bindings,'functions':names,'scope':'Original full programming/wrapper instructions, scripted MMIO/system-time and diagnostics. No native/hardware execution. Static vtable+168/+178 are separate from per-object HAL slots.','observations':['Original helper diagnostic return6b is discarded by wrapper, whose executed return is0.','Original callback busy marker is1 during primitives and cleared0 afterwards; early gated skip preserves initial marker.','Actual system-time and MMIO leaf return registers0x56 are ignored by original; replacement outer unavailability is a distinct safety state.'],'rows':rows}
(R/'reports/timer-init-original.json').write_text(json.dumps(report,indent=2)+'\n');print(len(rows),'original timer init cases; static init/load bindings verified')