Files
nvdriver/tools/check_kernel_module.py
AutoJanitor 618a270c09 tools: fail the module check on Rust-object calls to memcpy/memset/memmove (#478)
CLAUDE.md, AGENTS.md, docs/GPU_BRINGUP_GUIDE.md and CONTRIBUTING.md say
tools/check_kernel_module.py fails on calls to memcpy, memset and memmove.
It had no such check: its only undefined-symbol test looks for private
nv_rs_/Rust runtime names, and prepare_kernel_archive.py removes the
compiler_builtins copies of these helpers, so a lowered copy or fill in
Rust would bind to the kernel's symbol and the gate would stay green.

Add no_Rust_object_calls_to_memcpy_memset_memmove. It reads the Rust
object (nv-rust.o_binary), not nvidia_rs.ko: the thin C adapters
legitimately call the kernel's memcpy/memset (dma_adapter.o, rmapi_node.o,
gpu_owner.o, ...). A call is any relocation against one of the three names
or the name left undefined, whether or not the object also defines it.
Every REL/RELA section counts, .rela.debug_* included, which errs toward
refusing. The check also runs under --object-only. The offending names
are printed on stderr and listed under
rust_object_calls_to_memcpy_memset_memmove in the stdout JSON in every
mode, and in the committed report on a no-argument run.

Blind spot: a call to a local or hidden definition in the same section
resolves without a relocation and is not seen. That cannot happen with
today's build, because prepare_kernel_archive.py deletes the
compiler_builtins copies.

strlen is allowed on purpose and the comment says so: 456fafd2 removes
the precompiled compiler_builtins strlen so Rust's core::ffi::CStr calls
(kernel/irq.rs ColdPciPolicy::resolve) bind to the strlen Linux exports.
CONTRIBUTING.md:18 disagrees: it also lists strlen. That is left as a
question for the maintainers rather than changed here.

Test: test_gate_cases.py assembles a caller of each of memcpy, memset,
memmove and strlen, with and without a local definition. Before this
change the three mem* cases error (no such check). After it, the new
check is false for them, the JSON lists exactly that name and stderr
says "calls <name>;". For strlen the check is true, the list is empty
and stderr names nothing. On the current tree the Rust object's only
libc-style import is strlen, so make modules passes.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 16:16:11 -08:00

139 lines
13 KiB
Python

