2026-11-22 10:49:59 +02:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
"""Extract device-owned MT6797 Wi-Fi, Bluetooth, and SPM firmware blobs
|
|
|
|
|
from a stock Gemini PDA system partition image or mounted directory.
|
|
|
|
|
|
|
|
|
|
Extracted files are placed in gitignored firmware-cache/mt6797/ so Geminux can
|
|
|
|
|
bundle them locally on the device without redistributing non-free firmware.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
import argparse
|
|
|
|
|
import hashlib
|
|
|
|
|
import os
|
|
|
|
|
import shutil
|
|
|
|
|
import subprocess
|
|
|
|
|
import sys
|
|
|
|
|
import tempfile
|
|
|
|
|
|
|
|
|
|
REQUIRED_BLOBS = (
|
|
|
|
|
"ROMv3_patch_1_0_hdr.bin",
|
|
|
|
|
"ROMv3_patch_1_1_hdr.bin",
|
|
|
|
|
"WIFI_RAM_CODE_6797",
|
|
|
|
|
"WMT_SOC.cfg",
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
OPTIONAL_SPM_GLOB_PREFIX = "pcm_"
|
|
|
|
|
|
|
|
|
|
SEARCH_SUBDIRS = (
|
|
|
|
|
"vendor/firmware",
|
|
|
|
|
"system/vendor/firmware",
|
|
|
|
|
"etc/firmware",
|
|
|
|
|
"system/etc/firmware",
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
SPARSE_MAGIC = b"\x3a\xff\x26\xed"
|
|
|
|
|
|
|
|
|
|
|
2026-11-28 09:18:51 +02:00
|
|
|
def is_firmware_blob_name(name):
|
|
|
|
|
"""Return True if filename is a required MT6797 blob or optional SPM binary."""
|
|
|
|
|
return name in REQUIRED_BLOBS or (
|
|
|
|
|
name.startswith(OPTIONAL_SPM_GLOB_PREFIX) and name.endswith(".bin")
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def list_firmware_blobs(fw_dir):
|
|
|
|
|
"""Return sorted (filename, abs_path) pairs for MT6797 firmware blobs in fw_dir."""
|
|
|
|
|
if not fw_dir or not os.path.isdir(fw_dir):
|
|
|
|
|
return []
|
|
|
|
|
abs_fw = os.path.abspath(fw_dir)
|
|
|
|
|
blobs = []
|
|
|
|
|
for name in sorted(os.listdir(abs_fw)):
|
|
|
|
|
if not is_firmware_blob_name(name):
|
|
|
|
|
continue
|
|
|
|
|
path = os.path.join(abs_fw, name)
|
|
|
|
|
if os.path.isfile(path) and not os.path.islink(path):
|
|
|
|
|
blobs.append((name, path))
|
|
|
|
|
return blobs
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _have_host_e2fs():
|
|
|
|
|
return shutil.which("debugfs") is not None and shutil.which("e2fsck") is not None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _run_docker_e2fs(img_dir, extra_mounts, shell_cmd, input_text=None):
|
|
|
|
|
docker_bin = shutil.which("docker")
|
|
|
|
|
if not docker_bin:
|
|
|
|
|
raise RuntimeError("Need host debugfs/e2fsck (e2fsprogs) or docker to modify ext4 image")
|
|
|
|
|
cmd = [docker_bin, "run", "--rm", "-i", "-v", f"{img_dir}:/img"]
|
|
|
|
|
for host_path, container_path in extra_mounts:
|
|
|
|
|
cmd += ["-v", f"{host_path}:{container_path}:ro"]
|
|
|
|
|
cmd += [
|
|
|
|
|
"alpine:3.24", "sh", "-eu", "-c",
|
|
|
|
|
f"apk add --no-cache e2fsprogs >/dev/null && {shell_cmd}",
|
|
|
|
|
]
|
|
|
|
|
return subprocess.run(cmd, input=input_text, text=True, check=True, capture_output=True)
|
|
|
|
|
|
|
|
|
|
|
2026-11-22 10:49:59 +02:00
|
|
|
def sha256_file(path):
|
|
|
|
|
h = hashlib.sha256()
|
|
|
|
|
with open(path, "rb") as f:
|
|
|
|
|
while True:
|
|
|
|
|
chunk = f.read(65536)
|
|
|
|
|
if not chunk:
|
|
|
|
|
break
|
|
|
|
|
h.update(chunk)
|
|
|
|
|
return h.hexdigest()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def is_sparse_image(path):
|
|
|
|
|
with open(path, "rb") as f:
|
|
|
|
|
return f.read(4) == SPARSE_MAGIC
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def debugfs_ls(image_path, internal_dir):
|
|
|
|
|
cmd = ["debugfs", "-R", f"ls -p /{internal_dir}", image_path]
|
|
|
|
|
res = subprocess.run(cmd, capture_output=True, text=True, check=False)
|
|
|
|
|
if res.returncode != 0:
|
|
|
|
|
return []
|
|
|
|
|
names = []
|
|
|
|
|
for line in res.stdout.splitlines():
|
|
|
|
|
# debugfs ls -p format: /inode/mode/uid/gid/name/size/
|
|
|
|
|
parts = line.split("/")
|
|
|
|
|
if len(parts) >= 6:
|
|
|
|
|
name = parts[5]
|
|
|
|
|
if name and name not in (".", ".."):
|
|
|
|
|
names.append(name)
|
|
|
|
|
return names
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def debugfs_dump(image_path, internal_path, dest_path):
|
|
|
|
|
cmd = ["debugfs", "-R", f"dump /{internal_path} {dest_path}", image_path]
|
|
|
|
|
res = subprocess.run(cmd, capture_output=True, text=True, check=False)
|
|
|
|
|
return res.returncode == 0 and os.path.isfile(dest_path) and os.path.getsize(dest_path) > 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def extract_from_ext4(image_path, out_dir):
|
|
|
|
|
os.makedirs(out_dir, exist_ok=True)
|
|
|
|
|
found = {}
|
|
|
|
|
|
|
|
|
|
# Collect candidate files across known firmware directories inside system.img
|
|
|
|
|
for subdir in SEARCH_SUBDIRS:
|
|
|
|
|
entries = debugfs_ls(image_path, subdir)
|
|
|
|
|
if not entries:
|
|
|
|
|
continue
|
|
|
|
|
for name in entries:
|
2026-11-28 09:18:51 +02:00
|
|
|
if not is_firmware_blob_name(name) or name in found:
|
2026-11-22 10:49:59 +02:00
|
|
|
continue
|
|
|
|
|
dest = os.path.join(out_dir, name)
|
|
|
|
|
if debugfs_dump(image_path, f"{subdir}/{name}", dest):
|
|
|
|
|
found[name] = dest
|
|
|
|
|
|
|
|
|
|
return found
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def extract_from_dir(src_dir, out_dir):
|
|
|
|
|
os.makedirs(out_dir, exist_ok=True)
|
|
|
|
|
found = {}
|
|
|
|
|
candidates = [src_dir] + [os.path.join(src_dir, s) for s in SEARCH_SUBDIRS]
|
|
|
|
|
for base in candidates:
|
|
|
|
|
if not os.path.isdir(base):
|
|
|
|
|
continue
|
|
|
|
|
for name in os.listdir(base):
|
2026-11-28 09:18:51 +02:00
|
|
|
if not is_firmware_blob_name(name) or name in found:
|
2026-11-22 10:49:59 +02:00
|
|
|
continue
|
|
|
|
|
src = os.path.join(base, name)
|
|
|
|
|
if os.path.isfile(src):
|
|
|
|
|
dest = os.path.join(out_dir, name)
|
|
|
|
|
shutil.copy2(src, dest)
|
|
|
|
|
found[name] = dest
|
|
|
|
|
return found
|
|
|
|
|
|
|
|
|
|
|
2026-11-28 09:18:51 +02:00
|
|
|
def _debugfs_path_exists(abs_img, internal_path):
|
|
|
|
|
res = subprocess.run(
|
|
|
|
|
["debugfs", "-R", f"stat {internal_path}", abs_img],
|
|
|
|
|
capture_output=True, text=True, check=False,
|
|
|
|
|
)
|
|
|
|
|
return res.returncode == 0 and "Type:" in res.stdout
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def inject_firmware_into_ext4(ext4_img_path, fw_dir):
|
|
|
|
|
"""Inject extracted MT6797 firmware blobs into /lib/firmware/mediatek/mt6797 of an ext4 image."""
|
|
|
|
|
blobs = list_firmware_blobs(fw_dir)
|
|
|
|
|
if not blobs:
|
|
|
|
|
return []
|
|
|
|
|
|
|
|
|
|
abs_img = os.path.abspath(ext4_img_path)
|
|
|
|
|
if not os.path.isfile(abs_img):
|
|
|
|
|
raise FileNotFoundError(f"ext4 image not found: {abs_img}")
|
|
|
|
|
abs_fw = os.path.abspath(fw_dir)
|
|
|
|
|
img_dir = os.path.dirname(abs_img)
|
|
|
|
|
img_name = os.path.basename(abs_img)
|
|
|
|
|
use_host = _have_host_e2fs()
|
|
|
|
|
|
|
|
|
|
target_dirs = ("/lib", "/lib/firmware", "/lib/firmware/mediatek", "/lib/firmware/mediatek/mt6797")
|
|
|
|
|
existing_files = set(debugfs_ls(abs_img, "lib/firmware/mediatek/mt6797")) if use_host else set()
|
|
|
|
|
|
|
|
|
|
def build_cmds(fw_prefix, check_exists):
|
|
|
|
|
cmds = []
|
|
|
|
|
for d in target_dirs:
|
|
|
|
|
if not check_exists or not _debugfs_path_exists(abs_img, d):
|
|
|
|
|
cmds.append(f"mkdir {d}")
|
|
|
|
|
cmds.append(f"set_inode_field {d} uid 0")
|
|
|
|
|
cmds.append(f"set_inode_field {d} gid 0")
|
|
|
|
|
cmds.append(f"set_inode_field {d} mode 040755")
|
|
|
|
|
for name, _host_p in blobs:
|
|
|
|
|
dst = f"/lib/firmware/mediatek/mt6797/{name}"
|
|
|
|
|
if not check_exists or name in existing_files:
|
|
|
|
|
cmds.append(f"rm {dst}")
|
|
|
|
|
cmds.append(f"write {fw_prefix}/{name} {dst}")
|
|
|
|
|
cmds.append(f"set_inode_field {dst} uid 0")
|
|
|
|
|
cmds.append(f"set_inode_field {dst} gid 0")
|
|
|
|
|
cmds.append(f"set_inode_field {dst} mode 0100644")
|
|
|
|
|
return "\n".join(cmds) + "\n"
|
|
|
|
|
|
|
|
|
|
if use_host:
|
|
|
|
|
subprocess.run(
|
|
|
|
|
["debugfs", "-w", abs_img],
|
|
|
|
|
input=build_cmds(abs_fw, True), text=True, check=True, stdout=subprocess.DEVNULL,
|
|
|
|
|
)
|
|
|
|
|
subprocess.run(["e2fsck", "-fn", abs_img], check=True, stdout=subprocess.DEVNULL)
|
|
|
|
|
else:
|
|
|
|
|
_run_docker_e2fs(
|
|
|
|
|
img_dir,
|
|
|
|
|
[(abs_fw, "/fw")],
|
|
|
|
|
f"debugfs -w '/img/{img_name}' >/dev/null 2>&1 && e2fsck -fn '/img/{img_name}' >/dev/null",
|
|
|
|
|
input_text=build_cmds("/fw", False),
|
|
|
|
|
)
|
|
|
|
|
return [name for name, _p in blobs]
|
|
|
|
|
|
|
|
|
|
|
2026-11-22 10:49:59 +02:00
|
|
|
def write_manifest(out_dir, found):
|
|
|
|
|
manifest = os.path.join(out_dir, "MANIFEST.sha256")
|
|
|
|
|
with open(manifest, "w") as f:
|
|
|
|
|
for name in sorted(found):
|
|
|
|
|
digest = sha256_file(found[name])
|
|
|
|
|
f.write(f"{digest} {name}\n")
|
|
|
|
|
return manifest
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def extract_firmware(source_path, out_dir):
|
|
|
|
|
if not os.path.exists(source_path):
|
|
|
|
|
raise FileNotFoundError(f"Source path not found: {source_path}")
|
|
|
|
|
|
|
|
|
|
if os.path.isdir(source_path):
|
|
|
|
|
found = extract_from_dir(source_path, out_dir)
|
|
|
|
|
else:
|
|
|
|
|
if shutil.which("debugfs") is None:
|
|
|
|
|
raise RuntimeError("'debugfs' (e2fsprogs) is required to extract firmware from ext4 images")
|
|
|
|
|
if is_sparse_image(source_path):
|
|
|
|
|
if shutil.which("simg2img") is None:
|
|
|
|
|
raise RuntimeError("'simg2img' (android-tools) is required for sparse system images")
|
|
|
|
|
with tempfile.TemporaryDirectory(prefix="geminux-fw-") as tmp:
|
|
|
|
|
raw_img = os.path.join(tmp, "system.raw.img")
|
|
|
|
|
subprocess.run(["simg2img", source_path, raw_img], check=True)
|
|
|
|
|
found = extract_from_ext4(raw_img, out_dir)
|
|
|
|
|
else:
|
|
|
|
|
found = extract_from_ext4(source_path, out_dir)
|
|
|
|
|
|
|
|
|
|
missing = [b for b in REQUIRED_BLOBS if b not in found]
|
|
|
|
|
if found:
|
|
|
|
|
write_manifest(out_dir, found)
|
|
|
|
|
return found, missing
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
|
parser = argparse.ArgumentParser(description="Extract MT6797 firmware blobs from stock Gemini system.img or directory.")
|
|
|
|
|
parser.add_argument("source", help="Path to stock system.img (raw/sparse ext4) or extracted directory")
|
|
|
|
|
parser.add_argument("-o", "--out-dir", default=os.path.join(
|
|
|
|
|
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
|
|
|
|
"firmware-cache", "mt6797"),
|
|
|
|
|
help="Destination directory (default: firmware-cache/mt6797)")
|
|
|
|
|
parser.add_argument("--allow-partial", action="store_true",
|
|
|
|
|
help="Exit 0 even if some required blobs were not found")
|
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
|
|
found, missing = extract_firmware(args.source, args.out_dir)
|
|
|
|
|
print(f"[fw-extract] Extracted {len(found)} file(s) into {args.out_dir}:")
|
|
|
|
|
for name in sorted(found):
|
|
|
|
|
print(f" - {name} ({os.path.getsize(found[name])} bytes)")
|
|
|
|
|
|
|
|
|
|
if missing:
|
|
|
|
|
print(f"[fw-extract] Warning: missing required blob(s): {', '.join(missing)}", file=sys.stderr)
|
|
|
|
|
if not args.allow_partial:
|
|
|
|
|
return 1
|
|
|
|
|
return 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
sys.exit(main())
|