Files
nvdriver/tools/gpu_firmware_probe_prefixes.py

155 lines
6.6 KiB
Python

#!/usr/bin/env python3
"""Read installed NVIDIA module ELF prefixes; never register/execute probes."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import platform
import re
import struct
import subprocess
ROOT = Path(__file__).resolve().parents[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(raw: bytes):
if len(raw) < 64 or raw[:4] != b'\x7fELF' or raw[4] != 2 or raw[5] != 1:
raise SystemExit('input 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 main(argv=None) -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--nvidia-ko', type=Path, default=None)
args = parser.parse_args(argv)
module_path = find_nvidia_ko(args.nvidia_ko)
manifest = json.loads((ROOT / 'reports/gpu-firmware-live-trace-map.json').read_text(encoding='utf-8'))
names = [r['symbol'] for r in manifest['symbols']] + ['rm_init_adapter', '_nv000790rm', 'nv_open_device', 'nv_close_device']
raw_elf = module_path.read_bytes()
sections, by_name = _parse_elf64(raw_elf)
syms = _load_symbols(raw_elf, sections, by_name['.symtab'])
symbols = {s[0]: s for s in syms}
text_idx = by_name['.text']
text_h = sections[text_idx][1]
text = raw_elf[text_h[4]:text_h[4] + text_h[5]]
rows = []
for name in names:
if name not in symbols:
raise SystemExit(f'symbol {name!r} not found in {module_path}')
s = symbols[name]
if s[1] != text_idx:
raise SystemExit(f'symbol {name!r} is not in .text')
off = s[2]
raw = text[off:off + 24]
output = subprocess.check_output(['objdump', '-d', '--disassemble=' + name, str(module_path)], text=True)
instructions = [line.strip() for line in output.splitlines() if re.match(r'^\s*[0-9a-f]+:\s', line)][:6]
is_endbr = raw[:4] == bytes.fromhex('f30f1efa')
rows.append({
'symbol': name,
'module_text_offset': hex(off),
'prefix_hex': raw.hex(),
'first_instructions': instructions,
'endbr64_at_entry': is_endbr,
'offset4_preserves_all_entry_registers_and_RSP': is_endbr,
'offset4_safe_instruction_boundary': is_endbr,
'trace_registration_guaranteed': False,
})
fentry = []
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_elf, rel_h[4] + i * rel_entsize)
target_name = syms[r_info >> 32][0]
if target_name in ('__fentry__', 'mcount', '_mcount'):
for name in ('nv_open_device', 'nv_close_device', 'rm_init_adapter', '_nv000790rm', '_nv028470rm'):
fn = symbols[name]
if fn[1] == text_idx and fn[2] <= r_offset < fn[2] + 24:
fentry.append({'symbol': name, 'relocation_offset_from_entry': r_offset - fn[2], 'target': target_name})
report = {
'read_only': True,
'installed_module_file': str(module_path),
'installed_module_sha256': hashlib.sha256(raw_elf).hexdigest(),
'prefixes': rows,
'entry_fentry_relocations': fentry,
'interpretation': [
'ENDBR64 is4bytes and has no architectural register/SP mutation. A probe at+4 lands on the next original instruction and sees entry registers/RSP.',
'This is an instruction-boundary/snapshot contract only; kernel trace policy, decoder and module lifetime still control registration.',
'RM code uses a customRBP frame area; RBP must not be assumed a conventional frame pointer or C unwinding proof.',
'A probe after the first push changes entry stackargument offsets. Exact+4 avoids that for ENDBR-prefixed entries.',
'Public wrapperfentry versus privateRM nofentry is consistent with NOTRACE policy rejection; installedprefix evidence alone cannot prove rejection cause.',
],
'tracing_changed': False,
}
out = ROOT / 'reports/gpu-firmware-probe-prefixes.json'
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
print('entries', len(rows), 'ENDBR', sum(r['endbr64_at_entry'] for r in rows), 'fentry', fentry)
if __name__ == '__main__':
main()