#!/usr/bin/env python3
"""Check the built diagnostic module before any load; no hardware access."""
import hashlib,json,os,re,shutil,struct,subprocess,sys
from pathlib import Path
root=Path(__file__).resolve().parents[1]
args=sys.argv[1:];pos=[a for a in args if a!='--object-only'];obj=Path(pos[0]) if pos else root/'kernel-open/nvidia/nv-rust.o_binary';module=Path(pos[1]) if len(pos)>1 else root/'kernel-open/nvidia_rs.ko';object_only='--object-only' in args;committed_run=not args
# Binutils headings are parsed below; keep their output independent of the user locale.
def run(*args):
if args[0]=='modinfo':
executable=shutil.which('modinfo') or shutil.which('modinfo',path='/usr/sbin:/sbin')
if executable is None:raise SystemExit('modinfo is required for module checks; install kmod or add modinfo to PATH')
args=(executable,*args[1:])
return subprocess.check_output(args,text=True,env=dict(os.environ,LC_ALL="C"))
EXEC,ALLOC,SYMTAB,RELA,REL,SHN_UNDEF,SHN_LORESERVE,SHN_XINDEX,SHT_SYMTAB_SHNDX,STT_FUNC,STT_SECTION=4,2,2,4,9,0,0xff00,0xffff,18,2,3
# 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('<IIQQQQIIQQ',raw[eh[6]+i*64:eh[6]+i*64+64])
def blob(i):s=sh(i);return raw[s[4]:s[4]+s[5]]
def cstr(t,o):end=t.find(b'\0',o);return t[o:end if end!=-1 else len(t)].decode()
h0=sh(0)
shnum=eh[12] if eh[12] and eh[12]<SHN_LORESERVE else h0[5]
shstrndx=eh[13] if eh[13]<SHN_LORESERVE else h0[6]
shnames=blob(shstrndx)
shlist=[sh(i) for i in range(shnum)];sections=[(cstr(shnames,s[0]),s[2],s[7]) for s in shlist]
elf_symbols={};func_entries=set()
for i,s in enumerate(shlist):
if s[1]==SYMTAB:
body=blob(i);names=blob(s[6])
shndx=next((blob(j) for j,t in enumerate(shlist) if t[1]==SHT_SYMTAB_SHNDX and t[6]==i),None)
for k in range(s[5]//(s[9] or 1)):
e=struct.unpack('<IBBHQQ',body[k*s[9]:k*s[9]+s[9]])
st_type=e[1]&0xf;raw_index=e[3] # st_shndx as written, before SHN_XINDEX expansion
idx=struct.unpack('<I',shndx[k*4:k*4+4])[0] if raw_index==SHN_XINDEX and shndx else raw_index
elf_symbols[k]=(idx,e[4],cstr(names,e[0]),raw_index,st_type)
if st_type==STT_FUNC and raw_index!=SHN_UNDEF and not (SHN_LORESERVE<=raw_index<SHN_XINDEX) and idx<shnum:
func_entries.add((idx,e[4]))
break
export_names={n for _,_,n,raw_index,_ in elf_symbols.values() if n and raw_index!=SHN_UNDEF}
elf_relocs=[]
for i,s in enumerate(shlist):
if s[1] in (RELA,REL):
ent=s[9] or (24 if s[1]==RELA else 16);body=blob(i)
for k in range(s[5]//ent):r=body[k*ent:k*ent+ent];off,info=struct.unpack('<QQ',r[:16]);elf_relocs.append((s[7],info>>32,off,struct.unpack('<q',r[16:24])[0] if s[1]==RELA else 0))
assembly=run('objdump','-dr',str(obj));reloc_text=run('readelf','-rW',str(module)) if not object_only and module.exists() else '';undefined=run('nm','-u',str(module)) if not object_only and module.exists() else '';frames={};fn='';first_instr={};instr_at={};ambiguous=set();unattributable=set();duplicate_names=set();name_map={}
for i,(n,f,inf) in enumerate(sections):
name_map.setdefault(n,[]).append(i)
for n,c in name_map.items():
if len(c)>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();unhardened_sls_ret=set();prev_was_ret=False;has_arm64_neon_fp=False
for line in assembly.splitlines():
m=re.match(r'^Disassembly of section (\S+):',line)
if m:
if prev_was_ret:unhardened_sls_ret.add(fn);prev_was_ret=False
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:
if prev_was_ret:unhardened_sls_ret.add(fn);prev_was_ret=False
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 prev_was_ret and instr!='int3':unhardened_sls_ret.add(fn)
prev_was_ret=instr in ('ret','retq')
if prev_was_ret:naked_ret_fns.add(fn)
if aarch64:
ma=re.match(r'^\s*([0-9a-f]+):\s+(?:(?:[0-9a-f]{2}\s+){4}|[0-9a-f]{8}\s+)(.+)$',line)
if ma:
ins=re.sub(r'\b[0-9a-f]+\s+<[^>]+>|<[^>]+>|//.*','',ma[2]).strip()
ip=ins.split(None,1)
if len(ip)==2 and not re.match(r'^(?:b(?:\.[a-z]+)?|bl|cbn?z|tbn?z|adrp?)$',ip[0]) and re.search(r'\b[vqdsbh](?:[0-9]|[12][0-9]|3[01])\b',ip[1]):has_arm64_neon_fp=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)
if prev_was_ret:unhardened_sls_ret.add(fn)
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
# __patchable_function_entries is kernel call-padding metadata (CONFIG_CALL_PADDING),
# pointing to the pre-entry NOP prefix rather than an indirect-call target.
if sections[sec][0]=='__patchable_function_entries':continue
target,value,name,st_type=sec,0,sections[sec][0],STT_SECTION
if sym:
e=elf_symbols.get(sym)
if not e:continue
target,value,name,raw_index,st_type=e
if target is None:unresolved.append((name,value+addend));continue
if SHN_LORESERVE<=raw_index<SHN_XINDEX:continue # a reserved st_shndx is a special value, not a section reference
if target>=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)
# Under CONFIG_CALL_PADDING (-Z patchable-function-entry=N,N), a per-function code section
# starts with N single-byte NOPs (0x90) before the STT_FUNC entry at +N, so section-relative
# function-pointer relocations carry addend == N while targeting the exact function entry.
ts=shlist[target]
padded_entry=addend>0 and st_type==STT_SECTION and value==0 and key in func_entries and ts[5]>=addr and raw[ts[4]:ts[4]+addr]==b'\x90'*addr
if key in instr_at:data_relocs.append((name,0 if (addend==0 or padded_entry) else 1,instr_at[key]))
else:unresolved.append((name,addr))
# CLAUDE.md and AGENTS.md: the Rust object makes no calls to memcpy, memset or memmove.
# Judged on the Rust object, not on the .ko, whose thin C adapters legitimately call the kernel's copies.
# A call is any relocation against one of these names, or the name left undefined, whether or not the
# object also defines it. strlen is allowed on purpose: prepare_kernel_archive.py removes the precompiled
# compiler_builtins strlen so that core::ffi::CStr calls bind to the strlen Linux exports (456fafd2).
# CONTRIBUTING.md:18 disagrees: it also lists strlen.
# Every REL/RELA section counts, .rela.debug_* included, so a reference from debug info is refused too.
# Blind spot: a call to a local or hidden definition in the same section resolves without a relocation.
# That cannot happen with today's build: prepare_kernel_archive.py deletes the compiler_builtins copies.
FORBIDDEN_RUST_CALLS={'memcpy','memset','memmove'}
rust_forbidden_calls=sorted({e[2] for e in elf_symbols.values() if e[2] in FORBIDDEN_RUST_CALLS and e[3]==SHN_UNDEF}|{elf_symbols[sym][2] for _,sym,_,_ in elf_relocs if sym in elf_symbols and elf_symbols[sym][2] in FORBIDDEN_RUST_CALLS})
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':not has_arm64_neon_fp,'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 unhardened_sls_ret,'no_Rust_object_calls_to_memcpy_memset_memmove':not rust_forbidden_calls,'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(),'rust_object_calls_to_memcpy_memset_memmove':rust_forbidden_calls,'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 rust_forbidden_calls:print(f"check_kernel_module: {obj} calls {', '.join(rust_forbidden_calls)}; the Rust object must not call memcpy/memset/memmove (CLAUDE.md, AGENTS.md). Find the caller with objdump -dr and replace the copy or fill with explicit loads/stores.",file=sys.stderr)
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'],'rust_object_calls_to_memcpy_memset_memmove':rust_forbidden_calls}));raise SystemExit(0 if report['passed']else 1)