mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
201 lines
7.9 KiB
Python
201 lines
7.9 KiB
Python
#!/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('<Q', raw, 40)
|
|
e_shentsize, e_shnum, e_shstrndx = struct.unpack_from('<HHH', raw, 58)
|
|
sh0 = struct.unpack_from('<IIQQQQIIQQ', raw, e_shoff)
|
|
if e_shnum == 0:
|
|
e_shnum = sh0[5]
|
|
if e_shstrndx == 0xFFFF:
|
|
e_shstrndx = sh0[6]
|
|
hdrs = [struct.unpack_from('<IIQQQQIIQQ', raw, e_shoff + i * e_shentsize) for i in range(e_shnum)]
|
|
str_off, str_size = hdrs[e_shstrndx][4], hdrs[e_shstrndx][5]
|
|
shstr = raw[str_off:str_off + str_size]
|
|
sections = []
|
|
by_name = {}
|
|
for idx, h in enumerate(hdrs):
|
|
nul = shstr.find(b'\x00', h[0])
|
|
name = shstr[h[0]:nul if nul != -1 else len(shstr)].decode('utf-8', errors='replace')
|
|
sections.append((name, h))
|
|
by_name[name] = idx
|
|
return sections, by_name
|
|
|
|
|
|
def _load_symbols(raw: bytes, sections, sym_idx: int):
|
|
_, h = sections[sym_idx]
|
|
entsize = h[9] or 24
|
|
str_h = sections[h[6]][1]
|
|
strtab = raw[str_h[4]:str_h[4] + str_h[5]]
|
|
ext = None
|
|
for _, sh in sections:
|
|
if sh[1] == 18 and sh[6] == sym_idx:
|
|
ext = struct.unpack_from(f'<{sh[5] // 4}I', raw, sh[4])
|
|
break
|
|
syms = []
|
|
for i in range(h[5] // entsize):
|
|
st_name, st_info, _st_other, st_shndx, st_value, st_size = struct.unpack_from('<IBBHQQ', raw, h[4] + i * entsize)
|
|
if st_shndx == 0xFFFF and ext is not None and i < len(ext):
|
|
st_shndx = ext[i]
|
|
nul = strtab.find(b'\x00', st_name)
|
|
name = strtab[st_name:nul if nul != -1 else len(strtab)].decode('utf-8', errors='replace')
|
|
syms.append((name, st_shndx, st_value, st_size, st_info & 0xF))
|
|
return syms
|
|
|
|
|
|
def _load_pt_load_segments(stream) -> 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('<Q', ehdr, 32)
|
|
e_phentsize, e_phnum = struct.unpack_from('<HH', ehdr, 54)
|
|
if e_phoff == 0 or e_phentsize < 56 or e_phnum == 0:
|
|
raise SystemExit('kcore has no program headers')
|
|
segments = []
|
|
stream.seek(e_phoff)
|
|
for _ in range(e_phnum):
|
|
ph = stream.read(e_phentsize)
|
|
if len(ph) < 56:
|
|
break
|
|
p_type, _p_flags, p_offset, p_vaddr, _p_paddr, p_filesz, _p_memsz, _p_align = struct.unpack_from('<IIQQQQQQ', ph, 0)
|
|
if p_type == PT_LOAD:
|
|
segments.append((p_vaddr, p_offset, p_filesz))
|
|
return segments
|
|
|
|
|
|
def main(argv=None) -> 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('<QQq', raw_mod, rel_h[4] + i * rel_entsize)
|
|
relocs.append({
|
|
'offset': r_offset,
|
|
'type': r_info & 0xFFFFFFFF,
|
|
'symbol': syms_all[r_info >> 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()
|