#!/usr/bin/env python3 """Validate the source-built nokia-coconut lk2nd boot image. Checks (all offline, pure Python): * Android boot.img header, cmdline and SEANDROIDENFORCE trailer. * QCDT v2 exact MSM8905 QRD SKUB entry (0x14b / 0x1000b / 0x100 / 0) and QRD fallback entry (0x14b / 0xb / 0x100) sharing one DTB. * Every unique QCDT DTB has /cpus/cpu@2 and /cpus/cpu@3 with a 4-byte device_type (the 2019 HMD partial-goods ASSERT fix). * /lk2nd/nokia-coconut node: model, compatible, match-panel, dtb-files, and panel init nodes (with GC9305 v2 init stream). * Base and coconut patch layers plus shared spi-panel-init.h stay in sync. """ import argparse import os import struct import sys BOOT_MAGIC = b"ANDROID!" QCDT_MAGIC = b"QCDT" FDT_MAGIC = 0xd00dfeed FDT_BEGIN_NODE = 1 FDT_END_NODE = 2 FDT_PROP = 3 FDT_NOP = 4 FDT_END = 9 STOCK_PLATFORM_ID = 0x14b STOCK_VARIANT_ID = 0x1000b STOCK_SUBTYPE = 0x100 STOCK_SOC_REV = 0 FALLBACK_VARIANT_ID = 0xb BOARD_ID = [FALLBACK_VARIANT_ID, STOCK_SUBTYPE, STOCK_VARIANT_ID, STOCK_SUBTYPE] PANEL_NAMES = ( "qcom,mdss_spi_gc9305_qvga_cmd", "qcom,mdss_spi_gc9305_v2_qvga_cmd", "qcom,mdss_spi_gc9305_3rd_qvga_cmd", "qcom,mdss_spi_st7789_qvga_cmd", "qcom,mdss_spi_gc9306_qvga_cmd", ) INIT_PANEL = PANEL_NAMES[1] EXPECTED_CMDS = 10 RGB565 = bytes([0x3a, 0x05]) COLUMN_WINDOW = bytes([0x2a, 0x00, 0x00, 0x00, 0xef]) ROW_WINDOW = bytes([0x2b, 0x00, 0x00, 0x01, 0x3f]) def align(value, page): return (value + page - 1) // page * page def fdt_nodes(data): vals = struct.unpack_from(">10I", data, 0) magic, totalsize, off_struct, off_strings, _, version = vals[:6] size_strings, size_struct = vals[8], vals[9] if magic != FDT_MAGIC or version not in (16, 17): raise ValueError("invalid FDT header") strings = data[off_strings:off_strings + size_strings] nodes = {} stack = [] pos = off_struct while True: token = struct.unpack_from(">I", data, pos)[0] pos += 4 if token == FDT_BEGIN_NODE: end = data.index(b"\0", pos) name = data[pos:end].decode("utf-8", "replace") pos = (end + 4) & ~3 if not stack: path = "/" elif stack[-1] == "/": path = "/" + name else: path = stack[-1] + "/" + name stack.append(path) nodes[path] = {} elif token == FDT_END_NODE: stack.pop() if not stack: break elif token == FDT_PROP: length, nameoff = struct.unpack_from(">II", data, pos) pos += 8 value = data[pos:pos + length] pos = (pos + length + 3) & ~3 end = strings.index(b"\0", nameoff) prop = strings[nameoff:end].decode("utf-8", "replace") nodes[stack[-1]][prop] = value elif token == FDT_NOP: continue elif token == FDT_END: break else: raise ValueError("bad FDT token 0x%x" % token) return nodes, totalsize def prop_str(nodes, path, prop): return nodes.get(path, {}).get(prop, b"").rstrip(b"\0").decode("utf-8", "replace") def prop_cells(nodes, path, prop): raw = nodes.get(path, {}).get(prop, b"") return list(struct.unpack(">%dI" % (len(raw) // 4), raw[:len(raw) // 4 * 4])) def parse_stream(raw): """Return (commands, total_delay) or raise ValueError.""" off = 0 commands = [] total_delay = 0 while off + 2 <= len(raw): wait, dlen = raw[off], raw[off + 1] off += 2 if not dlen or off + dlen > len(raw): raise ValueError("malformed command at byte %d" % (off - 2)) payload = raw[off:off + dlen] off += dlen commands.append((wait, payload)) total_delay += wait if off != len(raw): raise ValueError("trailing garbage at byte %d" % off) return commands, total_delay def check_stream(name, raw, problems): try: commands, total_delay = parse_stream(raw) except ValueError as exc: problems.append("%s panel init stream: %s" % (name, exc)) return None if len(commands) != EXPECTED_CMDS: problems.append("%s panel init has %d commands, expected %d" % (name, len(commands), EXPECTED_CMDS)) if total_delay != 120: problems.append("%s panel init waits %d ms total, expected 120" % (name, total_delay)) payloads = [payload for _, payload in commands] for label, want in (("RGB565 COLMOD", RGB565), ("240 column window", COLUMN_WINDOW), ("320 row window", ROW_WINDOW)): if want not in payloads: problems.append("%s panel init is missing the %s command" % (name, label)) if b"\x11" not in payloads: problems.append("%s panel init is missing sleep-out (0x11)" % name) if b"\x29" not in payloads: problems.append("%s panel init is missing display-on (0x29)" % name) if not payloads or payloads[-1] != b"\x2c": problems.append("%s panel init does not end with RAMWR (0x2c)" % name) return commands def check_device_node(nodes, label, problems): prefix = "%s: " % label if prop_cells(nodes, "/", "qcom,msm-id")[:2] != [STOCK_PLATFORM_ID, 0]: problems.append(prefix + "qcom,msm-id is not the stock 0x14b/0") board = prop_cells(nodes, "/", "qcom,board-id") if board != BOARD_ID: problems.append(prefix + "qcom,board-id is %r, expected %r" % (board, BOARD_ID)) if "/chosen" not in nodes: problems.append(prefix + "missing /chosen") if not any(props.get("device_type") == b"memory\0" for props in nodes.values()): problems.append(prefix + "missing /memory node") subnodes = sorted(p for p in nodes if p.startswith("/lk2nd/") and p.count("/") == 2) for needed in ("/lk2nd/cat-b35", "/lk2nd/nokia-argon", "/lk2nd/nokia-beatles", "/lk2nd/nokia-coconut"): if needed not in subnodes: problems.append(prefix + "missing %s (device node lost)" % needed) node = "/lk2nd/nokia-coconut" if node not in nodes: problems.append(prefix + "missing /lk2nd/nokia-coconut") return None props = nodes[node] if prop_str(nodes, node, "model") != "Nokia 800 Tough": problems.append(prefix + "wrong model %r" % prop_str(nodes, node, "model")) if prop_str(nodes, node, "compatible") != "nokia,coconut": problems.append(prefix + "wrong compatible %r" % prop_str(nodes, node, "compatible")) if "lk2nd,match-panel" not in props: problems.append(prefix + "coconut node lost lk2nd,match-panel") if prop_str(nodes, node, "lk2nd,dtb-files") != "msm8905-nokia-coconut": problems.append(prefix + "wrong lk2nd,dtb-files %r" % prop_str(nodes, node, "lk2nd,dtb-files")) stream = None for name in PANEL_NAMES: panel = node + "/panel/" + name if panel not in nodes: problems.append(prefix + "missing panel node %s" % name) continue if name == INIT_PANEL: if "lk2nd,panel-init" not in nodes[panel]: problems.append(prefix + "panel %s has no lk2nd,panel-init" % name) else: stream = nodes[panel]["lk2nd,panel-init"] check_stream(name, stream, problems) elif "lk2nd,panel-init" in nodes[panel]: problems.append(prefix + "panel %s must stay compact (no init stream)" % name) return stream def extract_patch_file(patch_text, path): """Return the added-file body for a 'new file' diff section.""" marker = "diff --git a/%s b/%s\n" % (path, path) start = patch_text.find(marker) if start < 0: return None lines = patch_text[start:].split("\n") out = [] started = False for line in lines[1:]: if line.startswith("@@"): started = True continue if not started: continue if line.startswith("diff --git "): break if line.startswith("+"): out.append(line[1:]) return "\n".join(out) + "\n" def main(): base = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--image", default=os.path.join(base, "images", "boot-lk2nd-nokia-coconut.img")) ap.add_argument("--base-patch", default=os.path.join(base, "bootloader", "lk2nd", "nokia-beatles.patch")) ap.add_argument("--patch", default=os.path.join(base, "bootloader", "lk2nd", "nokia-coconut.patch")) ap.add_argument("--emit-streams-header", default=None, help="write the panel init stream as a C array for the host unit test") ap.add_argument("--expect-fastboot", type=int, choices=(0, 1), default=0, help="require (1) or forbid (0) the forced-fastboot diagnostic build") ap.add_argument("--expect-display", type=int, choices=(0, 1), default=0, help="require (1) or forbid (0) the boot-time SPI display build") args = ap.parse_args() problems = [] if not os.path.isfile(args.image): print("FAIL: missing %s" % args.image) return 1 data = open(args.image, "rb").read() if data[:8] != BOOT_MAGIC: print("FAIL: %s is not an Android boot image" % args.image) return 1 hdr = struct.unpack_from("<8s10I", data, 0) kernel_size, kernel_addr, ramdisk_size, _ = hdr[1:5] second_size, _, _, page = hdr[5:9] dt_size = hdr[9] if page != 2048: problems.append("page size is %d, expected 2048" % page) if kernel_addr != 0x80008000: problems.append("kernel load address %#x is not the stock 0x80008000" % kernel_addr) if dt_size == 0 or dt_size % page != 0: problems.append("dt_size %d is not a page-multiple QCDT image" % dt_size) if len(data) > 512 * 1024: problems.append("lk2nd image %d bytes exceeds the 512 KiB lk2nd partition" % len(data)) cmdline = data[64:576].split(b"\0")[0].decode("utf-8", "replace") cmd_parts = cmdline.split(" ") if cmd_parts[:2] != ["lk2nd", "lk2nd.compatible=nokia,coconut"] or \ any(p not in ("lk2nd.force-panel-init", "lk2nd.no-display", "lk2nd.display=on") for p in cmd_parts[2:]): problems.append("cmdline is %r" % cmdline) no_display = "lk2nd.no-display" in cmd_parts[2:] display_on = "lk2nd.display=on" in cmd_parts[2:] if args.expect_fastboot and not no_display: problems.append("diagnostic image must carry lk2nd.no-display") if args.expect_display and not display_on: problems.append("display image must carry lk2nd.display=on") if args.expect_display and no_display: problems.append("display image must not carry lk2nd.no-display") if not args.expect_display and display_on: problems.append("non-display image must not carry lk2nd.display=on") forced_fastboot = b"Fastboot mode was forced with compile-time flag." in data if forced_fastboot != bool(args.expect_fastboot): problems.append("fastboot diagnostic marker is %s, expected %s" % (forced_fastboot, bool(args.expect_fastboot))) for marker in (b"lk2nd.no-display", b"lk2nd.display=on", b"oem scan-boot", b"oem display-init", b"oem display-test", b"oem scan-dtb", b"QUP output FIFO timeout", b"SPI panel %s: keeping aboot continuous splash", b"SPI display ready", b"scan-only: final kernel cmdline/DTB ready", b"No valid pstore console", b"SPI panel fallback from QCDT: %s", b"offset is not block-aligned", b"aligned read exceeds partition", b"nokia,coconut"): if marker not in data: problems.append("binary is missing %r" % marker.decode("ascii", "replace")) if b"beatles low-bit reboot cookie" not in data: problems.append("binary is missing low-bit reboot cookie") if not data.endswith(b"SEANDROIDENFORCE"): problems.append("missing SEANDROIDENFORCE trailer") qcdt_off = (page + align(kernel_size, page) + align(ramdisk_size, page) + align(second_size, page)) entries = {} num_entries = 0 if data[qcdt_off:qcdt_off + 4] != QCDT_MAGIC: problems.append("no QCDT table at offset %d" % qcdt_off) else: _, version, num_entries = struct.unpack_from("<4sII", data, qcdt_off) if version != 2: problems.append("QCDT version is %d, expected 2" % version) for i in range(num_entries): off = qcdt_off + 12 + 24 * i platform_id, variant_id, subtype, soc_rev, dtb_off, dtb_size = \ struct.unpack_from("<6I", data, off) if (platform_id == STOCK_PLATFORM_ID and soc_rev == STOCK_SOC_REV and subtype == STOCK_SUBTYPE and variant_id in (STOCK_VARIANT_ID, FALLBACK_VARIANT_ID)): entries[variant_id] = (dtb_off, dtb_size, i) for variant, label in ((STOCK_VARIANT_ID, "exact MSM8905 QRD SKUB"), (FALLBACK_VARIANT_ID, "QRD fallback")): if variant not in entries: problems.append("QCDT has no %s entry" % label) if len(entries) == 2: exact, fallback = entries[STOCK_VARIANT_ID], entries[FALLBACK_VARIANT_ID] if exact[:2] != fallback[:2]: problems.append("the two MSM8905 QRD SKUB entries must share one DTB") seen_offsets = {} for i in range(num_entries): off = qcdt_off + 12 + 24 * i _, _, _, _, dtb_off, dtb_size = struct.unpack_from("<6I", data, off) if dtb_off and dtb_size: seen_offsets.setdefault(dtb_off, dtb_size) for dtb_off, dtb_size in seen_offsets.items(): dtb = data[qcdt_off + dtb_off:qcdt_off + dtb_off + dtb_size] if dtb[:4] != b"\xd0\x0d\xfe\xed": continue try: nodes, _ = fdt_nodes(dtb) except ValueError: continue if "/cpus" not in nodes: problems.append("QCDT DTB@0x%x lacks /cpus (aboot partial-goods ASSERT)" % dtb_off) continue for cpu in ("cpu@2", "cpu@3"): path = "/cpus/" + cpu if path not in nodes: problems.append("QCDT DTB@0x%x lacks %s" % (dtb_off, path)) elif nodes[path].get("device_type") != b"cpu\0": problems.append("QCDT DTB@0x%x %s device_type is %r, expected b'cpu\\0'" % (dtb_off, path, nodes[path].get("device_type"))) stream = None if STOCK_VARIANT_ID in entries: dtb_off, dtb_size, _ = entries[STOCK_VARIANT_ID] dtb = data[qcdt_off + dtb_off:qcdt_off + dtb_off + dtb_size] if dtb[:4] != b"\xd0\x0d\xfe\xed": problems.append("coconut DTB is not an FDT") else: try: nodes, totalsize = fdt_nodes(dtb) if totalsize > dtb_size: problems.append("coconut DTB is truncated (%d > %d)" % (totalsize, dtb_size)) stream = check_device_node(nodes, "coconut DTB", problems) except ValueError as exc: problems.append("coconut DTB: %s" % exc) header_path = os.path.join(base, "bootloader", "lk2nd", "spi-panel-init.h") if not os.path.isfile(args.base_patch): problems.append("missing base patch %s" % args.base_patch) elif not os.path.isfile(args.patch): problems.append("missing coconut patch %s" % args.patch) elif not os.path.isfile(header_path): problems.append("missing %s" % header_path) else: base_text = open(args.base_patch, "r").read() patch_text = open(args.patch, "r").read() want = open(header_path, "r").read() got = extract_patch_file(base_text, "lk2nd/include/lk2nd/spi-panel-init.h") if got != want: problems.append("bootloader/lk2nd/spi-panel-init.h is out of sync with base patch") for needed in ( "lk2nd/device/2nd/spi-display.c", "lk2nd/device/dts/msm8909/msm8905-qrd-skub.dts", "lk2nd/device/dts/msm8909/nokia-coconut.dtsi", ): if "diff --git a/%s b/%s" % (needed, needed) not in patch_text: problems.append("coconut patch is missing %s" % needed) if "nokia,coconut" not in patch_text or "lk2nd,panel-init" not in patch_text: problems.append("coconut patch is missing nokia,coconut or lk2nd,panel-init") if problems: for problem in problems: print("FAIL: %s" % problem) return 1 print("[ok] source-built coconut lk2nd (%s): cmdline=%r, %d bytes, " "dt_size=%d, both 0x14b entries -> DTB@0x%x" % ("diagnostic" if args.expect_fastboot else "display" if args.expect_display else "normal", cmdline, len(data), dt_size, entries[STOCK_VARIANT_ID][0])) print("[ok] all %d QCDT DTBs have /cpus/cpu@2 and cpu@3 (partial-goods fix)" % len(seen_offsets)) print("[ok] coconut DTB carries /lk2nd/nokia-coconut with the GC9305 v2 panel init stream") print("[ok] patches/header in sync") if args.emit_streams_header: out = ["/* generated by scripts/check-lk2nd-coconut.py */", "#ifndef PANEL_STREAMS_H", "#define PANEL_STREAMS_H", "", "static const unsigned char stream_v2[] = {"] for i in range(0, len(stream), 12): out.append(" " + ", ".join("0x%02x" % x for x in stream[i:i + 12]) + ",") out += ["};", "", "#endif"] with open(args.emit_streams_header, "w") as fh: fh.write("\n".join(out) + "\n") print("[ok] wrote %s" % args.emit_streams_header) return 0 if __name__ == "__main__": sys.exit(main())