Files
nvdriver/tools/gpu_generate_clock_object_metadata.py

184 lines
7.8 KiB
Python

#!/usr/bin/env python3
"""Exact580 original method identities and relocation-backed template headers."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import struct
ROOT = Path(__file__).resolve().parent.parent
EXPECTED_SHA256 = '5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b'
DEFAULT_ANALYSIS_ROOT = Path('/home/geodd/nvidia-driver/analysis-580.178.04')
METHOD_IDS = [
'021082', '021087', '021096', '021084', '021089', '021090', '021095',
'021080', '021094', '021085', '021088', '021079', '021081', '021083',
'021086', '021091', '021092', '021093', '020586', '020592', '021059',
]
def find_rm_object() -> Path:
env_rm = os.environ.get('NV_RS_RM_OBJECT')
if env_rm:
p = Path(env_rm)
if p.is_file():
return p
raise SystemExit(f'NV_RS_RM_OBJECT not found: {p}')
candidates = []
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)
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)
syms = load_symbols(raw, sections, by_name['.symtab'])
byname = {s[0]: s for s in syms}
rdidx = by_name['.rodata']
rd_h = sections[rdidx][1]
data = raw[rd_h[4]:rd_h[4] + rd_h[5]]
rel_h = sections[by_name['.rela.rodata']][1]
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_addend)
methods = {}
for n in METHOD_IDS:
s = byname['_nv' + n + 'rm']
if sections[s[1]][0] != '.text':
raise SystemExit(f'symbol {s[0]} is in {sections[s[1]][0]!r}, expected .text')
methods[n] = s[2]
noop = byname['_nv021089rm']
noop_h = sections[noop[1]][1]
noop_bytes = raw[noop_h[4] + noop[2]:noop_h[4] + noop[2] + noop[3]]
if noop_bytes != bytes.fromhex('f30f1efac3'):
raise SystemExit(f'unexpected _nv021089rm bytes: {noop_bytes.hex()}')
templates = []
for s in syms:
if s[1] != rdidx or s[3] != 64 or not s[0].startswith('_nv0213'):
continue
slots = []
for i in range(8):
off = s[2] + i * 8
v = rels.get(off)
if v is None:
if struct.unpack_from('<Q', data, off)[0] != 0:
raise SystemExit(f'non-zero unrelocated slot {i} in {s[0]}')
slots.append(None)
else:
target = syms[v[0]]
slots.append({'symbol': target[0], 'addend': v[1]})
if slots[0] != {'symbol': s[0], 'addend': 0}:
raise SystemExit(f'template {s[0]} is not self-linked at slot 0: {slots[0]}')
templates.append({'symbol': s[0], 'section_offset': hex(s[2]), 'slots': slots})
if len(templates) <= 20:
raise SystemExit(f'expected >20 clock object templates, found {len(templates)}')
deactivation = {n: v for n, v in methods.items() if n not in ('020586', '020592', '021059')}
replacements = {n: methods[n] for n in ('020586', '020592', '021059')}
unknown_template_callbacks = sorted(
{t['slots'][1]['symbol'] for t in templates if t['slots'][1]} - {'_nv' + n + 'rm' for n in deactivation}
)
if len(deactivation) != 18 or unknown_template_callbacks:
raise SystemExit(f'unexpected deactivation callbacks: count={len(deactivation)} unknown={unknown_template_callbacks}')
code = '// Generated from exact580 ELF .text offsets; arbitrary unknown bindings remain External.\nimpl OriginalMethod {\n pub fn from_580_text_offset(offset: u32) -> Self {\n match offset {\n'
for n, v in methods.items():
code += f' 0x{v:x} => Self::Nv{n},\n'
code += ' _ => Self::External,\n }\n }\n}\n'
report = {
'source_sha256': sha,
'method_text_offsets': {n: hex(v) for n, v in methods.items()},
'deactivation_method_offsets': {n: hex(v) for n, v in deactivation.items()},
'header_replacement_function_offsets': {n: hex(v) for n, v in replacements.items()},
'unknown_template_deactivation_callbacks': unknown_template_callbacks,
'original_noop_bytes': 'f30f1efac3',
'template_count': len(templates),
'templates': templates,
'limits': 'Original relocation-backed headers. Actual object-template and method token registry still must retain the constructed objects. No hardware execution.',
}
for out, text in [
(ROOT / 'src/nvidia/src/gpu/clock_object_methods.rs', code),
(ROOT / 'reports/gpu-clock-object-metadata.json', json.dumps(report, indent=2) + '\n'),
]:
if args.check:
if not out.is_file() or out.read_text(encoding='utf-8') != text:
raise SystemExit('Stale ' + str(out))
else:
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(text, encoding='utf-8')
print(f'Original clock-object metadata:{len(deactivation)}deactivation+{len(replacements)}header identities,{len(templates)}self-linked templates')
if __name__ == '__main__':
main()