Merge pull request #290 from morebrackets/fix/tools-table-generators-and-lpwr-check-portability

tools: make table generators and LPWR/error-policy checks portable and -O-safe
This commit is contained in:
Eric Hartford
2026-12-02 20:48:23 -08:00
committed by GitHub
7 changed files with 988 additions and 161 deletions

View File

@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""Offline tests for generate_rmapi_tables, generate_pf_board_ids,
generate_engine_discovery_tables, gpu_generate_legacy_hal_data,
gpu_check_lpwr108, and gpu_error_policy_table.
"""
import contextlib
import importlib.util
import io
import json
import os
from pathlib import Path
import shutil
import tempfile
import unittest
from unittest import mock
ROOT = Path(__file__).resolve().parents[2]
def _load(name: str, rel: str):
spec = importlib.util.spec_from_file_location(name, ROOT / rel)
mod = importlib.util.module_from_spec(spec)
assert spec.loader is not None
spec.loader.exec_module(mod)
return mod
class TableGeneratorsAndLpwrCheckTest(unittest.TestCase):
def test_all_six_scripts_are_import_safe(self):
for rel in (
"tools/generate_rmapi_tables.py",
"tools/generate_pf_board_ids.py",
"tools/generate_engine_discovery_tables.py",
"tools/gpu_generate_legacy_hal_data.py",
"tools/gpu_check_lpwr108.py",
"tools/gpu_error_policy_table.py",
):
mod = _load(Path(rel).stem, rel)
self.assertTrue(callable(mod.main))
def test_generate_rmapi_tables_check_fails_under_O_and_rejects_bad_cli(self):
mod = _load("generate_rmapi_tables", "tools/generate_rmapi_tables.py")
with contextlib.redirect_stderr(io.StringIO()):
with self.assertRaises(SystemExit) as ctx:
mod.main(["--bogus"])
self.assertEqual(ctx.exception.code, 2)
with tempfile.TemporaryDirectory() as tmp:
t = Path(tmp)
dossier = t / "dossier.json"
dossier.write_text(
json.dumps({
"class_defs": [{"name": "Obj", "classId": 0x1, "ancestors": []}],
"methods": [[0x101, "_nv000001rm", 0, 0, 4, "Obj", "m"]],
}),
encoding="utf-8",
)
target = t / "control_table.rs"
target.write_text("// stale\n", encoding="utf-8")
with mock.patch.object(mod, "DOSSIER", dossier), mock.patch.object(mod, "TARGET", target):
with self.assertRaisesRegex(SystemExit, "stale"):
mod.main(["--check"])
with contextlib.redirect_stdout(io.StringIO()):
mod.main([])
with contextlib.redirect_stdout(io.StringIO()):
mod.main(["--check"])
def test_find_rm_object_and_sha256_mismatch_under_O(self):
for rel in (
"tools/generate_pf_board_ids.py",
"tools/generate_engine_discovery_tables.py",
"tools/gpu_generate_legacy_hal_data.py",
"tools/gpu_check_lpwr108.py",
"tools/gpu_error_policy_table.py",
):
mod = _load(Path(rel).stem, rel)
with tempfile.TemporaryDirectory() as tmp:
fake = Path(tmp) / "nv-kernel.o_binary"
fake.write_bytes(b"corrupt")
with mock.patch.dict(os.environ, {"NV_RS_RM_OBJECT": str(fake)}, clear=True):
self.assertEqual(mod.find_rm_object(), fake)
with self.assertRaisesRegex(SystemExit, "sha256 mismatch"):
mod.main(["--check"])
def test_generate_pf_board_ids_portable_rustfmt_resolution(self):
mod = _load("generate_pf_board_ids", "tools/generate_pf_board_ids.py")
with mock.patch.dict(os.environ, {"RUSTFMT": "/custom/rustfmt"}, clear=True):
self.assertEqual(mod.find_rustfmt(), "/custom/rustfmt")
with tempfile.TemporaryDirectory() as tmp:
fake = Path(tmp) / "bin/rustfmt"
fake.parent.mkdir(parents=True)
fake.write_text("", encoding="utf-8")
with (
mock.patch.dict(os.environ, {"CARGO_HOME": tmp}, clear=True),
mock.patch.object(shutil, "which", return_value=None),
):
self.assertEqual(mod.find_rustfmt(), str(fake))
if __name__ == "__main__":
unittest.main()

View File

@ -1,22 +1,183 @@
#!/usr/bin/env python3
"""Extract exact580 immutable engine descriptor/type/name facts from original ELF."""
import hashlib,json,struct
import argparse
import hashlib
import json
import os
from pathlib import Path
from elftools.elf.elffile import ELFFile
R=Path(__file__).resolve().parents[1];P=Path('/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/nv-kernel.o_binary')
with P.open('rb') as f:
e=ELFFile(f);ss=list(e.get_section_by_name('.symtab').iter_symbols());defined={s.name:s for s in ss};data=e.get_section_by_name('.rodata').data();textrel=list(e.get_section_by_name('.rela.text').iter_relocations());rs={r['r_offset']:r for r in e.get_section_by_name('.rela.rodata').iter_relocations()}
def offset(name):
s=defined[name];r=[r for r in textrel if s['st_value']<=r['r_offset']<s['st_value']+s['st_size'] and ss[r['r_info_sym']]['st_shndx']==e.get_section_index('.rodata')];assert len(r)==1;(rel,)=r;return rel['r_addend']
meta_off=offset('_nv027854rm');dev_off=offset('_nv031279rm');rmrefs=[r for r in textrel if defined['_nv031280rm']['st_value']<=r['r_offset']<defined['_nv031280rm']['st_value']+defined['_nv031280rm']['st_size'] and ss[r['r_info_sym']]['st_shndx']==e.get_section_index('.rodata')];rm_off=min(r['r_addend'] for r in rmrefs)
device=list(struct.unpack_from('<23I',data,dev_off));metadata=[]
for i in range(15):
off=meta_off+i*24;desc,rc,mc,reserved=struct.unpack_from('<4I',data,off);assert reserved==0;start=rs[off+16]['r_addend'];name=data[start:data.index(b'\0',start)];assert len(name)<16;metadata.append((desc,rc,mc,name.decode()))
rms=[]
for i in range(57):
rm,cls,instance,reserved=struct.unpack_from('<4I',data,rm_off+i*16);rms.append(((cls<<8|instance)&0xffffffff,rm))
assert rms[0][0]==0xd334df00
lines=['// Exact original ELF facts; tools/generate_engine_discovery_tables.py.','use super::Metadata;','#[rustfmt::skip]','pub const DEVICE_CLASS_MAP: [u32;23] = ['+','.join(hex(x) for x in device)+'];','#[rustfmt::skip]','pub const METADATA: [Metadata;15] = [']
for desc,rc,mc,name in metadata:lines.append('Metadata { descriptor:0x%x, rc_mask:0x%x, mc_index:0x%x, name:*b"%s" },'%(desc,rc,mc,name+'\\0'*(16-len(name))))
lines+= ['];','#[rustfmt::skip]','pub const RM_TYPES: &[(u32,u32)] = &['+','.join('(0x%x,0x%x)'%x for x in rms)+'];']
(R/'src/nvidia/src/mmu/engine_discovery_data.rs').write_text('\n'.join(lines)+'\n');(R/'reports/engine-discovery-data.json').write_text(json.dumps({'artifact_sha256':hashlib.sha256(P.read_bytes()).hexdigest(),'source_relocation_functions':['_nv027854rm','_nv031279rm','_nv031280rm'],'rodata_offsets':{'engine_metadata':hex(meta_off),'device_classes':hex(dev_off),'RM_engine_types':hex(rm_off)},'metadata':metadata,'device_classes':device,'RM_engine_types':rms},indent=2)+'\n');print('Extracted15 engine metadata,23 device classes,57 RM types')
import struct
R = Path(__file__).resolve().parents[1]
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 load_relas(raw: bytes, sections, idx: int):
_, h = sections[idx]
entsize = h[9] or 24
out = []
for i in range(h[5] // entsize):
r_offset, r_info, r_addend = struct.unpack_from('<QQq', raw, h[4] + i * entsize)
out.append((r_offset, r_info >> 32, r_info & 0xFFFFFFFF, r_addend))
return out
def main(argv=None) -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--check', action='store_true', help='fail if generated table/report differ')
args = parser.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'])
defined = {s[0]: s for s in syms}
ro_idx = by_name['.rodata']
ro_h = sections[ro_idx][1]
data = raw[ro_h[4]:ro_h[4] + ro_h[5]]
textrel = load_relas(raw, sections, by_name['.rela.text'])
rs = {r[0]: r for r in load_relas(raw, sections, by_name['.rela.rodata'])}
def offset(name: str) -> int:
s = defined[name]
matches = [r for r in textrel if s[2] <= r[0] < s[2] + s[3] and syms[r[1]][1] == ro_idx]
if len(matches) != 1:
raise SystemExit(f'expected 1 .rodata relocation in {name}, found {len(matches)}')
return matches[0][3]
meta_off = offset('_nv027854rm')
dev_off = offset('_nv031279rm')
fn_rm = defined['_nv031280rm']
rmrefs = [r for r in textrel if fn_rm[2] <= r[0] < fn_rm[2] + fn_rm[3] and syms[r[1]][1] == ro_idx]
if not rmrefs:
raise SystemExit('no .rodata relocations found in _nv031280rm')
rm_off = min(r[3] for r in rmrefs)
device = list(struct.unpack_from('<23I', data, dev_off))
metadata = []
for i in range(15):
off = meta_off + i * 24
desc, rc, mc, reserved = struct.unpack_from('<4I', data, off)
if reserved != 0:
raise SystemExit(f'unexpected non-zero reserved word {reserved} in metadata[{i}]')
start = rs[off + 16][3]
name = data[start:data.index(b'\0', start)]
if len(name) >= 16:
raise SystemExit(f'engine metadata name too long: {name!r}')
metadata.append((desc, rc, mc, name.decode()))
rms = []
for i in range(57):
rm, cls, instance, _reserved = struct.unpack_from('<4I', data, rm_off + i * 16)
rms.append(((cls << 8 | instance) & 0xFFFFFFFF, rm))
if rms[0][0] != 0xD334DF00:
raise SystemExit(f'unexpected first RM engine descriptor: 0x{rms[0][0]:x}')
lines = [
'// Exact original ELF facts; tools/generate_engine_discovery_tables.py.',
'use super::Metadata;',
'#[rustfmt::skip]',
'pub const DEVICE_CLASS_MAP: [u32;23] = [' + ','.join(hex(x) for x in device) + '];',
'#[rustfmt::skip]',
'pub const METADATA: [Metadata;15] = [',
]
for desc, rc, mc, name in metadata:
lines.append('Metadata { descriptor:0x%x, rc_mask:0x%x, mc_index:0x%x, name:*b"%s" },' % (desc, rc, mc, name + '\\0' * (16 - len(name))))
lines += [
'];',
'#[rustfmt::skip]',
'pub const RM_TYPES: &[(u32,u32)] = &[' + ','.join('(0x%x,0x%x)' % x for x in rms) + '];',
]
code = '\n'.join(lines) + '\n'
report = {
'artifact_sha256': sha,
'source_relocation_functions': ['_nv027854rm', '_nv031279rm', '_nv031280rm'],
'rodata_offsets': {'engine_metadata': hex(meta_off), 'device_classes': hex(dev_off), 'RM_engine_types': hex(rm_off)},
'metadata': [list(m) for m in metadata],
'device_classes': device,
'RM_engine_types': [list(r) for r in rms],
}
target = R / 'src/nvidia/src/mmu/engine_discovery_data.rs'
meta_path = R / 'reports/engine-discovery-data.json'
if args.check:
if not target.is_file() or target.read_text(encoding='utf-8') != code:
raise SystemExit('engine_discovery_data.rs differs')
if not meta_path.is_file() or json.loads(meta_path.read_text(encoding='utf-8')) != report:
raise SystemExit('reports/engine-discovery-data.json differs')
else:
target.parent.mkdir(parents=True, exist_ok=True)
meta_path.parent.mkdir(parents=True, exist_ok=True)
target.write_text(code, encoding='utf-8')
meta_path.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
print('Extracted15 engine metadata,23 device classes,57 RM types')
if __name__ == '__main__':
main()

View File

@ -1,30 +1,176 @@
#!/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 argparse,hashlib,json,struct,subprocess
from elftools.elf.elffile import ELFFile
R=Path(__file__).resolve().parent.parent
B=Path('/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/nv-kernel.o_binary')
p=argparse.ArgumentParser();p.add_argument('--check',action='store_true');args=p.parse_args()
with B.open('rb') as f:
e=ELFFile(f);symbols=e.get_section_by_name('.symtab')
fn=next(s for s in symbols.iter_symbols() if s.name=='_nv031218rm')
rel=e.get_section_by_name('.rela.text');sym=e.get_section(rel['sh_link'])
operands=[]
for offset in [0x18e,0x19b]:
r=next(r for r in rel.iter_relocations() if r['r_offset']==fn['st_value']+offset)
target=sym.get_symbol(r['r_info_sym']);assert e.get_section(target['st_shndx']).name=='.rodata'
assert r['r_info_type']==11 # Original MOV/CMP signed32 immediate relocation.
operands.append(target['st_value']+r['r_addend'])
start,end=operands[0]-4,operands[1]
assert (end-start)%4==0
data=e.get_section_by_name('.rodata').data()[start:end]
ids=list(struct.unpack('<'+str(len(data)//4)+'I',data));assert len(ids)==314 and ids[0]==0x1f8
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([str(Path.home()/'.cargo/bin/rustfmt'),'--edition','2024','--emit','stdout'],input=generated,text=True)
report={'original_rm_sha256':hashlib.sha256(B.read_bytes()).hexdigest(),'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 out.read_text()!=generated or json.loads(meta.read_text())!=report:raise SystemExit('Original PF board table differs')
else:out.write_text(generated);meta.write_text(json.dumps(report,indent=2)+'\n')
print('Original PF board policy verified:',len(ids),'entries')
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()

View File

@ -5,69 +5,90 @@ The dossier's `methods` and `class_defs` arrays are decodes of the original's
NVOC_EXPORTED_METHOD_DEF arrays and class definitions (relocation records of
nv-kernel.o_binary 580.178.04; see analysis/closed-driver-580/rmapi-userspace.md 2.3).
"""
import argparse
import json
from pathlib import Path
import sys
ROOT = Path(__file__).resolve().parents[1]
DOSSIER = ROOT / "analysis/closed-driver-580/rmapi-userspace.json"
TARGET = ROOT / "src/nvidia/src/rmapi/control_table.rs"
data = json.loads(DOSSIER.read_text())
class_ids = {entry["name"]: entry["classId"] for entry in data["class_defs"]}
def class_of(owner):
return class_ids[owner] if owner in class_ids else int(owner, 16)
def render_table(data: dict) -> tuple[str, int, int]:
class_ids = {entry["name"]: entry["classId"] for entry in data["class_defs"]}
def class_of(owner):
return class_ids[owner] if owner in class_ids else int(owner, 16)
methods = sorted(
(class_of(owner), method, flags, access, size, int(handler[3:-2]))
for method, handler, flags, access, size, owner, _name in data["methods"]
)
lines = [
"//! Exported control methods and NVOC class ancestry of the original (580.178.04).",
"//! Generated by tools/generate_rmapi_tables.py from the RM API dossier; do not edit.",
"",
"/// One `NVOC_EXPORTED_METHOD_DEF`: `class` is the NVOC class id whose table holds it,",
"/// `handler` the number in the original symbol `_nv<handler>rm`.",
"#[derive(Clone, Copy, Debug, PartialEq, Eq)]",
"pub struct ControlMethod {",
" pub class: u32,",
" pub id: u32,",
" pub flags: u32,",
" pub access_right: u32,",
" pub param_size: u32,",
" pub handler: u32,",
"}",
"const fn m(",
" class: u32,",
" id: u32,",
" flags: u32,",
" access_right: u32,",
" param_size: u32,",
" handler: u32,",
") -> ControlMethod {",
" ControlMethod {",
" class,",
" id,",
" flags,",
" access_right,",
" param_size,",
" handler,",
" }",
"}",
"/// Sorted by (class, id).",
"#[rustfmt::skip]",
f"pub static METHODS: [ControlMethod; {len(methods)}] = [",
]
lines += [f" m({c:#x}, {i:#x}, {f:#x}, {a}, {s}, {h})," for c, i, f, a, s, h in methods]
lines += [
"];",
"/// NVOC class id and its ancestors, nearest first (the cast table of the class).",
"#[rustfmt::skip]",
f"pub static ANCESTORS: [(u32, &[u32]); {len(data['class_defs'])}] = [",
]
for entry in sorted(data["class_defs"], key=lambda entry: entry["classId"]):
ancestors = ", ".join(f"{value:#x}" for value in entry["ancestors"])
lines.append(f" ({entry['classId']:#x}, &[{ancestors}]),")
lines += ["];", ""]
return "\n".join(lines), len(methods), len(data["class_defs"])
methods = sorted((class_of(owner), method, flags, access, size, int(handler[3:-2]))
for method, handler, flags, access, size, owner, _name in data["methods"])
lines = [
"//! Exported control methods and NVOC class ancestry of the original (580.178.04).",
"//! Generated by tools/generate_rmapi_tables.py from the RM API dossier; do not edit.",
"",
"/// One `NVOC_EXPORTED_METHOD_DEF`: `class` is the NVOC class id whose table holds it,",
"/// `handler` the number in the original symbol `_nv<handler>rm`.",
"#[derive(Clone, Copy, Debug, PartialEq, Eq)]",
"pub struct ControlMethod {",
" pub class: u32,",
" pub id: u32,",
" pub flags: u32,",
" pub access_right: u32,",
" pub param_size: u32,",
" pub handler: u32,",
"}",
"const fn m(",
" class: u32,",
" id: u32,",
" flags: u32,",
" access_right: u32,",
" param_size: u32,",
" handler: u32,",
") -> ControlMethod {",
" ControlMethod {",
" class,",
" id,",
" flags,",
" access_right,",
" param_size,",
" handler,",
" }",
"}",
"/// Sorted by (class, id).",
"#[rustfmt::skip]",
f"pub static METHODS: [ControlMethod; {len(methods)}] = [",
]
lines += [f" m({c:#x}, {i:#x}, {f:#x}, {a}, {s}, {h})," for c, i, f, a, s, h in methods]
lines += ["];", "/// NVOC class id and its ancestors, nearest first (the cast table of the class).",
"#[rustfmt::skip]",
f"pub static ANCESTORS: [(u32, &[u32]); {len(data['class_defs'])}] = ["]
for entry in sorted(data["class_defs"], key=lambda entry: entry["classId"]):
ancestors = ", ".join(f"{value:#x}" for value in entry["ancestors"])
lines.append(f" ({entry['classId']:#x}, &[{ancestors}]),")
lines += ["];", ""]
text = "\n".join(lines)
if "--check" in sys.argv:
assert TARGET.read_text() == text, "control_table.rs is stale"
else:
TARGET.write_text(text)
print(len(methods), "methods,", len(data["class_defs"]), "classes")
def main(argv=None) -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--check", action="store_true", help="fail if control_table.rs is stale")
args = parser.parse_args(argv)
data = json.loads(DOSSIER.read_text(encoding="utf-8"))
text, method_count, class_count = render_table(data)
if args.check:
if not TARGET.is_file() or TARGET.read_text(encoding="utf-8") != text:
raise SystemExit("control_table.rs is stale")
else:
TARGET.parent.mkdir(parents=True, exist_ok=True)
TARGET.write_text(text, encoding="utf-8")
print(method_count, "methods,", class_count, "classes")
if __name__ == "__main__":
main()

