Skip to content

Apple's open-source XNU kernel on Android phones: its own loader and drivers, Metal on the Adreno. Runs from RAM; a reboot gives the phone back to Android.

C

install: a read-only backup tool that proves every copy, and the order of work from RAM to the phone's storage

shimoku98a6b7f1e9ae
diff --git a/ci/github-check.yml b/ci/github-check.yml
index af93be7..010c63f 100644
--- a/ci/github-check.yml
+++ b/ci/github-check.yml
@@ -38,6 +38,8 @@ jobs:
run: python3 tools/mkesp-test.py
- name: The kernel's version string is made as it should be
run: python3 tools/kernel-version-test.py
+ - name: The backup tool only reads, copies exactly, and proves every copy
+ run: python3 tools/backup-partitions-test.py
- name: The boot-argument catalogue is read from the source, and is current
run: |
python3 tools/boot-args-test.py
diff --git a/docs/install-safe.md b/docs/install-safe.md
new file mode 100644
index 0000000..bd0a249
--- /dev/null
+++ b/docs/install-safe.md
@@ -0,0 +1,64 @@
+# From RAM to the phone's own storage, without a brick: the order, the gates, and what has been done
+
+[install.md](install.md) is the design and its rules. This is the order of work that follows from them, with a gate between
+every two steps, and an honest account of how far it has got. **Nothing here has written a byte to a phone.** The first two
+stages are tools that only read; the rest is a plan for a person at the desk.
+
+## Why this order
+
+A phone is bricked by writing the wrong thing to the chain it starts from, or by leaving it with no slot that starts. So:
+
+1. nothing is written until what cannot be made again has been copied off and proven;
+2. the system moves to the phone's own storage **before** the boot chain does: the loader is still started from RAM
+ (`fastboot boot`), so a wrong system image costs a reboot into Android, not a phone;
+3. the boot chain moves last, into the slot Android does **not** run from, with the other slot left exactly as it was;
+4. the bootloader chain itself (`xbl`, `abl`, `tz`, `hyp` ...), the modem's and the radio's calibration, and the active slot are
+ never written by this project. On Xiaomi phones a damaged bootloader chain can need an authorised service tool to revive;
+ that is the one failure no step here may risk.
+
+## The stages
+
+| # | Stage | What happens to the phone | State |
+|---|---|---|---|
+| 0 | **Preflight.** Two slots? Which one is Android on? Is the bootloader really unlocked? Battery over 60% and the cable good? `darwin` already there? | nothing; reads | `make doctor` does most of it. The battery gate is NOT checked by anything yet (see "The phone that went quiet") |
+| 1 | **Backup.** The boot-related partitions of both slots, `vbmeta*`, `persist`, `modemst1/2`, `fsg`, the partition tables, and with `--with-bootchain` the chain. Each copy is proven by three SHA-256s (the phone's before, the host's, the phone's after) | nothing; reads, as root | **written and tested** against a stand-in adb: `tools/backup-partitions.py` (`tools/backup-partitions-test.py`). Not run on a phone: the phone was not on USB when it was finished |
+| 2 | **Carve `darwin`** off the end of Android's userdata | **Android's data is shrunk and moved**: the f2fs is resized and the GPT rewritten. Back up the phone's data first (the user's own, with Android's tools); the tool does not | plan only: `tools/userdata-carve.py` prints the commands and writes nothing |
+| 3 | **Write the system image to `darwin`** with the guarded writer | writes `darwin` only; the writer refuses any other partition and reads every write back | exists: `tools/darwin-write.py`; its self-test refuses the wrong partition. Never run on a phone |
+| 4 | **Boot from the phone's storage, still from RAM.** `fastboot boot` the loader, and the kernel mounts its root from `darwin` (`root_apfs=`) instead of from an image uploaded to RAM | `fastboot boot` writes nothing; `ufs_write` stays 0 | **not verified**: the arguments the flash recipe needs are not confirmed. Repeat until it is boring; this is the gate before stage 5 |
+| 5 | **The boot image into the inactive slot**, `fastboot set_active` to it, once | writes the inactive slot's `boot` (and what its recipe needs); the active slot is not touched | **not done, not tried**; whether Project Silicium's boot manager behaves from a boot slot, and what `vbmeta` says to a modified boot image, are unknown |
+| 6 | **A way back**, tested before it is needed: `fastboot set_active a` (or b) from the bootloader, and Android's own slot switch | writes the slot flag | the standard fastboot command; not tried here |
+
+Stage 4 is the one that changes the project: it makes "the system lives in RAM for the length of a session" false, and it does so
+without any step that can brick. A phone that boots from `darwin` by `fastboot boot` is already "not RAM"; stage 5 only removes the cable.
+
+## The gates
+
+A stage is started only when the one before it has a recorded result and a person has read it:
+
+- before stage 2: `manifest.json` of stage 1 exists and every partition in it is proven; a copy of the phone's data exists;
+- before stage 3: the new GPT was read back from the phone and equals what the carve tool made; Android boots and its data is there;
+- before stage 5: stage 4 has booted the system from `darwin` at least three times in a row, and the log says so;
+- before every write: `tools/provenance.allow` lists the writer (CI fails if a writer appears that is not listed).
+
+## The phone that went quiet
+
+Writing this, the phone vanished from USB: not adb, not fastboot, not Qualcomm's emergency mode. The last run before that ended
+normally and left the phone in the loader. The likeliest cause is the **battery**: nothing charges the phone while it sits in the
+loader (the kernel's charging path is not written; the UEFI shell does not charge), the screen was on for hours, and a long session
+is a flat battery. If so, plugging it into a charger for a few minutes brings it back to Android by itself. That has not been
+confirmed. It is why stage 0 has a battery gate, and why an unattended run is not a safe thing to leave overnight until the kernel
+reads the battery and stops the run (`thermal_stop` is the same idea for heat; a battery guard is the same again, and needs the
+battery reading of the audio DSP's driver, which only runs with `adsp=1`).
+
+## What the user decides
+
+1. Whether to give up some of the phone's storage (stage 2): the size of `darwin`. The system image alone is 2.5 GB; room to live in
+ is more.
+2. Whether Android's data may be disturbed at all. If not, stages 2 to 5 wait for a second phone or a spare partition.
+3. Who is at the desk for stage 5.
+
+## What was not done tonight, on purpose
+
+No partition was written, no slot was switched, `darwin` was not made, and the installer was not written: an installer that
+has never run on a phone, written while its owner sleeps, would be a guess with a progress bar. The tools above are the part
+that could be built and tested without a phone, and they are.
diff --git a/tools/backup-partitions-test.py b/tools/backup-partitions-test.py
new file mode 100644
index 0000000..56c32a5
--- /dev/null
+++ b/tools/backup-partitions-test.py
@@ -0,0 +1,162 @@
+#!/usr/bin/env python3
+"""tools/backup-partitions.py against a stand-in adb: a "phone" that is a folder of files.
+
+What is checked: the dry run copies nothing; a real run copies exactly the bytes, proves them with three hashes and writes the
+manifest and the restore notes (which are text, never run); a partition the phone lacks is skipped and said; a partition that
+changes while it is read is read again, and one that never holds still is not kept; a phone without root stops the tool before
+a byte is copied; and the stand-in saw only reads (no `of=`, no write).
+"""
+import hashlib
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+TOOL = os.path.join(HERE, "backup-partitions.py")
+failures = []
+
+# the stand-in adb: `adb exec-out su -c "<command>"` on a phone that is the folder $FAKE_PHONE (parts/NAME, disk_sda)
+FAKE = r'''
+import hashlib, os, re, sys
+root = os.environ["FAKE_PHONE"]
+mode = os.environ.get("FAKE_MODE", "")
+args = sys.argv[1:]
+log = open(os.path.join(root, "commands.log"), "a")
+if args[:3] != ["exec-out", "su", "-c"]:
+ sys.exit(2)
+cmd = args[3]
+log.write(cmd + "\n"); log.close()
+if mode == "noroot":
+ sys.stderr.write("su: not allowed\n"); sys.exit(1)
+names = sorted(os.listdir(os.path.join(root, "parts")))
+node_file = {"/dev/block/sda%d" % (i + 1): os.path.join(root, "parts", n) for i, n in enumerate(names)}
+node_file["/dev/block/sda"] = os.path.join(root, "disk_sda")
+counter = os.path.join(root, "hashcount")
+
+def data(node, skip=None, count=None, bs=1048576):
+ b = open(node_file[node], "rb").read()
+ if skip is not None:
+ b = b[skip * bs: (skip + count) * bs]
+ return b
+
+def sha(b):
+ return hashlib.sha256(b).hexdigest()
+
+m = re.fullmatch(r"ls -l /dev/block/by-name", cmd)
+if m:
+ for i, n in enumerate(names):
+ print("lrwxrwxrwx 1 root root 16 2024-01-01 00:00 %s -> /dev/block/sda%d" % (n, i + 1))
+ sys.exit(0)
+m = re.fullmatch(r"blockdev --getsize64 (\S+)", cmd)
+if m:
+ print(os.path.getsize(node_file[m.group(1)])); sys.exit(0)
+m = re.fullmatch(r"sha256sum (\S+)", cmd)
+if m:
+ b = data(m.group(1))
+ if mode == "change": # the partition changes under the copy: the first hash is of the old content
+ n = int(open(counter).read()) if os.path.exists(counter) else 0
+ open(counter, "w").write(str(n + 1))
+ if n == 0: # only the first look: the second attempt finds it holding still
+ with open(node_file[m.group(1)], "r+b") as f:
+ f.seek(0); f.write(bytes([(b[0] + 1) % 256]))
+ print("%s %s" % (sha(b), m.group(1))); sys.exit(0)
+m = re.fullmatch(r"dd if=(\S+) bs=(\d+) skip=(\d+) count=(\d+) 2>/dev/null \| sha256sum", cmd)
+if m:
+ print("%s -" % sha(data(m.group(1), int(m.group(3)), int(m.group(4)), int(m.group(2))))); sys.exit(0)
+m = re.fullmatch(r"dd if=(\S+) bs=(\d+) skip=(\d+) count=(\d+) 2>/dev/null", cmd)
+if m:
+ sys.stdout.buffer.write(data(m.group(1), int(m.group(3)), int(m.group(4)), int(m.group(2)))); sys.exit(0)
+m = re.fullmatch(r"dd if=(\S+) bs=1048576 2>/dev/null", cmd)
+if m:
+ sys.stdout.buffer.write(data(m.group(1)))
+ if mode == "never": # one that never holds still: every look is different
+ with open(node_file[m.group(1)], "r+b") as f:
+ f.seek(0); f.write(os.urandom(1))
+ sys.exit(0)
+sys.stderr.write("stand-in adb: no such command: %s\n" % cmd); sys.exit(3)
+'''
+
+
+def check(label, ok, detail=""):
+ print("%s %s" % ("ok " if ok else "FAIL", label))
+ if not ok:
+ failures.append(label)
+ if detail:
+ print(" " + str(detail).strip().replace("\n", "\n ")[:500])
+
+
+def phone(root, parts):
+ os.makedirs(os.path.join(root, "parts"))
+ for name, content in parts.items():
+ open(os.path.join(root, "parts", name), "wb").write(content)
+ open(os.path.join(root, "disk_sda"), "wb").write(bytes(range(256)) * 16 * 64) # 64 blocks of 4096
+ open(os.path.join(root, "fake_adb.py"), "w").write(FAKE)
+
+
+def run(root, out, *flags, mode=""):
+ env = dict(os.environ, FAKE_PHONE=root, FAKE_MODE=mode)
+ return subprocess.run([sys.executable, TOOL, out, "--adb", sys.executable, "--adb-arg", os.path.join(root, "fake_adb.py")] + list(flags),
+ capture_output=True, text=True, env=env)
+
+
+work = tempfile.mkdtemp(prefix="backup-test-")
+try:
+ boot = os.urandom(3000)
+ persist = os.urandom(70000)
+ parts = {"boot_a": boot, "persist": persist, "userdata": os.urandom(200000), "vbmeta_a": b"AVB0" + os.urandom(100)}
+ root = os.path.join(work, "phone")
+ phone(root, parts)
+
+ out = os.path.join(work, "out-dry")
+ r = run(root, out)
+ check("dry run: says what it would read, copies nothing", r.returncode == 0 and not os.path.exists(out) and "boot_a" in r.stdout and "nothing was copied" in r.stdout, r.stdout + r.stderr)
+ check("dry run: the partitions the phone lacks are said, not invented", "boot_b" in r.stdout and "the phone does not have it" in r.stdout, r.stdout)
+ check("dry run: userdata is never in the plan", "userdata" not in r.stdout, r.stdout)
+
+ out = os.path.join(work, "out")
+ r = run(root, out, "--yes")
+ check("a real run succeeds", r.returncode == 0, r.stdout + r.stderr)
+ same = all(open(os.path.join(out, n + ".img"), "rb").read() == parts[n] for n in ("boot_a", "persist", "vbmeta_a"))
+ check("the copies are the bytes of the partitions", same)
+ check("userdata was not copied", not os.path.exists(os.path.join(out, "userdata.img")))
+ manifest = json.load(open(os.path.join(out, "manifest.json")))
+ by = {p["name"]: p for p in manifest["partitions"]}
+ check("the manifest has each hash", by["boot_a"]["sha256"] == hashlib.sha256(boot).hexdigest() and by["persist"]["bytes"] == len(persist), by)
+ disk = open(os.path.join(root, "disk_sda"), "rb").read()
+ heads = [t for t in manifest["tables"] if t["part"] == "head"]
+ check("the partition tables: the head and the tail of the disk, 8 blocks each",
+ len(manifest["tables"]) == 2 and heads and open(os.path.join(out, "gpt-sda-head.bin"), "rb").read() == disk[:8 * 4096]
+ and open(os.path.join(out, "gpt-sda-tail.bin"), "rb").read() == disk[-8 * 4096:], manifest["tables"])
+ restore = open(os.path.join(out, "restore.txt")).read()
+ check("restore.txt names the fastboot lines and is only text", "fastboot flash persist persist.img" in restore and restore.startswith("# What would put these back"), restore)
+ log = open(os.path.join(root, "commands.log")).read()
+ check("the stand-in saw only reads: no of=, no write, no flash", "of=" not in log and "write" not in log and "flash" not in log and ">" not in log.replace("2>/dev/null", ""), log[:400])
+
+ # a partition that changes while it is read is read again and kept once it holds still
+ shutil.rmtree(root); phone(root, parts)
+ out = os.path.join(work, "out-change")
+ r = run(root, out, "--yes", "--only", "boot_a", mode="change")
+ check("a partition that changes under the copy is read again", r.returncode == 0 and "the hashes differ" in r.stdout, r.stdout + r.stderr)
+ check("... and what was kept matches the partition as it is now", open(os.path.join(out, "boot_a.img"), "rb").read() == open(os.path.join(root, "parts", "boot_a"), "rb").read())
+
+ # one that never holds still is not kept
+ shutil.rmtree(root); phone(root, parts)
+ out = os.path.join(work, "out-never")
+ r = run(root, out, "--yes", "--only", "boot_a", mode="never")
+ check("a partition that never holds still stops the tool, with the reason", r.returncode == 1 and "could not be proven" in r.stderr, r.stdout + r.stderr)
+ check("... and its copy is not left behind", not os.path.exists(os.path.join(out, "boot_a.img")))
+
+ # no root: stopped before a byte is copied
+ shutil.rmtree(root); phone(root, parts)
+ out = os.path.join(work, "out-noroot")
+ r = run(root, out, "--yes", mode="noroot")
+ check("a phone without root stops the tool before anything is copied", r.returncode == 1 and "STOPPED" in r.stderr and not os.path.exists(out), r.stdout + r.stderr)
+finally:
+ shutil.rmtree(work, ignore_errors=True)
+
+if failures:
+ sys.exit("backup-partitions-test: %d FAILED" % len(failures))
+print("backup-partitions-test: all passed")
diff --git a/tools/backup-partitions.py b/tools/backup-partitions.py
new file mode 100644
index 0000000..a2f389e
--- /dev/null
+++ b/tools/backup-partitions.py
@@ -0,0 +1,200 @@
+#!/usr/bin/env python3
+"""Copy the partitions that cannot be made again off the phone, and prove the copies: READ ONLY.
+
+usage: tools/backup-partitions.py OUTDIR [--yes] [--only NAME,NAME] [--with-bootchain] [--adb PROGRAM [--adb-arg ARG ...]]
+
+Rule 1 of docs/install.md: before anything is ever written to a phone, what could not be made again is copied off it and
+checked. This is that copy. It never writes to the phone: the only things it runs there are `ls`, `blockdev`, `dd if=`
+(a read) and `sha256sum`. Without --yes it makes no copy at all and says what it would read and how much room that needs.
+
+What is copied (the names are the phone's own, from /dev/block/by-name; one that the phone does not have is skipped and said):
+ the small partitions that decide whether it boots boot_a boot_b init_boot_a init_boot_b vendor_boot_a vendor_boot_b dtbo_a dtbo_b
+ vbmeta_a vbmeta_b vbmeta_system_a vbmeta_system_b misc devinfo
+ the ones that hold THIS phone's identity and radio persist modemst1 modemst2 fsg (the calibration, the IMEI, the Wi-Fi and
+ Bluetooth addresses: Android cannot make them again)
+ the partition tables the first and last 8 blocks of each disk (sda ... sdf), which is what the carve
+ (tools/userdata-carve.py) changes
+ with --with-bootchain: xbl xbl_config abl aop aop_config tz hyp devcfg qupfw uefisecapp shrm cpucp keymaster featenabler imagefv
+ (small; what the phone starts from; useful if it ever has to be revived)
+Never copied: userdata, super and the other big ones (they are Android's, and their size is the problem).
+
+How a copy is proven. The partition is read over adb (exec-out, so the bytes are not changed on the way), its SHA-256 is made as
+it arrives, and the phone is then asked for the SHA-256 of the same partition, once BEFORE and once AFTER the copy: the three must
+be the same, or the partition changed while it was read (then it is read again, up to three times) or the copy is wrong. The copy
+is kept only if they agree. manifest.json says what was copied, its size and hash, and when; restoring is NOT done by this tool:
+`restore.txt` says which fastboot command would put each back, for a person to run.
+
+These files are the phone's own and some of them (persist, modemst*, fsg) hold its identity: keep them off the network, and do
+not commit them (the folder name backups/ is ignored by git).
+
+Needs root on the phone (`su`): the partitions are not readable by the shell user.
+"""
+import argparse
+import datetime
+import hashlib
+import json
+import os
+import re
+import subprocess
+import sys
+
+BOOT = ["boot_a", "boot_b", "init_boot_a", "init_boot_b", "vendor_boot_a", "vendor_boot_b", "dtbo_a", "dtbo_b", "vbmeta_a", "vbmeta_b",
+ "vbmeta_system_a", "vbmeta_system_b", "misc", "devinfo"]
+IDENTITY = ["persist", "modemst1", "modemst2", "fsg"]
+BOOTCHAIN = ["xbl", "xbl_config", "abl", "aop", "aop_config", "tz", "hyp", "devcfg", "qupfw", "uefisecapp", "shrm", "cpucp", "keymaster",
+ "featenabler", "imagefv"]
+BLOCK = 4096
+TRIES = 3
+ENOUGH_FREE = 1.5 # the room that has to be free on the host, as a multiple of what is copied
+
+
+class Failure(Exception):
+ pass
+
+
+def device(adb, command, binary=False):
+ """Run `command` as root on the phone; its output, or a Failure."""
+ r = subprocess.run(adb + ["exec-out", "su", "-c", command], capture_output=True)
+ if r.returncode != 0:
+ raise Failure("on the phone `%s` failed (%d): %s" % (command, r.returncode, r.stderr.decode(errors="replace").strip()[:200]))
+ return r.stdout if binary else r.stdout.decode(errors="replace")
+
+
+def by_name(adb):
+ """{partition name: block device} from /dev/block/by-name, resolved to the device the link points at."""
+ out = device(adb, "ls -l /dev/block/by-name")
+ parts = {}
+ for line in out.splitlines():
+ m = re.search(r"\s(\S+) -> (/dev/block/\S+)\s*$", line.strip())
+ if m:
+ parts[m.group(1)] = m.group(2)
+ if not parts:
+ raise Failure("the phone shows no partitions under /dev/block/by-name (is the shell root? `adb shell su -c id`)")
+ return parts
+
+
+def size_of(adb, node):
+ out = device(adb, "blockdev --getsize64 %s" % node).strip()
+ if not out.isdigit():
+ raise Failure("%s: the size is %r" % (node, out))
+ return int(out)
+
+
+def hash_on_phone(adb, node, count=None, skip=None):
+ """SHA-256 of the whole device, or of `count` 4 KB blocks after `skip` of them."""
+ if count is None:
+ cmd = "sha256sum %s" % node
+ else:
+ cmd = "dd if=%s bs=%d skip=%d count=%d 2>/dev/null | sha256sum" % (node, BLOCK, skip, count)
+ out = device(adb, cmd).split()
+ if not out or not re.fullmatch(r"[0-9a-f]{64}", out[0]):
+ raise Failure("%s: the phone's sha256sum said %r" % (node, out[:1]))
+ return out[0]
+
+
+def copy_one(adb, node, path, size, skip=None, count=None):
+ """Read the device over adb into `path`; the SHA-256 of what arrived."""
+ if count is None:
+ cmd = "dd if=%s bs=1048576 2>/dev/null" % node
+ else:
+ cmd = "dd if=%s bs=%d skip=%d count=%d 2>/dev/null" % (node, BLOCK, skip, count)
+ h = hashlib.sha256()
+ total = 0
+ with subprocess.Popen(adb + ["exec-out", "su", "-c", cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p, open(path, "wb") as out:
+ for chunk in iter(lambda: p.stdout.read(1 << 20), b""):
+ out.write(chunk)
+ h.update(chunk)
+ total += len(chunk)
+ p.wait()
+ err = p.stderr.read().decode(errors="replace").strip()
+ if p.returncode != 0:
+ raise Failure("reading %s failed (%d): %s" % (node, p.returncode, err[:200]))
+ if total != size:
+ raise Failure("%s: %d bytes arrived, %d were expected" % (node, total, size))
+ return h.hexdigest()
+
+
+def proven_copy(adb, node, path, size, skip=None, count=None):
+ """A copy that three hashes agree on (the phone's before, the host's, the phone's after), or a Failure."""
+ last = ""
+ for attempt in range(1, TRIES + 1):
+ before = hash_on_phone(adb, node, count, skip)
+ mine = copy_one(adb, node, path, size, skip, count)
+ after = hash_on_phone(adb, node, count, skip)
+ if before == mine == after:
+ return mine
+ last = "phone before %s.., host %s.., phone after %s.." % (before[:12], mine[:12], after[:12])
+ print(" attempt %d: the hashes differ (%s)" % (attempt, last))
+ os.remove(path)
+ raise Failure("%s: the copy could not be proven after %d tries (%s); it was not kept" % (node, TRIES, last))
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("outdir")
+ ap.add_argument("--yes", action="store_true", help="really copy (without it: say what would be)")
+ ap.add_argument("--only", help="only these partitions, comma separated (and their disks' tables are not copied)")
+ ap.add_argument("--with-bootchain", action="store_true")
+ ap.add_argument("--adb", default="adb", help="the adb program (tests use a stand-in)")
+ ap.add_argument("--adb-arg", action="append", default=[], help="an argument to put after the adb program (tests: the stand-in's script)")
+ a = ap.parse_args(argv)
+ adb = [a.adb] + a.adb_arg
+ try:
+ parts = by_name(adb)
+ wanted = [n.strip() for n in a.only.split(",")] if a.only else BOOT + IDENTITY + (BOOTCHAIN if a.with_bootchain else [])
+ plan, missing = [], []
+ for name in wanted:
+ if name in parts:
+ plan.append((name, parts[name], size_of(adb, parts[name])))
+ else:
+ missing.append(name)
+ disks = {}
+ if not a.only:
+ for node in sorted({re.sub(r"p?\d+$", "", n) for n in parts.values() if re.search(r"/sd[a-z]\d+$", n)}):
+ disks[node] = size_of(adb, node)
+ total = sum(s for _n, _d, s in plan) + sum(2 * 8 * BLOCK for _ in disks)
+ print("backup-partitions: %d partitions to copy, %d disks' tables, %.1f MB in all" % (len(plan), len(disks), total / 1e6))
+ for name, node, size in plan:
+ print(" %-18s %-26s %10d bytes" % (name, node, size))
+ for node in disks:
+ print(" %-18s %-26s first and last 8 blocks" % ("table of " + os.path.basename(node), node))
+ for name in missing:
+ print(" %-18s the phone does not have it: skipped" % name)
+ if not a.yes:
+ print("backup-partitions: nothing was copied (add --yes). This tool only reads from the phone.")
+ return 0
+ os.makedirs(a.outdir, exist_ok=True)
+ free = __import__("shutil").disk_usage(a.outdir).free
+ if free < total * ENOUGH_FREE:
+ raise Failure("%.1f MB free in %s, and %.1f MB is %.1f times what is copied: not enough" % (free / 1e6, a.outdir, total * ENOUGH_FREE / 1e6, ENOUGH_FREE))
+ manifest = {"made": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"),
+ "note": "read only; the hashes were checked on the phone before and after each copy", "partitions": [], "tables": []}
+ restore = ["# What would put these back. NOT run by backup-partitions.py: a person runs a line, knowing why.",
+ "# Never write a bootchain partition (xbl abl tz hyp ...) unless you are certain; a wrong one cannot be undone without EDL.", ""]
+ for name, node, size in plan:
+ path = os.path.join(a.outdir, name + ".img")
+ print("backup-partitions: %s ..." % name, flush=True)
+ digest = proven_copy(adb, node, path, size)
+ manifest["partitions"].append({"name": name, "node": node, "bytes": size, "sha256": digest, "file": name + ".img"})
+ restore.append("fastboot flash %s %s # sha256 %s" % (name, name + ".img", digest))
+ for node, size in disks.items():
+ blocks = size // BLOCK
+ for label, skip in (("head", 0), ("tail", blocks - 8)):
+ path = os.path.join(a.outdir, "gpt-%s-%s.bin" % (os.path.basename(node), label))
+ digest = proven_copy(adb, node, path, 8 * BLOCK, skip, 8)
+ manifest["tables"].append({"disk": node, "part": label, "skip_blocks": skip, "blocks": 8, "sha256": digest, "file": os.path.basename(path)})
+ with open(os.path.join(a.outdir, "manifest.json"), "w", newline="\n") as f:
+ json.dump(manifest, f, indent=2)
+ f.write("\n")
+ with open(os.path.join(a.outdir, "restore.txt"), "w", newline="\n") as f:
+ f.write("\n".join(restore) + "\n")
+ print("backup-partitions: %d partitions and %d table copies proven and kept in %s (manifest.json, restore.txt)" %
+ (len(manifest["partitions"]), len(manifest["tables"]), a.outdir))
+ return 0
+ except Failure as e:
+ print("backup-partitions: STOPPED: %s" % e, file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())