mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
Merge pull request #325 from morebrackets/fix/kernel-verify-object-accuracy-and-portability
kernel: fix verify-object.py symbol, stack, GOT, and modinfo checks
This commit is contained in:
@ -1,65 +1,300 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Inspect actual generated Rust machine code; never load a module."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
root = pathlib.Path(__file__).resolve().parents[3]
|
||||
obj = root / 'kernel-open/nvidia/nv-rust.o_binary'
|
||||
module = root / 'kernel-open/nvidia_rs.ko'
|
||||
def run(*args):
|
||||
return subprocess.check_output(args, text=True)
|
||||
assembly = run('objdump', '-dr', str(obj))
|
||||
sections = run('readelf', '-SW', str(obj))
|
||||
undefined = run('nm', '-u', str(obj)).strip()
|
||||
exports = run('nm', '--defined-only', str(obj))
|
||||
undefined_symbols = {line.split()[-1] for line in undefined.splitlines()}
|
||||
# Private C adapters are resolved inside this module, never by another driver.
|
||||
# Keep this explicit: accepting an arbitrary nv_rs_* name would hide missing code.
|
||||
private_adapters = {'nv_rs_dma_context_create', 'nv_rs_dma_context_close',
|
||||
'nv_rs_dma_context_force_close', 'nv_rs_dma_context_leaked',
|
||||
'nv_rs_dma_allocate', 'nv_rs_dma_map', 'nv_rs_dma_unmap', 'nv_rs_dma_release',
|
||||
'nv_rs_copy_owned', 'nv_rs_gpu_module_get', 'nv_rs_gpu_module_put',
|
||||
'nv_rs_gpu_registry_lock', 'nv_rs_gpu_registry_unlock',
|
||||
'nv_rs_rom_acpi_read', 'nv_rs_pci_bar0_info', 'nv_rs_registry_open', 'nv_rs_registry_close',
|
||||
'nv_rs_registry_read', 'nv_rs_registry_read_string', 'nv_rs_registry_write'}
|
||||
kernel_memory = {'memcpy', 'memset', 'memmove', 'memcmp', 'bcmp'}
|
||||
nano_adapters = {'nv_rs_nano_payload_alloc', 'nv_rs_nano_payload_free',
|
||||
'nv_rs_nano_create', 'nv_rs_nano_start',
|
||||
'nv_rs_nano_cancel', 'nv_rs_nano_destroy'}
|
||||
private_adapters |= nano_adapters
|
||||
module_definitions = {line.split()[-1] for line in run('nm', '--defined-only', str(module)).splitlines() if line.split()}
|
||||
referenced_adapters = undefined_symbols & private_adapters
|
||||
checks = {
|
||||
'no_unresolved_rust_or_userspace_symbols': undefined_symbols <= kernel_memory | private_adapters,
|
||||
'private_adapters_resolved_in_module': referenced_adapters <= module_definitions,
|
||||
'nano_timer_adapters_present': nano_adapters <= module_definitions,
|
||||
'prepared_gpu_registry_entries_present': all(' T nv_rs_gpu_registry_' + name in exports
|
||||
for name in ('publish', 'retire')),
|
||||
'pci_probe_identity_entry_present': ' T nv_rs_gpu_set_probe_identity' in exports,
|
||||
'prepared_gpu_registry_lock_adapters_present':
|
||||
{'nv_rs_gpu_registry_lock', 'nv_rs_gpu_registry_unlock'} <= module_definitions,
|
||||
'no_simd_or_x87_registers': not re.search(r'%(?:[xyz]mm\d+|mm\d+|st(?:\(|\b))', assembly),
|
||||
'no_kernel_unsupported_got_relocations': 'GOT' not in run('readelf', '-rW', str(module)),
|
||||
'no_unwind_sections': not re.search(r'\.eh_frame|\.gcc_except_table', sections),
|
||||
'no_stack_reservation_above_1024_bytes': all(int(v,16)<=1024 for v in re.findall(r'sub\s+\$0x([0-9a-f]+),%rsp', assembly)),
|
||||
'no_rsp_redzone_references': not re.search(r'-0x[0-9a-f]+\(%rsp\)', assembly),
|
||||
'rust_protocol_entry_present': ' T nv_rs_protocol_version' in exports,
|
||||
'rust_event_selftest_present': ' T nv_rs_event_selftest' in exports,
|
||||
'rust_capabilities_entry_present': ' T nv_rs_gpu_capabilities' in exports,
|
||||
'rust_system_memory_entries_present': all(' T nv_rs_sysmem_' + name in exports
|
||||
for name in ('state_size', 'state_align', 'pin_size', 'pin_align', 'prepare',
|
||||
'allocate', 'info', 'pin', 'unpin', 'sync', 'close')),
|
||||
'distinct_module_name': run('modinfo', '-F', 'name', str(module)).strip() == 'nvidia_rs',
|
||||
'no_pci_aliases': not run('modinfo', '-F', 'alias', str(module)).strip(),
|
||||
}
|
||||
report = {'checks': checks, 'rust_object_undefined_symbols': sorted(undefined_symbols),
|
||||
'private_adapters_resolved_in_module': sorted(referenced_adapters & module_definitions),
|
||||
'kernel_vermagic': run('modinfo', '-F', 'vermagic', str(module)).strip(),
|
||||
'sha256': {str(p.relative_to(root)): hashlib.sha256(p.read_bytes()).hexdigest() for p in (obj, module)},
|
||||
'limits': ['Machine-code checks cover this build only.', 'This static check does not prove live execution; see the build-matched live-control-session.json.',
|
||||
'Opt-in PCI bridge is present; empty pci_target binds no GPUs. Physical PCI/DMA/GPU behavior remains unvalidated.']}
|
||||
print(json.dumps(report, indent=2))
|
||||
raise SystemExit(0 if all(checks.values()) else 1)
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[3]
|
||||
DEFAULT_OBJ = ROOT / "kernel-open/nvidia/nv-rust.o_binary"
|
||||
DEFAULT_MODULE = ROOT / "kernel-open/nvidia_rs.ko"
|
||||
|
||||
# Kernel runtime helpers that Rust codegen or kernel mitigations may emit as
|
||||
# external references in nv-rust.o_binary. Forbidden bulk memory routines
|
||||
# (memcpy/memset/memmove) are intentionally excluded.
|
||||
ALLOWED_KERNEL_EXTERNALS = frozenset(
|
||||
{
|
||||
"memcmp",
|
||||
"bcmp",
|
||||
"strlen",
|
||||
"strnlen",
|
||||
"__x86_return_thunk",
|
||||
"__fentry__",
|
||||
"_mcount",
|
||||
"__stack_chk_fail",
|
||||
}
|
||||
)
|
||||
ALLOWED_KERNEL_EXTERNAL_PREFIXES = (
|
||||
"__x86_indirect_thunk_",
|
||||
"__arm64_",
|
||||
)
|
||||
FORBIDDEN_MEMORY_ROUTINES = frozenset({"memcpy", "memset", "memmove"})
|
||||
|
||||
NANO_ADAPTERS = frozenset(
|
||||
{
|
||||
"nv_rs_nano_payload_alloc",
|
||||
"nv_rs_nano_payload_free",
|
||||
"nv_rs_nano_create",
|
||||
"nv_rs_nano_start",
|
||||
"nv_rs_nano_cancel",
|
||||
"nv_rs_nano_destroy",
|
||||
}
|
||||
)
|
||||
REGISTRY_LOCK_ADAPTERS = frozenset(
|
||||
{
|
||||
"nv_rs_gpu_registry_lock",
|
||||
"nv_rs_gpu_registry_unlock",
|
||||
}
|
||||
)
|
||||
REQUIRED_SYSMEM_EXPORTS = (
|
||||
"state_size",
|
||||
"state_align",
|
||||
"pin_size",
|
||||
"pin_align",
|
||||
"prepare",
|
||||
"allocate",
|
||||
"info",
|
||||
"pin",
|
||||
"unpin",
|
||||
"sync",
|
||||
"close",
|
||||
)
|
||||
|
||||
|
||||
def find_modinfo() -> str:
|
||||
found = shutil.which("modinfo")
|
||||
if found:
|
||||
return found
|
||||
for candidate in ("/usr/sbin/modinfo", "/sbin/modinfo"):
|
||||
if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
|
||||
return candidate
|
||||
return "modinfo"
|
||||
|
||||
|
||||
def run_tool(*args: str) -> str:
|
||||
env = dict(os.environ, LC_ALL="C")
|
||||
return subprocess.check_output(args, text=True, env=env)
|
||||
|
||||
|
||||
def parse_nm_symbols(nm_output: str) -> set[str]:
|
||||
return {line.split()[-1] for line in nm_output.splitlines() if line.split()}
|
||||
|
||||
|
||||
def parse_nm_global_text_exports(nm_output: str) -> set[str]:
|
||||
exports: set[str] = set()
|
||||
for line in nm_output.splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) >= 3 and parts[-2] == "T":
|
||||
exports.add(parts[-1])
|
||||
return exports
|
||||
|
||||
|
||||
def is_allowed_kernel_external(sym: str) -> bool:
|
||||
return sym in ALLOWED_KERNEL_EXTERNALS or sym.startswith(ALLOWED_KERNEL_EXTERNAL_PREFIXES)
|
||||
|
||||
|
||||
_RELOC_ROW_RE = re.compile(r"^\s*[0-9a-fA-F]+\s+[0-9a-fA-F]+\s+(\S+)")
|
||||
_GOT_RELOC_TYPE_RE = re.compile(r"^R_[A-Z0-9_]*GOT[A-Z0-9_]*$")
|
||||
_ARM64_SUB_SP_RE = re.compile(
|
||||
r"\bsub\s+sp,\s*sp,\s*#(?:0x([0-9a-f]+)|(\d+))(?:\s*,\s*lsl\s*#(?:0x([0-9a-f]+)|(\d+)))?",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_ARM64_SP_PREINDEX_RE = re.compile(r"\[sp,\s*#-(?:0x([0-9a-f]+)|(\d+))\]!", re.IGNORECASE)
|
||||
|
||||
|
||||
def has_got_relocation(reloc_text: str) -> bool:
|
||||
for line in reloc_text.splitlines():
|
||||
m = _RELOC_ROW_RE.match(line)
|
||||
if m and _GOT_RELOC_TYPE_RE.match(m.group(1)):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _parse_arm64_imm(hex_part: str | None, dec_part: str | None) -> int:
|
||||
if hex_part is not None:
|
||||
return int(hex_part, 16)
|
||||
if dec_part is not None:
|
||||
return int(dec_part, 10)
|
||||
raise ValueError("expected hex or decimal AArch64 immediate")
|
||||
|
||||
|
||||
def max_conservative_function_stack_bytes(assembly: str) -> int:
|
||||
frames: dict[str, int] = {}
|
||||
fn = ""
|
||||
for line in assembly.splitlines():
|
||||
m_fn = re.search(r"^[0-9a-f]+ <(.+)>:$", line)
|
||||
if m_fn:
|
||||
fn = m_fn.group(1)
|
||||
frames.setdefault(fn, 0)
|
||||
continue
|
||||
m_sub = re.search(r"\bsub\s+\$0x([0-9a-f]+),%rsp", line)
|
||||
if m_sub:
|
||||
frames[fn] = frames.get(fn, 0) + int(m_sub.group(1), 16)
|
||||
if re.search(r"\bpush(?:q|l)?\s", line):
|
||||
frames[fn] = frames.get(fn, 0) + 8
|
||||
m_arm_sub = _ARM64_SUB_SP_RE.search(line)
|
||||
if m_arm_sub:
|
||||
imm = _parse_arm64_imm(m_arm_sub.group(1), m_arm_sub.group(2))
|
||||
if m_arm_sub.group(3) is not None or m_arm_sub.group(4) is not None:
|
||||
imm <<= _parse_arm64_imm(m_arm_sub.group(3), m_arm_sub.group(4))
|
||||
frames[fn] = frames.get(fn, 0) + imm
|
||||
m_arm_pre = _ARM64_SP_PREINDEX_RE.search(line)
|
||||
if m_arm_pre:
|
||||
frames[fn] = frames.get(fn, 0) + _parse_arm64_imm(
|
||||
m_arm_pre.group(1), m_arm_pre.group(2)
|
||||
)
|
||||
return max(frames.values(), default=0)
|
||||
|
||||
|
||||
def evaluate_outputs(
|
||||
*,
|
||||
assembly: str,
|
||||
sections: str,
|
||||
obj_undefined_nm: str,
|
||||
obj_defined_nm: str,
|
||||
module_defined_nm: str,
|
||||
module_undefined_nm: str,
|
||||
module_relocs: str,
|
||||
modinfo_name: str,
|
||||
modinfo_alias: str,
|
||||
modinfo_vermagic: str,
|
||||
sha256_map: dict[str, str],
|
||||
) -> dict[str, object]:
|
||||
undefined_symbols = parse_nm_symbols(obj_undefined_nm)
|
||||
obj_text_exports = parse_nm_global_text_exports(obj_defined_nm)
|
||||
module_definitions = parse_nm_symbols(module_defined_nm)
|
||||
module_undefined = parse_nm_symbols(module_undefined_nm)
|
||||
|
||||
# Private C adapters (nv_rs_*) referenced by nv-rust.o_binary must be
|
||||
# resolved inside nvidia_rs.ko itself — never left unresolved or deferred to
|
||||
# another module.
|
||||
referenced_private_adapters = {s for s in undefined_symbols if s.startswith("nv_rs_")}
|
||||
unresolved_private_adapters = sorted(
|
||||
(referenced_private_adapters - module_definitions)
|
||||
| (referenced_private_adapters & module_undefined)
|
||||
)
|
||||
external_undefined = undefined_symbols - referenced_private_adapters
|
||||
unexpected_external_symbols = sorted(
|
||||
s for s in external_undefined if not is_allowed_kernel_external(s)
|
||||
)
|
||||
forbidden_memory_symbols = sorted(undefined_symbols & FORBIDDEN_MEMORY_ROUTINES)
|
||||
largest_stack = max_conservative_function_stack_bytes(assembly)
|
||||
|
||||
checks = {
|
||||
"no_unresolved_rust_or_userspace_symbols": not unexpected_external_symbols
|
||||
and not unresolved_private_adapters,
|
||||
"no_forbidden_memcpy_memset_memmove": not forbidden_memory_symbols,
|
||||
"private_adapters_resolved_in_module": not unresolved_private_adapters,
|
||||
"nano_timer_adapters_present": NANO_ADAPTERS <= module_definitions,
|
||||
"prepared_gpu_registry_entries_present": all(
|
||||
f"nv_rs_gpu_registry_{name}" in obj_text_exports for name in ("publish", "retire")
|
||||
),
|
||||
"pci_probe_identity_entry_present": "nv_rs_gpu_set_probe_identity" in obj_text_exports,
|
||||
"prepared_gpu_registry_lock_adapters_present": REGISTRY_LOCK_ADAPTERS <= module_definitions,
|
||||
"no_simd_or_x87_registers": not re.search(
|
||||
r"%(?:[xyz]mm\d+|mm\d+|st(?:\(|\b))", assembly
|
||||
),
|
||||
"no_kernel_unsupported_got_relocations": not has_got_relocation(module_relocs),
|
||||
"no_unwind_sections": not re.search(r"\.eh_frame|\.gcc_except_table", sections),
|
||||
"no_stack_reservation_above_1024_bytes": largest_stack <= 1024,
|
||||
"no_rsp_redzone_references": not re.search(r"-0x[0-9a-f]+\(%rsp\)", assembly),
|
||||
"rust_protocol_entry_present": "nv_rs_protocol_version" in obj_text_exports,
|
||||
"rust_event_selftest_present": "nv_rs_event_selftest" in obj_text_exports,
|
||||
"rust_capabilities_entry_present": "nv_rs_gpu_capabilities" in obj_text_exports,
|
||||
"rust_system_memory_entries_present": all(
|
||||
f"nv_rs_sysmem_{name}" in obj_text_exports for name in REQUIRED_SYSMEM_EXPORTS
|
||||
),
|
||||
"distinct_module_name": modinfo_name.strip() == "nvidia_rs",
|
||||
"no_pci_aliases": not modinfo_alias.strip(),
|
||||
}
|
||||
|
||||
return {
|
||||
"checks": checks,
|
||||
"rust_object_undefined_symbols": sorted(undefined_symbols),
|
||||
"private_adapters_resolved_in_module": sorted(
|
||||
referenced_private_adapters & module_definitions - module_undefined
|
||||
),
|
||||
"unresolved_private_adapters": unresolved_private_adapters,
|
||||
"unexpected_external_symbols": unexpected_external_symbols,
|
||||
"largest_conservative_function_stack_bytes": largest_stack,
|
||||
"kernel_vermagic": modinfo_vermagic.strip(),
|
||||
"sha256": sha256_map,
|
||||
"limits": [
|
||||
"Machine-code checks cover this build only.",
|
||||
"This static check does not prove live execution; see the build-matched live-control-session.json.",
|
||||
"Opt-in PCI bridge is present; empty pci_target binds no GPUs. Physical PCI/DMA/GPU behavior remains unvalidated.",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _display_path(path: pathlib.Path, root: pathlib.Path) -> str:
|
||||
try:
|
||||
return str(path.resolve().relative_to(root.resolve()))
|
||||
except ValueError:
|
||||
return str(path)
|
||||
|
||||
|
||||
def verify_artifacts(obj: pathlib.Path, module: pathlib.Path) -> dict[str, object]:
|
||||
for label, path in (("Rust object", obj), ("kernel module", module)):
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(f"{label} not found: {path}")
|
||||
|
||||
modinfo = find_modinfo()
|
||||
return evaluate_outputs(
|
||||
assembly=run_tool("objdump", "-dr", str(obj)),
|
||||
sections=run_tool("readelf", "-SW", str(obj)),
|
||||
obj_undefined_nm=run_tool("nm", "-u", str(obj)),
|
||||
obj_defined_nm=run_tool("nm", "--defined-only", str(obj)),
|
||||
module_defined_nm=run_tool("nm", "--defined-only", str(module)),
|
||||
module_undefined_nm=run_tool("nm", "-u", str(module)),
|
||||
module_relocs=run_tool("readelf", "-rW", str(module)),
|
||||
modinfo_name=run_tool(modinfo, "-F", "name", str(module)),
|
||||
modinfo_alias=run_tool(modinfo, "-F", "alias", str(module)),
|
||||
modinfo_vermagic=run_tool(modinfo, "-F", "vermagic", str(module)),
|
||||
sha256_map={
|
||||
_display_path(p, ROOT): hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
for p in (obj, module)
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
||||
ap = argparse.ArgumentParser(
|
||||
description="Inspect generated Rust kernel object and nvidia_rs.ko without loading any module."
|
||||
)
|
||||
ap.add_argument(
|
||||
"--object",
|
||||
type=pathlib.Path,
|
||||
default=DEFAULT_OBJ,
|
||||
help="Path to nv-rust.o_binary (default: kernel-open/nvidia/nv-rust.o_binary)",
|
||||
)
|
||||
ap.add_argument(
|
||||
"--module",
|
||||
type=pathlib.Path,
|
||||
default=DEFAULT_MODULE,
|
||||
help="Path to nvidia_rs.ko (default: kernel-open/nvidia_rs.ko)",
|
||||
)
|
||||
return ap.parse_args(argv)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
args = parse_args(argv)
|
||||
try:
|
||||
report = verify_artifacts(args.object, args.module)
|
||||
except FileNotFoundError as exc:
|
||||
print(f"error: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
print(json.dumps(report, indent=2))
|
||||
checks = report["checks"]
|
||||
return 0 if isinstance(checks, dict) and all(checks.values()) else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
||||
191
tests/offline/test_kernel_verify_object.py
Normal file
191
tests/offline/test_kernel_verify_object.py
Normal file
@ -0,0 +1,191 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline unit and live-artifact tests for src/nvidia/kernel/verify-object.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
SCRIPT = ROOT / "src/nvidia/kernel/verify-object.py"
|
||||
|
||||
|
||||
def _load_module():
|
||||
spec = importlib.util.spec_from_file_location("nv_verify_object", SCRIPT)
|
||||
if spec is None or spec.loader is None:
|
||||
raise RuntimeError(f"failed to load {SCRIPT}")
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
return mod
|
||||
|
||||
|
||||
MOD = _load_module()
|
||||
|
||||
|
||||
def _base_inputs() -> dict[str, object]:
|
||||
obj_defined_lines = [
|
||||
"0000000000000000 T nv_rs_gpu_registry_publish",
|
||||
"0000000000000010 T nv_rs_gpu_registry_retire",
|
||||
"0000000000000020 T nv_rs_gpu_set_probe_identity",
|
||||
"0000000000000030 T nv_rs_protocol_version",
|
||||
"0000000000000040 T nv_rs_event_selftest",
|
||||
"0000000000000050 T nv_rs_gpu_capabilities",
|
||||
] + [
|
||||
f"00000000000001{idx:02x} T nv_rs_sysmem_{name}"
|
||||
for idx, name in enumerate(MOD.REQUIRED_SYSMEM_EXPORTS)
|
||||
]
|
||||
module_defined_lines = [
|
||||
"0000000000000000 T nv_rs_custom_adapter",
|
||||
"0000000000000010 T nv_rs_gpu_registry_lock",
|
||||
"0000000000000020 T nv_rs_gpu_registry_unlock",
|
||||
] + [
|
||||
f"00000000000001{idx:02x} T {name}"
|
||||
for idx, name in enumerate(sorted(MOD.NANO_ADAPTERS))
|
||||
]
|
||||
return {
|
||||
"assembly": (
|
||||
"0000000000000000 <nv_rs_protocol_version>:\n"
|
||||
" 0:\t55\tpush %rbp\n"
|
||||
" 1:\t48 81 ec 00 02 00 00\tsub $0x200,%rsp\n"
|
||||
" 8:\tc3\tret\n"
|
||||
),
|
||||
"sections": " [ 1] .text PROGBITS 0000000000000000 000040 000100 00 AX 0 0 16\n",
|
||||
"obj_undefined_nm": (
|
||||
"\n"
|
||||
" U nv_rs_custom_adapter\n"
|
||||
" U __x86_return_thunk\n"
|
||||
" U __x86_indirect_thunk_r11\n"
|
||||
" U strlen\n"
|
||||
),
|
||||
"obj_defined_nm": "\n".join(obj_defined_lines) + "\n",
|
||||
"module_defined_nm": "\n".join(module_defined_lines) + "\n",
|
||||
"module_undefined_nm": (
|
||||
" U __x86_return_thunk\n"
|
||||
" U __x86_indirect_thunk_r11\n"
|
||||
" U strlen\n"
|
||||
),
|
||||
"module_relocs": (
|
||||
"Relocation section '.rela.text' at offset 0x100 contains 2 entries:\n"
|
||||
" Offset Info Type Sym. Value Sym. Name + Addend\n"
|
||||
"0000000000000010 0000000100000002 R_X86_64_PC32 0000000000000000 MY_GOT_NAMED_SYM - 4\n"
|
||||
"0000000000000020 0000000200000002 R_X86_64_PC32 0000000000000000 R_GOT - 4\n"
|
||||
),
|
||||
"modinfo_name": "nvidia_rs\n",
|
||||
"modinfo_alias": "\n",
|
||||
"modinfo_vermagic": "7.0.0-test SMP preempt mod_unload\n",
|
||||
"sha256_map": {"obj": "0" * 64, "module": "1" * 64},
|
||||
}
|
||||
|
||||
|
||||
class VerifyObjectTests(unittest.TestCase):
|
||||
def test_clean_inputs_pass_and_ignore_got_in_symbol_name(self) -> None:
|
||||
report = MOD.evaluate_outputs(**_base_inputs())
|
||||
self.assertTrue(all(report["checks"].values()), report["checks"])
|
||||
self.assertEqual(report["unresolved_private_adapters"], [])
|
||||
self.assertEqual(report["unexpected_external_symbols"], [])
|
||||
self.assertEqual(report["largest_conservative_function_stack_bytes"], 520)
|
||||
|
||||
def test_rejects_got_relocation_type(self) -> None:
|
||||
inputs = _base_inputs()
|
||||
inputs["module_relocs"] = (
|
||||
"0000000000000010 000000010000002a R_X86_64_REX_GOTPCRELX 0000000000000000 foo - 4\n"
|
||||
)
|
||||
report = MOD.evaluate_outputs(**inputs)
|
||||
self.assertFalse(report["checks"]["no_kernel_unsupported_got_relocations"])
|
||||
|
||||
def test_rejects_unresolved_private_adapter_and_forbidden_memcpy(self) -> None:
|
||||
inputs = _base_inputs()
|
||||
inputs["obj_undefined_nm"] = (
|
||||
" U nv_rs_missing_adapter\n"
|
||||
" U memcpy\n"
|
||||
" U rust_eh_personality\n"
|
||||
)
|
||||
report = MOD.evaluate_outputs(**inputs)
|
||||
self.assertFalse(report["checks"]["private_adapters_resolved_in_module"])
|
||||
self.assertFalse(report["checks"]["no_forbidden_memcpy_memset_memmove"])
|
||||
self.assertFalse(report["checks"]["no_unresolved_rust_or_userspace_symbols"])
|
||||
self.assertEqual(report["unresolved_private_adapters"], ["nv_rs_missing_adapter"])
|
||||
self.assertEqual(report["unexpected_external_symbols"], ["memcpy", "rust_eh_personality"])
|
||||
|
||||
def test_rejects_prefix_spoofed_exports(self) -> None:
|
||||
inputs = _base_inputs()
|
||||
inputs["obj_defined_nm"] = str(inputs["obj_defined_nm"]).replace(
|
||||
"nv_rs_gpu_set_probe_identity",
|
||||
"nv_rs_gpu_set_probe_identity_extra",
|
||||
)
|
||||
report = MOD.evaluate_outputs(**inputs)
|
||||
self.assertFalse(report["checks"]["pci_probe_identity_entry_present"])
|
||||
|
||||
def test_cumulative_function_stack_overflow_detected(self) -> None:
|
||||
inputs = _base_inputs()
|
||||
inputs["assembly"] = (
|
||||
"0000000000000000 <heavy_fn>:\n"
|
||||
" 0:\t48 81 ec 00 03 00 00\tsub $0x300,%rsp\n"
|
||||
" 7:\t48 81 ec 00 02 00 00\tsub $0x200,%rsp\n"
|
||||
)
|
||||
report = MOD.evaluate_outputs(**inputs)
|
||||
self.assertEqual(report["largest_conservative_function_stack_bytes"], 1280)
|
||||
self.assertFalse(report["checks"]["no_stack_reservation_above_1024_bytes"])
|
||||
|
||||
def test_aarch64_preindex_writeback_counted_in_stack_limit(self) -> None:
|
||||
# 16 + 0x3f0 = 1024 bytes -> passes at exact boundary.
|
||||
ok_inputs = _base_inputs()
|
||||
ok_inputs["assembly"] = (
|
||||
"0000000000000000 <arm64_exact_limit>:\n"
|
||||
" 0:\ta9bf7bfd\tstp\tx29, x30, [sp, #-16]!\n"
|
||||
" 4:\td10fc3ff\tsub\tsp, sp, #0x3f0\n"
|
||||
)
|
||||
ok_report = MOD.evaluate_outputs(**ok_inputs)
|
||||
self.assertEqual(ok_report["largest_conservative_function_stack_bytes"], 1024)
|
||||
self.assertTrue(ok_report["checks"]["no_stack_reservation_above_1024_bytes"])
|
||||
|
||||
# 16 + 0x400 = 1040 bytes -> rejected.
|
||||
over_inputs = _base_inputs()
|
||||
over_inputs["assembly"] = (
|
||||
"0000000000000000 <arm64_over_limit>:\n"
|
||||
" 0:\ta9bf7bfd\tstp\tx29, x30, [sp, #-16]!\n"
|
||||
" 4:\td11003ff\tsub\tsp, sp, #0x400\n"
|
||||
)
|
||||
over_report = MOD.evaluate_outputs(**over_inputs)
|
||||
self.assertEqual(over_report["largest_conservative_function_stack_bytes"], 1040)
|
||||
self.assertFalse(over_report["checks"]["no_stack_reservation_above_1024_bytes"])
|
||||
|
||||
def test_find_modinfo_falls_back_to_sbin(self) -> None:
|
||||
with mock.patch.object(MOD.shutil, "which", return_value=None):
|
||||
with mock.patch.object(
|
||||
MOD.os.path, "isfile", side_effect=lambda p: p == "/sbin/modinfo"
|
||||
):
|
||||
with mock.patch.object(MOD.os, "access", return_value=True):
|
||||
self.assertEqual(MOD.find_modinfo(), "/sbin/modinfo")
|
||||
|
||||
def test_missing_artifact_returns_nonzero_cleanly(self) -> None:
|
||||
proc = subprocess.run(
|
||||
[sys.executable, "-O", str(SCRIPT), "--object", "/nonexistent/nv-rust.o_binary"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
self.assertNotEqual(proc.returncode, 0)
|
||||
self.assertIn("Rust object not found", proc.stderr)
|
||||
|
||||
def test_live_built_artifacts_if_present(self) -> None:
|
||||
if not (MOD.DEFAULT_OBJ.is_file() and MOD.DEFAULT_MODULE.is_file()):
|
||||
self.skipTest("kernel-open build artifacts not present")
|
||||
proc = subprocess.run(
|
||||
[sys.executable, "-O", str(SCRIPT)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
|
||||
report = json.loads(proc.stdout)
|
||||
self.assertTrue(all(report["checks"].values()), report["checks"])
|
||||
self.assertEqual(report["unresolved_private_adapters"], [])
|
||||
self.assertEqual(report["unexpected_external_symbols"], [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user