#!/usr/bin/env python3 """Automated Qualcomm EDL Sahara/Firehose Flasher for Bananarchy Linux (MSM8909).""" import argparse import os import re import subprocess import sys import tempfile import time import usb.core import usb.util BASE_DIR = os.path.dirname(os.path.abspath(__file__)) DEFAULT_USER_PASSWORD = os.environ.get("BANANARCHY_USER_PASSWORD", "147147") DEFAULT_USB_IO_TIMEOUT_SEC = 30 # The EDL client library is vendored under vendor/edl so a clean clone can # flash without any manual download. A local edl/ checkout takes precedence # for development, and BANANARCHY_EDL_DIR overrides both. EDL_DIR = os.environ.get("BANANARCHY_EDL_DIR", "") if not EDL_DIR: local_edl = os.path.join(BASE_DIR, "edl") vendor_edl = os.path.join(BASE_DIR, "vendor", "edl") EDL_DIR = local_edl if os.path.isfile(os.path.join(local_edl, "Library", "usb.py")) else vendor_edl if not os.path.isfile(os.path.join(EDL_DIR, "Library", "usb.py")): sys.exit("Error: the EDL client library is missing from " + EDL_DIR) sys.path.insert(0, EDL_DIR) from Library.usb import usb_class from Library.gpt import gpt from Library.sahara import qualcomm_sahara from Library.firehose import qualcomm_firehose, xmlparser DEVICE_LABELS = { "nokia-argon": "Nokia 8110 4G (nokia-argon)", "nokia-beatles": "Nokia 2720 Flip (nokia-beatles)", "nokia-coconut": "Nokia 800 Tough (nokia-coconut)", "nokia-sparkler": "Nokia 8000 4G (nokia-sparkler)", "nokia-leo": "Nokia 6300 4G (nokia-leo)", } DEVICE_ALIASES = { "argon": "nokia-argon", "beatles": "nokia-beatles", "coconut": "nokia-coconut", "nokia-tough": "nokia-coconut", "tough": "nokia-coconut", "sparkler": "nokia-sparkler", "leo": "nokia-leo", } # Firehose programmers are signed for one root of trust, so the PBL rejects a # mismatched one in Sahara. Never silently fall back to the 8110 programmer # for a different target; --loader is the explicit escape hatch. # Identities below were read from the attestation certificates embedded in # each .mbn (see --list-loaders). 8k.mbn is signed Nokia_leo but covers both # MSM8909 phones; 2720v.mbn is signed Nokia_bts_us, the 2720 Flip US variant. DEVICE_LOADERS = { "nokia-argon": "8110.mbn", # legacy generic MSM8905 programmer "nokia-beatles": "2720.mbn", # Nokia_beatles "nokia-coconut": "800t.mbn", # Nokia_coconut "nokia-sparkler": "8k.mbn", # Nokia_leo root, shared with 6300 4G "nokia-leo": "8k.mbn", # Nokia_leo } DEVICE_LOADER_VARIANTS = { "nokia-beatles": {"us": "2720v.mbn"}, # Nokia_bts_us, 2720 Flip US variant } DEVICE_LOADER_IDENTITIES = { "nokia-argon": "", "nokia-beatles": "Nokia_beatles", "nokia-coconut": "Nokia_coconut", "nokia-sparkler": "Nokia_leo", "nokia-leo": "Nokia_leo", } VARIANT_LOADER_IDENTITIES = { ("nokia-beatles", "us"): "Nokia_bts_us", } # A failed boot can leave the PBL in Sahara on 900e (QHSUSB_BULK) instead of # the usual 9008 (QDLoader); 9006 is the diag/DLOAD variant. Probe all three # so a power-cycle is not needed just because the PID changed. EDL_PIDS = (0x9008, 0x900E, 0x9006) # On nokia-sparkler (8000 4G) and nokia-leo (6300 4G), * (gpio90) and # # (pm8941_resin) wire to Volume Up + Volume Down in SBL1/aboot, so holding # * + # while plugging in USB enters EDL (instead of D-Pad Up + D-Pad Down). EDL_STAR_HASH_DEVICES = ("nokia-sparkler", "nokia-leo") # images/boot-lk2nd-nokia-beatles.img is built from upstream lk2nd source plus # bootloader/lk2nd/nokia-beatles.patch (see bootloader/lk2nd/README.md). It has # a dedicated QCDT DTB for the exact stock 2720 IDs (0x14b/0x1000b/0x100), a # /lk2nd/nokia-beatles device node with the three GC9305 panel init streams, # and cmdline lk2nd.compatible=nokia,beatles. aboot hands off to lk2nd, lk2nd # brings up the 240x320 RGB565 main panel and boots Bananarchy from userdata # via extlinux.conf. This is the default path on nokia-beatles. BOOT_IMAGE_DEVICES = ("nokia-beatles", "nokia-coconut", "nokia-sparkler") # Stock 2720/800 Tough/8000 4G/6300 4G aboot has secure boot enabled and devinfo is locked. Writing a # custom boot.img (lk2nd or mainline) is rejected unless devinfo.is_unlocked=1. UNLOCK_DEFAULT_DEVICES = ("nokia-beatles", "nokia-coconut", "nokia-sparkler", "nokia-leo") DEVINFO_MAGIC = b"ANDROID-BOOT!" DEVINFO_UNLOCKED_OFFSET = 13 DEVINFO_TAMPERED_OFFSET = 14 # aboot reads is_allow_unlock from the last byte of the "config" partition. # VB1 enables USE_RPMB_FOR_DEVINFO, so only "fastboot oem unlock-go" can write # the authoritative RPMB devinfo; eMMC devinfo alone is not enough. OEM_UNLOCK_PARTITIONS = ("config", "frp") OEM_UNLOCK_FLAG_OFFSET = -1 # Rebuild the source port with scripts/build-lk2nd-beatles.sh or # scripts/build-lk2nd-coconut.sh after changing bootloader/lk2nd patches; never # binary-patch the prebuilt bootloader/lk2nd-msm8909.img. BEATLES_LK2ND_IMAGE = "images/boot-lk2nd-nokia-beatles-display.img" COCONUT_LK2ND_IMAGE = "images/boot-lk2nd-nokia-coconut-display.img" SPARKLER_LK2ND_IMAGE = "images/boot-lk2nd-nokia-sparkler-display.img" DEVICE_LK2ND_IMAGES = { "nokia-beatles": BEATLES_LK2ND_IMAGE, "nokia-coconut": COCONUT_LK2ND_IMAGE, "nokia-sparkler": SPARKLER_LK2ND_IMAGE, } BOOT_METHOD_PARTITIONS = { "lk2nd": "boot", # lk2nd image into boot "boot": "boot", # raw Bananarchy boot.img into boot (normal power-on) "recovery": "recovery", # boot.img into recovery (Volume Up) "both": "boot", # boot.img into boot and recovery (covers either path) } BOOT_METHOD_TARGETS = { "lk2nd": ("boot",), "boot": ("boot",), "recovery": ("recovery",), "both": ("boot", "recovery"), } DIAG_PARTITIONS = ( "devinfo", "config", "misc", "frp", "aboot", "abootbak", "sbl1", "sbl1bak", "tz", "tzbak", "rpm", "rpmbak", "hyp", "hypbak", "sec", "keystore", "cmnlib", "cmnlib64", "devcfg", "keymaster", "prov", "limits", "toolsfv", "logfs", "dip", "mdtp", "cdt", "ddr", "sp", "uefivarstore", ) def _fb_read_status(ep_in, timeout_ms=15000): while True: resp = bytes(ep_in.read(64, timeout=timeout_ms)) if resp.startswith(b"INFO"): continue return resp def _fb_send_edl(fb_dev): cfg = fb_dev.get_active_configuration() intf = cfg[(0, 0)] ep_out = usb.util.find_descriptor( intf, custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_OUT, ) ep_in = usb.util.find_descriptor( intf, custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_IN, ) if ep_out is None or ep_in is None: return False for cmd in (b"oem reboot-edl", b"oem edl"): ep_out.write(cmd, timeout=5000) try: resp = _fb_read_status(ep_in, timeout_ms=5000) if resp.startswith(b"OKAY"): break except Exception: break return True def _fb_upgrade_lk2nd_and_edl(fb_dev): lk2nd_path = os.path.join(BASE_DIR, "bootloader", "lk2nd-msm8909.img") if not os.path.isfile(lk2nd_path): return with open(lk2nd_path, "rb") as f: lk2nd_data = f.read() print("[*] Updating lk2nd on boot partition via Fastboot to enable EDL reboot...") cfg = fb_dev.get_active_configuration() intf = cfg[(0, 0)] ep_out = usb.util.find_descriptor( intf, custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_OUT, ) ep_in = usb.util.find_descriptor( intf, custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_IN, ) if ep_out is None or ep_in is None: return ep_out.write(f"download:{len(lk2nd_data):08x}".encode("ascii"), timeout=5000) resp = _fb_read_status(ep_in, timeout_ms=5000) if not resp.startswith(b"DATA"): return chunk_sz = 16384 for off in range(0, len(lk2nd_data), chunk_sz): ep_out.write(lk2nd_data[off:off + chunk_sz], timeout=15000) if not _fb_read_status(ep_in, timeout_ms=15000).startswith(b"OKAY"): return ep_out.write(b"flash:boot", timeout=5000) if not _fb_read_status(ep_in, timeout_ms=30000).startswith(b"OKAY"): return ep_out.write(b"reboot-bootloader", timeout=5000) try: _fb_read_status(ep_in, timeout_ms=5000) except Exception: pass usb.util.dispose_resources(fb_dev) time.sleep(2.0) for _ in range(20): new_fb = usb.core.find(idVendor=0x18D1, idProduct=0xD00D) if new_fb is not None: time.sleep(0.3) _fb_send_edl(new_fb) usb.util.dispose_resources(new_fb) return time.sleep(0.5) _fb_edl_kicked = False def try_kick_into_edl(): global _fb_edl_kicked try: res = subprocess.run( ["adb", "get-state"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, timeout=5, ) if res.returncode == 0 and "device" in res.stdout: print("[*] Detected device in ADB mode. Sending 'adb reboot edl'...") subprocess.run(["adb", "reboot", "edl"], timeout=10) return except Exception: pass # Direct USB Fastboot check (18d1:d00d) via pyusb so host fastboot CLI is optional try: fb_dev = usb.core.find(idVendor=0x18D1, idProduct=0xD00D) if fb_dev is not None: print("[*] Detected device in Fastboot mode (18d1:d00d). Sending 'oem reboot-edl'...") _fb_send_edl(fb_dev) usb.util.dispose_resources(fb_dev) return except Exception: pass try: res = subprocess.run( ["fastboot", "devices"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, timeout=5, ) if res.returncode == 0 and res.stdout.strip(): print("[*] Detected device in Fastboot mode. Sending 'fastboot oem reboot-edl'...") rc = subprocess.run(["fastboot", "oem", "reboot-edl"], timeout=10) if rc.returncode != 0: subprocess.run(["fastboot", "oem", "edl"], timeout=10) except Exception: pass def edl_button_combo_hint(device=""): if device in EDL_STAR_HASH_DEVICES: return "* + #" return "D-Pad Up + D-Pad Down" def wait_for_edl_usb(vid, pids, device_label, timeout_sec=0, device="", usb_timeout_ms=DEFAULT_USB_IO_TIMEOUT_SEC * 1000): if isinstance(pids, int): pids = (pids,) pids = tuple(pids) print( "[*] Waiting for %s in EDL mode (USB %04x:%s Qualcomm Sahara/Firehose)..." % (device_label, vid, "/".join("%04x" % pid for pid in pids)) ) print(" To enter EDL mode on the phone, use one of:") print(" 1) From lk2nd Fastboot menu, select 'EDL' (or connect in Fastboot mode)") print(f" 2) Power off, hold {edl_button_combo_hint(device)}, and plug in USB") print(" 3) Plug in via an EDL deep-flash cable") print(" 4) Run 'adb reboot edl' or 'fastboot oem reboot-edl'") try_kick_into_edl() start_ts = time.time() dots = 0 while True: for pid in pids: if usb.core.find(idVendor=vid, idProduct=pid) is None: continue cdc = usb_class(vid=vid, pid=pid, timeout_ms=usb_timeout_ms) try: cdc.connected = cdc.connect() except usb.core.USBError as exc: if getattr(exc, "errno", None) == 13: print( "\n[!] Error: USB permission denied when opening 05c6:%04x. " "Please run via sudo (e.g. sudo ./flash-edl.sh)." % pid ) sys.exit(1) continue if cdc.connected: if dots > 0: sys.stdout.write("\n") print("[+] USB EDL device connected (05c6:%04x)." % pid) return cdc if timeout_sec > 0 and (time.time() - start_ts) >= timeout_sec: if dots > 0: sys.stdout.write("\n") print(f"[!] Timed out after {timeout_sec} seconds waiting for EDL device.") sys.exit(1) if dots > 0 and dots % 100 == 0: try_kick_into_edl() if dots % 20 == 0: sys.stdout.write(".") sys.stdout.flush() dots += 1 if dots % 800 == 0: sys.stdout.write("\n") time.sleep(0.05) return cdc def find_partition(partentries, name): for entry in partentries: if entry.name == name: return entry return None def verify_partition(fh, lun, part, source_path): """Read back a written partition and compare its leading bytes. Returns (ok, detail). A mismatch means the Sahara/Firehose session did not actually commit the image, which is the usual cause of a phone that keeps booting the stock image. """ size = os.path.getsize(source_path) tmp_path = "" try: with tempfile.NamedTemporaryFile(prefix="verify-partition-", delete=False) as tf: tmp_path = tf.name res = fh.cmd_read(lun, part.sector, part.sectors, tmp_path, Display=False) if res == "" or not os.path.exists(tmp_path): return False, "read-back failed" with open(source_path, "rb") as src, open(tmp_path, "rb") as got: if src.read(size) != got.read(size): return False, "read-back differs from the source image" return True, "read-back matches" except Exception as exc: # noqa: BLE001 - report the USB/Firehose error return False, "read-back error: %s" % exc finally: if tmp_path and os.path.exists(tmp_path): os.unlink(tmp_path) def write_partition(fh, lun, part, filepath): size = os.stat(filepath).st_size sector_size = fh.cfg.SECTOR_SIZE_IN_BYTES sectors = size // sector_size if (size % sector_size) > 0: sectors += 1 if sectors > part.sectors: print( f"[!] Error: {filepath} requires {sectors} sectors, " f"but partition '{part.name}' only has {part.sectors} sectors." ) return False print( f"[*] Flashing '{part.name}' (start sector {part.sector}, " f"{sectors}/{part.sectors} sectors, {size / (1024 * 1024):.1f} MiB) " f"from {filepath}..." ) ok = fh.cmd_write(lun, part.sector, filepath, Display=True) if not ok: print(f"[!] Failed writing {filepath} to partition '{part.name}'.") return False print(f"[+] Successfully flashed '{part.name}'.") return True def dump_partition(fh, lun, part, filepath): size_mib = (part.sectors * fh.cfg.SECTOR_SIZE_IN_BYTES) / (1024 * 1024) print( f"[*] Backing up '{part.name}' (sector {part.sector}, " f"{part.sectors} sectors, {size_mib:.2f} MiB) -> {filepath}..." ) res = fh.cmd_read(lun, part.sector, part.sectors, filepath, Display=True) if res == "" or not os.path.exists(filepath) or os.stat(filepath).st_size == 0: print(f"[!] Failed backing up partition '{part.name}'.") return False print(f"[+] Saved backup: {filepath}") return True def dump_diagnostics(fh, lun, partentries, backup_dir): """Copy small bootloader/config partitions for offline secure-boot analysis.""" os.makedirs(backup_dir, exist_ok=True) max_sectors = 4096 for pname in DIAG_PARTITIONS: part = find_partition(partentries, pname) if not part: continue sectors = min(part.sectors, max_sectors) dest = os.path.join(backup_dir, f"diag-{pname}.img") print(f"[*] Diagnostic read '{pname}' ({sectors} sectors) -> {dest}...") res = fh.cmd_read(lun, part.sector, sectors, dest, Display=False) if res == "" or not os.path.isfile(dest) or os.stat(dest).st_size == 0: print(f"[!] Warning: diagnostic read of '{pname}' failed.") else: print(f"[+] Saved diagnostic: {dest}") def unlock_devinfo(fh, lun, partentries, backup_dir, device): """Set devinfo.is_unlocked=1 so aboot skips signed-boot verification.""" part = find_partition(partentries, "devinfo") if not part: print("[!] Warning: 'devinfo' partition not found; cannot unlock bootloader.") return False os.makedirs(backup_dir, exist_ok=True) locked_backup = os.path.join(backup_dir, f"devinfo-locked-{device}.img") tmp_path = "" try: with tempfile.NamedTemporaryFile(prefix="devinfo-", delete=False) as tf: tmp_path = tf.name res = fh.cmd_read(lun, part.sector, part.sectors, tmp_path, Display=False) if res == "" or not os.path.exists(tmp_path) or os.stat(tmp_path).st_size == 0: print("[!] Error: failed to read 'devinfo' for unlocking.") return False data = bytearray(open(tmp_path, "rb").read()) if bytes(data[:len(DEVINFO_MAGIC)]) != DEVINFO_MAGIC: print("[!] Error: 'devinfo' magic mismatch; refusing to modify it.") return False with open(locked_backup, "wb") as handle: handle.write(data) print(f"[+] Saved locked devinfo backup: {locked_backup}") data[DEVINFO_UNLOCKED_OFFSET] = 1 data[DEVINFO_TAMPERED_OFFSET] = 0 with open(tmp_path, "wb") as handle: handle.write(data) print("[*] Setting devinfo: is_unlocked=1, is_tampered=0 ...") if not fh.cmd_write(lun, part.sector, tmp_path, Display=True): print("[!] Error: failed to write unlocked devinfo.") return False print("[+] Bootloader unlock flag written to 'devinfo'.") return True except Exception as exc: # noqa: BLE001 - report Firehose error print(f"[!] Error unlocking devinfo: {exc}") return False finally: if tmp_path and os.path.exists(tmp_path): os.unlink(tmp_path) def enable_oem_unlock(fh, lun, partentries, backup_dir, device): """Set the last byte of config/frp so aboot allows 'oem unlock-go'.""" part = None for name in OEM_UNLOCK_PARTITIONS: part = find_partition(partentries, name) if part: break if not part: print("[!] Warning: neither 'config' nor 'frp' partition found; " "cannot enable OEM unlock.") return False os.makedirs(backup_dir, exist_ok=True) backup = os.path.join(backup_dir, f"{part.name}-locked-{device}.img") tmp_path = "" try: with tempfile.NamedTemporaryFile(prefix="oem-unlock-", delete=False) as tf: tmp_path = tf.name res = fh.cmd_read(lun, part.sector, part.sectors, tmp_path, Display=False) if res == "" or not os.path.exists(tmp_path) or os.stat(tmp_path).st_size == 0: print(f"[!] Error: failed to read '{part.name}' for OEM unlock.") return False data = bytearray(open(tmp_path, "rb").read()) with open(backup, "wb") as handle: handle.write(data) print(f"[+] Saved original {part.name} backup: {backup}") data[OEM_UNLOCK_FLAG_OFFSET] |= 1 with open(tmp_path, "wb") as handle: handle.write(data) print(f"[*] Enabling OEM unlock in '{part.name}' (last byte |= 1)...") if not fh.cmd_write(lun, part.sector, tmp_path, Display=True): print(f"[!] Error: failed to write '{part.name}'.") return False # Read back and confirm the flag persisted. res = fh.cmd_read(lun, part.sector, part.sectors, tmp_path, Display=False) if res == "" or not os.path.exists(tmp_path): print(f"[!] Warning: could not read back '{part.name}'.") elif not (open(tmp_path, "rb").read()[OEM_UNLOCK_FLAG_OFFSET] & 1): print(f"[!] Error: OEM unlock flag did not persist in '{part.name}'.") return False print(f"[+] OEM unlock enabled in '{part.name}'.") return True except Exception as exc: # noqa: BLE001 print(f"[!] Error enabling OEM unlock: {exc}") return False finally: if tmp_path and os.path.exists(tmp_path): os.unlink(tmp_path) def loader_identity(path): """Return the Nokia_ attestation name embedded in an .mbn.""" try: with open(path, "rb") as handle: data = handle.read(1024 * 1024) except OSError: return "" match = re.search(rb"Nokia_[A-Za-z0-9_]+", data) return match.group(0).decode("ascii", "replace") if match else "" def available_loaders(): loaders_dir = os.path.join(BASE_DIR, "bootloader", "loaders") if not os.path.isdir(loaders_dir): return [] return sorted( name for name in os.listdir(loaders_dir) if name.lower().endswith(".mbn") and os.path.isfile(os.path.join(loaders_dir, name)) ) def list_loaders(): loaders_dir = os.path.join(BASE_DIR, "bootloader", "loaders") names = available_loaders() print("Firehose programmers in %s:" % loaders_dir) if not names: print(" (none found)") for name in names: path = os.path.join(loaders_dir, name) ident = loader_identity(path) or "no embedded Nokia identity" users = [dev for dev, fn in DEVICE_LOADERS.items() if fn == name] for dev, variants in DEVICE_LOADER_VARIANTS.items(): for variant, fn in variants.items(): if fn == name: users.append("%s --variant %s" % (dev, variant)) note = "-> " + ", ".join(users) if users else "(unused: select with --loader)" print(" %-12s %9d bytes %-22s %s" % ( name, os.path.getsize(path), ident, note)) print("\nThe device default is chosen by --device / the positional target.") print("Use --variant us for a 2720 Flip US (Nokia_bts_us) device.") print("Use --loader PATH to select any programmer explicitly.") return 0 def resolve_default_loader(device="nokia-argon", variant=""): name = DEVICE_LOADERS.get(device, "8110.mbn") if variant: name = DEVICE_LOADER_VARIANTS.get(device, {}).get(variant, name) for cand in [ os.path.join(BASE_DIR, "bootloader", "loaders", name), os.path.join(BASE_DIR, name), ]: if os.path.isfile(cand): return cand return os.path.join(BASE_DIR, "bootloader", "loaders", name) def resolve_default_bootloader(): for cand in [ os.path.join(BASE_DIR, "bootloader", "lk2nd-msm8909.img"), os.path.join(BASE_DIR, "lk2nd-msm8909.img"), ]: if os.path.isfile(cand): return cand return os.path.join(BASE_DIR, "bootloader", "lk2nd-msm8909.img") def resolve_default_image(device): return os.path.join(BASE_DIR, "images", f"bananarchy-{device}.img") def resolve_wipe_system(method, no_wipe, wipe): """Zero the stock system superblock by default for every method. This is the original Bananarchy behavior: the stock KaiOS system must not be mountable when the phone is re-purposed. --no-wipe-system is the opt-out. """ if no_wipe: return False if wipe: return True return method in BOOT_METHOD_PARTITIONS def resolve_boot_method(device, explicit=""): if explicit: return explicit # lk2nd is the Android boot.img for every target. On the 2720 the # source-built port has a dedicated QCDT DTB for the exact stock # 0x14b/0x1000b/0x100 entry, so aboot accepts it, lk2nd initializes the # GC9305 main panel and boots Bananarchy from userdata via extlinux. return "lk2nd" def resolve_recovery_image(device): return os.path.join(BASE_DIR, "images", f"boot-bananarchy-{device}.img") def resolve_beatles_lk2nd_image(): return os.path.join(BASE_DIR, BEATLES_LK2ND_IMAGE) def resolve_device_lk2nd_image(device): rel = DEVICE_LK2ND_IMAGES.get(device, "") return os.path.join(BASE_DIR, rel) if rel else "" def parse_args(): parser = argparse.ArgumentParser( description="Automated EDL Flasher for Bananarchy Linux (MSM8909 / Sxmo)" ) valid_targets = list(DEVICE_LABELS.keys()) + list(DEVICE_ALIASES.keys()) parser.add_argument( "device_pos", nargs="?", choices=["sxmo"] + valid_targets, default=None, help="Target device to flash (default: nokia-argon)", ) parser.add_argument( "--device", choices=valid_targets, default="nokia-argon", help="Target MSM8909 device (default: nokia-argon)", ) parser.add_argument( "--image", default="", help="Explicit path to raw userdata image (overrides --device)", ) parser.add_argument( "--bootloader", default=resolve_default_bootloader(), help="Path to lk2nd boot image", ) parser.add_argument( "--loader", default=None, help="Path to Firehose programmer (.mbn); default: device-specific loader", ) parser.add_argument( "--list-loaders", action="store_true", help="List available Firehose programmers and their device mapping, then exit", ) parser.add_argument( "--method", choices=["lk2nd", "boot", "recovery", "both"], default="", help="Boot method (default: lk2nd for all targets). On nokia-beatles, " "nokia-coconut, and nokia-sparkler lk2nd is written to boot and lk2nd, " "mainline boot.img to recovery; both writes boot.img to boot and recovery", ) parser.add_argument( "--boot-image", default="", help="Standalone Android boot.img for recovery flashing " "(default: images/boot-bananarchy-.img)", ) parser.add_argument( "--lk2nd-image", default="", help="Override the nokia-beatles/nokia-coconut/nokia-sparkler lk2nd boot.img written to 'boot' " "(e.g. images/boot-lk2nd-nokia-sparkler-diagnostic.img for diagnostic logs)", ) parser.add_argument( "--variant", choices=["us"], default="", help="Hardware variant: 'us' selects the Nokia_bts_us programmer " "(2720v.mbn) for the 2720 Flip US variant", ) parser.add_argument( "--backup-dir", default=os.path.join(BASE_DIR, "backup"), help="Directory for partition backups (default: ./backup)", ) parser.add_argument( "--skip-backup", action="store_true", help="Skip backing up critical partitions before flashing", ) parser.add_argument( "--force-backup", action="store_true", help="Re-dump backup partitions even if backup files already exist", ) parser.add_argument( "--backup-modem", action="store_true", help="Also back up the 64 MiB modem partition into backup-dir", ) parser.add_argument( "--no-wipe-system", action="store_true", help="Keep the stock system superblock intact (opt-out of the default wipe)", ) parser.add_argument( "--verify", action="store_true", help="Read back the flashed boot/recovery partition and compare it " "(diagnoses a flash that never committed)", ) parser.add_argument( "--dump-diagnostics", action="store_true", help="Before flashing, read small bootloader/config partitions into " "backup/diag-*.img (helps diagnose secure boot / aboot state)", ) parser.add_argument( "--unlock-bootloader", action="store_true", help="Set devinfo.is_unlocked=1 (default on nokia-beatles/nokia-coconut/nokia-sparkler/nokia-leo; " "needed for locked stock aboot to accept an unsigned boot.img)", ) parser.add_argument( "--no-unlock-bootloader", action="store_true", help="Leave devinfo untouched (custom boot.img will likely be rejected)", ) parser.add_argument( "--enable-oem-unlock", action="store_true", help="Patch config/frp allow-unlock flag (default on nokia-beatles/nokia-coconut/nokia-sparkler/nokia-leo). " "Required before 'fastboot oem unlock-go' can write RPMB devinfo", ) parser.add_argument( "--no-enable-oem-unlock", action="store_true", help="Do not patch the config/frp allow-unlock flag", ) parser.add_argument( "--only-unlock", action="store_true", help="Only patch eMMC devinfo and config/frp and exit without flashing", ) parser.add_argument( "--only-backup", action="store_true", help="Back up GPT and stock partitions to --backup-dir and exit without modifying eMMC", ) parser.add_argument( "--wipe-system", action="store_true", help="Zero the stock system superblock (already the default; kept for compatibility)", ) parser.add_argument( "--no-reset", action="store_true", help="Do not reboot the phone automatically after flashing", ) parser.add_argument( "--timeout", type=int, default=0, help="Timeout in seconds while waiting for USB connection (0 = infinite)", ) parser.add_argument( "--usb-timeout", type=int, default=DEFAULT_USB_IO_TIMEOUT_SEC, help="Per-transfer USB bulk read/write timeout in seconds (default: 30)", ) parser.add_argument( "--vid", default="0x05C6", help="USB Vendor ID (default: 0x05C6)", ) parser.add_argument( "--pid", default="", help="USB Product ID (default: auto-detect 05c6:9008, 900e or 9006)", ) parser.add_argument( "--lun", type=int, default=0, help="Storage LUN number (default: 0)", ) return parser.parse_args() def main(): args = parse_args() if args.list_loaders: return list_loaders() raw_device = args.device_pos if args.device_pos and args.device_pos != "sxmo" else args.device device = DEVICE_ALIASES.get(raw_device, raw_device) device_label = DEVICE_LABELS.get(device, device) method = resolve_boot_method(device, args.method) boot_img = os.path.abspath(args.boot_image or resolve_recovery_image(device)) userdata_img = ( os.path.abspath(args.image) if args.image else os.path.abspath(resolve_default_image(device)) ) bootloader_img = os.path.abspath(args.bootloader) device_lk2nd_img = ( os.path.abspath(args.lk2nd_image or resolve_device_lk2nd_image(device)) if (args.lk2nd_image or device in DEVICE_LK2ND_IMAGES) else "" ) mainline_img = boot_img loader_mbn = os.path.abspath( args.loader or resolve_default_loader(device, args.variant)) backup_dir = os.path.abspath(args.backup_dir) unlock_bootloader = ( not args.no_unlock_bootloader and (args.unlock_bootloader or device in UNLOCK_DEFAULT_DEVICES) ) oem_unlock_enabled = ( not args.no_enable_oem_unlock and (args.enable_oem_unlock or device in UNLOCK_DEFAULT_DEVICES) ) print("============================================================") print(" Bananarchy Linux (MSM8909 / Sxmo) Automated EDL Flasher") print("============================================================") print(f" Target Device : {device_label}") print(f" Target UI : Sxmo (240x320 native, Multi-Mode T9)") print(f" Target Variant : {args.variant or 'default'}") print(f" Boot Method : {method}") wipe_system = resolve_wipe_system( method, args.no_wipe_system, args.wipe_system) print(f" Wipe System : {'yes' if wipe_system else 'no (--no-wipe-system)'}") print(f" Verify Writes : {'yes' if args.verify else 'no (--verify to enable)'}") print(f" Unlock Bootloader: {'yes (devinfo)' if unlock_bootloader else 'no'}") print(f" Enable OEM Unlock: {'yes (config/frp)' if oem_unlock_enabled else 'no'}") if args.only_backup: print(" Mode : backup only (no partitions modified)") elif args.only_unlock: print(" Mode : prepare unlock only (no images flashed)") if method in ("boot", "recovery", "both"): print(f" Boot Image : {boot_img}") print(f" Firehose Loader : {loader_mbn}") if os.path.isfile(loader_mbn) and os.path.getsize(loader_mbn) > 0: ident = loader_identity(loader_mbn) if ident: print(f" Firehose ID : {ident}") expected = VARIANT_LOADER_IDENTITIES.get( (device, args.variant), DEVICE_LOADER_IDENTITIES.get(device, "")) if expected and ident and ident != expected: print( "[!] Warning: %s is signed for %s, expected %s for %s. " "Verify on hardware or pass --loader." % ( os.path.basename(loader_mbn), ident, expected, device)) if method == "lk2nd" and device in DEVICE_LK2ND_IMAGES: print(f" LK2ND (boot) : {device_lk2nd_img} ({device} source port)") print(f" Boot Image (rec) : {mainline_img}") if not (method == "lk2nd" and device in DEVICE_LK2ND_IMAGES): print(f" Bootloader (boot): {bootloader_img}") print(f" System (userdata): {userdata_img}") print( f" Partition Backup: " f"{'disabled (--skip-backup)' if args.skip_backup else backup_dir}" ) print("============================================================") if not os.path.isfile(loader_mbn) or os.path.getsize(loader_mbn) == 0: print("[!] Error: Firehose programmer for %s not found or empty at: %s" % ( device, loader_mbn)) print(" Expected %s; available: %s" % ( os.path.basename(loader_mbn), ", ".join(available_loaders()) or "none")) print(" Run './flash-edl.sh --list-loaders' or pass --loader PATH.") sys.exit(1) if args.only_backup or args.only_unlock: required_files = [ ("Firehose programmer", loader_mbn), ] else: required_files = [ ("Firehose programmer", loader_mbn), ("System userdata image", userdata_img), ] if method in ("boot", "recovery", "both"): required_files.append(("Boot image", boot_img)) else: required_files.append(("lk2nd bootloader image", bootloader_img)) if method == "lk2nd" and device in DEVICE_LK2ND_IMAGES: required_files.append((f"{device} lk2nd image", device_lk2nd_img)) required_files.append(("Recovery boot image", mainline_img)) for label, path in required_files: if not os.path.isfile(path) or os.stat(path).st_size == 0: print(f"[!] Error: {label} not found or empty at: {path}") sys.exit(1) vid = int(args.vid, 16) pids = [int(args.pid, 16)] if args.pid else list(EDL_PIDS) cdc = wait_for_edl_usb( vid, pids, device_label, timeout_sec=args.timeout, device=device, usb_timeout_ms=max(1, args.usb_timeout) * 1000, ) sahara = qualcomm_sahara(cdc) with open(loader_mbn, "rb") as rf: sahara.programmer = rf.read() mode = sahara.connect() print(f"[*] Device protocol mode: {mode}") if mode == "Sahara": sahara.info() print(f"[*] Uploading Firehose programmer ({os.path.basename(loader_mbn)})...") if not sahara.upload_firehoseloader(): print("[!] Error: Failed to upload Firehose programmer via Sahara.") sys.exit(1) time.sleep(0.3) mode = "Firehose" print("[+] Firehose programmer uploaded and active.") elif mode == "Firehose": if len(sahara.programmer) > 4 and sahara.programmer[:4] == b"\x7fELF": sahara.bit64 = sahara.programmer[4] == 2 else: sahara.bit64 = False print("[+] Device is already in Firehose mode.") else: print( f"[!] Error: Could not establish Sahara or Firehose mode (got '{mode}'). " "Please power-cycle the phone back into EDL mode and retry." ) sys.exit(1) xml = xmlparser() cfg = qualcomm_firehose.cfg() cfg.MemoryName = "eMMC" cfg.ZLPAwareHost = 1 cfg.SkipStorageInit = False cfg.SkipWrite = False cfg.MaxPayloadSizeToTargetInBytes = 1048576 cfg.SECTOR_SIZE_IN_BYTES = 512 cfg.bit64 = sahara.bit64 fh = qualcomm_firehose(cdc, xml, cfg) print("[*] Connecting to Firehose storage controller...") fh.connect(0) print("[*] Reading GPT partition table from eMMC...") gpt_sectors = 0x4000 // fh.cfg.SECTOR_SIZE_IN_BYTES gpt_raw = fh.cmd_read_buffer(args.lun, 0, gpt_sectors, Display=False) if not gpt_raw: print("[!] Error: Failed to read GPT partition table from device.") sys.exit(1) guid_gpt = gpt() if not guid_gpt.parse(gpt_raw, fh.cfg.SECTOR_SIZE_IN_BYTES): print("[!] Error: Failed to parse GPT partition table.") sys.exit(1) boot_part = find_partition(guid_gpt.partentries, "boot") recovery_part = find_partition(guid_gpt.partentries, "recovery") userdata_part = find_partition(guid_gpt.partentries, "userdata") system_part = find_partition(guid_gpt.partentries, "system") target_names = BOOT_METHOD_TARGETS[method] if method == "lk2nd" and device in DEVICE_LK2ND_IMAGES: # Match the 8110/Argon shape: lk2nd in boot, mainline boot.img in # recovery (Volume Up fallback). Also refresh the separate 512 KiB # lk2nd partition so "Reboot to loader" cannot chain-load a stale # image without the visible menu. target_names = ("boot", "recovery", "lk2nd") target_parts = [] for name in target_names: part = find_partition(guid_gpt.partentries, name) if not part: if name == "lk2nd" and method == "lk2nd" and device in DEVICE_LK2ND_IMAGES: print(f"[!] Warning: optional partition '{name}' not found; skipping.") continue if args.only_backup: continue print(f"[!] Error: Partition '{name}' not found in device GPT.") sys.exit(1) target_parts.append((name, part)) def source_for(name): if method == "lk2nd" and device in DEVICE_LK2ND_IMAGES: if name in ("boot", "lk2nd"): return device_lk2nd_img return mainline_img if method == "lk2nd": return bootloader_img return boot_img if not userdata_part and not args.only_backup: print("[!] Error: Partition 'userdata' not found in device GPT.") sys.exit(1) if boot_part: print( f"[+] Found 'boot' : sector {boot_part.sector}, " f"{boot_part.sectors} sectors " f"({(boot_part.sectors * fh.cfg.SECTOR_SIZE_IN_BYTES) / (1024 * 1024):.1f} MiB)" ) if userdata_part: print( f"[+] Found 'userdata' : sector {userdata_part.sector}, " f"{userdata_part.sectors} sectors " f"({(userdata_part.sectors * fh.cfg.SECTOR_SIZE_IN_BYTES) / (1024 * 1024):.1f} MiB)" ) if args.dump_diagnostics: dump_diagnostics(fh, args.lun, guid_gpt.partentries, backup_dir) if args.only_backup: os.makedirs(backup_dir, exist_ok=True) gpt_backup_path = os.path.join(backup_dir, "gpt.bin") if args.force_backup or not os.path.exists(gpt_backup_path): with open(gpt_backup_path, "wb") as wf: wf.write(gpt_raw) print(f"[+] Saved GPT backup: {gpt_backup_path}") device_named = {"boot", "recovery", "aboot", "devinfo", "config", "splash", "lk2nd"} backup_parts = [ "fsc", "fsg", "modemst1", "modemst2", "persist", "boot", "recovery", "aboot", "devinfo", "config", "splash", "lk2nd", ] if args.backup_modem: backup_parts.append("modem") for pname in backup_parts: part = find_partition(guid_gpt.partentries, pname) if not part: print(f"[!] Warning: Partition '{pname}' not found in GPT; skipping backup.") continue dest_name = f"{pname}-{device}.img" if pname in device_named else f"{pname}.img" dest_file = os.path.join(backup_dir, dest_name) if ( not args.force_backup and os.path.exists(dest_file) and os.stat(dest_file).st_size > 0 ): print(f"[*] Backup already exists for '{pname}' ({dest_file}); skipping.") continue if not dump_partition(fh, args.lun, part, dest_file): sys.exit(1) print("\n============================================================") print(" STOCK PARTITION BACKUP COMPLETE") print("============================================================") print(f" Saved backups to: {backup_dir}") print(" No eMMC partitions were modified.") print("============================================================") if not args.no_reset: fh.cmd_reset() return 0 if args.only_unlock: ok = True if unlock_bootloader: print("\n[*] Unlocking eMMC devinfo for unsigned boot images...") ok = unlock_devinfo(fh, args.lun, guid_gpt.partentries, backup_dir, device) and ok if oem_unlock_enabled: print("\n[*] Enabling OEM unlock in config/frp...") ok = enable_oem_unlock(fh, args.lun, guid_gpt.partentries, backup_dir, device) and ok if not ok: print("[!] Unlock preparation failed; re-enter EDL and retry.") sys.exit(1) print("\n============================================================") print(" UNLOCK PREPARATION COMPLETE") print("============================================================") print(" The stock aboot reads devinfo from RPMB, not eMMC. To finish:") fastboot_key = "# (Volume Down)" if device in EDL_STAR_HASH_DEVICES else "Volume Down" print(f" 1. Power off, hold {fastboot_key}, plug USB to enter fastboot.") print(" 2. Run: fastboot oem unlock-go") print(" (Confirm on-screen if asked; this wipes userdata.)") print(" 3. Re-enter EDL and run the normal flash again.") print(" It will write lk2nd to boot/recovery and userdata.") print("============================================================") if not args.no_reset: fh.cmd_reset() return if unlock_bootloader: print("\n[*] Unlocking eMMC devinfo for unsigned boot images...") if not unlock_devinfo(fh, args.lun, guid_gpt.partentries, backup_dir, device): print("[!] Custom boot.img will be rejected while devinfo stays locked.") print(" Re-enter EDL and retry; do not trust this flash.") sys.exit(1) if oem_unlock_enabled: print("\n[*] Enabling OEM unlock in config/frp (RPMB unlock prerequisite)...") if not enable_oem_unlock(fh, args.lun, guid_gpt.partentries, backup_dir, device): print("[!] Could not enable 'oem unlock-go'. Run --only-unlock first.") sys.exit(1) if not args.skip_backup: os.makedirs(backup_dir, exist_ok=True) gpt_backup_path = os.path.join(backup_dir, "gpt.bin") if args.force_backup or not os.path.exists(gpt_backup_path): with open(gpt_backup_path, "wb") as wf: wf.write(gpt_raw) print(f"[+] Saved GPT backup: {gpt_backup_path}") backup_parts = ["fsc", "fsg", "modemst1", "modemst2", "persist"] backup_parts += list(target_names) if args.backup_modem: backup_parts.append("modem") for pname in backup_parts: part = find_partition(guid_gpt.partentries, pname) if not part: print(f"[!] Warning: Partition '{pname}' not found in GPT; skipping backup.") continue dest_file = os.path.join(backup_dir, f"{pname}.img") # Never reuse a stale backup of a partition we are about to overwrite: # an older device's boot.img in ./backup must not be trusted. is_target = pname in target_names if is_target: dest_file = os.path.join(backup_dir, f"{pname}-{device}.img") if ( not is_target and not args.force_backup and os.path.exists(dest_file) and os.stat(dest_file).st_size > 0 ): print(f"[*] Backup already exists for '{pname}' ({dest_file}); skipping.") continue if not dump_partition(fh, args.lun, part, dest_file): sys.exit(1) for name, part in target_parts: source = source_for(name) if method == "lk2nd" and source != mainline_img and ( source == bootloader_img or source == device_lk2nd_img): print("\n[*] Step 1/3: Flashing lk2nd secondary bootloader to '%s'..." % name) else: print("\n[*] Step 1/3: Flashing Bananarchy boot.img to '%s'..." % name) if not write_partition(fh, args.lun, part, source): sys.exit(1) if args.verify: for name, part in target_parts: source = source_for(name) ok, detail = verify_partition(fh, args.lun, part, source) print("[%s] Read-back of '%s': %s" % ( "+" if ok else "!", name, detail)) if not ok: print("[!] The image was not committed to '%s'. Re-enter EDL and " "retry before trusting the flash." % name) sys.exit(1) print(f"\n[*] Step 2/3: Flashing Bananarchy Linux ({device}) image to 'userdata'...") if not write_partition(fh, args.lun, userdata_part, userdata_img): sys.exit(1) if wipe_system and system_part: print( "\n[*] Step 3/3: Clearing stock 'system' superblock " "(first 64 sectors / 32 KiB)..." ) with tempfile.NamedTemporaryFile(prefix="wipe-system-", delete=False) as tf: tf.write(b"\x00" * (64 * fh.cfg.SECTOR_SIZE_IN_BYTES)) zero_path = tf.name try: if not fh.cmd_write(args.lun, system_part.sector, zero_path, Display=False): print("[!] Warning: Could not clear 'system' superblock; continuing.") else: print("[+] Cleared stock 'system' superblock.") finally: if os.path.exists(zero_path): os.unlink(zero_path) else: print("\n[*] Step 3/3: Skipping 'system' superblock wipe " "(--no-wipe-system).") if not args.no_reset: print(f"\n[*] Resetting and booting {device_label}...") fh.cmd_reset() print("\n============================================================") print(" BANANARCHY EDL FLASHING COMPLETED SUCCESSFULLY") print("============================================================") if unlock_bootloader: print(" eMMC devinfo.is_unlocked=1; note stock aboot also reads RPMB devinfo.") if oem_unlock_enabled: print(" config/frp allow-unlock flag set; run 'fastboot oem unlock-go'") print(" once if verification still blocks lk2nd (see --only-unlock).") if method == "recovery": print(" system superblock wiped; a normal power-on will hang on the KaiOS logo.") print(" Hold Volume Up at power-on to boot Bananarchy from 'recovery'.") elif method == "both": print(" boot and recovery both hold Bananarchy boot.img.") print(" Try a normal power-on first; if the KaiOS logo persists, hold") print(" Volume Up at power-on to boot the recovery copy.") elif method == "boot": print(" boot now holds Bananarchy boot.img: a normal power-on boots it.") print(" (system superblock wiped; restore boot + system from stock firmware") print(" if you ever want KaiOS back.)") elif method == "lk2nd" and device in ("nokia-beatles", "nokia-coconut", "nokia-sparkler"): print(" boot and lk2nd hold the display-enabled %s lk2nd port; recovery holds the mainline boot.img." % device) print(" Normal power-on: aboot -> lk2nd -> extlinux -> Bananarchy.") if device == "nokia-sparkler": print(" Alternate recovery slot (# / Volume Down at power-on): aboot -> recovery -> mainline boot.img -> Bananarchy.") else: print(" Volume Up: aboot -> recovery -> mainline boot.img -> Bananarchy.") else: print(" The phone will now boot via lk2nd into Bananarchy Linux (Sxmo).") print(" Default login: user / " + DEFAULT_USER_PASSWORD + " | USB SSH: ssh user@172.16.42.1") print("============================================================") if __name__ == "__main__": main()