mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
229 lines
10 KiB
Python
229 lines
10 KiB
Python
#!/usr/bin/env python3
|
|
"""Extract original RM GV100 child order/presence; never execute target code."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import struct
|
|
|
|
ROOT = Path(__file__).resolve().parent.parent
|
|
EXPECTED_SHA256 = '5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b'
|
|
DEFAULT_ANALYSIS_ROOT = Path.home() / '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_generated_headers_dir() -> Path | None:
|
|
candidates = []
|
|
for env_name in ('NV_RS_OPEN_GPU_SRC', 'OPEN_GPU_ROOT'):
|
|
val = os.environ.get(env_name)
|
|
if val:
|
|
base = Path(val)
|
|
candidates.extend([base / 'src/nvidia/generated', base / 'nvidia/generated', base])
|
|
analysis = Path(os.environ.get('NV_RS_ANALYSIS_ROOT', str(DEFAULT_ANALYSIS_ROOT)))
|
|
candidates.append(analysis / 'reference/open-gpu-kernel-modules-580.178.04/src/nvidia/generated')
|
|
for candidate in candidates:
|
|
if candidate.is_dir():
|
|
return candidate
|
|
return None
|
|
|
|
|
|
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})')
|
|
|
|
names = {}
|
|
gen_dir = find_generated_headers_dir()
|
|
if gen_dir is None:
|
|
raise SystemExit(
|
|
'Cannot find 580.178.04 open-gpu-kernel-modules generated headers; '
|
|
'set NV_RS_OPEN_GPU_SRC or NV_RS_ANALYSIS_ROOT'
|
|
)
|
|
for source in sorted(gen_dir.glob('*.h')):
|
|
for name, value in re.findall(r'#define __nvoc_class_id_(\w+) (0x[0-9a-fA-F]+)', source.read_text(errors='replace')):
|
|
names[int(value, 16)] = name
|
|
if not names:
|
|
raise SystemExit(f'{gen_dir}: no __nvoc_class_id_* definitions found in generated headers')
|
|
|
|
sections, by_name = parse_elf64(raw)
|
|
sectionidx = by_name['.rodata']
|
|
ro_h = sections[sectionidx][1]
|
|
data = raw[ro_h[4]:ro_h[4] + ro_h[5]]
|
|
syms = load_symbols(raw, sections, by_name['.symtab'])
|
|
symbols = {s[0]: s for s in syms}
|
|
section_data = {sectionidx: data}
|
|
|
|
relocs = {}
|
|
for _rname, rh in sections:
|
|
if rh[1] == 4 and rh[7] == sectionidx: # SHT_RELA targeting .rodata
|
|
rsyms = load_symbols(raw, sections, rh[6])
|
|
entsize = rh[9] or 24
|
|
for i in range(rh[5] // entsize):
|
|
r_offset, r_info, r_addend = struct.unpack_from('<QQq', raw, rh[4] + i * entsize)
|
|
relocs[r_offset] = {
|
|
'symbol': rsyms[r_info >> 32][0],
|
|
'type': r_info & 0xFFFFFFFF,
|
|
'addend': r_addend,
|
|
}
|
|
|
|
start = 0x4C60EE0
|
|
presence_start = 0x4C63760
|
|
order = []
|
|
for i in range(100):
|
|
cls, flags = struct.unpack_from('<II', data, start + i * 8)
|
|
if not (cls < (1 << 24) and 0 < flags <= 15):
|
|
raise SystemExit(f'unexpected GV100 ORDER entry {i}: cls=0x{cls:x} flags=0x{flags:x}')
|
|
order.append({'class_id': cls, 'flags': flags, 'name': names.get(cls, f'class_{cls:06x}'), 'section_offset': start + i * 8})
|
|
|
|
presence = []
|
|
for i in range(75):
|
|
off = presence_start + i * 16
|
|
cls, n = struct.unpack_from('<II', data, off)
|
|
ref = relocs[off + 8]
|
|
sym = symbols[ref['symbol']]
|
|
raw_section = section_data.get(sym[1])
|
|
if raw_section is None:
|
|
raise SystemExit(f'symbol {sym[0]} is not in .rodata')
|
|
record = raw_section[sym[2]:sym[2] + sym[3]]
|
|
size, info_id = struct.unpack_from('<II', record)
|
|
if not (cls < (1 << 24) and info_id < (1 << 24) and 0 < n <= 256):
|
|
raise SystemExit(f'unexpected GV100 PRESENT entry {i}: cls=0x{cls:x} info=0x{info_id:x} n={n}')
|
|
presence.append({
|
|
'class_id': cls,
|
|
'instances': n,
|
|
'name': names.get(cls, f'class_{cls:06x}'),
|
|
'class_info_symbol': sym[0],
|
|
'class_object_size': size,
|
|
'concrete_class_id': info_id,
|
|
'class_info_bytes': record.hex(),
|
|
'class_info_relocations': [
|
|
{**rel, 'relative_offset': offset - sym[2]}
|
|
for offset, rel in relocs.items()
|
|
if sym[2] <= offset < sym[2] + sym[3]
|
|
],
|
|
'section_offset': off,
|
|
})
|
|
if len({x['class_id'] for x in presence}) != 75:
|
|
raise SystemExit('duplicate class_id in GV100 presence table')
|
|
|
|
def ordered(mask, reverse=False):
|
|
out = []
|
|
available = {x['class_id']: x['instances'] for x in presence}
|
|
for entry in (reversed(order) if reverse else order):
|
|
if entry['flags'] & mask != mask:
|
|
continue
|
|
rng = range(available.get(entry['class_id'], 0))
|
|
for instance in (reversed(rng) if reverse else rng):
|
|
out.append(entry['class_id'] << 8 | instance)
|
|
return out
|
|
|
|
phases = {n: ordered(mask, rev) for n, mask, rev in [('init', 1, False), ('load', 2, False), ('unload', 4, True), ('destroy', 8, True)]}
|
|
report = {
|
|
'source_sha256': sha,
|
|
'architecture': {'architecture': 0x14, 'implementation': 0, 'HAL_index': 0x23, 'evidence': '_nv006052rm + _nv005978rm'},
|
|
'order': {'source_function': '_nv030434rm', 'section': '.rodata', 'offset': start, 'record_size': 8, 'records': order},
|
|
'presence': {'source_function': '_nv030452rm', 'section': '.rodata', 'offset': presence_start, 'record_size': 16, 'records': presence},
|
|
'descriptor_encoding': '(class_id <<8)|instance; init/load forward; unload/destroy reverse including instances',
|
|
'phases': phases,
|
|
'limits': [
|
|
'Static GV100 monolithic class/HAL binding; no live register reads or boot writes.',
|
|
'Actual constructed engine availability can remove classes later; caller must check each engine object.',
|
|
'Class-info metadata layouts differ from public NVOCv2; raw records and relocations retained without guessing extra field names.',
|
|
],
|
|
}
|
|
code = (
|
|
'// Generated from original580.178.04 RM GV100 tables; see reports/gpu-gv100-tables.json.\n'
|
|
'use super::{ChildOrder,ChildPresence};\n'
|
|
'pub static ORDER:[ChildOrder;100]=[\n'
|
|
+ ''.join(' ChildOrder{class_id:0x%x,flags:0x%x}, // %s\n' % (x['class_id'], x['flags'], x['name']) for x in order)
|
|
+ '];\npub static PRESENT:[ChildPresence;75]=[\n'
|
|
+ ''.join(' ChildPresence{class_id:0x%x,concrete_class_id:0x%x,instances:%d,object_bytes:0x%x}, // %s %s\n' % (x['class_id'], x['concrete_class_id'], x['instances'], x['class_object_size'], x['name'], x['class_info_symbol']) for x in presence)
|
|
+ '];\n\n'
|
|
+ ''.join('pub static ' + name.upper() + '_DESCRIPTORS:[u32;' + str(len(values)) + ']=[' + ','.join(hex(x) for x in values) + '];\n' for name, values in phases.items())
|
|
)
|
|
output = ROOT / 'src/nvidia/src/gpu/gv100_data.rs'
|
|
if args.check:
|
|
if not output.is_file() or output.read_text(encoding='utf-8') != code:
|
|
raise SystemExit(f'Stale {output}')
|
|
else:
|
|
output.parent.mkdir(parents=True, exist_ok=True)
|
|
output.write_text(code, encoding='utf-8')
|
|
report_path = ROOT / 'reports/gpu-gv100-tables.json'
|
|
report_path.parent.mkdir(parents=True, exist_ok=True)
|
|
report_path.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
|
|
print('GV100', len(order), 'order rows', len(presence), 'present classes;', {k: len(v) for k, v in phases.items()})
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|