From c88901e514b1ee9be2bf8fdd6962a214e2ec03b4 Mon Sep 17 00:00:00 2001 From: morebrackets <19673572+morebrackets@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:06:58 -0800 Subject: [PATCH] fix(tools): fail fast on missing explicit paths, derive alarm claim from evidence, and add valid ELF64 tests --- ...t_clock_register_policy_and_timer_tools.py | 156 +++++++++++++++++- tools/gpu_generate_clock_object_metadata.py | 8 +- tools/gpu_generate_register_policy_oracle.py | 8 +- tools/timer-alarm-context-os-evidence.py | 51 +++++- tools/timer-timeout-vgx-evidence.py | 31 ++-- 5 files changed, 232 insertions(+), 22 deletions(-) diff --git a/tests/offline/test_clock_register_policy_and_timer_tools.py b/tests/offline/test_clock_register_policy_and_timer_tools.py index 4417f1e6..658f8640 100644 --- a/tests/offline/test_clock_register_policy_and_timer_tools.py +++ b/tests/offline/test_clock_register_policy_and_timer_tools.py @@ -6,9 +6,11 @@ timer-timeout-vgx-evidence, and timer-alarm-context-os-evidence. import contextlib import importlib.util import io +import json import os from pathlib import Path import shutil +import struct import tempfile import unittest from unittest import mock @@ -16,6 +18,69 @@ from unittest import mock ROOT = Path(__file__).resolve().parents[2] +def _build_elf64_fixture( + funcs: list[tuple[str, int, int, bool]], + relocs: list[tuple[int, int, int, int]], + modinfo: bytes = b"version=580.178.04\x00", +) -> bytes: + """Build a minimal valid 64-bit LE ELF with .text, .strtab, .symtab, + .symtab_shndx (SHT_SYMTAB_SHNDX=18), .rela.text, .modinfo, and .shstrtab. + + `funcs` is [(name, offset, size, use_xindex), ...]; symbol 0 is STN_UNDEF. + `relocs` is [(r_offset, sym_idx, r_type, r_addend), ...]. + """ + text_len = max((off + sz for _, off, sz, _ in funcs), default=32) + text_bytes = bytes((i & 0xFF) for i in range(max(text_len, 32))) + + shstr = b"\x00.text\x00.strtab\x00.symtab\x00.symtab_shndx\x00.rela.text\x00.modinfo\x00.shstrtab\x00" + strtab = bytearray(b"\x00") + syms = [struct.pack(" int: + return shstr.index(b"\x00" + sec_name + b"\x00") + 1 + + shdrs = b"".join([ + shdr(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), + shdr(_name_off(b".text"), 1, 6, 0, off_text, len(text_bytes), 0, 0, 16, 0), + shdr(_name_off(b".strtab"), 3, 0, 0, off_strtab, len(strtab), 0, 0, 1, 0), + shdr(_name_off(b".symtab"), 2, 0, 0, off_symtab, len(symtab), 2, 1, 8, 24), + shdr(_name_off(b".symtab_shndx"), 18, 0, 0, off_shndx, len(symtab_shndx), 3, 0, 4, 4), + shdr(_name_off(b".rela.text"), 4, 0, 0, off_rela, len(rela_text), 3, 1, 8, 24), + shdr(_name_off(b".modinfo"), 1, 0, 0, off_modinfo, len(modinfo), 0, 0, 1, 0), + shdr(_name_off(b".shstrtab"), 3, 0, 0, off_shstr, len(shstr), 0, 0, 1, 0), + ]) + return bytes(ehdr) + text_bytes + bytes(strtab) + symtab + symtab_shndx + rela_text + modinfo + shstr + shdrs + + def _load(name: str, rel: str): spec = importlib.util.spec_from_file_location(name, ROOT / rel) mod = importlib.util.module_from_spec(spec) @@ -73,14 +138,103 @@ class ClockRegisterPolicyAndTimerToolsTest(unittest.TestCase): def test_timer_evidence_portable_nvidia_ko_discovery(self): vgx = _load("timer_timeout_vgx_evidence", "tools/timer-timeout-vgx-evidence.py") alarm = _load("timer_alarm_context_os_evidence", "tools/timer-alarm-context-os-evidence.py") + clk = _load("gpu_generate_clock_object_metadata", "tools/gpu_generate_clock_object_metadata.py") + reg = _load("gpu_generate_register_policy_oracle", "tools/gpu_generate_register_policy_oracle.py") with tempfile.TemporaryDirectory() as tmp: fake_ko = Path(tmp) / "nvidia.ko" fake_ko.write_bytes(b"not-elf") - with mock.patch.dict(os.environ, {"NV_RS_NVIDIA_KO": str(fake_ko)}, clear=True): + missing = Path(tmp) / "missing.ko" + with mock.patch.dict(os.environ, {"NV_RS_NVIDIA_KO": str(fake_ko), "NV_RS_RM_OBJECT": str(fake_ko)}, clear=True): self.assertEqual(vgx.find_nvidia_ko(), fake_ko) self.assertEqual(alarm.find_nvidia_ko(), fake_ko) + with self.assertRaisesRegex(SystemExit, "Explicit --nvidia-ko not found"): + vgx.find_nvidia_ko(missing) + with self.assertRaisesRegex(SystemExit, "Explicit --rm-object not found"): + vgx.find_rm_object(missing) + with self.assertRaisesRegex(SystemExit, "Explicit --nvidia-ko not found"): + alarm.find_nvidia_ko(missing) with self.assertRaisesRegex(SystemExit, "not a valid 64-bit"): alarm.main([]) + with mock.patch.dict(os.environ, {"NV_RS_NVIDIA_KO": str(missing), "NV_RS_RM_OBJECT": str(missing)}, clear=True): + with self.assertRaisesRegex(SystemExit, "NV_RS_NVIDIA_KO not found"): + vgx.find_nvidia_ko() + with self.assertRaisesRegex(SystemExit, "NV_RS_RM_OBJECT not found"): + vgx.find_rm_object() + with self.assertRaisesRegex(SystemExit, "NV_RS_NVIDIA_KO not found"): + alarm.find_nvidia_ko() + with self.assertRaisesRegex(SystemExit, "NV_RS_RM_OBJECT not found"): + clk.find_rm_object() + with self.assertRaisesRegex(SystemExit, "NV_RS_RM_OBJECT not found"): + reg.find_rm_object() + + def test_valid_elf64_readers_sections_xindex_and_relocations(self): + clk = _load("gpu_generate_clock_object_metadata", "tools/gpu_generate_clock_object_metadata.py") + reg = _load("gpu_generate_register_policy_oracle", "tools/gpu_generate_register_policy_oracle.py") + vgx = _load("timer_timeout_vgx_evidence", "tools/timer-timeout-vgx-evidence.py") + alarm = _load("timer_alarm_context_os_evidence", "tools/timer-alarm-context-os-evidence.py") + + # Symbol 1 uses standard shndx=1; symbol 2 uses SHN_XINDEX (0xFFFF) resolved via SHT_SYMTAB_SHNDX -> 1. + raw = _build_elf64_fixture( + funcs=[ + ("nv_create_nano_timer", 0x00, 0x20, False), + ("nv_jiffy_timer_callback_typed_data", 0x20, 0x20, True), + ("os_queue_work_item", 0x40, 0x20, False), + ("os_execute_work_item", 0x60, 0x20, True), + ], + relocs=[ + (0x08, 2, 11, 0), # nv_create_nano_timer -> nv_jiffy_timer_callback_typed_data + (0x48, 4, 11, 0), # os_queue_work_item -> os_execute_work_item + ], + ) + + # Verify all 4 ELF readers parse sections and resolve SHN_XINDEX -> section 1 (.text). + for mod, parse_fn, sym_fn in ( + (clk, clk.parse_elf64, clk.load_symbols), + (vgx, vgx._parse_elf64, vgx._load_symbols), + (alarm, alarm._parse_elf64, alarm._load_symbols), + ): + sections, by_name = parse_fn(raw) + self.assertIn(".text", by_name) + self.assertIn(".rela.text", by_name) + syms = sym_fn(raw, sections, by_name[".symtab"]) + by_sym = {s[0]: s for s in syms} + self.assertEqual(by_sym["nv_jiffy_timer_callback_typed_data"][1], by_name[".text"]) + self.assertEqual(by_sym["os_execute_work_item"][1], by_name[".text"]) + + sections, by_name = reg.parse_elf64(raw) + reg_syms = reg.load_symbols(raw, sections, by_name[".symtab"]) + self.assertEqual(reg_syms[2], (by_name[".text"], 0x20)) + self.assertEqual(reg_syms[4], (by_name[".text"], 0x60)) + + # Verify timer-timeout-vgx-evidence.symbol() reads relocations on the valid ELF. + with tempfile.TemporaryDirectory() as tmp: + t = Path(tmp) + ko_full = t / "nvidia_full.ko" + ko_full.write_bytes(raw) + info = vgx.symbol(ko_full, "nv_create_nano_timer") + self.assertEqual(info["section"], ".text") + self.assertEqual( + [r["target"] for r in info["relocations"]], + ["nv_jiffy_timer_callback_typed_data"], + ) + + # Verify timer-alarm-context-os-evidence confirms claim when evidence is present... + with mock.patch.object(alarm, "ROOT", t), contextlib.redirect_stdout(io.StringIO()): + alarm.main(["--nvidia-ko", str(ko_full)]) + rep_full = json.loads((t / "reports/timer-alarm-context-os-evidence.json").read_text()) + self.assertTrue(rep_full["jiffy_branch_confirmed"]) + self.assertTrue(rep_full["rm_work_queue_confirmed"]) + self.assertIn("confirms jiffy timer branch", rep_full["claim"]) + + # ...and does NOT overstate the claim when wanted timer/work symbols are absent. + ko_empty = t / "nvidia_empty.ko" + ko_empty.write_bytes(_build_elf64_fixture(funcs=[("unrelated_fn", 0x0, 0x20, False)], relocs=[])) + with mock.patch.object(alarm, "ROOT", t), contextlib.redirect_stdout(io.StringIO()): + alarm.main(["--nvidia-ko", str(ko_empty)]) + rep_empty = json.loads((t / "reports/timer-alarm-context-os-evidence.json").read_text()) + self.assertFalse(rep_empty["jiffy_branch_confirmed"]) + self.assertFalse(rep_empty["rm_work_queue_confirmed"]) + self.assertIn("incomplete", rep_empty["claim"]) if __name__ == "__main__": diff --git a/tools/gpu_generate_clock_object_metadata.py b/tools/gpu_generate_clock_object_metadata.py index 2ab92695..0f3130f6 100644 --- a/tools/gpu_generate_clock_object_metadata.py +++ b/tools/gpu_generate_clock_object_metadata.py @@ -18,9 +18,13 @@ METHOD_IDS = [ def find_rm_object() -> Path: + env_rm = os.environ.get('NV_RS_RM_OBJECT') + if env_rm: + p = Path(env_rm) + if p.is_file(): + return p + raise SystemExit(f'NV_RS_RM_OBJECT not found: {p}') candidates = [] - if os.environ.get('NV_RS_RM_OBJECT'): - candidates.append(Path(os.environ['NV_RS_RM_OBJECT'])) if os.environ.get('NV_RS_KERNEL_SRC'): base = Path(os.environ['NV_RS_KERNEL_SRC']) candidates.extend([base / 'nvidia/nv-kernel.o_binary', base]) diff --git a/tools/gpu_generate_register_policy_oracle.py b/tools/gpu_generate_register_policy_oracle.py index 7861c014..eb634502 100644 --- a/tools/gpu_generate_register_policy_oracle.py +++ b/tools/gpu_generate_register_policy_oracle.py @@ -14,9 +14,13 @@ DEFAULT_ANALYSIS_ROOT = Path('/home/geodd/nvidia-driver/analysis-580.178.04') def find_rm_object() -> Path: + env_rm = os.environ.get('NV_RS_RM_OBJECT') + if env_rm: + p = Path(env_rm) + if p.is_file(): + return p + raise SystemExit(f'NV_RS_RM_OBJECT not found: {p}') candidates = [] - if os.environ.get('NV_RS_RM_OBJECT'): - candidates.append(Path(os.environ['NV_RS_RM_OBJECT'])) if os.environ.get('NV_RS_KERNEL_SRC'): base = Path(os.environ['NV_RS_KERNEL_SRC']) candidates.extend([base / 'nvidia/nv-kernel.o_binary', base]) diff --git a/tools/timer-alarm-context-os-evidence.py b/tools/timer-alarm-context-os-evidence.py index 54f696a6..4391500b 100644 --- a/tools/timer-alarm-context-os-evidence.py +++ b/tools/timer-alarm-context-os-evidence.py @@ -22,16 +22,21 @@ WANTED = [ def find_nvidia_ko(explicit: Path | None = None) -> Path: - candidates = [] if explicit is not None: - candidates.append(explicit) - if os.environ.get('NV_RS_NVIDIA_KO'): - candidates.append(Path(os.environ['NV_RS_NVIDIA_KO'])) + if explicit.is_file(): + return explicit + raise SystemExit(f'Explicit --nvidia-ko not found: {explicit}') + env_ko = os.environ.get('NV_RS_NVIDIA_KO') + if env_ko: + p = Path(env_ko) + if p.is_file(): + return p + raise SystemExit(f'NV_RS_NVIDIA_KO not found: {p}') release = platform.release() - candidates.extend([ + candidates = [ Path(f'/lib/modules/{release}/updates/dkms/nvidia.ko'), Path('/lib/modules/5.15.0-202-generic/updates/dkms/nvidia.ko'), - ]) + ] for candidate in candidates: if candidate.is_file(): return candidate @@ -150,13 +155,45 @@ def main(argv=None) -> None: else f'Installed({module_version or "unknown"})' ) + jiffy_branch_confirmed = ( + records['nv_jiffy_timer_callback_typed_data']['present'] + and any( + r['target'] == 'nv_jiffy_timer_callback_typed_data' + for r in records['nv_create_nano_timer']['references'] + ) + ) + rm_work_queue_confirmed = ( + records['os_queue_work_item']['present'] + and records['os_execute_work_item']['present'] + and any( + r['target'] == 'os_execute_work_item' + for r in records['os_queue_work_item']['references'] + ) + ) + present_names = [name for name in WANTED if records[name]['present']] + if jiffy_branch_confirmed and rm_work_queue_confirmed: + claim = ( + f'{version_tag} relocation evidence confirms jiffy timer branch and RM work-queue ' + 'path; static relocation facts only, not live callback execution.' + ) + else: + claim = ( + f'{version_tag} relocation evidence incomplete ' + f'(jiffy_branch_confirmed={jiffy_branch_confirmed}, ' + f'rm_work_queue_confirmed={rm_work_queue_confirmed}, ' + f'present={len(present_names)}/{len(WANTED)}); ' + 'static relocation facts only, not live callback execution.' + ) + report = { 'read_only': True, 'installed_module': str(module_path), 'installed_module_version': module_version, 'installed_module_sha256': hashlib.sha256(raw).hexdigest(), 'functions': records, - 'claim': f'{version_tag} usesjiffytimer branch andqueuesRMwork; relocationfactsnotlivecallbackexecution.', + 'jiffy_branch_confirmed': jiffy_branch_confirmed, + 'rm_work_queue_confirmed': rm_work_queue_confirmed, + 'claim': claim, 'tracing_changed': False, } out = ROOT / 'reports/timer-alarm-context-os-evidence.json' diff --git a/tools/timer-timeout-vgx-evidence.py b/tools/timer-timeout-vgx-evidence.py index 2a7cf7bb..a576763e 100644 --- a/tools/timer-timeout-vgx-evidence.py +++ b/tools/timer-timeout-vgx-evidence.py @@ -13,11 +13,17 @@ DEFAULT_ANALYSIS_ROOT = Path('/home/geodd/nvidia-driver/analysis-580.178.04') def find_rm_object(explicit: Path | None = None) -> Path: - candidates = [] if explicit is not None: - candidates.append(explicit) - if os.environ.get('NV_RS_RM_OBJECT'): - candidates.append(Path(os.environ['NV_RS_RM_OBJECT'])) + if explicit.is_file(): + return explicit + raise SystemExit(f'Explicit --rm-object not found: {explicit}') + env_rm = os.environ.get('NV_RS_RM_OBJECT') + if env_rm: + p = Path(env_rm) + if p.is_file(): + return p + raise SystemExit(f'NV_RS_RM_OBJECT not found: {p}') + candidates = [] if os.environ.get('NV_RS_KERNEL_SRC'): base = Path(os.environ['NV_RS_KERNEL_SRC']) candidates.extend([base / 'nvidia/nv-kernel.o_binary', base]) @@ -34,16 +40,21 @@ def find_rm_object(explicit: Path | None = None) -> Path: def find_nvidia_ko(explicit: Path | None = None) -> Path: - candidates = [] if explicit is not None: - candidates.append(explicit) - if os.environ.get('NV_RS_NVIDIA_KO'): - candidates.append(Path(os.environ['NV_RS_NVIDIA_KO'])) + if explicit.is_file(): + return explicit + raise SystemExit(f'Explicit --nvidia-ko not found: {explicit}') + env_ko = os.environ.get('NV_RS_NVIDIA_KO') + if env_ko: + p = Path(env_ko) + if p.is_file(): + return p + raise SystemExit(f'NV_RS_NVIDIA_KO not found: {p}') release = platform.release() - candidates.extend([ + candidates = [ Path(f'/lib/modules/{release}/updates/dkms/nvidia.ko'), Path('/lib/modules/5.15.0-202-generic/updates/dkms/nvidia.ko'), - ]) + ] for candidate in candidates: if candidate.is_file(): return candidate