Files
nvdriver/tools/gpu_scan_packed_firmware.py

33 lines
2.7 KiB
Python

#!/usr/bin/env python3
"""Bounded packed-descriptor scan; matches are candidates, not HAL selection."""
from pathlib import Path
from elftools.elf.elffile import ELFFile
import zlib,json,struct,hashlib
R=Path(__file__).resolve().parents[1];P=Path('/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/nv-kernel.o_binary');OUT=R/'analysis/firmware-candidates';OUT.mkdir(parents=True,exist_ok=True)
files={str(p):p.read_bytes()for p in Path('/lib/firmware/nvidia/gv100').rglob('*.bin')};records=[];seen=set();candidates=0
with P.open('rb')as f:
e=ELFFile(f);ss=list(e.get_section_by_name('.symtab').iter_symbols());ro=e.get_section_index('.rodata');raw=e.get_section(ro).data()
for rel in e.get_section_by_name('.rela.rodata').iter_relocations():
offset=rel['r_offset'];s=ss[rel['r_info_sym']]
if s['st_shndx']!=ro or offset<8 or offset+16>len(raw):continue
size,stored=struct.unpack_from('<II',raw,offset-8);flags,reserved=struct.unpack_from('<II',raw,offset+8);storage=s['st_value']+rel['r_addend']
if flags not in [1,3,11] or not 128<=size<=8*1024*1024 or not 8<stored<=8*1024*1024 or not 0<=storage<=len(raw)-stored:continue
key=(storage,size,stored)
if key in seen:continue
seen.add(key);candidates+=1;compressed=raw[storage:storage+stored]
try:
decoder=zlib.decompressobj(-15);decoded=decoder.decompress(compressed,size+1)
if not decoder.eof or len(decoded)!=size:continue
except zlib.error:continue
matches=[]
for name,value in files.items():
where=value.find(decoded)
if where>=0:matches.append({'file':name,'decoded_in_file':where,'whole_decoded_bytes':size})
name=f'{offset-8+0x0111d660:x}';row={'descriptor':hex(offset-8+0x0111d660),'decoded_size':size,'stored_bytes':stored,'storage':hex(storage+0x0111d660),'flags':flags,'word20':reserved,'decoded_sha256':hashlib.sha256(decoded).hexdigest(),'installed_whole_payload_matches':matches}
if matches:
(OUT/(name+'.packed')).write_bytes(compressed);(OUT/(name+'.decoded')).write_bytes(decoded);row['packed_file']=str(OUT/(name+'.packed'));row['decoded_file']=str(OUT/(name+'.decoded'))
records.append(row)
(R/'reports/gpu-packed-firmware-candidates.json').write_text(json.dumps({'artifact_sha256':hashlib.sha256(P.read_bytes()).hexdigest(),'examined_candidates':candidates,'valid_deflate_descriptors':len(records),'records':records,'runtime_hal_selection_proven':False,'physical_gpu_access':False},indent=2)+'\n');print(json.dumps({'examined':candidates,'valid':len(records),'whole_match_descriptors':sum(bool(r['installed_whole_payload_matches'])for r in records)}))
for row in records:
if row['installed_whole_payload_matches']:print(row['descriptor'],row['decoded_size'],row['installed_whole_payload_matches'])