#!/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" 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: is_req = name in REQUIRED_BLOBS is_spm = name.startswith(OPTIONAL_SPM_GLOB_PREFIX) and name.endswith(".bin") if not (is_req or is_spm): continue if name in found: 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): is_req = name in REQUIRED_BLOBS is_spm = name.startswith(OPTIONAL_SPM_GLOB_PREFIX) and name.endswith(".bin") if not (is_req or is_spm): continue if name in found: 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 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())