#!/usr/bin/env python3 """Compare captured runtime code to modulefile at existing PT decode errors. Reads only cached code, never /proc/kcore; does not decode/capture or mutateperf. """ import argparse import json import os from pathlib import Path import platform import re import struct PT_LOAD = 1 def find_nvidia_ko(explicit: Path | None = None) -> Path: if explicit is not None: 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() candidates.extend([ 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 raise SystemExit('Cannot find installed nvidia.ko; set NV_RS_NVIDIA_KO or pass --nvidia-ko') def _parse_elf64_sections(raw: bytes): if len(raw) < 64 or raw[:4] != b'\x7fELF' or raw[4] != 2 or raw[5] != 1: raise SystemExit('module file is not a valid 64-bit little-endian ELF file') e_shoff, = struct.unpack_from(' list[tuple[int, int, int]]: ehdr = stream.read(64) if len(ehdr) < 64 or ehdr[:4] != b'\x7fELF' or ehdr[4] != 2 or ehdr[5] != 1: raise SystemExit('kcore is not a valid 64-bit little-endian ELF file') e_phoff, = struct.unpack_from(' None: p = argparse.ArgumentParser(description=__doc__) p.add_argument('--cache', type=Path, required=True) p.add_argument('--errors', type=Path, required=True) p.add_argument('--output', type=Path, required=True) p.add_argument('--nvidia-ko', type=Path, default=None) args = p.parse_args(argv) module_path = find_nvidia_ko(args.nvidia_ko) cache_dir = args.cache modules_file = cache_dir / 'modules' if not modules_file.is_file(): raise SystemExit(f'modules snapshot not found: {modules_file}') moduleline = next( (x for x in modules_file.read_text(encoding='utf-8').splitlines() if (parts := x.split()) and parts[0] == 'nvidia'), None, ) if moduleline is None or len(moduleline.split()) < 6: raise SystemExit(f'no valid nvidia module line found in {modules_file}') textbase = int(moduleline.split()[5], 16) raw_mod = module_path.read_bytes() sections, by_name = _parse_elf64_sections(raw_mod) textindex = by_name['.text'] text_h = sections[textindex][1] text = raw_mod[text_h[4]:text_h[4] + text_h[5]] syms_all = _load_symbols(raw_mod, sections, by_name['.symtab']) relocs = [] if '.rela.text' in by_name: rel_h = sections[by_name['.rela.text']][1] rel_entsize = rel_h[9] or 24 for i in range(rel_h[5] // rel_entsize): r_offset, r_info, _r_addend = struct.unpack_from('> 32][0], }) syms = sorted((s[2], s[0]) for s in syms_all if s[1] == textindex and s[4] == 2) with (cache_dir / 'kcore').open('rb') as f: segments = _load_pt_load_segments(f) rows = [] for line in args.errors.read_text(encoding='utf-8').splitlines()[:12]: match = re.search(r' ip (0x[0-9a-f]+)', line) if not match: continue ip = int(match[1], 16) ph = next((seg for seg in segments if seg[0] <= ip and ip + 16 <= seg[0] + seg[2]), None) if ph is None: rows.append({'ip': hex(ip), 'cached_code_present': False}) continue p_vaddr, p_offset, _p_filesz = ph f.seek(p_offset + ip - p_vaddr) runtime = f.read(16) offset = ip - textbase if offset < 0 or offset + 16 > len(text): rows.append({ 'ip': hex(ip), 'module_offset': hex(offset), 'cached_code_present': True, 'in_module_text': False, 'runtime_hex': runtime.hex(), }) continue disk = text[offset:offset + 16] near = max((s for s in syms if s[0] <= offset), default=(0, '')) near_reloc = [ {'relative_to_ip': r['offset'] - offset, 'type': r['type'], 'symbol': r['symbol']} for r in relocs if offset - 8 <= r['offset'] < offset + 16 ] rows.append({ 'ip': hex(ip), 'module_offset': hex(offset), 'symbol': near[1], 'symbol_offset': hex(offset - near[0]), 'cached_code_present': True, 'in_module_text': True, 'runtime_hex': runtime.hex(), 'installed_file_hex': disk.hex(), 'equal': runtime == disk, 'near_relocations': near_reloc, }) report = { 'read_only': True, 'cache_dir': str(cache_dir), 'module_line': moduleline, 'module_text_base': hex(textbase), 'initial_mismatch_code_comparisons': rows, 'claim': 'Read-only cached runtime instruction comparison; no decoded execution sequence or call hits validated by this comparison.', 'tracing_changed': False, } args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8') print(json.dumps(rows[:3], indent=2)) if __name__ == '__main__': main()