Files
nvdriver/tools/check_kernel_module.py
arabek 4bec328edf Gate the endbr64 relocation rule to x86_64 objects
PR #10 review comment 4741785482: the endbr64 + zero-addend pass condition
applied to every object without reading the ELF machine type. AArch64 function
entries do not start with endbr64, so a data relocation to a function in an
ARM64 object fails the gate and make modules exits non-zero on ARM64 hosts -
the aarch64 build path in utils.mk is unchanged by this PR, so the failure is
new in the PR.

Read the e_machine field via readelf -h and enforce the endbr64 + zero-addend
rule only for x86_64 objects; every other check stays active on ARM64. The
report carries elf_machine. Proven: current x86 object unchanged, gate green;
synthetic AArch64 object with a data relocation to a non-endbr entry passes
gated and fails when x86 enforcement is forced on the same object.
2026-11-30 17:39:55 +01:00

39 lines
4.8 KiB
Python

#!/usr/bin/env python3
"""Check the built diagnostic module before any load; no hardware access."""
import hashlib,json,re,subprocess
from pathlib import Path
root=Path(__file__).resolve().parents[1]
obj=root/'kernel-open/nvidia/nv-rust.o_binary';module=root/'kernel-open/nvidia_rs.ko'
def run(*args):return subprocess.check_output(args,text=True)
assembly=run('objdump','-dr',str(obj));relocs=run('readelf','-rW',str(module));sections=run('readelf','-SW',str(obj));symbols=run('nm','--defined-only',str(obj));undefined=run('nm','-u',str(module));frames={};fn='';first_instr={};instr_at={};cur='';entry=False;machine=run('readelf','-h',str(obj));x86_64='X86-64' in machine
for line in assembly.splitlines():
m=re.match(r'^Disassembly of section (\S+):',line)
if m:cur=m[1]
m=re.search(r'^[0-9a-f]+ <(.+)>:$',line)
if m:fn=m[1];entry=True
m=re.match(r'^\s+([0-9a-f]+):\t',line)
if m:instr=line.split('\t')[-1].strip().split()[0];instr_at[(cur,m[1])]=instr
if entry and m:first_instr[fn]=instr;entry=False
m=re.search(r'\bsub\s+\$0x([0-9a-f]+),%rsp',line)
if m:frames[fn]=frames.get(fn,0)+int(m[1],16)
if re.search(r'\bpush\s',line):frames[fn]=frames.get(fn,0)+8
data_sections=set();code_sections=set()
for line in sections.splitlines():
m=re.match(r'\s+\[\s*(\d+)\]\s+(\S+)\s+\S+\s+([0-9a-f]+)\s+([0-9a-f]+)\s+([0-9a-f]+)\s+\S+\s+(\S+)\s',line)
if m and 'A' in m.group(6):(data_sections if 'X' not in m.group(6) else code_sections).add(m.group(2))
data_relocs=[];sec=''
for line in run('readelf','-rW',str(obj)).splitlines():
m=re.search(r"Relocation section '([^']+)'",line)
if m:sec=m[1];continue
p=line.split()
if not sec or not re.match(r'^[0-9a-f]{12,16}$',p[0] if p else ''):continue
base='.'+sec[len('.rela.'):]
if base not in data_sections or len(p)<5:continue
name=p[4].split('+')[0];off=int(p[4].split('+')[1],16) if '+' in p[4] else int(p[-1],16) if len(p)>6 else 0
key=(name,format(off,'x')) if name in code_sections else None
target=key if key in instr_at else (name if name in first_instr else (name[len('.text.'):] if name.startswith('.text.') and name[len('.text.'):] in first_instr else None))
if target:data_relocs.append((target,off,instr_at[key] if key else first_instr[target]))
checks={'no_unresolved_private_or_Rust_runtime_symbols':not re.search(r'\b(?:nv_rs_|_RNv|_ZN|__rust_|rust_eh_personality)',undefined),'no_unsupported_GOT_relocations':'GOT'not in relocs,'no_SIMD_x87_registers':not re.search(r'%(?:[xyz]mm\d+|mm\d+|st(?:\(|\b))',assembly),'no_Rust_unwind_sections':not re.search(r'\.eh_frame|\.gcc_except_table',sections),'bounded_fixed_function_stack':max(frames.values(),default=0)<=1024,'no_dynamic_RSP_subtraction':not re.search(r'\bsub\s+%[^,]+,%rsp',assembly),'no_RSP_redzone_reference':not re.search(r'-0x[\da-f]+\(%rsp\)',assembly),'endbr64_at_data_relocation_targets':True if not x86_64 else all(i=='endbr64' and a==0 for _,a,i in data_relocs),'protocol_exports_present':all('nv_rs_'+s in symbols for s in ['protocol_version','gpu_capabilities','event_selftest','gpu_prepare_owned','gpu_set_probe_identity','gpu_registry_publish','gpu_registry_retire','sysmem_prepare','sysmem_close']),'distinct_diagnostic_module_name':run('modinfo','-F','name',str(module)).strip()=='nvidia_rs','no_PCI_aliases':not run('modinfo','-F','alias',str(module)).strip()}
report={'passed':all(checks.values()),'checks':checks,'largest_conservative_function_stack_bytes':max(frames.values(),default=0),'functions_without_endbr':sum(1 for v in first_instr.values() if v!='endbr64'),'endbr64_at_every_function_entry_informational':bool(first_instr) and all(v=='endbr64' for v in first_instr.values()),'data_relocations_to_code':len(data_relocs),'data_relocation_targets_without_endbr':sum(1 for _,a,i in data_relocs if i!='endbr64'),'data_relocations_pointing_inside_a_function':sum(1 for _,a,_ in data_relocs if a!=0),'elf_machine':machine.split(':',1)[1].strip(),'object_sha256':hashlib.sha256(obj.read_bytes()).hexdigest(),'module_sha256':hashlib.sha256(module.read_bytes()).hexdigest(),'undefined_kernel_symbols':undefined.splitlines(),'scope':'Static codegen/export checks for the current diagnostic module only. Per-function stack accounting is not a full call-chain proof; this does not prove GPU initialization, CUDA, hardware ownership or parity.'}
(root/'reports/kernel-module-codegen-validation.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps({'passed':report['passed'],'checks':checks,'largest_stack':report['largest_conservative_function_stack_bytes'],'functions_without_endbr':report['functions_without_endbr'],'data_relocations_to_code':report['data_relocations_to_code'],'data_relocation_targets_without_endbr':report['data_relocation_targets_without_endbr'],'data_relocations_pointing_inside_a_function':report['data_relocations_pointing_inside_a_function']}));raise SystemExit(0 if report['passed']else 1)