Files
nvdriver/tools/gpu_generate_register_policy_oracle.py

180 lines
8.0 KiB
Python

#!/usr/bin/env python3
"""Compile literal original inferred C policy selectors, with relocation-backed tables."""
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:
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
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]
syms.append((st_shndx, st_value))
return syms
def main(argv=None) -> None:
check = argparse.ArgumentParser(description=__doc__)
check.add_argument('--check', action='store_true')
args = check.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)
data_h = sections[by_name['.data']][1]
data = raw_elf[data_h[4]:data_h[4] + data_h[5]]
syms = load_symbols(raw_elf, sections, by_name['.symtab'])
groups = [struct.unpack_from('<6I', data, 0x41120 + i * 24) for i in range(32)]
sub = [struct.unpack_from('<8I', data, 0x40C00 + i * 32) for i in range(41)]
rows = json.loads((ROOT / 'reports/gpu-gv100-hal-audit-diff.json').read_text(encoding='utf-8'))['rows']
bindings = {'0x740': '_nv030423rm', '0x750': '_nv030519rm', '0x768': '_nv030894rm', '0x6e8': '_nv031029rm'}
for variant in ('0', '1', '2'):
for slot, fn in bindings.items():
if rows[variant][slot] != fn:
raise SystemExit(f'HAL binding mismatch for variant {variant} slot {slot}: {rows[variant][slot]} != {fn}')
ro_h = sections[by_name['.rodata']][1]
rodata = raw_elf[ro_h[4]:ro_h[4] + ro_h[5]]
mo = 0x05DFE560 - 0x100000 - ro_h[3]
engine_keys = [struct.unpack_from('<II', rodata, mo + i * 8) for i in range(18)]
if any(region in [r for r, _k in engine_keys] for region in (0, 0x8B000)):
raise SystemExit('unexpected BIF fallback region found in region_engine_keys')
if groups[1] != (7, 0, 18, 15, 0, 0):
raise SystemExit(f'unexpected group7 row: {groups[1]}')
if sub[40] != (0xB33B1500, 0, 7, 5, 28, 15, 0, 0):
raise SystemExit(f'unexpected subtype sentinel row: {sub[40]}')
rel_h = sections[by_name['.rela.data']][1]
rel_entsize = rel_h[9] or 24
relocs = {}
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)
relocs[r_offset] = (r_info >> 32, r_addend)
descriptors = []
for i in range(21):
o = 0x46C40 + i * 24
region, _, _, count, _ = struct.unpack_from('<IIQII', data, o)
r_sym, r_addend = relocs[o + 8]
shndx, st_value = syms[r_sym]
if sections[shndx][0] != '.data':
raise SystemExit(f'unexpected region descriptor target section {sections[shndx][0]!r} != .data')
p = st_value + r_addend
pairs = [struct.unpack_from('<II', data, p + j * 8) for j in range(count)]
descriptors.append({'region': region, 'count': count, 'offset': p, 'pairs': pairs})
if next((x['pairs'] for x in descriptors if x['region'] == 0), None) != [(0x884E8, 0x44)]:
raise SystemExit('unexpected region 0 descriptor pairs')
if next((x['pairs'] for x in descriptors if x['region'] == 0x8B000), None) != [(0x8E000, 0x4B)]:
raise SystemExit('unexpected region 0x8b000 descriptor pairs')
# Kept source is reviewed literal inferred C, with harness helpers separate.
c = ROOT / 'tools/gpu_register_policy_oracle.c'
build = ROOT / 'target/register-policy-oracle'
build.parent.mkdir(parents=True, exist_ok=True)
subprocess.run(['cc', '-std=gnu11', '-O0', '-fno-strict-aliasing', str(c), '-o', str(build)], check=True)
result = subprocess.check_output([str(build)], text=True).strip().split()
if len(result) != 2:
raise SystemExit(f'unexpected oracle output: {result!r}')
output = '// Generated by tools/gpu_generate_register_policy_oracle.py; literal original C oracle.\n'
output += f'const ORIGINAL_POLICY_CASES: usize = {result[0]};\nconst ORIGINAL_POLICY_HASH: u64 = 0x{result[1]};\n'
report = {
'source_sha256': sha,
'oracle_c_sha256': hashlib.sha256(c.read_bytes()).hexdigest(),
'case_count': int(result[0]),
'fnv1a64': result[1],
'runtime_variant_bindings': bindings,
'region_engine_keys': [list(k) for k in engine_keys],
'bif_fallback_engine_key': '0xb33b1500',
'group7': list(groups[1]),
'subtype_sentinel': list(sub[40]),
'region_descriptors': [
{**d, 'pairs': [list(pair) for pair in d['pairs']]} for d in descriptors
],
'limits': 'Synthetic memory and recorded writes. Literal inferred original C, not execution of original machine code or hardware. Only physical BIF regions 0 and 0x8b000 translated.',
}
for path, text in [
(ROOT / 'src/nvidia/src/gpu/gv100_register_policy_oracle.rs', output),
(ROOT / 'reports/gpu-gv100-register-policy-oracle.json', json.dumps(report, indent=2) + '\n'),
]:
if args.check:
if not path.is_file() or path.read_text(encoding='utf-8') != text:
raise SystemExit(f'Stale {path}')
else:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding='utf-8')
print(f'Original register-policy oracle: {result[0]} cases; hash {result[1]}')
if __name__ == '__main__':
main()