Merge pull request #247 from dikeckaan/fbe-reset-resume

Make room on an encrypted Android: reset by recovery, then resume the install (EXPERIMENTAL, kano's flow)
This commit is contained in:
KAAN DIKEC authored and GitHub committed 2026-10-15 22:44:37 +03:00
commit 70a21b243c
20 files changed
+1843 -111

No files matched your search

+1 -1
View File
@@ -22,7 +22,7 @@ jobs:
run: python tools/check-i18n.py
- name: Shell syntax
shell: bash
run: for f in install.sh uninstall.sh tools/i18n.sh tools/self-update.sh tools/linux-mode.sh tools/answers.sh tools/releases.sh tools/gui-launch.sh tools/package.sh android/magisk/computer/start.sh android/magisk/computer/start-gui.sh android/magisk/computer/uninstall-linux.sh android/magisk/installer/mu300-install.sh android/magisk/installer/customize.sh tools/android-boot-image.sh tools/make-magisk-zips.sh; do sh -n "$f"; done
run: for f in install.sh uninstall.sh tools/i18n.sh tools/self-update.sh tools/linux-mode.sh tools/answers.sh tools/releases.sh tools/gui-launch.sh tools/package.sh tools/resume.sh android/magisk/computer/start.sh android/magisk/computer/start-gui.sh android/magisk/computer/uninstall-linux.sh android/magisk/installer/mu300-install.sh android/magisk/installer/customize.sh tools/android-boot-image.sh tools/make-magisk-zips.sh; do sh -n "$f"; done
- name: PowerShell 5.1 parse
shell: powershell
run: |
+24
View File
@@ -199,6 +199,30 @@ and it asks first. Back the device up with `tools/backup-device.sh` before sayin
neither case, stop and open an issue with what `--check` printed; they identify the variant. With an SD card in the
slot there is a way that erases nothing: `--check` says so, and the installer offers the card instead.
**Making room is a reset, and the installation resumes afterwards (EXPERIMENTAL).** Android keeps its data
encrypted (file-based encryption, with the metadata key in `/metadata`), and a data filesystem cleared from outside
is one it cannot mount: it would stop in its recovery, waiting for a person at a screen these devices do not have.
So the installer does what kano's desktop installer does (kanoqwq's branch `clean-tf-7.2`, commits `f6b0668d` and
`0e19fe32`): before anything is written it saves a backup (the partition table, `misc`, `boot` and the boot chain of
both slots - never the NV or calibration partitions) and a *transaction* on this computer, in `~/mu300-backups/<date>-<id>/`
(`MU300_BACKUP_DIR` elsewhere). Then it shrinks `userdata` (the backup copy of the table first, both read back),
writes a token to the first 4 KiB of the new region (outside every partition, where the reset does not reach) and
asks Android's own recovery, through the bootloader message in `misc`, to format `userdata` on the next start.
The device restarts, Android is reset - **all of its data is erased** - and starts as new.
Then: set Android up again, turn USB debugging back on and bring root back (Magisk survives in the boot partition,
but its app and its grants were in the erased data: install the Magisk app again and let Shell have root), and run
`./install.sh` (or `.\install.ps1`, or the window) again. It finds the transaction and continues, when the device
(serial, the eMMC's CID), Android's slot, `userdata`'s node, start and size, the partition table (both copies, every
CRC), the region by the installers' own arithmetic, the token on the device and the installer's own tools (the GPT
reader, the region's arithmetic, what formats and fills it, `boot/init`) are all still the ones it was prepared with;
otherwise it stops, having written nothing, and says which. `--resume` insists on a transaction, `--no-resume`
installs as if nothing had been prepared (the region is then space that holds data, and you type `overwrite`),
`--transaction FILE` takes another one (`-Resume`, `-NoResume`, `-Transaction` for `install.ps1`). While a
transaction waits the installer does not update itself. kano says he ran the stage after the reset's check against
his V50's record ("passing the 8.00 GiB partition, identity, token and payload checks") and that the reset itself
"still needs real MU300 validation"; this project has not run it on a device either (FINDINGS 112).
**On the SD card.** With a card of at least 700 MiB in the slot the installer asks whether the Linux filesystem
goes there instead of into the free eMMC space (`MU300_STORAGE=sd` answers it). The card is formatted (ext4,
label `mu300sd`); on the eMMC only `boot_b` (or `boot_a`) and 32 bytes of `misc` are written, so a device with a small eMMC
+2
View File
@@ -18,6 +18,8 @@ tools/storage.sh
tools/releases.sh
tools/release_pick.py
tools/package.sh
tools/resume.sh
tools/resume.py
tools/self-update.sh
tools/gui-launch.sh
tools/gui-launch.ps1
+111 -1
View File
@@ -122,7 +122,7 @@ what replaced it. The table below gives each section's state.
| 54 | A webhook body of the user's own for SMS forwarding: values escaped for the type, never evaluated (#171) | current (unit tests; not sent from a device to a real service) |
| 55 | Imported Android files nobody but root could read: the CP was never loaded (#127, #135, #170) | current (fixed; what differed between #170's boots is not known) |
| 56 | The VPN page showed a refused config without its reason; the engines' own defects are in the VPN module's FINDINGS 26i-26m | current (fixed; measured on the U30 Air) |
| 57 | A 64 GB unit whose partition table has `userdata` filling the disk, and no way to make room from Windows (#32) | current (fixed; unit tests against a table built from #9's figures, not measured on a device) |
| 57 | A 64 GB unit whose partition table has `userdata` filling the disk, and no way to make room from Windows (#32) | current (fixed; the erase of Android's data superseded by §112; unit tests against a table built from #9's figures, not measured on a device) |
| 58 | A service's own error in an HTTP 200 answer to the SMS webhook: a KEY=VALUE check of the answer; a button that clears the delivery log (#171) | current (unit tests; measured on the U30 Air against a fake webhook, not against the real services) |
| 60 | `/run` takes files from every user: the daemons' directories there are checked, and a squatted name is put out of the way (review of #145/#149) | current (fixed for mu300-atd and mu300-voice, F50-B on 5.4 and 7.2.10); `/run` itself is still 1777 |
| 63 | A reused SMS reference number mixed long messages, or kept them from ever being joined; a part delivered again | current (fixed; unit tests only, not measured on a device) |
@@ -140,6 +140,7 @@ what replaced it. The table below gives each section's state.
| 86 | Updating from the panel: System > Update, an update from a file (a release's Magisk zip), and release signatures (`SHA256SUMS.sig`) | current (unit tests, a page test under Node, the commands in the image's container; the device protocol run on a U30 Air on openwrt-luci, 2026-10-15; F50 and Ubuntu not run) |
| 95 | The ZTE V50 (MU3351), experimental: how it is told apart, and what kano measured on his (f6b0668d, 0438ab01) | experimental; nothing of it measured by this project (no V50 here): unit tests, the device trees of an F50 and a U30 Air, both mainline kernels built |
| 111 | One zip, two ways in: Magisk on the device, or unpacked on a computer as the computer's installer (kano's two-entry package, `f6b0668d`); adb not bundled | current (unit and integration tests, the release's real zips built both ways and compared; no install from an unpacked zip on a device) |
| 112 | Making room by a reset, and the installation that resumes afterwards: kano's transaction, Android's recovery formats the encrypted `userdata`, the checks of the resumed run (`f6b0668d`, `0e19fe32`) | experimental; unit tests and tests against fakes (a fake eMMC); not run on a device, here or by kano |
## Hardware and firmware facts
@@ -289,6 +290,8 @@ Asked for often, because a smaller eMMC variant leaves less free space behind `u
that still boots.
* **It rewrites the partition table and erases everything in Android.** Take a full backup first
(`tools/backup-device.sh`), and treat the path as experimental: it has been done by hand on one device.
* (2026-10-15) Android's data is no longer cleared by the installer: Android's own recovery is asked to reset it,
and the installation resumes after the reset (§112).
### 10. Mounting gotchas
* busybox `mount -o loop,offset=` only creates a loop for regular files; for a block device the options go to
@@ -6609,3 +6612,110 @@ window's choices and answers), `tests/test_boot_image.py` (the image without the
**Not measured.** An install from an unpacked zip on a device, on any platform; Windows Explorer's unpacking (the
launchers are CRLF and need no exec bit there; macOS and Linux keep the bits, and `sh start.sh` needs none).
## Making room on an encrypted Android
### 112. Making room by a reset, and the installation that resumes afterwards (EXPERIMENTAL; kano's flow, ported)
**Status: experimental. Unit tests and tests against fakes only. Nobody in this project has run any of it on a
device, and neither has kano run its reset part (below).** The owner asked for kano's reset-and-resume flow (kanoqwq,
branch `clean-tf-7.2`, MIT; commits `f6b0668d` 2026-10-14 "add desktop deployment", which brought
`desktop/installer.py`'s transaction, `validate_resume`, `resume_payload_id` and `desktop/boot/part-prepare.sh`, and
`0e19fe32` 2026-10-15, which added the GUI's journal around it). The owner's word (2026-10-15): "if kano did it, we
don't need to test it, take it." kano's code was read; none of it was run here and no binary of it was taken.
**Why the make-room path changed.** It used to shrink `userdata` from the running Android, then zero the first
32 MiB of it so that Android would "format /data cleanly on the next boot" (§9b, §57). These devices keep `/data`
with file-based and metadata encryption (§9: `dm-default-key`, the key in `/metadata`). A raw filesystem zeroed from
outside then decrypts to noise under the old key, so Android cannot mount it. It reboots into recovery with
`--prompt_and_wipe_data`, and that prompt waits for a person at a screen. The F50, U30 Air and V50 have no screen.
kano's answer is to ask recovery itself for the reset. That is AOSP's bootloader message in the first 2 KiB of
`misc`: `boot-recovery` at 0 and `recovery\n--wipe_data\n` at 0x40. Recovery formats `userdata` at its new size and
resets the encryption with it. His `part-prepare.sh` says "the vendor flashing tool's erase-userdata writes the same
block, zeroed in full". That is the one piece of device evidence he gives for the mechanism.
**What his flow does, and what this port does.**
| kano (`desktop/installer.py`, `part-prepare.sh`) | here (`tools/resume.sh`, `tools/resume.py`, `install.ps1`) |
|---|---|
| backup on the computer in `~/mu300-backups/<date>-<cid>`: both GPT copies, misc, boot and the boot chain of both slots, `SHA256SUMS` | the same, each file checked against `sha256sum` on the device; the NV and calibration partitions are never read |
| `transaction.json` saved before the first write (`prepared-request`); serial, slot, `storage` (CID, node, start, size, disk), target, need, token, payload identity | the same fields, written atomically by `resume.py new`; `prepared` once everything is written |
| stage one in a desktop initramfs on the Linux slot: checks the request against the device, carves `userdata` and a `mu300root` GPT partition, writes the token to its first sector, writes the BCB and Android's slot to misc, reboots | from the running Android, as this project's make-room path always did: the new table (the backup copy first, both read back, resize-last-partition.py checks both and every CRC), the token in the first 4 KiB of the region behind `userdata` (read back), the BCB (read back, and the A/B block behind it unchanged). No GPT partition: this project's Linux region stays unpartitioned (§9) |
| recovery formats the smaller `userdata`; Android starts as new; the user sets it up, enables USB debugging and restores root | the same; the installer says so, and that Magisk's app and grants were in the erased data |
| `resume-internal-install`: the newest transaction under `~/mu300-backups`, or `--transaction` | found by itself on the next run (newest waiting for this serial and CID), or `--resume` / `--transaction FILE`; `--no-resume` ignores it |
| `validate_resume`: CID, node, start, slot, serial; userdata size equal to the target; root geometry; the marker `MU300-PART-PREPARED-V2 <token>` unless the record says installed | the same, plus the table read back (both copies, every CRC; its first, end and usable end), the region by `FreeRegion`/`region_probe`'s arithmetic, and the BCB: a reset that has not run yet (misc still asks for it) is said as such, before anything else |
| `resume_payload_id`: the checksums of his boot image, rootfs, filesystem tools and kernel family, not of prompts or paths | the checksums of the tools that decide what a resumed install writes where: `resize-last-partition.py`, `storage.sh`, `android-install.sh`, `android-mount-mu300root.sh`, `boot/init` (and, from an unpacked zip, its two payload files: §111). The installer does not update itself while a transaction waits |
| state `installed` after the boot image is written | the same, after `write_linux_boot` |
| `encrypted()`: encrypted state or type, or `/data` on dm, is encrypted; `unencrypted` with an F2FS/ext4 magic is not; anything else raises | the same rule (`resume.py encrypted`); an unknown state stops the make-room path, nothing changed |
What kano has that is not ported: the preserving offline shrink for an unencrypted `userdata`. This project's
make-room path always erases. Also not ported: his desktop initramfs and its tools, the free-GPT-gap install into a
new partition, and the userdata image. Where this differs on purpose: the token. kano writes it offline, with nothing
mounted. Here it is written while Android still has the old, larger `userdata` mounted. f2fs may write into its old
tail until the restart and overwrite the token. That is unlikely (the token is one 4 KiB block at a 2 MiB boundary,
written right before the restart), and if it happens the resume refuses with "token mismatch" and writes nothing.
`--no-resume` then installs into the region as into any space that holds data (`overwrite` typed). It is the same
failure his flow stops on, without its cause.
**What survives the reset, and where the transaction lives.** The reset formats `userdata`, and with FBE its keys
in `/metadata`. `/sdcard` (`/data/media`) and `/data/local/tmp` are in it. So nothing the installer could put in
Android's storage survives, and the transaction lives on the computer, as with kano. On the device, the reset leaves
what lies outside `userdata`: the new partition table, the token at the start of the region (outside every
partition from then on), `boot_a`/`boot_b` (Magisk's patched boot included), the boot chain and the A/B block in
`misc`. Recovery clears the BCB once it has run.
**What kano says he measured** (his notes, `docs/DESKTOP-INSTALLER-PORT.zh-CN.md` and `desktop/README.md` of
`f6b0668d`, `installer/VERIFICATION.md` of `0e19fe32`; translated from Chinese where marked):
* 2026-10-13: "MU300 实机缩容、原厂 recovery 重置/续装、完整部署后的重启和更新仍待验证" (translated: shrinking on a
real MU300, the stock-recovery reset and resume, and the reboot and update after a full deployment still need
verification).
* 2026-10-14, on a V50: "新版 EXE 对旧记录进行只读续装预检,通过 8.00 GiB 分区、身份、令牌及载荷校验。没有再次缩容或
写独立分区" (translated: the new EXE ran a read-only resume pre-check against the old record and passed the
8.00 GiB partition, identity, token and payload checks; no second shrink, no write to the independent partition).
The same notes say a first stage existed on that V50 ("现有 8 GiB 分区可继续续装", translated: the existing 8 GiB
partition can still be resumed into). They do not say how the reset went there.
* `desktop/README.md`: "Hardware installation, especially stock-recovery reset/resume, still needs real MU300
validation before a release."
* 2026-10-15: "No connected-device installation, formatting, GPT mutation, userdata reset/shrink, boot-chain
synchronization, misc write, live SSH upgrade or Magisk flash was performed."
**Tests.** `tests/test_resume.py`:
* the transaction: kano's wrong-device/geometry/marker cases, plus this project's own checks; the identity; `find`;
the BCB and the marker; kano's encryption rule.
* `install.sh` as a whole against `tests/fakeadb.py` in its new `emmc` mode, real storage in a directory
(`tests/fakeemmc.py`). The prepare is checked on what it wrote: only `userdata`'s end moved, then the token, the
BCB with the A/B block unchanged, the order of the writes, the backup, and that no NV partition was read.
* the run before the reset (refused: "reset not run yet"), the reset (the kernel's view, recovery's format), the
resumed run (no storage or overwrite question, the region as prepared), `--check`, `--no-resume`, `--resume`
without a record, and a slot, token, geometry or identity that changed (each refused, nothing written).
* `tests/installer.Tests.ps1`: `install.ps1`'s `OfferRepartition` with the same writes on its own fake.
* `tests/test_gui.py`: the window's texts.
**Before this is used on a device.**
1. The vendor's recovery honours `--wipe_data` from the BCB without a prompt (kano's evidence is the vendor tool's
block, not a run).
2. The bootloader starts recovery from the BCB on a plain reboot.
3. Android starts after the reset with `userdata` at its new size.
4. Magisk's root can be brought back on a screenless unit (the Magisk app over adb, the Shell grant through scrcpy).
5. The token is still there after the restart.
Until then the path stays EXPERIMENTAL, and an SD card remains the way that erases nothing.
**A first device run, 2026-10-15 (an F50 the owner gave up for it): not done, the unit has room.** Read only, from
the SD card's Linux on it: the eMMC is 122159104 sectors (58.2 GiB), `userdata` (`mmcblk0p75`, the last partition)
runs from 12275712 for 41943040 sectors (20 GiB, ends at 54218751), and 32.4 GiB behind it belong to no partition,
the 64 GB layout of section 9. The region starts at 54222848 and already holds a `mu300root` ext4. The make-room path
only starts below 700 MiB of free region and without an SD card chosen, so it cannot run here without making a
32 GB layout by hand, which was not done. **None of the five checks above was done**; they still need a 32 GB unit
(or one whose layout is changed on purpose). What the unit did show, for the checks:
* No `recovery` partition; `boot_a` is a version 4 boot image with a ramdisk (Magisk's patch is there), `init_boot_a`
is empty. So recovery is the `vendor_boot` ramdisk's, reached through the patched `boot` ramdisk (check 1 and 2
run through Magisk's init on this unit).
* `misc` begins with a leftover bootloader message, `bootonce-bootloader`, and the unit boots normally with it on
every start: this bootloader does not act on at least that command (check 2 stays open; `boot-recovery` may still
be read). `resume.py`'s prepare replaces the first 2 KiB whole, and its "reset not run yet" test looks for its own
message only, so the leftover changes nothing for it.
* Over USB, in Linux, the unit is `MU300LINUX-324950664950-2128e853` on the computer's adb list; a second F50 cloned
from the same unit shows `MU300LINUX-324950664950-203d8329`, and in Android both would be `324950664950`. A
resume on one computer with both in Android cannot tell them apart by serial; the eMMC CID in the transaction does.
+10 -1
View File
@@ -77,7 +77,7 @@ A question is asked only where the installer asks it by hand too.
| `MU300_ANS_MAKE_ROOM` | `yes`, `no` | no free space: shrink `userdata` (erases Android's data) |
| `MU300_ANS_LINUX_GIB` | a number, `4` or `2.5` | then: how many GiB for Linux |
| `MU300_ANS_ERASE_ANDROID` | `ERASE` | then: the word that allows it |
| `MU300_ANS_REBOOT` | `yes`, `no` | then: reboot |
| `MU300_ANS_REBOOT` | `yes`, `no` | then: reboot (into the reset by Android's recovery; the installation resumes on the next run) |
| `MU300_ANS_OVERWRITE` | `overwrite` | the free space holds data: use it anyway |
| `MU300_ANS_BETA` | `yes`, `no` | a prerelease newer than the newest release: install it. `MU300_RELEASE=<tag>` (`-Release`) names the release and asks nothing |
| `MU300_ANS_SYSTEMS` | `1`, `2`, `3` | Ubuntu, OpenWrt, both |
@@ -109,6 +109,13 @@ others. The `download` step checks the two files of the zip instead (`verify` ev
manifest that is not one of a release's stops the run before the device is asked anything. The graphical installer
started from such a folder offers that system and kernel only.
**A prepared installation** (making room by a reset, EXPERIMENTAL; `tools/resume.sh`, `tools/resume.py`):
`MU300_BACKUP_DIR` (default `~/mu300-backups`) is where the transaction and the backup go; `MU300_RESUME=0`
(`--no-resume` / `-NoResume`) ignores a waiting transaction, `MU300_RESUME=1` (`--resume` / `-Resume`) stops when
there is none for the device, `MU300_TRANSACTION=FILE` (`--transaction` / `-Transaction`) names one. A resumed run
asks no `MU300_STORAGE` and no `MU300_ANS_OVERWRITE` (the region is the prepared one); a transaction that does not
match stops the run before anything is written, with the reason in the error event.
### The variables of `uninstall.sh` / `uninstall.ps1`
| variable | values | the question |
@@ -176,6 +183,8 @@ The stages of an installation, in order: `preflight` 2, `storage` 6, `choices` 1
| `makeroom.first`, `.end`, `.usable_end`, `.min_android`, `.min_linux`, `.max_linux` | where `userdata` fills the disk: its sectors, and the limits of a split, in sectors |
| `release` | the release this run installs |
| `package`, `package.system`, `package.kernel`, `package.release` | an unpacked Magisk zip this run installs from: its folder, and what it holds |
| `makeroom.crypto`, `.crypto_state`, `.crypto_type` | the make-room path: whether Android's data is encrypted (`yes`, `no`, `unknown`: kano's rule), and `ro.crypto.state` / `ro.crypto.type` |
| `resume.transaction`, `resume.check`, `resume.backup` | a prepared installation: its transaction, what its checks said (`RESUME-OK` or `RESUME-REFUSED: why`), the backup made before it |
| `backup.boot`, `backup.misc`, `backup.sha256` | `--backup`: the two files and the boot image's hash |
The facts before `root` need no root, and they are sent before the check for it: a device without root still says
+9 -2
View File
@@ -551,6 +551,13 @@ class App:
facts(i, rows).pack(fill='x')
if f.get('verdict'):
banner(i, f['verdict'], 'warn' if f.get('verdict.code') == 'dirty' else 'good').pack(fill='x', pady=(S3, 0))
# a prepared installation (making room by a reset, tools/resume.sh): what its checks said
if f.get('resume.transaction'):
if f.get('resume.check') == 'RESUME-OK':
banner(i, _('A prepared installation waits for this device (EXPERIMENTAL: room was made by resetting Android). Install continues it into the prepared region. Its record: {1}', f['resume.transaction']), 'accent').pack(fill='x', pady=(S3, 0))
else:
banner(i, _('A prepared installation waits for this device, but it cannot be continued: {1}. Nothing is written. Its record: {2}',
f.get('resume.check', '').replace('RESUME-REFUSED: ', ''), f['resume.transaction']), 'bad').pack(fill='x', pady=(S3, 0))
sd = f.sd
o, i = card(body, _('SD card'))
@@ -624,7 +631,7 @@ class App:
ttk.Label(line, text=_('Type ERASE:'), style='Warn.TLabel').pack(side='left', padx=(S4, 0))
ttk.Entry(line, textvariable=self.v['room_word'], width=10).pack(side='left', padx=S2)
ttk.Button(i, text=_('Make room now'), style='Danger.TButton', command=self._make_room_go).pack(anchor='w', pady=(S3, 0))
ttk.Label(i, text=_('Afterwards the device restarts, Android sets its data up again (a few minutes), and the check finds the free space.'),
ttk.Label(i, text=_('First the partition table, misc, boot and the boot chain are backed up to this computer, with a record of what is prepared. Then the device restarts into Android\'s own recovery, which resets Android - a factory reset, a few minutes and more than one restart. Set Android up again, turn USB debugging on and bring root back (install the Magisk app again, let Shell have root); then Refresh: the installation continues where it was prepared. EXPERIMENTAL (ported from kano\'s desktop installer).'),
style='Warn.Muted.TLabel', wraplength=660, justify='left').pack(anchor='w', pady=(S2, 0))
def _make_room_go(self):
@@ -1084,7 +1091,7 @@ class App:
return
box = self.w['run-banner']
if kind == 'makeroom' and p.ok:
banner(box, _('Room was made. The device restarts and Android sets its data up again (a few minutes). Then press Refresh on the Device page.'), 'good').pack(fill='x', pady=(0, S3))
banner(box, _('Room was made. The device restarts into Android\'s recovery, which resets Android (a few minutes, more than one restart). Set Android up again, turn USB debugging on and bring root back (the Magisk app, Shell allowed); then press Refresh on the Device page: the installation continues where it was prepared.'), 'good').pack(fill='x', pady=(0, S3))
elif kind in ('install', 'makeroom') and not p.ok:
banner(box, _('It stopped: {1}', p.error or '?'), 'bad').pack(fill='x', pady=(0, S2))
reached = [s_[0] for s_ in p.steps if s_[2] in ('done', 'failed', 'running')]
+2 -1
View File
@@ -469,7 +469,8 @@ UNINSTALL_STEPS = (('preflight', N_('Check the computer and the device')), ('fin
CHECK_STEPS = (('preflight', N_('Check the computer and the device')), ('storage', N_('Find the place for Linux')))
BACKUP_STEPS = (('preflight', N_('Check the computer and the device')), ('backup', N_('Copy the boot image and the start of misc')))
MAKEROOM_STEPS = (('preflight', N_('Check the computer and the device')), ('storage', N_('Read the partition table')),
('repartition', N_('Rewrite the partition table and clear Android\'s data')))
('backup', N_('Back up the partition table, misc, boot and the boot chain')),
('repartition', N_('Rewrite the partition table and ask Android\'s recovery for the reset')))
# From these stages on a run writes to the device: stopping it there can leave a write half done. Before them
# nothing on the device has changed and a run can be stopped at any moment.
NO_CANCEL = {'install': ('device', 'boot', 'switch', 'done'), 'uninstall': ('misc', 'boot', 'erase', 'sd', 'userdata', 'switch', 'done'),
+48 -7
View File
@@ -37,9 +37,6 @@ Verifying Doğrulanıyor
the table on the device does not read back as valid GPT. cihazdaki tablo geçerli bir GPT olarak geri okunamıyor.
the table did not take (userdata still ends at {1}). Nothing else was changed. tablo uygulanmadı (userdata hâlâ {1} sektöründe bitiyor). Başka hiçbir şey değiştirilmedi.
userdata now ends at sector {1} userdata artık {1} sektöründe bitiyor
Done - the device has to reboot before the new layout is visible Tamamlandı - yeni düzenin görünmesi için cihazın yeniden başlaması gerekiyor
Android will set up its data partition again on this boot, which takes a few minutes. Android bu açılışta veri bölümünü yeniden kuracak; bu birkaç dakika sürer.
When it is back, run this installer again and it will find the free space. Açıldığında yükleyiciyi tekrar çalıştırın; boş alanı bulacaktır.
Reboot now? (yes/no) Şimdi yeniden başlatılsın mı? (evet/hayır)
Locating free eMMC space after the last partition Son bölümden sonraki boş eMMC alanı aranıyor
could not read the partition table from the device (is su granted? try again) bölüm tablosu cihazdan okunamadı (su izni verildi mi? tekrar deneyin)
@@ -159,7 +156,6 @@ switch systems: mu300-os {1} back to Android: mu300-next-boot android sistem d
back to Linux from Android (with Magisk): su -c mu300-linux Android'den Linux'a dönüş (Magisk ile): su -c mu300-linux
Type ERASE to rewrite the partition table and wipe Android's data Bölüm tablosunu yeniden yazmak ve Android verilerini silmek için ERASE yazın
The backup copy at the end of the disk was written first, so Android's own repair may still fix this. Do not power off. Diskin sonundaki yedek kopya önce yazıldı, bu yüzden Android'in kendi onarımı bunu hâlâ düzeltebilir. Cihazı kapatmayın.
Clearing Android's data filesystem so it is recreated on the next boot Android'in veri dosya sistemi, bir sonraki açılışta yeniden oluşturulması için temizleniyor
ERROR: HATA:
Python 3 not found (install it from python.org or the Microsoft Store) Python 3 bulunamadı (python.org'dan ya da Microsoft Store'dan kurun)
Python 3.8 or newer is required Python 3.8 ya da daha yenisi gerekiyor
@@ -590,7 +586,6 @@ userdata fills the whole disk, so there is nowhere to put Linux. The installer c
GiB for Linux: Linux için GiB:
Type ERASE: ERASE yazın:
Make room now Şimdi yer aç
Afterwards the device restarts, Android sets its data up again (a few minutes), and the check finds the free space. Sonrasında cihaz yeniden başlar, Android verilerini yeniden kurar (birkaç dakika) ve kontrol boş alanı bulur.
It goes to the installer in a private file that is deleted when the run ends; only its hash reaches the device. It is never written to a log. Yükleyiciye, çalışma bitince silinen özel bir dosyayla iletilir; cihaza yalnızca özeti (hash) ulaşır. Hiçbir günlüğe yazılmaz.
Advanced Gelişmiş
There is not enough free space for this installation in that folder. Free some, or set MU300_WORK to a folder on another disk before starting. Bu klasörde bu kurulum için yeterli boş alan yok. Yer açın ya da başlatmadan önce MU300_WORK değişkenini başka bir diskteki bir klasöre ayarlayın.
@@ -600,7 +595,6 @@ The backup stopped: {1} Yedekleme durdu: {1}
Copy the log Günlüğü kopyala
Save the log… Günlüğü kaydet…
Text Metin
Room was made. The device restarts and Android sets its data up again (a few minutes). Then press Refresh on the Device page. Yer açıldı. Cihaz yeniden başlıyor ve Android verilerini yeniden kuruyor (birkaç dakika). Sonra Cihaz sayfasında Yenile'ye basın.
Open an SSH session SSH oturumu aç
The Wi-Fi network the device broadcasts is its hotspot. Then try: sudo mu300-toolkit Cihazın yayınladığı Wi-Fi ağı onun hotspot'udur. Sonra şunu deneyin: sudo mu300-toolkit
News and new releases are on the project's Telegram channel; you can follow it. Haberler ve yeni sürümler projenin Telegram kanalında; takip edebilirsiniz.
@@ -737,7 +731,6 @@ Remove the on-device switch Cihaz üzerindeki geçiş aracını kaldır
Done Tamamlandı
Copy the boot image and the start of misc Önyükleme imajını ve misc'in başını kopyala
Read the partition table Bölüm tablosunu oku
Rewrite the partition table and clear Android's data Bölüm tablosunu yeniden yaz ve Android verilerini temizle
Where Nereye
Default boot Varsayılan açılış
Also Ayrıca
@@ -789,6 +782,54 @@ ZTE V50: EXPERIMENTAL, tested by nobody in this project (kano ported it); mainli
The ZTE V50 runs a mainline kernel only: install a prebuilt release (without --build) ZTE V50 yalnızca ana hat (mainline) çekirdekle çalışır: hazır bir sürüm kurun (--build olmadan)
The ZTE V50 runs a mainline kernel only (6.18 or 7.2). ZTE V50 yalnızca ana hat (mainline) çekirdekle çalışır (6.18 ya da 7.2).
The ZTE V50 runs only a mainline kernel of a release that knows it: take the zip for kernel 6.18 or 7.2 (of a newer release if this one has none) ZTE V50 yalnızca onu tanıyan bir sürümün ana hat (mainline) çekirdeğiyle çalışır: 6.18 ya da 7.2 çekirdeğinin zip dosyasını alın (bu sürümde yoksa daha yeni bir sürümün)
a prepared installation is waiting (tools/resume.sh): this installer does not update itself until it is done hazırlanmış bir kurulum bekliyor (tools/resume.sh): bu kurulum programı o bitene kadar kendini güncellemez
could not read what identifies this device (serial, eMMC CID, userdata) bu cihazı tanımlayan bilgiler okunamadı (seri numarası, eMMC CID, userdata)
the partition table and the running kernel disagree about userdata; reboot Android and try again bölüm tablosu ile çalışan çekirdek userdata konusunda uyuşmuyor; Android'i yeniden başlatıp tekrar deneyin
encrypted şifreli
not encrypted şifresiz
unknown bilinmiyor
Android's own recovery erases Android's data: the device restarts into it, resets Android (a factory Android'in verilerini Android'in kendi kurtarma modu (recovery) siler: cihaz ona yeniden başlar, Android'i sıfırlar (fabrika
reset) and starts Android again, which takes a few minutes and more than one restart. Then set Android up ayarlarına döndürme) ve Android'i yeniden başlatır; bu birkaç dakika ve birden çok yeniden başlatma sürer. Sonra Android'i
again, turn USB debugging back on and bring root back (Magisk: install the Magisk app again and let yeniden kurun, USB hata ayıklamayı tekrar açın ve root'u geri getirin (Magisk: Magisk uygulamasını yeniden kurup
Shell have root), and run this installer again: it finds what was prepared and continues. Shell'e root izni verin) ve bu kurulum programını yeniden çalıştırın: hazırlananı bulur ve devam eder.
What was prepared, and a backup of the partition table, misc, boot and the boot chain, are kept on this Hazırlananlar ile bölüm tablosunun, misc'in, boot'un ve önyükleme zincirinin yedeği bu
computer in {1} - the reset erases everything of it on the device. bilgisayarda {1} içinde tutulur - sıfırlama cihazdaki her şeyi siler.
Backing up to {1} {1} konumuna yedekleniyor
Done - the device restarts into the reset now Bitti - cihaz şimdi sıfırlamaya yeniden başlıyor
Android's recovery formats Android's data on the next start; then Android starts as new. Set it up, Android'in kurtarma modu bir sonraki açılışta Android'in verilerini biçimlendirir; ardından Android sıfırdan açılır. Kurun,
turn USB debugging on, bring root back (the Magisk app, Shell allowed), and run this installer again. USB hata ayıklamayı açın, root'u geri getirin (Magisk uygulaması, Shell'e izin), ve bu kurulum programını yeniden çalıştırın.
transaction: {1} işlem kaydı: {1}
OK: the region prepared by making room, checked against its transaction TAMAM: yer açılarak hazırlanmış alan, işlem kaydıyla karşılaştırıldı
could not mark {1} as done {1} tamamlandı olarak işaretlenemedi
Android's data: {1} ({2}) Android verileri: {1} ({2})
Android's encryption state is unknown ({1}); nothing is changed. Android'in şifreleme durumu bilinmiyor ({1}); hiçbir şey değiştirilmedi.
no saved transaction for this device in {1} (--transaction FILE names one) {1} içinde bu cihaz için kayıtlı bir işlem yok (--transaction DOSYA birini belirtir)
A prepared installation is waiting: {1} Hazırlanmış bir kurulum bekliyor: {1}
EXPERIMENTAL: it continues the installation that made room by resetting Android. --no-resume ignores it. DENEYSEL: Android'i sıfırlayarak yer açan kurulumu sürdürür. --no-resume onu yok sayar.
could not read the transaction {1} {1} işlem kaydı okunamadı
The prepared installation cannot be continued: {1} Hazırlanmış kurulum sürdürülemiyor: {1}
Nothing was written. Keep the device as it is and keep {1}. Hiçbir şey yazılmadı. Cihazı olduğu gibi bırakın ve {1} dosyasını saklayın.
Another transaction: --transaction FILE. To install as if nothing had been prepared: --no-resume (the region is then treated as space that holds data). Başka bir işlem kaydı: --transaction DOSYA. Hiçbir şey hazırlanmamış gibi kurmak için: --no-resume (alan o zaman veri içeren bir alan olarak ele alınır).
the device, its slot, its partition table, the region, the token and this installer are the ones the transaction was made with cihaz, yuvası, bölüm tablosu, alan, belirteç ve bu kurulum programı işlem kaydının oluşturulduğu haliyle aynı
Backing up {1} {1} yedekleniyor
the copy of {1} is not what the device holds; nothing was changed {1} kopyası cihazdakiyle aynı değil; hiçbir şey değiştirilmedi
could not compute the installer identity kurulum programının kimliği hesaplanamadı
could not save the transaction; nothing was changed işlem kaydı kaydedilemedi; hiçbir şey değiştirilmedi
transaction saved: {1} işlem kaydı kaydedildi: {1}
could not prepare the files to write; nothing was changed yazılacak dosyalar hazırlanamadı; hiçbir şey değiştirilmedi
the token did not read back from the device; misc was not changed, Android keeps its data. Run the installer again. belirteç cihazdan geri okunamadı; misc değiştirilmedi, Android verilerini korur. Kurulum programını yeniden çalıştırın.
Asking Android's recovery to reset Android's data on the next boot Android'in kurtarma modundan bir sonraki açılışta Android verilerini sıfırlaması isteniyor
the request for the reset did not read back from misc. The partition table is changed already: run the installer again, it continues from here. sıfırlama isteği misc'ten geri okunamadı. Bölüm tablosu zaten değişti: kurulum programını yeniden çalıştırın, buradan devam eder.
could not save the transaction işlem kaydı kaydedilemedi
could not create {1} {1} oluşturulamadı
could not copy the partition table into the backup bölüm tablosu yedeğe kopyalanamadı
could not make a token belirteç oluşturulamadı
First the partition table, misc, boot and the boot chain are backed up to this computer, with a record of what is prepared. Then the device restarts into Android's own recovery, which resets Android - a factory reset, a few minutes and more than one restart. Set Android up again, turn USB debugging on and bring root back (install the Magisk app again, let Shell have root); then Refresh: the installation continues where it was prepared. EXPERIMENTAL (ported from kano's desktop installer). Önce bölüm tablosu, misc, boot ve önyükleme zinciri, hazırlananın kaydıyla birlikte bu bilgisayara yedeklenir. Sonra cihaz Android'in kendi kurtarma moduna yeniden başlar ve Android'i sıfırlar - fabrika ayarlarına döndürme, birkaç dakika ve birden çok yeniden başlatma. Android'i yeniden kurun, USB hata ayıklamayı açın ve root'u geri getirin (Magisk uygulamasını yeniden kurun, Shell'e root verin); sonra Yenile: kurulum hazırlandığı yerden devam eder. DENEYSEL (kano'nun masaüstü kurulum programından aktarıldı).
Room was made. The device restarts into Android's recovery, which resets Android (a few minutes, more than one restart). Set Android up again, turn USB debugging on and bring root back (the Magisk app, Shell allowed); then press Refresh on the Device page: the installation continues where it was prepared. Yer açıldı. Cihaz Android'in kurtarma moduna yeniden başlar ve Android'i sıfırlar (birkaç dakika, birden çok yeniden başlatma). Android'i yeniden kurun, USB hata ayıklamayı açın ve root'u geri getirin (Magisk uygulaması, Shell'e izin); sonra Cihaz sayfasında Yenile'ye basın: kurulum hazırlandığı yerden devam eder.
A prepared installation waits for this device (EXPERIMENTAL: room was made by resetting Android). Install continues it into the prepared region. Its record: {1} Bu cihaz için hazırlanmış bir kurulum bekliyor (DENEYSEL: yer, Android sıfırlanarak açıldı). Kur, onu hazırlanan alana sürdürür. Kaydı: {1}
A prepared installation waits for this device, but it cannot be continued: {1}. Nothing is written. Its record: {2} Bu cihaz için hazırlanmış bir kurulum bekliyor, ama sürdürülemiyor: {1}. Hiçbir şey yazılmaz. Kaydı: {2}
Back up the partition table, misc, boot and the boot chain Bölüm tablosunu, misc'i, boot'u ve önyükleme zincirini yedekle
Rewrite the partition table and ask Android's recovery for the reset Bölüm tablosunu yeniden yaz ve Android'in kurtarma modundan sıfırlama iste
--build builds the systems itself: run it from a copy of the project, not from an unpacked Magisk zip --build sistemleri kendisi derler: onu açılmış bir Magisk zip'inden değil, projenin bir kopyasından çalıştırın
Package: {1} with kernel {2}, release {3} (unpacked Magisk zip at {4}) Paket: {1}, {2} çekirdeği, sürüm {3} ({4} konumunda açılmış Magisk zip'i)
This package installs {1} with kernel {2} (release {3}); nothing is downloaded. Bu paket {1} ve {2} çekirdeğini kurar (sürüm {3}); hiçbir şey indirilmez.
Can't render this file because it contains an unexpected character in line 109 and column 18.
+48 -7
View File
@@ -37,9 +37,6 @@ Verifying 正在验证
the table on the device does not read back as valid GPT. 设备上的分区表读回后不是有效的 GPT。
the table did not take (userdata still ends at {1}). Nothing else was changed. 分区表未生效(userdata 仍结束于 {1})。未做其他更改。
userdata now ends at sector {1} userdata 现在结束于扇区 {1}
Done - the device has to reboot before the new layout is visible 完成——设备需要重启后新布局才会生效
Android will set up its data partition again on this boot, which takes a few minutes. Android 将在本次启动时重新建立数据分区,需要几分钟。
When it is back, run this installer again and it will find the free space. 启动完成后,请再次运行此安装程序,它会找到空闲空间。
Reboot now? (yes/no) 现在重启吗?(是/否)
Locating free eMMC space after the last partition 正在查找最后一个分区之后的空闲 eMMC 空间
could not read the partition table from the device (is su granted? try again) 无法从设备读取分区表(是否已授予 su 权限?请重试)
@@ -159,7 +156,6 @@ switch systems: mu300-os {1} back to Android: mu300-next-boot android 切换
back to Linux from Android (with Magisk): su -c mu300-linux 从 Android 回到 Linux(需 Magisk):su -c mu300-linux
Type ERASE to rewrite the partition table and wipe Android's data 输入 ERASE 以重写分区表并清除 Android 数据
The backup copy at the end of the disk was written first, so Android's own repair may still fix this. Do not power off. 磁盘末尾的备份副本已先写入,Android 自身的修复仍可能解决此问题。请勿断电。
Clearing Android's data filesystem so it is recreated on the next boot 正在清除 Android 的数据文件系统,以便下次启动时重新创建
ERROR: 错误:
Python 3 not found (install it from python.org or the Microsoft Store) 未找到 Python 3(请从 python.org 或 Microsoft Store 安装)
Python 3.8 or newer is required 需要 Python 3.8 或更高版本
@@ -590,7 +586,6 @@ userdata fills the whole disk, so there is nowhere to put Linux. The installer c
GiB for Linux: 分配给 Linux 的 GiB 数:
Type ERASE: 输入 ERASE:
Make room now 立即腾出空间
Afterwards the device restarts, Android sets its data up again (a few minutes), and the check finds the free space. 之后设备会重启,Android 重新建立数据分区(需要几分钟),然后检查就能找到空闲空间。
It goes to the installer in a private file that is deleted when the run ends; only its hash reaches the device. It is never written to a log. 密码通过一个私有文件传给安装程序,运行结束时该文件即被删除;只有它的哈希会到达设备。密码绝不会写入日志。
Advanced 高级
There is not enough free space for this installation in that folder. Free some, or set MU300_WORK to a folder on another disk before starting. 该文件夹中的空闲空间不足以完成本次安装。请腾出一些空间,或在开始前把 MU300_WORK 设为另一块磁盘上的文件夹。
@@ -600,7 +595,6 @@ The backup stopped: {1} 备份已停止:{1}
Copy the log 复制日志
Save the log… 保存日志…
Text 文本
Room was made. The device restarts and Android sets its data up again (a few minutes). Then press Refresh on the Device page. 空间已腾出。设备会重启,Android 重新建立数据分区(需要几分钟)。之后请在“设备”页面按“刷新”。
Open an SSH session 打开 SSH 会话
The Wi-Fi network the device broadcasts is its hotspot. Then try: sudo mu300-toolkit 设备广播的 Wi-Fi 网络就是它的热点。然后可以试试:sudo mu300-toolkit
News and new releases are on the project's Telegram channel; you can follow it. 新闻和新版本发布在本项目的 Telegram 频道,欢迎关注。
@@ -737,7 +731,6 @@ Remove the on-device switch 移除设备端切换工具
Done 完成
Copy the boot image and the start of misc 复制启动镜像和 misc 的开头
Read the partition table 读取分区表
Rewrite the partition table and clear Android's data 重写分区表并清除 Android 数据
Where 位置
Default boot 默认启动
Also 另外
@@ -789,6 +782,54 @@ ZTE V50: EXPERIMENTAL, tested by nobody in this project (kano ported it); mainli
The ZTE V50 runs a mainline kernel only: install a prebuilt release (without --build) ZTE V50 只能使用主线内核:请安装预编译的版本(不加 --build)
The ZTE V50 runs a mainline kernel only (6.18 or 7.2). ZTE V50 只能使用主线内核(6.18 或 7.2)。
The ZTE V50 runs only a mainline kernel of a release that knows it: take the zip for kernel 6.18 or 7.2 (of a newer release if this one has none) ZTE V50 只能使用认识它的版本中的主线内核:请选择 6.18 或 7.2 内核的 zip(本版本没有时请用更新的版本)
a prepared installation is waiting (tools/resume.sh): this installer does not update itself until it is done 有一个已准备的安装正在等待(tools/resume.sh):在它完成之前,本安装程序不会自我更新
could not read what identifies this device (serial, eMMC CID, userdata) 无法读取识别本设备的信息(序列号、eMMC CID、userdata)
the partition table and the running kernel disagree about userdata; reboot Android and try again 分区表与正在运行的内核对 userdata 的认识不一致;请重启 Android 后再试
encrypted 已加密
not encrypted 未加密
unknown 未知
Android's own recovery erases Android's data: the device restarts into it, resets Android (a factory Android 的数据由 Android 自带的 recovery 清除:设备会重启进入 recovery,重置 Android(恢复
reset) and starts Android again, which takes a few minutes and more than one restart. Then set Android up 出厂设置)再重新启动 Android,需要几分钟和不止一次重启。之后请重新设置 Android,
again, turn USB debugging back on and bring root back (Magisk: install the Magisk app again and let 重新打开 USB 调试并恢复 root(Magisk:重新安装 Magisk 应用,并允许
Shell have root), and run this installer again: it finds what was prepared and continues. Shell 获取 root),然后再次运行本安装程序:它会找到已准备的内容并继续。
What was prepared, and a backup of the partition table, misc, boot and the boot chain, are kept on this 已准备的内容,以及分区表、misc、boot 和启动链的备份,保存在本
computer in {1} - the reset erases everything of it on the device. 电脑的 {1} 中——重置会清除设备上的所有这些内容。
Backing up to {1} 正在备份到 {1}
Done - the device restarts into the reset now 完成——设备现在重启并进行重置
Android's recovery formats Android's data on the next start; then Android starts as new. Set it up, 下次启动时 Android 的 recovery 会格式化 Android 的数据,然后 Android 作为新设备启动。请完成设置,
turn USB debugging on, bring root back (the Magisk app, Shell allowed), and run this installer again. 打开 USB 调试,恢复 root(Magisk 应用,允许 Shell),然后再次运行本安装程序。
transaction: {1} 事务记录:{1}
OK: the region prepared by making room, checked against its transaction 正常:腾出空间时准备的区域,已与其事务记录核对
could not mark {1} as done 无法将 {1} 标记为已完成
Android's data: {1} ({2}) Android 数据: {1}({2})
Android's encryption state is unknown ({1}); nothing is changed. Android 的加密状态未知({1});未做任何更改。
no saved transaction for this device in {1} (--transaction FILE names one) {1} 中没有本设备已保存的事务(--transaction FILE 可指定一个)
A prepared installation is waiting: {1} 有一个已准备的安装正在等待:{1}
EXPERIMENTAL: it continues the installation that made room by resetting Android. --no-resume ignores it. 实验性功能:继续那次通过重置 Android 腾出空间的安装。--no-resume 会忽略它。
could not read the transaction {1} 无法读取事务记录 {1}
The prepared installation cannot be continued: {1} 无法继续已准备的安装:{1}
Nothing was written. Keep the device as it is and keep {1}. 未写入任何内容。请保持设备现状,并保留 {1}。
Another transaction: --transaction FILE. To install as if nothing had been prepared: --no-resume (the region is then treated as space that holds data). 使用其他事务记录:--transaction FILE。如同未做任何准备那样安装:--no-resume(届时该区域被视为含有数据的空间)。
the device, its slot, its partition table, the region, the token and this installer are the ones the transaction was made with 设备、其槽位、分区表、区域、令牌和本安装程序均与创建该事务时一致
Backing up {1} 正在备份 {1}
the copy of {1} is not what the device holds; nothing was changed {1} 的副本与设备上的内容不一致;未做任何更改
could not compute the installer identity 无法计算安装程序的标识
could not save the transaction; nothing was changed 无法保存事务记录;未做任何更改
transaction saved: {1} 事务记录已保存:{1}
could not prepare the files to write; nothing was changed 无法准备要写入的文件;未做任何更改
the token did not read back from the device; misc was not changed, Android keeps its data. Run the installer again. 无法从设备读回令牌;misc 未被更改,Android 的数据得以保留。请再次运行安装程序。
Asking Android's recovery to reset Android's data on the next boot 正在请求 Android 的 recovery 在下次启动时重置 Android 的数据
the request for the reset did not read back from misc. The partition table is changed already: run the installer again, it continues from here. 无法从 misc 读回重置请求。分区表已经更改:请再次运行安装程序,它会从这里继续。
could not save the transaction 无法保存事务记录
could not create {1} 无法创建 {1}
could not copy the partition table into the backup 无法将分区表复制到备份中
could not make a token 无法生成令牌
First the partition table, misc, boot and the boot chain are backed up to this computer, with a record of what is prepared. Then the device restarts into Android's own recovery, which resets Android - a factory reset, a few minutes and more than one restart. Set Android up again, turn USB debugging on and bring root back (install the Magisk app again, let Shell have root); then Refresh: the installation continues where it was prepared. EXPERIMENTAL (ported from kano's desktop installer). 首先把分区表、misc、boot 和启动链连同已准备内容的记录备份到本电脑。然后设备重启进入 Android 自带的 recovery,重置 Android——即恢复出厂设置,需要几分钟和不止一次重启。请重新设置 Android,打开 USB 调试并恢复 root(重新安装 Magisk 应用,允许 Shell 获取 root);然后刷新:安装会从准备好的地方继续。实验性功能(移植自 kano 的桌面安装器)。
Room was made. The device restarts into Android's recovery, which resets Android (a few minutes, more than one restart). Set Android up again, turn USB debugging on and bring root back (the Magisk app, Shell allowed); then press Refresh on the Device page: the installation continues where it was prepared. 空间已腾出。设备会重启进入 Android 的 recovery 并重置 Android(几分钟,不止一次重启)。请重新设置 Android,打开 USB 调试并恢复 root(Magisk 应用,允许 Shell);然后在设备页面点击刷新:安装会从准备好的地方继续。
A prepared installation waits for this device (EXPERIMENTAL: room was made by resetting Android). Install continues it into the prepared region. Its record: {1} 有一个为本设备准备的安装正在等待(实验性功能:通过重置 Android 腾出了空间)。安装会在准备好的区域中继续。其记录:{1}
A prepared installation waits for this device, but it cannot be continued: {1}. Nothing is written. Its record: {2} 有一个为本设备准备的安装正在等待,但无法继续:{1}。不会写入任何内容。其记录:{2}
Back up the partition table, misc, boot and the boot chain 备份分区表、misc、boot 和启动链
Rewrite the partition table and ask Android's recovery for the reset 重写分区表并请求 Android 的 recovery 进行重置
--build builds the systems itself: run it from a copy of the project, not from an unpacked Magisk zip --build 会自行构建系统:请在本项目的副本中运行,而不是在解压的 Magisk zip 中
Package: {1} with kernel {2}, release {3} (unpacked Magisk zip at {4}) 安装包:{1},内核 {2},版本 {3}(解压的 Magisk zip 位于 {4})
This package installs {1} with kernel {2} (release {3}); nothing is downloaded. 本安装包安装 {1},内核 {2}(版本 {3});不下载任何东西。
Can't render this file because it contains an unexpected character in line 109 and column 18.
+233 -26
View File
@@ -38,7 +38,10 @@
Only the Linux region (or the SD card), the boot partition of the slot Android does not run from (boot_b, or
boot_a when Android runs from b) and 32 bytes of misc are written; Android's boot partition, the GPT and
userdata stay untouched. The one exception is asked for first and needs ERASE typed: where userdata fills the
disk (the 32 GB variant), the installer offers to shrink it, which rewrites the GPT and erases Android's data. With an SD card in the slot it asks where the Linux filesystem goes ($env:MU300_STORAGE =
disk (the 32 GB variant), the installer offers to shrink it, which rewrites the GPT and erases Android's data -
EXPERIMENTAL: Android's own recovery resets Android, and the installation resumes on the next run once Android is
set up again with USB debugging and root (a transaction in ~\mu300-backups; -Resume, -NoResume, -Transaction FILE;
tools\resume.py). With an SD card in the slot it asks where the Linux filesystem goes ($env:MU300_STORAGE =
'internal' or 'sd' answers without asking).
The VPN, when wanted, is the module of github.com/dikeckaan/mu300-linux-vpn: its latest release
($env:MU300_VPN_URL: another place with its files and SHA256SUMS; $env:MU300_VPN_MODULE: a copy on this computer).
@@ -58,6 +61,9 @@ param(
[switch]$AdbPath, # only print the adb that would be used
[switch]$NoSelfUpdate, # do not bring this copy up to date with GitHub first
[switch]$NoBootchainSync, # leave the Linux slot's boot chain as it is ($env:MU300_SYNC_BOOTCHAIN = '0' too)
[switch]$Resume, # continue the installation prepared by making room, or stop when there is none
[switch]$NoResume, # install as if nothing had been prepared ($env:MU300_RESUME = '0' too)
[string]$Transaction = '', # that transaction, not the newest one for this device ($env:MU300_TRANSACTION)
[string]$Package = '' # an unpacked Magisk zip of a release: its system and kernel, nothing downloaded
)
@@ -569,8 +575,27 @@ if ($PKG) {
Info 'package' $PKG; Info 'package.system' $PM.SYSTEM; Info 'package.kernel' $PM.KERNEL; Info 'package.release' $PM.TAG
Write-Host (T 'Package: {1} with kernel {2}, release {3} (unpacked Magisk zip at {4})' $PM.SYSTEM $PM.KERNEL $PM.TAG $PKG)
}
# first of all, make this the newest installer (it runs the updated one and ends when it changed)
if (-not $PKG -and (SelfUpdate)) {
# Making room by a reset, and the installation that resumes afterwards (EXPERIMENTAL; tools/resume.sh is the same for
# install.sh, tools/resume.py keeps the transaction): where the transactions and backups are kept, and whether one waits.
$BackupDir = if ($env:MU300_BACKUP_DIR) { $env:MU300_BACKUP_DIR } else { Join-Path $HOME 'mu300-backups' }
$ResumeWanted = if ($Resume) { '1' } elseif ($NoResume) { '0' } else { [string]$env:MU300_RESUME }
if (-not $Transaction -and $env:MU300_TRANSACTION) { $Transaction = $env:MU300_TRANSACTION }
# ResumePending: a transaction in $Dir still waits (for any device) - read here without Python, before the self-update
function ResumePending([string]$Dir) {
if (-not (Test-Path -LiteralPath $Dir -PathType Container)) { return $false }
foreach ($f in @(Get-ChildItem -LiteralPath $Dir -Directory -ErrorAction SilentlyContinue | ForEach-Object { Join-Path $_.FullName 'transaction.json' })) {
if (-not (Test-Path -LiteralPath $f)) { continue }
try { $j = [IO.File]::ReadAllText($f) | ConvertFrom-Json } catch { continue }
if ($j.format -eq 1 -and @('prepared-request', 'prepared') -contains [string]$j.state) { return $true }
}
return $false
}
$resumeWaits = $ResumeWanted -ne '0' -and ($Transaction -or (ResumePending $BackupDir))
if ($resumeWaits) { Write-Host (' ' + (T 'a prepared installation is waiting (tools/resume.sh): this installer does not update itself until it is done')) }
# first of all, make this the newest installer (it runs the updated one and ends when it changed) - not from a
# package, and not while a prepared installation waits: its transaction is bound to the tools that prepared it
if (-not $PKG -and -not $resumeWaits -and (SelfUpdate)) {
$env:MU300_SELF_UPDATED = '1'
AnswersReexport
$PSBoundParameters['Lang'] = $Lang
@@ -817,6 +842,57 @@ $region = FreeRegion $lastEnd $disk
[int64]$OFF = $region.Start * 512
[int64]$SIZE = ($region.End - $region.Start) * 512
Info 'emmc.sectors' $disk; Info 'emmc.last_end' $lastEnd; Info 'region.offset' $OFF; Info 'region.size' $SIZE
# a prepared installation waiting for this device (the make-room path below, on an earlier run): its checks first
$RESUMING = 0; $RESUME_TX = ''
if ($ResumeWanted -ne '0' -and ($ResumeWanted -eq '1' -or $resumeWaits)) {
$rv = ResumeFacts
if (-not $rv) {
if ($ResumeWanted -eq '1') { Die (T 'could not read what identifies this device (serial, eMMC CID, userdata)') }
} else {
$RESUME_TX = if ($Transaction) { $Transaction } else { [string]((ResumePy find $BackupDir $rv.SERIAL $rv.CID) | Select-Object -First 1) }
if (-not $RESUME_TX) {
if ($ResumeWanted -eq '1') { Die (T 'no saved transaction for this device in {1} (--transaction FILE names one)' $BackupDir) }
} elseif (-not (Test-Path -LiteralPath $RESUME_TX)) {
Die (T '{1} not found' $RESUME_TX)
} else {
$RESUMING = 1
Info 'resume.transaction' $RESUME_TX
Say (T 'A prepared installation is waiting: {1}' $RESUME_TX)
Write-Host (' ' + (T 'EXPERIMENTAL: it continues the installation that made room by resetting Android. --no-resume ignores it.'))
# every check of the transaction against the device, read only (tools\resume.py check)
$g = Join-Path $Work 'gpt'
New-Item -ItemType Directory -Force -Path $g | Out-Null
$rs = $null
if (GptDump $disk "$g\resume") { $rs = GptShow @(GptTool $g @('resume.head,resume.tail', '--disk-sectors', "$disk", '--name', 'userdata', '--show')) }
if (-not $rs) { Die (T 'could not read the partition table') }
$rr = [string]((ResumePy get $RESUME_TX region_start) | Select-Object -First 1) -replace '^region_start=', ''
if ($rr -notmatch '^[0-9]+$') { Die (T 'could not read the transaction {1}' $RESUME_TX) }
Remove-Item -Force "$g\resume-marker.bin", "$g\resume-bcb.bin" -ErrorAction SilentlyContinue
SuDoToFile "dd if=/dev/block/mmcblk0 bs=512 skip=$rr count=8 2>/dev/null" "$g\resume-marker.bin"
SuDoToFile 'dd if=/dev/block/by-name/misc bs=2048 count=1 2>/dev/null' "$g\resume-bcb.bin"
$idArgs = @('identity', $Top)
if ($PKG) { $idArgs += (Join-Path $PKG 'mu300\manifest') }
$id = [string]((ResumePy @idArgs) | Select-Object -First 1)
$out = [string]((ResumePy check $RESUME_TX "serial=$($rv.SERIAL)" "slot=$ANDROID_SLOT" "cid=$($rv.CID)" "node=$($rv.NODE)" `
"start=$($rv.START)" "size=$($rv.SIZE)" "disk=$disk" "gpt_first=$($rs.First)" "gpt_end=$($rs.End)" "usable_end=$($rs.UsableEnd)" `
"region_start=$([int64]($OFF / 512))" "region_end=$([int64](($OFF + $SIZE) / 512))" "marker=$g\resume-marker.bin" `
"bcb=$g\resume-bcb.bin" "identity=$id") | Select-Object -First 1)
Info 'resume.check' $out
if ($script:ResumeRc -ne 0) {
$why = $out -replace '^RESUME-REFUSED: ', ''
if ($Check) {
Write-Host (' ' + (T 'The prepared installation cannot be continued: {1}' $why))
$RESUMING = 0
} else {
Die ((T 'The prepared installation cannot be continued: {1}' $why) + "`n" + (T 'Nothing was written. Keep the device as it is and keep {1}.' $RESUME_TX) + "`n" +
(T 'Another transaction: --transaction FILE. To install as if nothing had been prepared: --no-resume (the region is then treated as space that holds data).'))
}
} else {
Write-Host (' ' + (T 'the device, its slot, its partition table, the region, the token and this installer are the ones the transaction was made with'))
}
}
}
}
# the partitions, for a picture of the eMMC: "name:first sector:sectors" of each (the stream only; sysfs, read only)
if ($script:MuProgress) { Info 'partitions' ((SuDo 'for p in /sys/block/mmcblk0/mmcblk0p*; do echo $(sed -n s/^PARTNAME=//p $p/uevent):$(cat $p/start):$(cat $p/size); done') -replace "`n", ' ') }
function Gib([int64]$b) { '{0:N1} GiB' -f ($b / 1GB) }
@@ -988,6 +1064,73 @@ function GptDump([int64]$Disk, [string]$Prefix) {
if (-not (Test-Path "$Prefix.head") -or -not (Test-Path "$Prefix.tail")) { return $false }
return ((Get-Item "$Prefix.head").Length -eq 34 * 512 -and (Get-Item "$Prefix.tail").Length -eq 33 * 512)
}
# ---- reset and resume (EXPERIMENTAL; tools/resume.sh): ported from kano's desktop installer (kanoqwq/mu300-linux,
# clean-tf-7.2, desktop/installer.py and desktop/boot/part-prepare.sh; f6b0668d, 0e19fe32). userdata is shrunk as before,
# but Android's own recovery formats it (a bootloader message in misc, --wipe_data): with file-based encryption a
# filesystem cleared from outside is one Android cannot mount. A transaction and a backup are saved on this computer
# first, a token goes to the start of the new region (outside every partition, where the reset does not reach), and
# the next run continues when the device, its slot, the partition table, the region, the token and these tools still
# match (tools\resume.py check).
# resume.py with these arguments: its lines, and its exit code in $script:ResumeRc
function ResumePy {
param([Parameter(ValueFromRemainingArguments = $true)][string[]]$RArgs)
$ErrorActionPreference = 'Continue'
$out = @(Python "$Top\tools\resume.py" @RArgs 2>$null | ForEach-Object { "$_" })
$script:ResumeRc = $LASTEXITCODE
return $out
}
# what identifies the device and its userdata, and how Android keeps its data: the same command as install.sh's
# (sysfs, properties, /proc/mounts; read only, and no double quotes - see the data check)
$script:FactsCmd = 'd=$(readlink -f /dev/block/by-name/userdata); n=${d##*/}; b=${n%p*}; echo NODE=$n; echo CID=$(cat /sys/class/block/$b/device/cid); echo START=$(cat /sys/class/block/$n/start); echo SIZE=$(cat /sys/class/block/$n/size); echo STATE=$(getprop ro.crypto.state); echo TYPE=$(getprop ro.crypto.type); while read s m r; do case $m in /data) echo SOURCE=$s; break ;; esac; done < /proc/mounts; echo MAGIC=$(dd if=$d bs=1 skip=1024 count=4 2>/dev/null | od -An -tx1 | tr -d \\040\\012); echo EXT=$(dd if=$d bs=1 skip=1080 count=2 2>/dev/null | od -An -tx1 | tr -d \\040\\012)'
function ParseFacts([string]$Text) {
$f = @{}
foreach ($l in ($Text -split "`n")) { if ($l -match '^([A-Z]+)=(.*)$') { if (-not $f.ContainsKey($Matches[1])) { $f[$Matches[1]] = $Matches[2].Trim() } } }
return $f
}
# FactsOk: the identity is one kano's checks take (an eMMC partition node, a 128-bit CID, numbers, a serial)
function FactsOk($F) {
return ([string]$F.NODE -cmatch '^mmcblk[0-9]p[0-9]+$' -and [string]$F.CID -cmatch '^[0-9a-f]{32}$' -and
[string]$F.START -match '^[0-9]+$' -and [string]$F.SIZE -match '^[0-9]+$' -and [string]$F.SERIAL)
}
function ResumeFacts {
$f = ParseFacts (SuDo $script:FactsCmd)
$f.SERIAL = AdbProp 'ro.serialno'
if (-not (FactsOk $f)) { return $null }
$magic = if ($f.EXT -eq '53ef') { '53ef' } else { [string]$f.MAGIC }
$f.CRYPTO = [string]((ResumePy encrypted "state=$($f.STATE)" "type=$($f.TYPE)" "source=$($f.SOURCE)" "magic=$magic") | Select-Object -First 1)
return $f
}
# the backup of kano's: the table (as read for the plan), the first block of misc, both slots' boot and boot chain,
# each checked against the device. Never the NV or calibration partitions.
function ResumeBackup([string]$Dir, [string]$G) {
New-Item -ItemType Directory -Force -Path $Dir | Out-Null
Copy-Item "$G\gpt.head" (Join-Path $Dir 'gpt.head'); Copy-Item "$G\gpt.tail" (Join-Path $Dir 'gpt.tail')
SuDoToFile 'dd if=/dev/block/by-name/misc bs=4096 count=1 2>/dev/null' (Join-Path $Dir 'misc-head.bin')
if (-not (Test-Path (Join-Path $Dir 'misc-head.bin'))) { Die (T 'could not read the misc header from the device') }
foreach ($bp in 'boot', 'uboot', 'sml', 'teecfg', 'trustos', 'vbmeta') {
foreach ($bs in 'a', 'b') {
$n = "${bp}_$bs"
Say (T 'Backing up {1}' $n)
$f = Join-Path $Dir "$n.img"
SuDoToFile "cat /dev/block/by-name/$n" $f
$want = (([string](SuDo "sha256sum /dev/block/by-name/$n")).Trim() -split '\s+')[0]
if (-not (Test-Path $f) -or -not $want -or (Get-FileHash $f -Algorithm SHA256).Hash.ToLower() -ne $want) {
Die (T 'the copy of {1} is not what the device holds; nothing was changed' $n)
}
}
}
$lines = foreach ($n in @('gpt.head', 'gpt.tail', 'misc-head.bin') + @(Get-ChildItem -LiteralPath $Dir -Filter '*.img' | Sort-Object Name | ForEach-Object { $_.Name })) {
"$((Get-FileHash (Join-Path $Dir $n) -Algorithm SHA256).Hash.ToLower()) $n"
}
WriteUnix (Join-Path $Dir 'SHA256SUMS') ((@($lines) -join "`n") + "`n")
}
# a file to the device, and there with the checksum it has here
function ResumePush([string]$Local, [string]$Remote) {
Quiet { adb push $Local $Remote } | Out-Null
$sum = (([string](SuDo "sha256sum $Remote")).Trim() -split '\s+')[0]
return ($sum -eq (Get-FileHash $Local -Algorithm SHA256).Hash.ToLower())
}
function ResumeSha([string]$Cmd) { return (([string](SuDo $Cmd)).Trim() -split '\s+')[0] }
function OfferRepartition([int64]$Disk, [int64]$LastEnd, [int64]$Size) {
Say (T 'Not enough free space - this looks like the 32 GB variant')
$g = Join-Path $Work 'gpt'
@@ -1016,11 +1159,20 @@ function OfferRepartition([int64]$Disk, [int64]$LastEnd, [int64]$Size) {
Die ((@((T 'there is not enough room to split: {1} in total,' (Gib ($plan.Total * 512))), (T 'and Android needs at least {1} of it. Nothing is changed.' (Gib ($plan.MinAndroid * 512)))) + @(LayoutFigures $Disk $LastEnd $Size $info $plan)) -join "`n")
}
# the device's identity and how Android keeps its data (read only); kano's rule: encrypted, plain, or unknown
$rf = ResumeFacts
if (-not $rf) { Die (T 'could not read what identifies this device (serial, eMMC CID, userdata)') }
if ([int64]$rf.START -ne $info.First -or [int64]$rf.START + [int64]$rf.SIZE - 1 -ne $info.End) {
Die (T 'the partition table and the running kernel disagree about userdata; reboot Android and try again')
}
Info 'makeroom.crypto' $rf.CRYPTO; Info 'makeroom.crypto_state' $rf.STATE; Info 'makeroom.crypto_type' $rf.TYPE
$cryptoText = switch ($rf.CRYPTO) { 'yes' { T 'encrypted' } 'no' { T 'not encrypted' } default { T 'unknown' } }
Write-Host ''
Write-Host " eMMC: $(Gib ($Disk * 512))"
Write-Host (' ' + (T 'userdata now: {1} (sectors {2}..{3})' (Gib (($info.End - $info.First + 1) * 512)) $info.First $info.End))
Write-Host (' ' + (T 'free behind it: {1}' (Gib ($plan.Free * 512))))
Write-Host (' ' + (T 'to share: {1}' (Gib ($plan.Total * 512))))
Write-Host (' ' + (T "Android's data: {1} ({2})" $cryptoText ("$(if ($rf.STATE) { $rf.STATE } else { '?' })$(if ($rf.TYPE) { '/' + $rf.TYPE })")))
Write-Host ''
Write-Host (' ' + (T 'Linux needs at least {1} (OpenWrt) / 1.6 GiB (Ubuntu) / 2.4 GiB (both)' (Gib ($plan.MinLinux * 512))))
Write-Host (' ' + (T 'Android keeps at least {1}' (Gib ($plan.MinAndroid * 512))))
@@ -1028,11 +1180,21 @@ function OfferRepartition([int64]$Disk, [int64]$LastEnd, [int64]$Size) {
Write-Host (' ' + (T 'THIS IS EXPERIMENTAL. It rewrites the partition table and ERASES everything in Android -'))
Write-Host (' ' + (T 'apps, photos, accounts, settings. Take a full backup first: sh tools/backup-device.sh'))
Write-Host (' ' + (T 'Only userdata changes size; it is the last partition, so nothing else moves.'))
Write-Host (' ' + (T "Android's own recovery erases Android's data: the device restarts into it, resets Android (a factory"))
Write-Host (' ' + (T 'reset) and starts Android again, which takes a few minutes and more than one restart. Then set Android up'))
Write-Host (' ' + (T 'again, turn USB debugging back on and bring root back (Magisk: install the Magisk app again and let'))
Write-Host (' ' + (T 'Shell have root), and run this installer again: it finds what was prepared and continues.'))
Write-Host (' ' + (T 'What was prepared, and a backup of the partition table, misc, boot and the boot chain, are kept on this'))
Write-Host (' ' + (T 'computer in {1} - the reset erases everything of it on the device.' $BackupDir))
Write-Host ''
if ($Check) {
Write-Host (' ' + (T '-Check writes nothing. Run the installer without it to make room.'))
return
}
# kano's rule: an encryption state that cannot be told is no ground to stand on
if ($rf.CRYPTO -ne 'yes' -and $rf.CRYPTO -ne 'no') {
Die (T "Android's encryption state is unknown ({1}); nothing is changed." "$(if ($rf.STATE) { $rf.STATE } else { '?' })/$(if ($rf.TYPE) { $rf.TYPE } else { '?' })")
}
if ((Ask (T 'Make room by shrinking userdata? (yes/no)') 'no' 'MU300_ANS_MAKE_ROOM') -ne 'yes') { Die (T 'nothing was changed.') }
while ($true) {
@@ -1050,6 +1212,32 @@ function OfferRepartition([int64]$Disk, [int64]$LastEnd, [int64]$Size) {
# the word itself, in capitals, in every language
if ((Ask (T 'Type ERASE to rewrite the partition table and wipe Android''s data') '' 'MU300_ANS_ERASE_ANDROID') -cne 'ERASE') { Die (T 'nothing was changed.') }
# a backup on this computer, before anything is written
Step 'backup' 30
$bd = Join-Path $BackupDir ((Get-Date -Format 'yyyyMMdd-HHmmss') + '-' + $rf.CID.Substring(24, 8))
Say (T 'Backing up to {1}' $bd)
ResumeBackup $bd $g
Info 'resume.backup' $bd
# the transaction, saved before the first write; the region by the installers' arithmetic behind the new end
$rg = FreeRegion ($newEnd + 1) $Disk
$tok = [string]((ResumePy token) | Select-Object -First 1)
$idArgs = @('identity', $Top)
if ($PKG) { $idArgs += (Join-Path $PKG 'mu300\manifest') }
$id = [string]((ResumePy @idArgs) | Select-Object -First 1)
if ($tok -notmatch '^[0-9a-f]{32}$' -or $id -notmatch '^[0-9a-f]{64}$') { Die (T 'could not compute the installer identity') }
$tx = Join-Path $bd 'transaction.json'
ResumePy new $tx "serial=$($rf.SERIAL)" "slot=$ANDROID_SLOT" "cid=$($rf.CID)" "node=$($rf.NODE)" "start=$($rf.START)" `
"size=$($rf.SIZE)" "disk=$Disk" "target=$($newEnd - [int64]$rf.START + 1)" "need=$($rg.End - $rg.Start)" `
"usable_end=$($info.UsableEnd)" "region_start=$($rg.Start)" "region_end=$($rg.End)" "token=$tok" "identity=$id" `
"crypto=$($rf.CRYPTO)" "crypto_state=$($rf.STATE)" "crypto_type=$($rf.TYPE)" "backup=$bd" | Out-Null
if ($script:ResumeRc -ne 0) { Die (T 'could not save the transaction; nothing was changed') }
Info 'resume.transaction' $tx
Write-Host (' ' + (T 'transaction saved: {1}' $tx))
ResumePy marker $tok "$g\marker.bin" | Out-Null
ResumePy bcb "$g\bcb.bin" | Out-Null
if (-not (Test-Path "$g\marker.bin") -or -not (Test-Path "$g\bcb.bin")) { Die (T 'could not prepare the files to write; nothing was changed') }
Step 'repartition' 50
Say (T 'Rewriting the partition table')
Remove-Item -Force "$g\new.head", "$g\new.tail" -ErrorAction SilentlyContinue
@@ -1057,21 +1245,18 @@ function OfferRepartition([int64]$Disk, [int64]$LastEnd, [int64]$Size) {
$made = $script:GptRc -eq 0 -and (Test-Path "$g\new.head") -and (Test-Path "$g\new.tail")
if ($made) { $made = (Get-Item "$g\new.head").Length -eq 34 * 512 -and (Get-Item "$g\new.tail").Length -eq 33 * 512 }
if (-not $made) { Die (T 'the resize was refused; nothing is changed') }
# What goes into the partition table is what the tool made, byte for byte: a push that failed or stopped halfway
# leaves no file or a short one on the device, and dd would write that (install.sh does not look).
foreach ($n in 'head', 'tail') {
Quiet { adb push "$g\new.$n" "$T/new.$n" } | Out-Null
$sum = (([string](SuDo "sha256sum $T/new.$n")).Trim() -split '\s+')[0]
if ($sum -ne (Get-FileHash "$g\new.$n" -Algorithm SHA256).Hash.ToLower()) {
SuDo "rm -f $T/new.head $T/new.tail" | Out-Null
# what goes to the device is what was made here, byte for byte (a push that stopped halfway leaves a short file)
foreach ($n in 'new.head', 'new.tail', 'marker.bin', 'bcb.bin') {
if (-not (ResumePush "$g\$n" "$T/mu300-$n")) {
SuDo "rm -f $T/mu300-new.head $T/mu300-new.tail $T/mu300-marker.bin $T/mu300-bcb.bin" | Out-Null
Die (T 'the new partition table did not arrive on the device as it was made; nothing is changed')
}
}
# the backup copy first: if power is lost between the two, the primary is still the old table and the
# device boots, which is the recoverable order
SuDo "dd if=$T/new.tail of=/dev/block/mmcblk0 bs=512 seek=$($Disk - 33) conv=fsync 2>/dev/null" | Out-Null
SuDo "dd if=$T/new.head of=/dev/block/mmcblk0 bs=512 conv=fsync 2>/dev/null" | Out-Null
SuDo "sync; rm -f $T/new.head $T/new.tail" | Out-Null
$abBefore = (SuDo 'dd if=/dev/block/by-name/misc bs=1 skip=2048 count=32 2>/dev/null | od -An -tx1 -v') -replace '\s', ''
# the backup copy first: if power is lost between the two, the primary is still the old table and the device
# boots, which is the recoverable order
SuDo "dd if=$T/mu300-new.tail of=/dev/block/mmcblk0 bs=512 seek=$($Disk - 33) conv=fsync 2>/dev/null" | Out-Null
SuDo "dd if=$T/mu300-new.head of=/dev/block/mmcblk0 bs=512 conv=fsync 2>/dev/null" | Out-Null
Say (T 'Verifying')
$null = GptDump $Disk "$g\after"
@@ -1082,16 +1267,28 @@ function OfferRepartition([int64]$Disk, [int64]$LastEnd, [int64]$Size) {
if ($after.End -ne $newEnd) { Die (T 'the table did not take (userdata still ends at {1}). Nothing else was changed.' $after.End) }
Write-Host (' ' + (T 'userdata now ends at sector {1}' $after.End))
# Android cannot mount a filesystem that claims to be larger than its partition; clearing the superblocks
# is what makes it format /data cleanly on the next boot instead of bootlooping on a repair attempt.
Say (T 'Clearing Android''s data filesystem so it is recreated on the next boot')
SuDo 'dd if=/dev/zero of=/dev/block/by-name/userdata bs=1M count=32 conv=fsync 2>/dev/null' | Out-Null
# the token: the first 4 KiB of the region, outside every partition from now on
SuDo "dd if=$T/mu300-marker.bin of=/dev/block/mmcblk0 bs=512 seek=$($rg.Start) count=8 conv=notrunc,fsync 2>/dev/null" | Out-Null
if ((ResumeSha "dd if=/dev/block/mmcblk0 bs=512 skip=$($rg.Start) count=8 2>/dev/null | sha256sum") -ne (Get-FileHash "$g\marker.bin" -Algorithm SHA256).Hash.ToLower()) {
Die (T 'the token did not read back from the device; misc was not changed, Android keeps its data. Run the installer again.')
}
# the reset, by Android's own recovery: the bootloader message in the first 2 KiB of misc
Say (T 'Asking Android''s recovery to reset Android''s data on the next boot')
SuDo "dd if=$T/mu300-bcb.bin of=/dev/block/by-name/misc bs=2048 count=1 conv=notrunc,fsync 2>/dev/null" | Out-Null
$abAfter = (SuDo 'dd if=/dev/block/by-name/misc bs=1 skip=2048 count=32 2>/dev/null | od -An -tx1 -v') -replace '\s', ''
if ((ResumeSha 'dd if=/dev/block/by-name/misc bs=2048 count=1 2>/dev/null | sha256sum') -ne (Get-FileHash "$g\bcb.bin" -Algorithm SHA256).Hash.ToLower() -or $abAfter -ne $abBefore) {
Die (T 'the request for the reset did not read back from misc. The partition table is changed already: run the installer again, it continues from here.')
}
SuDo "sync; rm -f $T/mu300-new.head $T/mu300-new.tail $T/mu300-marker.bin $T/mu300-bcb.bin" | Out-Null
ResumePy set $tx 'state=prepared' | Out-Null
if ($script:ResumeRc -ne 0) { Die (T 'could not save the transaction') }
Say (T 'Done - the device has to reboot before the new layout is visible')
Write-Host (' ' + (T 'Android will set up its data partition again on this boot, which takes a few minutes.'))
Write-Host (' ' + (T 'When it is back, run this installer again and it will find the free space.'))
Say (T 'Done - the device restarts into the reset now')
Write-Host (' ' + (T "Android's recovery formats Android's data on the next start; then Android starts as new. Set it up,"))
Write-Host (' ' + (T 'turn USB debugging on, bring root back (the Magisk app, Shell allowed), and run this installer again.'))
Write-Host (' ' + (T 'transaction: {1}' $tx))
$rb = Ask (T 'Reboot now? (yes/no)') 'yes' 'MU300_ANS_REBOOT'
Progress 'done' 'result' 'ok' 'repartitioned' 'yes'
Progress 'done' 'result' 'ok' 'repartitioned' 'yes' 'resume' 'pending' 'transaction' $tx
if ($rb -eq 'yes') { Quiet { adb reboot } | Out-Null }
}
@@ -1111,7 +1308,9 @@ if ($sd.Count -eq 3 -and $sd[2] -eq 'SD' -and $sd[1] -match '^[0-9]+$') {
}
Info 'sd.device' $SD_DEV; Info 'sd.bytes' $SD_BYTES
$SD_MODE = 0; $sdEx = 'no'
if ($Check) {
if ($RESUMING -eq 1 -and -not $Check) {
Info 'storage' 'internal' # the region that was prepared for it
} elseif ($Check) {
if ($SD_DEV) {
$sdEx = SdExisting
Info 'sd.state' $sdEx
@@ -1184,7 +1383,7 @@ if ($SD_MODE -eq 1) {
}
$dirty = 0
if ($SD_MODE -eq 0 -and $existing -eq 'no') {
if ($SD_MODE -eq 0 -and $existing -eq 'no' -and $RESUMING -eq 0) {
$step = [int64]($SIZE / 1MB / 16)
$probe = (0..15 | ForEach-Object { [int64]($OFF / 1MB) + $_ * $step }) -join ' '
# Empty is 0x00 or 0xFF (what an eMMC reads back after an erase). No double quotes in the command: Windows
@@ -1199,7 +1398,10 @@ if ($SD_MODE -eq 0 -and $existing -eq 'no') {
Write-Host (' ' + (T 'start of the region: {1}' $head.Trim()))
}
}
if ($existing -eq 'yes') {
if ($RESUMING -eq 1) {
# (what the region holds is what was userdata, erased with the word ERASE when it was prepared, and the token)
$vcode = 'resume'; $verdict = T 'OK: the region prepared by making room, checked against its transaction'
} elseif ($existing -eq 'yes') {
$vcode = 'existing'; $verdict = T 'OK: a MU300 Linux installation is already present (it can be kept or replaced)'
} elseif ($SD_MODE -eq 1) {
$vcode = 'sd'; $verdict = T 'OK: the SD card will be formatted; everything on it is erased'
@@ -1710,6 +1912,11 @@ if ("$readBack".Split(' ')[0] -ne $EXP) {
Die (T 'boot_{1} verify failed (slot {2} still active, Android keeps booting)' $LINUX_SLOT $ANDROID_SLOT)
}
SuDo "dd if=$T/mu300-bc.bin of=/dev/block/by-name/misc bs=1 seek=2048 conv=notrunc && sync && rm $T/mu300-boot.img $T/mu300-bc.bin $T/mu300-boot.rb" | Out-Null
# the prepared installation is done: its transaction no longer waits (kano: state installed)
if ($RESUMING -eq 1) {
ResumePy set $RESUME_TX 'state=installed' | Out-Null
if ($script:ResumeRc -ne 0) { Write-Host (' ' + (T 'could not mark {1} as done' $RESUME_TX)) }
}
# on-device switch for later: one command in Android instead of plugging into a computer (needs Magisk)
Step 'switch' 96
+63 -38
View File
@@ -5,7 +5,12 @@
#
# On the 32 GB variant there is no free region at all (userdata fills the disk). The installer then offers
# to shrink userdata to make one - EXPERIMENTAL, it rewrites the partition table and erases everything in
# Android, so take a full backup with tools/backup-device.sh first.
# Android, so take a full backup with tools/backup-device.sh first. Android's own recovery resets Android's data
# (that is what works with its encryption), and the installation resumes on the next run of this installer, once
# Android is set up again with USB debugging and root (tools/resume.sh; a transaction in ~/mu300-backups):
# ./install.sh --resume continue the prepared installation, or stop when there is none for this device
# ./install.sh --no-resume install as if nothing had been prepared (MU300_RESUME=0)
# ./install.sh --transaction FILE that transaction, not the newest one for the device (MU300_TRANSACTION)
# ./install.sh install Ubuntu, OpenWrt or both from the prebuilt release images
# ./install.sh --build build kernel outputs/root filesystems locally instead (see README "Build and run")
# ./install.sh --backup only copy what an installation reads first to this computer: Android's boot image
@@ -73,6 +78,7 @@ T=/data/local/tmp
MODE=prebuilt; CHECK_ONLY=0; BACKUP_ONLY=0; ADB_PATH_ONLY=0; ANSWERS_FILE=; _opt=
for a in "$@"; do
if [ "$_opt" = answers ]; then ANSWERS_FILE=$a; _opt=; continue; fi
if [ "$_opt" = transaction ]; then MU300_TRANSACTION=$a; export MU300_TRANSACTION; _opt=; continue; fi
if [ "$_opt" = package ]; then MU300_PACKAGE=$a; export MU300_PACKAGE; _opt=; continue; fi
case $a in
--check) CHECK_ONLY=1 ;;
@@ -82,6 +88,10 @@ for a in "$@"; do
--adb-path) ADB_PATH_ONLY=1 ;;
--answers) _opt=answers ;;
--answers=*) ANSWERS_FILE=${a#--answers=} ;;
--resume) MU300_RESUME=1; export MU300_RESUME ;;
--no-resume) MU300_RESUME=0; export MU300_RESUME ;;
--transaction) _opt=transaction ;;
--transaction=*) MU300_TRANSACTION=${a#--transaction=}; export MU300_TRANSACTION ;;
--package) _opt=package ;;
--package=*) MU300_PACKAGE=${a#--package=}; export MU300_PACKAGE ;;
-h|--help) sed -n '2,/^set -eu/{/^set -eu/d;s/^# \{0,1\}//p;}' "$0"; exit 0 ;;
@@ -96,6 +106,7 @@ REPO=${MU300_REPO:-dikeckaan/mu300-linux}
. "$TOP/tools/i18n.sh"
. "$TOP/tools/storage.sh"
. "$TOP/tools/releases.sh"
. "$TOP/tools/resume.sh"
. "$TOP/tools/package.sh"
# adb from platform-tools unzipped next to the project (or into the usual places) needs no PATH entry
find_adb() {
@@ -122,9 +133,16 @@ if [ -n "$PKG" ]; then
info package "$PKG"; info package.system "$PKG_SYSTEM"; info package.kernel "$PKG_KERNEL"; info package.release "$PKG_TAG"
echo "$(t 'Package: {1} with kernel {2}, release {3} (unpacked Magisk zip at {4})' "$PKG_SYSTEM" "$PKG_KERNEL" "$PKG_TAG" "$PKG")"
fi
# first of all, make this the newest installer (it restarts itself when it changed)
# first of all, make this the newest installer (it restarts itself when it changed) - not from a package, and not
# while a prepared installation waits: its transaction is bound to the tools that prepared it (tools/resume.sh)
. "$TOP/tools/self-update.sh"
[ -n "$PKG" ] || self_update "$0" "$@"
if [ -n "$PKG" ]; then
:
elif resume_pending; then
echo " $(t 'a prepared installation is waiting (tools/resume.sh): this installer does not update itself until it is done')"
else
self_update "$0" "$@"
fi
# the graphical installer, offered once to a person who starts a plain installation
. "$TOP/tools/gui-launch.sh"
[ $CHECK_ONLY = 1 ] || [ $BACKUP_ONLY = 1 ] || [ $MODE != prebuilt ] || gui_offer
@@ -458,12 +476,18 @@ offer_repartition() {
info makeroom.min_android $MIN_ANDROID; info makeroom.min_linux $MIN_LINUX; info makeroom.max_linux $max_linux
[ $max_linux -ge $MIN_LINUX ] || die "$(t 'there is not enough room to split: {1} in total,' "$(gib $((total * 512)))")
$(t 'and Android needs at least {1} of it. Nothing is changed.' "$(gib $((MIN_ANDROID * 512)))")"
# the device's identity and how Android keeps its data (read only); kano's rule: encrypted, plain, or unknown
resume_facts || die "$(t 'could not read what identifies this device (serial, eMMC CID, userdata)')"
[ "$UD_START" = "$LAST_FIRST" ] && [ $((UD_START + UD_SIZE - 1)) = "$LAST_END" ] ||
die "$(t 'the partition table and the running kernel disagree about userdata; reboot Android and try again')"
info makeroom.crypto "$CRYPTO"; info makeroom.crypto_state "$CRYPTO_STATE"; info makeroom.crypto_type "$CRYPTO_TYPE"
echo
echo " eMMC: $(gib $((disk * 512)))"
echo " $(t 'userdata now: {1} (sectors {2}..{3})' "$(gib $((LAST_END - LAST_FIRST + 1)))" "$LAST_FIRST" "$LAST_END")"
echo " $(t 'free behind it: {1}' "$(gib $(( (USABLE_END - LAST_END) * 512 )))")"
echo " $(t 'to share: {1}' "$(gib $((total * 512)))")"
echo " $(t "Android's data: {1} ({2})" "$(case $CRYPTO in yes) t 'encrypted' ;; no) t 'not encrypted' ;; *) t 'unknown' ;; esac)" "${CRYPTO_STATE:-?}${CRYPTO_TYPE:+/$CRYPTO_TYPE}")"
echo
echo " $(t 'Linux needs at least {1} (OpenWrt) / 1.6 GiB (Ubuntu) / 2.4 GiB (both)' "$(gib $((MIN_LINUX * 512)))")"
echo " $(t 'Android keeps at least {1}' "$(gib $((MIN_ANDROID * 512)))")"
@@ -471,12 +495,20 @@ $(t 'and Android needs at least {1} of it. Nothing is changed.' "$(gib $((MIN_AN
echo " $(t 'THIS IS EXPERIMENTAL. It rewrites the partition table and ERASES everything in Android -')"
echo " $(t 'apps, photos, accounts, settings. Take a full backup first: sh tools/backup-device.sh')"
echo " $(t 'Only userdata changes size; it is the last partition, so nothing else moves.')"
echo " $(t "Android's own recovery erases Android's data: the device restarts into it, resets Android (a factory")"
echo " $(t 'reset) and starts Android again, which takes a few minutes and more than one restart. Then set Android up')"
echo " $(t 'again, turn USB debugging back on and bring root back (Magisk: install the Magisk app again and let')"
echo " $(t 'Shell have root), and run this installer again: it finds what was prepared and continues.')"
echo " $(t 'What was prepared, and a backup of the partition table, misc, boot and the boot chain, are kept on this')"
echo " $(t 'computer in {1} - the reset erases everything of it on the device.' "$BACKUP_DIR")"
echo
if [ $CHECK_ONLY = 1 ]; then
echo " $(t '--check writes nothing. Run the installer without it to make room.')"
progress done result ok
exit 0
fi
# kano's rule: an encryption state that cannot be told is no ground to stand on
[ "$CRYPTO" != unknown ] || die "$(t "Android's encryption state is unknown ({1}); nothing is changed." "${CRYPTO_STATE:-?}/${CRYPTO_TYPE:-?}")"
ask go "$(t 'Make room by shrinking userdata? (yes/no)')" no MU300_ANS_MAKE_ROOM
[ "$go" = yes ] || die "$(t 'nothing was changed.')"
@@ -501,41 +533,21 @@ $(t 'and Android needs at least {1} of it. Nothing is changed.' "$(gib $((MIN_AN
ask sure "$(t "Type ERASE to rewrite the partition table and wipe Android's data")" "" MU300_ANS_ERASE_ANDROID
[ "$sure" = ERASE ] || die "$(t 'nothing was changed.')"
step repartition 50
say "$(t 'Rewriting the partition table')"
python3 "$TOP/tools/resize-last-partition.py" "$WORK/gpt/gpt.head,$WORK/gpt/gpt.tail" \
--disk-sectors "$disk" --name userdata --end-sector "$new_end" --out "$WORK/gpt/new" || die "$(t 'the resize was refused; nothing is changed')"
adb push "$WORK/gpt/new.head" /data/local/tmp/new.head >/dev/null 2>&1
adb push "$WORK/gpt/new.tail" /data/local/tmp/new.tail >/dev/null 2>&1
# the backup copy first: if power is lost between the two, the primary is still the old table and the
# device boots, which is the recoverable order
su_do "dd if=/data/local/tmp/new.tail of=/dev/block/mmcblk0 bs=512 seek=$((disk - 33)) conv=fsync 2>/dev/null" >/dev/null
su_do "dd if=/data/local/tmp/new.head of=/dev/block/mmcblk0 bs=512 conv=fsync 2>/dev/null" >/dev/null
su_do 'sync; rm -f /data/local/tmp/new.head /data/local/tmp/new.tail' >/dev/null
# a backup on this computer, before anything is written (kano's backup: the table, misc, boot and the boot chain
# of both slots, checked against the device)
step backup 30
RESUME_BD=$BACKUP_DIR/$(date +%Y%m%d-%H%M%S)-$(printf '%s' "$CID" | cut -c25-32)
say "$(t 'Backing up to {1}' "$RESUME_BD")"
resume_backup "$RESUME_BD"
info resume.backup "$RESUME_BD"
resume_prepare "$new_end"
say "$(t 'Verifying')"
su_do "dd if=/dev/block/mmcblk0 bs=512 count=34 2>/dev/null > /data/local/tmp/gpt.head" >/dev/null
su_do "dd if=/dev/block/mmcblk0 bs=512 skip=$((disk - 33)) count=33 2>/dev/null > /data/local/tmp/gpt.tail" >/dev/null
adb pull /data/local/tmp/gpt.head "$WORK/gpt/after.head" >/dev/null 2>&1 || true
adb pull /data/local/tmp/gpt.tail "$WORK/gpt/after.tail" >/dev/null 2>&1 || true
su_do 'rm -f /data/local/tmp/gpt.head /data/local/tmp/gpt.tail' >/dev/null
check=$(python3 "$TOP/tools/resize-last-partition.py" "$WORK/gpt/after.head,$WORK/gpt/after.tail" \
--disk-sectors "$disk" --name userdata --show) || die "$(t 'the table on the device does not read back as valid GPT.')
$(t "The backup copy at the end of the disk was written first, so Android's own repair may still fix this. Do not power off.")"
got=$(echo "$check" | sed -n 's/^LAST_END=//p')
[ "$got" = "$new_end" ] || die "$(t 'the table did not take (userdata still ends at {1}). Nothing else was changed.' "$got")"
echo " $(t 'userdata now ends at sector {1}' "$got")"
# Android cannot mount a filesystem that claims to be larger than its partition; clearing the superblocks
# is what makes it format /data cleanly on the next boot instead of bootlooping on a repair attempt.
say "$(t "Clearing Android's data filesystem so it is recreated on the next boot")"
su_do "dd if=/dev/zero of=/dev/block/by-name/userdata bs=1M count=32 conv=fsync 2>/dev/null" >/dev/null
say "$(t 'Done - the device has to reboot before the new layout is visible')"
echo " $(t 'Android will set up its data partition again on this boot, which takes a few minutes.')"
echo " $(t 'When it is back, run this installer again and it will find the free space.')"
say "$(t 'Done - the device restarts into the reset now')"
echo " $(t "Android's recovery formats Android's data on the next start; then Android starts as new. Set it up,")"
echo " $(t 'turn USB debugging on, bring root back (the Magisk app, Shell allowed), and run this installer again.')"
echo " $(t 'transaction: {1}' "$RESUME_FILE")"
ask rb "$(t 'Reboot now? (yes/no)')" yes MU300_ANS_REBOOT
progress done result ok repartitioned yes
progress done result ok repartitioned yes resume pending transaction "$RESUME_FILE"
[ "$rb" = yes ] && adb reboot
exit 0
}
@@ -545,6 +557,11 @@ step storage 6
say "$(t 'Locating free eMMC space after the last partition')"
region_probe || die "$(t 'could not read the partition table from the device (is su granted? try again)')"
info emmc.sectors "$disk"; info emmc.last_end "$last_end"; info region.offset "$OFF"; info region.size "$SIZE"
# a prepared installation waiting for this device (the make-room path below, on an earlier run): its checks first
resume_lookup
if [ $RESUME = 1 ]; then
if [ $CHECK_ONLY = 1 ]; then resume_validate soft || RESUME=0; else resume_validate; fi
fi
# the partitions, for a picture of the eMMC: "name:first sector:sectors" of each (the stream only; sysfs, read only)
[ -z "$PROGRESS_FD" ] || info partitions "$(su_do 'for p in /sys/block/mmcblk0/mmcblk0p*; do echo $(sed -n s/^PARTNAME=//p $p/uevent):$(cat $p/start):$(cat $p/size); done' | tr '\n' ' ')"
gib() { awk -v b="$1" 'BEGIN { printf "%.1f GiB", b / 1073741824 }'; }
@@ -565,6 +582,9 @@ if [ $CHECK_ONLY = 1 ]; then
echo "$(t 'SD card: {1}, {2}, existing mu300sd filesystem: {3}' "$SD_DEV" "$(gib "$SD_BYTES")" "$(t "$([ $sd_ex = yes ] && echo yes || echo no)")")"
[ $sd_ex = foreign ] && echo " $(t 'the SD card holds another Linux (ext4) filesystem; the installer will not format it')"
fi
elif [ $RESUME = 1 ]; then
SD_MODE=0 # the region that was prepared for it
info storage internal
else
choose_storage
info storage "$([ $SD_MODE = 1 ] && echo sd || echo internal)"
@@ -597,14 +617,17 @@ fi
# 0x00 or 0xFF: an eMMC reads back what its erase leaves (EXT_CSD ERASED_MEM_CONT), and on some F50s that is 0xFF -
# counted as data, a region that was never written stopped the install with "not empty".
DIRTY=0
if [ $SD_MODE = 0 ] && [ $existing = no ]; then
if [ $SD_MODE = 0 ] && [ $existing = no ] && [ $RESUME = 0 ]; then
region_dirty
echo "$(t 'data check: {1} of 16 samples contain data' "$DIRTY")"
info region.dirty "$DIRTY"
# what is there, for a report: the first bytes of the region
[ "$DIRTY" -gt 0 ] && echo " $(t 'start of the region: {1}' "$(su_do "dd if=/dev/block/mmcblk0 bs=1048576 skip=$(( OFF / 1048576 )) count=1 2>/dev/null | od -An -tx1 -N32" | tr -s ' \n' ' ')")"
fi
if [ $existing = yes ]; then
if [ $RESUME = 1 ]; then
# (what the region holds is what was userdata, erased with the word ERASE when it was prepared, and the token)
vcode=resume; verdict=$(t 'OK: the region prepared by making room, checked against its transaction')
elif [ $existing = yes ]; then
vcode=existing; verdict=$(t 'OK: a MU300 Linux installation is already present (it can be kept or replaced)')
elif [ $SD_MODE = 1 ]; then
vcode=sd; verdict=$(t 'OK: the SD card will be formatted; everything on it is erased')
@@ -1050,6 +1073,8 @@ bootchain_pull
step boot 92
write_linux_boot "$WORK/boot-linux-slot$LINUX_SLOT.img"
# the prepared installation is done: its transaction no longer waits (kano: state installed)
[ $RESUME = 0 ] || resume_py set "$RESUME_FILE" state=installed || echo " $(t 'could not mark {1} as done' "$RESUME_FILE")"
# on-device switch for later: one command in Android instead of plugging into a computer (needs Magisk)
step switch 96
+72 -1
View File
@@ -12,6 +12,11 @@ Every call is appended to <state.json>.log as one JSON line: {"argv": [...], "ki
"read" for what only reads, "write" for a device command that would have written (dd of=, rm, a redirection into a
file, sh of a pushed script), "push", "pull", "reboot", and "unknown" for a command this file has no answer for -
which a test should treat as a mistake.
With "emmc" set to a directory (tests/fakeemmc.py makes one) the device's storage is real: every command that names
a block device, sysfs, /proc/mounts or /data/local/tmp runs in a shell against that directory (those paths rewritten
into it, dd kept from truncating a file it writes into), pushes and pulls copy files there, and the rest is answered
as above. The make-room path's writes and the resumed installation's checks are then tested on what was written.
"""
import hashlib
import json
@@ -50,7 +55,13 @@ DEFAULT = {
'boot_image_bytes': 4096, # size of the fake boot image a pull gives
'linux_json': '', # what `mu300-device --json` says on a device whose serial is MU300LINUX-...
'pull': True, # adb pull works; false: every pull fails, as with a cable that drops out;
# "gpt": only the two pieces of the partition table can be pulled
# "gpt": only the two pieces of the partition table can be pulled; "noboot" (with
# "emmc"): every pull but that of a boot partition works
'cid': '15010053454d36344720c1a6b7d2e900', # the eMMC's CID (sysfs), 32 hex digits
'crypto_state': 'encrypted', # ro.crypto.state (the F50's Android 13: file-based encryption)
'crypto_type': 'file', # ro.crypto.type
'data_source': '/dev/block/dm-6', # what /data is mounted from
'emmc': None, # a directory standing for the device's storage (tests/fakeemmc.py): see above
}
T = '/data/local/tmp'
@@ -150,12 +161,56 @@ def pending_is_gpt(flag=None):
return flag
def emmc_run(st, cmd):
"""A device command run for real against the directory st['emmc'] (see the module's docstring); (text, kind)."""
import subprocess
d = st['emmc']
real = cmd
for path, there in (('/data/local/tmp', d + '/tmp'), ('/dev/block/', d + '/dev/block/'), ('/sys/', d + '/sys/'),
('/proc/mounts', d + '/proc/mounts')):
real = real.replace(path, there)
# (dd: tests/fakeemmc.py's bin/dd keeps it from cutting short a file it writes into)
env = dict(os.environ, PATH=d + '/bin:' + os.environ.get('PATH', ''), FAKE_EMMC=d)
r = subprocess.run(['sh', '-c', real], capture_output=True, env=env)
out = r.stdout.decode('utf-8', 'replace').replace(os.path.realpath(d), '').replace(d, '').rstrip('\n')
if re.fullmatch(r'cat /dev/block/by-name/boot_[ab] > /data/local/tmp/mu300-pull\.bin', cmd):
open(state_path() + '.boot-pending', 'w').close() # (pull "noboot": this pull is refused)
elif '/data/local/tmp/mu300-pull.bin' in cmd and os.path.exists(state_path() + '.boot-pending'):
os.remove(state_path() + '.boot-pending')
return out, ('write' if re.search(r'\bof=/dev/block/|(?<![0-9])>\s*/dev/(?!null)', cmd) else 'read')
def emmc_cmd(cmd):
"""Whether a command touches the storage that tests/fakeemmc.py makes real."""
return any(p in cmd for p in ('/dev/block/', '/sys/', '/proc/mounts', '/data/local/tmp'))
def facts(st):
"""What resume_facts reads (tools/resume.sh, install.ps1's ResumeFacts): userdata's node, first sector and sectors,
the eMMC's CID, the crypto properties and what /data is mounted from."""
disk, parts, last_end, off, size = geometry(st)
names = [n for n, _, _ in parts]
i = names.index('userdata')
first, last = parts[i][1], parts[i][2]
return '\n'.join(['NODE=mmcblk0p%d' % (i + 1), 'CID=' + st['cid'], 'START=%d' % first, 'SIZE=%d' % (last - first + 1),
'STATE=' + st['crypto_state'], 'TYPE=' + st['crypto_type'], 'SOURCE=' + st['data_source'],
'MAGIC=', 'EXT='])
FACTS_CMD = 'd=$(readlink -f /dev/block/by-name/userdata);'
def su(st, cmd, argv):
"""The answer of the device to `su -c 'cmd'`; (text, kind)."""
if st.get('emmc') and emmc_cmd(cmd) and cmd != 'sh %s/android-bootchain.sh check' % T:
return emmc_run(st, cmd)
disk, parts, last_end, off, size = geometry(st)
sd = st['sd']
if cmd == 'id -u':
return '0', 'read'
if cmd.startswith(FACTS_CMD):
return facts(st), 'read'
m = re.fullmatch(r'getprop (\S+)', cmd)
if m:
return prop(st, m.group(1)), 'read'
@@ -348,6 +403,11 @@ def main(argv):
return 0
if cmd == 'push':
log('push', argv)
if st.get('emmc'):
import shutil
srcs, dst = rest[:-1], rest[-1].replace('/data/local/tmp', st['emmc'] + '/tmp')
for src in srcs:
shutil.copy(src, os.path.join(dst, os.path.basename(src)) if dst.endswith('/') or os.path.isdir(dst) else dst)
return 0
if cmd == 'pull':
log('pull', argv)
@@ -356,6 +416,17 @@ def main(argv):
if not st['pull'] or (st['pull'] == 'gpt' and name not in ('gpt.head', 'gpt.tail') and not pending_is_gpt()):
sys.stderr.write('adb: error: failed to copy: remote object does not exist\n')
return 1
if st.get('emmc'):
if st['pull'] == 'noboot' and name == 'mu300-pull.bin' and os.path.exists(state_path() + '.boot-pending'):
sys.stderr.write('adb: error: failed to copy: remote object does not exist\n')
return 1
there = src.replace('/data/local/tmp', st['emmc'] + '/tmp')
if not os.path.isfile(there):
sys.stderr.write('adb: error: failed to stat remote object\n')
return 1
with open(there, 'rb') as f, open(dst, 'wb') as g:
g.write(f.read())
return 0
if name == 'mu300-pull.bin':
data = pending(st)
elif name in ('gpt.head', 'gpt.tail'):
+149
View File
@@ -0,0 +1,149 @@
"""Not a test: the storage of a fake F50 as a directory, for tests/fakeadb.py's "emmc" mode - the make-room path's
writes (tools/resume.sh) and the checks of the installation that resumes after the reset, on what was written.
dev/block/mmcblk0 the whole eMMC: a sparse file of the layout's size, with its partition table
(tests/fakegpt.py) in its first 34 and last 33 sectors
dev/block/mmcblk0pN userdata's node (a small file: its first bytes are all that is read)
dev/block/by-name/NAME misc (its A/B block valid, slot a), boot_a/b, the boot chain of both slots;
userdata a link to its node, as readlink -f resolves it on the device
sys/block/mmcblk0/... start, size and PARTNAME of every partition, the disk's size
sys/class/block/... userdata's start and size, the eMMC's CID
proc/mounts, props what /data is mounted from; the properties getprop answers
bin/ getprop, dd (never truncates a file it writes into, takes no conv=fsync), sha256sum
tmp/ /data/local/tmp
reset(d) does what the device does on the next start after the make-room path: the kernel reads the partition table
again (sysfs follows the table in the eMMC), and Android's recovery, asked by the bootloader message in misc,
formats userdata and clears the message. Nothing here runs on, or reaches, a real device.
"""
import os
import shutil
import stat
import struct
import sys
import zlib
from pathlib import Path
import fakegpt
SECTOR = 512
CID = '15010053454d36344720c1a6b7d2e900'
CHAIN = ('uboot', 'sml', 'teecfg', 'trustos', 'vbmeta')
def _misc(slot='a'):
bc = bytearray(32)
bc[0:4] = ('_' + slot).encode() + b'\0\0'
bc[4:8] = b'BCAB'
bc[8] = 1
bc[12], bc[14] = (0x9f, 0x1e) if slot == 'a' else (0x1e, 0x9f)
bc[28:32] = struct.pack('<I', zlib.crc32(bytes(bc[:28])))
return bytes(2048) + bytes(bc) + bytes((1 << 20) - 2048 - 32)
def _exe(path, text):
path.write_text(text)
path.chmod(path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
def make(d, layout='vendor64', crypto=('encrypted', 'file'), source='/dev/block/dm-6', cid=CID, slot='a'):
"""The directory D standing for a device with this partition table; returns D."""
d = Path(d)
disk, usable, parts = fakegpt.layout(layout)
for sub in ('dev/block/by-name', 'sys/block/mmcblk0', 'sys/class/block/mmcblk0/device', 'proc', 'bin', 'tmp'):
(d / sub).mkdir(parents=True, exist_ok=True)
head, tail = fakegpt.make(disk, usable, parts)
with open(d / 'dev/block/mmcblk0', 'wb') as f:
f.truncate(disk * SECTOR)
f.write(head)
f.seek((disk - 33) * SECTOR)
f.write(tail)
(d / 'sys/block/mmcblk0/size').write_text('%d\n' % disk)
(d / 'sys/class/block/mmcblk0/device/cid').write_text(cid + '\n')
sysfs(d, parts)
for i, (name, _first, _last) in enumerate(parts, 1):
if name == 'userdata':
node = d / 'dev/block' / ('mmcblk0p%d' % i)
node.write_bytes(bytes(1024) + bytes.fromhex('1020f5f2') + bytes(4096 - 1028))
os.symlink('../mmcblk0p%d' % i, d / 'dev/block/by-name/userdata')
(d / 'dev/block/by-name/misc').write_bytes(_misc(slot))
for s in ('a', 'b'):
(d / 'dev/block/by-name' / ('boot_' + s)).write_bytes(('boot_%s ' % s).encode() * 100000)
for p in CHAIN:
(d / 'dev/block/by-name' / ('%s_%s' % (p, s))).write_bytes(('%s_%s ' % (p, s)).encode() * 3000)
(d / 'proc/mounts').write_text('%s /data f2fs rw,lazytime 0 0\n/dev/block/dm-3 /metadata ext4 ro 0 0\n' % source)
(d / 'props').write_text('ro.crypto.state=%s\nro.crypto.type=%s\n' % crypto)
_exe(d / 'bin/getprop', '#!/bin/sh\nsed -n "s/^$1=//p" "$FAKE_EMMC/props"\n')
real_dd = shutil.which('dd') or '/bin/dd'
_exe(d / 'bin/dd', '#!%s\n' % sys.executable + r'''import os, sys
# the device's dd on a directory: a write never cuts a file short (a block device has no length to lose), and
# BSD dd knows no conv=fsync
args = [a for a in sys.argv[1:] if not a.startswith('conv=')]
conv = [c for a in sys.argv[1:] if a.startswith('conv=') for c in a[5:].split(',') if c and c != 'fsync']
if any(a.startswith('of=') for a in args):
conv.append('notrunc')
if conv:
args.append('conv=' + ','.join(dict.fromkeys(conv)))
''' + 'os.execv(%r, ["dd"] + args)\n' % real_dd)
if not shutil.which('sha256sum'):
_exe(d / 'bin/sha256sum', '#!/bin/sh\nexec shasum -a 256 "$@"\n')
return d
def sysfs(d, parts):
"""sysfs as the kernel shows the table PARTS"""
d = Path(d)
for p in (d / 'sys/block/mmcblk0').glob('mmcblk0p*'):
shutil.rmtree(p)
for p in (d / 'sys/class/block').glob('mmcblk0p*'):
shutil.rmtree(p)
for i, (name, first, last) in enumerate(parts, 1):
for base in (d / 'sys/block/mmcblk0' / ('mmcblk0p%d' % i), d / 'sys/class/block' / ('mmcblk0p%d' % i)):
base.mkdir(parents=True)
(base / 'start').write_text('%d\n' % first)
(base / 'size').write_text('%d\n' % (last - first + 1))
(base / 'uevent').write_text('MAJOR=179\nMINOR=%d\nDEVNAME=mmcblk0p%d\nDEVTYPE=partition\nPARTN=%d\nPARTNAME=%s\n'
% (i, i, i, name))
def table(d):
"""the partition table in the fake eMMC, as [(name, first, last)] (both copies must agree)"""
d = Path(d)
disk = int((d / 'sys/block/mmcblk0/size').read_text())
with open(d / 'dev/block/mmcblk0', 'rb') as f:
head = f.read(34 * SECTOR)
f.seek((disk - 33) * SECTOR)
tail = f.read(33 * SECTOR)
nents, esize = struct.unpack_from('<II', head, SECTOR + 80)
parts, back = [], []
for i in range(nents):
for buf, base, out in ((head, 2 * SECTOR, parts), (tail, 0, back)):
e = buf[base + i * esize:base + (i + 1) * esize]
if e[:16] != bytes(16):
first, last = struct.unpack_from('<QQ', e, 32)
out.append((e[56:128].decode('utf-16-le').rstrip('\0'), first, last))
assert parts == back, 'the two copies of the table differ'
return parts
def bcb(d):
return (Path(d) / 'dev/block/by-name/misc').read_bytes()[:2048]
def reset(d, wipe=True):
"""the next start: the kernel reads the table again; recovery, when misc asks it to, formats userdata and clears
the request (WIPE=False: a recovery that did not run)"""
d = Path(d)
sysfs(d, table(d))
misc = d / 'dev/block/by-name/misc'
data = misc.read_bytes()
if wipe and data.startswith(b'boot-recovery\0') and b'--wipe_data' in data[64:832]:
node = Path(os.path.realpath(d / 'dev/block/by-name/userdata'))
node.write_bytes(bytes(1024) + bytes.fromhex('1020f5f2') + b'freshly formatted'.ljust(4096 - 1028, b'\0'))
misc.write_bytes(bytes(2048) + data[2048:])
def read(d, sector, count):
with open(Path(d) / 'dev/block/mmcblk0', 'rb') as f:
f.seek(sector * SECTOR)
return f.read(count * SECTOR)
+93 -22
View File
@@ -256,13 +256,28 @@ Check 'no install: default no' (VpnDefault @(VpnOnSystems @('ubuntu') 'no' 0 ''
Check 'no install: no probe' $script:suCmd ''
# ---- making room (issue #32): install.sh's offer_repartition, here OfferRepartition -------------------------------
$rnames = 'Quiet', 'FreeRegion', 'GptShow', 'RepartitionPlan', 'RepartitionSectors', 'LayoutFigures', 'GptTool', 'GptDump', 'OfferRepartition'
$rnames = 'Quiet', 'FreeRegion', 'GptShow', 'RepartitionPlan', 'RepartitionSectors', 'LayoutFigures', 'GptTool', 'GptDump', 'OfferRepartition',
'ResumePy', 'ParseFacts', 'FactsOk', 'ResumeFacts', 'ResumeBackup', 'ResumePush', 'ResumeSha', 'WriteUnix', 'ResumePending'
$rdefs = $ast.FindAll({ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $rnames -contains $n.Name }, $true)
foreach ($d in $rdefs) { . ([scriptblock]::Create($d.Extent.Text)) }
foreach ($w in $rnames) {
if (-not (Get-Command $w -CommandType Function -ErrorAction SilentlyContinue)) { Write-Host "FAIL: $w not found in install.ps1"; exit 99 }
}
LoadLanguage 'en'
# what the make-room path reads to identify the device, as install.ps1 sends it (the same text as tools/resume.sh's)
$FactsCmd = [regex]::Match([IO.File]::ReadAllText((Join-Path $Top 'install.ps1')), "(?m)^\`$script:FactsCmd = '([^']*)'").Groups[1].Value
$script:FactsCmd = $FactsCmd
$shFacts = [regex]::Match([IO.File]::ReadAllText((Join-Path (Join-Path $Top 'tools') 'resume.sh')), "_rf=\`$\(su_do '([^']*)'\)").Groups[1].Value
Check 'facts: the same command as install.sh' ($FactsCmd -and $FactsCmd -ceq $shFacts) $true
Check 'facts: no double quotes (Windows PowerShell 5.1 drops them)' $FactsCmd.Contains('"') $false
$pf = ParseFacts "NODE=mmcblk0p18`r`nCID=15010053454d36344720c1a6b7d2e900`nSTART=12275712`nSIZE=109879296`nSTATE=encrypted`nTYPE=file`nSOURCE=/dev/block/dm-6`nMAGIC=`nEXT="
Check 'facts: read' "$($pf.NODE) $($pf.START) $($pf.SIZE) $($pf.STATE) $($pf.TYPE) [$($pf.MAGIC)]" 'mmcblk0p18 12275712 109879296 encrypted file []'
$pf.SERIAL = '324950664950'
Check 'facts: ok' (FactsOk $pf) $true
foreach ($bad in @(@{ NODE = 'sda1' }, @{ NODE = 'mmcblk0p18;x' }, @{ CID = 'XYZ' }, @{ CID = ('a' * 31) }, @{ START = '' }, @{ SIZE = '1e3' }, @{ SERIAL = '' })) {
$b = $pf.Clone(); foreach ($k in $bad.Keys) { $b[$k] = $bad[$k] }
Check "facts: refused $(@($bad.Keys) -join ',')" (FactsOk $b) $false
}
# The figures of the 64 GB eMMC (FINDINGS #9): 122159104 sectors, last usable LBA 122155007, userdata from sector
# 12275712, 20 GiB of it at the factory. Issue #32 gives no sectors: its layout is this one with userdata extended to
# the last usable LBA (tests/fakegpt.py's vendor64).
@@ -373,16 +388,24 @@ if (-not $py) {
& $py (Join-Path (Join-Path $Top 'tests') 'fakegpt.py') (Join-Path $fx 'dev') $Layout
$script:dev = @{ disk = $D64; head = [IO.File]::ReadAllBytes((Join-Path $fx 'dev.head')); tail = [IO.File]::ReadAllBytes((Join-Path $fx 'dev.tail'))
files = @{}; cmds = (New-Object System.Collections.ArrayList); bad = 0; rebooted = $false; wiped = $false
shortPush = $false; deafDisk = $false; noRead = $false }
shortPush = $false; deafDisk = $false; noRead = $false; marker = @{}; bcb = $null
facts = "NODE=mmcblk0p18`nCID=15010053454d36344720c1a6b7d2e900`nSTART=$F64`nSIZE=$($U64 - $F64 + 1)`nSTATE=encrypted`nTYPE=file`nSOURCE=/dev/block/dm-6`nMAGIC=`nEXT=" }
$script:dev.head0 = Sha256Hex $script:dev.head; $script:dev.tail0 = Sha256Hex $script:dev.tail
if (-not $SameWork) { $script:Work = Join-Path $fx ('work-' + [guid]::NewGuid()) }
}
function Python { & $py @args }
function AdbProp($name) { if ($name -eq 'ro.serialno') { return '324950664950' } else { $script:dev.bad++; return '' } }
$ANDROID_SLOT = 'a'
$BackupDir = Join-Path $fx 'backups'
# the bytes of a partition of the fake device, the same every time
function PartBytes([string]$Name) { return [Text.Encoding]::ASCII.GetBytes(("$Name " * 300)) }
function SuDoToFile($cmd, $path) {
[void]$script:dev.cmds.Add("pull: $cmd")
if ($script:dev.noRead) { return }
if ($cmd -ceq 'dd if=/dev/block/mmcblk0 bs=512 count=34 2>/dev/null') { [IO.File]::WriteAllBytes($path, $script:dev.head) }
elseif ($cmd -ceq "dd if=/dev/block/mmcblk0 bs=512 skip=$($script:dev.disk - 33) count=33 2>/dev/null") { [IO.File]::WriteAllBytes($path, $script:dev.tail) }
elseif ($cmd -ceq 'dd if=/dev/block/by-name/misc bs=4096 count=1 2>/dev/null') { [IO.File]::WriteAllBytes($path, (New-Object byte[] 4096)) }
elseif ($cmd -cmatch '^cat /dev/block/by-name/((boot|uboot|sml|teecfg|trustos|vbmeta)_[ab])$') { [IO.File]::WriteAllBytes($path, (PartBytes $Matches[1])) }
else { $script:dev.bad++ }
}
function adb {
@@ -394,19 +417,35 @@ if (-not $py) {
} elseif ($args[0] -eq 'reboot' -and $args.Count -eq 1) { $script:dev.rebooted = $true }
else { $script:dev.bad++ }
}
$tmpFiles = '/data/local/tmp/mu300-new.head /data/local/tmp/mu300-new.tail /data/local/tmp/mu300-marker.bin /data/local/tmp/mu300-bcb.bin'
function SuDo($cmd) {
[void]$script:dev.cmds.Add("su: $cmd")
$seek = $script:dev.disk - 33
if ($cmd -cmatch '^sha256sum (/data/local/tmp/new\.(head|tail))$') {
if ($cmd -ceq $script:FactsCmd) { return $script:dev.facts }
if ($cmd -cmatch '^sha256sum (/data/local/tmp/mu300-(new\.head|new\.tail|marker\.bin|bcb\.bin))$') {
$f = $Matches[1]
if ($script:dev.files.ContainsKey($f)) { return "$(Sha256Hex $script:dev.files[$f]) $f`r" } else { return '' }
}
if ($cmd -ceq "dd if=/data/local/tmp/new.tail of=/dev/block/mmcblk0 bs=512 seek=$seek conv=fsync 2>/dev/null") {
if (-not $script:dev.deafDisk) { $script:dev.tail = $script:dev.files['/data/local/tmp/new.tail'] }
} elseif ($cmd -ceq 'dd if=/data/local/tmp/new.head of=/dev/block/mmcblk0 bs=512 conv=fsync 2>/dev/null') {
if (-not $script:dev.deafDisk) { $script:dev.head = $script:dev.files['/data/local/tmp/new.head'] }
} elseif ($cmd -ceq 'dd if=/dev/zero of=/dev/block/by-name/userdata bs=1M count=32 conv=fsync 2>/dev/null') { $script:dev.wiped = $true }
elseif ($cmd -cne 'sync; rm -f /data/local/tmp/new.head /data/local/tmp/new.tail' -and $cmd -cne 'rm -f /data/local/tmp/new.head /data/local/tmp/new.tail') { $script:dev.bad++ }
if ($cmd -cmatch '^sha256sum /dev/block/by-name/((boot|uboot|sml|teecfg|trustos|vbmeta)_[ab])$') { return "$(Sha256Hex (PartBytes $Matches[1])) /dev/block/by-name/$($Matches[1])`r" }
if ($cmd -ceq 'dd if=/dev/block/by-name/misc bs=1 skip=2048 count=32 2>/dev/null | od -An -tx1 -v') { return ' 5f 61 00 00 42 43 41 42 01 02 00 00 9f 00 1e 00 00 00 00 00 00 00 00 00 00 00 00 00 0b e1 71 46' }
if ($cmd -cmatch '^dd if=/dev/block/mmcblk0 bs=512 skip=(\d+) count=8 2>/dev/null \| sha256sum$') {
$b = if ($script:dev.marker.ContainsKey($Matches[1])) { $script:dev.marker[$Matches[1]] } else { New-Object byte[] 4096 }
return "$(Sha256Hex $b) -"
}
if ($cmd -ceq 'dd if=/dev/block/by-name/misc bs=2048 count=1 2>/dev/null | sha256sum') {
$b = if ($script:dev.bcb) { $script:dev.bcb } else { New-Object byte[] 2048 }
return "$(Sha256Hex $b) -"
}
if ($cmd -ceq "dd if=/data/local/tmp/mu300-new.tail of=/dev/block/mmcblk0 bs=512 seek=$seek conv=fsync 2>/dev/null") {
if (-not $script:dev.deafDisk) { $script:dev.tail = $script:dev.files['/data/local/tmp/mu300-new.tail'] }
} elseif ($cmd -ceq 'dd if=/data/local/tmp/mu300-new.head of=/dev/block/mmcblk0 bs=512 conv=fsync 2>/dev/null') {
if (-not $script:dev.deafDisk) { $script:dev.head = $script:dev.files['/data/local/tmp/mu300-new.head'] }
} elseif ($cmd -cmatch '^dd if=/data/local/tmp/mu300-marker\.bin of=/dev/block/mmcblk0 bs=512 seek=(\d+) count=8 conv=notrunc,fsync 2>/dev/null$') {
$script:dev.marker[$Matches[1]] = $script:dev.files['/data/local/tmp/mu300-marker.bin']
} elseif ($cmd -ceq 'dd if=/data/local/tmp/mu300-bcb.bin of=/dev/block/by-name/misc bs=2048 count=1 conv=notrunc,fsync 2>/dev/null') {
$script:dev.bcb = $script:dev.files['/data/local/tmp/mu300-bcb.bin']
} elseif ($cmd -cmatch '^dd if=/dev/zero of=') { $script:dev.wiped = $true }
elseif ($cmd -cne "sync; rm -f $tmpFiles" -and $cmd -cne "rm -f $tmpFiles") { $script:dev.bad++ }
return ''
}
function Die($m) { throw "DIE: $m" }
@@ -430,11 +469,16 @@ if (-not $py) {
try { OfferRepartition $script:dev.disk ($U64 + 1) 0 } catch { $script:died = "$($_.Exception.Message)" }
}
function Writes { @($script:dev.cmds | Where-Object { $_ -match ' of=' }) }
function Untouched { ((Sha256Hex $script:dev.head) -eq $script:dev.head0) -and ((Sha256Hex $script:dev.tail) -eq $script:dev.tail0) -and -not $script:dev.wiped -and -not $script:dev.rebooted -and (Writes).Count -eq 0 }
function Untouched { ((Sha256Hex $script:dev.head) -eq $script:dev.head0) -and ((Sha256Hex $script:dev.tail) -eq $script:dev.tail0) -and -not $script:dev.wiped -and -not $script:dev.rebooted -and (Writes).Count -eq 0 -and $null -eq $script:dev.bcb -and $script:dev.marker.Count -eq 0 }
function Printed([string]$Pattern) { [bool](@($script:out | Where-Object { $_ -match $Pattern }).Count) }
$tailDd = "su: dd if=/data/local/tmp/new.tail of=/dev/block/mmcblk0 bs=512 seek=$($D64 - 33) conv=fsync 2>/dev/null"
$headDd = 'su: dd if=/data/local/tmp/new.head of=/dev/block/mmcblk0 bs=512 conv=fsync 2>/dev/null'
$zeroDd = 'su: dd if=/dev/zero of=/dev/block/by-name/userdata bs=1M count=32 conv=fsync 2>/dev/null'
$tailDd = "su: dd if=/data/local/tmp/mu300-new.tail of=/dev/block/mmcblk0 bs=512 seek=$($D64 - 33) conv=fsync 2>/dev/null"
$headDd = 'su: dd if=/data/local/tmp/mu300-new.head of=/dev/block/mmcblk0 bs=512 conv=fsync 2>/dev/null'
# the region behind the new end of userdata (4 GiB less): its first 4 KiB hold the token
$rgStart = (FreeRegion ($U64 - 8388608 + 1) $D64).Start
$markerDd = "su: dd if=/data/local/tmp/mu300-marker.bin of=/dev/block/mmcblk0 bs=512 seek=$rgStart count=8 conv=notrunc,fsync 2>/dev/null"
$bcbDd = 'su: dd if=/data/local/tmp/mu300-bcb.bin of=/dev/block/by-name/misc bs=2048 count=1 conv=notrunc,fsync 2>/dev/null'
$bcbFile = Join-Path $fx 'bcb.bin'
& $py (Join-Path (Join-Path $Top 'tools') 'resume.py') bcb $bcbFile
# -Check: the figures, no question, nothing written
$Check = $true
@@ -448,7 +492,9 @@ if (-not $py) {
Check 'check: says so' ($script:out[$script:out.Count - 1]) ' -Check writes nothing. Run the installer without it to make room.'
Check 'check: no question' $script:asked.Count 0
Check 'check: device untouched' (Untouched) $true
Check 'check: reads the table only' (($script:dev.cmds -join '|')) "pull: dd if=/dev/block/mmcblk0 bs=512 count=34 2>/dev/null|pull: dd if=/dev/block/mmcblk0 bs=512 skip=$($D64 - 33) count=33 2>/dev/null"
Check 'check: reads the table and what identifies the device' (($script:dev.cmds -join '|')) "pull: dd if=/dev/block/mmcblk0 bs=512 count=34 2>/dev/null|pull: dd if=/dev/block/mmcblk0 bs=512 skip=$($D64 - 33) count=33 2>/dev/null|su: $FactsCmd"
Check 'check: the reset, it says' (Printed "Android's own recovery erases Android's data") $true
Check 'check: encrypted, it says' (Printed "^ Android's data: encrypted \(encrypted/file\)$") $true
Check 'check: nothing unexpected' $script:dev.bad 0
# the default answer is no
@@ -477,8 +523,9 @@ if (-not $py) {
Check 'shrink: what Android keeps' (Printed '^ userdata \(Android\): 48[.,]4 GiB$') $true
Check 'shrink: what Linux gets' (Printed '^ Linux region: 4[.,]0 GiB$') $true
Check 'shrink: questions' ($script:asked -join '|') ('Make room by shrinking userdata? (yes/no)|' + ('How many GiB for Linux? (the rest stays with Android)|' * 4) + "Type ERASE to rewrite the partition table and wipe Android's data|Reboot now? (yes/no)")
# the backup copy of the table first, then the primary, then the start of userdata - and nothing else is written
Check 'shrink: what is written' ((Writes) -join '|') "$tailDd|$headDd|$zeroDd"
# the backup copy of the table first, then the primary, then the token, then the request to recovery - and nothing
# else is written
Check 'shrink: what is written' ((Writes) -join '|') "$tailDd|$headDd|$markerDd|$bcbDd"
Check 'shrink: nothing unexpected' $script:dev.bad 0
Check 'shrink: the table was kept' ((Sha256Hex ([IO.File]::ReadAllBytes("$gd\gpt.head"))) + (Sha256Hex ([IO.File]::ReadAllBytes("$gd\gpt.tail")))) ($script:dev.head0 + $script:dev.tail0)
Check 'shrink: the device has the new one' ((Sha256Hex $script:dev.head) + (Sha256Hex $script:dev.tail)) ((Sha256Hex ([IO.File]::ReadAllBytes("$gd\new.head"))) + (Sha256Hex ([IO.File]::ReadAllBytes("$gd\new.tail"))))
@@ -487,29 +534,53 @@ if (-not $py) {
Check 'shrink: userdata starts where it did' $now.First $F64
Check 'shrink: userdata ends 4 GiB earlier' $now.End ($U64 - 8388608)
Check 'shrink: says where' (Printed '^ userdata now ends at sector 113766399$') $true
Check 'shrink: userdata cleared' $script:dev.wiped $true
Check 'shrink: userdata not cleared from here' $script:dev.wiped $false
Check 'shrink: the request to recovery' (Sha256Hex $script:dev.bcb) (Sha256Hex ([IO.File]::ReadAllBytes($bcbFile)))
$tx = @(Get-ChildItem -LiteralPath $BackupDir -Recurse -Filter 'transaction.json')
Check 'shrink: one transaction' $tx.Count 1
$txj = [IO.File]::ReadAllText($tx[0].FullName) | ConvertFrom-Json
Check 'shrink: the transaction' "$($txj.state) $($txj.serial) $($txj.slot) $($txj.cid) $($txj.region_start) $($txj.target)" "prepared 324950664950 a 15010053454d36344720c1a6b7d2e900 $rgStart $($U64 - 8388608 - $F64 + 1)"
$mk = Join-Path $fx 'marker.bin'
& $py (Join-Path (Join-Path $Top 'tools') 'resume.py') marker $txj.token $mk
Check 'shrink: the token' (Sha256Hex $script:dev.marker["$rgStart"]) (Sha256Hex ([IO.File]::ReadAllBytes($mk)))
$bk = Split-Path -Parent $tx[0].FullName
Check 'shrink: the backup' (@(Get-Content (Join-Path $bk 'SHA256SUMS')).Count) 15
Check 'shrink: the backup of boot_b' (Sha256Hex ([IO.File]::ReadAllBytes((Join-Path $bk 'boot_b.img')))) (Sha256Hex (PartBytes 'boot_b'))
Check 'shrink: reboots' $script:dev.rebooted $true
Check 'shrink: the last thing' ($script:dev.cmds[$script:dev.cmds.Count - 1]) 'adb: reboot'
# no partition but userdata is named, and nothing but the partition table is read
Check 'shrink: no other partition' (@($script:dev.cmds | Where-Object { $_ -match 'by-name/(?!userdata )|nvram|fixnv|runtimenv|prodnv|persist|miscdata|mmcblk0p' }).Count) 0
Check 'shrink: reads' (@($script:dev.cmds | Where-Object { $_ -like 'pull:*' } | Sort-Object -Unique).Count) 2
Check 'shrink: no other partition' (@($script:dev.cmds | Where-Object { $_ -match 'by-name/(?!(misc|userdata|boot_[ab]|uboot_[ab]|sml_[ab]|teecfg_[ab]|trustos_[ab]|vbmeta_[ab])\b)|nvram|fixnv|runtimenv|prodnv|persist|miscdata' }).Count) 0
Check 'shrink: reads' (@($script:dev.cmds | Where-Object { $_ -like 'pull:*' } | Sort-Object -Unique).Count) 15
Remove-Item -Recurse -Force $BackupDir
# "no" to the reboot
FakeDevice 'vendor64'; RunOffer @('yes', '2.5', 'ERASE', 'no')
Check 'no reboot: no error' $script:died ''
Check 'no reboot: written' ((Writes) -join '|') "$tailDd|$headDd|$zeroDd"
Check 'no reboot: written' ((Writes) -join '|') ("$tailDd|$headDd|$markerDd|$bcbDd" -replace "seek=$rgStart", "seek=$((FreeRegion ($U64 - 5242880 + 1) $D64).Start)")
Check 'no reboot: stays up' $script:dev.rebooted $false
# a push that stops halfway: what is on the device is not what was made, and nothing is written
FakeDevice 'vendor64'; $script:dev.shortPush = $true; RunOffer @('yes', '4', 'ERASE')
Check 'short push: refused' $script:died 'DIE: the new partition table did not arrive on the device as it was made; nothing is changed'
Check 'short push: device untouched' (Untouched) $true
Check 'short push: cleaned up' ($script:dev.cmds[$script:dev.cmds.Count - 1]) 'su: rm -f /data/local/tmp/new.head /data/local/tmp/new.tail'
Check 'short push: cleaned up' ($script:dev.cmds[$script:dev.cmds.Count - 1]) "su: rm -f $tmpFiles"
# a device whose table does not change: said, and userdata is not cleared
FakeDevice 'vendor64'; $script:dev.deafDisk = $true; RunOffer @('yes', '4', 'ERASE')
Check 'did not take: said' $script:died 'DIE: the table did not take (userdata still ends at 122155007). Nothing else was changed.'
Check 'did not take: userdata not cleared' ($script:dev.wiped -or $script:dev.rebooted) $false
Check 'did not take: no reset asked for' ($script:dev.wiped -or $script:dev.rebooted -or $null -ne $script:dev.bcb -or $script:dev.marker.Count -gt 0) $false
# an encryption state that cannot be told: kano's rule, nothing is changed
FakeDevice 'vendor64'; $script:dev.facts = $script:dev.facts -replace 'STATE=encrypted', 'STATE=' -replace 'TYPE=file', 'TYPE=' -replace 'SOURCE=/dev/block/dm-6', 'SOURCE=/dev/block/mmcblk0p18' -replace 'MAGIC=', 'MAGIC=1020f5f2'
RunOffer @('yes', '4', 'ERASE')
Check 'unknown crypto: refused' $script:died "DIE: Android's encryption state is unknown (?/?); nothing is changed."
Check 'unknown crypto: no question' $script:asked.Count 0
Check 'unknown crypto: device untouched' (Untouched) $true
# the table and the running kernel disagree: reboot first
FakeDevice 'vendor64'; $script:dev.facts = $script:dev.facts -replace "SIZE=\d+", 'SIZE=4096'
RunOffer @('yes', '4', 'ERASE')
Check 'kernel disagrees: refused' $script:died 'DIE: the partition table and the running kernel disagree about userdata; reboot Android and try again'
Check 'kernel disagrees: device untouched' (Untouched) $true
# a partition behind userdata: not a table to make room in. The tool's reason and the figures, no question
FakeDevice 'nvlast64'; RunOffer @('yes', '4', 'ERASE')
+8 -1
View File
@@ -1226,7 +1226,14 @@ class Window(unittest.TestCase):
self.assertIn('holds a MU300 Linux installation', page)
ctl.facts = facts(region__size='0', makeroom__first='12275712', makeroom__end='122155007', makeroom__usable_end='122155007',
makeroom__min_android='8388608', makeroom__min_linux='1638400', makeroom__max_linux='101490688')
self.assertIn('Make room now', show('install', 1))
page = show('install', 1)
self.assertIn('Make room now', page)
self.assertIn("restarts into Android's own recovery", page) # the reset, and how it goes on (tools/resume.sh)
# a prepared installation waiting (tools/resume.sh): what its checks said
ctl.facts = facts(resume__transaction='/home/u/mu300-backups/x/transaction.json', resume__check='RESUME-OK', verdict__code='resume')
self.assertIn('A prepared installation waits for this device (EXPERIMENTAL', show('install', 1))
ctl.facts = facts(resume__transaction='/home/u/mu300-backups/x/transaction.json', resume__check='RESUME-REFUSED: preparation token mismatch')
self.assertIn('it cannot be continued: preparation token mismatch', show('install', 1))
# a check that fitted the choices to the device: the widgets follow (a card that holds an installation)
ctl.choices.storage = 'sd'
a.on_change({'check'})
+472
View File
@@ -0,0 +1,472 @@
"""Making room on an encrypted Android by a reset, and the installation that resumes afterwards (EXPERIMENTAL;
tools/resume.py, tools/resume.sh, install.ps1's make-room path; docs/FINDINGS.md 112). Ported from kano's desktop
installer: the transaction and its checks first (the device, its slot, the partition geometry, the token, the
installer's tools), then install.sh as a whole against tests/fakeadb.py with real storage (tests/fakeemmc.py): the
backup, the partition table, the token and the request to recovery as they land on the fake eMMC; the reset; the
resumed run and every way it refuses. Nothing here runs on, or reaches, a real device."""
import hashlib
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
import unittest
from pathlib import Path
import fakeemmc
import fakegpt
from helpers import TOP, ShellTest
from test_answers import Device, events
sys.path.insert(0, str(TOP / 'tools'))
import resume # noqa: E402
TOK = 'b' * 32
def record(**kw):
r = {'format': 1, 'state': 'prepared', 'serial': 'SERIAL', 'slot': 'a', 'cid': 'c' * 32, 'node': 'mmcblk0p18',
'start': 2000000, 'size': 120155008, 'disk': 122159104, 'target': 100000000, 'need': 20152320,
'usable_end': 122155007, 'region_start': 102002688, 'region_end': 122155008, 'token': TOK, 'identity': 'i' * 64}
r.update(kw)
return r
class Transaction(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp(prefix='mu300-resume-'))
self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True)
(self.tmp / 'marker').write_bytes(resume.marker(TOK))
(self.tmp / 'bcb').write_bytes(bytes(2048))
def facts(self, **kw):
r = record()
f = {'serial': 'SERIAL', 'slot': 'a', 'cid': 'c' * 32, 'node': 'mmcblk0p18', 'start': 2000000, 'size': r['target'],
'disk': r['disk'], 'gpt_first': 2000000, 'gpt_end': 2000000 + r['target'] - 1, 'usable_end': r['usable_end'],
'region_start': r['region_start'], 'region_end': r['region_end'], 'marker': str(self.tmp / 'marker'),
'bcb': str(self.tmp / 'bcb'), 'identity': 'i' * 64}
f.update(kw)
return f
def test_the_prepared_device_passes(self):
resume.check(record(), self.facts())
# once installed, the token is not needed any more (kano: root_verified)
(self.tmp / 'marker').write_bytes(bytes(4096))
resume.check(record(state='installed'), self.facts())
def test_wrong_device_slot_geometry_marker_or_tools_never_pass(self):
# kano's test_resume_wrong_device_geometry_or_marker_never_pass, with this project's own checks beside it
bad = {'serial': dict(serial='OTHER'), 'slot': dict(slot='b'), 'cid': dict(cid='d' * 32),
'node': dict(node='mmcblk0p17'), 'start': dict(start=2000001), 'disk': dict(disk=61079552),
'size': dict(size=100000000 - 4096), 'gpt_first': dict(gpt_first=2000001),
'gpt_end': dict(gpt_end=2000000 + 100000000), 'usable_end': dict(usable_end=122155006),
'region_start': dict(region_start=102002688 + 4096), 'region_end': dict(region_end=122155008 - 4096),
'identity': dict(identity='j' * 64)}
for why, kw in bad.items():
with self.assertRaises(ValueError, msg=why):
resume.check(record(), self.facts(**kw))
(self.tmp / 'marker').write_bytes(resume.marker('c' * 32))
with self.assertRaisesRegex(ValueError, 'token mismatch'):
resume.check(record(), self.facts())
(self.tmp / 'marker').write_bytes(b'')
with self.assertRaisesRegex(ValueError, 'token mismatch'):
resume.check(record(), self.facts())
def test_a_reset_that_has_not_run(self):
(self.tmp / 'bcb').write_bytes(resume.bcb())
with self.assertRaisesRegex(ValueError, 'has not reset the device yet'):
resume.check(record(), self.facts())
def test_a_preparation_that_did_not_finish_is_not_resumed(self):
with self.assertRaisesRegex(ValueError, 'did not finish'):
resume.check(record(state='prepared-request'), self.facts())
with self.assertRaises(ValueError):
resume.check(record(state='cancelled'), self.facts())
def test_a_record_that_does_not_add_up(self):
with self.assertRaisesRegex(ValueError, 'does not add up'):
resume.check(record(need=4096), self.facts())
def test_the_bootloader_message(self):
b = resume.bcb()
self.assertEqual(len(b), 2048)
self.assertEqual(b[:14], b'boot-recovery\0')
n = len(b'recovery\n--wipe_data\n--reason=mu300-make-room\n')
self.assertEqual(b[64:64 + n], b'recovery\n--wipe_data\n--reason=mu300-make-room\n')
self.assertEqual(b[14:64], bytes(50))
self.assertEqual(b[64 + n:], bytes(2048 - 64 - n))
self.assertTrue(resume.bcb_pending(b))
self.assertFalse(resume.bcb_pending(bytes(2048)))
self.assertFalse(resume.bcb_pending(b'boot-recovery\0'.ljust(2048, b'\0'))) # somebody else's request
def test_the_marker(self):
m = resume.marker(TOK)
self.assertEqual(len(m), 4096)
self.assertTrue(m.startswith(b'MU300-PREPARED-V1 ' + TOK.encode() + b'\n'))
for bad in ('x' * 32, 'b' * 31, 'B' * 32, ''):
with self.assertRaises(ValueError):
resume.marker(bad)
self.assertEqual(len(resume.token()), 32)
self.assertNotEqual(resume.token(), resume.token())
def test_encryption_kanos_rule(self):
# kano's test_fbe_with_plain_superblock_still_requires_format
self.assertTrue(resume.encrypted('encrypted', 'file', '/dev/block/mmcblk0p40', '1020f5f2'))
self.assertTrue(resume.encrypted('unencrypted', '', '/dev/block/dm-0', '53ef'))
self.assertFalse(resume.encrypted('unencrypted', '', '/dev/block/mmcblk0p40', '53ef'))
with self.assertRaises(ValueError):
resume.encrypted('', '', '/dev/block/mmcblk0p40', '1020f5f2')
out = subprocess.run([sys.executable, str(TOP / 'tools/resume.py'), 'encrypted', 'state=', 'type=', 'source=/dev/block/mmcblk0p40', 'magic='],
capture_output=True, text=True).stdout
self.assertEqual(out, 'unknown\n')
def test_the_identity_follows_the_tools_and_the_package_only(self):
top = self.tmp / 'top'
for name in resume.TOOLS + ('install.sh', 'README.md'):
(top / name).parent.mkdir(parents=True, exist_ok=True)
(top / name).write_text(name)
before = resume.identity(top)
(top / 'install.sh').write_text('a repaired prompt')
(top / 'README.md').write_text('another text')
self.assertEqual(resume.identity(top), before) # kano: prompts and texts may change
for name in resume.TOOLS:
saved = (top / name).read_text()
(top / name).write_text(saved + 'changed')
self.assertNotEqual(resume.identity(top), before, name)
(top / name).write_text(saved)
m = self.tmp / 'manifest'
m.write_text('KERNEL_ASSET=k.tar.gz\nSHA256_KERNEL=%s\nROOTFS_ASSET=r.tar.gz\nSHA256_ROOTFS=%s\n' % ('1' * 64, '2' * 64))
with_package = resume.identity(top, m)
self.assertNotEqual(with_package, before)
m.write_text(m.read_text().replace('2' * 64, '3' * 64))
self.assertNotEqual(resume.identity(top, m), with_package)
def test_saved_atomically_and_found_for_its_device(self):
d = self.tmp / 'backups'
for name, kw, age in (('old', {}, 300), ('new', {}, 100), ('other', dict(cid='d' * 32), 0),
('done', dict(state='installed'), 0), ('broken', None, 0)):
(d / name).mkdir(parents=True)
p = d / name / 'transaction.json'
if kw is None:
p.write_text('{not json')
else:
resume.save(p, record(**kw))
t = time.time() - age
os.utime(p, (t, t))
self.assertEqual(resume.find(d, 'SERIAL', 'c' * 32), d / 'new' / 'transaction.json')
self.assertEqual(resume.find(d, 'SERIAL', 'd' * 32), d / 'other' / 'transaction.json')
self.assertIsNone(resume.find(d, 'OTHER', 'c' * 32))
self.assertEqual(resume.find(d), d / 'other' / 'transaction.json') # any device: the newest
self.assertFalse(list(d.rglob('*.tmp')))
with self.assertRaises(ValueError):
resume.new(self.tmp / 'x.json', {'serial': 'S'}) # never half a transaction
def tables_equal_but_userdata(before, after):
"""[(name, first, last)] of two tables: the same partitions at the same places, userdata's end aside"""
return [p for p in before if p[0] != 'userdata'] == [p for p in after if p[0] != 'userdata']
MAKE_ROOM = dict(MU300_ANS_MAKE_ROOM='yes', MU300_ANS_LINUX_GIB='4', MU300_ANS_ERASE_ANDROID='ERASE', MU300_ANS_REBOOT='yes')
INSTALL = dict(MU300_ANS_SYSTEMS='2', MU300_OPENWRT='plain', MU300_ANS_DEFAULT_LINUX='yes', MU300_ANS_BOOT_ATTEMPTS='5',
MU300_ANS_HOTSPOT='yes', MU300_ANS_GPU='no', MU300_ANS_VPN='no', MU300_ANS_ADB='no', MU300_ANS_KERNEL='6.18',
MU300_ANS_PASSWORD='hunter2secret', MU300_ANS_CONFIRM='INSTALL')
class ResetAndResume(Device):
"""install.sh's make-room path on the fake eMMC (tests/fakeemmc.py), the reset, and the run that resumes."""
def setUp(self):
super().setUp()
self.emmc = fakeemmc.make(self.tmp / 'emmc')
self.backups = self.tmp / 'home' / 'mu300-backups'
def device(self, **keys):
keys.setdefault('layout', 'vendor64')
keys.setdefault('emmc', str(self.emmc))
super().device(**keys)
def inst(self, shell, answers, *args, **env):
f = self.tmp / 'answers.txt'
f.write_text(''.join(f'{k}={v}\n' for k, v in answers.items()))
f.chmod(0o600)
r = self.run_script(shell, 'install.sh', '--answers', str(f), *args, MU300_PROGRESS='1', **env)
ev = events(r.stdout)
return r, ev, {e['key']: e['value'] for e in ev if e['event'] == 'info'}
def writes(self):
return [c['cmd'] for c in self.calls('write')]
def prepare(self, shell):
self.device(pull=True)
before = fakeemmc.table(self.emmc)
misc_before = fakeemmc.bcb(self.emmc)
r, ev, facts = self.inst(shell, MAKE_ROOM)
self.assertEqual(r.returncode, 0, r.stdout[-3000:] + r.stderr)
return r, ev, facts, before, misc_before
def test_prepare_writes_the_table_the_token_and_the_request_and_saves_the_transaction(self):
for shell in self.each_shell():
shutil.rmtree(self.emmc); self.emmc = fakeemmc.make(self.tmp / 'emmc')
shutil.rmtree(self.backups, ignore_errors=True)
r, ev, facts, before, misc_before = self.prepare(shell)
self.assertEqual(ev[-1]['event'], 'done')
self.assertEqual((ev[-1]['repartitioned'], ev[-1]['resume']), ('yes', 'pending'))
self.assertEqual(facts['makeroom.crypto'], 'yes')
tx = Path(ev[-1]['transaction'])
self.assertTrue(tx.is_file() and tx.parent.parent == self.backups, tx)
rec = json.loads(tx.read_text())
self.assertEqual(rec['state'], 'prepared')
self.assertEqual((rec['serial'], rec['slot'], rec['cid']), ('324950664950', 'a', fakeemmc.CID))
after = fakeemmc.table(self.emmc)
ud_before = [p for p in before if p[0] == 'userdata'][0]
ud_after = [p for p in after if p[0] == 'userdata'][0]
# only userdata's end moved, by the size asked for; every other partition is where it was
self.assertTrue(tables_equal_but_userdata(before, after))
self.assertEqual(ud_after[1], ud_before[1])
self.assertEqual(ud_before[2] - ud_after[2], 4 << 21)
self.assertEqual(rec['target'], ud_after[2] - ud_after[1] + 1)
# the region by the installers' arithmetic, and the token at its start
start = ((ud_after[2] + 1) // 4096 + 1) * 4096
self.assertEqual(rec['region_start'], start)
self.assertEqual(fakeemmc.read(self.emmc, start, 8), resume.marker(rec['token']))
# the request to recovery, and the A/B block behind it as it was
misc = (self.emmc / 'dev/block/by-name/misc').read_bytes()
self.assertEqual(misc[:2048], resume.bcb())
self.assertEqual(misc[2048:2080], fakeemmc._misc()[2048:2080])
# writes: the backup table first, then the primary, the token, the request - nothing else
w = self.writes()
targets = [('mmcblk0 tail' if 'seek=%d' % (fakegpt.DISK64 - 33) in c else
'mmcblk0 head' if 'of=/dev/block/mmcblk0 bs=512 conv' in c else
'token' if 'mu300-marker.bin' in c else 'misc' if 'of=/dev/block/by-name/misc' in c else c) for c in w
if 'of=/dev/block/' in c]
self.assertEqual(targets, ['mmcblk0 tail', 'mmcblk0 head', 'token', 'misc'], w)
self.assertEqual(self.calls('reboot')[0]['argv'], ['reboot'])
# the backup on this computer: the table, misc, boot and the boot chain of both slots, all checked
bd = Path(rec['backup'])
names = sorted(l.split(' ')[1] for l in (bd / 'SHA256SUMS').read_text().splitlines())
want = ['gpt.head', 'gpt.tail', 'misc-head.bin'] + sorted(f'{p}_{s}.img' for p in ('boot',) + fakeemmc.CHAIN for s in 'ab')
self.assertEqual(names, sorted(want))
for line in (bd / 'SHA256SUMS').read_text().splitlines():
h, n = line.split(' ')
self.assertEqual(hashlib.sha256((bd / n).read_bytes()).hexdigest(), h)
self.assertEqual((bd / 'boot_b.img').read_bytes(), (self.emmc / 'dev/block/by-name/boot_b').read_bytes())
# never an NV or calibration partition, not even read
for c in self.calls():
self.assertNotRegex(c['cmd'], r'by-name/(prodnv|miscdata|persist|ztecfg|ztepersist|calinv|isedata|\w*nv\w*)', c['cmd'])
def test_resumed_after_the_reset_and_refused_before_it(self):
for shell in self.each_shell():
shutil.rmtree(self.emmc); self.emmc = fakeemmc.make(self.tmp / 'emmc')
shutil.rmtree(self.backups, ignore_errors=True)
r, ev, facts, *_ = self.prepare(shell)
tx = ev[-1]['transaction']
rec = json.loads(Path(tx).read_text())
# before the reset: the kernel still has the old table and misc still asks recovery for the reset
self.device(pull='noboot')
r, ev, facts = self.inst(shell, INSTALL)
self.assertEqual(r.returncode, 1)
self.assertIn('has not reset the device yet', ev[-1]['message'])
self.assertEqual(self.writes(), [])
# the reset: the kernel reads the table again, recovery formats userdata and clears the request
fakeemmc.reset(self.emmc)
self.device(pull='noboot')
r, ev, facts = self.inst(shell, INSTALL)
self.assertEqual(facts['resume.transaction'], tx, r.stdout[-3000:])
self.assertEqual(facts['resume.check'], 'RESUME-OK')
self.assertEqual(facts['verdict.code'], 'resume')
self.assertEqual(facts['storage'], 'internal')
self.assertEqual(int(facts['region.offset']), rec['region_start'] * 512)
asked = [e['id'] for e in ev if e['event'] == 'question']
self.assertNotIn('MU300_ANS_OVERWRITE', asked) # the region's old contents were erased by consent
self.assertNotIn('MU300_ANS_MAKE_ROOM', asked)
self.assertIn('MU300_ANS_SYSTEMS', asked)
self.assertIn('could not read /dev/block/by-name/boot_a', ev[-1]['message']) # (pulls refused: it ends here)
self.assertEqual(self.writes(), [])
# --check says the same, and writes nothing
r, ev, facts = self.inst(shell, {}, '--check')
self.assertEqual((facts['resume.check'], facts['verdict.code']), ('RESUME-OK', 'resume'))
self.assertEqual(self.writes(), [])
# --no-resume: as if nothing had been prepared - the region's contents are data to be asked about
r, ev, facts = self.inst(shell, INSTALL, '--no-resume')
self.assertNotIn('resume.transaction', facts)
self.assertIn('set MU300_ANS_OVERWRITE', ev[-1]['message'])
# what no longer matches stops it, before anything is written
for why, change, word in (
('another slot', lambda: self.device(pull='noboot', slot='b'), 'slot'),
('a token overwritten', lambda: self.overwrite(rec['region_start']), 'token mismatch'),
('the transaction edited', lambda: self.edit(tx, target=rec['target'] - 4096), 'geometry differs'),
('other tools', lambda: self.edit(tx, identity='0' * 64), 'tools or the package differ')):
self.device(pull='noboot')
change()
r, ev, facts = self.inst(shell, INSTALL)
self.assertEqual(r.returncode, 1, why)
self.assertIn(word, ev[-1]['message'], why)
self.assertIn('Nothing was written', ev[-1]['message'], why)
self.assertEqual(self.writes(), [], why)
self.restore(tx, rec)
# --resume with nothing saved for this device
shutil.rmtree(self.backups)
self.device(pull='noboot')
r, ev, facts = self.inst(shell, INSTALL, '--resume')
self.assertIn('no saved transaction for this device', ev[-1]['message'])
def overwrite(self, sector):
with open(self.emmc / 'dev/block/mmcblk0', 'r+b') as f:
f.seek(sector * 512)
f.write(b'somebody else was here')
def edit(self, tx, **kw):
r = json.loads(Path(tx).read_text())
r.update(kw)
Path(tx).write_text(json.dumps(r))
def restore(self, tx, rec):
Path(tx).write_text(json.dumps(rec))
with open(self.emmc / 'dev/block/mmcblk0', 'r+b') as f:
f.seek(rec['region_start'] * 512)
f.write(resume.marker(rec['token']))
def test_an_encryption_state_that_cannot_be_told_changes_nothing(self):
for shell in self.each_shell():
shutil.rmtree(self.emmc); self.emmc = fakeemmc.make(self.tmp / 'emmc', crypto=('', ''), source='/dev/block/mmcblk0p18')
self.device(pull=True)
r, ev, facts = self.inst(shell, MAKE_ROOM)
self.assertEqual(r.returncode, 1)
self.assertIn("encryption state is unknown", ev[-1]['message'])
self.assertEqual(self.writes(), [])
self.assertFalse(self.backups.exists())
def test_kanos_rule_on_the_device(self):
# what the device says decides (resume_facts): FBE is encrypted whatever its superblock; a plain F2FS with
# "unencrypted" is not; --check reads it and writes nothing
for crypto, source, want in ((('encrypted', 'file'), '/dev/block/dm-6', 'yes'),
(('unencrypted', ''), '/dev/block/mmcblk0p18', 'no'),
(('unencrypted', ''), '/dev/block/dm-2', 'yes')):
shutil.rmtree(self.emmc); self.emmc = fakeemmc.make(self.tmp / 'emmc', crypto=crypto, source=source)
for shell in self.each_shell():
self.device(pull=True)
r, ev, facts = self.inst(shell, {}, '--check')
self.assertEqual(facts.get('makeroom.crypto'), want, (crypto, source, r.stdout[-2000:]))
self.assertEqual(self.writes(), [])
def test_nothing_is_written_without_every_word(self):
for shell in self.each_shell():
self.device(pull=True)
for answers, word in ((dict(MAKE_ROOM, MU300_ANS_ERASE_ANDROID='erase'), 'nothing was changed.'),
(dict(MAKE_ROOM, MU300_ANS_MAKE_ROOM='no'), 'nothing was changed.')):
r, ev, facts = self.inst(shell, answers)
self.assertEqual(ev[-1], {'event': 'error', 'message': word})
self.assertEqual(self.writes(), [])
self.assertFalse(self.backups.exists())
def test_the_self_update_waits_while_a_transaction_does(self):
self.backups.mkdir(parents=True)
for shell in self.each_shell():
code = (f'TOP="{TOP}"; HOME="{self.tmp}/home"; . "$TOP/tools/resume.sh"; '
'resume_pending && echo PENDING || echo NONE')
self.assertIn('NONE', self.sh(shell, code).stdout)
(self.backups / 'x').mkdir(exist_ok=True)
resume.save(self.backups / 'x' / 'transaction.json', record())
self.assertIn('PENDING', self.sh(shell, code).stdout)
self.assertIn('NONE', self.sh(shell, code, MU300_RESUME='0').stdout)
shutil.rmtree(self.backups / 'x')
src = (TOP / 'install.sh').read_text()
self.assertLess(src.index('if resume_pending; then'), src.index('self_update "$0" "$@"'))
class FromAnUnpackedZip(ResetAndResume):
"""The two together (tools/package.sh, §111): room made from an unpacked Magisk zip's own installer, and the
installation resumed by it after the reset. The transaction is bound to that zip's payload (kano's payload
identity): the same zip continues it, another zip or a copy of the project does not."""
@classmethod
def setUpClass(cls):
from test_magisk_zip import fake_release
cls.zips = Path(tempfile.mkdtemp(prefix='mu300-resume-zips-'))
fake_release(cls.zips / 'v2026.10.06')
r = subprocess.run(['sh', str(TOP / 'tools/make-magisk-zips.sh'), str(cls.zips / 'v2026.10.06'), str(cls.zips / 'out')],
capture_output=True, text=True)
assert r.returncode == 0, r.stderr
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.zips, ignore_errors=True)
def unpack(self, name):
import zipfile
d = self.tmp / 'unpacked' / name
shutil.rmtree(d, ignore_errors=True)
with zipfile.ZipFile(self.zips / 'out' / f'mu300-magisk-v2026.10.06-{name}.zip') as z:
z.extractall(d)
return d
def pkg(self, shell, pkg, answers, *args):
f = self.tmp / 'answers.txt'
f.write_text(''.join(f'{k}={v}\n' for k, v in answers.items()))
f.chmod(0o600)
r = self.run_script(shell, str(pkg / 'computer/install.sh'), '--answers', str(f), *args, MU300_PROGRESS='1', MU300_RELEASE='')
ev = events(r.stdout)
return r, ev, {e['key']: e['value'] for e in ev if e['event'] == 'info'}
def test_prepared_and_resumed_by_the_same_zip(self):
zip_a = self.unpack('openwrt-k6.18')
zip_b = self.unpack('ubuntu-24.04-k7.2')
answers = {k: v for k, v in INSTALL.items() if k not in ('MU300_ANS_SYSTEMS', 'MU300_OPENWRT', 'MU300_ANS_KERNEL')}
for shell in self.each_shell():
shutil.rmtree(self.emmc); self.emmc = fakeemmc.make(self.tmp / 'emmc')
shutil.rmtree(self.backups, ignore_errors=True)
self.device(pull=True)
r, ev, facts = self.pkg(shell, zip_a, MAKE_ROOM)
self.assertEqual(r.returncode, 0, r.stdout[-3000:] + r.stderr)
self.assertEqual(facts['package.system'], 'openwrt')
tx = ev[-1]['transaction']
fakeemmc.reset(self.emmc)
# another zip, or a copy of the project: not the payload the transaction was made with
for run in (lambda: self.pkg(shell, zip_b, answers), lambda: self.inst(shell, INSTALL)):
self.device(pull='noboot')
r, ev, facts = run()
self.assertEqual(r.returncode, 1)
self.assertIn('tools or the package differ', ev[-1]['message'])
self.assertEqual(self.writes(), [])
# the same zip: found, checked, continued into the prepared region, as a package (no system question)
self.device(pull='noboot')
r, ev, facts = self.pkg(shell, zip_a, answers)
self.assertEqual((facts['resume.transaction'], facts['resume.check'], facts['verdict.code']), (tx, 'RESUME-OK', 'resume'),
r.stdout[-3000:])
self.assertEqual(facts['package.system'], 'openwrt')
asked = [e['id'] for e in ev if e['event'] == 'question']
for q in ('MU300_ANS_SYSTEMS', 'MU300_ANS_KERNEL', 'MU300_ANS_OVERWRITE', 'MU300_STORAGE'):
self.assertNotIn(q, asked)
self.assertIn('could not read /dev/block/by-name/boot_a', ev[-1]['message'])
self.assertEqual(self.writes(), [])
# (the tests of ResetAndResume run there, not again here)
for _n in [n for n in dir(ResetAndResume) if n.startswith('test_')]:
locals()[_n] = None
del _n
class Static(unittest.TestCase):
def test_marked_installed_only_after_the_boot_image_and_misc(self):
src = (TOP / 'install.sh').read_text()
self.assertLess(src.index('write_linux_boot "$WORK/boot-linux-slot$LINUX_SLOT.img"\n'),
src.index('resume_py set "$RESUME_FILE" state=installed'))
def test_the_old_clear_of_userdata_is_gone(self):
# a filesystem cleared from outside is one an encrypted Android cannot mount: recovery formats it now
for name in ('install.sh', 'install.ps1', 'tools/resume.sh'):
self.assertNotIn('of=/dev/block/by-name/userdata', (TOP / name).read_text(), name)
def test_experimental_and_credited(self):
for name in ('tools/resume.sh', 'tools/resume.py'):
text = (TOP / name).read_text()
self.assertIn('EXPERIMENTAL', text)
self.assertIn('f6b0668d', text)
self.assertIn('kano', text)
if __name__ == '__main__':
unittest.main()
+1 -1
View File
@@ -16,7 +16,7 @@ from pathlib import Path
TOP = Path(__file__).resolve().parent.parent
SOURCES = ['install.sh', 'install.ps1', 'tools/linux-mode.sh', 'tools/self-update.sh', 'tools/storage.sh',
'tools/releases.sh', 'tools/package.sh', 'tools/answers.sh', 'tools/answers.ps1', 'tools/gui-launch.sh', 'tools/gui-launch.ps1',
'tools/releases.sh', 'tools/package.sh', 'tools/resume.sh', 'tools/answers.sh', 'tools/answers.ps1', 'tools/gui-launch.sh', 'tools/gui-launch.ps1',
'android/magisk/installer/mu300-install.sh']
# single- or double-quoted first argument; the PowerShell side writes '' for a quote inside '...'
PATTERNS = [re.compile(r"""\b[tT] '((?:[^']|'')*)'"""), re.compile(r'''\b[tT] "([^"$`]*)"''')]
+262
View File
@@ -0,0 +1,262 @@
#!/usr/bin/env python3
"""Making room on an encrypted Android by a reset, and the installation that resumes afterwards (EXPERIMENTAL; the
installers' make-room path, docs/FINDINGS.md 112). Ported from kano's desktop installer (kanoqwq/mu300-linux, branch
clean-tf-7.2, desktop/installer.py and desktop/boot/part-prepare.sh, f6b0668d and 0e19fe32): a transaction saved on
the computer before anything is written, Android's own recovery formatting the smaller userdata, and a second run that
continues only when the device, its slot, its partition geometry, a token written to the device and the installer's
tools are still the ones the transaction was made with.
install.sh and install.ps1 call this file; the graphical installer and tests/ import it.
resume.py token a new token (32 hex digits)
resume.py marker TOKEN OUT the 4096-byte block written at the start of the prepared region
resume.py bcb OUT the 2048-byte bootloader message that has recovery wipe userdata
resume.py encrypted state=S type=T source=DEV magic=HEX yes / no / unknown: is Android's data encrypted
resume.py identity TOP [MANIFEST] the payload identity of this installer (and of a package's manifest)
resume.py new FILE KEY=VALUE... a new transaction (state prepared-request), written atomically
resume.py set FILE KEY=VALUE... change fields of a transaction (state=prepared, state=installed)
resume.py get FILE KEY... KEY=VALUE lines, for a shell
resume.py find DIR [SERIAL CID] the newest transaction in DIR/*/transaction.json still waiting for
this device (any device without SERIAL and CID); nothing when none
resume.py check FILE KEY=VALUE... RESUME-OK, or RESUME-REFUSED: <why> and status 1
The facts `check` takes, as the installers read them from the device: serial, slot (the slot Android runs from),
cid, node, start, size, disk (userdata's node, first sector and sectors, and the eMMC's sectors, from sysfs),
gpt_first, gpt_end, usable_end (resize-last-partition.py --show of the table read back: both copies and every CRC
valid), region_start, region_end (the free region by the installers' own arithmetic), marker (a file: the first
4096 bytes of that region), bcb (a file: the first 2048 bytes of misc), identity (resume.py identity of the installer
that runs now).
"""
import hashlib
import json
import os
import secrets
import sys
import time
from pathlib import Path
FORMAT = 1
MARKER = b'MU300-PREPARED-V1 '
BCB_COMMAND = b'boot-recovery'
BCB_RECOVERY = b'recovery\n--wipe_data\n--reason=mu300-make-room\n'
# the files of this project that decide what a resumed installation writes where: the partition table's reader, the
# region's arithmetic, what formats and fills the region on the device, and what boots it. kano binds his
# transaction to his boot image, rootfs and filesystem tools in the same way (resume_payload_id): a repaired prompt
# may change, these may not.
TOOLS = ('tools/resize-last-partition.py', 'tools/storage.sh', 'tools/android-install.sh',
'tools/android-mount-mu300root.sh', 'boot/init')
INTS = ('start', 'size', 'disk', 'target', 'need', 'gpt_first', 'gpt_end', 'usable_end', 'region_start', 'region_end')
WAITING = ('prepared-request', 'prepared')
def sha256_file(path):
h = hashlib.sha256()
with open(path, 'rb') as f:
for block in iter(lambda: f.read(1 << 20), b''):
h.update(block)
return h.hexdigest()
def token():
return secrets.token_hex(16)
def marker(tok):
"""The block at the start of the prepared region: outside every partition, so the reset that formats userdata
leaves it, and the resumed run finds it there."""
if len(tok) != 32 or any(c not in '0123456789abcdef' for c in tok):
raise ValueError('not a token')
return (MARKER + tok.encode() + b'\n').ljust(4096, b'\0')
def bcb():
"""AOSP's bootloader_message, as kano's part_prepare writes it and as he says the vendor flashing tool's
erase-userdata does: 2048 bytes, "boot-recovery" at 0 and the recovery's arguments at 64, the rest zero. It is
the first 2 KiB of misc; the A/B boot control block at 2048 is not part of it."""
out = bytearray(2048)
out[:len(BCB_COMMAND)] = BCB_COMMAND
out[64:64 + len(BCB_RECOVERY)] = BCB_RECOVERY
return bytes(out)
def bcb_pending(data):
"""Whether misc still asks recovery for this project's reset: it has not run yet."""
return data[:len(BCB_COMMAND) + 1] == BCB_COMMAND + b'\0' and BCB_RECOVERY in data[64:64 + 768]
def encrypted(state, type_, source, magic):
"""kano's rule (installer.py, encrypted): FBE can have a perfectly readable filesystem superblock, so a signature
alone never says "not encrypted". True for an encrypted state or type, or /data on a device-mapper node; False only
for "unencrypted" with a plain F2FS or ext4 superblock on userdata; anything else is unknown (ValueError)."""
if state == 'encrypted' or type_ in ('file', 'block') or '/dm-' in source or '/mapper/' in source:
return True
if state == 'unencrypted' and magic in ('1020f5f2', '53ef'):
return False
raise ValueError("Android's encryption state is unknown")
def identity(top, manifest=None):
"""The payload identity: the checksums of TOOLS, and of a package's two payload files when it has a manifest
(tools/package.sh). Canonical JSON, hashed, as kano's resume_payload_id."""
top = Path(top)
files = {}
for name in TOOLS:
p = top / name
files[name] = sha256_file(p) if p.is_file() else 'missing'
package = {}
if manifest:
m = {}
for line in Path(manifest).read_text(encoding='utf-8', errors='replace').splitlines():
k, sep, v = line.partition('=')
if sep:
m[k] = v.strip()
package = {m.get('KERNEL_ASSET', ''): m.get('SHA256_KERNEL', ''), m.get('ROOTFS_ASSET', ''): m.get('SHA256_ROOTFS', '')}
canonical = {'format': FORMAT, 'layout': 'mu300-free-region', 'files': files, 'package': package}
return hashlib.sha256(json.dumps(canonical, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
def load(path):
with open(path, encoding='utf-8') as f:
r = json.load(f)
if not isinstance(r, dict) or r.get('format') != FORMAT:
raise ValueError('not a transaction of this installer')
return r
def save(path, record):
"""Atomically: a transaction is never half written (kano: transaction())."""
path = Path(path)
tmp = path.with_name(path.name + '.tmp')
tmp.write_text(json.dumps(record, indent=2, sort_keys=True) + '\n', encoding='utf-8')
os.replace(tmp, path)
def typed(pairs):
out = {}
for kv in pairs:
k, sep, v = kv.partition('=')
if not sep or not k:
raise ValueError('not KEY=VALUE: ' + kv)
out[k] = (int(v) if v.strip() else -1) if k in INTS else v
return out
def new(path, fields):
r = {'format': FORMAT, 'state': 'prepared-request', 'created': time.strftime('%Y-%m-%dT%H:%M:%S')}
r.update(fields)
for k in ('serial', 'slot', 'cid', 'node', 'start', 'size', 'disk', 'target', 'need', 'usable_end', 'region_start',
'region_end', 'token', 'identity'):
if k not in r or r[k] in ('', None):
raise ValueError('a transaction needs ' + k)
marker(r['token'])
save(path, r)
return r
def find(directory, serial='', cid=''):
"""The newest transaction still waiting, for this device when SERIAL and CID are given."""
best = None
for p in Path(directory).glob('*/transaction.json'):
try:
r = load(p)
except (OSError, ValueError):
continue
if r.get('state') not in WAITING:
continue
if serial and (r.get('serial') != serial or r.get('cid') != cid):
continue
key = (p.stat().st_mtime, str(p))
if best is None or key > best[0]:
best = (key, p)
return best[1] if best else None
def check(r, facts):
"""Raise ValueError with the reason when this device is not the one, or not in the state, the transaction
prepared (kano's validate_resume and validate_resume_package, and this project's own: the table read back with
both copies and every CRC valid, the region by the installers' arithmetic, the reset having run)."""
f = dict(facts)
if r.get('state') not in WAITING + ('installed',):
raise ValueError('the transaction is %s, not one to resume' % r.get('state'))
if r.get('state') == 'prepared-request':
raise ValueError('the preparation did not finish (the transaction was saved, the device may be unchanged); '
'run the installer without --resume')
if 'bcb' in f and bcb_pending(Path(f['bcb']).read_bytes()):
raise ValueError("Android's recovery has not reset the device yet (misc still asks for it): reboot the device "
'(adb reboot), set Android up again, and run the installer once more')
for k in ('serial', 'slot', 'cid', 'node', 'start', 'disk'):
if str(f.get(k)) != str(r.get(k)):
raise ValueError('the device or its slot differs from the saved transaction (%s)' % k)
if int(f.get('size', -1)) != r['target']:
raise ValueError('the prepared partition geometry differs (userdata is %s sectors, the transaction made it %s)'
% (f.get('size'), r['target']))
want = {'gpt_first': r['start'], 'gpt_end': r['start'] + r['target'] - 1, 'usable_end': r['usable_end'],
'region_start': r['region_start'], 'region_end': r['region_end']}
for k, v in want.items():
if int(f.get(k, -1)) != v:
raise ValueError('the prepared partition geometry differs (%s)' % k)
if r['region_end'] - r['region_start'] != r['need']:
raise ValueError('the transaction does not add up (its region is not the size it reserved)')
if r.get('state') != 'installed':
got = Path(f['marker']).read_bytes()[:4096] if f.get('marker') else b''
if got != marker(r['token']):
raise ValueError('preparation token mismatch; refusing to overwrite the region')
if f.get('identity') != r['identity']:
raise ValueError("this installer's tools or the package differ from the ones that prepared the installation")
def main(argv):
if not argv:
print(__doc__)
return 2
cmd, args = argv[0], argv[1:]
try:
if cmd == 'token':
print(token())
elif cmd == 'marker':
Path(args[1]).write_bytes(marker(args[0]))
elif cmd == 'bcb':
Path(args[0]).write_bytes(bcb())
elif cmd == 'encrypted':
# KEY=VALUE (state= type= source= magic=): an empty value is never a missing argument (Windows
# PowerShell 5.1 drops empty arguments on the way to a program)
f = typed(args)
try:
print('yes' if encrypted(f.get('state', ''), f.get('type', ''), f.get('source', ''), f.get('magic', '')) else 'no')
except ValueError:
print('unknown')
elif cmd == 'identity':
print(identity(args[0], args[1] if len(args) > 1 and args[1] else None))
elif cmd == 'new':
new(args[0], typed(args[1:]))
elif cmd == 'set':
r = load(args[0])
r.update(typed(args[1:]))
r['changed'] = time.strftime('%Y-%m-%dT%H:%M:%S')
save(args[0], r)
elif cmd == 'get':
r = load(args[0])
for k in args[1:]:
print('%s=%s' % (k, r.get(k, '')))
elif cmd == 'find':
p = find(args[0], *(args[1:3] if len(args) >= 3 else ()))
if p:
print(p)
elif cmd == 'check':
try:
check(load(args[0]), typed(args[1:]))
except (ValueError, KeyError, OSError) as e:
print('RESUME-REFUSED: %s' % (e.args[0] if e.args else e))
return 1
print('RESUME-OK')
else:
print('unknown command ' + cmd, file=sys.stderr)
return 2
except (ValueError, IndexError, OSError) as e:
print('resume.py: %s' % e, file=sys.stderr)
return 2
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
+218
View File
@@ -0,0 +1,218 @@
# Making room by a reset of Android, and the installation that resumes afterwards - EXPERIMENTAL (docs/FINDINGS.md
# 112). Ported from kano's desktop installer (kanoqwq/mu300-linux, branch clean-tf-7.2: desktop/installer.py and
# desktop/boot/part-prepare.sh, commits f6b0668d and 0e19fe32); the transaction itself is tools/resume.py's. Sourced by
# install.sh (su_do, dev_pull, adb_prop, sha256_of, ask, say, die, t, info, progress, gib are its own; needs $TOP,
# $WORK, $T).
#
# userdata is shrunk as before (only it: the last partition), but Android's data is not cleared by this installer:
# Android's own recovery is asked to format it (the bootloader message in misc, "--wipe_data"), which also starts
# its encryption anew - with file-based encryption a filesystem cleared from outside is one Android cannot mount, and
# recovery then waits for a person at a screen these devices do not have. Before anything is written, a transaction
# and a backup are saved on this computer; a token goes to the start of the region that is made, outside every
# partition, where the reset does not reach. After the reset - Android set up again, USB debugging on and root back -
# the installer finds the transaction and continues, when the device, its slot, its partition table (both copies,
# every CRC), the region, the token and this installer's tools are still the ones it was prepared with.
#
# MU300_BACKUP_DIR=DIR where the transactions and backups are kept (default ~/mu300-backups)
# MU300_RESUME=0|1 0 (--no-resume): never resume; 1 (--resume): resume, or stop when there is nothing to
# MU300_TRANSACTION=FILE (--transaction FILE) this transaction, not the newest one for the device
RESUME=0; RESUME_FILE=
BACKUP_DIR=${MU300_BACKUP_DIR:-${HOME:-.}/mu300-backups}
resume_py() { python3 "$TOP/tools/resume.py" "$@"; }
# resume_pending: any transaction waiting in BACKUP_DIR (for any device). The installer does not update itself then:
# the transaction is bound to the tools that made it.
resume_pending() {
[ "${MU300_RESUME:-}" != 0 ] || return 1
[ -n "${MU300_TRANSACTION:-}" ] && return 0
[ -d "$BACKUP_DIR" ] && command -v python3 >/dev/null 2>&1 && [ -n "$(resume_py find "$BACKUP_DIR" 2>/dev/null)" ]
}
# resume_facts: what identifies the device and its userdata, and how Android keeps its data (sysfs and properties,
# read only): SERIAL CID UD_NODE UD_START UD_SIZE CRYPTO (yes|no|unknown) CRYPTO_STATE CRYPTO_TYPE DATA_SOURCE
resume_facts() {
# (no double quotes: install.ps1 sends the same text, and Windows PowerShell 5.1 drops them on the way to adb)
_rf=$(su_do 'd=$(readlink -f /dev/block/by-name/userdata); n=${d##*/}; b=${n%p*}; echo NODE=$n; echo CID=$(cat /sys/class/block/$b/device/cid); echo START=$(cat /sys/class/block/$n/start); echo SIZE=$(cat /sys/class/block/$n/size); echo STATE=$(getprop ro.crypto.state); echo TYPE=$(getprop ro.crypto.type); while read s m r; do case $m in /data) echo SOURCE=$s; break ;; esac; done < /proc/mounts; echo MAGIC=$(dd if=$d bs=1 skip=1024 count=4 2>/dev/null | od -An -tx1 | tr -d \\040\\012); echo EXT=$(dd if=$d bs=1 skip=1080 count=2 2>/dev/null | od -An -tx1 | tr -d \\040\\012)')
_rv() { printf '%s\n' "$_rf" | sed -n "s/^$1=//p" | head -n1; }
UD_NODE=$(_rv NODE); CID=$(_rv CID); UD_START=$(_rv START); UD_SIZE=$(_rv SIZE)
CRYPTO_STATE=$(_rv STATE); CRYPTO_TYPE=$(_rv TYPE); DATA_SOURCE=$(_rv SOURCE)
_m=$(_rv EXT); [ "$_m" = 53ef ] || _m=$(_rv MAGIC)
SERIAL=$(adb_prop ro.serialno)
# (kano's checks of the identity: an eMMC partition node and the eMMC's 128-bit CID)
case $UD_NODE in mmcblk[0-9]p[0-9]*) ;; *) return 1 ;; esac
case $UD_NODE in *[!a-z0-9]*) return 1 ;; esac
[ ${#CID} = 32 ] || return 1
case $CID in *[!0-9a-f]*) return 1 ;; esac
case $UD_START$UD_SIZE in ''|*[!0-9]*) return 1 ;; esac
[ -n "$SERIAL" ] || return 1
CRYPTO=$(resume_py encrypted state="$CRYPTO_STATE" type="$CRYPTO_TYPE" source="$DATA_SOURCE" magic="$_m")
}
# resume_region NEW_LAST_END: RG_START and RG_END (sectors) of the free region behind a userdata that ends before
# sector NEW_LAST_END - tools/storage.sh's region_probe arithmetic
resume_region() {
RG_START=$(( ($1 / 4096 + 1) * 4096 ))
RG_END=$(( ((disk - 34) / 4096 - 1) * 4096 ))
[ $RG_END -gt $RG_START ] || RG_END=$RG_START
}
# resume_backup DIR: what an installation reads first and what the prepare writes over, copied to DIR on this
# computer and checked against the device: the partition table (as read for the plan), the first block of misc, both
# slots' boot and boot chain partitions. Never the NV or calibration partitions. A SHA256SUMS lists them.
resume_backup() {
_bd=$1
mkdir -p "$_bd" || die "$(t 'could not create {1}' "$_bd")"
cp "$WORK/gpt/gpt.head" "$_bd/gpt.head" && cp "$WORK/gpt/gpt.tail" "$_bd/gpt.tail" ||
die "$(t 'could not copy the partition table into the backup')"
su_do 'dd if=/dev/block/by-name/misc bs=4096 count=1 2>/dev/null > /data/local/tmp/mu300-pull.bin' >/dev/null
adb pull /data/local/tmp/mu300-pull.bin "$_bd/misc-head.bin" >/dev/null 2>&1 || true
su_do 'rm -f /data/local/tmp/mu300-pull.bin' >/dev/null
[ -s "$_bd/misc-head.bin" ] || die "$(t 'could not read the misc header from the device')"
for _bp in boot uboot sml teecfg trustos vbmeta; do
for _bs in a b; do
say "$(t 'Backing up {1}' "${_bp}_$_bs")"
dev_pull "/dev/block/by-name/${_bp}_$_bs" "$_bd/${_bp}_$_bs.img"
_bw=$(su_do "sha256sum /dev/block/by-name/${_bp}_$_bs" | cut -d' ' -f1)
[ -n "$_bw" ] && [ "$_bw" = "$(sha256_of "$_bd/${_bp}_$_bs.img")" ] ||
die "$(t 'the copy of {1} is not what the device holds; nothing was changed' "${_bp}_$_bs")"
done
done
(cd "$_bd" && for _f in gpt.head gpt.tail misc-head.bin *.img; do printf '%s %s\n' "$(sha256_of "$_f")" "$_f"; done) > "$_bd/SHA256SUMS"
}
# resume_push LOCAL REMOTE: LOCAL to the device, and there with the checksum it has here (a push that stopped
# halfway leaves a short file, which dd would write)
resume_push() {
adb push "$1" "$2" >/dev/null 2>&1 || true
[ "$(su_do "sha256sum $2" | cut -d' ' -f1)" = "$(sha256_of "$1")" ]
}
# resume_prepare NEW_END: the destructive stage. Everything has been asked and the backup made; the transaction is
# saved before the first write. Then: the partition table (the backup copy first), read back and checked; the token
# at the start of the region, read back; the bootloader message that has recovery format userdata, read back, with
# the A/B boot control block behind it as it was. The transaction then says "prepared". Android keeps running from
# its slot; nothing of boot_a, boot_b or the boot chain is written.
resume_prepare() {
_ne=$1
resume_region $((_ne + 1))
_tok=$(resume_py token) || die "$(t 'could not make a token')"
RESUME_FILE=$RESUME_BD/transaction.json
_id=$(resume_py identity "$TOP" "${PKG:+$PKG/mu300/manifest}") || die "$(t 'could not compute the installer identity')"
resume_py new "$RESUME_FILE" serial="$SERIAL" slot="$ANDROID_SLOT" cid="$CID" node="$UD_NODE" start="$UD_START" \
size="$UD_SIZE" disk="$disk" target=$((_ne - UD_START + 1)) need=$((RG_END - RG_START)) usable_end="$USABLE_END" \
region_start="$RG_START" region_end="$RG_END" token="$_tok" identity="$_id" crypto="$CRYPTO" \
crypto_state="$CRYPTO_STATE" crypto_type="$CRYPTO_TYPE" backup="$RESUME_BD" ||
die "$(t 'could not save the transaction; nothing was changed')"
info resume.transaction "$RESUME_FILE"
echo " $(t 'transaction saved: {1}' "$RESUME_FILE")"
resume_py marker "$_tok" "$WORK/gpt/marker.bin" && resume_py bcb "$WORK/gpt/bcb.bin" ||
die "$(t 'could not prepare the files to write; nothing was changed')"
step repartition 50
say "$(t 'Rewriting the partition table')"
python3 "$TOP/tools/resize-last-partition.py" "$WORK/gpt/gpt.head,$WORK/gpt/gpt.tail" \
--disk-sectors "$disk" --name userdata --end-sector "$_ne" --out "$WORK/gpt/new" || die "$(t 'the resize was refused; nothing is changed')"
for _f in new.head new.tail marker.bin bcb.bin; do
resume_push "$WORK/gpt/$_f" "$T/mu300-$_f" ||
{ su_do "rm -f $T/mu300-new.head $T/mu300-new.tail $T/mu300-marker.bin $T/mu300-bcb.bin" >/dev/null
die "$(t 'the new partition table did not arrive on the device as it was made; nothing is changed')"; }
done
_bc=$(su_do 'dd if=/dev/block/by-name/misc bs=1 skip=2048 count=32 2>/dev/null | od -An -tx1 -v' | tr -d ' \n')
# the backup copy first: if power is lost between the two, the primary is still the old table and the device
# boots, which is the recoverable order
su_do "dd if=$T/mu300-new.tail of=/dev/block/mmcblk0 bs=512 seek=$((disk - 33)) conv=fsync 2>/dev/null" >/dev/null
su_do "dd if=$T/mu300-new.head of=/dev/block/mmcblk0 bs=512 conv=fsync 2>/dev/null" >/dev/null
say "$(t 'Verifying')"
su_do "dd if=/dev/block/mmcblk0 bs=512 count=34 2>/dev/null > /data/local/tmp/gpt.head" >/dev/null
su_do "dd if=/dev/block/mmcblk0 bs=512 skip=$((disk - 33)) count=33 2>/dev/null > /data/local/tmp/gpt.tail" >/dev/null
adb pull /data/local/tmp/gpt.head "$WORK/gpt/after.head" >/dev/null 2>&1 || true
adb pull /data/local/tmp/gpt.tail "$WORK/gpt/after.tail" >/dev/null 2>&1 || true
su_do 'rm -f /data/local/tmp/gpt.head /data/local/tmp/gpt.tail' >/dev/null
check=$(python3 "$TOP/tools/resize-last-partition.py" "$WORK/gpt/after.head,$WORK/gpt/after.tail" \
--disk-sectors "$disk" --name userdata --show) || die "$(t 'the table on the device does not read back as valid GPT.')
$(t "The backup copy at the end of the disk was written first, so Android's own repair may still fix this. Do not power off.")"
got=$(echo "$check" | sed -n 's/^LAST_END=//p')
[ "$got" = "$_ne" ] || die "$(t 'the table did not take (userdata still ends at {1}). Nothing else was changed.' "$got")"
echo " $(t 'userdata now ends at sector {1}' "$got")"
# the token: the first 4 KiB of the region, outside every partition from now on
su_do "dd if=$T/mu300-marker.bin of=/dev/block/mmcblk0 bs=512 seek=$RG_START count=8 conv=notrunc,fsync 2>/dev/null" >/dev/null
[ "$(su_do "dd if=/dev/block/mmcblk0 bs=512 skip=$RG_START count=8 2>/dev/null | sha256sum" | cut -d' ' -f1)" = "$(sha256_of "$WORK/gpt/marker.bin")" ] ||
die "$(t 'the token did not read back from the device; misc was not changed, Android keeps its data. Run the installer again.')"
# the reset, by Android's own recovery: the bootloader message in the first 2 KiB of misc
say "$(t "Asking Android's recovery to reset Android's data on the next boot")"
su_do "dd if=$T/mu300-bcb.bin of=/dev/block/by-name/misc bs=2048 count=1 conv=notrunc,fsync 2>/dev/null" >/dev/null
[ "$(su_do 'dd if=/dev/block/by-name/misc bs=2048 count=1 2>/dev/null | sha256sum' | cut -d' ' -f1)" = "$(sha256_of "$WORK/gpt/bcb.bin")" ] &&
[ "$(su_do 'dd if=/dev/block/by-name/misc bs=1 skip=2048 count=32 2>/dev/null | od -An -tx1 -v' | tr -d ' \n')" = "$_bc" ] ||
die "$(t 'the request for the reset did not read back from misc. The partition table is changed already: run the installer again, it continues from here.')"
su_do "sync; rm -f $T/mu300-new.head $T/mu300-new.tail $T/mu300-marker.bin $T/mu300-bcb.bin" >/dev/null
resume_py set "$RESUME_FILE" state=prepared || die "$(t 'could not save the transaction')"
}
# resume_lookup: RESUME=1 and RESUME_FILE when a transaction waits for this device (or MU300_TRANSACTION names one);
# dies when --resume was asked for and there is none. Needs region_probe (disk) and slot_setup.
resume_lookup() {
[ "${MU300_RESUME:-}" != 0 ] || return 0
# nothing saved on this computer, and not asked for: nothing more is read from the device
[ "${MU300_RESUME:-}" = 1 ] || resume_pending || return 0
command -v python3 >/dev/null 2>&1 || die "$(t '{1} not found' python3)"
if ! resume_facts; then
[ "${MU300_RESUME:-}" != 1 ] || die "$(t 'could not read what identifies this device (serial, eMMC CID, userdata)')"
return 0
fi
RESUME_FILE=${MU300_TRANSACTION:-}
[ -n "$RESUME_FILE" ] || RESUME_FILE=$(resume_py find "$BACKUP_DIR" "$SERIAL" "$CID" 2>/dev/null)
if [ -z "$RESUME_FILE" ]; then
[ "${MU300_RESUME:-}" != 1 ] || die "$(t 'no saved transaction for this device in {1} (--transaction FILE names one)' "$BACKUP_DIR")"
return 0
fi
[ -f "$RESUME_FILE" ] || die "$(t '{1} not found' "$RESUME_FILE")"
RESUME=1
info resume.transaction "$RESUME_FILE"
say "$(t 'A prepared installation is waiting: {1}' "$RESUME_FILE")"
echo " $(t 'EXPERIMENTAL: it continues the installation that made room by resetting Android. --no-resume ignores it.')"
}
# resume_validate [soft]: every check of the transaction against the device, before anything is written
# (resume.py check, read only); dies with the reason - with soft (--check) says it and returns 1.
resume_validate() {
mkdir -p "$WORK/gpt"
rm -f "$WORK/gpt/resume.head" "$WORK/gpt/resume.tail" "$WORK/gpt/resume-marker.bin" "$WORK/gpt/resume-bcb.bin"
su_do "dd if=/dev/block/mmcblk0 bs=512 count=34 2>/dev/null > /data/local/tmp/gpt.head" >/dev/null
su_do "dd if=/dev/block/mmcblk0 bs=512 skip=$((disk - 33)) count=33 2>/dev/null > /data/local/tmp/gpt.tail" >/dev/null
adb pull /data/local/tmp/gpt.head "$WORK/gpt/resume.head" >/dev/null 2>&1 || true
adb pull /data/local/tmp/gpt.tail "$WORK/gpt/resume.tail" >/dev/null 2>&1 || true
su_do 'rm -f /data/local/tmp/gpt.head /data/local/tmp/gpt.tail' >/dev/null
_rs=$(python3 "$TOP/tools/resize-last-partition.py" "$WORK/gpt/resume.head,$WORK/gpt/resume.tail" \
--disk-sectors "$disk" --name userdata --show 2>&1) || _rs=
[ -n "$_rs" ] || die "$(t 'could not read the partition table')"
_rg() { printf '%s\n' "$_rs" | sed -n "s/^$1=//p"; }
_rr=$(resume_py get "$RESUME_FILE" region_start) || die "$(t 'could not read the transaction {1}' "$RESUME_FILE")"
_rr=${_rr#region_start=}
case $_rr in ''|*[!0-9]*) die "$(t 'could not read the transaction {1}' "$RESUME_FILE")" ;; esac
su_do "dd if=/dev/block/mmcblk0 bs=512 skip=$_rr count=8 2>/dev/null > /data/local/tmp/mu300-pull.bin" >/dev/null
adb pull /data/local/tmp/mu300-pull.bin "$WORK/gpt/resume-marker.bin" >/dev/null 2>&1 || true
su_do 'dd if=/dev/block/by-name/misc bs=2048 count=1 2>/dev/null > /data/local/tmp/mu300-pull.bin' >/dev/null
adb pull /data/local/tmp/mu300-pull.bin "$WORK/gpt/resume-bcb.bin" >/dev/null 2>&1 || true
su_do 'rm -f /data/local/tmp/mu300-pull.bin' >/dev/null
_id=$(resume_py identity "$TOP" "${PKG:+$PKG/mu300/manifest}")
_ok=0
_out=$(resume_py check "$RESUME_FILE" serial="$SERIAL" slot="$ANDROID_SLOT" cid="$CID" node="$UD_NODE" \
start="$UD_START" size="$UD_SIZE" disk="$disk" gpt_first="$(_rg LAST_FIRST)" gpt_end="$(_rg LAST_END)" \
usable_end="$(_rg USABLE_END)" region_start=$((OFF / 512)) region_end=$(( (OFF + SIZE) / 512 )) \
marker="$WORK/gpt/resume-marker.bin" bcb="$WORK/gpt/resume-bcb.bin" identity="$_id") || _ok=$?
info resume.check "$_out"
if [ $_ok != 0 ]; then
if [ "${1:-}" = soft ]; then
echo " $(t 'The prepared installation cannot be continued: {1}' "${_out#RESUME-REFUSED: }")"
return 1
fi
die "$(t 'The prepared installation cannot be continued: {1}' "${_out#RESUME-REFUSED: }")
$(t 'Nothing was written. Keep the device as it is and keep {1}.' "$RESUME_FILE")
$(t 'Another transaction: --transaction FILE. To install as if nothing had been prepared: --no-resume (the region is then treated as space that holds data).')"
fi
echo " $(t 'the device, its slot, its partition table, the region, the token and this installer are the ones the transaction was made with')"
}
+17 -2
View File
@@ -114,8 +114,23 @@ On the 32 GB device `userdata` fills the whole disk, so there is no free space.
* **An SD card (F50):** erases nothing on the internal storage. The installer offers it.
* **Shrink `userdata`:** the installer can make room, asks how many GiB to give Linux and keeps at least 4 GiB for
Android. **This rewrites the partition table and erases everything in Android. It is experimental** and you must
type `ERASE`. Take a full backup with `tools/backup-device.sh` first. Android sets its data up again on the next
boot; then run the installer again.
type `ERASE`. Take a full backup with `tools/backup-device.sh` first.
How it goes (ported from kano's desktop installer, EXPERIMENTAL, not yet run on a device by this project):
1. The installer saves a backup (partition table, `misc`, `boot` and the boot chain of both slots; never the NV or
calibration partitions) and a record of what it prepares, a *transaction*, on your computer in
`~/mu300-backups/` - keep that folder.
2. It shrinks `userdata`, writes a token at the start of the new free region and asks Android's own recovery to
reset Android on the next start. Android's data is encrypted, so only Android itself can format it again.
3. The device restarts into recovery, which erases Android's data (a factory reset), and Android starts as new.
This takes a few minutes and more than one restart.
4. Set Android up again, turn USB debugging on, and bring root back: install the Magisk app again and let Shell
have root (Magisk itself is still in the boot partition).
5. Run the installer again. It finds the transaction and checks that this is the same device, slot, partition
table, region and token, and the same installer; then it installs as usual into the region. If anything differs
it stops and writes nothing. `--no-resume` ignores the transaction, `--resume` insists on one,
`--transaction FILE` names one.
### The SD card (F50 only)