#!/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("