Files
bananarchy/scripts/sync-beatles-bootfs.py
T

279 lines
10 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
"""Repair/validate the pmOS_boot ext2 filesystem inside a 2720 raw image.
The raw image written to `userdata` is an MBR disk image whose first
partition (LBA 2048, 256 MiB) is an ext2 filesystem containing
/vmlinuz, /initramfs, /qcom-msm8905-nokia-beatles.dtb, /boot.img and
/extlinux/extlinux.conf. lk2nd mounts that filesystem to find
extlinux.conf. An earlier repack mistakenly wrote an Android boot.img at
offset 1 MiB, destroying the ext2 superblock; lk2nd then found no
bootable fs and hung.
This tool extracts that partition, updates the boot.img, DTB and (optionally)
extlinux.conf with debugfs, and writes it back at the MBR-specified offset.
Use --check to validate without modifying anything.
"""
import argparse
import hashlib
import os
import struct
import subprocess
import sys
import tempfile
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
EXT2_MAGIC_OFFSET = 1080
EXT2_MAGIC = b"\x53\xef"
BOOT_FS_FILES = {
"boot.img": BASE_DIR / "images" / "boot-bananarchy-nokia-beatles.img",
"qcom-msm8905-nokia-beatles.dtb":
BASE_DIR / "devices" / "nokia-beatles" / "qcom-msm8905-nokia-beatles.dtb",
}
DEBUG_PREFIX = "loglevel=8 ignore_loglevel initcall_debug panic=10"
QUIET_PREFIX = "quiet splash"
BOOT_CMD_FLAGS = "plymouth.ignore-serial-consoles plymouth.prefer-fbcon"
def release_cmdline(conf):
"""Restore the shipping cmdline (quiet splash) in an extlinux.conf.
The pmOS initramfs defaults to nosplash=y and only starts plymouthd when
the literal "splash" parameter is present. Kernel-level debugging used the
replace-with-DEBUG_PREFIX path below; without the reverse conversion the
shipped image keeps loglevel=8/initcall_debug and never shows a boot splash.
"""
if DEBUG_PREFIX in conf:
conf = conf.replace(DEBUG_PREFIX, QUIET_PREFIX, 1)
if QUIET_PREFIX not in conf:
conf = conf.replace("append ", "append " + QUIET_PREFIX + " ", 1)
return conf
def debug_cmdline(conf):
if QUIET_PREFIX in conf:
conf = conf.replace(QUIET_PREFIX, DEBUG_PREFIX, 1)
elif DEBUG_PREFIX not in conf:
conf = conf.replace("append ", "append " + DEBUG_PREFIX + " ", 1)
return conf
def mbr_first_partition(data):
if len(data) < 512 or data[510:512] != b"\x55\xaa":
raise ValueError("raw image has no MBR signature")
entry = data[446:462]
ptype = entry[4]
lba, sectors = struct.unpack_from("<II", entry, 8)
if ptype != 0x83 or not lba or not sectors:
raise ValueError("first MBR entry is not a Linux partition")
return lba * 512, sectors * 512
def run_debugfs(fs, commands):
with tempfile.NamedTemporaryFile("w", suffix=".cmd", delete=False) as handle:
handle.write("\n".join(commands) + "\n")
cmd_file = handle.name
try:
proc = subprocess.run(["debugfs", "-w", "-f", cmd_file, fs],
capture_output=True, text=True)
if proc.returncode != 0:
raise ValueError("debugfs failed: %s" % (proc.stdout + proc.stderr).strip())
finally:
os.unlink(cmd_file)
def cat(fs, path):
proc = subprocess.run(["debugfs", "-R", "cat %s" % path, fs],
capture_output=True)
if proc.returncode != 0:
raise ValueError("cannot read %s from boot fs" % path)
return proc.stdout
def sha(data):
return hashlib.sha256(data).hexdigest()
def validate_cmdline(conf, allow_debug=False):
append = ""
for line in conf.splitlines():
if line.strip().startswith("append "):
append = line.strip()[len("append "):]
break
if not append:
raise ValueError("extlinux.conf has no append line")
parts = append.split()
if "earlycon" in parts:
raise ValueError("extlinux.conf still contains earlycon")
if not allow_debug:
if "splash" not in parts or "quiet" not in parts:
raise ValueError("extlinux.conf is missing 'quiet splash' (no Plymouth splash at boot)")
for flag in ("loglevel=8", "ignore_loglevel", "initcall_debug"):
if flag in parts:
raise ValueError("extlinux.conf still has kernel debug flag %s" % flag)
for flag in BOOT_CMD_FLAGS.split():
if flag not in parts:
raise ValueError("extlinux.conf is missing %s" % flag)
return append
def check(raw_path, dtb_path, boot_img_path, verbose=True, allow_debug=False,
files=None, dtb_name="qcom-msm8905-nokia-beatles.dtb"):
files = files if files is not None else BOOT_FS_FILES
raw = open(raw_path, "rb").read(1024 * 1024 + 4096)
offset, size = mbr_first_partition(raw)
if len(raw) < offset + 2048 or raw[offset + EXT2_MAGIC_OFFSET:offset + EXT2_MAGIC_OFFSET + 2] != EXT2_MAGIC:
raise ValueError("pmOS_boot ext2 superblock is missing at %#x "
"(raw image was overwritten by an Android boot.img)" % offset)
with tempfile.NamedTemporaryFile(suffix=".img", delete=False) as handle:
fs = handle.name
try:
with open(raw_path, "rb") as src, open(fs, "wb") as dst:
src.seek(offset)
left = size
while left > 0:
chunk = src.read(min(1 << 20, left))
if not chunk:
break
dst.write(chunk)
left -= len(chunk)
conf = cat(fs, "/extlinux/extlinux.conf").decode("utf-8", "replace")
if ("fdt /%s" % dtb_name) not in conf:
raise ValueError("extlinux.conf does not name %s" % dtb_name)
validate_cmdline(conf, allow_debug)
for name, expected in files.items():
got = sha(cat(fs, "/" + name))
want = sha(open(expected, "rb").read())
if got != want:
raise ValueError("/%s in boot fs is stale (%s != %s)" % (name, got[:12], want[:12]))
if verbose:
print("[ok] pmOS_boot at %#x (%d bytes): ext2 intact, extlinux.conf, "
"boot.img and %s all current" % (offset, size, dtb_name))
return offset, size, fs
finally:
if fs and os.path.exists(fs):
os.unlink(fs)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--device", choices=["nokia-beatles", "nokia-coconut"],
default="nokia-beatles")
parser.add_argument("--raw-image", default="")
parser.add_argument("--source-boot-fs", default="",
help="Pristine ext2 boot-fs image to seed from when the "
"raw image's superblock is destroyed")
parser.add_argument("--debug-cmdline", action="store_true",
help="Replace 'quiet splash' in extlinux.conf with "
"verbose/panic settings (diagnostic builds only)")
parser.add_argument("--allow-debug", action="store_true",
help="With --check, accept a diagnostic cmdline")
parser.add_argument("--check", action="store_true")
parser.add_argument("--dtb", default="",
help="Override the DTB written to/checked in pmOS_boot")
parser.add_argument("--boot-image", default="",
help="Override the boot.img written to/checked in pmOS_boot")
args = parser.parse_args()
dtb_name = "qcom-msm8905-%s.dtb" % args.device
raw_image = args.raw_image or str(BASE_DIR / "images" / ("bananarchy-%s.img" % args.device))
dtb = Path(args.dtb) if args.dtb else (BASE_DIR / "devices" / args.device / dtb_name)
boot_img = Path(args.boot_image) if args.boot_image else (
BASE_DIR / "images" / ("boot-bananarchy-%s.img" % args.device)
)
boot_files = {
"boot.img": boot_img,
dtb_name: dtb,
}
for path in (raw_image, str(dtb), str(boot_img)):
if not os.path.isfile(path):
print("FAIL: missing %s" % path)
return 1
if args.check:
try:
check(raw_image, dtb, boot_img, allow_debug=args.allow_debug,
files=boot_files, dtb_name=dtb_name)
return 0
except ValueError as exc:
print("FAIL: %s" % exc)
return 1
raw = open(raw_image, "rb").read(1024 * 1024 + 4096)
offset, size = mbr_first_partition(raw)
with tempfile.NamedTemporaryFile(suffix=".img", delete=False) as handle:
fs = handle.name
try:
if args.source_boot_fs:
with open(args.source_boot_fs, "rb") as src, open(fs, "wb") as dst:
while True:
chunk = src.read(1 << 20)
if not chunk:
break
dst.write(chunk)
else:
with open(raw_image, "rb") as src, open(fs, "wb") as dst:
src.seek(offset)
left = size
while left > 0:
chunk = src.read(min(1 << 20, left))
if not chunk:
break
dst.write(chunk)
left -= len(chunk)
if os.path.getsize(fs) != size:
raise ValueError("source boot fs is %d bytes, expected %d" %
(os.path.getsize(fs), size))
if open(fs, "rb").read(EXT2_MAGIC_OFFSET + 2)[EXT2_MAGIC_OFFSET:EXT2_MAGIC_OFFSET + 2] != EXT2_MAGIC:
raise ValueError("source boot fs has no ext2 superblock")
commands = []
for name, host_path in boot_files.items():
commands += ["rm /%s" % name,
"write %s /%s" % (host_path, name)]
conf = cat(fs, "/extlinux/extlinux.conf").decode("utf-8", "replace")
new_conf = conf
new_conf = debug_cmdline(new_conf) if args.debug_cmdline else release_cmdline(new_conf)
new_conf = new_conf.replace(" earlycon ", " ")
new_conf = new_conf.replace("append earlycon ", "append ")
new_conf = new_conf.replace("append earlycon", "append")
validate_cmdline(new_conf, allow_debug=args.debug_cmdline)
if new_conf != conf:
with tempfile.NamedTemporaryFile("w", suffix=".conf", delete=False) as handle:
handle.write(new_conf)
conf_file = handle.name
commands += ["rm /extlinux/extlinux.conf",
"write %s /extlinux/extlinux.conf" % conf_file]
conf_tmp = conf_file
else:
conf_tmp = None
run_debugfs(fs, commands)
if conf_tmp:
os.unlink(conf_tmp)
with open(raw_image, "r+b") as dst, open(fs, "rb") as src:
dst.seek(offset)
while True:
chunk = src.read(1 << 20)
if not chunk:
break
dst.write(chunk)
print("patched pmOS_boot at %#x (%d bytes)" % (offset, size))
except (ValueError, OSError) as exc:
print("FAIL: %s" % exc)
return 1
finally:
if os.path.exists(fs):
os.unlink(fs)
try:
check(raw_image, dtb, boot_img, files=boot_files, dtb_name=dtb_name)
except ValueError as exc:
print("FAIL: %s" % exc)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())