mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 14:38:47 +00:00
83 lines
8.6 KiB
Python
83 lines
8.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Label observed immediate EngState callbacks through original NVOC metadata.
|
|
Read-only inputs; generates evidence, never samples or edits driver production.
|
|
"""
|
|
from pathlib import Path
|
|
from collections import defaultdict,Counter
|
|
from elftools.elf.elffile import ELFFile
|
|
import json,re,struct,hashlib
|
|
R=Path(__file__).resolve().parents[1];E=Path('/home/geodd/nvidia-driver/analysis-580.178.04');P=E/'extracted/kernel/nvidia/nv-kernel.o_binary';G=E/'reference/open-gpu-kernel-modules-580.178.04/src/nvidia/generated';I=R/'reports/original-live-init-bp-4/timestamped-dispatch.json';SLOTS={'InitLocked':0x50,'InitUnlocked':0x58,'PreLoad':0x60,'Load':0x68};NOOPS={'_nv026842rm','_nv026845rm','_nv026851rm'}
|
|
cap=json.loads(I.read_text());events=[x for x in cap['events']if x['gpu_ordinal']==0];assert len(events)==257
|
|
labels=defaultdict(list)
|
|
for p in sorted(G.glob('*_nvoc.h')):
|
|
for line,s in enumerate(p.read_text().splitlines(),1):
|
|
m=re.match(r'#define __nvoc_class_id_(\w+) (0x[0-9a-fA-F]+)',s)
|
|
if m:labels[int(m[2],16)].append({'class_name':m[1],'source_file':str(p),'line':line})
|
|
def choose_label(cid):
|
|
choices=labels[cid];canonical=[x for x in choices if Path(x['source_file']).name=='g_eng_desc_nvoc.h'];return canonical or choices[:1]
|
|
methods={};class_catalog={}
|
|
with P.open('rb')as f:
|
|
elf=ELFFile(f);ss=list(elf.get_section_by_name('.symtab').iter_symbols());byname={s.name:(i,s)for i,s in enumerate(ss)};ro=elf.get_section_by_name('.rodata').data();roidx=elf.get_section_index('.rodata');rels={r['r_offset']:r for r in elf.get_section_by_name('.rela.rodata').iter_relocations()};refs=defaultdict(list)
|
|
for off,r in rels.items():refs[r['r_info_sym']].append(off)
|
|
def target(off):
|
|
rel=rels.get(off);return ss[rel['r_info_sym']]if rel else None
|
|
def ro_target(off):
|
|
rel=rels.get(off)
|
|
if rel is None:return None
|
|
s=ss[rel['r_info_sym']]
|
|
return s['st_value']+rel['r_addend']if s['st_shndx']==roidx else None
|
|
owners=defaultdict(list)
|
|
for owner in ss:
|
|
if owner['st_shndx']!=roidx or owner['st_info']['type']!='STT_OBJECT' or owner['st_size']!=40:continue
|
|
cast=ro_target(owner['st_value']+0x18)
|
|
if cast is None or cast+8>len(ro):continue
|
|
count=struct.unpack_from('<I',ro,cast)[0]
|
|
if not 0<count<32:continue
|
|
relatives=[ro_target(cast+8+i*8)for i in range(count)]
|
|
if any(x is None for x in relatives):continue
|
|
roots=[x for x in relatives if target(x) is not None and target(x).name==owner.name and struct.unpack_from('<I',ro,x+16)[0]==0]
|
|
if len(roots)!=1:continue
|
|
for base in relatives:
|
|
ancestor=target(base)
|
|
if ancestor is not None and ancestor.name=='_nv003100rm':owners[base].append((owner,roots[0],cast,relatives))
|
|
def candidates(name,slot):
|
|
answer=[]
|
|
for off in refs[byname[name][0]]:
|
|
base=off-slot
|
|
for owner,root,cast,relatives in owners[base]:
|
|
cid=struct.unpack_from('<I',ro,owner['st_value']+4)[0];key=hex(cid)
|
|
ancestor_ids=[]
|
|
for relative in relatives:
|
|
ancestor=target(relative)
|
|
if ancestor is not None and ancestor['st_info']['type']=='STT_OBJECT':ancestor_ids.append(hex(struct.unpack_from('<I',ro,ancestor['st_value']+4)[0]))
|
|
class_catalog[key]={'class_id':key,'binary_class_definition':owner.name,'class_definition_rodata_offset':hex(owner['st_value']),'class_id_field_offset':4,'source_labels':choose_label(cid),'ancestor_class_ids':ancestor_ids}
|
|
answer.append({'class_id':key,'metadata_engstate_rodata_offset':hex(base),'callback_relocation_rodata_offset':hex(off),'root_rtti_rodata_offset':hex(root),'castinfo_rodata_offset':hex(cast),'castinfo_num_relatives':len(relatives),'engstate_subobject_offset':struct.unpack_from('<I',ro,base+16)[0]})
|
|
return answer
|
|
for ev in events:
|
|
name=ev['callback']['name'];stage=ev['stage'];key=name+':'+stage
|
|
if key in methods:continue
|
|
assert ev['callback']['offset']=='0x0'
|
|
methods[key]={'symbol':name,'stage':stage,'vtable_slot':hex(SLOTS[stage]),'shared_default_noop':name in NOOPS,'candidates':candidates(name,SLOTS[stage])}
|
|
engines=[]
|
|
for ordinal in range(78):
|
|
selected=[ev for ev in events if ev['engine_ordinal']==ordinal];owners={x['engine_owner']for x in selected};assert len(owners)==1
|
|
matching=None
|
|
for ev in selected:
|
|
keys={x['class_id']for x in methods[ev['callback']['name']+':'+ev['stage']]['candidates']}
|
|
matching=keys if matching is None else matching&keys
|
|
matching=sorted(matching or []);declarations=[d for cid in matching for d in class_catalog[cid]['source_labels']]
|
|
name=declarations[0]['class_name']if len(matching)==1 and len({d['class_name']for d in declarations})==1 else None
|
|
engines.append({'engine_ordinal0':ordinal,'gpu_owner':selected[0]['gpu_owner'],'engine_owner':next(iter(owners)),'class_label':name,'phase_positions0':{phase:order.index(ordinal)for phase,order in cap['gpu_groups'][0]['engine_orders'].items()if ordinal in order},'class_candidate_ids':matching,'class_label_evidence':'intersection of actual callback-slot original metadata classes whose ClassDef CastInfo owns SAME EngStateRTTI; capturedSI matches across phases; no live classID read','callbacks':{ev['stage']:{'symbol':ev['callback']['name'],'callback_address':ev['callback_address'],'sample':ev['sample'],'source_line':ev['source_line'],'method_evidence':ev['callback']['name']+':'+ev['stage'],'shared_default_noop':ev['callback']['name']in NOOPS}for ev in selected}})
|
|
# Compare capture1 actual AX sequences/owner grouping without comparing heap addresses.
|
|
raw=R/'reports/original-live-init-bp-4/standalone-dispatch-registers.txt';raw_rows=[]
|
|
for line in raw.read_text().splitlines():
|
|
m=re.search(r'mem:(0x[0-9a-f]+):x:.*AX:(0x[0-9a-f]+).*DX:(0x[0-9a-f]+).*SI:(0x[0-9a-f]+).*DI:(0x[0-9a-f]+)',line)
|
|
if m:raw_rows.append(m.groups())
|
|
first_gpu=raw_rows[0][-1];first=[x for x in raw_rows if x[-1]==first_gpu];assert len(first)==257
|
|
repeat=[(x[0],x[1])for x in first]==[(ev['site'],ev['callback_address'])for ev in events]
|
|
used_sources={d['source_file']for c in class_catalog.values()for d in c['source_labels']};source_hashes={p:hashlib.sha256(Path(p).read_bytes()).hexdigest()for p in sorted(used_sources)}
|
|
report={'schema':1,'scope':'Observed immediate callback attempts for first GPU group. Exact580 generated-source names label original binary classIDs only; no final HAL body/completion claim.','inputs':{str(I.relative_to(R)):hashlib.sha256(I.read_bytes()).hexdigest(),str(raw.relative_to(R)):hashlib.sha256(raw.read_bytes()).hexdigest(),'original_rm_sha256':hashlib.sha256(P.read_bytes()).hexdigest()},'ordinal_convention':'engine_ordinal0 isZEROBASED and matches timestamped-dispatch.json engine_ordinal; not1-based position','sample_clock':cap['sample_clock'],'input_revision':json.loads((R/'reports/gpu-live-engine-labels-revision.json').read_text()),'first_gpu_owner':events[0]['gpu_owner'],'first_gpu_samples':257,'stage_counts':dict(Counter(x['stage']for x in events)),'capture1_callback_order_repeats_capture2':repeat,'engine_count':78,'source_named_engines':sum(x['class_label']is not None for x in engines),'ambiguous_or_undeclared_engines':[x['engine_ordinal0']for x in engines if x['class_label']is None],'engines':engines,'phase_orders':cap['gpu_groups'][0]['engine_orders'],'ordered_attempts':[{'sample':x['sample'],'perf_time_ns':x['perf_time_ns'],'stage':x['stage'],'engine_ordinal0':x['engine_ordinal'],'callback':x['callback']['name']}for x in events],'method_catalog':methods,'class_catalog':class_catalog,'label_source_hashes':source_hashes,'limitations':['No live classID/object memory dereference. Shared callback/noop mappings remain ambiguous unless other captured methods for SAME SI narrow the class.','Unknown binary classIDs without exact generated-source declaration remain numeric, unnamed. In particular ordinal38 class5dfed5 has Pmu ancestor but must not be labeled the base Pmu class.','Labels are classes consistent with the observed original metadata; no class name inferred from ordinal, method number or neighboring class.','CapturedRAX is the immediate wrapper/default method, not proof of final HAL target, completion, result status, authentication or hardware readiness.','Capture1 has no printed timestamps; primaryorder uses capture2 timestamped events and compares capture1 actual site+AX sequence.'],'read_only':True,'tracing_changed':False,'production_changed':False}
|
|
(R/'reports/gpu-live-engine-labels.json').write_text(json.dumps(report,indent=2)+'\n');print('Named',report['source_named_engines'],'of78; unresolved',report['ambiguous_or_undeclared_engines'],'repeat',repeat)
|
|
for x in engines:
|
|
if x['class_label']in['Graphics','GraphicsManager','KernelGraphics','OBJLSFM','OBJACR','OBJFIFO','KernelFifo','OBJGMMU','KernelGmmu','OBJBUS','KernelBus']:print(x['engine_ordinal0'],x['class_label'],{k:v['symbol']for k,v in x['callbacks'].items()})
|