Files
nvdriver/tools/check_bar2_root_binary.py
nvidia-driver-rs 4526e6a816 Baseline: validated 30/30 tree with passing Level 7 hardware regression
- Updated tools/post_reboot.sh to check kernel oops taint bit and stuck driver tasks instead of <86400s uptime
- Level 7 hardware regression passed on 0000:b3:00.0 (module 37e6fa430835eee2b426019db3ad70eeb7a9e9070c09c84bd9b973cf56cbe529, 107 inventory words, 0 static mismatches, CUDA baseline verified before and after)
- Updated .gitignore to exclude build archives (*.a, *.rlib), __pycache__, and raw trace dumps
2026-11-23 23:48:38 +00:00

103 lines
7.8 KiB
Python

#!/home/geodd/.local/opt/rea-python/bin/python
"""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 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=Path('/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/nv-kernel.o_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=['_nv040785rm','_nv040762rm','_nv040755rm','_nv040786rm','_nv039298rm','_nv039476rm'];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 ['_nv043721rm','_nv040815rm','_nv043734rm','_nv047869rm','_nv046745rm']:
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=='_nv043721rm':assert u.reg_read(UC_X86_REG_RDI)==DESC;ret(descriptor_address)
elif name=='_nv040815rm':assert u.reg_read(UC_X86_REG_RSI)==DESC;ret(descriptor_aperture)
elif name=='_nv043734rm':assert u.reg_read(UC_X86_REG_RDI)==DESC;ret(descriptor_volatile)
elif name in ['_nv047869rm','_nv046745rm']:raise AssertionError('unexpected diagnostic '+name)
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)
support=[]
for version in list(range(9))+[0xffffffff]:
actual=call('_nv040785rm',[MMU,version])&255;assert actual==int(version==2);support.append([version,actual])
levels=[]
for big in [65536,131072]:
for base in [LEVELS,LEVELS+0x1000]:
u.mem_write(base,bytes(144));call('_nv040762rm',[MMU,base,6,2,big.bit_length()-1])
levels.append({'big_page':big,'base':base,'bytes':list(u.mem_read(base,144))})
getters=[]
put(MMU+0x4a8,0);put(MMU+0x4b0,FAMILY);put(MMU+0x4b8,0);put(FAMILY+0x520,FMT64);put(FAMILY+0x528,FMT128)
for actual_big in [0,4096,65536,131072]:
put(MMU+0x498,actual_big)
for version in [0,1,2,3,4]:
for requested in [0,4096,65536,131072]:
address=call('_nv040755rm',[MMU,version,requested]);selected=requested or actual_big or 65536
expected=({65536:FMT64,131072:FMT128}.get(selected,0) if version in[0,2] else 0);assert address==expected
getters.append([actual_big,version,requested,selected if address else 0])
instances=[]
put(GPU+0x1f90,MMU);put(BUS+0x4670,FMT64);u.mem_write(FMT64,struct.pack('<I',2));put(BUS+0x420,TEXT+functions['_nv039476rm'][0])
for descriptor_address in [0,0x100000,0x12345000,0x123456789000]:
for descriptor_aperture in [0,2,3]:
for descriptor_volatile in [0,1]:
for big in [65536,131072]:
for limit in [0xfffff,0x2003fff,(1<<49)-1]:
u.mem_write(INSTANCE,bytes([0x5a])*4096);call('_nv039298rm',[GPU,BUS,INSTANCE,DESC,limit,big]);data=list(u.mem_read(INSTANCE+0x200,16))
expected_low=(descriptor_address&0xfffff000)|descriptor_aperture|(descriptor_volatile<<2)|0x400|(0x800 if big==65536 else 0)
assert bytes(data)==struct.pack('<IIQ',expected_low,descriptor_address>>32,limit|4095)
instances.append({'address':descriptor_address,'aperture':descriptor_aperture,'volatile':bool(descriptor_volatile),'big_page':big,'limit':limit,'bytes':data})
report={'passed':True,'artifact_sha256':hashlib.sha256(P.read_bytes()).hexdigest(),'support':support,'levels':levels,'default_getters':getters,'instances':instances,'scope':'Whole original040785/040762/040755/040786/039298/039476 instructions. Real rodata version table. Only owned address/aperture/volatility getters mocked for instance inputs. No native code, actual BAR2 root bind, DMA, IRQ, TLB or hardware execution.'}
lines=['// Generated from exact580 original BAR2 format/instance instructions.','pub struct Levels {\n pub big_page: u64,\n pub base: u64,\n pub bytes: [u8; 144],\n}','pub struct Instance {\n pub address: u64,\n pub aperture: u32,\n pub volatile: bool,\n pub big_page: u64,\n pub limit: u64,\n pub bytes: [u8; 16],\n}','#[rustfmt::skip]','pub const SUPPORT: &[(u32,bool)] = &[']
for version,supported in support:lines.append(f'({version},{str(bool(supported)).lower()}),')
lines+= ['];','#[rustfmt::skip]','pub const LEVELS: &[Levels] = &[']
for row in levels:lines.append('Levels{big_page:%d,base:%d,bytes:%s},'%(row['big_page'],row['base'],row['bytes']))
lines+= ['];','#[rustfmt::skip]','pub const GETTERS: &[(u64,u32,u64,u64)] = &[']
for row in getters:lines.append('(%d,%d,%d,%d),'%tuple(row))
lines+= ['];','#[rustfmt::skip]','pub const INSTANCES: &[Instance] = &[']
for row in instances:lines.append('Instance{address:%d,aperture:%d,volatile:%s,big_page:%d,limit:%d,bytes:%s},'%(row['address'],row['aperture'],str(row['volatile']).lower(),row['big_page'],row['limit'],row['bytes']))
lines.append('];')
outputs={R/'reports/bar2-root-binary.json':json.dumps(report,indent=2)+'\n',R/'src/nvidia/src/mmu/bar2_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(support)+len(levels)+len(getters)+len(instances),'original BAR2 format/instance cases passed')