diff --git a/tests/offline/test_binary_extractors.py b/tests/offline/test_binary_extractors.py new file mode 100644 index 00000000..eaa039f7 --- /dev/null +++ b/tests/offline/test_binary_extractors.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""Offline tests for _elf64_reader and the 6 binary/workload extractor scripts.""" +import contextlib +import importlib.util +import io +import json +import os +from pathlib import Path +import struct +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[2] + + +def _load(name: str, rel: str): + spec = importlib.util.spec_from_file_location(name, ROOT / rel) + mod = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(mod) + return mod + + +class BinaryExtractorsTest(unittest.TestCase): + def test_elf64_reader_discovery_and_sha256_check_under_O(self): + reader = _load("_elf64_reader", "tools/_elf64_reader.py") + with tempfile.TemporaryDirectory() as tmp: + fake = Path(tmp) / "nv-kernel.o_binary" + fake.write_bytes(b"not-a-real-rm-object") + with mock.patch.dict(os.environ, {"NV_RS_RM_OBJECT": str(fake)}, clear=True): + self.assertEqual(reader.find_rm_object(), fake) + with self.assertRaisesRegex(SystemExit, "sha256 mismatch"): + reader.verify_rm_object_sha256(fake) + with self.assertRaisesRegex(SystemExit, "not a valid 64-bit"): + reader.Elf64Relocatable(b"bad") + + def test_all_binary_extractors_are_import_safe(self): + for rel in ( + "tools/extract_gv100_gr_netlist.py", + "tools/extract_mmu_callback_table.py", + "tools/gpu_extract_acr_packed.py", + "tools/gpu_extract_sec2_packed.py", + "tools/gpu_extract_lsf_signatures.py", + "tools/extract_rmapi_memory_workload.py", + ): + mod = _load(Path(rel).stem, rel) + self.assertTrue(callable(mod.main)) + + def test_rmapi_memory_workload_cli_and_check_under_O(self): + mod = _load("extract_rmapi_memory_workload", "tools/extract_rmapi_memory_workload.py") + with contextlib.redirect_stderr(io.StringIO()): + with self.assertRaises(SystemExit) as ctx: + mod.main(["--bogus-flag"]) + self.assertEqual(ctx.exception.code, 2) + + with tempfile.TemporaryDirectory() as tmp: + tmp_path = Path(tmp) + # Empty capture fails with clean SystemExit instead of IndexError. + empty_cap = tmp_path / "empty.jsonl" + empty_cap.write_text("", encoding="utf-8") + with self.assertRaisesRegex(SystemExit, "no RM device allocation"): + mod.main(["--input", str(empty_cap), "--check"]) + + # Valid minimal capture: alloc device (0x80) + subdevice (0x2080). + dev_after = struct.pack("<4I", 0x1111, 0x1111, 0x2222, 0x80).hex() + sub_after = struct.pack("<4I", 0x1111, 0x2222, 0x3333, 0x2080).hex() + cap = tmp_path / "cap.jsonl" + cap.write_text( + "\n".join([ + json.dumps({"device": "/dev/nvidiactl", "request": "0xc030462b", "before": dev_after, "after": dev_after, "params_before": "", "params_after": ""}), + json.dumps({"device": "/dev/nvidiactl", "request": "0xc030462b", "before": sub_after, "after": sub_after, "params_before": "", "params_after": ""}), + ]) + "\n", + encoding="utf-8", + ) + out_target = tmp_path / "workload.json" + out_target.write_text('{"stale": true}\n', encoding="utf-8") + with mock.patch.object(mod, "TARGET", out_target): + with self.assertRaisesRegex(SystemExit, "differs from the checked copy"): + mod.main(["--input", str(cap), "--check"]) + with contextlib.redirect_stdout(io.StringIO()): + mod.main(["--input", str(cap)]) + with contextlib.redirect_stdout(io.StringIO()): + mod.main(["--input", str(cap), "--check"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/_elf64_reader.py b/tools/_elf64_reader.py new file mode 100644 index 00000000..2c2c78f8 --- /dev/null +++ b/tools/_elf64_reader.py @@ -0,0 +1,196 @@ +"""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(' len(raw): + raise SystemExit('ELF section header 0 exceeds file size') + + sh0 = struct.unpack_from('= 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(' 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( + '> 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('> 32, r_info & 0xFFFFFFFF, r_addend)) + return out diff --git a/tools/extract_gv100_gr_netlist.py b/tools/extract_gv100_gr_netlist.py index b5e4b8f5..ad7bc083 100644 --- a/tools/extract_gv100_gr_netlist.py +++ b/tools/extract_gv100_gr_netlist.py @@ -1,19 +1,116 @@ #!/usr/bin/env python3 """Extract the actually selected580 GV100 GR netlist; no target execution.""" +import hashlib +import json from pathlib import Path -from elftools.elf.elffile import ELFFile -import hashlib,json,struct,zlib -R=Path(__file__).resolve().parents[1];P=Path('/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/nv-kernel.o_binary');SHA='5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b';assert hashlib.sha256(P.read_bytes()).hexdigest()==SHA -selection=json.loads((R/'reports/native-gr-hal-selection.json').read_text());assert any(m['offset']=='0x12b8' and m['symbol']=='_nv032830rm'for m in selection['cases'][0]['methods']) -with P.open('rb')as f: - e=ELFFile(f);raw=e.get_section_by_name('.rodata').data();ss=list(e.get_section_by_name('.symtab').iter_symbols());d=0x1148528-0x111d660;size,stored=struct.unpack_from('032830->descriptor01148528, decoded by independent zlib. Original033300 calls017879 to decode; original032983 consumes the count at4 and12-byte id/size/offset records from8. Region meanings beyond exact whole-file matches remain consumer-dependent. No authentication, hardware boot, Rust decoder parity or GR initialization proven by extraction.','policy_condition':'Original033300 normal-container branch, index3 and emptymanager slot. Physical runtime branch selection/authentication is not observed here.','artifact_sha256':SHA,'HAL_selection':'reports/native-gr-hal-selection.json','descriptor_mapped_address':'0x1148528','descriptor_file_offset_in_rodata':d,'stored_offset_in_rodata':offset,'decoded_size':size,'stored_bytes':stored,'descriptor_flags':flags,'header_word0':word,'region_count':count,'decoded_file':str(out/'gv100-netlist.bin'),'packed_file':str(out/'gv100-netlist.packed'),'decoded_sha256':hashlib.sha256(data).hexdigest(),'packed_sha256':hashlib.sha256(packed).hexdigest(),'records':records} -(R/'reports/gv100-gr-netlist.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps({'decoded_bytes':len(data),'region_count':count,'decoded_file':report['decoded_file']})) +import struct +import sys +import zlib + +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT / 'tools') not in sys.path: + sys.path.insert(0, str(ROOT / 'tools')) + +from _elf64_reader import ( + EXPECTED_RM_OBJECT_SHA256, + Elf64Relocatable, + find_rm_object, + verify_rm_object_sha256, +) + + +def main() -> None: + obj_path = find_rm_object() + sha = verify_rm_object_sha256(obj_path, EXPECTED_RM_OBJECT_SHA256) + + selection = json.loads((ROOT / 'reports/native-gr-hal-selection.json').read_text(encoding='utf-8')) + if not any(m['offset'] == '0x12b8' and m['symbol'] == '_nv032830rm' for m in selection['cases'][0]['methods']): + raise SystemExit('reports/native-gr-hal-selection.json does not confirm 0x12b8 -> _nv032830rm') + + elf = Elf64Relocatable.from_path(obj_path) + rodata_idx = elf.section_index('.rodata') + raw = elf.section_data(rodata_idx) + syms = elf.symbols() + desc_off = 0x1148528 - 0x111D660 + size, stored = struct.unpack_from(' len(raw): + raise SystemExit(f'packed netlist range [0x{offset:x}..0x{offset + stored:x}] out of .rodata bounds') + packed = raw[offset:offset + stored] + + decoder = zlib.decompressobj(-15) + data = decoder.decompress(packed, size + 1) + if not decoder.eof or len(data) != size: + raise SystemExit(f'netlist decompression failed: eof={decoder.eof} len={len(data)} expected={size}') + + word, count = struct.unpack_from(' len(data): + raise SystemExit(f'unexpected netlist header: count={count} len={len(data)}') + + records = [] + fw_dir = Path('/lib/firmware/nvidia/gv100/gr') + fw_files = sorted(fw_dir.glob('*.bin')) if fw_dir.is_dir() else [] + for i in range(count): + kind, length, start = struct.unpack_from(' len(data): + raise SystemExit(f'netlist record {i} out of bounds: {start}+{length} > {len(data)}') + blob = data[start:start + length] + matches = [str(fw) for fw in fw_files if blob == fw.read_bytes()] + records.append({ + 'id': kind, + 'bytes': length, + 'offset': start, + 'sha256': hashlib.sha256(blob).hexdigest(), + 'exact_whole_installed_file_matches': matches, + }) + + out = ROOT / 'analysis/gr-580' + out.mkdir(parents=True, exist_ok=True) + (out / 'gv100-netlist.packed').write_bytes(packed) + (out / 'gv100-netlist.bin').write_bytes(data) + + report = { + 'scope': ( + 'Selected GR12b8->032830->descriptor01148528, decoded by independent zlib. ' + 'Original033300 calls017879 to decode; original032983 consumes the count at4 ' + 'and12-byte id/size/offset records from8. Region meanings beyond exact whole-file ' + 'matches remain consumer-dependent. No authentication, hardware boot, Rust decoder ' + 'parity or GR initialization proven by extraction.' + ), + 'policy_condition': ( + 'Original033300 normal-container branch, index3 and emptymanager slot. ' + 'Physical runtime branch selection/authentication is not observed here.' + ), + 'artifact_sha256': sha, + 'HAL_selection': 'reports/native-gr-hal-selection.json', + 'descriptor_mapped_address': '0x1148528', + 'descriptor_file_offset_in_rodata': desc_off, + 'stored_offset_in_rodata': offset, + 'decoded_size': size, + 'stored_bytes': stored, + 'descriptor_flags': flags, + 'header_word0': word, + 'region_count': count, + 'decoded_file': str(out / 'gv100-netlist.bin'), + 'packed_file': str(out / 'gv100-netlist.packed'), + 'decoded_sha256': hashlib.sha256(data).hexdigest(), + 'packed_sha256': hashlib.sha256(packed).hexdigest(), + 'records': records, + } + report_path = ROOT / 'reports/gv100-gr-netlist.json' + report_path.parent.mkdir(parents=True, exist_ok=True) + report_path.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8') + print(json.dumps({'decoded_bytes': len(data), 'region_count': count, 'decoded_file': report['decoded_file']})) + + +if __name__ == '__main__': + main() diff --git a/tools/extract_mmu_callback_table.py b/tools/extract_mmu_callback_table.py index 3c906e77..3e4dfa85 100755 --- a/tools/extract_mmu_callback_table.py +++ b/tools/extract_mmu_callback_table.py @@ -1,16 +1,79 @@ #!/usr/bin/env python3 """Record original ELF relocations establishing gmmu-walk callback identity.""" -import hashlib,json +import json from pathlib import Path -from elftools.elf.elffile import ELFFile -R=Path(__file__).resolve().parents[1] -P=Path('/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/nv-kernel.o_binary') -with P.open('rb') as f: - e=ELFFile(f);syms=e.get_section_by_name('.symtab');names={s['st_value']:s.name for s in syms.iter_symbols() if s.name.startswith('_nv') and s['st_info']['type']=='STT_FUNC'};sec=e.get_section_by_name('.rela.rodata');table=[] - for x in sec.iter_relocations(): - offset=x['r_offset'] - if 0x4c5da80<=offset<0x4c5dab8: - sym=syms.get_symbol(x['r_info_sym']);assert e.get_section(sym['st_shndx']).name=='.text' - table.append({'offset':hex(offset),'text_addend':hex(x['r_addend']),'symbol':names[x['r_addend']]}) -assert [x['symbol'] for x in table]==['_nv013506rm','_nv013507rm','_nv013511rm','_nv013512rm','_nv013503rm','_nv013500rm'] -(R/'reports/mmu-callback-relocations.json').write_text(json.dumps({'artifact':str(P),'sha256':hashlib.sha256(P.read_bytes()).hexdigest(),'rodata_base':'0x4c5da80','callback_order':['LevelAlloc','LevelFree','UpdatePdb','UpdatePde','FillEntries','CopyEntries'],'relocations':table,'interpretation':'Callback order corroborated by exact-version g_gmmuWalkCallbacks definition and complete REA callback behavior'},indent=2)+'\n');print('Six actual ELF callback relocations verified') +import sys + +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT / 'tools') not in sys.path: + sys.path.insert(0, str(ROOT / 'tools')) + +from _elf64_reader import ( + EXPECTED_RM_OBJECT_SHA256, + STT_FUNC, + Elf64Relocatable, + find_rm_object, + verify_rm_object_sha256, +) + +EXPECTED_SYMBOLS = [ + '_nv013506rm', + '_nv013507rm', + '_nv013511rm', + '_nv013512rm', + '_nv013503rm', + '_nv013500rm', +] + + +def main() -> None: + obj_path = find_rm_object() + sha = verify_rm_object_sha256(obj_path, EXPECTED_RM_OBJECT_SHA256) + + elf = Elf64Relocatable.from_path(obj_path) + syms = elf.symbols() + names = { + s['st_value']: s['name'] + for s in syms + if s['name'].startswith('_nv') and s['st_type'] == STT_FUNC + } + table = [] + for r_offset, r_sym, _, r_addend in elf.relocations('.rela.rodata'): + if 0x4C5DA80 <= r_offset < 0x4C5DAB8: + sym = syms[r_sym] + sec_name = elf.section_name(sym['st_shndx']) + if sec_name != '.text': + raise SystemExit(f'unexpected callback relocation target section {sec_name!r} != .text') + if r_addend not in names: + raise SystemExit(f'no _nv* function symbol at .text+0x{r_addend:x}') + table.append({ + 'offset': hex(r_offset), + 'text_addend': hex(r_addend), + 'symbol': names[r_addend], + }) + observed = [x['symbol'] for x in table] + if observed != EXPECTED_SYMBOLS: + raise SystemExit(f'unexpected g_gmmuWalkCallbacks sequence: {observed} != {EXPECTED_SYMBOLS}') + + report_path = ROOT / 'reports/mmu-callback-relocations.json' + report_path.parent.mkdir(parents=True, exist_ok=True) + report_path.write_text( + json.dumps( + { + 'artifact': str(obj_path), + 'sha256': sha, + 'rodata_base': '0x4c5da80', + 'callback_order': ['LevelAlloc', 'LevelFree', 'UpdatePdb', 'UpdatePde', 'FillEntries', 'CopyEntries'], + 'relocations': table, + 'interpretation': 'Callback order corroborated by exact-version g_gmmuWalkCallbacks definition and complete REA callback behavior', + }, + indent=2, + ) + + '\n', + encoding='utf-8', + ) + print('Six actual ELF callback relocations verified') + + +if __name__ == '__main__': + main() diff --git a/tools/extract_rmapi_memory_workload.py b/tools/extract_rmapi_memory_workload.py index dcac936f..e067d4be 100644 --- a/tools/extract_rmapi_memory_workload.py +++ b/tools/extract_rmapi_memory_workload.py @@ -22,21 +22,42 @@ occur as whole 32-bit words in a request or reply. User addresses stay as captur checked-in JSON is what the oracle tool and the Rust replay test read; this script only regenerates it (`--check` compares). """ +import argparse import json -import struct -import sys +import os from pathlib import Path +import struct ROOT = Path(__file__).resolve().parents[1] -CAPTURE = Path("/home/geodd/nvidia-driver/analysis-580.178.04/reports/" - "cuda-compute-exact-allocation-ioctl-payloads.jsonl") +DEFAULT_ANALYSIS_ROOT = Path("/home/geodd/nvidia-driver/analysis-580.178.04") +CAPTURE_NAME = "cuda-compute-exact-allocation-ioctl-payloads.jsonl" TARGET = ROOT / "tools/rmapi_memory_workload.json" CLASSES = (0x90f1, 0x503c, 0x50a0, 0x40, 0x3e) CONTROLS = (0xd01, 0x503c0102, 0x503c0104, 0x503c0105) -def main(): - rows = [json.loads(line) for line in CAPTURE.read_text().splitlines()] +def find_capture(explicit: Path | None = None) -> Path: + if explicit is not None: + if not explicit.is_file(): + raise SystemExit(f"capture file not found: {explicit}") + return explicit + analysis = Path(os.environ.get("NV_RS_ANALYSIS_ROOT", str(DEFAULT_ANALYSIS_ROOT))) + candidate = analysis / "reports" / CAPTURE_NAME + if candidate.is_file(): + return candidate + raise SystemExit( + f"capture file not found at {candidate}; pass --input or set NV_RS_ANALYSIS_ROOT" + ) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--check", action="store_true", help="compare output against checked-in JSON") + parser.add_argument("--input", type=Path, default=None, help="path to ioctl payload capture JSONL") + args = parser.parse_args(argv) + + capture = find_capture(args.input) + rows = [json.loads(line) for line in capture.read_text(encoding="utf-8").splitlines() if line.strip()] rows = [row for row in rows if "nvidia-uvm" not in row["device"]] def number(row): @@ -51,10 +72,21 @@ def main(): if number(row) == 0x2b and words(row["after"])[3] == 0x80: devices.append(words(row["after"])[2]) client = words(row["after"])[0] + if not devices or client is None: + raise SystemExit(f"no RM device allocation (class 0x80) found in {capture}") device = devices[-1] - subdevice = next(words(row["after"])[2] for row in rows - if number(row) == 0x2b and words(row["after"])[3] == 0x2080 - and words(row["after"])[1] == device) + subdevice = next( + ( + words(row["after"])[2] + for row in rows + if number(row) == 0x2b + and words(row["after"])[3] == 0x2080 + and words(row["after"])[1] == device + ), + None, + ) + if subdevice is None: + raise SystemExit(f"no RM subdevice allocation (class 0x2080) for device 0x{device:x} in {capture}") rename = {client: 0xc1d00001, device: 0xcaf00000, subdevice: 0xcaf00001} def canonical(text): @@ -68,7 +100,7 @@ def main(): objects, operations = {device, subdevice}, [] for index, row in enumerate(rows): escape = number(row) - before, after = words(row["before"]), words(row["after"]) + after = words(row["after"]) kind = None if escape == 0x2b and after[3] in CLASSES and after[1] in objects: kind = "alloc" @@ -95,12 +127,14 @@ def main(): request=canonical(row["before"]), reply=canonical(row["after"]), params=canonical(row["params_before"]) if row["params_before"] else None, params_reply=canonical(row["params_after"]) if row["params_after"] else None)) - text = json.dumps(dict(source=CAPTURE.name, client=0xc1d00001, device=0xcaf00000, + text = json.dumps(dict(source=capture.name, client=0xc1d00001, device=0xcaf00000, subdevice=0xcaf00001, operations=operations), indent=1) + "\n" - if "--check" in sys.argv: - assert TARGET.read_text() == text, "workload extract differs from the checked copy" + if args.check: + if not TARGET.is_file() or TARGET.read_text(encoding="utf-8") != text: + raise SystemExit("workload extract differs from the checked copy") else: - TARGET.write_text(text) + TARGET.parent.mkdir(parents=True, exist_ok=True) + TARGET.write_text(text, encoding="utf-8") counts = {} for operation in operations: counts[operation["kind"]] = counts.get(operation["kind"], 0) + 1 diff --git a/tools/gpu_extract_acr_packed.py b/tools/gpu_extract_acr_packed.py index 41b686b2..096ad806 100644 --- a/tools/gpu_extract_acr_packed.py +++ b/tools/gpu_extract_acr_packed.py @@ -2,49 +2,159 @@ """Recover bounded selected original ACR packed bundle storage, CPU-only. Payloads are artifact evidence, not authenticated/ready firmware objects. """ +import hashlib +import json from pathlib import Path -import struct,json,hashlib,zlib -from elftools.elf.elffile import ELFFile -R=Path(__file__).resolve().parents[1];P=Path('/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/nv-kernel.o_binary');OUT=R/'analysis/acr-580';OUT.mkdir(parents=True,exist_ok=True) -with P.open('rb')as f: - e=ELFFile(f);ss=list(e.get_section_by_name('.symtab').iter_symbols());bases={e.get_section_index('.rodata'):0x0111d660,e.get_section_index('.data'):0x00f7e890,e.get_section_index('.bss'):0x05fd2180,e.get_section_index('.text'):0x0616f810};raw={i:e.get_section(i).data()for i in bases if e.get_section(i).name!='.bss'};rel={} - for i in raw: - section=e.get_section_by_name('.rela'+e.get_section(i).name) - if section: - for x in section.iter_relocations():rel[(i,x['r_offset'])]=x - def where(address): - for i,b in bases.items(): - if i in raw and b<=address0:objects.setdefault(bases[s['st_shndx']]+s['st_value'],[]).append((s.name,s['st_size'])) - records=[] - for bundle in [0x011430c8,0x01141350,0x01141058,0x01141ea0,0x01140830,0x011407a0]: - count=int.from_bytes(data(bundle,4),'little');assert count<128 - for index in range(count): - tag=int.from_bytes(data(bundle+8+index*16,4),'little');address=ptr(bundle+16+index*16) - header=data(address,24);size,unknown,_,flags,_=struct.unpack(' None: + obj_path = find_rm_object() + sha = verify_rm_object_sha256(obj_path, EXPECTED_RM_OBJECT_SHA256) + out = ROOT / 'analysis/acr-580' + out.mkdir(parents=True, exist_ok=True) + + elf = Elf64Relocatable.from_path(obj_path) + syms = elf.symbols() + bases = { + elf.section_index('.rodata'): 0x0111D660, + elf.section_index('.data'): 0x00F7E890, + elf.section_index('.bss'): 0x05FD2180, + elf.section_index('.text'): 0x0616F810, + } + raw = { + idx: elf.section_data(idx) + for idx in bases + if elf.section_name(idx) != '.bss' + } + rel = {} + for idx in raw: + rela_name = '.rela' + elf.section_name(idx) + if elf.has_section(rela_name): + for r_offset, r_sym, _r_type, r_addend in elf.relocations(rela_name): + rel[(idx, r_offset)] = (r_sym, r_addend) + + def where(address: int) -> tuple[int, int]: + for idx, base in bases.items(): + if idx in raw and base <= address < base + len(raw[idx]): + return idx, address - base + raise ValueError(hex(address)) + + def data(address: int, length: int) -> bytes: + idx, off = where(address) + if length < 0 or off + length > len(raw[idx]): + raise SystemExit(f'slice 0x{address:x}+{length} exceeds section bounds') + return raw[idx][off:off + length] + + def ptr(address: int) -> int: + idx, off = where(address) + entry = rel.get((idx, off)) + if entry is None: + return int.from_bytes(raw[idx][off:off + 8], 'little') + r_sym, r_addend = entry + sym = syms[r_sym] + return bases[sym['st_shndx']] + sym['st_value'] + r_addend + + objects: dict[int, list[tuple[str, int]]] = {} + for sym in syms: + if sym['st_shndx'] in bases and sym['st_type'] == STT_OBJECT and sym['st_size'] > 0: + objects.setdefault(bases[sym['st_shndx']] + sym['st_value'], []).append( + (sym['name'], sym['st_size']) + ) + + records = [] + for bundle in BUNDLES: + count = int.from_bytes(data(bundle, 4), 'little') + if count >= 128: + raise SystemExit(f'unexpected bundle count {count} at 0x{bundle:x}') + for index in range(count): + tag = int.from_bytes(data(bundle + 8 + index * 16, 4), 'little') + address = ptr(bundle + 16 + index * 16) + header = data(address, 24) + size, unknown, _, flags, _ = struct.unpack('0:objects.setdefault(bases[s['st_shndx']]+s['st_value'],[]).append((s.name,s['st_size'])) +import struct +import sys +import zlib - records=[] - for address in [0x01148cd8,0x01148e10,0x01149e90,0x01149410,0x0114a568]: - header=data(address,24);size,stored,_,flags,last=struct.unpack(' None: + obj_path = find_rm_object() + sha = verify_rm_object_sha256(obj_path, EXPECTED_RM_OBJECT_SHA256) + out = ROOT / 'analysis/lsf-580' + out.mkdir(parents=True, exist_ok=True) + + elf = Elf64Relocatable.from_path(obj_path) + syms = elf.symbols() + bases = { + elf.section_index('.rodata'): 0x0111D660, + elf.section_index('.data'): 0x00F7E890, + elf.section_index('.bss'): 0x05FD2180, + elf.section_index('.text'): 0x0616F810, + } + raw = { + idx: elf.section_data(idx) + for idx in bases + if elf.section_name(idx) != '.bss' + } + rel = {} + for idx in raw: + rela_name = '.rela' + elf.section_name(idx) + if elf.has_section(rela_name): + for r_offset, r_sym, _r_type, r_addend in elf.relocations(rela_name): + rel[(idx, r_offset)] = (r_sym, r_addend) + + def where(address: int) -> tuple[int, int]: + for idx, base in bases.items(): + if idx in raw and base <= address < base + len(raw[idx]): + return idx, address - base + raise ValueError(hex(address)) + + def data(address: int, length: int) -> bytes: + idx, off = where(address) + if length < 0 or off + length > len(raw[idx]): + raise SystemExit(f'slice 0x{address:x}+{length} exceeds section bounds') + return raw[idx][off:off + length] + + def ptr(address: int) -> int: + idx, off = where(address) + entry = rel.get((idx, off)) + if entry is None: + return int.from_bytes(raw[idx][off:off + 8], 'little') + r_sym, r_addend = entry + sym = syms[r_sym] + return bases[sym['st_shndx']] + sym['st_value'] + r_addend + + records = [] + for address in DESCRIPTORS: + header = data(address, 24) + size, stored, _, flags, last = struct.unpack('0:objects.setdefault(bases[s['st_shndx']]+s['st_value'],[]).append((s.name,s['st_size'])) - records=[] - for bundle in [0x011401d8]: - count=int.from_bytes(data(bundle,4),'little');assert count<128 - for index in range(count): - tag=int.from_bytes(data(bundle+8+index*16,4),'little');address=ptr(bundle+16+index*16) - header=data(address,24);size,unknown,_,flags,_=struct.unpack(' None: + obj_path = find_rm_object() + sha = verify_rm_object_sha256(obj_path, EXPECTED_RM_OBJECT_SHA256) + out = ROOT / 'analysis/sec2-580' + out.mkdir(parents=True, exist_ok=True) + + elf = Elf64Relocatable.from_path(obj_path) + syms = elf.symbols() + bases = { + elf.section_index('.rodata'): 0x0111D660, + elf.section_index('.data'): 0x00F7E890, + elf.section_index('.bss'): 0x05FD2180, + elf.section_index('.text'): 0x0616F810, + } + raw = { + idx: elf.section_data(idx) + for idx in bases + if elf.section_name(idx) != '.bss' + } + rel = {} + for idx in raw: + rela_name = '.rela' + elf.section_name(idx) + if elf.has_section(rela_name): + for r_offset, r_sym, _r_type, r_addend in elf.relocations(rela_name): + rel[(idx, r_offset)] = (r_sym, r_addend) + + def where(address: int) -> tuple[int, int]: + for idx, base in bases.items(): + if idx in raw and base <= address < base + len(raw[idx]): + return idx, address - base + raise ValueError(hex(address)) + + def data(address: int, length: int) -> bytes: + idx, off = where(address) + if length < 0 or off + length > len(raw[idx]): + raise SystemExit(f'slice 0x{address:x}+{length} exceeds section bounds') + return raw[idx][off:off + length] + + def ptr(address: int) -> int: + idx, off = where(address) + entry = rel.get((idx, off)) + if entry is None: + return int.from_bytes(raw[idx][off:off + 8], 'little') + r_sym, r_addend = entry + sym = syms[r_sym] + return bases[sym['st_shndx']] + sym['st_value'] + r_addend + + objects: dict[int, list[tuple[str, int]]] = {} + for sym in syms: + if sym['st_shndx'] in bases and sym['st_type'] == STT_OBJECT and sym['st_size'] > 0: + objects.setdefault(bases[sym['st_shndx']] + sym['st_value'], []).append( + (sym['name'], sym['st_size']) + ) + + records = [] + for bundle in BUNDLES: + count = int.from_bytes(data(bundle, 4), 'little') + if count >= 128: + raise SystemExit(f'unexpected bundle count {count} at 0x{bundle:x}') + for index in range(count): + tag = int.from_bytes(data(bundle + 8 + index * 16, 4), 'little') + address = ptr(bundle + 16 + index * 16) + header = data(address, 24) + size, unknown, _, flags, _ = struct.unpack('