View File

@ -1,29 +1,165 @@
#!/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 argparse,hashlib,json,struct,subprocess
from elftools.elf.elffile import ELFFile
root=Path(__file__).resolve().parent.parent
p=argparse.ArgumentParser();p.add_argument('--check',action='store_true');args=p.parse_args()
source=Path('/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/nv-kernel.o_binary')
with source.open('rb') as stream:
elf=ELFFile(stream);symbols=list(elf.get_section_by_name('.symtab').iter_symbols());by_name={s.name:s for s in symbols};rodata=elf.get_section_by_name('.rodata').data()
owner=by_name['_nv003037rm'];child=by_name['_nv002888rm']
owner_meta=struct.unpack_from('<II',rodata,owner['st_value']);child_meta=struct.unpack_from('<II',rodata,child['st_value'])
assert owner_meta==(0x1230,0x112230) and child_meta==(0x13910,0x8ae552)
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={r['r_offset']:r for r in elf.get_section_by_name('.rela.rodata').iter_relocations()}
assert symbols[rel[0x4dc5160]['r_info_sym']].name=='_nv003037rm'
assert symbols[rel[0x4dc5250]['r_info_sym']].name=='_nv042751rm'
method=by_name['_nv019295rm'];text=elf.get_section(method['st_shndx']).data();raw=text[method['st_value']:method['st_value']+method['st_size']]
assert raw==bytes.fromhex('f30f1efac3'), raw.hex() # Original ENDBR64; RET.
fixture=root/'tools/gpu_gv100_lpwr108_bindings_eval.c';binary=root/'target/lpwr108-binding-oracle';binary.parent.mkdir(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()
assert 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)]
report={'source_sha256':hashlib.sha256(source.read_bytes()).hexdigest(),'fixture_sha256':hashlib.sha256(fixture.read_bytes()).hexdigest(),'owner_metadata':{'symbol':owner.name,'bytes':owner_meta[0],'class_id':hex(owner_meta[1]),'public_name':'Lpwr'},'child_metadata':{'symbol':child.name,'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 out.read_text()!=payload:raise SystemExit('Stale '+str(out))
else:out.write_text(payload)
print('Original GV100 Lpwr child+108:3 RM bindings+9 other-chip counterexamples; exact ENDBR64/RET bytes verified')
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()

View File

@ -1,19 +1,146 @@
#!/usr/bin/env python3
"""Recover the exact original status-table row used by error-init group10."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import hashlib,json,struct
from elftools.elf.elffile import ELFFile
root=Path(__file__).resolve().parent.parent
source=Path('/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/nv-kernel.o_binary')
with source.open('rb') as stream:
elf=ELFFile(stream);symbols=elf.get_section_by_name('.symtab')
function=next(s for s in symbols.iter_symbols() if s.name=='_nv031134rm')
rel=next(r for r in elf.get_section_by_name('.rela.text').iter_relocations() if r['r_offset']==function['st_value']+0x5a)
target=symbols.get_symbol(rel['r_info_sym']);section=elf.get_section(target['st_shndx'])
assert section.name=='.data'
offset=target['st_value']+rel['r_addend'];rows=[struct.unpack_from('<6I',section.data(),offset+i*24) for i in range(32)]
matches=[(i,row) for i,row in enumerate(rows) if row[0]==10]
assert matches==[(10,(10,0,8,3,0,0))]
report={'source_sha256':hashlib.sha256(source.read_bytes()).hexdigest(),'source_function':'_nv031134rm','original_text_relocation_offset':hex(function['st_value']+0x5a),'relative_function_relocation_offset':'0x5a','section':'.data','table_offset':hex(offset),'record_bytes':24,'rows':[list(row) for row in rows],'selected_group':10,'selected_row':list(matches[0][1]),'gpu_word_offset':'0x6d90','rust_update':'(old & !0x300) | 0x100','limits':'Only the exact group10 / sentinelb33b1500 / value1 call is implemented; other groups still require their actual state owners.'}
(root/'reports/gpu-gv100-error-policy-table.json').write_text(json.dumps(report,indent=2)+'\n')
print('Original relocation-backed group10 row verified:',matches[0])
import struct
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:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--check', action='store_true', help='fail if report differs')
args = parser.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'])
function = next((s for s in syms if s[0] == '_nv031134rm'), None)
if function is None:
raise SystemExit('symbol _nv031134rm not found')
rel_h = sections[by_name['.rela.text']][1]
rel_entsize = rel_h[9] or 24
target_rel = None
want_off = function[2] + 0x5A
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)
if r_offset == want_off:
target_rel = (r_info >> 32, r_addend)
break
if target_rel is None:
raise SystemExit(f'missing relocation at _nv031134rm+0x5a (0x{want_off:x})')
r_sym, r_addend = target_rel
target = syms[r_sym]
sec_name, sec_h = sections[target[1]]
if sec_name != '.data':
raise SystemExit(f'unexpected target section {sec_name!r} != .data')
sec_data = raw_elf[sec_h[4]:sec_h[4] + sec_h[5]]
offset = target[2] + r_addend
rows = [struct.unpack_from('<6I', sec_data, offset + i * 24) for i in range(32)]
matches = [(i, row) for i, row in enumerate(rows) if row[0] == 10]
if matches != [(10, (10, 0, 8, 3, 0, 0))]:
raise SystemExit(f'unexpected group10 error policy row: {matches}')
report = {
'source_sha256': sha,
'source_function': '_nv031134rm',
'original_text_relocation_offset': hex(want_off),
'relative_function_relocation_offset': '0x5a',
'section': '.data',
'table_offset': hex(offset),
'record_bytes': 24,
'rows': [list(row) for row in rows],
'selected_group': 10,
'selected_row': list(matches[0][1]),
'gpu_word_offset': '0x6d90',
'rust_update': '(old & !0x300) | 0x100',
'limits': 'Only the exact group10 / sentinelb33b1500 / value1 call is implemented; other groups still require their actual state owners.',
}
out = ROOT / 'reports/gpu-gv100-error-policy-table.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 relocation-backed group10 row verified:', matches[0])
if __name__ == '__main__':
main()

View File

@ -1,20 +1,155 @@
#!/usr/bin/env python3
"""Extract selected immutable legacy HAL interface labels from pinned original ELF."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import json,hashlib,argparse,struct
from elftools.elf.elffile import ELFFile
R=Path(__file__).resolve().parents[1];P=Path('/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/nv-kernel.o_binary');opt=argparse.ArgumentParser();opt.add_argument('--check',action='store_true');a=opt.parse_args()
assert hashlib.sha256(P.read_bytes()).hexdigest()=='5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b'
with P.open('rb')as f:
e=ELFFile(f);symbols=list(e.get_section_by_name('.symtab').iter_symbols());relocs={r['r_offset']:r for r in e.get_section_by_name('.rela.rodata').iter_relocations()};raw=e.get_section_by_name('.rodata').data();bases={e.get_section_index('.text'):0x0616f810,e.get_section_index('.rodata'):0x0111d660,e.get_section_index('.data'):0x00f7e890,e.get_section_index('.bss'):0x05fd2180}
def pointer(address):
offset=address-0x0111d660;r=relocs.get(offset)
if r is None:return struct.unpack_from('<Q',raw,offset)[0]
s=symbols[r['r_info_sym']];return bases[s['st_shndx']]+s['st_value']+r['r_addend']
setup=[pointer(0x0113b3f0+i*8)for i in range(2)];entries=[pointer(0x01137f20+i*8)for i in range(205)]
code='// Original GV100 legacy HAL setup labels; metadata, never native calls.\nconst SETUP_IDENTITY:u64=0x0113b3f0;\nconst SETUP:[u64;2]=['+','.join(map(str,setup))+'];\n#[rustfmt::skip]\nconst INTERFACES:[u64;205]=[\n'+''.join(str(v)+',\n'for v in entries)+'];\n'
p=R/'src/nvidia/src/gpu/legacy_hal_data.rs'
if a.check:assert p.read_text()==code
else:p.write_text(code)
(R/'reports/gpu-legacy-hal-data.json').write_text(json.dumps({'artifact_sha256':hashlib.sha256(P.read_bytes()).hexdigest(),'hal_index':35,'setup_identity':0x0113b3f0,'setup':setup,'interface_source':0x01137f20,'interface_count':205,'interfaces':entries,'scope':'immutable metadata labels only; method implementations not established by presence'},indent=2)+'\n')
print('2 setup labels,205 interfaces')
import struct
R = Path(__file__).resolve().parents[1]
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 main(argv=None) -> None:
opt = argparse.ArgumentParser(description=__doc__)
opt.add_argument('--check', action='store_true')
args = opt.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)
sym_idx = by_name['.symtab']
sym_h = sections[sym_idx][1]
sym_entsize = sym_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(sym_h[5] // sym_entsize):
_st_name, _st_info, _st_other, st_shndx, st_value, _st_size = struct.unpack_from('<IBBHQQ', raw, sym_h[4] + i * sym_entsize)
if st_shndx == 0xFFFF and ext is not None and i < len(ext):
st_shndx = ext[i]
syms.append((st_shndx, st_value))
rel_h = sections[by_name['.rela.rodata']][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, rel_h[4] + i * rel_entsize)
relocs[r_offset] = (r_info >> 32, r_addend)
ro_h = sections[by_name['.rodata']][1]
rodata = raw[ro_h[4]:ro_h[4] + ro_h[5]]
bases = {
by_name['.text']: 0x0616F810,
by_name['.rodata']: 0x0111D660,
by_name['.data']: 0x00F7E890,
by_name['.bss']: 0x05FD2180,
}
def pointer(address: int) -> int:
offset = address - 0x0111D660
r = relocs.get(offset)
if r is None:
return struct.unpack_from('<Q', rodata, offset)[0]
r_sym, r_addend = r
shndx, st_value = syms[r_sym]
return bases[shndx] + st_value + r_addend
setup = [pointer(0x0113B3F0 + i * 8) for i in range(2)]
entries = [pointer(0x01137F20 + i * 8) for i in range(205)]
code = (
'// Original GV100 legacy HAL setup labels; metadata, never native calls.\n'
'const SETUP_IDENTITY:u64=0x0113b3f0;\n'
'const SETUP:[u64;2]=[' + ','.join(map(str, setup)) + '];\n'
'#[rustfmt::skip]\n'
'const INTERFACES:[u64;205]=[\n'
+ ''.join(str(v) + ',\n' for v in entries)
+ '];\n'
)
report = {
'artifact_sha256': sha,
'hal_index': 35,
'setup_identity': 0x0113B3F0,
'setup': setup,
'interface_source': 0x01137F20,
'interface_count': 205,
'interfaces': entries,
'scope': 'immutable metadata labels only; method implementations not established by presence',
}
target = R / 'src/nvidia/src/gpu/legacy_hal_data.rs'
meta = R / 'reports/gpu-legacy-hal-data.json'
if args.check:
if not target.is_file() or not target.read_text(encoding='utf-8').startswith(code):
raise SystemExit('src/nvidia/src/gpu/legacy_hal_data.rs differs')
if not meta.is_file() or json.loads(meta.read_text(encoding='utf-8')) != report:
raise SystemExit('reports/gpu-legacy-hal-data.json differs')
else:
target.parent.mkdir(parents=True, exist_ok=True)
meta.parent.mkdir(parents=True, exist_ok=True)
suffix = ''
if target.is_file():
existing = target.read_text(encoding='utf-8')
marker = 'const INTERFACES:[u64;205]=[\n'
pos = existing.find(marker)
if pos != -1:
end = existing.find('];\n', pos)
if end != -1:
suffix = existing[end + 3:]
target.write_text(code + suffix, encoding='utf-8')
meta.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
print('2 setup labels,205 interfaces')
if __name__ == '__main__':
main()