mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
Merge pull request #288 from morebrackets/fix/tools-binary-extractors-portability-and-stdlib-elf
tools: add stdlib ELF64 reader and harden 580.178.04 binary and workload extractors
This commit is contained in:
88
tests/offline/test_binary_extractors.py
Normal file
88
tests/offline/test_binary_extractors.py
Normal file
@ -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()
|
||||
196
tools/_elf64_reader.py
Normal file
196
tools/_elf64_reader.py
Normal file
@ -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('<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
|
||||
@ -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('<II',raw,d);flags=struct.unpack_from('<I',raw,d+16)[0]
|
||||
rels=[r for r in e.get_section_by_name('.rela.rodata').iter_relocations()if r['r_offset']==d+8];assert len(rels)==1;rel=rels[0];symbol=ss[rel['r_info_sym']];assert symbol['st_shndx']==e.get_section_index('.rodata');offset=symbol['st_value']+rel['r_addend'];packed=raw[offset:offset+stored];decoder=zlib.decompressobj(-15);data=decoder.decompress(packed,size+1);assert decoder.eof and len(data)==size
|
||||
word,count=struct.unpack_from('<II',data);assert count==38 and 8+count*12<=len(data);records=[]
|
||||
for i in range(count):
|
||||
kind,length,start=struct.unpack_from('<III',data,8+i*12);assert start+length<=len(data);blob=data[start:start+length];matches=[]
|
||||
for file in Path('/lib/firmware/nvidia/gv100/gr').glob('*.bin'):
|
||||
if blob==file.read_bytes():matches.append(str(file))
|
||||
records.append({'id':kind,'bytes':length,'offset':start,'sha256':hashlib.sha256(blob).hexdigest(),'exact_whole_installed_file_matches':matches})
|
||||
out=R/'analysis/gr-580';out.mkdir(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':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('<II', raw, desc_off)
|
||||
flags, = struct.unpack_from('<I', raw, desc_off + 16)
|
||||
|
||||
rels = [r for r in elf.relocations('.rela.rodata') if r[0] == desc_off + 8]
|
||||
if len(rels) != 1:
|
||||
raise SystemExit(f'expected 1 relocation at .rodata+0x{desc_off + 8:x}, found {len(rels)}')
|
||||
_, r_sym, _, r_addend = rels[0]
|
||||
symbol = syms[r_sym]
|
||||
if symbol['st_shndx'] != rodata_idx:
|
||||
raise SystemExit(f'unexpected relocation section index {symbol["st_shndx"]} != {rodata_idx}')
|
||||
offset = symbol['st_value'] + r_addend
|
||||
if offset < 0 or offset + stored > 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('<II', data)
|
||||
if count != 38 or 8 + count * 12 > 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('<III', data, 8 + i * 12)
|
||||
if start + length > 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()
|
||||
|
||||
@ -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()
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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<=address<b+len(raw[i]):return i,address-b
|
||||
raise ValueError(hex(address))
|
||||
def data(address,length):i,o=where(address);assert o+length<=len(raw[i]);return raw[i][o:o+length]
|
||||
def ptr(address):
|
||||
i,o=where(address);x=rel.get((i,o))
|
||||
if x is None:return int.from_bytes(raw[i][o:o+8],'little')
|
||||
s=ss[x['r_info_sym']];return bases[s['st_shndx']]+s['st_value']+x['r_addend']
|
||||
objects={}
|
||||
for s in ss:
|
||||
if s['st_shndx']in bases and s['st_info']['type']=='STT_OBJECT' and s['st_size']>0: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('<IIQII',header);storage=ptr(address+8);candidates=objects.get(storage,[])
|
||||
row={'bundle':hex(bundle),'tag':hex(tag),'descriptor':hex(address),'decoded_size':size,'word4':unknown,'flags':flags,'storage':hex(storage),'storage_symbols':candidates}
|
||||
if not candidates:
|
||||
candidates=[(name,base,length)for base,items in objects.items()for name,length in items if base<=storage<base+length]
|
||||
row['enclosing_storage_symbols']=candidates
|
||||
# Descriptor word4 is the stored byte count; section bounds checked by data().
|
||||
stored_size=unknown if flags&1 else size
|
||||
assert 0<stored_size<16*1024*1024,row
|
||||
compressed=data(storage,stored_size)
|
||||
if flags&1:
|
||||
decoder=zlib.decompressobj(-15);decoded=decoder.decompress(compressed)+decoder.flush();assert decoder.eof
|
||||
consumed=len(compressed)-len(decoder.unused_data)
|
||||
else:decoded=compressed[:size];consumed=size
|
||||
assert len(decoded)==size,(row,len(decoded))
|
||||
name=f'{bundle:x}-{tag:x}';(OUT/(name+'.packed')).write_bytes(compressed);(OUT/(name+'.decoded')).write_bytes(decoded)
|
||||
row.update(stored_bytes=len(compressed),consumed=consumed,decoded_sha256=hashlib.sha256(decoded).hexdigest(),storage_sha256=hashlib.sha256(compressed).hexdigest(),packed_file=str(OUT/(name+'.packed')),decoded_file=str(OUT/(name+'.decoded')),head=decoded[:32].hex())
|
||||
records.append(row)
|
||||
(R/'reports/gpu-acr-packed-inventory.json').write_text(json.dumps({'artifact_sha256':hashlib.sha256(P.read_bytes()).hexdigest(),'decoder_reference':'Python zlib raw DEFLATE; not original decoder execution','records':records,'physical_gpu_access':False},indent=2)+'\n')
|
||||
print(json.dumps({'records':len(records),'decoded_bytes':sum(x['decoded_size']for x in records)}))
|
||||
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,
|
||||
STT_OBJECT,
|
||||
Elf64Relocatable,
|
||||
find_rm_object,
|
||||
verify_rm_object_sha256,
|
||||
)
|
||||
|
||||
BUNDLES = [0x011430C8, 0x01141350, 0x01141058, 0x01141EA0, 0x01140830, 0x011407A0]
|
||||
|
||||
|
||||
def main() -> 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('<IIQII', header)
|
||||
storage = ptr(address + 8)
|
||||
candidates = objects.get(storage, [])
|
||||
row = {
|
||||
'bundle': hex(bundle),
|
||||
'tag': hex(tag),
|
||||
'descriptor': hex(address),
|
||||
'decoded_size': size,
|
||||
'word4': unknown,
|
||||
'flags': flags,
|
||||
'storage': hex(storage),
|
||||
'storage_symbols': candidates,
|
||||
}
|
||||
if not candidates:
|
||||
enclosing = [
|
||||
(name, base, length)
|
||||
for base, items in objects.items()
|
||||
for name, length in items
|
||||
if base <= storage < base + length
|
||||
]
|
||||
row['enclosing_storage_symbols'] = enclosing
|
||||
# Descriptor word4 is the stored byte count; section bounds checked by data().
|
||||
stored_size = unknown if flags & 1 else size
|
||||
if not (0 < stored_size < 16 * 1024 * 1024):
|
||||
raise SystemExit(f'invalid stored_size {stored_size} for {row}')
|
||||
compressed = data(storage, stored_size)
|
||||
if flags & 1:
|
||||
decoder = zlib.decompressobj(-15)
|
||||
decoded = decoder.decompress(compressed) + decoder.flush()
|
||||
if not decoder.eof:
|
||||
raise SystemExit(f'incomplete DEFLATE stream for {row}')
|
||||
consumed = len(compressed) - len(decoder.unused_data)
|
||||
else:
|
||||
decoded = compressed[:size]
|
||||
consumed = size
|
||||
if len(decoded) != size:
|
||||
raise SystemExit(f'decoded size mismatch ({len(decoded)} != {size}) for {row}')
|
||||
name = f'{bundle:x}-{tag:x}'
|
||||
(out / (name + '.packed')).write_bytes(compressed)
|
||||
(out / (name + '.decoded')).write_bytes(decoded)
|
||||
row.update(
|
||||
stored_bytes=len(compressed),
|
||||
consumed=consumed,
|
||||
decoded_sha256=hashlib.sha256(decoded).hexdigest(),
|
||||
storage_sha256=hashlib.sha256(compressed).hexdigest(),
|
||||
packed_file=str(out / (name + '.packed')),
|
||||
decoded_file=str(out / (name + '.decoded')),
|
||||
head=decoded[:32].hex(),
|
||||
)
|
||||
records.append(row)
|
||||
|
||||
report_path = ROOT / 'reports/gpu-acr-packed-inventory.json'
|
||||
report_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
report_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
'artifact_sha256': sha,
|
||||
'decoder_reference': 'Python zlib raw DEFLATE; not original decoder execution',
|
||||
'records': records,
|
||||
'physical_gpu_access': False,
|
||||
},
|
||||
indent=2,
|
||||
)
|
||||
+ '\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
print(json.dumps({'records': len(records), 'decoded_bytes': sum(x['decoded_size'] for x in records)}))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
@ -1,38 +1,124 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Recover bounded selected original ACR packed bundle storage, CPU-only.
|
||||
"""Recover bounded selected original LSF signature descriptors, 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/lsf-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<=address<b+len(raw[i]):return i,address-b
|
||||
raise ValueError(hex(address))
|
||||
def data(address,length):i,o=where(address);assert o+length<=len(raw[i]);return raw[i][o:o+length]
|
||||
def ptr(address):
|
||||
i,o=where(address);x=rel.get((i,o))
|
||||
if x is None:return int.from_bytes(raw[i][o:o+8],'little')
|
||||
s=ss[x['r_info_sym']];return bases[s['st_shndx']]+s['st_value']+x['r_addend']
|
||||
objects={}
|
||||
for s in ss:
|
||||
if s['st_shndx']in bases and s['st_info']['type']=='STT_OBJECT' and s['st_size']>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('<IIQII',header);storage=ptr(address+8);compressed=data(storage,stored if flags&1 else size)
|
||||
if flags&1:
|
||||
decoder=zlib.decompressobj(-15);decoded=decoder.decompress(compressed)+decoder.flush();assert decoder.eof
|
||||
else:decoded=compressed[:size]
|
||||
assert len(decoded)==size
|
||||
name=f'{address:x}';(OUT/(name+'.packed')).write_bytes(compressed);(OUT/(name+'.decoded')).write_bytes(decoded)
|
||||
records.append({'descriptor':hex(address),'decoded_size':size,'stored_bytes':stored,'flags':flags,'word20':last,'storage':hex(storage),'decoded_sha256':hashlib.sha256(decoded).hexdigest(),'packed_file':str(OUT/(name+'.packed')),'decoded_file':str(OUT/(name+'.decoded')),'head':decoded[:96].hex()})
|
||||
(R/'reports/gpu-lsf-signature-descriptors.json').write_text(json.dumps({'artifact_sha256':hashlib.sha256(P.read_bytes()).hexdigest(),'records':records,'runtime_id_assignment_proven':False,'physical_gpu_access':False},indent=2)+'\n')
|
||||
for row in records:print(row)
|
||||
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,
|
||||
)
|
||||
|
||||
DESCRIPTORS = [0x01148CD8, 0x01148E10, 0x01149E90, 0x01149410, 0x0114A568]
|
||||
|
||||
|
||||
def main() -> 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('<IIQII', header)
|
||||
storage = ptr(address + 8)
|
||||
compressed = data(storage, stored if flags & 1 else size)
|
||||
if flags & 1:
|
||||
decoder = zlib.decompressobj(-15)
|
||||
decoded = decoder.decompress(compressed) + decoder.flush()
|
||||
if not decoder.eof:
|
||||
raise SystemExit(f'incomplete DEFLATE stream at 0x{address:x}')
|
||||
else:
|
||||
decoded = compressed[:size]
|
||||
if len(decoded) != size:
|
||||
raise SystemExit(f'decoded size mismatch at 0x{address:x}: {len(decoded)} != {size}')
|
||||
name = f'{address:x}'
|
||||
(out / (name + '.packed')).write_bytes(compressed)
|
||||
(out / (name + '.decoded')).write_bytes(decoded)
|
||||
records.append({
|
||||
'descriptor': hex(address),
|
||||
'decoded_size': size,
|
||||
'stored_bytes': stored,
|
||||
'flags': flags,
|
||||
'word20': last,
|
||||
'storage': hex(storage),
|
||||
'decoded_sha256': hashlib.sha256(decoded).hexdigest(),
|
||||
'packed_file': str(out / (name + '.packed')),
|
||||
'decoded_file': str(out / (name + '.decoded')),
|
||||
'head': decoded[:96].hex(),
|
||||
})
|
||||
|
||||
report_path = ROOT / 'reports/gpu-lsf-signature-descriptors.json'
|
||||
report_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
report_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
'artifact_sha256': sha,
|
||||
'records': records,
|
||||
'runtime_id_assignment_proven': False,
|
||||
'physical_gpu_access': False,
|
||||
},
|
||||
indent=2,
|
||||
)
|
||||
+ '\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
for row in records:
|
||||
print(row)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
@ -1,50 +1,159 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Recover bounded selected original ACR packed bundle storage, CPU-only.
|
||||
"""Recover bounded selected original SEC2 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/sec2-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<=address<b+len(raw[i]):return i,address-b
|
||||
raise ValueError(hex(address))
|
||||
def data(address,length):i,o=where(address);assert o+length<=len(raw[i]);return raw[i][o:o+length]
|
||||
def ptr(address):
|
||||
i,o=where(address);x=rel.get((i,o))
|
||||
if x is None:return int.from_bytes(raw[i][o:o+8],'little')
|
||||
s=ss[x['r_info_sym']];return bases[s['st_shndx']]+s['st_value']+x['r_addend']
|
||||
objects={}
|
||||
for s in ss:
|
||||
if s['st_shndx']in bases and s['st_info']['type']=='STT_OBJECT' and s['st_size']>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('<IIQII',header);storage=ptr(address+8);candidates=objects.get(storage,[])
|
||||
row={'bundle':hex(bundle),'tag':hex(tag),'descriptor':hex(address),'decoded_size':size,'word4':unknown,'flags':flags,'storage':hex(storage),'storage_symbols':candidates}
|
||||
if not candidates:
|
||||
candidates=[(name,base,length)for base,items in objects.items()for name,length in items if base<=storage<base+length]
|
||||
row['enclosing_storage_symbols']=candidates
|
||||
# Descriptor word4 is the stored byte count; section bounds checked by data().
|
||||
stored_size=unknown if flags&1 else size
|
||||
assert 0<stored_size<16*1024*1024,row
|
||||
compressed=data(storage,stored_size)
|
||||
if flags&1:
|
||||
decoder=zlib.decompressobj(-15);decoded=decoder.decompress(compressed)+decoder.flush();assert decoder.eof
|
||||
consumed=len(compressed)-len(decoder.unused_data)
|
||||
else:decoded=compressed[:size];consumed=size
|
||||
assert len(decoded)==size,(row,len(decoded))
|
||||
name=f'{bundle:x}-{tag:x}';(OUT/(name+'.packed')).write_bytes(compressed);(OUT/(name+'.decoded')).write_bytes(decoded)
|
||||
row.update(stored_bytes=len(compressed),consumed=consumed,decoded_sha256=hashlib.sha256(decoded).hexdigest(),storage_sha256=hashlib.sha256(compressed).hexdigest(),packed_file=str(OUT/(name+'.packed')),decoded_file=str(OUT/(name+'.decoded')),head=decoded[:32].hex())
|
||||
records.append(row)
|
||||
(R/'reports/gpu-sec2-packed-inventory.json').write_text(json.dumps({'artifact_sha256':hashlib.sha256(P.read_bytes()).hexdigest(),'decoder_reference':'Python zlib raw DEFLATE; not original decoder execution','records':records,'physical_gpu_access':False},indent=2)+'\n')
|
||||
print(json.dumps({'records':len(records),'decoded_bytes':sum(x['decoded_size']for x in records)}))
|
||||
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,
|
||||
STT_OBJECT,
|
||||
Elf64Relocatable,
|
||||
find_rm_object,
|
||||
verify_rm_object_sha256,
|
||||
)
|
||||
|
||||
BUNDLES = [0x011401D8]
|
||||
|
||||
|
||||
def main() -> 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('<IIQII', header)
|
||||
storage = ptr(address + 8)
|
||||
candidates = objects.get(storage, [])
|
||||
row = {
|
||||
'bundle': hex(bundle),
|
||||
'tag': hex(tag),
|
||||
'descriptor': hex(address),
|
||||
'decoded_size': size,
|
||||
'word4': unknown,
|
||||
'flags': flags,
|
||||
'storage': hex(storage),
|
||||
'storage_symbols': candidates,
|
||||
}
|
||||
if not candidates:
|
||||
enclosing = [
|
||||
(name, base, length)
|
||||
for base, items in objects.items()
|
||||
for name, length in items
|
||||
if base <= storage < base + length
|
||||
]
|
||||
row['enclosing_storage_symbols'] = enclosing
|
||||
stored_size = unknown if flags & 1 else size
|
||||
if not (0 < stored_size < 16 * 1024 * 1024):
|
||||
raise SystemExit(f'invalid stored_size {stored_size} for {row}')
|
||||
compressed = data(storage, stored_size)
|
||||
if flags & 1:
|
||||
decoder = zlib.decompressobj(-15)
|
||||
decoded = decoder.decompress(compressed) + decoder.flush()
|
||||
if not decoder.eof:
|
||||
raise SystemExit(f'incomplete DEFLATE stream for {row}')
|
||||
consumed = len(compressed) - len(decoder.unused_data)
|
||||
else:
|
||||
decoded = compressed[:size]
|
||||
consumed = size
|
||||
if len(decoded) != size:
|
||||
raise SystemExit(f'decoded size mismatch ({len(decoded)} != {size}) for {row}')
|
||||
name = f'{bundle:x}-{tag:x}'
|
||||
(out / (name + '.packed')).write_bytes(compressed)
|
||||
(out / (name + '.decoded')).write_bytes(decoded)
|
||||
row.update(
|
||||
stored_bytes=len(compressed),
|
||||
consumed=consumed,
|
||||
decoded_sha256=hashlib.sha256(decoded).hexdigest(),
|
||||
storage_sha256=hashlib.sha256(compressed).hexdigest(),
|
||||
packed_file=str(out / (name + '.packed')),
|
||||
decoded_file=str(out / (name + '.decoded')),
|
||||
head=decoded[:32].hex(),
|
||||
)
|
||||
records.append(row)
|
||||
|
||||
report_path = ROOT / 'reports/gpu-sec2-packed-inventory.json'
|
||||
report_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
report_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
'artifact_sha256': sha,
|
||||
'decoder_reference': 'Python zlib raw DEFLATE; not original decoder execution',
|
||||
'records': records,
|
||||
'physical_gpu_access': False,
|
||||
},
|
||||
indent=2,
|
||||
)
|
||||
+ '\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
print(json.dumps({'records': len(records), 'decoded_bytes': sum(x['decoded_size'] for x in records)}))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user