mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
fix(tools): fail fast on missing explicit --nvidia-ko and add ELF kcore bounds tests
This commit is contained in:
@ -5,8 +5,10 @@ gpu_firmware_trace_map, gpu_firmware_probe_prefixes, and gpu_perf_kcore_bytes.
|
||||
import contextlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
@ -14,6 +16,49 @@ from unittest import mock
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def _make_minimal_module_elf(text_bytes: bytes, sym_name: bytes = b"test_fn") -> bytes:
|
||||
"""Build a minimal 64-bit LE ELF object with .text, .strtab, .symtab, .shstrtab."""
|
||||
shstr = b"\x00.text\x00.strtab\x00.symtab\x00.shstrtab\x00"
|
||||
strtab = b"\x00" + sym_name + b"\x00"
|
||||
# Two Elf64_Sym entries: STN_UNDEF + FUNC symbol in .text (shndx=1) at offset 0.
|
||||
sym0 = struct.pack("<IBBHQQ", 0, 0, 0, 0, 0, 0)
|
||||
sym1 = struct.pack("<IBBHQQ", 1, (1 << 4) | 2, 0, 1, 0, len(text_bytes))
|
||||
symtab = sym0 + sym1
|
||||
|
||||
off_text = 64
|
||||
off_strtab = off_text + len(text_bytes)
|
||||
off_symtab = off_strtab + len(strtab)
|
||||
off_shstr = off_symtab + len(symtab)
|
||||
off_shdrs = off_shstr + len(shstr)
|
||||
|
||||
ehdr = bytearray(64)
|
||||
ehdr[0:16] = b"\x7fELF\x02\x01\x01" + b"\x00" * 9
|
||||
struct.pack_into("<HHIQQQIHHHHHH", ehdr, 16, 1, 62, 1, 0, 0, off_shdrs, 0, 64, 0, 0, 64, 5, 4)
|
||||
|
||||
def shdr(name_off, sh_type, flags, addr, offset, size, link, info, align, entsize):
|
||||
return struct.pack("<IIQQQQIIQQ", name_off, sh_type, flags, addr, offset, size, link, info, align, entsize)
|
||||
|
||||
shdrs = b"".join([
|
||||
shdr(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
|
||||
shdr(1, 1, 6, 0, off_text, len(text_bytes), 0, 0, 16, 0), # .text (idx 1)
|
||||
shdr(7, 3, 0, 0, off_strtab, len(strtab), 0, 0, 1, 0), # .strtab (idx 2)
|
||||
shdr(15, 2, 0, 0, off_symtab, len(symtab), 2, 1, 8, 24), # .symtab (idx 3)
|
||||
shdr(23, 3, 0, 0, off_shstr, len(shstr), 0, 0, 1, 0), # .shstrtab (idx 4)
|
||||
])
|
||||
return bytes(ehdr) + text_bytes + strtab + symtab + shstr + shdrs
|
||||
|
||||
|
||||
def _make_minimal_kcore_elf(vaddr: int, payload: bytes) -> bytes:
|
||||
"""Build a minimal 64-bit LE ELF with a single PT_LOAD segment."""
|
||||
off_phdr = 64
|
||||
off_data = 64 + 56
|
||||
ehdr = bytearray(64)
|
||||
ehdr[0:16] = b"\x7fELF\x02\x01\x01" + b"\x00" * 9
|
||||
struct.pack_into("<HHIQQQIHHHHHH", ehdr, 16, 4, 62, 1, 0, off_phdr, 0, 0, 64, 56, 1, 0, 0, 0)
|
||||
phdr = struct.pack("<IIQQQQQQ", 1, 5, off_data, vaddr, 0, len(payload), len(payload), 4096)
|
||||
return bytes(ehdr) + phdr + payload
|
||||
|
||||
|
||||
def _load(name: str, rel: str):
|
||||
spec = importlib.util.spec_from_file_location(name, ROOT / rel)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
@ -64,11 +109,66 @@ class EngineAnalysisAndKcoreToolsTest(unittest.TestCase):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
fake_ko = Path(tmp) / "nvidia.ko"
|
||||
fake_ko.write_bytes(b"bad")
|
||||
missing = Path(tmp) / "does-not-exist.ko"
|
||||
with mock.patch.dict(os.environ, {"NV_RS_NVIDIA_KO": str(fake_ko)}, clear=True):
|
||||
self.assertEqual(mod.find_nvidia_ko(), fake_ko)
|
||||
with self.assertRaisesRegex(SystemExit, "Explicit --nvidia-ko not found"):
|
||||
mod.find_nvidia_ko(missing)
|
||||
with self.assertRaisesRegex(SystemExit, "not a valid 64-bit"):
|
||||
mod.main([])
|
||||
|
||||
def test_kcore_bytes_rejects_missing_explicit_nvidia_ko(self):
|
||||
mod = _load("gpu_perf_kcore_bytes", "tools/gpu_perf_kcore_bytes.py")
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
fallback_ko = Path(tmp) / "nvidia.ko"
|
||||
fallback_ko.write_bytes(b"fallback")
|
||||
missing = Path(tmp) / "missing.ko"
|
||||
with mock.patch.dict(os.environ, {"NV_RS_NVIDIA_KO": str(fallback_ko)}, clear=True):
|
||||
with self.assertRaisesRegex(SystemExit, "Explicit --nvidia-ko not found"):
|
||||
mod.find_nvidia_ko(missing)
|
||||
|
||||
def test_kcore_bytes_bounds_check_negative_past_end_and_in_range(self):
|
||||
mod = _load("gpu_perf_kcore_bytes", "tools/gpu_perf_kcore_bytes.py")
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
t = Path(tmp)
|
||||
text_bytes = bytes(range(0x10, 0x30)) # 32 bytes of .text
|
||||
mod_ko = t / "nvidia.ko"
|
||||
mod_ko.write_bytes(_make_minimal_module_elf(text_bytes, b"nv_test_fn"))
|
||||
|
||||
textbase = 0xFFFFFFFFC0001000
|
||||
seg_vaddr = textbase - 0x40
|
||||
# Layout in kcore segment: [0x40 prefix][32-byte .text][0x40 suffix]
|
||||
kcore_payload = (b"\xAA" * 0x40) + text_bytes + (b"\xBB" * 0x40)
|
||||
(t / "kcore").write_bytes(_make_minimal_kcore_elf(seg_vaddr, kcore_payload))
|
||||
(t / "modules").write_text(f"nvidia 4096 0 - Live {hex(textbase)}\n", encoding="utf-8")
|
||||
|
||||
ip_neg = textbase - 0x10 # negative offset into .text
|
||||
ip_past = textbase + 0x18 # offset 24 + 16 = 40 > 32
|
||||
ip_ok = textbase + 0x04 # in-range offset 4..20
|
||||
(t / "errors.txt").write_text(
|
||||
f"err1 ip {hex(ip_neg)}\nerr2 ip {hex(ip_past)}\nerr3 ip {hex(ip_ok)}\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
out_path = t / "out.json"
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
mod.main([
|
||||
"--cache", str(t),
|
||||
"--errors", str(t / "errors.txt"),
|
||||
"--output", str(out_path),
|
||||
"--nvidia-ko", str(mod_ko),
|
||||
])
|
||||
report = json.loads(out_path.read_text(encoding="utf-8"))
|
||||
rows = report["initial_mismatch_code_comparisons"]
|
||||
self.assertEqual(len(rows), 3)
|
||||
self.assertFalse(rows[0]["in_module_text"])
|
||||
self.assertEqual(rows[0]["module_offset"], "-0x10")
|
||||
self.assertFalse(rows[1]["in_module_text"])
|
||||
self.assertEqual(rows[1]["module_offset"], "0x18")
|
||||
self.assertTrue(rows[2]["in_module_text"])
|
||||
self.assertTrue(rows[2]["equal"])
|
||||
self.assertEqual(rows[2]["symbol"], "nv_test_fn")
|
||||
self.assertEqual(rows[2]["installed_file_hex"], text_bytes[4:20].hex())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@ -14,9 +14,11 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def find_nvidia_ko(explicit: Path | None = None) -> Path:
|
||||
candidates = []
|
||||
if explicit is not None:
|
||||
candidates.append(explicit)
|
||||
if explicit.is_file():
|
||||
return explicit
|
||||
raise SystemExit(f'Explicit --nvidia-ko not found: {explicit}')
|
||||
candidates = []
|
||||
if os.environ.get('NV_RS_NVIDIA_KO'):
|
||||
candidates.append(Path(os.environ['NV_RS_NVIDIA_KO']))
|
||||
release = platform.release()
|
||||
|
||||
@ -14,9 +14,11 @@ PT_LOAD = 1
|
||||
|
||||
|
||||
def find_nvidia_ko(explicit: Path | None = None) -> Path:
|
||||
candidates = []
|
||||
if explicit is not None:
|
||||
candidates.append(explicit)
|
||||
if explicit.is_file():
|
||||
return explicit
|
||||
raise SystemExit(f'Explicit --nvidia-ko not found: {explicit}')
|
||||
candidates = []
|
||||
if os.environ.get('NV_RS_NVIDIA_KO'):
|
||||
candidates.append(Path(os.environ['NV_RS_NVIDIA_KO']))
|
||||
release = platform.release()
|
||||
|
||||
Reference in New Issue
Block a user