Files
nvdriver/tools/check_native_codegen.py
Eric Hartford d5e0b9bb87 Wave 7A: Proactive P0 lock/UAF fixes and kernel build/compat hardening
Cluster 2 (RMAPI/UVM/Locking/Memory P0s):
- Convert runtime_start_users to atomic_t so wait_event() in
  nv_rs_rmapi_node_gpu_remove never calls mutex_lock while !TASK_RUNNING.
- Guard all 6 unlocked nv_rs_alloc_reg_find() call sites in rmapi_node.c with
  nv_rs_rmapi_alloc_lock.
- Run nv_rs_rmapi_rc_recover_fault while nv_rs_rmapi_lock is held from
  nv_rs_rmapi_node_trylock() in nv_rs_uvm_fault_work_fn (no blocking re-lock).
- Filter MANAGED_RANGES and PAGE_TREES by UvmFile owner in uvm_node.rs to
  prevent cross-process managed_unmap UAF; use flush_gpu_tlb_trylock() +
  TLB_FLUSH_PENDING deferral so .mmap/vm_ops->close never touch LIVE_ENGINES
  without nv_rs_rmapi_lock.
- Pin FD-exported memory backings in memory::Table::export_pins and check via
  shared backing_shares_resource() so export -> free original -> import never
  UAFs; release orphaned backings on FD owner close.
- Fix Backing::System map_protection(flags), deduplicate video_allocated_bytes,
  and unmap Backing::Register in drop_mappings.

Cluster 4 (Kernel Build Hygiene & Linux 5.15-7.3 Compat P0s):
- Factor shared kernel-open/compat_probes.mk for Kbuild + build_guest_test.sh
  (fixing Linux 5.15 char *date probe and Linux 7.0+ guest_build).
- Extend tools/prepare_kernel_archive.py to strip all kernel-exported
  compiler_builtins mem/string members (strlen/memcpy/memmove/memset/memcmp/bcmp)
  and wire it into tools/vm/build_guest_test.sh.
- Fix tools/check_kernel_module.py no_unhardened_sls_return to check per-ret
  int3 succession instead of file-wide has_int3.
- Set AR=llvm-ar / NM=llvm-nm under LLVM=1 in utils.mk, LC_ALL=C and non-rustup
  fallback in verify_rust_guest.py/check_native_codegen.py, and 1024 MiB guest RAM.

Validated: cargo fmt/clippy/test (958+2), test_gate_cases.py (24/24),
test_kernel_archive.py (5/5), NV_RS_KERNEL_IBT=0 & 1 make modules +
check_kernel_module.py (largest_stack=1000), QEMU EDU verify_rust_guest.py.
2026-12-02 01:34:46 +00:00

61 lines
5.4 KiB
Python

#!/usr/bin/env python3
"""Inspect retained real constructors under production flags. Never load code."""
import hashlib
import argparse
import json
from pathlib import Path
import os
import re
import shutil
import subprocess
import tempfile
ROOT = Path(__file__).resolve().parents[1]
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--object',type=Path,default=ROOT/'target/codegen/audit.o')
parser.add_argument('--report',type=Path,default=ROOT/'reports/native-path-codegen-validation.json')
parser.add_argument('--entrypoint',action='append',help='Explicit alternative retained entrypoint; defaults retain every production audit root')
parser.add_argument('--scope')
options = parser.parse_args()
obj = options.object
def run(*args): return subprocess.check_output(args, text=True, env=dict(os.environ, LC_ALL='C'))
# A concurrent rebuild can replace the input between binutils invocations.
# Inspect and hash the same private snapshot for the entire report.
with tempfile.TemporaryDirectory() as directory:
snapshot = Path(directory) / obj.name
shutil.copyfile(obj, snapshot)
assembly = run('objdump', '-drC', str(snapshot))
relocations = run('readelf', '-rW', str(snapshot))
sections = run('readelf', '-SW', str(snapshot))
symbols = run('nm', '--defined-only', str(snapshot))
undefined_symbols = run('nm', '-u', str(snapshot)).splitlines()
object_sha256 = hashlib.sha256(snapshot.read_bytes()).hexdigest()
fn = ''
frames = {}
for line in assembly.splitlines():
match = re.search(r'^[0-9a-f]+ <(.+)>:$', line)
if match: fn = match[1]
match = re.search(r'\bsub\s+\$0x([0-9a-f]+),%rsp', line)
if match: frames[fn] = frames.get(fn, 0) + int(match[1], 16)
if re.search(r'\bpush\s', line): frames[fn] = frames.get(fn, 0) + 8
required = ['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', 'DEVICE_SOFTWARE_PREPARE', 'TIMEOUT_FIELDS', 'TIMEOUT_COMMIT', 'TIMEOUT_INTERNAL_COMMIT', 'REGISTRY_DWORD_BASE', 'REGISTRY_DWORD_COMPLETE', 'FAULT_PREPARE_DEFAULT', 'FAULT_CLOSE', 'FAULT_RETIRE', 'QMD', 'CONSTANTS', 'PUSHBUFFER']
checks = {
'actual_constructor_and_payload_roots_present': all(name in {line.split()[-1] for line in symbols.splitlines()} for name in (options.entrypoint or ['NV_RS_AUDIT_' + n for n in required])),
'no_unsupported_GOT_relocations': 'GOT' not in relocations,
'no_SIMD_x87_registers': not re.search(r'%(?:[xyz]mm\d+|mm\d+|st(?:\(|\b))', assembly),
'bounded_fixed_function_stack': max(frames.values(), default=0) <= 1024,
'no_dynamic_RSP_subtraction': not re.search(r'\bsub\s+%[^,]+,%rsp', assembly),
'no_unwind_sections': not re.search(r'\.eh_frame|\.gcc_except_table', sections),
}
report = {'passed': all(checks.values()), 'checks': checks,
'largest_conservative_function_stack_bytes': max(frames.values(), default=0),
'largest_functions': sorted(frames.items(), key=lambda item: item[1], reverse=True)[:20],
'object_sha256': object_sha256,
'undefined_symbols': undefined_symbols,
'scope': 'Compile-only retained production SmallVm prepare/freeze/close and native payload composition/writers plus VRAM owner methods firmware unpack/close, and native WPR policy/gather and selected LSF image construction/headers/boot descriptors and concrete shared BAR2 prepare/close/freeze/bind/retire/reference/insert/remove and its actual fault prepare/default/close/retire, and actual canonical timeout field reads/commits and named DWORD base/complete registry composition and cold PCI IRQ policy and GV100 stall programming/routing and engine discovery, with utils.mk production flags and no guest memcpy/memset threshold overrides. Conservative per-function frame accounting is not a complete call-chain stack proof. This object must never be loaded or executed.'}
if options.scope: report['scope'] = options.scope
report['required_entrypoints'] = options.entrypoint or ['NV_RS_AUDIT_' + n for n in required]
options.report.write_text(json.dumps(report, indent=2) + '\n')
print(json.dumps({'passed': report['passed'], 'checks': checks, 'largest_functions': report['largest_functions'][:4]}))
raise SystemExit(0 if report['passed'] else 1)