mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
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>
This commit is contained in:
@ -428,6 +428,35 @@ class KernelModuleGate(unittest.TestCase):
|
||||
self.assertEqual(report["checks"]["no_naked_ret_under_rethunk"], hardened)
|
||||
CASES_RUN.append(f"rethunk-{name}-{hardened}")
|
||||
|
||||
def test_rust_object_calls_to_memcpy_memset_memmove_are_refused(self):
|
||||
# CLAUDE.md and AGENTS.md say the module check fails on these calls; it did not
|
||||
# look for them. prepare_kernel_archive.py drops the compiler_builtins copies, so a lowered copy or
|
||||
# fill in Rust would bind to the kernel's symbol and pass unnoticed. "defined" keeps a local
|
||||
# definition beside the call: a builtin that survived the archive step is still a call. strlen is
|
||||
# allowed on purpose (456fafd2 binds Rust's CStr calls to Linux's strlen), so it must stay green.
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
for name, refused in (("memcpy", True), ("memset", True), ("memmove", True), ("strlen", False)):
|
||||
for defined in (False, True):
|
||||
with self.subTest(name=name, defined=defined):
|
||||
path = OUT / f"call-{name}-{'defined' if defined else 'undefined'}.o"
|
||||
source = ".text\n.globl caller\n.type caller, @function\ncaller:\n endbr64\n call " + name + "\n int3\n"
|
||||
if defined:
|
||||
source += f".globl {name}\n.type {name}, @function\n{name}:\n endbr64\n int3\n"
|
||||
subprocess.run(["as", "-o", str(path)], input=source, text=True, check=True)
|
||||
result = subprocess.run(
|
||||
[sys.executable, str(CHECKER), str(path), "--object-only"],
|
||||
capture_output=True, text=True, env=dict(os.environ, NV_RS_KERNEL_IBT="1"),
|
||||
)
|
||||
report = json.loads(result.stdout)
|
||||
self.assertEqual(report["checks"]["no_Rust_object_calls_to_memcpy_memset_memmove"], not refused)
|
||||
self.assertEqual(report["rust_object_calls_to_memcpy_memset_memmove"], [name] if refused else [])
|
||||
self.assertEqual(f"calls {name};" in result.stderr, refused)
|
||||
CASES_RUN.append(f"rust-call-{name}-{'defined' if defined else 'undefined'}")
|
||||
with self.subTest(case="no-call-control"):
|
||||
report = check(case_object("entry"))
|
||||
self.assertTrue(report["checks"]["no_Rust_object_calls_to_memcpy_memset_memmove"])
|
||||
CASES_RUN.append("rust-call-none")
|
||||
|
||||
def test_rethunk_and_sls_static_mitigation_gates(self):
|
||||
# Synthetic case_object("entry") contains a naked `ret` without `int3`:
|
||||
# under NV_RS_KERNEL_RETHUNK=1 it must fail `no_naked_ret_under_rethunk`,
|
||||
|
||||
@ -112,6 +112,17 @@ for sec,sym,off,addend in elf_relocs:
|
||||
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)
|
||||
@ -120,7 +131,8 @@ rethunk_enforced=x86_64 and (os.environ.get('NV_RS_KERNEL_RETHUNK')=='1' or (com
|
||||
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_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.'}
|
||||
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']}));raise SystemExit(0 if report['passed']else 1)
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user