Finalize verified 2720 Flip release source and untrack image outputs

This commit is contained in:
Luxferre committed 2026-11-09 23:04:13 +02:00
1 parent 2a3078e42c
commit 1c011b360a
121 files changed
+8467 -686

No files matched your search

+600 -53
View File
@@ -3,6 +3,7 @@
import argparse
import os
import re
import subprocess
import sys
import tempfile
@@ -39,6 +40,84 @@ DEVICE_LABELS = {
"nokia-leo": "Nokia 6300 4G (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-tough": "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-tough": "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)
# 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",)
# Stock 2720 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",)
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 after changing
# bootloader/lk2nd/nokia-beatles.patch; never binary-patch the prebuilt
# bootloader/lk2nd-msm8909.img.
BEATLES_LK2ND_IMAGE = "images/boot-lk2nd-nokia-beatles-display.img"
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=5000):
while True:
@@ -174,11 +253,13 @@ def try_kick_into_edl():
pass
def wait_for_edl_usb(vid, pid, device_label, timeout_sec=0):
cdc = usb_class(vid=vid, pid=pid)
def wait_for_edl_usb(vid, pids, device_label, timeout_sec=0):
if isinstance(pids, int):
pids = (pids,)
pids = tuple(pids)
print(
f"[*] Waiting for {device_label} in EDL mode "
f"(USB {vid:04x}:{pid:04x} Qualcomm QDLoader 9008)..."
"[*] 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)")
@@ -190,24 +271,26 @@ def wait_for_edl_usb(vid, pid, device_label, timeout_sec=0):
start_ts = time.time()
dots = 0
while not cdc.connected:
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:9008. "
"Please run via sudo (e.g. sudo ./flash-edl.sh)."
)
sys.exit(1)
time.sleep(0.05)
continue
if cdc.connected:
if dots > 0:
sys.stdout.write("\n")
print("[+] USB EDL device connected.")
return cdc
while True:
for pid in pids:
if usb.core.find(idVendor=vid, idProduct=pid) is None:
continue
cdc = usb_class(vid=vid, pid=pid)
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:
@@ -236,6 +319,33 @@ def find_partition(partentries, name):
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
@@ -277,14 +387,170 @@ def dump_partition(fh, lun, part, filepath):
return True
def resolve_default_loader():
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_<codename> 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", "8110.mbn"),
os.path.join(BASE_DIR, "8110.mbn"),
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", "8110.mbn")
return os.path.join(BASE_DIR, "bootloader", "loaders", name)
def resolve_default_bootloader():
@@ -301,6 +567,37 @@ 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 parse_args():
parser = argparse.ArgumentParser(
description="Automated EDL Flasher for Bananarchy Linux (MSM8909 / Sxmo)"
@@ -343,8 +640,41 @@ def parse_args():
)
parser.add_argument(
"--loader",
default=resolve_default_loader(),
help="Path to Firehose programmer (.mbn)",
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 "
"lk2nd is written to boot and recovery; both writes the mainline "
"boot.img to both slots; recovery needs Volume Up",
)
parser.add_argument(
"--boot-image",
default="",
help="Standalone Android boot.img for recovery flashing "
"(default: images/boot-bananarchy-<device>.img)",
)
parser.add_argument(
"--lk2nd-image",
default="",
help="Override the nokia-beatles lk2nd boot.img written to 'boot' "
"(e.g. images/boot-lk2nd-nokia-beatles-diagnostic.img for the "
"forced-fastboot/on-screen-log diagnostic build)",
)
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",
@@ -369,7 +699,51 @@ def parse_args():
parser.add_argument(
"--no-wipe-system",
action="store_true",
help="Do not zero the stock system partition superblock",
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; needed for "
"the 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). "
"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(
"--wipe-system",
action="store_true",
help="Zero the stock system superblock (already the default; kept for compatibility)",
)
parser.add_argument(
"--no-reset",
@@ -389,8 +763,8 @@ def parse_args():
)
parser.add_argument(
"--pid",
default="0x9008",
help="USB Product ID (default: 0x9008)",
default="",
help="USB Product ID (default: auto-detect 05c6:9008, 900e or 9006)",
)
parser.add_argument(
"--lun",
@@ -403,23 +777,64 @@ def parse_args():
def main():
args = parse_args()
if args.list_loaders:
return list_loaders()
device = args.device_pos if args.device_pos and args.device_pos != "sxmo" else args.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)
loader_mbn = os.path.abspath(args.loader)
beatles_lk2nd_img = os.path.abspath(args.lk2nd_image or resolve_beatles_lk2nd_image())
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_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 == "nokia-beatles":
print(f" LK2ND (boot) : {beatles_lk2nd_img} (nokia-beatles source port)")
print(f" Boot Image (rec) : {mainline_img}")
print(f" Bootloader (boot): {bootloader_img}")
print(f" System (userdata): {userdata_img}")
print(
@@ -428,18 +843,34 @@ def main():
)
print("============================================================")
for label, path in [
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)
required_files = [
("Firehose programmer", loader_mbn),
("lk2nd bootloader image", bootloader_img),
("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 == "nokia-beatles":
required_files.append(("nokia-beatles lk2nd image", beatles_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)
pid = int(args.pid, 16)
cdc = wait_for_edl_usb(vid, pid, device_label, timeout_sec=args.timeout)
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)
sahara = qualcomm_sahara(cdc)
with open(loader_mbn, "rb") as rf:
@@ -497,27 +928,97 @@ def main():
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")
if not boot_part:
print("[!] Error: Partition 'boot' not found in device GPT.")
sys.exit(1)
target_names = BOOT_METHOD_TARGETS[method]
if method == "lk2nd" and device == "nokia-beatles":
# 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 bootloader" 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 == "nokia-beatles":
print(f"[!] Warning: optional partition '{name}' not found; skipping.")
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 == "nokia-beatles":
if name in ("boot", "lk2nd"):
return beatles_lk2nd_img
return mainline_img
if method == "lk2nd":
return bootloader_img
return boot_img
if not userdata_part:
print("[!] Error: Partition 'userdata' not found in device GPT.")
sys.exit(1)
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 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)"
)
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_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:")
print(" 1. Power off, hold Volume Down, 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")
@@ -526,7 +1027,8 @@ def main():
wf.write(gpt_raw)
print(f"[+] Saved GPT backup: {gpt_backup_path}")
backup_parts = ["fsc", "fsg", "modemst1", "modemst2", "persist", "boot"]
backup_parts = ["fsc", "fsg", "modemst1", "modemst2", "persist"]
backup_parts += list(target_names)
if args.backup_modem:
backup_parts.append("modem")
@@ -536,8 +1038,14 @@ def main():
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 args.force_backup
not is_target
and not args.force_backup
and os.path.exists(dest_file)
and os.stat(dest_file).st_size > 0
):
@@ -546,15 +1054,32 @@ def main():
if not dump_partition(fh, args.lun, part, dest_file):
sys.exit(1)
print("\n[*] Step 1/3: Flashing lk2nd secondary bootloader to 'boot'...")
if not write_partition(fh, args.lun, boot_part, bootloader_img):
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 == beatles_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 not args.no_wipe_system and system_part:
if wipe_system and system_part:
print(
"\n[*] Step 3/3: Clearing stock 'system' superblock "
"(first 64 sectors / 32 KiB)..."
@@ -571,7 +1096,8 @@ def main():
if os.path.exists(zero_path):
os.unlink(zero_path)
else:
print("\n[*] Step 3/3: Skipping 'system' superblock wipe.")
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}...")
@@ -580,7 +1106,28 @@ def main():
print("\n============================================================")
print(" BANANARCHY EDL FLASHING COMPLETED SUCCESSFULLY")
print("============================================================")
print(" The phone will now boot via lk2nd into Bananarchy Linux (Sxmo).")
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 == "nokia-beatles":
print(" boot and lk2nd hold the display-enabled nokia-beatles lk2nd port; recovery holds the mainline boot.img.")
print(" Normal power-on: aboot -> lk2nd -> extlinux -> Bananarchy.")
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("============================================================")