Files
nvdriver/tools/check_kernel_module.py
Eric Hartford 4472b75ccd Follow-up to PR #10/#11: auto-gate IBT flags, fix RUSTC fallback & section-reloc gate, align stock 580.178.04 compat/FOLL_LONGTERM
- utils.mk: search ~/.cargo/bin in rustup lookup and fall back to ~/.cargo/bin/rustc; auto-gate -Z cf-protection=branch -C jump-tables=no on CONFIG_X86_KERNEL_IBT=y (overridable via NV_RS_KERNEL_IBT=0/1).
- rust-toolchain.toml: restore default stable 1.100.0 (IBT kernels build with RUSTUP_TOOLCHAIN=nightly-2026-11-29).
- tools/check_kernel_module.py: resolve section-symbol relocation targets against disassembled function-entry addresses (avoiding false mid-function failures on valid .text+<entry_off> relocs) and enforce the x86 endbr64 gate when IBT is configured or emitted.
- Stock 580.178.04 parity: omit .llseek across fops (matching nv.c/uvm.c), use container_of() in nano_timer_adapter.c (matching nv-timer.h), use #if defined(MAX_PAGE_ORDER) in rom_fw_adapter.c (matching nv-linux.h), and pass FOLL_LONGTERM in nv_rs_rmapi_os_lock_user_pages (matching os-mlock.c).
- Docs: remove scratch docs/HISTORY.md and update docs/KERNEL_COMPAT.md.
2026-11-30 17:19:30 +00:00

45 lines
5.2 KiB
Python

#!/usr/bin/env python3
"""Check the built diagnostic module before any load; no hardware access."""
import hashlib,json,os,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={};fn_entries=set();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[2];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;fn_entries.add((cur,m[1]));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
if key and key in instr_at:
data_relocs.append((key,0 if key in fn_entries else 1,instr_at[key]))
else:
target=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,first_instr[target]))
kcfg=Path(os.environ.get('KERNEL_OUTPUT',f"/lib/modules/{os.uname().release}/build"))/'.config'
ibt_cfg=os.environ.get('NV_RS_KERNEL_IBT')=='1' or (kcfg.exists() and 'CONFIG_X86_KERNEL_IBT=y' in kcfg.read_text(errors='ignore'))
ibt_enforced=x86_64 and (ibt_cfg or any(v=='endbr64' for v in first_instr.values()))
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 ibt_enforced 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),'ibt_gate_enforced':ibt_enforced,'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':re.search(r'Machine:\s+(.*)',machine).group(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)