mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
Merge pull request #244 from morebrackets/fix/extract-gsp-boot-ucode-and-ada-docs
fix(tools,docs): harden GSP boot ucode extractor and record RTX 4090 silicon parity (#236)
This commit is contained in:
@ -19,7 +19,7 @@ Comparison of all **43 discrete GPU chip tuples** in NVIDIA **580.178.04** (`src
|
||||
| **Turing** | `0x16` | TU102, TU104, TU106, TU116, TU117 (Tesla T4, RTX 2060–2080 Ti, GTX 1650–1660 Ti) | GSP-RM (`gsp_tu10x.bin`) | V2 | Supported | **GSP-RM loader + HALs wired & Unicorn-verified offline** *(untested on physical silicon)* |
|
||||
| **Ampere** | `0x17` | GA100 (`gsp_tu10x.bin`), GA102–GA107 (`gsp_ga10x.bin`) (A100, A10/A30/A40, RTX 3050–3090 Ti) | GSP-RM | V2 | Supported | **GSP-RM loader + HALs wired & Unicorn-verified offline** *(untested on physical silicon)* |
|
||||
| **Hopper** | `0x18` | GH100 (H100, H200) | GSP-RM (`gsp_ga10x.bin`) | V3 | Supported | **GSP-RM loader + MMU V3 + HALs wired & Unicorn-verified offline** *(untested on physical silicon)* |
|
||||
| **Ada Lovelace** | `0x19` | AD102–AD107 (L4, L40/L40S, RTX 4060–4090, RTX 6000 Ada) | GSP-RM (`gsp_ga10x.bin`) | V2 | Supported | **GSP-RM loader + HALs wired & Unicorn-verified offline** *(untested on physical silicon)* |
|
||||
| **Ada Lovelace** | `0x19` | AD102–AD107 (L4, L40/L40S, RTX 4060–4090, RTX 6000 Ada) | GSP-RM (`gsp_ga10x.bin`) | V2 | Supported | **Community-reported `[O]` on RTX 4090 (AD102, [issue #236](https://github.com/QuixiAI/nvdriver/issues/236) / [logs](https://github.com/QuixiAI/nvdriver/issues/236#issuecomment-7347513418); not maintainer-verified)** — `nvidia-smi` + `37/37` CUDA parity checks (`25/25` bit-identical digests vs stock) with `ga10x_gsp=1`, manual prerequisite: Resizable BAR / BAR1 >= 512 MiB (`install.sh` does not configure this yet), and AD102 boot ucode extracted from the 580.x `open-gpu-kernel-modules` `kernel-open/nvidia/nv-kernel.o_binary` (not the proprietary `kernel/` object) |
|
||||
| **Blackwell 1** | `0x1a` | GB100, GB102, GB10B (B100, B200, GB200) | GSP-RM (`gsp_ga10x.bin`) | V3 | Supported | **GSP-RM loader + MMU V3 + HALs wired & Unicorn-verified offline** *(untested on physical silicon)* |
|
||||
| **Blackwell 2** | `0x1b` | GB202, GB203, GB205, GB206, GB207, GB20B (RTX 5070–5090, RTX PRO Blackwell) | GSP-RM (`620.70.06` MCTP/NVDM default, `580` compat) | V3 | Supported | **GSP-RM 620.70.06 loader + MMU V3 + HALs wired & verified offline** *(untested on physical silicon)* |
|
||||
| **Rubin** | `0x1c` | GR100 | GSP-RM (`620.70.06` MCTP/NVDM) | V3 | Supported (620.x) | **Arch profile + GSP-RM 620.70.06 wired & verified offline** *(untested on physical silicon)* |
|
||||
|
||||
300
tests/offline/test_extract_gsp_boot_ucode.py
Normal file
300
tests/offline/test_extract_gsp_boot_ucode.py
Normal file
@ -0,0 +1,300 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline unit tests for tools/extract_gsp_boot_ucode.py."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import io
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
import zlib
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / "tools"))
|
||||
|
||||
import extract_gsp_boot_ucode as extractor # noqa: E402
|
||||
|
||||
|
||||
def _raw_deflate(payload: bytes) -> bytes:
|
||||
comp = zlib.compressobj(wbits=-zlib.MAX_WBITS)
|
||||
return comp.compress(payload) + comp.flush()
|
||||
|
||||
|
||||
def _make_elf64(
|
||||
rodata_entries: dict[str, bytes],
|
||||
*,
|
||||
use_xindex: bool = False,
|
||||
corrupt_sym_size: tuple[str, int] | None = None,
|
||||
) -> bytes:
|
||||
"""Build a minimal little-endian ELF64 relocatable object with .rodata/.symtab/.strtab/.shstrtab."""
|
||||
rodata = bytearray()
|
||||
sym_specs: list[tuple[str, int, int]] = []
|
||||
for name, payload in rodata_entries.items():
|
||||
off = len(rodata)
|
||||
rodata.extend(payload)
|
||||
size = corrupt_sym_size[1] if corrupt_sym_size and corrupt_sym_size[0] == name else len(payload)
|
||||
sym_specs.append((name, off, size))
|
||||
|
||||
strtab = bytearray(b"\x00")
|
||||
symtab = bytearray(24) # STN_UNDEF
|
||||
shndx_entries = [0]
|
||||
|
||||
rodata_shndx = 1
|
||||
for name, off, size in sym_specs:
|
||||
name_off = len(strtab)
|
||||
strtab.extend(name.encode("ascii") + b"\x00")
|
||||
st_shndx = extractor.SHN_XINDEX if use_xindex else rodata_shndx
|
||||
symtab.extend(struct.pack("<IBBHQQ", name_off, 0, 0, st_shndx, off, size))
|
||||
shndx_entries.append(rodata_shndx)
|
||||
|
||||
shstrtab = bytearray(b"\x00")
|
||||
|
||||
def add_shname(s: str) -> int:
|
||||
pos = len(shstrtab)
|
||||
shstrtab.extend(s.encode("ascii") + b"\x00")
|
||||
return pos
|
||||
|
||||
sh_rodata_name = add_shname(".rodata")
|
||||
sh_symtab_name = add_shname(".symtab")
|
||||
sh_strtab_name = add_shname(".strtab")
|
||||
sh_shstrtab_name = add_shname(".shstrtab")
|
||||
sh_shndx_name = add_shname(".symtab_shndx") if use_xindex else 0
|
||||
|
||||
shndx_bytes = b"".join(struct.pack("<I", idx) for idx in shndx_entries) if use_xindex else b""
|
||||
|
||||
body = bytearray(b"\x00" * 64) # ELF header placeholder
|
||||
rodata_off = len(body)
|
||||
body.extend(rodata)
|
||||
symtab_off = len(body)
|
||||
body.extend(symtab)
|
||||
strtab_off = len(body)
|
||||
body.extend(strtab)
|
||||
shstrtab_off = len(body)
|
||||
body.extend(shstrtab)
|
||||
shndx_off = len(body)
|
||||
if use_xindex:
|
||||
body.extend(shndx_bytes)
|
||||
|
||||
shoff = len(body)
|
||||
shnum = 6 if use_xindex else 5
|
||||
shstrndx = 4
|
||||
|
||||
def pack_shdr(name: int, stype: int, off: int, size: int, link: int = 0) -> bytes:
|
||||
return struct.pack("<IIQQQQIIQQ", name, stype, 0, 0, off, size, link, 0, 1, 0)
|
||||
|
||||
shdr0_size = shnum if use_xindex else 0
|
||||
shdr0_link = shstrndx if use_xindex else 0
|
||||
shdrs = [
|
||||
pack_shdr(0, 0, 0, shdr0_size, shdr0_link),
|
||||
pack_shdr(sh_rodata_name, 1, rodata_off, len(rodata)),
|
||||
pack_shdr(sh_symtab_name, extractor.SHT_SYMTAB, symtab_off, len(symtab), link=3),
|
||||
pack_shdr(sh_strtab_name, 3, strtab_off, len(strtab)),
|
||||
pack_shdr(sh_shstrtab_name, 3, shstrtab_off, len(shstrtab)),
|
||||
]
|
||||
if use_xindex:
|
||||
shdrs.append(
|
||||
pack_shdr(sh_shndx_name, extractor.SHT_SYMTAB_SHNDX, shndx_off, len(shndx_bytes), link=2)
|
||||
)
|
||||
for shdr in shdrs:
|
||||
body.extend(shdr)
|
||||
|
||||
e_shnum = 0 if use_xindex else shnum
|
||||
e_shstrndx = extractor.SHN_XINDEX if use_xindex else shstrndx
|
||||
ehdr = struct.pack(
|
||||
"<16sHHIQQQIHHHHHH",
|
||||
b"\x7fELF\x02\x01\x01" + b"\x00" * 9,
|
||||
1, # ET_REL
|
||||
62, # EM_X86_64
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
shoff,
|
||||
0,
|
||||
64,
|
||||
0,
|
||||
0,
|
||||
64,
|
||||
e_shnum,
|
||||
e_shstrndx,
|
||||
)
|
||||
body[:64] = ehdr
|
||||
return bytes(body)
|
||||
|
||||
|
||||
def _add_hs_entries(entries: dict[str, bytes], prefix: str, num_sigs: int = 1) -> None:
|
||||
entries[f"{prefix}_BINDATA_LABEL_NUM_SIGS_data"] = struct.pack("<I", num_sigs)
|
||||
entries[f"{prefix}_BINDATA_LABEL_SIG_PROD_data"] = b"\xaa" * (num_sigs * 384)
|
||||
entries[f"{prefix}_BINDATA_LABEL_PATCH_LOC_data"] = struct.pack("<I", 0x10)
|
||||
entries[f"{prefix}_BINDATA_LABEL_PATCH_SIG_data"] = struct.pack("<I", 0x20)
|
||||
entries[f"{prefix}_BINDATA_LABEL_PATCH_META_data"] = b"\x11" * 12
|
||||
entries[f"{prefix}_BINDATA_LABEL_HEADER_PROD_data"] = gzip.compress(b"\x22" * 36)
|
||||
entries[f"{prefix}_BINDATA_LABEL_IMAGE_PROD_data"] = _raw_deflate(b"\x33" * 256)
|
||||
|
||||
|
||||
def _make_full_chip_entries(chips: list[str]) -> dict[str, bytes]:
|
||||
entries: dict[str, bytes] = {}
|
||||
for chip in chips:
|
||||
spec = extractor.CHIPS[chip]
|
||||
bl = spec["bootloader"]
|
||||
entries[f"{bl}_BINDATA_LABEL_UCODE_DESC_PROD_data"] = gzip.compress(b"\x04" * 44)
|
||||
entries[f"{bl}_BINDATA_LABEL_UCODE_IMAGE_PROD_data"] = _raw_deflate(b"\x55" * 512)
|
||||
_add_hs_entries(entries, spec["booter_load"], num_sigs=2)
|
||||
_add_hs_entries(entries, spec["booter_unload"], num_sigs=1)
|
||||
if "scrubber" in spec:
|
||||
_add_hs_entries(entries, spec["scrubber"], num_sigs=1)
|
||||
return entries
|
||||
|
||||
|
||||
class ExtractGspBootUcodeTests(unittest.TestCase):
|
||||
def test_extract_ad102_and_ga102_all(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
root = Path(td)
|
||||
obj = root / "nv-kernel.o_binary"
|
||||
obj.write_bytes(_make_elf64(_make_full_chip_entries(["ga102", "ad102"])))
|
||||
out_dir = root / "fw"
|
||||
|
||||
buf = io.StringIO()
|
||||
with redirect_stdout(buf):
|
||||
rc = extractor.main(["--rm-object", str(obj), "--chip", "all", "--out-dir", str(out_dir)])
|
||||
self.assertEqual(rc, 0)
|
||||
|
||||
ad_dir = out_dir / "ad102" / "gsp"
|
||||
ga_dir = out_dir / "ga102" / "gsp"
|
||||
for name in ("bootloader-580.bin", "booter_load-580.bin", "booter_unload-580.bin", "scrubber-580.bin"):
|
||||
self.assertTrue((ad_dir / name).is_file(), f"missing {name}")
|
||||
for name in ("bootloader-580.bin", "booter_load-580.bin", "booter_unload-580.bin"):
|
||||
self.assertTrue((ga_dir / name).is_file(), f"missing {name}")
|
||||
self.assertFalse((ga_dir / "scrubber-580.bin").exists())
|
||||
|
||||
bl = (ad_dir / "bootloader-580.bin").read_bytes()
|
||||
magic, ver, total_size, hdr_off, data_off, data_size = struct.unpack_from("<6I", bl, 0)
|
||||
self.assertEqual((magic, ver, hdr_off, data_off, data_size), (0x10DE, 1, 0x18, 0x18 + 44, 512))
|
||||
self.assertEqual(total_size, extractor.align_up(0x18 + 44 + 512, 0x100))
|
||||
|
||||
load = (ad_dir / "booter_load-580.bin").read_bytes()
|
||||
hs = struct.unpack_from("<9I", load, 0x18)
|
||||
self.assertEqual(hs[0], 0x3C)
|
||||
self.assertEqual(hs[1], 2 * 384)
|
||||
self.assertEqual(hs[8], 36)
|
||||
|
||||
def test_extended_section_numbering_xindex(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
root = Path(td)
|
||||
obj = root / "nv-kernel-xindex.o_binary"
|
||||
obj.write_bytes(_make_elf64(_make_full_chip_entries(["ad102"]), use_xindex=True))
|
||||
out_dir = root / "fw"
|
||||
|
||||
buf = io.StringIO()
|
||||
with redirect_stdout(buf):
|
||||
rc = extractor.main(["--rm-object", str(obj), "--chip", "ad102", "--out-dir", str(out_dir)])
|
||||
self.assertEqual(rc, 0)
|
||||
self.assertTrue((out_dir / "ad102" / "gsp" / "scrubber-580.bin").is_file())
|
||||
|
||||
def test_proprietary_object_without_kgsp_symbols_reports_clear_hint(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
root = Path(td)
|
||||
obj = root / "proprietary.o_binary"
|
||||
obj.write_bytes(_make_elf64({"some_other_rodata_symbol": b"hello"}))
|
||||
out_dir = root / "fw"
|
||||
|
||||
err = io.StringIO()
|
||||
with redirect_stderr(err):
|
||||
rc = extractor.main(["--rm-object", str(obj), "--chip", "ad102", "--out-dir", str(out_dir)])
|
||||
self.assertEqual(rc, 1)
|
||||
msg = err.getvalue()
|
||||
self.assertIn("kernel-open/nvidia/nv-kernel.o_binary", msg)
|
||||
self.assertIn("kgspBinArchive", msg)
|
||||
self.assertFalse((out_dir / "ad102").exists())
|
||||
|
||||
def test_rejects_symbol_exceeding_rodata_bounds(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
root = Path(td)
|
||||
entries = _make_full_chip_entries(["ad102"])
|
||||
bad_sym = "kgspBinArchiveGspRmBoot_AD102_BINDATA_LABEL_UCODE_DESC_PROD_data"
|
||||
obj = root / "oob.o_binary"
|
||||
obj.write_bytes(_make_elf64(entries, corrupt_sym_size=(bad_sym, 10_000_000)))
|
||||
out_dir = root / "fw"
|
||||
|
||||
err = io.StringIO()
|
||||
with redirect_stderr(err):
|
||||
rc = extractor.main(["--rm-object", str(obj), "--chip", "ad102", "--out-dir", str(out_dir)])
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertIn("exceeds .rodata size", err.getvalue())
|
||||
|
||||
def test_rejects_zero_hs_sig_count(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
root = Path(td)
|
||||
entries = _make_full_chip_entries(["ad102"])
|
||||
entries["kgspBinArchiveBooterLoadUcode_AD102_BINDATA_LABEL_NUM_SIGS_data"] = struct.pack("<I", 0)
|
||||
obj = root / "zero-sig.o_binary"
|
||||
obj.write_bytes(_make_elf64(entries))
|
||||
out_dir = root / "fw"
|
||||
|
||||
err = io.StringIO()
|
||||
with redirect_stderr(err):
|
||||
rc = extractor.main(["--rm-object", str(obj), "--chip", "ad102", "--out-dir", str(out_dir)])
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertIn("invalid HS signature count", err.getvalue())
|
||||
|
||||
def test_failed_write_and_replace_preserve_existing_firmware_and_clean_tempfiles(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
root = Path(td)
|
||||
obj = root / "nv-kernel.o_binary"
|
||||
obj.write_bytes(_make_elf64(_make_full_chip_entries(["ad102"])))
|
||||
out_dir = root / "fw"
|
||||
gsp_dir = out_dir / "ad102" / "gsp"
|
||||
gsp_dir.mkdir(parents=True)
|
||||
existing = gsp_dir / "bootloader-580.bin"
|
||||
existing.write_bytes(b"ORIGINAL_INSTALLED_FIRMWARE")
|
||||
|
||||
# 1. os.replace failure preserves existing file, removes tempfiles, returns 1.
|
||||
err1 = io.StringIO()
|
||||
with (
|
||||
mock.patch.object(extractor.os, "replace", side_effect=OSError("simulated replace failure")),
|
||||
redirect_stderr(err1),
|
||||
):
|
||||
rc1 = extractor.main(["--rm-object", str(obj), "--chip", "ad102", "--out-dir", str(out_dir)])
|
||||
self.assertEqual(rc1, 1)
|
||||
self.assertIn("simulated replace failure", err1.getvalue())
|
||||
self.assertEqual(existing.read_bytes(), b"ORIGINAL_INSTALLED_FIRMWARE")
|
||||
self.assertEqual(list(gsp_dir.glob("*.tmp")), [])
|
||||
|
||||
# 2. Write failure inside os.fdopen preserves existing file, removes tempfiles, returns 1.
|
||||
real_fdopen = extractor.os.fdopen
|
||||
|
||||
class FailingWriter:
|
||||
def __init__(self, fh):
|
||||
self._fh = fh
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb):
|
||||
self._fh.close()
|
||||
return False
|
||||
|
||||
def write(self, _data: bytes) -> int:
|
||||
raise OSError("simulated disk full")
|
||||
|
||||
def flush(self) -> None:
|
||||
pass
|
||||
|
||||
err2 = io.StringIO()
|
||||
with (
|
||||
mock.patch.object(extractor.os, "fdopen", side_effect=lambda fd, mode: FailingWriter(real_fdopen(fd, mode))),
|
||||
redirect_stderr(err2),
|
||||
):
|
||||
rc2 = extractor.main(["--rm-object", str(obj), "--chip", "ad102", "--out-dir", str(out_dir)])
|
||||
self.assertEqual(rc2, 1)
|
||||
self.assertIn("simulated disk full", err2.getvalue())
|
||||
self.assertEqual(existing.read_bytes(), b"ORIGINAL_INSTALLED_FIRMWARE")
|
||||
self.assertEqual(list(gsp_dir.glob("*.tmp")), [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Extract 580.x GSP-RM boot ucode from nv-kernel.o_binary into linux-firmware nvfw_bin_hdr files.
|
||||
"""Extract 580.x GSP-RM boot ucode from kernel-open nv-kernel.o_binary into linux-firmware nvfw_bin_hdr files.
|
||||
|
||||
Produces standard nouveau / linux-firmware layout files under <output-dir>/<chip>/gsp/:
|
||||
- bootloader-580.bin (nvfw_bin_hdr + RM_RISCV_UCODE_DESC + RISC-V image)
|
||||
@ -7,9 +7,16 @@ Produces standard nouveau / linux-firmware layout files under <output-dir>/<chip
|
||||
- booter_unload-580.bin (nvfw_bin_hdr + nvfw_hs_header_v2 + sigs/meta/load_hdr + image)
|
||||
- scrubber-580.bin (AD10x only: ksec2BinArchiveSecurescrubUcode_AD10X)
|
||||
|
||||
Note: The input must be the open-kernel-modules object
|
||||
(`kernel-open/nvidia/nv-kernel.o_binary` from the 580.x `.run` installer or
|
||||
`open-gpu-kernel-modules` build). The proprietary `kernel/nvidia/nv-kernel.o_binary`
|
||||
strips the `kgspBinArchive*` bindata symbols and cannot be used here.
|
||||
Currently supports Ampere (`ga102`) and Ada (`ad102`); Hopper and Blackwell
|
||||
bootloaders are out of scope for this extractor.
|
||||
|
||||
Usage:
|
||||
python3 tools/extract_gsp_boot_ucode.py \\
|
||||
--rm-object /usr/src/nvidia-580.178.04/nvidia/nv-kernel.o_binary \\
|
||||
--rm-object /path/to/kernel-open/nvidia/nv-kernel.o_binary \\
|
||||
--chip ad102 \\
|
||||
--out-dir /lib/firmware/nvidia
|
||||
"""
|
||||
@ -21,77 +28,152 @@ import hashlib
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
ELF_MAGIC = b"\x7fELF"
|
||||
SHT_SYMTAB = 2
|
||||
SHT_SYMTAB_SHNDX = 18
|
||||
SHN_XINDEX = 0xFFFF
|
||||
MAX_HS_SIG_COUNT = 64
|
||||
|
||||
|
||||
def align_up(val: int, align: int) -> int:
|
||||
return (val + align - 1) & ~(align - 1)
|
||||
|
||||
|
||||
def parse_elf64_rodata_and_syms(path: Path) -> tuple[bytes, int, dict[str, tuple[int, int]]]:
|
||||
def _check_slice(data_len: int, offset: int, size: int, label: str) -> None:
|
||||
if offset < 0 or size < 0 or offset + size > data_len:
|
||||
raise ValueError(f"{label} out of bounds (offset={offset}, size={size}, file_len={data_len})")
|
||||
|
||||
|
||||
def parse_elf64_rodata_and_syms(path: Path) -> tuple[bytes, int, int, dict[str, tuple[int, int]]]:
|
||||
data = path.read_bytes()
|
||||
if len(data) < 64 or data[:4] != ELF_MAGIC or data[4] != 2 or data[5] != 1:
|
||||
data_len = len(data)
|
||||
if data_len < 64 or data[:4] != ELF_MAGIC or data[4] != 2 or data[5] != 1:
|
||||
raise ValueError(f"{path} is not a little-endian ELF64 object")
|
||||
|
||||
e_shoff = struct.unpack_from("<Q", data, 40)[0]
|
||||
e_shentsize, e_shnum, e_shstrndx = struct.unpack_from("<HHH", data, 58)
|
||||
sections = []
|
||||
for i in range(e_shnum):
|
||||
if e_shoff == 0 or e_shentsize < 64:
|
||||
raise ValueError(f"{path} has invalid section header table (shoff={e_shoff}, shentsize={e_shentsize})")
|
||||
_check_slice(data_len, e_shoff, e_shentsize, "section header 0")
|
||||
|
||||
sh0_name, sh0_type, _sh0_flags, _sh0_addr, sh0_offset, sh0_size, sh0_link = struct.unpack_from(
|
||||
"<IIQQQQI", data, e_shoff
|
||||
)
|
||||
shnum = sh0_size if e_shnum == 0 else e_shnum
|
||||
shstrndx = sh0_link if e_shstrndx == SHN_XINDEX else e_shstrndx
|
||||
if shnum == 0:
|
||||
raise ValueError(f"{path} has no ELF sections")
|
||||
_check_slice(data_len, e_shoff, shnum * e_shentsize, "section header table")
|
||||
if shstrndx >= shnum:
|
||||
raise ValueError(f"{path} has out-of-range shstrndx={shstrndx} (shnum={shnum})")
|
||||
|
||||
sections: list[tuple[int, int, int, int, int]] = []
|
||||
for i in range(shnum):
|
||||
off = e_shoff + i * e_shentsize
|
||||
sh_name, sh_type, _flags, _addr, sh_offset, sh_size, sh_link = struct.unpack_from(
|
||||
"<IIQQQQI", data, off
|
||||
)
|
||||
sections.append((sh_name, sh_type, sh_offset, sh_size, sh_link))
|
||||
|
||||
shstr_off = sections[e_shstrndx][2]
|
||||
_, _, shstr_off, shstr_size, _ = sections[shstrndx]
|
||||
_check_slice(data_len, shstr_off, shstr_size, "shstrtab")
|
||||
|
||||
def read_cstr(table_off: int, idx: int) -> str:
|
||||
end = data.index(b"\x00", table_off + idx)
|
||||
return data[table_off + idx : end].decode("ascii", errors="replace")
|
||||
def read_cstr(table_off: int, table_size: int, idx: int, label: str) -> str:
|
||||
if idx >= table_size:
|
||||
raise ValueError(f"{path}: {label} index {idx} out of bounds (size={table_size})")
|
||||
start = table_off + idx
|
||||
limit = table_off + table_size
|
||||
end = data.find(b"\x00", start, limit)
|
||||
if end < 0:
|
||||
raise ValueError(f"{path}: unterminated string in {label} at offset {idx}")
|
||||
return data[start:end].decode("ascii", errors="replace")
|
||||
|
||||
rodata_idx = None
|
||||
rodata_off = None
|
||||
rodata_size = None
|
||||
symtab_sec = None
|
||||
symtab_idx = None
|
||||
shndx_by_link: dict[int, tuple[int, int]] = {}
|
||||
for idx, (sh_name, sh_type, sh_offset, sh_size, sh_link) in enumerate(sections):
|
||||
name = read_cstr(shstr_off, sh_name)
|
||||
name = read_cstr(shstr_off, shstr_size, sh_name, "shstrtab")
|
||||
if name == ".rodata":
|
||||
_check_slice(data_len, sh_offset, sh_size, ".rodata")
|
||||
rodata_idx = idx
|
||||
rodata_off = sh_offset
|
||||
rodata_size = sh_size
|
||||
if sh_type == SHT_SYMTAB:
|
||||
_check_slice(data_len, sh_offset, sh_size, ".symtab")
|
||||
symtab_sec = (sh_offset, sh_size, sh_link)
|
||||
symtab_idx = idx
|
||||
elif sh_type == SHT_SYMTAB_SHNDX:
|
||||
_check_slice(data_len, sh_offset, sh_size, ".symtab_shndx")
|
||||
shndx_by_link[sh_link] = (sh_offset, sh_size)
|
||||
|
||||
if rodata_idx is None or rodata_off is None or symtab_sec is None:
|
||||
if rodata_idx is None or rodata_off is None or rodata_size is None or symtab_sec is None:
|
||||
raise ValueError(f"{path} missing .rodata or .symtab")
|
||||
|
||||
sym_off, sym_size, str_idx = symtab_sec
|
||||
str_off = sections[str_idx][2]
|
||||
if sym_size % 24 != 0:
|
||||
raise ValueError(f"{path}: .symtab size {sym_size} is not a multiple of 24")
|
||||
if str_idx >= shnum:
|
||||
raise ValueError(f"{path}: .symtab sh_link={str_idx} out of range (shnum={shnum})")
|
||||
_, _, str_off, str_size, _ = sections[str_idx]
|
||||
_check_slice(data_len, str_off, str_size, ".strtab")
|
||||
|
||||
ext_shndx = shndx_by_link.get(symtab_idx)
|
||||
|
||||
syms: dict[str, tuple[int, int]] = {}
|
||||
for pos in range(sym_off, sym_off + sym_size, 24):
|
||||
for sym_i, pos in enumerate(range(sym_off, sym_off + sym_size, 24)):
|
||||
st_name, _info, _other, st_shndx, st_value, st_size = struct.unpack_from(
|
||||
"<IBBHQQ", data, pos
|
||||
)
|
||||
if st_shndx == rodata_idx and st_size > 0:
|
||||
name = read_cstr(str_off, st_name)
|
||||
resolved_shndx = st_shndx
|
||||
if st_shndx == SHN_XINDEX:
|
||||
if ext_shndx is None:
|
||||
raise ValueError(
|
||||
f"{path}: symbol {sym_i} uses SHN_XINDEX without a matching "
|
||||
f"SHT_SYMTAB_SHNDX section for .symtab (index {symtab_idx})"
|
||||
)
|
||||
if (sym_i + 1) * 4 > ext_shndx[1]:
|
||||
raise ValueError(
|
||||
f"{path}: truncated SHT_SYMTAB_SHNDX section (size {ext_shndx[1]}) "
|
||||
f"for symbol index {sym_i}"
|
||||
)
|
||||
resolved_shndx = struct.unpack_from("<I", data, ext_shndx[0] + sym_i * 4)[0]
|
||||
if resolved_shndx == rodata_idx and st_size > 0:
|
||||
name = read_cstr(str_off, str_size, st_name, ".strtab")
|
||||
syms[name] = (st_value, st_size)
|
||||
|
||||
return data, rodata_off, syms
|
||||
return data, rodata_off, rodata_size, syms
|
||||
|
||||
|
||||
def read_bindata(
|
||||
data: bytes,
|
||||
rodata_off: int,
|
||||
rodata_size: int,
|
||||
syms: dict[str, tuple[int, int]],
|
||||
sym: str,
|
||||
compressed: bool | None = None,
|
||||
expected_len: int | None = None,
|
||||
) -> bytes:
|
||||
if sym not in syms:
|
||||
has_gsp_bindata = any(name.startswith("kgspBinArchive") for name in syms)
|
||||
if not has_gsp_bindata:
|
||||
raise KeyError(
|
||||
f"missing symbol {sym}: input ELF has no kgspBinArchive* symbols "
|
||||
"(the proprietary kernel/nvidia/nv-kernel.o_binary strips them; "
|
||||
"pass kernel-open/nvidia/nv-kernel.o_binary from the 580.x .run or open-gpu-kernel-modules)"
|
||||
)
|
||||
raise KeyError(f"missing symbol {sym}")
|
||||
voff, size = syms[sym]
|
||||
if voff + size > rodata_size:
|
||||
raise ValueError(
|
||||
f"{sym}: symbol range [{voff}, {voff + size}) exceeds .rodata size {rodata_size}"
|
||||
)
|
||||
raw = data[rodata_off + voff : rodata_off + voff + size]
|
||||
if compressed is False and (expected_len is None or len(raw) == expected_len):
|
||||
return raw
|
||||
@ -161,33 +243,38 @@ def pack_hs_booter(
|
||||
|
||||
|
||||
def extract_hs_archive(
|
||||
data: bytes, rodata_off: int, syms: dict[str, tuple[int, int]], prefix: str
|
||||
data: bytes, rodata_off: int, rodata_size: int, syms: dict[str, tuple[int, int]], prefix: str
|
||||
) -> bytes:
|
||||
num_sigs = read_bindata(
|
||||
data, rodata_off, syms, f"{prefix}_BINDATA_LABEL_NUM_SIGS_data", False, expected_len=4
|
||||
data, rodata_off, rodata_size, syms, f"{prefix}_BINDATA_LABEL_NUM_SIGS_data", False, expected_len=4
|
||||
)
|
||||
count = struct.unpack_from("<I", num_sigs, 0)[0]
|
||||
if count == 0 or count > MAX_HS_SIG_COUNT:
|
||||
raise ValueError(f"{prefix}: invalid HS signature count {count}")
|
||||
sig_prod = read_bindata(
|
||||
data,
|
||||
rodata_off,
|
||||
rodata_size,
|
||||
syms,
|
||||
f"{prefix}_BINDATA_LABEL_SIG_PROD_data",
|
||||
False,
|
||||
expected_len=count * 384,
|
||||
)
|
||||
patch_loc = read_bindata(
|
||||
data, rodata_off, syms, f"{prefix}_BINDATA_LABEL_PATCH_LOC_data", False, expected_len=4
|
||||
data, rodata_off, rodata_size, syms, f"{prefix}_BINDATA_LABEL_PATCH_LOC_data", False, expected_len=4
|
||||
)
|
||||
patch_sig = read_bindata(
|
||||
data, rodata_off, syms, f"{prefix}_BINDATA_LABEL_PATCH_SIG_data", False, expected_len=4
|
||||
data, rodata_off, rodata_size, syms, f"{prefix}_BINDATA_LABEL_PATCH_SIG_data", False, expected_len=4
|
||||
)
|
||||
patch_meta = read_bindata(
|
||||
data, rodata_off, syms, f"{prefix}_BINDATA_LABEL_PATCH_META_data", False, expected_len=12
|
||||
data, rodata_off, rodata_size, syms, f"{prefix}_BINDATA_LABEL_PATCH_META_data", False, expected_len=12
|
||||
)
|
||||
header_prod = read_bindata(
|
||||
data, rodata_off, syms, f"{prefix}_BINDATA_LABEL_HEADER_PROD_data", True, expected_len=36
|
||||
data, rodata_off, rodata_size, syms, f"{prefix}_BINDATA_LABEL_HEADER_PROD_data", True, expected_len=36
|
||||
)
|
||||
image_prod = read_bindata(
|
||||
data, rodata_off, rodata_size, syms, f"{prefix}_BINDATA_LABEL_IMAGE_PROD_data", True
|
||||
)
|
||||
image_prod = read_bindata(data, rodata_off, syms, f"{prefix}_BINDATA_LABEL_IMAGE_PROD_data", True)
|
||||
return pack_hs_booter(sig_prod, patch_loc, patch_sig, patch_meta, num_sigs, header_prod, image_prod)
|
||||
|
||||
|
||||
@ -206,38 +293,75 @@ CHIPS = {
|
||||
}
|
||||
|
||||
|
||||
def extract_chip(rm_object: Path, chip: str, out_dir: Path, suffix: str) -> None:
|
||||
data, rodata_off, syms = parse_elf64_rodata_and_syms(rm_object)
|
||||
spec = CHIPS[chip]
|
||||
gsp_dir = out_dir / chip / "gsp"
|
||||
gsp_dir.mkdir(parents=True, exist_ok=True)
|
||||
def _write_file_atomic(dst: Path, blob: bytes) -> None:
|
||||
fd, tmp_name = tempfile.mkstemp(prefix=f".{dst.name}.", suffix=".tmp", dir=dst.parent)
|
||||
tmp_path = Path(tmp_name)
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as fh:
|
||||
fh.write(blob)
|
||||
fh.flush()
|
||||
os.chmod(tmp_path, 0o644)
|
||||
os.replace(tmp_path, dst)
|
||||
except BaseException:
|
||||
try:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
def extract_chip_from_parsed(
|
||||
data: bytes,
|
||||
rodata_off: int,
|
||||
rodata_size: int,
|
||||
syms: dict[str, tuple[int, int]],
|
||||
chip: str,
|
||||
out_dir: Path,
|
||||
suffix: str,
|
||||
) -> None:
|
||||
spec = CHIPS[chip]
|
||||
bl_prefix = spec["bootloader"]
|
||||
desc = read_bindata(data, rodata_off, syms, f"{bl_prefix}_BINDATA_LABEL_UCODE_DESC_PROD_data", True)
|
||||
img = read_bindata(data, rodata_off, syms, f"{bl_prefix}_BINDATA_LABEL_UCODE_IMAGE_PROD_data", True)
|
||||
desc = read_bindata(
|
||||
data, rodata_off, rodata_size, syms, f"{bl_prefix}_BINDATA_LABEL_UCODE_DESC_PROD_data", True
|
||||
)
|
||||
img = read_bindata(
|
||||
data, rodata_off, rodata_size, syms, f"{bl_prefix}_BINDATA_LABEL_UCODE_IMAGE_PROD_data", True
|
||||
)
|
||||
outputs = {
|
||||
f"bootloader-{suffix}.bin": pack_riscv_bootloader(desc, img),
|
||||
f"booter_load-{suffix}.bin": extract_hs_archive(data, rodata_off, syms, spec["booter_load"]),
|
||||
f"booter_unload-{suffix}.bin": extract_hs_archive(data, rodata_off, syms, spec["booter_unload"]),
|
||||
f"booter_load-{suffix}.bin": extract_hs_archive(
|
||||
data, rodata_off, rodata_size, syms, spec["booter_load"]
|
||||
),
|
||||
f"booter_unload-{suffix}.bin": extract_hs_archive(
|
||||
data, rodata_off, rodata_size, syms, spec["booter_unload"]
|
||||
),
|
||||
}
|
||||
if "scrubber" in spec:
|
||||
outputs[f"scrubber-{suffix}.bin"] = extract_hs_archive(data, rodata_off, syms, spec["scrubber"])
|
||||
outputs[f"scrubber-{suffix}.bin"] = extract_hs_archive(
|
||||
data, rodata_off, rodata_size, syms, spec["scrubber"]
|
||||
)
|
||||
|
||||
gsp_dir = out_dir / chip / "gsp"
|
||||
gsp_dir.mkdir(parents=True, exist_ok=True)
|
||||
for fname, blob in outputs.items():
|
||||
dst = gsp_dir / fname
|
||||
dst.write_bytes(blob)
|
||||
os.chmod(dst, 0o644)
|
||||
_write_file_atomic(dst, blob)
|
||||
digest = hashlib.sha256(blob).hexdigest()[:16]
|
||||
print(f"{dst}: {len(blob)} bytes sha256={digest}...")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
def extract_chip(rm_object: Path, chip: str, out_dir: Path, suffix: str) -> None:
|
||||
data, rodata_off, rodata_size, syms = parse_elf64_rodata_and_syms(rm_object)
|
||||
extract_chip_from_parsed(data, rodata_off, rodata_size, syms, chip, out_dir, suffix)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__)
|
||||
ap.add_argument(
|
||||
"--rm-object",
|
||||
type=Path,
|
||||
default=Path("/usr/src/nvidia-580.178.04/nvidia/nv-kernel.o_binary"),
|
||||
help="Path to 580.x nv-kernel.o_binary",
|
||||
help="Path to 580.x kernel-open/nvidia/nv-kernel.o_binary (not proprietary kernel/)",
|
||||
)
|
||||
ap.add_argument(
|
||||
"--chip",
|
||||
@ -252,11 +376,17 @@ def main() -> int:
|
||||
help="Firmware root directory (default: /lib/firmware/nvidia)",
|
||||
)
|
||||
ap.add_argument("--suffix", default="580", help="Filename version suffix (default: 580)")
|
||||
args = ap.parse_args()
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
chips = list(CHIPS.keys()) if args.chip == "all" else [args.chip]
|
||||
for chip in chips:
|
||||
extract_chip(args.rm_object, chip, args.out_dir, args.suffix)
|
||||
try:
|
||||
data, rodata_off, rodata_size, syms = parse_elf64_rodata_and_syms(args.rm_object)
|
||||
for chip in chips:
|
||||
extract_chip_from_parsed(data, rodata_off, rodata_size, syms, chip, args.out_dir, args.suffix)
|
||||
except (OSError, ValueError, KeyError, zlib.error) as exc:
|
||||
msg = exc.args[0] if isinstance(exc, KeyError) and exc.args else str(exc)
|
||||
print(f"error: {msg}", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user