mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
166 lines
7.3 KiB
Python
166 lines
7.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Independently validate original selected GV100 Lpwr child+108 binding."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import struct
|
|
import subprocess
|
|
|
|
ROOT = Path(__file__).resolve().parent.parent
|
|
EXPECTED_SHA256 = '5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b'
|
|
DEFAULT_ANALYSIS_ROOT = Path('/home/geodd/nvidia-driver/analysis-580.178.04')
|
|
|
|
|
|
def find_rm_object() -> Path:
|
|
candidates = []
|
|
if os.environ.get('NV_RS_RM_OBJECT'):
|
|
candidates.append(Path(os.environ['NV_RS_RM_OBJECT']))
|
|
if os.environ.get('NV_RS_KERNEL_SRC'):
|
|
base = Path(os.environ['NV_RS_KERNEL_SRC'])
|
|
candidates.extend([base / 'nvidia/nv-kernel.o_binary', base])
|
|
analysis = Path(os.environ.get('NV_RS_ANALYSIS_ROOT', str(DEFAULT_ANALYSIS_ROOT)))
|
|
candidates.append(analysis / 'extracted/kernel/nvidia/nv-kernel.o_binary')
|
|
candidates.extend([
|
|
Path('/usr/src/nvidia-580.178.04/nvidia/nv-kernel.o_binary'),
|
|
Path('/usr/src/nvidia-srv-580.178.04/nvidia/nv-kernel.o_binary'),
|
|
])
|
|
for candidate in candidates:
|
|
if candidate.is_file():
|
|
return candidate
|
|
raise SystemExit('Cannot find 580.178.04 nv-kernel.o_binary; set NV_RS_RM_OBJECT or NV_RS_KERNEL_SRC')
|
|
|
|
|
|
def parse_elf64(raw: bytes):
|
|
if len(raw) < 64 or raw[:4] != b'\x7fELF' or raw[4] != 2 or raw[5] != 1:
|
|
raise SystemExit('nv-kernel.o_binary is not a valid 64-bit little-endian ELF file')
|
|
e_shoff, = struct.unpack_from('<Q', raw, 40)
|
|
e_shentsize, e_shnum, e_shstrndx = struct.unpack_from('<HHH', raw, 58)
|
|
sh0 = struct.unpack_from('<IIQQQQIIQQ', raw, e_shoff)
|
|
if e_shnum == 0:
|
|
e_shnum = sh0[5]
|
|
if e_shstrndx == 0xFFFF:
|
|
e_shstrndx = sh0[6]
|
|
hdrs = [struct.unpack_from('<IIQQQQIIQQ', raw, e_shoff + i * e_shentsize) for i in range(e_shnum)]
|
|
str_off, str_size = hdrs[e_shstrndx][4], hdrs[e_shstrndx][5]
|
|
shstr = raw[str_off:str_off + str_size]
|
|
sections = []
|
|
by_name = {}
|
|
for idx, h in enumerate(hdrs):
|
|
nul = shstr.find(b'\x00', h[0])
|
|
name = shstr[h[0]:nul if nul != -1 else len(shstr)].decode('utf-8', errors='replace')
|
|
sections.append((name, h))
|
|
by_name[name] = idx
|
|
return sections, by_name
|
|
|
|
|
|
def load_symbols(raw: bytes, sections, sym_idx: int):
|
|
_, h = sections[sym_idx]
|
|
entsize = h[9] or 24
|
|
str_h = sections[h[6]][1]
|
|
strtab = raw[str_h[4]:str_h[4] + str_h[5]]
|
|
ext = None
|
|
for _, sh in sections:
|
|
if sh[1] == 18 and sh[6] == sym_idx:
|
|
ext = struct.unpack_from(f'<{sh[5] // 4}I', raw, sh[4])
|
|
break
|
|
syms = []
|
|
for i in range(h[5] // entsize):
|
|
st_name, st_info, _st_other, st_shndx, st_value, st_size = struct.unpack_from('<IBBHQQ', raw, h[4] + i * entsize)
|
|
if st_shndx == 0xFFFF and ext is not None and i < len(ext):
|
|
st_shndx = ext[i]
|
|
nul = strtab.find(b'\x00', st_name)
|
|
name = strtab[st_name:nul if nul != -1 else len(strtab)].decode('utf-8', errors='replace')
|
|
syms.append((name, st_shndx, st_value, st_size, st_info & 0xF))
|
|
return syms
|
|
|
|
|
|
def main(argv=None) -> None:
|
|
p = argparse.ArgumentParser(description=__doc__)
|
|
p.add_argument('--check', action='store_true')
|
|
args = p.parse_args(argv)
|
|
|
|
source = find_rm_object()
|
|
raw_elf = source.read_bytes()
|
|
sha = hashlib.sha256(raw_elf).hexdigest()
|
|
if sha != EXPECTED_SHA256:
|
|
raise SystemExit(f'{source}: sha256 mismatch ({sha} != {EXPECTED_SHA256})')
|
|
|
|
sections, by_name = parse_elf64(raw_elf)
|
|
syms = load_symbols(raw_elf, sections, by_name['.symtab'])
|
|
by_name_sym = {s[0]: s for s in syms}
|
|
ro_h = sections[by_name['.rodata']][1]
|
|
rodata = raw_elf[ro_h[4]:ro_h[4] + ro_h[5]]
|
|
|
|
owner = by_name_sym['_nv003037rm']
|
|
child = by_name_sym['_nv002888rm']
|
|
owner_meta = struct.unpack_from('<II', rodata, owner[2])
|
|
child_meta = struct.unpack_from('<II', rodata, child[2])
|
|
if owner_meta != (0x1230, 0x112230) or child_meta != (0x13910, 0x8AE552):
|
|
raise SystemExit(f'unexpected Lpwr metadata: owner={owner_meta} child={child_meta}')
|
|
|
|
# Lpwr vtable base5160 has metadata003037; StateInit at+f0=042751.
|
|
rel_h = sections[by_name['.rela.rodata']][1]
|
|
rel_entsize = rel_h[9] or 24
|
|
rel = {}
|
|
for i in range(rel_h[5] // rel_entsize):
|
|
r_offset, r_info, _r_addend = struct.unpack_from('<QQq', raw_elf, rel_h[4] + i * rel_entsize)
|
|
rel[r_offset] = r_info >> 32
|
|
if syms[rel[0x4DC5160]][0] != '_nv003037rm':
|
|
raise SystemExit(f'unexpected vtable metadata symbol: {syms[rel[0x4DC5160]][0]}')
|
|
if syms[rel[0x4DC5250]][0] != '_nv042751rm':
|
|
raise SystemExit(f'unexpected vtable StateInit symbol: {syms[rel[0x4DC5250]][0]}')
|
|
|
|
method = by_name_sym['_nv019295rm']
|
|
text_h = sections[method[1]][1]
|
|
text = raw_elf[text_h[4]:text_h[4] + text_h[5]]
|
|
raw = text[method[2]:method[2] + method[3]]
|
|
if raw != bytes.fromhex('f30f1efac3'): # Original ENDBR64; RET.
|
|
raise SystemExit(f'unexpected _nv019295rm bytes: {raw.hex()}')
|
|
|
|
fixture = ROOT / 'tools/gpu_gv100_lpwr108_bindings_eval.c'
|
|
binary = ROOT / 'target/lpwr108-binding-oracle'
|
|
binary.parent.mkdir(parents=True, exist_ok=True)
|
|
subprocess.run(['cc', '-std=gnu11', '-O0', '-fno-strict-aliasing', str(fixture), '-o', str(binary)], check=True)
|
|
lines = subprocess.check_output([str(binary)], text=True).splitlines()
|
|
expected_lines = [
|
|
f'chip{chip:02x} RM{i} +108={fn}'
|
|
for chip, fn in [(0x23, '_nv019295rm'), (0x34, '_nv019288rm'), (0x3D, '_nv019290rm'), (0x3C, '_nv019294rm')]
|
|
for i in range(3)
|
|
]
|
|
if lines != expected_lines:
|
|
raise SystemExit(f'unexpected LPWR +108 oracle output: {lines}')
|
|
|
|
report = {
|
|
'source_sha256': sha,
|
|
'fixture_sha256': hashlib.sha256(fixture.read_bytes()).hexdigest(),
|
|
'owner_metadata': {'symbol': owner[0], 'bytes': owner_meta[0], 'class_id': hex(owner_meta[1]), 'public_name': 'Lpwr'},
|
|
'child_metadata': {'symbol': child[0], 'bytes': child_meta[0], 'class_id': hex(child_meta[1]), 'name': 'unresolved; use numeric class ID'},
|
|
'owner_original_vtable': {'section_offset': '0x4dc5160', 'state_init_offset': '0xf0', 'state_init_function': '_nv042751rm'},
|
|
'GV100_chip_HAL': '0x23',
|
|
'selected_runtime_bindings': lines[:3],
|
|
'other_chip_counterexamples': lines[3:],
|
|
'selected_function': '_nv019295rm',
|
|
'original_text_bytes': raw.hex(),
|
|
'limits': [
|
|
'Compiled literal inferred original HAL setter with address-only callbacks. No original constructor execution.',
|
|
'Original selected callback bytes are verified ENDBR64; RET, so no memory/state/IO effects.',
|
|
'Full Lpwr/child initialization and actual constructed input objects remain required elsewhere.',
|
|
'No hardware or original machine-code execution.',
|
|
],
|
|
}
|
|
out = ROOT / 'reports/gpu-gv100-lpwr108-oracle.json'
|
|
payload = json.dumps(report, indent=2) + '\n'
|
|
if args.check:
|
|
if not out.is_file() or out.read_text(encoding='utf-8') != payload:
|
|
raise SystemExit('Stale ' + str(out))
|
|
else:
|
|
out.parent.mkdir(parents=True, exist_ok=True)
|
|
out.write_text(payload, encoding='utf-8')
|
|
print('Original GV100 Lpwr child+108:3 RM bindings+9 other-chip counterexamples; exact ENDBR64/RET bytes verified')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|