mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 14:38:47 +00:00
265 lines
9.0 KiB
Python
Executable File
265 lines
9.0 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Extract 580.x GSP-RM boot ucode from 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)
|
|
- booter_load-580.bin (nvfw_bin_hdr + nvfw_hs_header_v2 + sigs/meta/load_hdr + image)
|
|
- booter_unload-580.bin (nvfw_bin_hdr + nvfw_hs_header_v2 + sigs/meta/load_hdr + image)
|
|
- scrubber-580.bin (AD10x only: ksec2BinArchiveSecurescrubUcode_AD10X)
|
|
|
|
Usage:
|
|
python3 tools/extract_gsp_boot_ucode.py \\
|
|
--rm-object /usr/src/nvidia-580.178.04/nvidia/nv-kernel.o_binary \\
|
|
--chip ad102 \\
|
|
--out-dir /lib/firmware/nvidia
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import hashlib
|
|
import os
|
|
import struct
|
|
import sys
|
|
import zlib
|
|
from pathlib import Path
|
|
|
|
ELF_MAGIC = b"\x7fELF"
|
|
SHT_SYMTAB = 2
|
|
|
|
|
|
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]]]:
|
|
data = path.read_bytes()
|
|
if len(data) < 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):
|
|
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]
|
|
|
|
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")
|
|
|
|
rodata_idx = None
|
|
rodata_off = None
|
|
symtab_sec = None
|
|
for idx, (sh_name, sh_type, sh_offset, sh_size, sh_link) in enumerate(sections):
|
|
name = read_cstr(shstr_off, sh_name)
|
|
if name == ".rodata":
|
|
rodata_idx = idx
|
|
rodata_off = sh_offset
|
|
if sh_type == SHT_SYMTAB:
|
|
symtab_sec = (sh_offset, sh_size, sh_link)
|
|
|
|
if rodata_idx is None or rodata_off 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]
|
|
syms: dict[str, tuple[int, int]] = {}
|
|
for pos in 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)
|
|
syms[name] = (st_value, st_size)
|
|
|
|
return data, rodata_off, syms
|
|
|
|
|
|
def read_bindata(
|
|
data: bytes,
|
|
rodata_off: int,
|
|
syms: dict[str, tuple[int, int]],
|
|
sym: str,
|
|
compressed: bool | None = None,
|
|
expected_len: int | None = None,
|
|
) -> bytes:
|
|
if sym not in syms:
|
|
raise KeyError(f"missing symbol {sym}")
|
|
voff, size = syms[sym]
|
|
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
|
|
if compressed is True or (expected_len is not None and len(raw) != expected_len):
|
|
if len(raw) >= 2 and raw[0] == 0x1F and raw[1] == 0x8B:
|
|
out = zlib.decompress(raw, 16 + zlib.MAX_WBITS)
|
|
else:
|
|
out = zlib.decompress(raw, -zlib.MAX_WBITS)
|
|
if expected_len is not None and len(out) != expected_len:
|
|
raise ValueError(f"{sym}: decompressed len {len(out)} != expected {expected_len}")
|
|
return out
|
|
return raw
|
|
|
|
|
|
def pack_riscv_bootloader(desc: bytes, image: bytes) -> bytes:
|
|
header_off = 0x18
|
|
data_off = header_off + len(desc)
|
|
total_size = align_up(data_off + len(image), 0x100)
|
|
bin_hdr = struct.pack("<6I", 0x10DE, 1, total_size, header_off, data_off, len(image))
|
|
return bin_hdr + desc + image
|
|
|
|
|
|
def pack_hs_booter(
|
|
sig_prod: bytes,
|
|
patch_loc: bytes,
|
|
patch_sig: bytes,
|
|
patch_meta: bytes,
|
|
num_sigs: bytes,
|
|
header_prod: bytes,
|
|
image_prod: bytes,
|
|
) -> bytes:
|
|
header_off = 0x18
|
|
hs_hdr_size = 9 * 4 # 0x24
|
|
sig_prod_off = header_off + hs_hdr_size # 0x3c
|
|
patch_loc_off = sig_prod_off + len(sig_prod)
|
|
patch_sig_off = patch_loc_off + len(patch_loc)
|
|
meta_off = patch_sig_off + len(patch_sig)
|
|
num_sigs_off = meta_off + len(patch_meta)
|
|
load_hdr_off = num_sigs_off + len(num_sigs)
|
|
data_off = load_hdr_off + len(header_prod)
|
|
total_size = align_up(data_off + len(image_prod), 0x100)
|
|
|
|
bin_hdr = struct.pack("<6I", 0x10DE, 1, total_size, header_off, data_off, len(image_prod))
|
|
hs_hdr = struct.pack(
|
|
"<9I",
|
|
sig_prod_off,
|
|
len(sig_prod),
|
|
patch_loc_off,
|
|
patch_sig_off,
|
|
meta_off,
|
|
len(patch_meta),
|
|
num_sigs_off,
|
|
load_hdr_off,
|
|
len(header_prod),
|
|
)
|
|
return (
|
|
bin_hdr
|
|
+ hs_hdr
|
|
+ sig_prod
|
|
+ patch_loc
|
|
+ patch_sig
|
|
+ patch_meta
|
|
+ num_sigs
|
|
+ header_prod
|
|
+ image_prod
|
|
)
|
|
|
|
|
|
def extract_hs_archive(
|
|
data: bytes, rodata_off: 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
|
|
)
|
|
count = struct.unpack_from("<I", num_sigs, 0)[0]
|
|
sig_prod = read_bindata(
|
|
data,
|
|
rodata_off,
|
|
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
|
|
)
|
|
patch_sig = read_bindata(
|
|
data, rodata_off, 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
|
|
)
|
|
header_prod = read_bindata(
|
|
data, rodata_off, syms, f"{prefix}_BINDATA_LABEL_HEADER_PROD_data", True, expected_len=36
|
|
)
|
|
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)
|
|
|
|
|
|
CHIPS = {
|
|
"ga102": {
|
|
"bootloader": "kgspBinArchiveGspRmBoot_GA102",
|
|
"booter_load": "kgspBinArchiveBooterLoadUcode_GA102",
|
|
"booter_unload": "kgspBinArchiveBooterUnloadUcode_GA102",
|
|
},
|
|
"ad102": {
|
|
"bootloader": "kgspBinArchiveGspRmBoot_AD102",
|
|
"booter_load": "kgspBinArchiveBooterLoadUcode_AD102",
|
|
"booter_unload": "kgspBinArchiveBooterUnloadUcode_AD102",
|
|
"scrubber": "ksec2BinArchiveSecurescrubUcode_AD10X",
|
|
},
|
|
}
|
|
|
|
|
|
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)
|
|
|
|
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)
|
|
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"]),
|
|
}
|
|
if "scrubber" in spec:
|
|
outputs[f"scrubber-{suffix}.bin"] = extract_hs_archive(data, rodata_off, syms, spec["scrubber"])
|
|
|
|
for fname, blob in outputs.items():
|
|
dst = gsp_dir / fname
|
|
dst.write_bytes(blob)
|
|
os.chmod(dst, 0o644)
|
|
digest = hashlib.sha256(blob).hexdigest()[:16]
|
|
print(f"{dst}: {len(blob)} bytes sha256={digest}...")
|
|
|
|
|
|
def main() -> 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",
|
|
)
|
|
ap.add_argument(
|
|
"--chip",
|
|
choices=[*CHIPS.keys(), "all"],
|
|
default="ad102",
|
|
help="Target chip family (default: ad102)",
|
|
)
|
|
ap.add_argument(
|
|
"--out-dir",
|
|
type=Path,
|
|
default=Path("/lib/firmware/nvidia"),
|
|
help="Firmware root directory (default: /lib/firmware/nvidia)",
|
|
)
|
|
ap.add_argument("--suffix", default="580", help="Filename version suffix (default: 580)")
|
|
args = ap.parse_args()
|
|
|
|
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)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|