461 lines
16 KiB
Python
Executable File
461 lines
16 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Offline test suite for Geminux flash-mtk GPT builder, safety guards, and firmware extractor."""
|
|
|
|
import os
|
|
import shutil
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import uuid
|
|
|
|
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
SCRIPTS_DIR = os.path.join(BASE_DIR, "scripts")
|
|
FLASH_DEPS = os.path.join(BASE_DIR, ".flash-deps")
|
|
if os.path.isdir(FLASH_DEPS):
|
|
sys.path.insert(0, FLASH_DEPS)
|
|
sys.path.insert(0, BASE_DIR)
|
|
sys.path.insert(0, SCRIPTS_DIR)
|
|
|
|
from geminux_gpt import (
|
|
BASIC_DATA_TYPE_GUID,
|
|
GPT_ARRAY_SECTORS,
|
|
GPT_ENTRY_COUNT,
|
|
GPT_ENTRY_SIZE,
|
|
LINUX_FS_TYPE_GUID,
|
|
PROTECTED_END_LBA,
|
|
SECTOR_SIZE,
|
|
GptEntry,
|
|
GptHeader,
|
|
build_geminux_gpts,
|
|
parse_primary_gpt,
|
|
verify_gpt_crcs,
|
|
)
|
|
import importlib.util
|
|
|
|
def _load_mod(name, path):
|
|
sp = importlib.util.spec_from_file_location(name, path)
|
|
mod = importlib.util.module_from_spec(sp)
|
|
sp.loader.exec_module(mod)
|
|
return mod
|
|
|
|
extract_firmware = _load_mod(
|
|
"extract_vendor_fw", os.path.join(SCRIPTS_DIR, "extract-vendor-fw.py")
|
|
).extract_firmware
|
|
flash_mtk = _load_mod("flash_mtk", os.path.join(BASE_DIR, "flash-mtk.py"))
|
|
|
|
|
|
def make_synthetic_gemini_pgpt(total_sectors):
|
|
# Replicate Planet Computers Gemini x27 SYS1..SYS34 partitions
|
|
parts_spec = [
|
|
("recovery", 0x8000, 0x1000000),
|
|
("para", 0x1008000, 0x80000),
|
|
("expdb", 0x1088000, 0xa00000),
|
|
("frp", 0x1a88000, 0x100000),
|
|
("nvcfg", 0x1b88000, 0x800000),
|
|
("nvdata", 0x2388000, 0x2000000),
|
|
("metadata", 0x4388000, 0x2000000),
|
|
("protect1", 0x6388000, 0x800000),
|
|
("protect2", 0x6b88000, 0xc78000),
|
|
("seccfg", 0x7800000, 0x800000),
|
|
("oemkeystore", 0x8000000, 0x200000),
|
|
("proinfo", 0x8200000, 0x300000),
|
|
("md1img", 0x8500000, 0x1800000),
|
|
("md1dsp", 0x9d00000, 0x400000),
|
|
("md1arm7", 0xa100000, 0x300000),
|
|
("md3img", 0xa400000, 0x500000),
|
|
("scp1", 0xa900000, 0x100000),
|
|
("scp2", 0xaa00000, 0x100000),
|
|
("nvram", 0xab00000, 0x500000),
|
|
("lk", 0xb000000, 0x80000),
|
|
("lk2", 0xb080000, 0x80000),
|
|
("boot", 0xb100000, 0x1000000),
|
|
("logo", 0xc100000, 0x800000),
|
|
("tee1", 0xc900000, 0x500000),
|
|
("tee2", 0xce00000, 0x500000),
|
|
("keystore", 0xd300000, 0xd00000),
|
|
("system", 0xe000000, 0xa0000000),
|
|
("cache", 0xae000000, 0x1b000000),
|
|
("userdata", 0xc9000000, (total_sectors - 32768 - 64) * SECTOR_SIZE - 0xc9000000),
|
|
]
|
|
|
|
entries = []
|
|
for name, start_b, size_b in parts_spec:
|
|
first_lba = start_b // SECTOR_SIZE
|
|
last_lba = (start_b + size_b) // SECTOR_SIZE - 1
|
|
entries.append(GptEntry(
|
|
BASIC_DATA_TYPE_GUID,
|
|
uuid.uuid4().bytes_le,
|
|
first_lba,
|
|
last_lba,
|
|
0,
|
|
name,
|
|
))
|
|
|
|
flashinfo_sectors = 0x1000000 // SECTOR_SIZE
|
|
flashinfo_first = total_sectors - 34 - flashinfo_sectors
|
|
entries.append(GptEntry(
|
|
BASIC_DATA_TYPE_GUID,
|
|
uuid.uuid4().bytes_le,
|
|
flashinfo_first,
|
|
flashinfo_first + flashinfo_sectors - 1,
|
|
0,
|
|
"flashinfo",
|
|
))
|
|
|
|
part_array = bytearray(GPT_ENTRY_COUNT * GPT_ENTRY_SIZE)
|
|
for i, e in enumerate(entries):
|
|
part_array[i * GPT_ENTRY_SIZE:(i + 1) * GPT_ENTRY_SIZE] = e.to_bytes()
|
|
|
|
raw_hdr = struct.pack(
|
|
"<8sIIIIQQQQ16sQIII",
|
|
b"EFI PART",
|
|
0x00010000,
|
|
92,
|
|
0,
|
|
0,
|
|
1,
|
|
total_sectors - 1,
|
|
34,
|
|
total_sectors - 34,
|
|
uuid.uuid4().bytes_le,
|
|
2,
|
|
GPT_ENTRY_COUNT,
|
|
GPT_ENTRY_SIZE,
|
|
0,
|
|
).ljust(SECTOR_SIZE, b"\x00")
|
|
hdr = GptHeader(raw_hdr)
|
|
hdr_bytes = hdr.pack_with_crcs(bytes(part_array))
|
|
mbr = bytearray(SECTOR_SIZE)
|
|
mbr[510:512] = b"\x55\xAA"
|
|
return bytes(mbr) + hdr_bytes + bytes(part_array)
|
|
|
|
|
|
def test_gpt_repartition():
|
|
# ~64 GB eMMC sector count
|
|
total_sectors = 122142720
|
|
orig_pgpt = make_synthetic_gemini_pgpt(total_sectors)
|
|
_, orig_hdr, orig_entries = parse_primary_gpt(orig_pgpt)
|
|
|
|
new_pgpt, new_sgpt, new_entries = build_geminux_gpts(orig_pgpt, total_sectors)
|
|
assert len(new_pgpt) == 34 * SECTOR_SIZE
|
|
assert len(new_sgpt) == 33 * SECTOR_SIZE
|
|
|
|
_, pri_hdr, parsed_entries = parse_primary_gpt(new_pgpt)
|
|
verify_gpt_crcs(pri_hdr, new_pgpt[2 * SECTOR_SIZE:])
|
|
|
|
# Verify backup GPT CRCs as well
|
|
bak_entries_bytes = new_sgpt[:GPT_ARRAY_SECTORS * SECTOR_SIZE]
|
|
bak_hdr = GptHeader(new_sgpt[GPT_ARRAY_SECTORS * SECTOR_SIZE:])
|
|
verify_gpt_crcs(bak_hdr, bak_entries_bytes)
|
|
assert bak_hdr.current_lba == total_sectors - 1
|
|
assert bak_hdr.backup_lba == 1
|
|
assert bak_hdr.part_entry_start_lba == total_sectors - 1 - GPT_ARRAY_SECTORS
|
|
|
|
# Check every pre-0x0E000000 partition is preserved byte-for-byte
|
|
orig_pre = [e for e in orig_entries if e.last_lba < PROTECTED_END_LBA]
|
|
new_pre = [e for e in parsed_entries if e.last_lba < PROTECTED_END_LBA]
|
|
assert len(orig_pre) == len(new_pre) == 26
|
|
for a, b in zip(orig_pre, new_pre):
|
|
assert a.to_bytes() == b.to_bytes(), f"Mismatch in preserved partition {a.name}"
|
|
|
|
names = [e.name for e in parsed_entries]
|
|
assert "system" not in names
|
|
assert "cache" not in names
|
|
assert "userdata" not in names
|
|
assert "linux" in names
|
|
assert "boot2" in names
|
|
assert "flashinfo" in names
|
|
|
|
linux_p = next(e for e in parsed_entries if e.name == "linux")
|
|
boot2_p = next(e for e in parsed_entries if e.name == "boot2")
|
|
flash_p = next(e for e in parsed_entries if e.name == "flashinfo")
|
|
|
|
assert linux_p.type_guid == LINUX_FS_TYPE_GUID
|
|
assert linux_p.first_lba == PROTECTED_END_LBA
|
|
assert linux_p.last_lba == boot2_p.first_lba - 1
|
|
linux_gib = (linux_p.sectors * SECTOR_SIZE) / (1024 ** 3)
|
|
assert linux_gib > 57.5, f"Expected >57.5 GiB linux partition, got {linux_gib:.2f}"
|
|
assert boot2_p.sectors * SECTOR_SIZE == 0x1000000
|
|
assert boot2_p.last_lba < flash_p.first_lba
|
|
print(f"[PASS] GPT repartitioning verified (linux={linux_gib:.2f} GiB, 26 protected partitions intact)")
|
|
|
|
|
|
def test_write_safety():
|
|
for protected in ("preloader", "nvram", "proinfo", "protect1", "protect2", "lk", "tee1", "md1img"):
|
|
blocked = False
|
|
try:
|
|
flash_mtk.enforce_write_safety(protected, allow_protected=False)
|
|
except PermissionError:
|
|
blocked = True
|
|
assert blocked, f"Protected partition {protected} was NOT blocked!"
|
|
flash_mtk.enforce_write_safety(protected, allow_protected=True)
|
|
|
|
for allowed in ("boot", "recovery", "boot2", "linux"):
|
|
flash_mtk.enforce_write_safety(allowed, allow_protected=False)
|
|
print("[PASS] Protected partition write-denylist verified")
|
|
|
|
|
|
def test_firmware_extraction():
|
|
if shutil.which("mke2fs") is None or shutil.which("debugfs") is None:
|
|
print("[SKIP] mke2fs/debugfs not available on host for ext4 extraction test")
|
|
return
|
|
with tempfile.TemporaryDirectory(prefix="geminux-fwtest-") as tmp:
|
|
src_tree = os.path.join(tmp, "sysroot", "vendor", "firmware")
|
|
os.makedirs(src_tree, exist_ok=True)
|
|
expected = {
|
|
"ROMv3_patch_1_0_hdr.bin": b"ROMV3_0" * 64,
|
|
"ROMv3_patch_1_1_hdr.bin": b"ROMV3_1" * 64,
|
|
"WIFI_RAM_CODE_6797": b"WIFI_FW" * 128,
|
|
"WMT_SOC.cfg": b"coex=1\n",
|
|
"pcm_suspend.bin": b"PCM_SUSPEND" * 16,
|
|
}
|
|
for name, data in expected.items():
|
|
with open(os.path.join(src_tree, name), "wb") as f:
|
|
f.write(data)
|
|
|
|
sys_img = os.path.join(tmp, "system.img")
|
|
subprocess.run(
|
|
["mke2fs", "-t", "ext4", "-F", "-q", "-d", os.path.join(tmp, "sysroot"), sys_img, "4M"],
|
|
check=True,
|
|
)
|
|
out_dir = os.path.join(tmp, "fw-out")
|
|
found, missing = extract_firmware(sys_img, out_dir)
|
|
assert not missing, f"Missing firmware blobs: {missing}"
|
|
assert set(found.keys()) == set(expected.keys())
|
|
for name, data in expected.items():
|
|
with open(os.path.join(out_dir, name), "rb") as f:
|
|
assert f.read() == data
|
|
assert os.path.isfile(os.path.join(out_dir, "MANIFEST.sha256"))
|
|
print("[PASS] Stock system.img firmware extraction verified")
|
|
|
|
|
|
def test_mtkclient_gpt_settings():
|
|
from types import SimpleNamespace
|
|
|
|
vendor_mtk = os.path.join(BASE_DIR, "vendor", "mtkclient")
|
|
if vendor_mtk not in sys.path:
|
|
sys.path.insert(0, vendor_mtk)
|
|
from mtkclient.Library.partition import Partition
|
|
|
|
cfg = flash_mtk.create_mtk_config()
|
|
assert cfg.gpt_settings is not None, "create_mtk_config() left cfg.gpt_settings as None"
|
|
assert cfg.gpt_settings.gpt_num_part_entries == 0
|
|
|
|
total_sectors = 122142720
|
|
pgpt = make_synthetic_gemini_pgpt(total_sectors)
|
|
# Ensure protective MBR has EFI partition entry matching hardware GPT
|
|
pgpt_arr = bytearray(pgpt)
|
|
pgpt_arr[0x1BE:0x1CE] = struct.pack("<B3sB3sII", 0x00, b"\x00\x02\x00", 0xEE, b"\xff\xff\xff", 1, total_sectors - 1)
|
|
pgpt = bytes(pgpt_arr)
|
|
|
|
def fake_readflash(addr, length, filename="", parttype="user", display=False):
|
|
chunk = pgpt[addr:addr + length]
|
|
return chunk.ljust(length, b"\x00")
|
|
|
|
daconfig = SimpleNamespace(storage=SimpleNamespace(flashsize=total_sectors * SECTOR_SIZE), pagesize=SECTOR_SIZE)
|
|
daloader = SimpleNamespace(daconfig=daconfig, readflash=fake_readflash)
|
|
fake_mtk = SimpleNamespace(config=cfg, daloader=daloader)
|
|
part = Partition(fake_mtk, fake_readflash, lambda: (b"", None))
|
|
_, guid_gpt = part.get_gpt(cfg.gpt_settings, "user")
|
|
assert guid_gpt is not None, "Partition.get_gpt failed with GptSettings(0, 0, 0)"
|
|
names = [e.name for e in guid_gpt.partentries]
|
|
assert "proinfo" in names and "nvram" in names and "linux" not in names, f"Unexpected entries: {names}"
|
|
print(f"[PASS] mtkclient GptSettings regression verified ({len(names)} partitions parsed)")
|
|
|
|
|
|
def test_finish_da_session():
|
|
from types import SimpleNamespace
|
|
|
|
with tempfile.TemporaryDirectory(prefix="geminux-da-exit-") as tmp:
|
|
state_file = os.path.join(tmp, ".state")
|
|
calls = []
|
|
|
|
class FakeDaloader:
|
|
def shutdown(self, bootmode=0):
|
|
calls.append(("shutdown", bootmode))
|
|
|
|
class FakePort:
|
|
def close(self):
|
|
calls.append(("close",))
|
|
|
|
fake_mtk = SimpleNamespace(
|
|
config=SimpleNamespace(hwparam_path=tmp),
|
|
daloader=FakeDaloader(),
|
|
port=FakePort(),
|
|
)
|
|
|
|
with open(state_file, "w") as f:
|
|
f.write("cached")
|
|
flash_mtk.finish_da_session(fake_mtk, reboot=True)
|
|
assert not os.path.exists(state_file), ".state file was not cleaned on DA reboot"
|
|
assert calls == [("shutdown", 1), ("close",)], f"Unexpected calls: {calls}"
|
|
|
|
calls.clear()
|
|
flash_mtk.finish_da_session(fake_mtk, reboot=False)
|
|
assert calls == [("shutdown", 0), ("close",)], f"Unexpected calls: {calls}"
|
|
print("[PASS] DA shutdown/reboot session cleanup verified")
|
|
|
|
|
|
def test_fast_preloader_handshake():
|
|
from types import SimpleNamespace
|
|
from mtkclient.Library.Port import Port
|
|
|
|
def run_case(initial_packets, coalesced_dup=False):
|
|
rx_packets = list(initial_packets)
|
|
tx_seen = []
|
|
|
|
class FakeEndpoint:
|
|
def __init__(self, is_in):
|
|
self.is_in = is_in
|
|
self.wMaxPacketSize = 512
|
|
|
|
def write(self, data, timeout=200):
|
|
tx_seen.append(bytes(data))
|
|
if data == b"\xa0":
|
|
if coalesced_dup:
|
|
rx_packets.append(b"READY\x5f\x5f")
|
|
else:
|
|
rx_packets.append(b"\x5f")
|
|
elif data == b"\x0a":
|
|
rx_packets.append(b"\xf5")
|
|
elif data == b"\x50":
|
|
rx_packets.append(b"\xaf")
|
|
elif data == b"\x05":
|
|
rx_packets.append(b"\xfa")
|
|
return len(data)
|
|
|
|
def read(self, size, timeout=100):
|
|
if not rx_packets:
|
|
return b""
|
|
pkt = rx_packets[0]
|
|
if size < len(pkt):
|
|
raise OSError("LIBUSB_ERROR_OVERFLOW")
|
|
rx_packets.pop(0)
|
|
return pkt
|
|
|
|
fake_cdc = SimpleNamespace(
|
|
pid=0x2000,
|
|
EP_OUT=FakeEndpoint(False),
|
|
EP_IN=FakeEndpoint(True),
|
|
set_line_coding=lambda *a, **kw: None,
|
|
setcontrollinestate=lambda *a, **kw: None,
|
|
)
|
|
fake_port = Port.__new__(Port)
|
|
fake_port.cdc = fake_cdc
|
|
fake_port.info = lambda *a, **kw: None
|
|
fake_port.debug = lambda *a, **kw: None
|
|
fake_port.warning = lambda *a, **kw: None
|
|
fake_port.error = lambda *a, **kw: None
|
|
|
|
assert fake_port.run_handshake(retries=25) is True, (
|
|
f"Preloader handshake failed (initial={initial_packets}, tx={tx_seen})"
|
|
)
|
|
assert tx_seen[-4:] == [b"\xa0", b"\x0a", b"\x50", b"\x05"], (
|
|
f"Unexpected handshake TX sequence: {tx_seen}"
|
|
)
|
|
|
|
run_case([b"READY\r\n"])
|
|
run_case([b"READY"], coalesced_dup=True)
|
|
|
|
parsed = flash_mtk.build_arg_parser().parse_args(["--wait-timeout", "450"])
|
|
assert parsed.wait_timeout == 450
|
|
cfg = flash_mtk.create_mtk_config(wait_timeout=450)
|
|
assert cfg.wait_timeout == 450
|
|
print("[PASS] Fast BROM/Preloader handshake (maxinsize, no overflow, READY-tolerant) verified")
|
|
|
|
|
|
def test_xflash_shutdown_wire_packet():
|
|
from types import SimpleNamespace
|
|
|
|
vendor_mtk = os.path.join(BASE_DIR, "vendor", "mtkclient")
|
|
if vendor_mtk not in sys.path:
|
|
sys.path.insert(0, vendor_mtk)
|
|
import mtkclient.Library.Connection.usblib as usblib
|
|
import mtkclient.Library.DA.xflash.xflash_lib as xflash_lib
|
|
from mtkclient.Library.DA.xflash.xflash_param import Cmd
|
|
|
|
orig_sleep = xflash_lib.time.sleep
|
|
sleep_calls = []
|
|
try:
|
|
xflash_lib.time.sleep = lambda sec: sleep_calls.append(sec)
|
|
|
|
for bootmode, expected in (
|
|
(1, (1, 100, 0, 1, 0, 1, 0)),
|
|
(0, (0, 0, 0, 0, 0, 1, 0)),
|
|
):
|
|
sent = []
|
|
close_calls = []
|
|
sleep_calls.clear()
|
|
da = xflash_lib.DAXFlash.__new__(xflash_lib.DAXFlash)
|
|
da.cmd = Cmd()
|
|
da.eh = SimpleNamespace(status=hex)
|
|
da.error = lambda *a, **kw: None
|
|
da.xsend = lambda data, *a, **kw: (sent.append(data), True)[1]
|
|
da.status = lambda: 0
|
|
da.mtk = SimpleNamespace(
|
|
port=SimpleNamespace(close=lambda reset=False: close_calls.append(reset))
|
|
)
|
|
|
|
assert da.shutdown(async_mode=0, dl_bit=0, bootmode=bootmode) is True
|
|
assert len(sent) == 2 and sent[0] == Cmd.SHUTDOWN, f"Unexpected commands: {sent}"
|
|
assert len(sent[1]) == 28, f"Expected 28-byte shutdown_ctrl, got {len(sent[1])} bytes"
|
|
unpacked = struct.unpack("<IIIIIII", sent[1])
|
|
assert unpacked == expected, f"bootmode={bootmode}: got {unpacked}, expected {expected}"
|
|
assert close_calls == [False], f"Unexpected port.close(reset=...) calls: {close_calls}"
|
|
assert sleep_calls == [0.35], f"Expected 0.35s disconnect wait, got {sleep_calls}"
|
|
|
|
class FakeDev:
|
|
def __init__(self):
|
|
self._ctx = SimpleNamespace(dispose=lambda dev: None)
|
|
|
|
def reset(self):
|
|
raise OSError(2, "Entity not found")
|
|
|
|
info_msgs = []
|
|
debug_msgs = []
|
|
usblib.time.sleep = lambda sec: None
|
|
uc = usblib.UsbClass.__new__(usblib.UsbClass)
|
|
uc.rxleft = bytearray()
|
|
uc.connected = True
|
|
uc.interface = 0
|
|
uc.device = FakeDev()
|
|
uc.info = lambda msg: info_msgs.append(msg)
|
|
uc.debug = lambda msg: debug_msgs.append(msg)
|
|
uc.close(reset=True)
|
|
assert info_msgs == [], f"Unexpected info log on expected ENOENT disconnect: {info_msgs}"
|
|
assert len(debug_msgs) == 1 and "Entity not found" in debug_msgs[0], debug_msgs
|
|
assert uc.connected is False
|
|
finally:
|
|
xflash_lib.time.sleep = orig_sleep
|
|
print("[PASS] XFlash 28-byte shutdown wire packet and ENOENT suppression verified")
|
|
|
|
|
|
def test_cli_help():
|
|
res = subprocess.run(
|
|
[os.path.join(BASE_DIR, "flash-mtk.sh"), "--help"],
|
|
capture_output=True,
|
|
text=True,
|
|
check=False,
|
|
)
|
|
assert res.returncode == 0, res.stderr
|
|
assert "--only-backup" in res.stdout and "--flash-full" in res.stdout
|
|
assert "--reboot" in res.stdout and "--poweroff" in res.stdout and "--no-reboot" in res.stdout
|
|
assert "--wait-timeout" in res.stdout
|
|
print("[PASS] flash-mtk.sh --help verified")
|
|
|
|
|
|
def main():
|
|
test_gpt_repartition()
|
|
test_write_safety()
|
|
test_firmware_extraction()
|
|
test_mtkclient_gpt_settings()
|
|
test_finish_da_session()
|
|
test_fast_preloader_handshake()
|
|
test_xflash_shutdown_wire_packet()
|
|
test_cli_help()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|