#!/usr/bin/env python3 """Check the built diagnostic module before any load; no hardware access.""" import hashlib,json,os,re,struct,subprocess,sys from pathlib import Path root=Path(__file__).resolve().parents[1] args=sys.argv[1:];obj=Path(args[0]) if args else root/'kernel-open/nvidia/nv-rust.o_binary';module=Path(args[1]) if len(args)>1 else root/'kernel-open/nvidia_rs.ko';object_only='--object-only' in args;committed_run=not args def run(*args):return subprocess.check_output(args,text=True) EXEC,ALLOC,SYMTAB,RELA,REL,SHN_UNDEF,SHN_LORESERVE,SHN_XINDEX,SHT_SYMTAB_SHNDX=4,2,2,4,9,0,0xff00,0xffff,18 # A relocation target's identity comes from the ELF tables, not from the names a tool prints: a # printed string can be another entity's 256-character truncation, so it attributes nothing. objdump # is still the source of instruction boundaries, and a disassembly header whose printed form belongs # to more than one section cannot be attributed, so every target in it is refused as ambiguous. raw=obj.read_bytes();eh=struct.unpack('<16sHHIQQQIHHHHHH',raw[:64]) def sh(i):return struct.unpack('>32,off,struct.unpack('1:duplicate_names.add(n);unattributable.update(c) cur=None;entry=False;machine=run('readelf','-h',str(obj));x86_64='X86-64' in machine;aarch64='AArch64' in machine;naked_ret_fns=set();has_int3=False;builtin_exempt={'strlen','memcmp','bcmp'} for line in assembly.splitlines(): m=re.match(r'^Disassembly of section (\S+):',line) if m: n=m[1];c=name_map.get(n,[]) if len(c)==1:cur=c[0] elif len(c)>1:cur=None else: p=[i for i,(nn,_,_) in enumerate(sections) if nn[:256]==n] if len(p)>1:ambiguous.add(n);unattributable.update(p);cur=None elif len(p)==1:cur=p[0] 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] if cur is not None:instr_at[(cur,int(m[1],16))]=instr if entry:first_instr[fn]=instr;entry=False if instr in ('ret','retq') and fn not in builtin_exempt:naked_ret_fns.add(fn) if instr=='int3':has_int3=True 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 if aarch64: m=re.search(r'\bsub\s+sp,\s*sp,\s*#0x([0-9a-f]+)',line) if m:frames[fn]=frames.get(fn,0)+int(m[1],16) data_relocs=[];unresolved=[];ambiguous_targets=[] for sec,sym,off,addend in elf_relocs: if not sections[sec][1]&ALLOC or sections[sec][1]&EXEC:continue target,value,name=sec,0,sections[sec][0] if sym: e=elf_symbols.get(sym) if not e:continue target,value,name,raw_index=e if target is None:unresolved.append((name,value+addend));continue if SHN_LORESERVE<=raw_index=shnum:continue name=name or sections[target][0] if not sections[target][1]&EXEC:continue addr=value+addend if target in unattributable:ambiguous_targets.append((name,addr));continue key=(target,addr) if key in instr_at:data_relocs.append((name,0 if addend==0 else 1,instr_at[key])) else:unresolved.append((name,addr)) kcfg=Path(os.environ.get('KERNEL_OUTPUT',f"/lib/modules/{os.uname().release}/build"))/'.config' kcfg_txt=kcfg.read_text(errors='ignore') if kcfg.exists() else '' ibt_cfg=os.environ.get('NV_RS_KERNEL_IBT')=='1' or (os.environ.get('NV_RS_KERNEL_IBT')!='0' and 'CONFIG_X86_KERNEL_IBT=y' in kcfg_txt) ibt_enforced=x86_64 and (ibt_cfg or any(v=='endbr64' for v in first_instr.values())) rethunk_enforced=x86_64 and (os.environ.get('NV_RS_KERNEL_RETHUNK')=='1' or (committed_run and os.environ.get('NV_RS_KERNEL_RETHUNK')!='0' and ('CONFIG_MITIGATION_RETHUNK=y' in kcfg_txt or 'CONFIG_RETHUNK=y' in kcfg_txt))) retpoline_enforced=x86_64 and (os.environ.get('NV_RS_KERNEL_RETPOLINE')=='1' or (committed_run and os.environ.get('NV_RS_KERNEL_RETPOLINE')!='0' and ('CONFIG_MITIGATION_RETPOLINE=y' in kcfg_txt or 'CONFIG_RETPOLINE=y' in kcfg_txt))) sls_enforced=x86_64 and (os.environ.get('NV_RS_KERNEL_SLS')=='1' or (committed_run and os.environ.get('NV_RS_KERNEL_SLS')!='0' and ('CONFIG_MITIGATION_SLS=y' in kcfg_txt or 'CONFIG_SLS=y' in kcfg_txt))) scs_enforced=aarch64 and (os.environ.get('NV_RS_KERNEL_SCS')=='1' or (committed_run and os.environ.get('NV_RS_KERNEL_SCS')!='0' and 'CONFIG_SHADOW_CALL_STACK=y' in kcfg_txt)) checks={'data_relocation_targets_resolve_to_instructions':True if not ibt_enforced else not unresolved and not ambiguous_targets,'module_present':object_only or module.exists(),'no_SIMD_x87_registers':not re.search(r'%(?:[xyz]mm\d+|mm\d+|st(?:\(|\b))',assembly),'no_ARM64_NEON_FP':True if not aarch64 else not re.search(r'\b[vqds](?:[0-9]|[12][0-9]|3[01])\b',assembly),'no_ARM64_x18_clobber_under_scs':True if not scs_enforced else not re.search(r'\t(?:mov|ldr|add|sub|orr|eor|and)\s+[xw]18,',assembly),'no_naked_ret_under_rethunk':True if not rethunk_enforced else not naked_ret_fns,'no_bare_indirect_branch_under_retpoline':True if not retpoline_enforced else not re.search(r'\t(?:callq?|jmpq?)\s+\*%r',assembly),'no_unhardened_sls_return':True if not sls_enforced else (not naked_ret_fns or has_int3),'no_Rust_unwind_sections':not any('eh_frame' in n or 'gcc_except_table' in n for n,_,_ in 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 export_names 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'])}|({'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 reloc_text,'distinct_diagnostic_module_name':run('modinfo','-F','name',str(module)).strip()=='nvidia_rs','no_PCI_aliases':not run('modinfo','-F','alias',str(module)).strip()} if not object_only and module.exists() else {}) 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_with_nonzero_addend':sum(1 for _,a,_ in data_relocs if a!=0),'unresolved_data_relocation_targets_in_code_sections':len(unresolved),'ambiguous_truncated_names':len(ambiguous),'unattributable_duplicate_names':len(duplicate_names),'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() if module.exists() else None,'undefined_kernel_symbols':undefined.splitlines(),'module_checks_run':not object_only and module.exists(),'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.'} if committed_run:(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_with_nonzero_addend':report['data_relocations_with_nonzero_addend'],'unresolved_code_targets':report['unresolved_data_relocation_targets_in_code_sections'],'ambiguous_truncated_names':report['ambiguous_truncated_names'],'unattributable_duplicate_names':report['unattributable_duplicate_names'],'ibt_gate_enforced':report['ibt_gate_enforced']}));raise SystemExit(0 if report['passed']else 1)