Files
nvdriver/tools/_elf64_reader.py

197 lines
7.8 KiB
Python

"""Minimal stdlib ELF64 relocatable-object reader and portable 580.178.04 discovery.
Provides section data, `.symtab` symbols, and `.rela.*` relocations without
requiring optional third-party `pyelftools`.
"""
import hashlib
import os
from pathlib import Path
import struct
EXPECTED_RM_OBJECT_SHA256 = (
'5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b'
)
DEFAULT_ANALYSIS_ROOT = Path('/home/geodd/nvidia-driver/analysis-580.178.04')
SHN_XINDEX = 0xFFFF
SHT_NOBITS = 8
SHT_SYMTAB_SHNDX = 18
STT_OBJECT = 1
STT_FUNC = 2
def find_rm_object(explicit: Path | None = None) -> Path:
candidates: list[Path] = []
if explicit is not None:
candidates.append(explicit)
env_obj = os.environ.get('NV_RS_RM_OBJECT')
if env_obj:
candidates.append(Path(env_obj))
env_ksrc = os.environ.get('NV_RS_KERNEL_SRC')
if env_ksrc:
base = Path(env_ksrc)
candidates.extend([base / 'nvidia/nv-kernel.o_binary', base])
analysis = Path(os.environ.get('NV_RS_ANALYSIS_ROOT', str(DEFAULT_ANALYSIS_ROOT)))
candidates.append(analysis / 'extracted/kernel/nvidia/nv-kernel.o_binary')
candidates.extend([
Path('/usr/src/nvidia-580.178.04/nvidia/nv-kernel.o_binary'),
Path('/usr/src/nvidia-srv-580.178.04/nvidia/nv-kernel.o_binary'),
])
for candidate in candidates:
if candidate.is_file():
return candidate
raise SystemExit(
'Cannot find 580.178.04 nv-kernel.o_binary. '
'Set NV_RS_RM_OBJECT, NV_RS_KERNEL_SRC, or NV_RS_ANALYSIS_ROOT.'
)
def sha256_file(path: Path) -> str:
h = hashlib.sha256()
with path.open('rb') as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
h.update(chunk)
return h.hexdigest()
def verify_rm_object_sha256(path: Path, expected: str = EXPECTED_RM_OBJECT_SHA256) -> str:
actual = sha256_file(path)
if actual != expected:
raise SystemExit(f'{path}: sha256 mismatch ({actual} != {expected})')
return actual
class Elf64Relocatable:
"""Pure-stdlib ELF64 little-endian section/symtab/rela reader."""
def __init__(self, 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)
if e_shoff == 0 or e_shentsize < 64:
raise SystemExit('ELF section header table is missing or malformed')
if e_shoff + e_shentsize > len(raw):
raise SystemExit('ELF section header 0 exceeds file size')
sh0 = struct.unpack_from('<IIQQQQIIQQ', raw, e_shoff)
if e_shnum == 0:
e_shnum = sh0[5] # sh_size
if e_shstrndx == SHN_XINDEX:
e_shstrndx = sh0[6] # sh_link
if e_shnum == 0 or e_shstrndx >= e_shnum:
raise SystemExit('ELF section header count/shstrndx is invalid')
if e_shoff + e_shentsize * e_shnum > len(raw):
raise SystemExit('ELF section header table exceeds file size')
self._raw = raw
headers = [
struct.unpack_from('<IIQQQQIIQQ', raw, e_shoff + idx * e_shentsize)
for idx in range(e_shnum)
]
str_off, str_size = headers[e_shstrndx][4], headers[e_shstrndx][5]
if str_off + str_size > len(raw):
raise SystemExit('ELF section string table exceeds file size')
shstrtab = raw[str_off:str_off + str_size]
self.sections: list[dict] = []
self._by_name: dict[str, int] = {}
for idx, (sh_name, sh_type, sh_flags, sh_addr, sh_offset, sh_size, sh_link, sh_info, sh_addralign, sh_entsize) in enumerate(headers):
nul = shstrtab.find(b'\x00', sh_name)
name = shstrtab[sh_name:nul if nul != -1 else len(shstrtab)].decode('utf-8', errors='replace')
if sh_type != SHT_NOBITS and sh_offset + sh_size > len(raw):
raise SystemExit(f'ELF section {name!r} exceeds file size')
entry = {
'index': idx,
'name': name,
'sh_type': sh_type,
'sh_flags': sh_flags,
'sh_addr': sh_addr,
'sh_offset': sh_offset,
'sh_size': sh_size,
'sh_link': sh_link,
'sh_info': sh_info,
'sh_addralign': sh_addralign,
'sh_entsize': sh_entsize,
}
self.sections.append(entry)
self._by_name[name] = idx
@classmethod
def from_path(cls, path: Path) -> 'Elf64Relocatable':
return cls(path.read_bytes())
def section_index(self, name: str) -> int:
if name not in self._by_name:
raise SystemExit(f'ELF missing required section {name!r}')
return self._by_name[name]
def has_section(self, name: str) -> bool:
return name in self._by_name
def section_name(self, index: int) -> str:
if not (0 <= index < len(self.sections)):
raise SystemExit(f'ELF section index out of range: {index}')
return self.sections[index]['name']
def section_data(self, index_or_name: int | str) -> bytes:
idx = self.section_index(index_or_name) if isinstance(index_or_name, str) else index_or_name
sec = self.sections[idx]
if sec['sh_type'] == SHT_NOBITS:
return b''
off, size = sec['sh_offset'], sec['sh_size']
return self._raw[off:off + size]
def symbols(self) -> list[dict]:
sym_idx = self.section_index('.symtab')
sym_sec = self.sections[sym_idx]
entsize = sym_sec['sh_entsize'] or 24
if entsize < 24 or sym_sec['sh_size'] % entsize != 0:
raise SystemExit('ELF .symtab has unexpected entry size')
str_idx = sym_sec['sh_link']
strtab = self.section_data(str_idx)
shndx_ext: list[int] | None = None
for sec in self.sections:
if sec['sh_type'] == SHT_SYMTAB_SHNDX and sec['sh_link'] == sym_idx:
ext_data = self.section_data(sec['index'])
count = len(ext_data) // 4
shndx_ext = list(struct.unpack_from(f'<{count}I', ext_data, 0))
break
raw_sym = self.section_data(sym_idx)
count = sym_sec['sh_size'] // entsize
out: list[dict] = []
for i in range(count):
st_name, st_info, st_other, st_shndx, st_value, st_size = struct.unpack_from(
'<IBBHQQ', raw_sym, i * entsize
)
if st_shndx == SHN_XINDEX and shndx_ext is not None and i < len(shndx_ext):
st_shndx = 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')
out.append({
'name': name,
'st_type': st_info & 0xF,
'st_bind': st_info >> 4,
'st_other': st_other,
'st_shndx': st_shndx,
'st_value': st_value,
'st_size': st_size,
})
return out
def relocations(self, section_name: str) -> list[tuple[int, int, int, int]]:
"""Return list of (r_offset, r_sym, r_type, r_addend) for a .rela.* section."""
sec = self.sections[self.section_index(section_name)]
entsize = sec['sh_entsize'] or 24
if entsize < 24 or sec['sh_size'] % entsize != 0:
raise SystemExit(f'ELF {section_name} has unexpected entry size')
raw_rel = self.section_data(sec['index'])
count = sec['sh_size'] // entsize
out: list[tuple[int, int, int, int]] = []
for i in range(count):
r_offset, r_info, r_addend = struct.unpack_from('<QQq', raw_rel, i * entsize)
out.append((r_offset, r_info >> 32, r_info & 0xFFFFFFFF, r_addend))
return out