mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
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>
553 lines
34 KiB
Python
553 lines
34 KiB
Python
#!/usr/bin/env python3
|
|
"""Assemble each gate fixture and assert what the checker reports for that case alone."""
|
|
import json
|
|
import os
|
|
import shutil
|
|
import tempfile
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import unittest
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
FIXTURES = ROOT / "tests/kernel-module-gate"
|
|
OUT = ROOT / "target/kernel-module-gate"
|
|
CHECKER = ROOT / "tools/check_kernel_module.py"
|
|
SHN_XINDEX = 0xffff
|
|
SHN_ABS = 0xfff1
|
|
SHT_SYMTAB_SHNDX = 18 # spec Table 3.2
|
|
|
|
# Cases whose result does not depend on how a tool prints a name, because the checker takes the
|
|
# target's identity from the ELF tables. Every case states the counts, so a fixture that produces no
|
|
# relocation at all cannot pass vacuously. Every case states the export set too, so a case that exports
|
|
# nothing asserts that it exports nothing instead of passing on whatever the checker happened to see.
|
|
CASES = {
|
|
"entry": dict(resolves=True, unresolved=0, ambiguous=0, recorded=1, not_entry_pad=0, endbr_rule=True, exports=False, duplicate=0),
|
|
"long-name": dict(resolves=True, unresolved=0, ambiguous=0, recorded=1, not_entry_pad=0, endbr_rule=True, exports=False, duplicate=0),
|
|
"mid-instruction": dict(resolves=False, unresolved=1, ambiguous=0, recorded=0, not_entry_pad=0, endbr_rule=True, exports=False, duplicate=0),
|
|
# objdump shows one symbol per address, so the alias name is not in its output. Resolved through
|
|
# the symbol table both targets are recorded: the alias at the entry is an entry pad, the alias
|
|
# inside the instruction is recorded as a target that is not one. Resolved by name both were
|
|
# dropped, so the ENDBR rule passed over an empty set.
|
|
"alias": dict(resolves=True, unresolved=0, ambiguous=0, recorded=2, not_entry_pad=1, endbr_rule=False, exports=False, duplicate=0),
|
|
# Two symbol names share their first 256 characters, one of them exactly 256 long. The relocation
|
|
# names the longer one, whose entry is the endbr64, so not_entry_pad 0 means it resolved to the
|
|
# entity the fixture names; the first symbol, a ret, is the wrong answer.
|
|
"duplicate-symbol-prefix": dict(resolves=True, unresolved=0, ambiguous=0, recorded=1, not_entry_pad=0, endbr_rule=True, exports=False, duplicate=0),
|
|
# The export set is built from the symbol table, so an entry for a name that is only referenced
|
|
# (st_shndx == SHN_UNDEF) must not count as an export. This fixture references all nine protocol
|
|
# names and defines none: before the fix the check passed on an object that exports nothing, which
|
|
# is what the nm --defined-only check it replaced rejected. defined-exports.s is the control - the
|
|
# same nine names, defined, still count.
|
|
"undefined-exports": dict(resolves=True, unresolved=0, ambiguous=0, recorded=0, not_entry_pad=0, endbr_rule=True, exports=False, duplicate=0),
|
|
"defined-exports": dict(resolves=True, unresolved=0, ambiguous=0, recorded=0, not_entry_pad=0, endbr_rule=True, exports=True, duplicate=0),
|
|
# Two distinct sections share one name, which as cannot produce, hence the linker script beside the
|
|
# fixture. Before the fix the single disassembly header for the shared name was attributed to the
|
|
# last index, so the endbr64 recorded under the empty section made the .quad to it pass. Duplicate
|
|
# names are not a truncation, so they are counted separately from ambiguous printed names.
|
|
"duplicate-section-name": dict(resolves=False, unresolved=0, ambiguous=0, recorded=0, not_entry_pad=0, endbr_rule=True, exports=False, duplicate=1),
|
|
# A code entry that is not an endbr64 pad, recorded and refused while IBT is in effect. Asserted from
|
|
# the enforced side; the disabled side is the test below.
|
|
"no-endbr-entry": dict(resolves=True, unresolved=0, ambiguous=0, recorded=1, not_entry_pad=1, endbr_rule=False, exports=False, duplicate=0),
|
|
}
|
|
# The section case is the one place a printed name still decides something: the target's identity is
|
|
# known from the ELF section table, but objdump's disassembly has to be attributed to a section, and a
|
|
# printed header that belongs to two sections cannot be attributed. The expectation is the rule, so it
|
|
# allows either outcome - refused when objdump prints the shared form, otherwise recorded against the
|
|
# entity the fixture names, whose entry is a ret - and records which printing it saw. Judging the
|
|
# relocation against the other section would report its endbr64 entry instead, so not_entry_pad 0 fails
|
|
# whichever branch applies.
|
|
SHARED_PREFIX = {
|
|
"duplicate-prefix": {
|
|
"full": dict(resolves=True, unresolved=0, ambiguous=0, recorded=1, not_entry_pad=1, endbr_rule=False, exports=False, duplicate=0),
|
|
"shared": dict(resolves=False, unresolved=0, ambiguous=1, recorded=0, not_entry_pad=0, endbr_rule=True, exports=False, duplicate=0),
|
|
},
|
|
}
|
|
PRINTING = {}
|
|
CASES_RUN = []
|
|
|
|
|
|
def rule(report):
|
|
return dict(resolves=report["checks"]["data_relocation_targets_resolve_to_instructions"],
|
|
unresolved=report["unresolved_code_targets"],
|
|
ambiguous=report["ambiguous_truncated_names"],
|
|
recorded=report["data_relocations_to_code"],
|
|
not_entry_pad=report["data_relocation_targets_without_endbr"],
|
|
endbr_rule=report["checks"]["endbr64_at_data_relocation_targets"],
|
|
exports=report["checks"]["protocol_exports_present"],
|
|
duplicate=report["unattributable_duplicate_names"])
|
|
|
|
|
|
# The checker is not executable in the tree, so call it through the running interpreter. Object-only
|
|
# mode keeps the committed report from being overwritten by fixture runs. IBT is set explicitly for every
|
|
# case instead of being taken from the host's kernel config, so the expectations hold on a host without
|
|
# CONFIG_X86_KERNEL_IBT=y; the disabled path is asserted separately below.
|
|
def check(object_path, module_path=None, ibt="1"):
|
|
args = [sys.executable, str(CHECKER), str(object_path)]
|
|
args += [str(module_path)] if module_path else ["--object-only"]
|
|
env = dict(os.environ, NV_RS_KERNEL_IBT=ibt)
|
|
return json.loads(subprocess.run(args, capture_output=True, text=True, env=env).stdout)
|
|
|
|
|
|
def case_object(name):
|
|
OUT.mkdir(parents=True, exist_ok=True)
|
|
assembled = OUT / f"{name}.input.o"
|
|
subprocess.check_call(["as", str(FIXTURES / f"{name}.s"), "-o", str(assembled)])
|
|
script = FIXTURES / f"{name}.ld"
|
|
if not script.exists():
|
|
return assembled
|
|
# as merges sections that share a name, so the duplicate-name case only exists after the linker.
|
|
object_path = OUT / f"{name}.o"
|
|
subprocess.check_call(["ld", "-r", "-T", str(script), "-o", str(object_path), str(assembled)])
|
|
return object_path
|
|
|
|
|
|
def craft_extended_object(with_shndx_table=True):
|
|
# ELF64 relocatable object with extended section numbering, which as and ld cannot emit: e_shnum is 0
|
|
# with the real count in sh_size of header 0, and e_shstrndx is the escape value SHN_XINDEX with the
|
|
# real string table index in sh_link of header 0 (spec Table 3.5). The .text entry is a ret, so the
|
|
# two data relocations are code targets that are not entry pads. The second symbol's st_shndx is
|
|
# SHN_XINDEX, so its section index exists only in the associated SHT_SYMTAB_SHNDX section.
|
|
OUT.mkdir(parents=True, exist_ok=True)
|
|
names = [".text", ".rodata", ".rela.rodata", ".symtab", ".strtab", ".shstrtab"]
|
|
if with_shndx_table:
|
|
names.append(".symtab_shndx")
|
|
blob = b"\0" + b"".join(n.encode() + b"\0" for n in names)
|
|
nameoff = {n: blob.find(n.encode()) for n in names}
|
|
strtab = b"\0symEntry\0symXindex\0"
|
|
symtab = [struct.pack("<IBBHQQ", 0, 0, 0, 0, 0, 0),
|
|
struct.pack("<IBBHQQ", strtab.find(b"symEntry"), 17, 0, 1, 0, 1),
|
|
struct.pack("<IBBHQQ", strtab.find(b"symXindex"), 17, 0, SHN_XINDEX, 0, 1)]
|
|
parts = [(1, b"\xc3"), (2, b"\0" * 16),
|
|
(3, struct.pack("<QQq", 0, (1 << 32) | 1, 0) + struct.pack("<QQq", 8, (2 << 32) | 1, 0)),
|
|
(4, b"".join(symtab)), (5, strtab), (6, blob)]
|
|
if with_shndx_table:
|
|
parts.append((7, b"".join(struct.pack("<I", i) for i in (0, 0, 1))))
|
|
types = {1: 1, 2: 1, 3: 4, 4: 2, 5: 3, 6: 3, 7: SHT_SYMTAB_SHNDX}
|
|
flags = {1: 6, 2: 3}
|
|
base, size = 64, sum(len(p[1]) for p in parts)
|
|
table = [struct.pack("<IIQQQQIIQQ", 0, 0, 0, 0, 0, len(names) + 1, 6, 0, 0, 0)]
|
|
cursor = base
|
|
for i, (idx, content) in enumerate(parts):
|
|
table.append(struct.pack("<IIQQQQIIQQ", nameoff[names[i]], types[idx], flags.get(idx, 0), 0, cursor,
|
|
len(content), 4 if idx in (3, 7) else (5 if idx == 4 else 0),
|
|
2 if idx in (2, 3) else 3 if idx == 4 else 0, 8, 24 if idx in (3, 4) else 0))
|
|
cursor += len(content)
|
|
header = (b"\x7fELF\x02\x01\x01" + b"\0" * 9 + struct.pack("<HHIQQQ", 1, 62, 0, 0, 0, base + size)
|
|
+ struct.pack("<IHHHHHH", 0, 64, 0, 0, 64, 0, SHN_XINDEX))
|
|
object_path = OUT / ("extended-%s.o" % ("with-table" if with_shndx_table else "without-table"))
|
|
object_path.write_bytes(header + b"".join(p[1] for p in parts) + b"".join(table))
|
|
return object_path
|
|
|
|
|
|
def craft_reserved_index_object():
|
|
# st_shndx values in the reserved range SHN_LORESERVE..0xfffe have special meaning (spec Table 3.4), so
|
|
# they name no section even when extended numbering makes the same number a real section index. The count
|
|
# is 0xfff3, so 65521 is both SHN_ABS's value and a real section: one symbol is absolute, one has
|
|
# st_shndx == SHN_XINDEX resolving to that section through the shndx table. The symbol over the code
|
|
# needs a size that spans the section, otherwise objdump prints the section as one undecodable blob
|
|
# instead of the endbr64 at its entry (measured with symbol size 1, 5 and 14).
|
|
OUT.mkdir(parents=True, exist_ok=True)
|
|
count = 0xfff3 # >= SHN_LORESERVE, so the real count is in sh_size of header 0
|
|
section_names = {1: ".rodata", 2: ".rela.rodata", 3: ".symtab", 4: ".strtab", 5: ".shstrtab",
|
|
6: ".symtab_shndx", SHN_ABS: "code_at_65521"}
|
|
order = sorted(section_names)
|
|
blob = b"\0" + b"".join(section_names[i].encode() + b"\0" for i in order)
|
|
nameoff = {i: blob.find(section_names[i].encode()) for i in order}
|
|
exports = ["nv_rs_protocol_version", "nv_rs_gpu_capabilities", "nv_rs_event_selftest",
|
|
"nv_rs_gpu_prepare_owned", "nv_rs_gpu_set_probe_identity", "nv_rs_gpu_registry_publish",
|
|
"nv_rs_gpu_registry_retire", "nv_rs_sysmem_prepare", "nv_rs_sysmem_close"]
|
|
strtab = b"\0" + b"".join(n.encode() + b"\0" for n in exports) + b"symXindex\0"
|
|
symoff = {n: strtab.find(n.encode()) for n in exports + ["symXindex"]}
|
|
symbols = [(0, 0, 0, 0, 0, 0)]
|
|
for n in exports:
|
|
symbols.append((symoff[n], 17, 0, SHN_ABS, 0, 1)) # raw st_shndx 65521, a special value
|
|
symbols.append((symoff["symXindex"], 14, 0, SHN_XINDEX, 0, 1)) # the index exists only in the shndx table
|
|
contents = {1: b"\0" * 16,
|
|
2: struct.pack("<QQq", 0, (1 << 32) | 1, 0) + struct.pack("<QQq", 8, (10 << 32) | 1, 0),
|
|
3: b"".join(struct.pack("<IBBHQQ", *s) for s in symbols),
|
|
4: strtab, 5: blob,
|
|
6: b"".join(struct.pack("<I", SHN_ABS if s[3] == SHN_XINDEX else 0) for s in symbols),
|
|
SHN_ABS: b"\xf3\x0f\x1e\xfa\xc3" + b"\x90" * 9}
|
|
keys = sorted(contents)
|
|
base = 64
|
|
offsets, cursor = {}, base
|
|
for k in keys:
|
|
offsets[k] = cursor
|
|
cursor += len(contents[k])
|
|
types = {1: 1, 2: 4, 3: 2, 4: 3, 5: 3, 6: SHT_SYMTAB_SHNDX, SHN_ABS: 1}
|
|
flags, links, infos, entsizes = {1: 3, SHN_ABS: 6}, {2: 3, 3: 4, 6: 3}, {2: 1, 3: 3}, {2: 24, 3: 24, 6: 4}
|
|
table = [struct.pack("<IIQQQQIIQQ", 0, 0, 0, 0, 0, count, 5, 0, 0, 0)]
|
|
for i in range(1, count):
|
|
if i in contents:
|
|
table.append(struct.pack("<IIQQQQIIQQ", nameoff[i], types[i], flags.get(i, 0), 0, offsets[i],
|
|
len(contents[i]), links.get(i, 0), infos.get(i, 0), 8, entsizes.get(i, 0)))
|
|
else:
|
|
table.append(struct.pack("<IIQQQQIIQQ", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
|
|
header = (b"\x7fELF\x02\x01\x01" + b"\0" * 9
|
|
+ struct.pack("<HHIQQQ", 1, 62, 0, 0, 0, base + sum(len(contents[k]) for k in keys))
|
|
+ struct.pack("<IHHHHHH", 0, 64, 0, 0, 64, 0, SHN_XINDEX))
|
|
object_path = OUT / "reserved-st_shndx.o"
|
|
object_path.write_bytes(header + b"".join(contents[k] for k in keys) + b"".join(table))
|
|
return object_path
|
|
|
|
|
|
def observed_printing(fixture, object_path):
|
|
names = [l.split('"')[1] for l in fixture.read_text().splitlines() if l.startswith('.section "')]
|
|
prefix = "Disassembly of section "
|
|
printed = [l[len(prefix):-1] for l in subprocess.check_output(["objdump", "-dr", str(object_path)],
|
|
text=True).splitlines() if l.startswith(prefix)]
|
|
return names, "shared" if any(p not in names for p in printed) else "full"
|
|
|
|
|
|
class KernelModuleGate(unittest.TestCase):
|
|
@unittest.skipUnless(any(os.access(p, os.X_OK) for p in ("/usr/sbin/modinfo", "/sbin/modinfo")),
|
|
"needs kmod's modinfo in a standard administration directory")
|
|
def test_modinfo_outside_user_path(self):
|
|
# Use a real ELF module-info section, without loading a module. A normal
|
|
# user PATH may contain binutils but omit /sbin and /usr/sbin (#57).
|
|
obj = case_object("defined-exports")
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
directory = Path(directory)
|
|
module = directory / "fixture.ko"
|
|
subprocess.run(["as", "-o", str(module)], input=
|
|
'.section .modinfo,"a"\n.asciz "name=nvidia_rs"\n',
|
|
text=True, check=True)
|
|
for tool in ("readelf", "objdump", "nm"):
|
|
(directory / tool).symlink_to(shutil.which(tool))
|
|
env = dict(os.environ, PATH=str(directory), NV_RS_KERNEL_IBT="0")
|
|
args = [sys.executable, str(CHECKER), str(obj), str(module)]
|
|
result = subprocess.run(args, capture_output=True, text=True, env=env)
|
|
self.assertNotIn("Traceback", result.stderr)
|
|
report = json.loads(result.stdout)
|
|
self.assertTrue(report["checks"]["distinct_diagnostic_module_name"])
|
|
self.assertTrue(report["checks"]["no_PCI_aliases"])
|
|
# A caller-provided modinfo must take precedence over the fallback.
|
|
wrapper = directory / "modinfo"
|
|
wrapper.write_text(f"#!{sys.executable}\nimport sys\n"
|
|
"print('different_name' if sys.argv[2] == 'name' else '')\n")
|
|
wrapper.chmod(0o755)
|
|
result = subprocess.run(args, capture_output=True, text=True, env=env)
|
|
self.assertEqual(result.returncode, 1, result.stderr)
|
|
self.assertFalse(json.loads(result.stdout)["checks"]["distinct_diagnostic_module_name"])
|
|
|
|
def test_localized_binutils_preserve_gate_results(self):
|
|
# Real binutils process real ELF fixtures. Translate only their headings
|
|
# when the caller requests a foreign locale, so this regression does not
|
|
# depend on installed locale definitions or translation packages.
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
for tool in ("readelf", "objdump"):
|
|
wrapper = Path(directory) / tool
|
|
real_tool = shutil.which(tool)
|
|
self.assertIsNotNone(real_tool)
|
|
wrapper.write_text(
|
|
f"#!{sys.executable}\n"
|
|
"import os, subprocess, sys\n"
|
|
f"result = subprocess.run([{real_tool!r}, *sys.argv[1:]], "
|
|
"capture_output=True, text=True, env=dict(os.environ, LC_ALL='C'))\n"
|
|
"output = result.stdout\n"
|
|
"if os.environ.get('LC_ALL') != 'C':\n"
|
|
" output = output.replace('Machine:', 'Машина:')\n"
|
|
" output = output.replace('Disassembly of section', 'Дизассемблирование раздела')\n"
|
|
"sys.stdout.write(output)\n"
|
|
"sys.stderr.write(result.stderr)\n"
|
|
"sys.exit(result.returncode)\n"
|
|
)
|
|
wrapper.chmod(0o755)
|
|
for name in ("entry", "no-endbr-entry"):
|
|
obj = case_object(name)
|
|
args = [sys.executable, str(CHECKER), str(obj), "--object-only"]
|
|
reference = subprocess.run(args, capture_output=True, text=True,
|
|
env=dict(os.environ, LC_ALL="C", NV_RS_KERNEL_IBT="1"))
|
|
expected = json.loads(reference.stdout)
|
|
for lc_all in ("ru_RU.UTF-8", ""):
|
|
with self.subTest(name=name, lc_all=lc_all):
|
|
env = dict(os.environ, LC_ALL=lc_all, LANG="ru_RU.UTF-8", LANGUAGE="ru",
|
|
NV_RS_KERNEL_IBT="1", PATH=directory + os.pathsep + os.environ["PATH"])
|
|
result = subprocess.run(args, capture_output=True, text=True, env=env)
|
|
self.assertNotIn("Traceback", result.stderr)
|
|
self.assertEqual(result.returncode, reference.returncode, result.stderr)
|
|
self.assertEqual(json.loads(result.stdout), expected)
|
|
|
|
def test_cases_that_do_not_depend_on_name_printing(self):
|
|
for name, want in CASES.items():
|
|
with self.subTest(case=name):
|
|
self.assertEqual(rule(check(case_object(name))), want)
|
|
CASES_RUN.append(name)
|
|
|
|
def test_shared_prefix_case_follows_the_printing_objdump_showed(self):
|
|
for name, branches in SHARED_PREFIX.items():
|
|
with self.subTest(case=name):
|
|
fixture = FIXTURES / f"{name}.s"
|
|
object_path = case_object(name)
|
|
names, branch = observed_printing(fixture, object_path)
|
|
self.assertEqual(len(names), 2, f"{name}: the case needs two names sharing a prefix")
|
|
self.assertEqual(names[0][:256], names[1][:256], f"{name}: the two names must share 256 characters")
|
|
self.assertEqual(rule(check(object_path)), branches[branch], f"{name}: objdump printed {branch}")
|
|
PRINTING[name] = branch
|
|
CASES_RUN.append(name)
|
|
|
|
def test_green_without_ibt_enforcement_means_the_rule_was_skipped(self):
|
|
# Same fixture, IBT not in effect: the target is still recorded as not an entry pad, but the ENDBR
|
|
# rule reports green over it. That green is the skip, not a resolution, which is the distinction
|
|
# the gate law says a reader has to be able to make.
|
|
with self.subTest(case="no-endbr-entry-disabled"):
|
|
report = check(case_object("no-endbr-entry"), ibt="0")
|
|
self.assertFalse(report["ibt_gate_enforced"])
|
|
self.assertTrue(report["checks"]["endbr64_at_data_relocation_targets"])
|
|
self.assertEqual(report["data_relocation_targets_without_endbr"], 1)
|
|
self.assertTrue(report["checks"]["data_relocation_targets_resolve_to_instructions"])
|
|
CASES_RUN.append("no-endbr-entry-disabled")
|
|
|
|
def test_entry_evidence_survives_failed_attribution(self):
|
|
# The entry pad is evidence by itself: objdump still shows the block entry, so a case whose
|
|
# disassembly cannot be attributed to a section must not lose it and fall back to the host config.
|
|
# With IBT not in effect and the only endbr64 entry inside a duplicate-name section, enforcement
|
|
# comes from the object and the target is still refused.
|
|
with self.subTest(case="duplicate-section-name-without-configuration"):
|
|
report = check(case_object("duplicate-section-name"), ibt="0")
|
|
self.assertTrue(report["ibt_gate_enforced"])
|
|
self.assertEqual(report["unattributable_duplicate_names"], 1)
|
|
self.assertFalse(report["checks"]["data_relocation_targets_resolve_to_instructions"])
|
|
CASES_RUN.append("duplicate-section-name-without-configuration")
|
|
|
|
def test_extended_section_numbering_is_read_from_the_escape_fields(self):
|
|
# Before the fix e_shnum and e_shstrndx were read straight from the header, so on this object the
|
|
# checker saw no sections and reported green over an empty set although both data relocations point
|
|
# at a ret entry: 0 recorded, 0 unresolved, the ENDBR rule green.
|
|
with self.subTest(case="extended-section-numbering"):
|
|
report = check(craft_extended_object())
|
|
self.assertEqual(report["data_relocations_to_code"], 2)
|
|
self.assertEqual(report["data_relocation_targets_without_endbr"], 2)
|
|
self.assertEqual(report["unresolved_code_targets"], 0)
|
|
self.assertFalse(report["checks"]["endbr64_at_data_relocation_targets"])
|
|
CASES_RUN.append("extended-section-numbering")
|
|
with self.subTest(case="extended-section-numbering-no-shndx-table"):
|
|
# An escape value with no associated table names no section, so this cannot report green: the
|
|
# resolver marks the symbol unresolvable, and objdump itself refuses the object, which is what
|
|
# happens first here (measured: "symbol number 2 references nonexistent SHT_SYMTAB_SHNDX
|
|
# section"), so the run exits nonzero instead of passing over an empty set.
|
|
result = subprocess.run([sys.executable, str(CHECKER), str(craft_extended_object(with_shndx_table=False)),
|
|
"--object-only"], capture_output=True, text=True,
|
|
env=dict(os.environ, NV_RS_KERNEL_IBT="1"))
|
|
self.assertNotEqual(result.returncode, 0)
|
|
self.assertIn("nonexistent SHT_SYMTAB_SHNDX", result.stderr + result.stdout)
|
|
CASES_RUN.append("extended-section-numbering-no-shndx-table")
|
|
|
|
def test_reserved_st_shndx_values_are_special_not_section_references(self):
|
|
# Before the fix the raw st_shndx was only stored after expansion, so a symbol whose raw value was
|
|
# SHN_ABS resolved through the section header table at index 65521 once extended numbering made that
|
|
# number a real section. Measured against the committed checker, this object reported green with 2
|
|
# recorded targets, one of them the absolute symbol misattributed to a section it does not name. Now
|
|
# the raw reserved value is skipped before the section-bounds check and only the SHN_XINDEX symbol,
|
|
# which resolves to the real index 65521, is recorded. The absolute symbol is not classified as
|
|
# unresolved or as SHN_UNDEF: the export set still counts it, which the nine absolute protocol names
|
|
# assert. duplicate 1 is the empty name shared by the headers that hold no content.
|
|
with self.subTest(case="reserved-st_shndx"):
|
|
report = check(craft_reserved_index_object())
|
|
self.assertEqual(rule(report), dict(resolves=True, unresolved=0, ambiguous=0, recorded=1,
|
|
not_entry_pad=0, endbr_rule=True, exports=True, duplicate=1))
|
|
CASES_RUN.append("reserved-st_shndx")
|
|
|
|
def test_make_modules_passes_kbuild_config_to_audit(self):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
work = Path(tmp)
|
|
repo = work / "repo"
|
|
(repo / "tools").mkdir(parents=True)
|
|
(repo / "kernel-open").mkdir()
|
|
(repo / "src/nvidia").mkdir(parents=True)
|
|
for path in ("Makefile", "utils.mk", "version.mk", "tools/timer-timeout-build-product.py"):
|
|
shutil.copyfile(ROOT / path, repo / path)
|
|
|
|
# Exercise the real modules recipe without compiling or loading a module.
|
|
(repo / "src/nvidia/Makefile").write_text("all:\n\t@:\n", encoding="utf-8")
|
|
(repo / "tools/check_kernel_module.py").write_text(
|
|
"import os\n"
|
|
"from pathlib import Path\n"
|
|
"config = Path(os.environ['KERNEL_OUTPUT']) / '.config'\n"
|
|
"Path('kernel-open/audited.config').write_bytes(config.read_bytes())\n",
|
|
encoding="utf-8",
|
|
)
|
|
|
|
source_config = b"CONFIG_X86_KERNEL_IBT=y\n"
|
|
output_config = b"# CONFIG_X86_KERNEL_IBT is not set\n"
|
|
for directory, config in (("kernel-source", source_config), ("kernel-output", output_config)):
|
|
kernel = work / directory
|
|
kernel.mkdir()
|
|
(kernel / ".config").write_bytes(config)
|
|
(kernel / "Makefile").write_text(
|
|
'modules:\n\t@cp .config "$(M)/built-with.config"\n', encoding="utf-8"
|
|
)
|
|
|
|
env = {"PATH": os.environ["PATH"], "HOME": tmp}
|
|
cases = (
|
|
(("KERNEL_SOURCES=kernel-source",), source_config),
|
|
(("KDIR=kernel-source", "SYSOUT=kernel-output"), output_config),
|
|
)
|
|
for options, config in cases:
|
|
with self.subTest(options=options):
|
|
result = subprocess.run(
|
|
["make", "-f", str(repo / "Makefile"), "modules", *options],
|
|
cwd=work,
|
|
env=env,
|
|
capture_output=True,
|
|
text=True,
|
|
)
|
|
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
|
self.assertEqual((repo / "kernel-open/built-with.config").read_bytes(), config)
|
|
self.assertEqual((repo / "kernel-open/audited.config").read_bytes(), config)
|
|
|
|
def test_default_validation_requires_the_module(self):
|
|
# A run that is not object-only must fail on a missing module rather than report green with
|
|
# the GOT-relocation, runtime-symbol, module-name and PCI-alias checks skipped.
|
|
with self.subTest(case="module-required"):
|
|
object_path = case_object("entry")
|
|
report = check(object_path, OUT / "no-such-module.ko")
|
|
self.assertFalse(report["checks"]["module_present"])
|
|
self.assertNotIn("no_PCI_aliases", report["checks"])
|
|
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_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`,
|
|
# and under NV_RS_KERNEL_SLS=1 it must fail `no_unhardened_sls_return`.
|
|
object_path = case_object("entry")
|
|
with self.subTest(case="rethunk-rejects-naked-ret"):
|
|
res = subprocess.run(
|
|
[sys.executable, str(CHECKER), str(object_path), "--object-only"],
|
|
capture_output=True, text=True,
|
|
env=dict(os.environ, NV_RS_KERNEL_IBT="1", NV_RS_KERNEL_RETHUNK="1"),
|
|
)
|
|
report = json.loads(res.stdout)
|
|
self.assertFalse(report["checks"]["no_naked_ret_under_rethunk"])
|
|
self.assertEqual(res.returncode, 1)
|
|
CASES_RUN.append("rethunk-rejects-naked-ret")
|
|
with self.subTest(case="sls-rejects-unhardened-ret"):
|
|
res = subprocess.run(
|
|
[sys.executable, str(CHECKER), str(object_path), "--object-only"],
|
|
capture_output=True, text=True,
|
|
env=dict(os.environ, NV_RS_KERNEL_IBT="1", NV_RS_KERNEL_SLS="1"),
|
|
)
|
|
report = json.loads(res.stdout)
|
|
self.assertFalse(report["checks"]["no_unhardened_sls_return"])
|
|
self.assertEqual(res.returncode, 1)
|
|
CASES_RUN.append("sls-rejects-unhardened-ret")
|
|
|
|
def test_call_padding_section_relative_entries_and_metadata(self):
|
|
# Under CONFIG_CALL_PADDING (-Z patchable-function-entry=16,16), each per-function code
|
|
# section begins with 16 NOP bytes before the STT_FUNC entry, and __patchable_function_entries
|
|
# points to the NOP preamble. A section-relative pointer to the padded STT_FUNC entry passes
|
|
# iff the entry starts with endbr64 and the preamble is strictly NOP padding.
|
|
OUT.mkdir(parents=True, exist_ok=True)
|
|
cases = [
|
|
(
|
|
"call-padding-valid",
|
|
".section .text.padded_ok,\"ax\"\n"
|
|
".Lpad:\n .rept 16\n nop\n .endr\n"
|
|
".type padded_ok, @function\n"
|
|
"padded_ok:\n endbr64\n ret\n"
|
|
".section __patchable_function_entries,\"a\"\n .quad .Lpad\n"
|
|
".section .rodata,\"a\"\n .quad padded_ok\n",
|
|
True, 0, 0,
|
|
),
|
|
(
|
|
"call-padding-no-endbr",
|
|
".section .text.padded_bad,\"ax\"\n"
|
|
".Lpad:\n .rept 16\n nop\n .endr\n"
|
|
".type padded_bad, @function\n"
|
|
"padded_bad:\n ret\n"
|
|
".section __patchable_function_entries,\"a\"\n .quad .Lpad\n"
|
|
".section .rodata,\"a\"\n .quad padded_bad\n",
|
|
False, 1, 0,
|
|
),
|
|
(
|
|
"call-padding-non-nop-prefix",
|
|
".section .text.non_nop,\"ax\"\n"
|
|
"xor %eax, %eax\n .rept 14\n nop\n .endr\n"
|
|
".type non_nop, @function\n"
|
|
"non_nop:\n endbr64\n ret\n"
|
|
".section .rodata,\"a\"\n .quad non_nop\n",
|
|
False, 0, 1,
|
|
),
|
|
(
|
|
"call-padding-func-sym-nonzero-addend",
|
|
".section .text.sym_off,\"ax\"\n"
|
|
".globl base_fn\n"
|
|
".type base_fn, @function\n"
|
|
"base_fn:\n .rept 16\n nop\n .endr\n"
|
|
".type target_fn, @function\n"
|
|
"target_fn:\n endbr64\n ret\n"
|
|
".section .rodata,\"a\"\n .quad base_fn+16\n",
|
|
False, 0, 1,
|
|
),
|
|
]
|
|
for name, source, want_rule, want_no_endbr, want_nonzero in cases:
|
|
with self.subTest(case=name):
|
|
path = OUT / f"{name}.o"
|
|
subprocess.run(["as", "-o", str(path)], input=source, text=True, check=True)
|
|
report = check(path)
|
|
self.assertEqual(report["data_relocations_to_code"], 1)
|
|
self.assertEqual(report["data_relocation_targets_without_endbr"], want_no_endbr)
|
|
self.assertEqual(report["data_relocations_with_nonzero_addend"], want_nonzero)
|
|
self.assertEqual(report["checks"]["endbr64_at_data_relocation_targets"], want_rule)
|
|
CASES_RUN.append(name)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
result = unittest.TextTestRunner(verbosity=2).run(
|
|
unittest.TestLoader().loadTestsFromModule(sys.modules[__name__]))
|
|
print(json.dumps({"kernel_module_gate_cases_passed": len(CASES_RUN), "cases": CASES_RUN,
|
|
"objdump_name_printing": PRINTING, "ib": "NV_RS_KERNEL_IBT=1 set by the test, not read from the host kernel config",
|
|
"hardware_exercised": False}))
|
|
raise SystemExit(0 if result.wasSuccessful() else 1)
|