Files
nvdriver/tools/timer-state-load-oracle.py

137 lines
9.1 KiB
Python

#!/usr/bin/env python3
"""Whole original059665/059564 and Linux049822 CPU-instruction differential vectors."""
from pathlib import Path
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,UC_HOOK_MEM_READ,UC_HOOK_MEM_WRITE
from unicorn.x86_const import *
opt=argparse.ArgumentParser();opt.add_argument('--check',action='store_true');args=opt.parse_args();R=Path(__file__).resolve().parents[1]
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;RO=0x18000000;DATA=0x30000000;STACK=0x40000000;STUB=0x50000000;STOP=0x60000000
with P.open('rb') as f:
e=ELFFile(f);ss=list(e.get_section_by_name('.symtab').iter_symbols());syms={s.name:s for s in ss};text=bytearray(e.get_section_by_name('.text').data());ro=e.get_section_by_name('.rodata').data();ti=e.get_section_index('.text');ri=e.get_section_index('.rodata');names=['_nv059665rm','_nv059564rm','_nv049822rm'];spans=[(syms[n]['st_value'],syms[n]['st_size'])for n in names];external={}
for rel in e.get_section_by_name('.rela.text').iter_relocations():
off=rel['r_offset']
if not any(a<=off<a+n for a,n in spans):continue
symbol=ss[rel['r_info_sym']]
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=external.setdefault(symbol.name,STUB+0x100+16*len(external))
else:raise AssertionError((symbol.name,symbol['st_shndx']))
value=target+rel['r_addend'];kind=rel['r_info_type'];assert kind in(2,4,11)
if kind in(2,4):value-=TEXT+off
struct.pack_into('<i',text,off,value)
u=Uc(UC_ARCH_X86,UC_MODE_64)
for addr,size in [(TEXT,len(text)),(RO,len(ro)),(DATA,0x50000),(STACK,0x10000),(STUB,0x10000),(STOP,4096)]:u.mem_map(addr,(size+4095)&~4095)
u.mem_write(TEXT,bytes(text));u.mem_write(RO,ro)
def address(n):return TEXT+syms[n]['st_value']
def w32(a,v):u.mem_write(a,struct.pack('<I',v))
def w64(a,v):u.mem_write(a,struct.pack('<Q',v))
def r32(a):return int.from_bytes(u.mem_read(a,4),'little')
def r64(a):return int.from_bytes(u.mem_read(a,8),'little')
def ret(value):
rsp=u.reg_read(UC_X86_REG_RSP);rip=r64(rsp);u.reg_write(UC_X86_REG_RSP,rsp+8);u.reg_write(UC_X86_REG_RAX,value);u.reg_write(UC_X86_REG_RIP,rip)
GPU=DATA;TIMER=DATA+0x10000;EVENT=DATA+0x20000;ALARM=DATA+0x30000
PENDING_A=STUB+0x8000;PENDING_C=STUB+0x8010;ENABLE_A=STUB+0x8020;ENABLE_C=STUB+0x8030
inverse={v:k for k,v in external.items()};events=[];variant=0;scripted=0;linux=True;now_calls=0;current_node=0
periods=[0,1,0x8000000000000000,0xffffffffffffffff]
def node(a):return (a-EVENT)//0x100+1 if EVENT<=a<EVENT+0x300 else 0
def nodeptr(n):return EVENT+(n-1)*0x100 if n else 0
def alarmptr(n):return ALARM+(n-1)*0x100 if n else 0
def alarmid(a):return (a-ALARM)//0x100+1 if ALARM<=a<ALARM+0x200 else 0
def snapshot():return [v for i in range(3)for v in [r32(EVENT+i*0x100+0x18),r64(EVENT+i*0x100+0x40),node(r64(EVENT+i*0x100+0x48))]]
def start_effects(n,delay):
global current_node
current_node=n;events.append([9,n,delay]);ptr=nodeptr(n);w32(ptr+0x18,0x5a5a0+n)
if n==1:
mode=(variant>>2)%3
if mode==1:w64(ptr+0x48,0)
if mode==2:w64(ptr+0x48,nodeptr(3))
if variant&64:w64(nodeptr(2)+0x10,0)
return scripted
def code(_,pc,size,user):
global now_calls
if pc in inverse:
name=inverse[pc]
if name.startswith('__x86_indirect_thunk_'):
u.reg_write(UC_X86_REG_RIP,u.reg_read(globals()['UC_X86_REG_'+name.rsplit('_',1)[-1].upper()]))
elif name=='nv_start_nano_timer':
assert u.reg_read(UC_X86_REG_RDI)==DATA+0x48000
n=node(u.reg_read(UC_X86_REG_RSI)-0x5000);assert n in(1,2,3)
ret(start_effects(n,u.reg_read(UC_X86_REG_RDX)))
else:raise AssertionError(name)
elif pc==address('_nv049086rm'):ret(GPU)
elif pc==address('_nv005245rm'):events.append([7,0,0]);ret(GPU)
elif pc==address('_nv049665rm'):
value=0x1234567800000000+now_calls*1000;now_calls+=1;events.append([5,0,value]);ret(value)
elif pc==address('_nv049822rm') and not linux:
n=node(u.reg_read(UC_X86_REG_RSI)-0x5000);ret(start_effects(n,u.reg_read(UC_X86_REG_RDX)))
elif pc in(PENDING_A,PENDING_C):
assert u.reg_read(UC_X86_REG_RDX)==0
pending=[0,1,0x100,0x101,0x80000000,0xff][variant%6];events.append([2,int(pc==PENDING_C),pending])
mutation=(variant>>4)%3
if mutation==1:w64(TIMER+0x250,0)
elif mutation==2:w64(TIMER+0x250,alarmptr(2))
if variant&32:w64(TIMER+0x258,nodeptr(3))
if variant&64:u.mem_write(TIMER+0x248,bytes([0 if r32(TIMER+0x248)&255 else 1]))
ret(pending)
elif pc==address('_nv016384rm'):
events.append([4,0,u.reg_read(UC_X86_REG_RDX)])
if variant&128:u.mem_write(TIMER+0x248,bytes([0 if r32(TIMER+0x248)&255 else 1]))
ret(0x65) # executed rearm's return is ignored by059665
elif pc in(ENABLE_A,ENABLE_C):events.append([6,int(pc==ENABLE_C),0]);ret(0x65)
elif pc==address('_nv047869rm'):
which=u.reg_read(UC_X86_REG_RSI);assert which in(0x740000,0x7d0000);events.append([12,int(which==0x7d0000),scripted if which==0x7d0000 else 0]);ret(0)
def memory_read(_,access,a,size,value,user):
if a==TIMER+0x250:events.append([0,0,alarmid(r64(a))])
elif a==TIMER+0x258:events.append([1,0,node(r64(a))])
elif a==TIMER+0x248:events.append([3,0,u.mem_read(a,1)[0]])
elif ALARM<=a<ALARM+0x200 and (a-ALARM)%0x100==0x38:events.append([13,alarmid(a-0x38),r64(a)])
elif EVENT<=a<EVENT+0x300:
n=node(a);off=(a-EVENT)%0x100
if off==0x38:events.append([14,n,r64(a)])
elif off==0x10:events.append([8,n,int(r64(a)!=0)])
elif off==0x18:events.append([10,n,r32(a)])
elif off==0x48:events.append([15,n,node(r64(a))])
def memory_write(_,access,a,size,value,user):
if EVENT<=a<EVENT+0x300:
n=node(a);off=(a-EVENT)%0x100
if off==0x40:events.append([16,n,value])
elif off==0x18:events.append([11,n,value&0xffffffff])
u.hook_add(UC_HOOK_CODE,code);u.hook_add(UC_HOOK_MEM_READ,memory_read);u.hook_add(UC_HOOK_MEM_WRITE,memory_write)
def prepare(v,s,is_linux):
global variant,scripted,linux,events,now_calls
variant=v;scripted=s;linux=is_linux;events=[];now_calls=0;u.mem_write(DATA,bytes(0x50000));w64(GPU+0x9d8,DATA+0x48000)
for off,ptr in [(0x1e8,PENDING_A),(0x208,PENDING_C),(0x1a0,ENABLE_A),(0x1f8,ENABLE_C)]:w64(TIMER+off,ptr)
w64(TIMER+0x250,alarmptr(1)if v&1 else 0);w64(TIMER+0x258,nodeptr(1)if(v>>1)%3 else 0);u.mem_write(TIMER+0x248,bytes([255 if v&8 else 0]));w64(ALARM+0x38,0x123400001234);w64(ALARM+0x100+0x38,0x987600009876)
for n in(1,2,3):
ptr=nodeptr(n);w64(ptr+0x10,ptr+0x5000 if(v+n)%5 else 0);w32(ptr+0x18,0x100*n+0x21);w64(ptr+0x38,periods[(v+n)%4]);w64(ptr+0x40,0xdead0000+n);w64(ptr+0x48,nodeptr(2)if n==1 and(v>>1)%3==2 else 0)
def call(name,params):
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,val in zip([UC_X86_REG_RDI,UC_X86_REG_RSI,UC_X86_REG_RDX],params):u.reg_write(reg,val)
w64(STACK+0xff00,STOP);u.reg_write(UC_X86_REG_RSP,STACK+0xff00);u.reg_write(UC_X86_REG_RBP,STACK+0x8000);u.emu_start(address(name),STOP,count=100000);assert u.reg_read(UC_X86_REG_RIP)==STOP
return u.reg_read(UC_X86_REG_RAX)&0xffffffff
cases=[]
for v in range(256):
for is_linux in [False,True]:
prepare(v,0x65,is_linux);status=call('_nv059665rm',[GPU,TIMER,0xa5a5a5a5]);assert status==0
cases.append(dict(spec=[v,int(is_linux)],ops=events,after=snapshot()))
helpers=[]
for present in [False,True]:
for delay in periods:
for status in [0,0x65]:
for is_linux in [False,True]:
prepare(0,status,is_linux);w64(EVENT+0x10,EVENT+0x5000 if present else 0);result=call('_nv059564rm',[TIMER,EVENT,delay]);helpers.append(dict(spec=[int(present),delay,status,int(is_linux)],status=result,ops=events,after=snapshot()))
lines=['// Whole original059665/059564, actualLinux049822 wrapper or explicit injected helper status.','const LOAD_CASES:&[LoadCase]=&[']
for c in cases:lines.append('LoadCase{spec:'+str(c['spec'])+',ops:&['+','.join('('+','.join(map(str,x))+')'for x in c['ops'])+'],after:'+str(c['after'])+'},')
lines+= ['];','const HELPER_CASES:&[HelperCase]=&[']
for c in helpers:lines.append('HelperCase{spec:'+str(c['spec'])+',status:'+str(c['status'])+',ops:&['+','.join('('+','.join(map(str,x))+')'for x in c['ops'])+'],after:'+str(c['after'])+'},')
lines.append('];');generated='\n'.join(lines)+'\n';out=R/'src/nvidia/src/gpu/timer/load_vectors.rs'
if args.check:assert out.read_text()==generated,'timer StateLoad vectors differ'
else:out.write_text(generated)
(R/'reports/timer-state-load-oracle.json').write_text(json.dumps(dict(artifact_sha256=SHA,load_cases=cases,helper_cases=helpers,scope='Whole original059665/059564 and actual Linux049822 wrapper. Hardware pending/rearm/enable, parent lookup, clock and OS timer primitive modeled; injected helper-return mode separately exercises original nonLinux/generic executed failure policy. No actual callbacks/GPU/event handles fabricated in production.'),indent=2)+'\n')
print(len(cases),'whole original StateLoad,',len(helpers),'OS-relative cases')