Files
geminux/flash-mtk.py
T

518 lines
19 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
"""Pure-Python MediaTek BROM/DA Flasher for Geminux (Gemini PDA MT6797X).
Uses vendored GPLv3 mtkclient transport (no proprietary MediaTek FlashTool).
"""
import argparse
import hashlib
import logging
import os
import shutil
import subprocess
import sys
import tempfile
import time
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
VENDOR_MTK = os.path.join(BASE_DIR, "vendor", "mtkclient")
SCRIPTS_DIR = os.path.join(BASE_DIR, "scripts")
for p in (VENDOR_MTK, SCRIPTS_DIR):
if p not in sys.path:
sys.path.insert(0, p)
from geminux_gpt import (
SECTOR_SIZE,
GPT_ARRAY_SECTORS,
PROTECTED_END_LBA,
build_geminux_gpts,
parse_primary_gpt,
)
# Critical factory/firmware/bootloader partitions blocked from accidental writes.
PROTECTED_PARTITIONS = frozenset({
"preloader",
"pgpt",
"sgpt",
"para",
"expdb",
"frp",
"nvcfg",
"nvdata",
"metadata",
"protect1",
"protect2",
"seccfg",
"oemkeystore",
"proinfo",
"md1img",
"md1dsp",
"md1arm7",
"md3img",
"scp1",
"scp2",
"nvram",
"lk",
"lk2",
"logo",
"tee1",
"tee2",
"keystore",
})
BACKUP_PARTITIONS = (
"proinfo",
"nvram",
"protect1",
"protect2",
"nvcfg",
"nvdata",
"seccfg",
"para",
"lk",
"lk2",
"tee1",
"tee2",
"md1img",
"md1dsp",
"md1arm7",
"md3img",
"scp1",
"scp2",
"boot",
"recovery",
)
SPARSE_MAGIC = b"\x3a\xff\x26\xed"
def sha256_bytes(data):
return hashlib.sha256(data).hexdigest()
def sha256_file(path):
h = hashlib.sha256()
with open(path, "rb") as f:
while True:
chunk = f.read(1048576)
if not chunk:
break
h.update(chunk)
return h.hexdigest()
def enforce_write_safety(partition_name, allow_protected=False):
"""Reject writes to protected MediaTek calibration/radio/bootloader partitions."""
if partition_name.lower() in PROTECTED_PARTITIONS and not allow_protected:
raise PermissionError(
f"Refusing to overwrite protected partition '{partition_name}'. "
"Pass --restore-backup or --danger-allow-protected only if you are certain."
)
def create_mtk_config(loader_path=None, preloader_path=None, verbose=False, wait_timeout=300):
from mtkclient.config.mtk_config import MtkConfig
from mtkclient.Library.Partitions.gpt import GptSettings
loglevel = logging.DEBUG if verbose else logging.INFO
cfg = MtkConfig(loglevel=loglevel, gui=None, guiprogress=None)
cfg.gpt_settings = GptSettings(0, 0, 0)
cfg.wait_timeout = wait_timeout
if loader_path:
if not os.path.isfile(loader_path):
raise FileNotFoundError(f"DA loader not found: {loader_path}")
cfg.loader = loader_path
if preloader_path and os.path.isfile(preloader_path):
cfg.preloader_filename = preloader_path
with open(preloader_path, "rb") as f:
cfg.preloader = f.read()
return cfg
def connect_mtk(loader_path=None, preloader_path=None, verbose=False, wait_timeout=300):
from mtkclient.Library.mtk_class import Mtk
from mtkclient.Library.DA.mtk_da_handler import DaHandler
loglevel = logging.DEBUG if verbose else logging.INFO
cfg = create_mtk_config(
loader_path=loader_path,
preloader_path=preloader_path,
verbose=verbose,
wait_timeout=wait_timeout,
)
mtk = Mtk(config=cfg, loglevel=loglevel)
da_handler = DaHandler(mtk, loglevel)
wait_desc = f"up to {wait_timeout}s" if wait_timeout > 0 else "indefinitely"
print(
f"[*] Waiting {wait_desc} for Gemini PDA on left USB-C port "
"(plug in powered-off PDA, or hold Esc + side Power for ~12s to force-reset)..."
)
mtk = da_handler.connect(mtk, BASE_DIR)
if mtk is None:
raise RuntimeError("Failed to establish MediaTek BROM/Preloader connection")
mtk = da_handler.configure_da(mtk)
if mtk is None:
raise RuntimeError("Failed to initialize MediaTek Download Agent (DA)")
return mtk, da_handler
def get_emmc_total_sectors(mtk):
flashsize = mtk.daloader.daconfig.storage.flashsize
if not flashsize:
raise RuntimeError("DA reported zero eMMC flash size")
return flashsize // SECTOR_SIZE
def run_backup(mtk, da_handler, backup_dir):
os.makedirs(backup_dir, exist_ok=True)
print(f"[*] Backing up Gemini PDA critical partitions into {backup_dir}...")
manifest = {}
# Dump primary GPT (34 sectors = 17 KiB) and backup GPT (last 33 sectors)
total_sectors = get_emmc_total_sectors(mtk)
pgpt_path = os.path.join(backup_dir, "pgpt.bin")
if not da_handler.da_rs(0, 2 + GPT_ARRAY_SECTORS, pgpt_path, "user", display=True):
raise RuntimeError("Failed to read primary GPT (pgpt)")
manifest["pgpt.bin"] = sha256_file(pgpt_path)
sgpt_lba = total_sectors - (GPT_ARRAY_SECTORS + 1)
sgpt_path = os.path.join(backup_dir, "sgpt.bin")
if not da_handler.da_rs(sgpt_lba, GPT_ARRAY_SECTORS + 1, sgpt_path, "user", display=True):
raise RuntimeError("Failed to read backup GPT (sgpt)")
manifest["sgpt.bin"] = sha256_file(sgpt_path)
# Dump EMMC_BOOT1 preloader
pre_path = os.path.join(backup_dir, "preloader.bin")
if da_handler.da_read("preloader", "boot1", pre_path, display=True) is not None and os.path.isfile(pre_path):
manifest["preloader.bin"] = sha256_file(pre_path)
for part in BACKUP_PARTITIONS:
out_file = os.path.join(backup_dir, f"{part}.img")
da_handler.da_read(part, "user", out_file, display=True)
if not os.path.isfile(out_file) or os.path.getsize(out_file) == 0:
raise RuntimeError(f"Backup failed or empty for partition '{part}'")
manifest[f"{part}.img"] = sha256_file(out_file)
# Sanity check nvram is non-zero
nvram_file = os.path.join(backup_dir, "nvram.img")
with open(nvram_file, "rb") as f:
sample = f.read(4096)
if sample == b"\x00" * len(sample):
print("[!] Warning: first 4 KiB of nvram.img is all zeros; verify backup before flashing!")
manifest_path = os.path.join(backup_dir, "MANIFEST.sha256")
with open(manifest_path, "w") as mf:
for name in sorted(manifest):
mf.write(f"{manifest[name]} {name}\n")
print(f"[+] Backup verified and written to {backup_dir} ({len(manifest)} files).")
def verify_written_partition(da_handler, part_name, expected_path):
expected_size = os.path.getsize(expected_path)
expected_hash = sha256_file(expected_path)
with tempfile.TemporaryDirectory(prefix="geminux-vfy-") as tmp:
rb = os.path.join(tmp, f"{part_name}.readback.img")
da_handler.da_read(part_name, "user", rb, offset=0, length=expected_size, display=False)
if not os.path.isfile(rb) or os.path.getsize(rb) != expected_size:
actual_sz = os.path.getsize(rb) if os.path.isfile(rb) else 0
raise RuntimeError(
f"Readback failed for '{part_name}': expected {expected_size} B, got {actual_sz} B"
)
actual_hash = sha256_file(rb)
if actual_hash != expected_hash:
raise RuntimeError(
f"Readback verification FAILED for '{part_name}': expected {expected_hash}, got {actual_hash}"
)
print(f"[+] Readback SHA-256 verified for '{part_name}' ({expected_size} bytes).")
def write_partition_checked(da_handler, part_name, img_path, verify=True, allow_protected=False):
enforce_write_safety(part_name, allow_protected=allow_protected)
if not os.path.isfile(img_path):
raise FileNotFoundError(f"Image not found: {img_path}")
found, res = da_handler.mtk.daloader.detect_partition(part_name, "user")
if not found or res is None:
raise RuntimeError(f"Partition '{part_name}' not found on device")
part_bytes = res.sectors * da_handler.config.pagesize
img_size = os.path.getsize(img_path)
if img_size > part_bytes:
raise RuntimeError(
f"Image '{img_path}' ({img_size} B) exceeds partition '{part_name}' ({part_bytes} B)"
)
print(f"[*] Flashing '{part_name}' from {img_path}...")
ok = da_handler.mtk.daloader.writeflash(
addr=res.sector * da_handler.config.pagesize,
length=part_bytes,
filename=img_path,
parttype="user",
display=True,
)
if not ok:
raise RuntimeError(f"Failed to write partition '{part_name}' from {img_path}")
if verify:
verify_written_partition(da_handler, part_name, img_path)
def load_extract_firmware():
import importlib.util
fw_path = os.path.join(SCRIPTS_DIR, "extract-vendor-fw.py")
sp = importlib.util.spec_from_file_location("extract_vendor_fw", fw_path)
mod = importlib.util.module_from_spec(sp)
sp.loader.exec_module(mod)
return mod.extract_firmware
def extract_fw_from_device(da_handler, fw_out_dir):
extract_firmware = load_extract_firmware()
with tempfile.TemporaryDirectory(prefix="geminux-sys-") as tmp:
sys_img = os.path.join(tmp, "system.img")
print("[*] Reading stock 'system' partition to extract Wi-Fi/BT/SPM firmware blobs...")
da_handler.da_read("system", "user", sys_img, display=True)
if not os.path.isfile(sys_img) or os.path.getsize(sys_img) == 0:
raise RuntimeError("Could not read stock 'system' partition")
found, missing = extract_firmware(sys_img, fw_out_dir)
if missing:
print(f"[!] Warning: missing firmware blobs from stock system: {', '.join(missing)}")
else:
print(f"[+] Extracted {len(found)} firmware blob(s) to {fw_out_dir}.")
def flash_full(mtk, da_handler, args):
backup_dir = args.backup_dir
if not args.skip_backup:
run_backup(mtk, da_handler, backup_dir)
elif not os.path.isdir(backup_dir) or not os.path.isfile(os.path.join(backup_dir, "nvram.img")):
raise RuntimeError("--skip-backup passed, but no valid nvram.img found in backup dir")
if not args.skip_firmware_extract:
req_check = os.path.join(args.firmware_dir, "WIFI_RAM_CODE_6797")
if not os.path.isfile(req_check):
extract_fw_from_device(da_handler, args.firmware_dir)
print("[*] Note: Rebuild rootfs image if extracted firmware was not yet bundled in images/geminux-rootfs.img.")
total_sectors = get_emmc_total_sectors(mtk)
pgpt_raw = da_handler.da_rs(0, 2 + GPT_ARRAY_SECTORS, "", "user", display=False)
if isinstance(pgpt_raw, bool) or not pgpt_raw:
with tempfile.TemporaryDirectory(prefix="geminux-gpt-") as tmp:
pfile = os.path.join(tmp, "pgpt.bin")
if not da_handler.da_rs(0, 2 + GPT_ARRAY_SECTORS, pfile, "user", display=False):
raise RuntimeError("Failed to read live primary GPT")
with open(pfile, "rb") as f:
pgpt_raw = f.read()
new_pgpt, new_sgpt, new_entries = build_geminux_gpts(
pgpt_raw, total_sectors, force_layout=args.force_gpt
)
linux_entry = next(e for e in new_entries if e.name == "linux")
boot2_entry = next(e for e in new_entries if e.name == "boot2")
print(
f"[*] Repartitioning eMMC ({total_sectors} sectors): "
f"linux={linux_entry.sectors * SECTOR_SIZE / (1024 ** 3):.2f} GiB @ LBA {linux_entry.first_lba}, "
f"boot2=16 MiB @ LBA {boot2_entry.first_lba}"
)
with tempfile.TemporaryDirectory(prefix="geminux-newgpt-") as tmp:
pgpt_out = os.path.join(tmp, "pgpt.new.bin")
sgpt_out = os.path.join(tmp, "sgpt.new.bin")
with open(pgpt_out, "wb") as f:
f.write(new_pgpt)
with open(sgpt_out, "wb") as f:
f.write(new_sgpt)
# Write Primary GPT (LBA 0..33) & Backup GPT (end of disk)
if not da_handler.da_wo(0, len(new_pgpt), pgpt_out, "user"):
raise RuntimeError("Failed writing updated primary GPT")
sgpt_byte_off = (total_sectors - (GPT_ARRAY_SECTORS + 1)) * SECTOR_SIZE
if not da_handler.da_wo(sgpt_byte_off, len(new_sgpt), sgpt_out, "user"):
raise RuntimeError("Failed writing updated backup GPT")
# Mandatory readback check on written GPTs
rb_pgpt = os.path.join(tmp, "pgpt.rb.bin")
da_handler.da_rs(0, 2 + GPT_ARRAY_SECTORS, rb_pgpt, "user", display=False)
with open(rb_pgpt, "rb") as f:
if f.read(len(new_pgpt)) != new_pgpt:
raise RuntimeError("Primary GPT readback verification FAILED!")
print("[+] Updated GPT readback verified.")
boot_img = os.path.join(args.images_dir, "boot-geminux.img")
rec_img = os.path.join(args.images_dir, "recovery-geminux.img")
root_img = os.path.join(args.images_dir, "geminux-rootfs.img")
write_partition_checked(da_handler, "boot", boot_img, verify=True)
write_partition_checked(da_handler, "recovery", rec_img, verify=True)
write_partition_checked(da_handler, "boot2", boot_img, verify=True)
# Convert sparse rootfs if needed before writing to 'linux'
with open(root_img, "rb") as rf:
is_sparse = rf.read(4) == SPARSE_MAGIC
if is_sparse:
if shutil.which("simg2img") is None:
raise RuntimeError("simg2img is required to unsparse geminux-rootfs.img")
with tempfile.TemporaryDirectory(prefix="geminux-rawroot-") as tmp:
raw_root = os.path.join(tmp, "linux.raw.img")
subprocess.run(["simg2img", root_img, raw_root], check=True)
write_partition_checked(da_handler, "linux", raw_root, verify=False)
else:
write_partition_checked(da_handler, "linux", root_img, verify=False)
print("[+] Full Geminux installation complete!")
def flash_kernel_only(da_handler, args):
boot_img = os.path.join(args.images_dir, "boot-geminux.img")
rec_img = os.path.join(args.images_dir, "recovery-geminux.img")
write_partition_checked(da_handler, "boot", boot_img, verify=True)
write_partition_checked(da_handler, "boot2", boot_img, verify=True)
if os.path.isfile(rec_img):
write_partition_checked(da_handler, "recovery", rec_img, verify=True)
print("[+] Kernel/recovery slots updated cleanly.")
def restore_backup(mtk, da_handler, backup_dir):
if not os.path.isdir(backup_dir):
raise FileNotFoundError(f"Backup directory not found: {backup_dir}")
pgpt_file = os.path.join(backup_dir, "pgpt.bin")
sgpt_file = os.path.join(backup_dir, "sgpt.bin")
if os.path.isfile(pgpt_file):
da_handler.da_wo(0, os.path.getsize(pgpt_file), pgpt_file, "user")
if os.path.isfile(sgpt_file):
total_sectors = get_emmc_total_sectors(mtk)
sgpt_off = (total_sectors - (GPT_ARRAY_SECTORS + 1)) * SECTOR_SIZE
da_handler.da_wo(sgpt_off, os.path.getsize(sgpt_file), sgpt_file, "user")
for name in sorted(os.listdir(backup_dir)):
if not name.endswith(".img"):
continue
part = name[:-4]
path = os.path.join(backup_dir, name)
write_partition_checked(da_handler, part, path, verify=False, allow_protected=True)
print(f"[+] Restored backup from {backup_dir}.")
def finish_da_session(mtk, reboot=False):
"""Cleanly exit DA mode by rebooting to OS (bootmode=1) or powering off (bootmode=0)."""
state_file = os.path.join(getattr(mtk.config, "hwparam_path", "."), ".state")
if os.path.exists(state_file):
try:
os.remove(state_file)
except OSError:
pass
bootmode = 1 if reboot else 0
print("[*] Handing device back to bootloader (USB disconnect is expected)...")
try:
mtk.daloader.shutdown(bootmode=bootmode)
except Exception as exc:
logging.debug("DA shutdown handshake raised %s", exc)
try:
mtk.port.close()
except Exception:
pass
def build_arg_parser():
p = argparse.ArgumentParser(
description="Geminux pure-Linux MediaTek BROM/DA Flasher for Planet Computers Gemini PDA (x27)"
)
mode = p.add_mutually_exclusive_group()
mode.add_argument("--flash-full", action="store_true",
help="Backup device, repartition full eMMC for Geminux, and flash all images (default)")
mode.add_argument("--only-backup", action="store_true",
help="Only dump & verify GPT, nvram, bootloader, and radio partitions")
mode.add_argument("--extract-firmware", action="store_true",
help="Extract MT6797 Wi-Fi/BT/SPM blobs from device 'system' or --system-img")
mode.add_argument("--flash-kernel-only", action="store_true",
help="Update only boot, boot2, and recovery images without touching GPT or linux")
mode.add_argument("--restore-backup", metavar="DIR",
help="Restore GPT and backed-up partitions from DIR")
mode.add_argument("--reboot", action="store_true",
help="Connect to BROM/DA and trigger immediate device reboot")
mode.add_argument("--poweroff", action="store_true",
help="Connect to BROM/DA and cleanly power off out of DA mode")
p.add_argument("--backup-dir", default=os.path.join(BASE_DIR, "backup", time.strftime("%Y%m%d-%H%M%S")),
help="Directory for partition backups")
p.add_argument("--images-dir", default=os.path.join(BASE_DIR, "images"),
help="Directory containing boot-geminux.img, recovery-geminux.img, geminux-rootfs.img")
p.add_argument("--firmware-dir", default=os.path.join(BASE_DIR, "firmware-cache", "mt6797"),
help="Directory for extracted MT6797 firmware blobs")
p.add_argument("--system-img", help="Local Android system.img file for --extract-firmware")
p.add_argument("--da", help="Optional custom MediaTek DA binary path (e.g. MTK_AllInOne_DA.bin)")
p.add_argument("--preloader", help="Optional preloader binary path for DRAM init")
p.add_argument("--skip-backup", action="store_true", help="Skip backup if already taken in --backup-dir")
p.add_argument("--skip-firmware-extract", action="store_true", help="Skip automatic firmware extraction")
p.add_argument("--force-gpt", action="store_true", help="Allow repartitioning unrecognized GPT layouts")
p.add_argument("--no-reboot", action="store_true",
help="Power off instead of auto-rebooting after flashing")
p.add_argument("--wait-timeout", type=int, default=300,
help="Seconds to wait for MediaTek BROM/Preloader USB connection (default: 300, 0 = infinite)")
p.add_argument("-v", "--verbose", action="store_true", help="Verbose USB/DA protocol logging")
return p
def main():
parser = build_arg_parser()
args = parser.parse_args()
if args.extract_firmware and args.system_img:
extract_firmware = load_extract_firmware()
found, missing = extract_firmware(args.system_img, args.firmware_dir)
print(f"[+] Extracted {len(found)} file(s) from {args.system_img} to {args.firmware_dir}.")
if missing:
print(f"[!] Missing required blobs: {', '.join(missing)}", file=sys.stderr)
return 1
return 0
mtk, da_handler = connect_mtk(
loader_path=args.da,
preloader_path=args.preloader,
verbose=args.verbose,
wait_timeout=args.wait_timeout,
)
finished = False
try:
if args.reboot:
finish_da_session(mtk, reboot=True)
print("[+] Triggering device reboot...")
finished = True
elif args.poweroff:
finish_da_session(mtk, reboot=False)
print("[+] Powered off out of DA mode.")
finished = True
elif args.only_backup:
run_backup(mtk, da_handler, args.backup_dir)
finish_da_session(mtk, reboot=False)
print("[+] Powered off out of DA mode.")
finished = True
elif args.extract_firmware:
extract_fw_from_device(da_handler, args.firmware_dir)
finish_da_session(mtk, reboot=False)
print("[+] Powered off out of DA mode.")
finished = True
elif args.flash_kernel_only:
flash_kernel_only(da_handler, args)
finish_da_session(mtk, reboot=not args.no_reboot)
print("[+] Powered off out of DA mode." if args.no_reboot else "[+] Triggering device reboot...")
finished = True
elif args.restore_backup:
restore_backup(mtk, da_handler, args.restore_backup)
finish_da_session(mtk, reboot=not args.no_reboot)
print("[+] Powered off out of DA mode." if args.no_reboot else "[+] Triggering device reboot...")
finished = True
else:
flash_full(mtk, da_handler, args)
finish_da_session(mtk, reboot=not args.no_reboot)
print("[+] Powered off out of DA mode." if args.no_reboot else "[+] Triggering device reboot...")
finished = True
finally:
if not finished:
try:
mtk.port.close()
except Exception:
pass
return 0
if __name__ == "__main__":
sys.exit(main())