Files
nvdriver/tools/gpu_generate_owned_clock_templates.py

42 lines
3.8 KiB
Python

#!/usr/bin/env python3
"""Immutable original clock templates and exact native constructor identities."""
from pathlib import Path
import json,argparse,hashlib,subprocess,re
from elftools.elf.elffile import ELFFile
r=Path(__file__).resolve().parent.parent;p=argparse.ArgumentParser();p.add_argument('--check',action='store_true');a=p.parse_args()
f=Path('/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/nv-kernel.o_binary')
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)},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.'}
channel=re.search(r'channel\s*=\s*"([^"]+)"',(r/'rust-toolchain.toml').read_text())[1]
rustfmt=Path.home()/'.rustup/toolchains'/f'{channel}-x86_64-unknown-linux-gnu/bin/rustfmt'
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')