build: use kernel strlen instead of precompiled Rust builtin

This commit is contained in:
Andrew Jessop
2026-12-01 23:29:08 +00:00
parent 467008472b
commit 456fafd234
6 changed files with 178 additions and 6 deletions

View File

@ -1,5 +1,6 @@
ROOT := $(abspath ../..)
include $(ROOT)/utils.mk
NM ?= nm
RUST_COMMON := $(filter-out --crate-type=lib --emit=obj,$(RUST_KERNEL_FLAGS)) -C embed-bitcode=yes
OUT := $(ROOT)/kernel-open/nvidia
ABI_SRC := $(ROOT)/src/common/abi/src/lib.rs
@ -13,16 +14,21 @@ $(OUT)/libnv_rs_core.rlib: src/lib.rs $(CORE_SRC) $(OUT)/libnv_rs_abi.rlib Makef
$(RUSTC) $(RUST_COMMON) --crate-name nv_rs_core --crate-type=rlib $< --extern nv_rs_abi=$(OUT)/libnv_rs_abi.rlib -o $@
$(OUT)/libnv_rs_kernel.a: kernel/lib.rs $(KERNEL_SRC) $(OUT)/libnv_rs_core.rlib $(OUT)/libnv_rs_abi.rlib $(ROOT)/rust-toolchain.toml
$(RUSTC) $(RUST_COMMON) --crate-type=staticlib -C lto=fat --crate-name nv_rs_kernel $< --extern nv_rs_abi=$(OUT)/libnv_rs_abi.rlib --extern nv_rs_core=$(OUT)/libnv_rs_core.rlib -L dependency=$(OUT) -o $@
$(OUT)/nv-rust.o_binary: $(OUT)/libnv_rs_kernel.a
# Keep precompiled compiler_builtins strlen out of the kernel link: it was not
# compiled with this kernel's return-thunk/IBT flags. Linux exports strlen.
$(OUT)/libnv_rs_kernel.kernel.a: $(OUT)/libnv_rs_kernel.a $(ROOT)/tools/prepare_kernel_archive.py Makefile
python3 $(ROOT)/tools/prepare_kernel_archive.py $< $@ --ar "$(AR)" --nm "$(NM)"
$(OUT)/nv-rust.o_binary: $(OUT)/libnv_rs_kernel.kernel.a
$(LD) -r --gc-sections --whole-archive $< --no-whole-archive $(foreach name,protocol_version rmapi_state_size rmapi_state_align rmapi_init rmapi_gpu_add rmapi_gpu_remove rmapi_gpu_minor rmapi_gpu_open rmapi_attach_register_count rmapi_attach_register rmapi_gpu_needs_registers rmapi_gpu_attach_registers rmapi_set_host_bridge rmapi_set_force_p2p rmapi_set_gsp_abi rmapi_set_driver_version rmapi_gpu_release rmapi_register_fd rmapi_prepare rmapi_nested_plan rmapi_execute rmapi_copy_fault rmapi_close rmapi_rc_recover_fault alloc_reg_can_admit alloc_reg_insert alloc_reg_find alloc_reg_retain alloc_reg_mark_freed_and_put alloc_reg_put_ptr alloc_reg_for_each alloc_reg_total_pages alloc_reg_pop_any alloc_reg_release_storage dma_reg_find dma_reg_insert dma_reg_pop_for_alloc dma_reg_pop_for_dev file_map_insert_alloc file_map_insert_io file_map_get file_map_remove gpu_slot_activate gpu_slot_deactivate gpu_slot_is_live_gen gpu_slot_set_numa gpu_slot_validate_bar0 gpu_slot_validate_bar1 uvm_file_size uvm_file_align uvm_file_init uvm_route_size uvm_route_status_offset uvm_file_ioctl uvm_file_mmap uvm_file_vma_closed uvm_file_release uvm_service_replayable_faults uvm_node_cleanup uvm_iface_register_uvm_callbacks uvm_iface_deregister_uvm_ops uvm_iface_register_gpu uvm_iface_unregister_gpu uvm_iface_session_create uvm_iface_session_destroy uvm_iface_device_create uvm_iface_device_destroy uvm_iface_get_gpu_info uvm_iface_get_fb_info uvm_iface_get_ecc_info uvm_iface_get_nvlink_info uvm_iface_query_caps uvm_iface_query_copy_engines_caps uvm_iface_memory_alloc_fb uvm_iface_memory_alloc_sys uvm_iface_memory_free uvm_iface_service_device_interrupts_rm uvm_iface_own_page_fault_intr uvm_iface_address_space_create uvm_iface_address_space_destroy uvm_iface_set_page_directory uvm_iface_unset_page_directory uvm_iface_p2p_object_create uvm_iface_p2p_object_destroy uvm_iface_tsg_allocate uvm_iface_tsg_destroy uvm_iface_channel_allocate uvm_iface_channel_destroy uvm_iface_paging_channel_allocate uvm_iface_paging_channel_destroy uvm_iface_toggle_prefetch_faults uvm_iface_report_fatal_error uvm_iface_init_access_cntr_info uvm_iface_destroy_access_cntr_info uvm_iface_enable_access_cntr uvm_iface_disable_access_cntr uvm_iface_flush_replayable_fault_buffer uvm_iface_has_pending_non_replayable_faults uvm_iface_dup_address_space uvm_iface_dup_allocation uvm_iface_dup_memory uvm_iface_free_duped_handle uvm_iface_memory_cpu_map uvm_iface_memory_cpu_unmap uvm_iface_retain_channel uvm_iface_bind_channel_resources uvm_iface_stop_channel uvm_iface_release_channel uvm_iface_paging_channels_map uvm_iface_paging_channels_unmap uvm_iface_paging_channel_push_stream uvm_iface_report_non_replayable_fault uvm_iface_get_non_replayable_faults uvm_iface_get_pma_object uvm_iface_pma_register_eviction_callbacks uvm_iface_pma_unregister_eviction_callbacks uvm_iface_init_fault_info uvm_iface_destroy_fault_info uvm_iface_get_external_alloc_ptes uvm_iface_get_external_alloc_phys_addrs uvm_iface_get_channel_resource_ptes uvm_iface_pma_alloc_pages uvm_iface_pma_pin_pages uvm_iface_pma_free_pages uvm_iface_csl_init_context uvm_iface_deinit_csl_context uvm_iface_csl_rotate_key uvm_iface_csl_rotate_iv uvm_iface_csl_increment_iv uvm_iface_csl_query_message_pool uvm_iface_csl_log_encryption uvm_iface_csl_encrypt uvm_iface_csl_decrypt uvm_iface_get_p2p_caps uvm_iface_csl_sign uvm_iface_access_bits_buf_alloc uvm_iface_access_bits_buf_free uvm_iface_access_bits_buf_dump uvm_iface_register_uvm_events uvm_iface_deregister_uvm_events modeset_get_rm_ops modeset_alloc_stack modeset_free_stack modeset_enumerate_gpus modeset_open_gpu modeset_close_gpu modeset_op modeset_set_callbacks modeset_register_gpu modeset_unregister_gpu modeset_notify_suspend modeset_notify_resume gpu_capabilities device_size file_size state_align device_init file_open file_close ioctl nested_plan nested_copy_error rm_preflight rm_ioctl event_selftest pci_admitted gpu_state_size gpu_state_align gpu_prepare gpu_prepare_owned gpu_software_prepare gpu_first_open gpu_pm_suspend_begin gpu_pm_suspend_rollback gpu_pm_resume_begin gpu_pm_resume_finish gpu_pm_runtime_suspend gpu_pm_runtime_resume gpu_pm_is_suspended gpu_pm_verify_alive software_manager_init software_manager_shutdown gpu_set_probe_identity gpu_registry_publish gpu_registry_retire gpu_close gpu_set_cleanup gpu_mark_removed gpu_release_driver gpu_retry_cleanup sysmem_state_size sysmem_state_align sysmem_pin_size sysmem_pin_align sysmem_prepare sysmem_allocate sysmem_info sysmem_pin sysmem_unpin sysmem_sync sysmem_close gpu_events gpu_events_retry,-u nv_rs_$(name)) -o $@
$(OBJCOPY) --remove-section=.llvmbc --remove-section=.llvmcmd --remove-section=.eh_frame --remove-section=.eh_frame_hdr --remove-section=.gcc_except_table $@
clean:
$(RM) $(OUT)/libnv_rs_kernel.a $(OUT)/nv-rust.o_binary $(OUT)/libnv_rs_abi.rlib $(OUT)/libnv_rs_core.rlib
$(RM) $(OUT)/libnv_rs_kernel.kernel.a $(OUT)/libnv_rs_kernel.a $(OUT)/nv-rust.o_binary $(OUT)/libnv_rs_abi.rlib $(OUT)/libnv_rs_core.rlib
.PHONY: audit-codegen
audit-codegen: $(OUT)/libnv_rs_core.rlib $(OUT)/libnv_rs_abi.rlib
@mkdir -p $(ROOT)/target/codegen
$(RUSTC) $(RUST_COMMON) --cfg 'feature="codegen_audit"' --crate-type=staticlib -C lto=fat --crate-name nv_rs_codegen_audit kernel/lib.rs --extern nv_rs_abi=$(OUT)/libnv_rs_abi.rlib --extern nv_rs_core=$(OUT)/libnv_rs_core.rlib -L dependency=$(OUT) -o $(ROOT)/target/codegen/audit.a
$(RUSTC) $(RUST_COMMON) --cfg 'feature="codegen_audit"' --crate-type=staticlib -C lto=fat --crate-name nv_rs_codegen_audit kernel/lib.rs --extern nv_rs_abi=$(OUT)/libnv_rs_abi.rlib --extern nv_rs_core=$(OUT)/libnv_rs_core.rlib -L dependency=$(OUT) -o $(ROOT)/target/codegen/audit-rustc.a
python3 $(ROOT)/tools/prepare_kernel_archive.py $(ROOT)/target/codegen/audit-rustc.a $(ROOT)/target/codegen/audit.a --ar "$(AR)" --nm "$(NM)"
$(LD) -r --gc-sections --whole-archive $(ROOT)/target/codegen/audit.a --no-whole-archive $(foreach name,SMALL_VM_PREPARE SMALL_VM_FREEZE SMALL_VM_CLOSE NATIVE_POPULATE VRAM_PREPARE VRAM_CLOSE VRAM_CREATE VRAM_ALLOCATE VRAM_MAP VRAM_COPY VRAM_UNMAP VRAM_RELEASE VRAM_READ VRAM_READ_LOCKED VRAM_COPY_LOCKED FIRMWARE_UNPACK FIRMWARE_CLOSE NATIVE_WPR_POLICY_READ NATIVE_WPR_POLICY_CLOSE NATIVE_WPR_GATHER COLD_PCI_IRQ_POLICY GV100_STALL_PROGRAM GV100_NONSTALL_SERVICE GV100_TIMER_ACK GV100_FIFO_DEADLINE GV100_FIFO_NAMESPACE GV100_FIFO_PTIMER GV100_FIFO_ROTATION GV100_FIFO_WEIGHTED GV100_RUNLIST_PREEMPT GV100_FIFO_SWITCH GV100_FIFO_CONTEXT GV100_FIFO_CONTEXT_WRAPPER GV100_FIFO_LPWR GV100_PMU_MUTEX_ACQUIRE GV100_PMU_MUTEX_RELEASE GV100_LPWR_ENGINE GV100_PMU_COMMAND_MEMORY GV100_PMU_INIT GV100_PMU_WAIT GV100_PMU_STARTUP GV100_PMU_STAGE_COMMAND GV100_PMU_PUBLISH_COMMAND GV100_PMU_SUBMIT_COMMAND GV100_PMU_SUBMIT_SYNC GV100_PMU_STALL_SCOPE GV100_PMU_DEFERRED GV100_PMU_DEFERRED_WORKER GV100_STALL_PENDING GV100_ENGINE_DISCOVER GV100_STALL_FROM_FIFO LSF_IMAGE_PREPARE LSF_IMAGE_CLOSE LSF_ENTRY_HEADERS LSF_BOOT_DESCRIPTOR SHARED_BAR2_PREPARE SHARED_BAR2_CLOSE SHARED_BAR2_FREEZE SHARED_BAR2_BIND SHARED_BAR2_RETIRE SHARED_BAR2_REFERENCE SHARED_BAR2_INSERT SHARED_BAR2_REMOVE FAULT_PREPARE_DEFAULT FAULT_CLOSE FAULT_RETIRE DEVICE_SOFTWARE_PREPARE TIMEOUT_FIELDS TIMEOUT_COMMIT TIMEOUT_INTERNAL_COMMIT REGISTRY_DWORD_BASE REGISTRY_DWORD_COMPLETE QMD CONSTANTS PUSHBUFFER,-u NV_RS_AUDIT_$(name)) -o $(ROOT)/target/codegen/audit.o
$(OBJCOPY) --remove-section=.llvmbc --remove-section=.llvmcmd --remove-section=.eh_frame --remove-section=.eh_frame_hdr --remove-section=.gcc_except_table $(ROOT)/target/codegen/audit.o
@ -31,7 +37,8 @@ audit-codegen: $(OUT)/libnv_rs_core.rlib $(OUT)/libnv_rs_abi.rlib
.PHONY: audit-os-event
audit-os-event: $(OUT)/libnv_rs_core.rlib $(OUT)/libnv_rs_abi.rlib
@mkdir -p $(ROOT)/target/codegen
$(RUSTC) $(RUST_COMMON) --crate-type=staticlib -C lto=fat --crate-name nv_rs_os_event_audit $(ROOT)/tests/vm/rust_backing.rs --extern nv_rs_abi=$(OUT)/libnv_rs_abi.rlib --extern nv_rs_core=$(OUT)/libnv_rs_core.rlib -L dependency=$(OUT) -o $(ROOT)/target/codegen/os-event-production.a
$(RUSTC) $(RUST_COMMON) --crate-type=staticlib -C lto=fat --crate-name nv_rs_os_event_audit $(ROOT)/tests/vm/rust_backing.rs --extern nv_rs_abi=$(OUT)/libnv_rs_abi.rlib --extern nv_rs_core=$(OUT)/libnv_rs_core.rlib -L dependency=$(OUT) -o $(ROOT)/target/codegen/os-event-production-rustc.a
python3 $(ROOT)/tools/prepare_kernel_archive.py $(ROOT)/target/codegen/os-event-production-rustc.a $(ROOT)/target/codegen/os-event-production.a --ar "$(AR)" --nm "$(NM)"
$(LD) -r --gc-sections --whole-archive $(ROOT)/target/codegen/os-event-production.a --no-whole-archive -u vm_os_event -o $(ROOT)/target/codegen/os-event-production.o
$(OBJCOPY) --remove-section=.llvmbc --remove-section=.llvmcmd --remove-section=.eh_frame --remove-section=.eh_frame_hdr --remove-section=.gcc_except_table $(ROOT)/target/codegen/os-event-production.o
cd $(ROOT) && python3 tools/check_native_codegen.py --object target/codegen/os-event-production.o --report reports/timer-os-event-production-codegen.json --entrypoint vm_os_event --scope 'Compile-only real Linux OS-event wrapper exercise with the QEMU one-event test dispatch under unchanged utils.mk production flags; no guest memcpy/memset lowering overrides. This tests one concrete OS-only callback type, not an RM list/dispatch provider or GPU readiness. Per-function stack is not a call-chain bound. Object never loaded.'

