forked from Blendman974/faceclaw
128 lines
5.5 KiB
Python
128 lines
5.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Turns a built g1v0 image into what the app ships: app/g1/firmware/g1v0-image.ts and g1v0-own-bytes.ts.
|
|
|
|
A built image embeds two of Even's files (scouter_kit g1_firmware/README.md, "Build the image"), which must not be
|
|
published: its network-core image and its TouchBar table. Those bytes are cut out here, and the phone puts them back
|
|
from Even's own download (app/g1/firmware-builder.ts). The result has the same SHA-256 as the build, so the MCUboot
|
|
signature made at build time stays valid.
|
|
|
|
tools/g1_firmware_bundle.py WORK/build/g1v0-v0563/zephyr/app_update.bin --firmware-dir ~/src/scouter_kit/g1_firmware
|
|
|
|
--firmware-dir holds stock_images.txt and, under work/firmware/1.6.6/, Even's unpacked files (scripts/fetch_stock.sh).
|
|
"""
|
|
import argparse
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
import struct
|
|
import subprocess
|
|
import zlib
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parent.parent
|
|
OUT = ROOT / "app" / "g1" / "firmware"
|
|
STOCK_VERSION = "1.6.6"
|
|
TABLE = "aw9320x_table"
|
|
|
|
|
|
def sha(data):
|
|
return hashlib.sha256(data).hexdigest()
|
|
|
|
|
|
def stock_pins(firmware_dir):
|
|
rows = [line.split() for line in (firmware_dir / "stock_images.txt").read_text().splitlines()
|
|
if line.strip() and not line.startswith("#")]
|
|
return {row[1]: row[2:] for row in rows if row[0] == STOCK_VERSION}
|
|
|
|
|
|
def only_place(image, part, label):
|
|
at = image.find(part)
|
|
if at < 0:
|
|
raise SystemExit(f"{label} is not in the image: was it built with Even's {STOCK_VERSION}?")
|
|
if image.find(part, at + 1) >= 0:
|
|
raise SystemExit(f"{label} is in the image twice")
|
|
return at
|
|
|
|
|
|
def image_version(image):
|
|
if image[:4] != bytes.fromhex("3db8f396"):
|
|
raise SystemExit("not an MCUboot image")
|
|
major, minor, revision = struct.unpack_from("<BBH", image, 20)
|
|
return f"{major}.{minor}.{revision}"
|
|
|
|
|
|
def source_commit(firmware_dir):
|
|
def git(*args):
|
|
return subprocess.run(["git", "-C", str(firmware_dir), *args], capture_output=True, text=True).stdout.strip()
|
|
return git("rev-parse", "--short=12", "HEAD") + ("+uncommitted" if git("status", "--porcelain", "--", "firmware", "../src/vm") else "")
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
ap.add_argument("image", type=Path)
|
|
ap.add_argument("--firmware-dir", type=Path, required=True)
|
|
args = ap.parse_args()
|
|
|
|
image = args.image.read_bytes()
|
|
pins = stock_pins(args.firmware_dir)
|
|
stock = args.firmware_dir / "work" / "firmware" / STOCK_VERSION
|
|
net = (stock / "net_core_app_update.bin").read_bytes()
|
|
app = (stock / "app_update.bin").read_bytes()
|
|
if sha(net) != pins["net_core_app_update.bin"][0] or sha(app) != pins["app_update.bin"][0]:
|
|
raise SystemExit(f"Even's files in {stock} don't match stock_images.txt")
|
|
|
|
table_hash, table_where = pins[TABLE]
|
|
table_offset, table_length = table_where.split("@")[1].split("+")
|
|
table_offset, table_length = int(table_offset, 16), int(table_length)
|
|
table = app[table_offset:table_offset + table_length]
|
|
if sha(table) != table_hash:
|
|
raise SystemExit("the TouchBar table isn't where stock_images.txt says")
|
|
|
|
parts = sorted([
|
|
{"offset": only_place(image, net, "the net-core image"), "length": len(net), "file": "net_core_app_update.bin",
|
|
"fileOffset": 0, "sha256": sha(net)},
|
|
{"offset": only_place(image, table, "the TouchBar table"), "length": len(table), "file": "app_update.bin",
|
|
"fileOffset": table_offset, "sha256": table_hash},
|
|
], key=lambda part: part["offset"])
|
|
|
|
own = bytearray()
|
|
position = 0
|
|
for part in parts:
|
|
own += image[position:part["offset"]]
|
|
position = part["offset"] + part["length"]
|
|
own += image[position:]
|
|
for label, part in (("net-core image", net), ("TouchBar table", table)):
|
|
if bytes(part[:64]) in own:
|
|
raise SystemExit(f"the bytes left over still hold Even's {label}")
|
|
|
|
manifest = {
|
|
"version": image_version(image),
|
|
"sha256": sha(image),
|
|
"size": len(image),
|
|
"source": source_commit(args.firmware_dir),
|
|
"stockVersion": STOCK_VERSION,
|
|
"stockZipUrl": pins["zip"][1],
|
|
"stockZipSha256": pins["zip"][0],
|
|
"parts": parts,
|
|
}
|
|
OUT.mkdir(parents=True, exist_ok=True)
|
|
(OUT / "g1v0-image.ts").write_text(
|
|
"// AUTO-GENERATED by tools/g1_firmware_bundle.py -- do not edit by hand.\n"
|
|
"// What the app installs on a G1, and the parts of it that come from Even's own download.\n\n"
|
|
"export type G1FirmwarePart = { offset: number; length: number; file: string; fileOffset: number; sha256: string };\n\n"
|
|
"export type G1FirmwareImage = {\n"
|
|
" version: string;\n sha256: string;\n size: number;\n source: string;\n stockVersion: string;\n"
|
|
" stockZipUrl: string;\n stockZipSha256: string;\n parts: G1FirmwarePart[];\n};\n\n"
|
|
f"export const G1V0_IMAGE: G1FirmwareImage = {json.dumps(manifest, indent=2)};\n")
|
|
packed = zlib.compress(bytes(own), 9)
|
|
(OUT / "g1v0-own-bytes.ts").write_text(
|
|
"// AUTO-GENERATED by tools/g1_firmware_bundle.py -- do not edit by hand.\n"
|
|
"// The built g1v0 image without Even's parts (g1v0-image.ts), deflated.\n\n"
|
|
f'export const G1V0_OWN_BYTES_BASE64 = "{base64.b64encode(packed).decode()}";\n')
|
|
print(f"g1v0 {manifest['version']}: {len(image)} B, {len(own)} B of its own, {len(packed)} B deflated; "
|
|
f"parts at {[part['offset'] for part in parts]}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|