Files
nvdriver/tools/check_gpu_instances_binary.py

80 lines
4.0 KiB
Python

#!/usr/bin/env python3
"""Execute whole original031359 GPU-instance selection in private Unicorn RAM."""
import argparse
from _binary_path import resolve_580_binary
import hashlib
import json
from pathlib import Path
import random
import struct
import 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 UC_X86_REG_RDI, UC_X86_REG_RSP, UC_X86_REG_RIP, UC_X86_REG_RAX
parser = argparse.ArgumentParser()
parser.add_argument("--check", action="store_true")
options = parser.parse_args()
ROOT = Path(__file__).resolve().parents[1]
ARTIFACT = resolve_580_binary(verify=True)
TEXT, BSS, DATA, STACK, STOP = 0x10000000, 0x20000000, 0x30000000, 0x40000000, 0x50000000
with ARTIFACT.open('rb') as stream:
elf = ELFFile(stream)
symbols = list(elf.get_section_by_name('.symtab').iter_symbols())
names = {symbol.name: symbol for symbol in symbols}
function = names['_nv031359rm']
start, size = function['st_value'], function['st_size']
text = bytearray(elf.get_section_by_name('.text').data())
for relocation in elf.get_section_by_name('.rela.text').iter_relocations():
offset = relocation['r_offset']
if not start <= offset < start + size:
continue
symbol = symbols[relocation['r_info_sym']]
assert symbol.name == '_nv029075rm' and relocation['r_info_type'] == 2
assert elf.get_section(symbol['st_shndx']).name == '.bss'
target = BSS + symbol['st_value']
struct.pack_into('<i', text, offset, target + relocation['r_addend'] - (TEXT + offset))
system_pointer = BSS + names['_nv029075rm']['st_value']
uc = Uc(UC_ARCH_X86, UC_MODE_64)
for address, size_bytes in ((TEXT, (len(text) + 4095) & ~4095), (BSS, 4096),
(DATA, 0x50000), (STACK, 4096), (STOP, 4096)):
uc.mem_map(address, size_bytes)
uc.mem_write(TEXT, bytes(text))
uc.mem_write(system_pointer, struct.pack('<Q', DATA + 0x100))
manager = DATA + 0x1000
uc.mem_write(DATA + 0x100 + 0x1e0, struct.pack('<Q', manager))
uc.hook_add(UC_HOOK_CODE, lambda emu, address, length, user: emu.emu_stop() if address == STOP else None)
inputs = [list(range(count)) for count in range(33)]
inputs += [[i for i in range(32) if i != missing] for missing in range(32)]
rng = random.Random(0x580031359)
for _ in range(128):
row = rng.sample(range(32), rng.randrange(33))
rng.shuffle(row)
inputs.append(row)
rows = []
for live in inputs:
uc.mem_write(manager + 0x3f430, struct.pack('<I', len(live)))
for index, instance in enumerate(live):
uc.mem_write(manager + 0x3f230 + 16 * index, struct.pack('<QI', DATA + 0x40000, instance))
uc.mem_write(DATA, bytes.fromhex('a5a5a5a5'))
uc.mem_write(STACK + 0xff8, struct.pack('<Q', STOP))
uc.reg_write(UC_X86_REG_RSP, STACK + 0xff8)
uc.reg_write(UC_X86_REG_RDI, DATA)
uc.emu_start(TEXT + start, STOP, count=4096)
assert uc.reg_read(UC_X86_REG_RIP) == STOP
rows.append({'live': live, 'instance': struct.unpack('<I', uc.mem_read(DATA, 4))[0],
'status': uc.reg_read(UC_X86_REG_RAX) & 0xffffffff})
generated = '// Generated from whole original031359 instruction execution.\n#[rustfmt::skip]\nconst VECTORS:&[(&[u32],u32,u32)]=&[\n'
generated += ''.join(f'(&{row["live"]},{row["instance"]},{row["status"]}),\n' for row in rows) + '];\n'
destination = ROOT / 'src/nvidia/src/gpu/instances_vectors.rs'
if options.check:
assert destination.read_text() == generated, 'GPU-instance vectors drifted'
else:
destination.write_text(generated)
report = {'passed': True, 'artifact_sha256': hashlib.sha256(ARTIFACT.read_bytes()).hexdigest(),
'function': '_nv031359rm', 'cases': rows,
'scope': 'Whole original instructions, no helper interception. Private modeled SYS/GPUMGR memory; no native driver, GPU or hardware initialization execution.'}
(ROOT / 'reports/gpu-instances-binary.json').write_text(json.dumps(report, indent=2) + '\n')
print(len(rows), 'whole original GPU-instance selections')