View File

@ -291,6 +291,25 @@ class KernelModuleGate(unittest.TestCase):
self.assertTrue(check(object_path)["checks"]["module_present"])
CASES_RUN.append("module-required")
def test_rethunk_checks_compiler_builtin_names(self):
# The name must not exempt code emitted by an unhardened compiler_builtins.
OUT.mkdir(parents=True, exist_ok=True)
for name in ("strlen", "memcmp", "bcmp"):
for hardened in (False, True):
with self.subTest(name=name, hardened=hardened):
path = OUT / f"{name}-{hardened}.o"
instruction = "jmp __x86_return_thunk" if hardened else "ret"
source = f".text\n.globl {name}\n.type {name}, @function\n{name}:\n {instruction}\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="0", NV_RS_KERNEL_RETHUNK="1"),
)
report = json.loads(result.stdout)
self.assertEqual(report["checks"]["no_naked_ret_under_rethunk"], hardened)
CASES_RUN.append(f"rethunk-{name}-{hardened}")
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`,

View File

@ -0,0 +1,86 @@
#!/usr/bin/env python3
"""Exercise the production archive preparer with real assembler/ar/linker inputs."""
import importlib.util
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
spec = importlib.util.spec_from_file_location("kernel_archive", ROOT / "tools/prepare_kernel_archive.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
class KernelArchiveTest(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
self.source = self.root / "source.a"
self.destination = self.root / "kernel.a"
def archive(self, objects):
paths = []
for name, assembly in objects:
path = self.root / name
subprocess.run(["as", "-o", str(path)], input=assembly, text=True, check=True)
paths.append(str(path))
subprocess.run(["ar", "rcs", str(self.source), *paths], check=True)
def symbols(self, path):
return subprocess.check_output(["nm", "--format=posix", str(path)], text=True)
def test_link_imports_kernel_strlen_and_keeps_other_helpers(self):
self.archive([
("entry.o", ".text\n.globl entry\nentry: call strlen\ncall helper\nret\n"),
("compiler_builtins-any-hash.o", ".text\n.weak strlen\nstrlen: ret\n"),
("compiler_builtins-other.o", ".text\n.globl helper\nhelper: ret\n"),
])
original = self.source.read_bytes()
module.prepare(self.source, self.destination)
linked = self.root / "linked.o"
subprocess.run(["ld", "-r", "--gc-sections", "-u", "entry", "--whole-archive",
str(self.destination), "--no-whole-archive", "-o", str(linked)], check=True)
symbols = self.symbols(linked)
self.assertIn("strlen U", symbols)
self.assertIn("helper T", symbols)
self.assertNotIn("strlen W", symbols)
self.assertEqual(self.source.read_bytes(), original)
def test_archive_without_strlen_is_preserved(self):
self.archive([("entry.o", ".text\n.globl entry\nentry: ret\n")])
module.prepare(self.source, self.destination)
self.assertEqual(self.source.read_bytes(), self.destination.read_bytes())
def test_refuses_to_remove_another_export_or_unknown_provider(self):
for name, extra in (("compiler_builtins-mixed.o", ".globl needed\nneeded: ret\n"),
("custom-strlen.o", "")):
with self.subTest(name=name):
self.source.unlink(missing_ok=True)
self.archive([(name, ".text\n.weak strlen\nstrlen: ret\n" + extra)])
self.destination.write_bytes(b"previous good archive")
original = self.source.read_bytes()
with self.assertRaisesRegex(ValueError, "cannot safely omit"):
module.prepare(self.source, self.destination)
self.assertEqual(self.source.read_bytes(), original)
self.assertEqual(self.destination.read_bytes(), b"previous good archive")
def test_refuses_ambiguous_duplicate_members(self):
name = "compiler_builtins-duplicate.o"
self.archive([(name, ".text\n.weak strlen\nstrlen: ret\n")])
subprocess.run(["ar", "q", str(self.source), str(self.root / name)], check=True)
with self.assertRaisesRegex(ValueError, "cannot safely omit"):
module.prepare(self.source, self.destination)
self.assertFalse(self.destination.exists())
def test_refuses_to_overwrite_rustc_archive(self):
self.archive([("entry.o", ".text\n.globl entry\nentry: ret\n")])
original = self.source.read_bytes()
with self.assertRaisesRegex(ValueError, "must differ"):
module.prepare(self.source, self.source)
self.assertEqual(self.source.read_bytes(), original)
if __name__ == "__main__":
unittest.main()

View File

@ -41,7 +41,7 @@ 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();has_int3=False;builtin_exempt={'strlen','memcmp','bcmp'}
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
for line in assembly.splitlines():
m=re.match(r'^Disassembly of section (\S+):',line)
if m:
@ -59,7 +59,7 @@ for line in assembly.splitlines():
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 in ('ret','retq'):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)

View File

@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""Leave strlen to Linux instead of linking Rust's precompiled, unhardened copy.
Select by exported symbol, not compiler-specific archive member hashes. Refuse
an unexpected layout rather than removing another helper along with strlen.
Only the generated copy is modified; the rustc archive remains intact.
"""
import argparse
import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
def prepare(source: Path, destination: Path, ar: str = "ar", nm: str = "nm") -> None:
if source.resolve() == destination.resolve():
raise ValueError("source and destination must differ")
output = subprocess.check_output(
[nm, "--format=posix", "--print-file-name", "--extern-only", "--defined-only", str(source)],
text=True, env=dict(os.environ, LC_ALL="C"),
)
pattern = re.compile(re.escape(str(source)) + r"\[(.+)\]: (\S+)\s+(\S)(?:\s|$)")
exports = {}
for line in output.splitlines():
if not line.strip():
continue
match = pattern.match(line)
if not match:
raise ValueError(f"unrecognised nm archive output: {line}")
member, symbol, kind = match.groups()
exports.setdefault(member, set()).add((symbol, kind))
remove = [member for member, symbols in exports.items() if any(s == "strlen" for s, _ in symbols)]
members = subprocess.check_output([ar, "t", str(source)], text=True).splitlines()
for member in remove:
if (not member.startswith("compiler_builtins-") or exports[member] != {("strlen", "W")}
or members.count(member) != 1):
raise ValueError(f"cannot safely omit strlen member {member}: {sorted(exports[member])}")
with tempfile.TemporaryDirectory(dir=destination.parent) as directory:
temporary = Path(directory) / "kernel.a"
shutil.copyfile(source, temporary)
if remove:
subprocess.run([ar, "d", str(temporary), *remove], check=True)
temporary.replace(destination)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("source", type=Path)
parser.add_argument("destination", type=Path)
parser.add_argument("--ar", default="ar")
parser.add_argument("--nm", default="nm")
args = parser.parse_args()
prepare(args.source, args.destination, args.ar, args.nm)
if __name__ == "__main__":
main()

View File

@ -33,6 +33,7 @@ step test cargo test --workspace
for t in device_software software_manager timeout_runtime pf_software dma_bridge clock_store file_cleanup gpu_arch_codegen gpu_registry pci_bridge registry_bridge rom_capture_bridge system_memory_bridge thread_state_bridge wpr_shadow_owner; do step test_$t sh tools/test_$t.sh; done
optional_step test_native_compute sh tools/test_native_compute.sh
step test_kernel_module_gate python3 tests/kernel-module-gate/test_gate_cases.py
step test_kernel_archive python3 tests/kernel-module-gate/test_kernel_archive.py
for t in gpu_firmware_owner lsf_image_owner; do step test_$t bash tools/test_$t.sh; done
step modules make modules
step audit make -C src/nvidia audit-codegen