mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
177 lines
7.1 KiB
Python
Executable File
177 lines
7.1 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Recover PF board policy from original Load instruction relocation operands."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import struct
|
|
import subprocess
|
|
|
|
R = 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 find_rustfmt() -> str:
|
|
if os.environ.get('RUSTFMT'):
|
|
return os.environ['RUSTFMT']
|
|
which = shutil.which('rustfmt')
|
|
if which:
|
|
return which
|
|
candidates = []
|
|
if os.environ.get('CARGO_HOME'):
|
|
candidates.append(Path(os.environ['CARGO_HOME']) / 'bin/rustfmt')
|
|
candidates.append(Path.home() / '.cargo/bin/rustfmt')
|
|
for candidate in candidates:
|
|
if candidate.is_file():
|
|
return str(candidate)
|
|
raise SystemExit('rustfmt not found; set RUSTFMT or add rustfmt to PATH')
|
|
|
|
|
|
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)
|
|
|
|
rm_obj = find_rm_object()
|
|
raw = rm_obj.read_bytes()
|
|
sha = hashlib.sha256(raw).hexdigest()
|
|
if sha != EXPECTED_SHA256:
|
|
raise SystemExit(f'{rm_obj}: sha256 mismatch ({sha} != {EXPECTED_SHA256})')
|
|
|
|
sections, by_name = parse_elf64(raw)
|
|
rel_idx = by_name['.rela.text']
|
|
rel_h = sections[rel_idx][1]
|
|
syms = load_symbols(raw, sections, rel_h[6])
|
|
fn = next((s for s in syms if s[0] == '_nv031218rm'), None)
|
|
if fn is None:
|
|
raise SystemExit('symbol _nv031218rm not found')
|
|
rel_entsize = rel_h[9] or 24
|
|
rels = {}
|
|
for i in range(rel_h[5] // rel_entsize):
|
|
r_offset, r_info, r_addend = struct.unpack_from('<QQq', raw, rel_h[4] + i * rel_entsize)
|
|
rels[r_offset] = (r_info >> 32, r_info & 0xFFFFFFFF, r_addend)
|
|
|
|
operands = []
|
|
for offset in (0x18E, 0x19B):
|
|
entry = rels.get(fn[2] + offset)
|
|
if entry is None:
|
|
raise SystemExit(f'missing relocation at _nv031218rm+0x{offset:x}')
|
|
r_sym, r_type, r_addend = entry
|
|
target = syms[r_sym]
|
|
if sections[target[1]][0] != '.rodata':
|
|
raise SystemExit(f'unexpected relocation section {sections[target[1]][0]!r} != .rodata')
|
|
if r_type != 11: # Original MOV/CMP signed32 immediate relocation.
|
|
raise SystemExit(f'unexpected relocation type {r_type} != 11')
|
|
operands.append(target[2] + r_addend)
|
|
|
|
start, end = operands[0] - 4, operands[1]
|
|
if start < 0 or end <= start or (end - start) % 4 != 0:
|
|
raise SystemExit(f'invalid board-ID table range [0x{start:x}..0x{end:x}]')
|
|
ro_h = sections[by_name['.rodata']][1]
|
|
rodata = raw[ro_h[4]:ro_h[4] + ro_h[5]]
|
|
data = rodata[start:end]
|
|
ids = list(struct.unpack('<' + str(len(data) // 4) + 'I', data))
|
|
if len(ids) != 314 or ids[0] != 0x1F8:
|
|
raise SystemExit(f'unexpected PF board-ID table: len={len(ids)} first=0x{ids[0]:x}')
|
|
|
|
generated = '// Original580 _nv031218 board-ID policy, see reports/gpu-pf-board-ids.json.\npub const IDS: &[u32] = &[' + ','.join(hex(n) for n in ids) + '];\n'
|
|
generated = subprocess.check_output(
|
|
[find_rustfmt(), '--edition', '2024', '--emit', 'stdout'],
|
|
input=generated,
|
|
text=True,
|
|
)
|
|
report = {
|
|
'original_rm_sha256': sha,
|
|
'section': '.rodata',
|
|
'offset': hex(start),
|
|
'end_exclusive': hex(end),
|
|
'entry_width': 4,
|
|
'instruction_evidence': 'reports/gpu-gv100-hal-audit-rea/_nv031218rm.rea.json',
|
|
'ids': ids,
|
|
'data_sha256': hashlib.sha256(data).hexdigest(),
|
|
'comparison': 'Original MOVZX reads only low16 of each u32 entry; initial ID is immediate0x1f8.',
|
|
}
|
|
out = R / 'src/nvidia/src/gpu/pf_board_ids.rs'
|
|
meta = R / 'reports/gpu-pf-board-ids.json'
|
|
if args.check:
|
|
if not out.is_file() or not meta.is_file():
|
|
raise SystemExit('Original PF board table files missing')
|
|
if out.read_text(encoding='utf-8') != generated or json.loads(meta.read_text(encoding='utf-8')) != report:
|
|
raise SystemExit('Original PF board table differs')
|
|
else:
|
|
out.parent.mkdir(parents=True, exist_ok=True)
|
|
meta.parent.mkdir(parents=True, exist_ok=True)
|
|
out.write_text(generated, encoding='utf-8')
|
|
meta.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
|
|
print('Original PF board policy verified:', len(ids), 'entries')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|