Files
nvdriver/tools/gpu_generate_owned_clock_templates.py

134 lines
6.2 KiB
Python

#!/usr/bin/env python3
"""Immutable original clock templates and exact native constructor identities."""
from pathlib import Path
import argparse, hashlib, json, os, re, shutil, subprocess
def find_rm_object():
candidates = []
if os.environ.get('NV_RS_RM_OBJECT'):
candidates.append(Path(os.environ['NV_RS_RM_OBJECT']))
if os.environ.get('NV_RS_ANALYSIS_ROOT'):
candidates.append(Path(os.environ['NV_RS_ANALYSIS_ROOT']) / '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'),
Path('/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/nv-kernel.o_binary'),
])
for cand in candidates:
if cand.is_file():
return cand
raise SystemExit('nv-kernel.o_binary not found (set NV_RS_RM_OBJECT or NV_RS_ANALYSIS_ROOT)')
def find_rustfmt(repo_root):
if os.environ.get('RUSTFMT'):
return Path(os.environ['RUSTFMT'])
rustup = shutil.which('rustup')
if rustup:
rustup = os.path.abspath(rustup)
res = subprocess.run([rustup, 'which', 'rustfmt'], cwd=str(repo_root), capture_output=True, text=True)
if res.returncode == 0 and res.stdout.strip():
return Path(res.stdout.strip())
which = shutil.which('rustfmt')
if which:
return Path(which)
channel = re.search(r'channel\s*=\s*"([^"]+)"', (repo_root / 'rust-toolchain.toml').read_text())[1]
rustup_home = Path(os.environ.get('RUSTUP_HOME', str(Path.home() / '.rustup')))
return rustup_home / 'toolchains' / f'{channel}-x86_64-unknown-linux-gnu/bin/rustfmt'
def main(argv=None):
try:
from elftools.elf.elffile import ELFFile
except ImportError as error:
raise SystemExit(f'pyelftools is required: {error}')
r = Path(__file__).resolve().parent.parent
p = argparse.ArgumentParser()
p.add_argument('--check', action='store_true')
a = p.parse_args(argv)
f = find_rm_object()
meta = json.loads((r / 'reports/gpu-clock-object-metadata.json').read_text())
source_sha = hashlib.sha256(f.read_bytes()).hexdigest()
assert source_sha == '5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b'
with f.open('rb') as stream:
e = ELFFile(stream)
symbols = list(e.get_section_by_name('.symtab').iter_symbols())
byname = {s.name: s for s in symbols}
relocs = {v['r_offset']: v for v in e.get_section_by_name('.rela.rodata').iter_relocations()}
def mid(slot, offset):
if slot is None:
return 'None'
rel = relocs[offset]
s = symbols[rel['r_info_sym']]
assert e.get_section(s['st_shndx']).name == '.text'
v = s['st_value'] + rel['r_addend'] + 1
assert 0 < v < 2**32
return f'Some(MethodId(NonZeroU32::new(0x{v:x}).unwrap()))'
code = '// Generated from exact580 original ELF template relocations.\n'
code += 'const HEADERS: &[(TemplateId, Header)] = &[\n'
for t in meta['templates']:
v = int(t['section_offset'], 16) + 1
slots = t['slots']
assert slots[0]['symbol'] == t['symbol'] and not slots[0]['addend']
tid = f'TemplateId(NonZeroU32::new(0x{v:x}).unwrap())'
code += (
f' ({tid}, Header {{template_0:Some({tid}),method_8:{mid(slots[1], v - 1 + 8)},'
f'methods_10_38:[' + ','.join(mid(slot, v - 1 + 16 + i * 8) for i, slot in enumerate(slots[2:]))
+ ']}), // ' + t['symbol'] + '\n'
)
code += '];\n'
for name, symbol in [
('CRYSTAL_TEMPLATE', '_nv021326rm'),
('CONDITIONAL_BASE_TEMPLATE', '_nv021357rm'),
('CONDITIONAL_PARENT_TEMPLATE', '_nv021342rm'),
]:
code += f'pub const {name}: TemplateId = TemplateId(NonZeroU32::new(0x{byname[symbol]["st_value"] + 1:x}).unwrap());\n'
native = {t['symbol']: int(t['section_offset'], 16) for t in meta['templates']}
def target_at(template, offset):
rel = relocs[native[template] + offset]
symbol = symbols[rel['r_info_sym']]
assert e.get_section(symbol['st_shndx']).name == '.text'
return symbol['st_value'] + rel['r_addend']
fixed = {
'NOOP_METHOD': byname['_nv021089rm']['st_value'],
'FIXED_020586': target_at('_nv021342rm', 0x10),
'FIXED_020592': target_at('_nv021342rm', 0x18),
'FIXED_021059': target_at('_nv021326rm', 0x20),
}
assert fixed['FIXED_020592'] == 0x1fd7e0 and target_at('_nv021326rm', 0x18) == 0x1d9ad0
for name, value in fixed.items():
code += f'const {name}: MethodId = MethodId(NonZeroU32::new(0x{value + 1:x}).unwrap());\n'
report = {
'source_sha256': source_sha,
'headers': len(meta['templates']),
'token_encoding': 'Immutable original rodata/text section offset+1. Object lifetime IDs use separate per-registry tags.',
'constructor_functions': ['020711', '020712'],
'same_named_020592_text_offsets': [hex(v['st_value']) for v in symbols if v.name == '_nv020592rm'],
'crystal_slot18': '0x1d9ad0',
'conditional_parent_slot18': '0x1fd7e0',
'fixed_bindings_from_context': {k: hex(v) for k, v in fixed.items()},
'limits': 'Original immutable headers only. Constructed object/owner state and all missing services remain required.',
}
rustfmt = find_rustfmt(r)
code = subprocess.run([str(rustfmt), '--edition', '2024'], input=code, text=True, capture_output=True, check=True).stdout
for out, text in [
(r / 'src/nvidia/src/gpu/clock_owned_templates.rs', code),
(r / 'reports/gpu-clock-owned-templates.json', json.dumps(report, indent=2) + '\n'),
]:
if a.check:
if out.read_text() != text:
raise SystemExit('Stale ' + str(out))
else:
out.write_text(text)
print('Original owned clock templates:35headers,020711/020712bindings')
return 0
if __name__ == '__main__':
raise SystemExit(main())