diff --git a/AGENTS.md b/AGENTS.md index 796b11262..d15e496a7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -128,7 +128,7 @@ Each entry gives the gotcha, then the reason or the fix. Details are in the link - **ABL leaves both cluster watchdogs running:** the phone resets at about 60 s of uptime unless `s3c2410_wdt` takes them over at probe. - **ABL picks the base DTB by `soc_id`:** `bin/omamobile images` ships both silicon revisions. It also needs an empty `/ect` node and `/chosen/bootargs`, and applies a DPM overlay that needs label stubs (build with `-@`). - **Pixel 7 Pro: once slot B has booted with AVB footers, it needs them.** A stock install's `vbmeta_b` chains `boot` and `init_boot`. After one boot of #104's footer-carrying images, ABL refused footer-less ones (images built by any tool from before #104, or a saved older image set): it stopped in fastboot or used up B's tries and fell back to stock, whose recovery offered "Try again" or "Factory data reset". Build every image with the current `bin/omamobile`, keep rollback sets built the same way, and on that recovery screen choose neither: hold Volume Down + Power about 20 s for fastboot. A stock boot rewrites `efs`, `persist` and `modem_userdata`, so take a fresh read-only backup after one. [NOTES](device/cheetah/NOTES.md#2026-10-30-the-charger-reads-offline-at-full-and-slot-b-now-needs-its-avb-footers) -- **Pixel 9a: a fallback to slot A costs the Linux root.** `fastboot --set-active=b` (which `bin/omamobile flash` runs) clears B's successful flag and gives B three ABL tries. A fastboot flash of slot B's images without `--set-active` clears the flag too: on 2026-10-31, `slot-successful:b` read `yes` before five suffixed flashes and `no` after, and the next boot started with `retry-count` 2 ([tegu NOTES](device/tegu/NOTES.md#2026-10-31-a-fastboot-flash-of-slot-b-cleared-its-successful-mark-and-b-was-marked-again)). Every boot uses one try, and the initramfs USB safety net (no USB host in about 65 s: panic) uses them fast. At zero ABL boots stock on slot A, and stock overwrote `userdata` on 10-28, and most likely on 10-26, before anyone could choose anything in recovery. So: `flash` only a known-good image set, and on the 9a ask the maintainer before any `flash` or fastboot write to slot B, because it unmarks B. Marking B successful is a `devinfo` write, and on the 9a it is on hold until the maintainer decides how it's done: don't mark B, and don't run `omamobile-bootctl` or anything that makes `devinfo` writable. With B marked, try new images with `push`, which doesn't call `--set-active` and leaves the mark alone; ABL then no longer falls back, so a broken pushed image means fastboot by the buttons, and the fastboot recovery leaves B unmarked: from then on every boot spends a try, so keep reboots few and ask the maintainer before marking B. With B unmarked, every boot spends one of the three tries: keep reboots few and don't test new images. [tegu NOTES](device/tegu/NOTES.md#2026-10-26-and-2026-10-28-slot-a-fallbacks-that-cost-userdata); the operation approved on 2026-10-22, now on hold: [NOTES](device/tegu/NOTES.md#approved-b-success-operation-after-layout-review-2026-10-22). +- **Pixel 9a: a fallback to slot A costs the Linux root.** `fastboot --set-active=b` (which `bin/omamobile flash` runs) clears B's successful flag and gives B three ABL tries. A fastboot flash of slot B's images without `--set-active` clears the flag too: on 2026-10-31, `slot-successful:b` read `yes` before five suffixed flashes and `no` after, and the next boot started with `retry-count` 2 ([tegu NOTES](device/tegu/NOTES.md#2026-10-31-a-fastboot-flash-of-slot-b-cleared-its-successful-mark-and-b-was-marked-again)). Every boot uses one try, and the initramfs USB safety net (no USB host in about 65 s: panic) uses them fast. At zero ABL boots stock on slot A, and stock overwrote `userdata` on 10-28, and most likely on 10-26, before anyone could choose anything in recovery. So: `flash` only a known-good image set, and on the 9a ask the maintainer before any `flash` or fastboot write to slot B, because it unmarks B. Marking B successful is a `devinfo` write, and on the 9a it is on hold until the maintainer decides how it's done: don't mark B, and don't run `omamobile-bootctl` or anything that makes `devinfo` writable. With B marked, try new images with `push`, which doesn't call `--set-active` and leaves the mark alone; ABL then no longer falls back, so a broken pushed image means fastboot by the buttons, and the fastboot recovery leaves B unmarked: from then on every boot spends a try, so keep reboots few and ask the maintainer before marking B. With B unmarked, every boot spends one of the three tries: keep reboots few and don't test new images. [tegu NOTES](device/tegu/NOTES.md#2026-10-26-and-2026-10-28-slot-a-fallbacks-that-cost-userdata); the operation approved on 2026-10-22, now on hold: [NOTES](device/tegu/NOTES.md#approved-b-success-operation-after-layout-review-2026-10-22). The reviewed way to mark B, once the maintainer has merged it and lifted this hold, is `omamobile-bootctl` from `omamobile-device-tegu`, run by hand from [BRINGUP-M1](device/tegu/BRINGUP-M1.md#6-slot-b-marked-successful-by-hand) ยง6 ([#252](https://github.com/derekross/omarchy-mobile/issues/252)); until then the hold above stands. - **`reboot -f` and busybox `reboot` hang:** use `reboot-to ` (`LINUX_REBOOT_CMD_RESTART2`). ABL often ignores the `bootloader` reason anyway. It stops no unit, so stop the modem first (section 2). - **Reserved memory on gs201 is `#address-cells = <2>`, `#size-cells = <1>`,** so each `reg`/`alloc-ranges` entry is 12 bytes. A 16-byte value is silently ignored, and the pool lands anywhere. The display pool's `alignment` must be two cells too, or `of_reserved_mem` rejects it. `/proc/device-tree` shows the raw property, so it *looks* right. [WIFI-BATTERY-PLAN](device/cheetah/WIFI-BATTERY-PLAN.md) 9.x, [NOTES](device/cheetah/NOTES.md) - **Check every stock `reserved-memory` region against `/proc/iomem`:** five were plain System RAM in our kernel, and firmware writes into them at runtime. diff --git a/README.md b/README.md index eed8beb71..fbbff2e4a 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ Large trees live outside the repo: the Android-side sources, images and captures ## Ground rules - We only ever flash the boot images and userdata. Never `bootloader`, `radio`, `devinfo`, `persist` or calibration partitions. -- **Licensing:** this repository is MIT ([LICENSE](LICENSE)) except where a file's SPDX header says otherwise. Kernel patches (and the board dtbo source) are GPL-2.0. The port of Google's Apache-2.0 boot-control code keeps that licence and Google's notice (`packages/omamobile-device-cheetah/src/omamobile-bootctl.c`). Every file we write carries an SPDX header. +- **Licensing:** this repository is MIT ([LICENSE](LICENSE)) except where a file's SPDX header says otherwise. Kernel patches (and the board dtbo source) are GPL-2.0. The ports of Google's Apache-2.0 boot-control code keep that licence and Google's notice (`packages/omamobile-device-cheetah/src/omamobile-bootctl.c`, and the husky and tegu packages' `bootctl/omamobile-bootctl.c`, each with `LICENSE.Apache-2.0` beside it). Every file we write carries an SPDX header. - Google's proprietary firmware and binaries are never committed: our scripts extract them from the user's own factory image. - No code from unlicensed sources. Google's GPL kernel, upstream Linux, postmarketOS and Mesa are fine. diff --git a/device/husky/BRINGUP-M1.md b/device/husky/BRINGUP-M1.md index 66a7fd681..94bc74685 100644 --- a/device/husky/BRINGUP-M1.md +++ b/device/husky/BRINGUP-M1.md @@ -179,6 +179,118 @@ Findings: The UFS boots that followed (U2, U3 and test K) are in husky's [UFS plan](UFS-PLAN.md). +## Slot B marked successful by hand + +**Status (2026-11-07):** tool written, **never run on a phone**; it waits for +the maintainer's review of its pull request. Nothing here may run until the maintainer has merged the tool and the layout evidence below is on #252. + +The decision on [#252](https://github.com/derekross/omarchy-mobile/issues/252): +slot B is marked successful by hand, attended, once per install of slot B's +images, and only after that image set has booted cleanly and passed +`tools/phone-smoke`. Never on the first boot of an untested image, and never +from a unit, a hook or the installer. Once B is marked, ABL no longer falls +back to slot A, so a broken image after that means fastboot by the buttons +(Power + Volume Up held 15-30 s to restart, then Power + Volume Down for fastboot, test 23). Any fastboot flash of slot B's images clears the mark again +(seen on the 9a, tegu NOTES 2026-10-31; expected on the 8 Pro, not yet seen); mark again only after the new set passes the smoke test. + +The tool is `omamobile-bootctl` from `omamobile-device-husky` +(`packages/omamobile-device-husky/bootctl/omamobile-bootctl.c`, the same source as +the tegu package; this phone's values in `bootctl/bootctl-device.h`). It +refuses another board, a devinfo version other than 3.15 (the one recorded +for husky: [BATTERY-NOTES](BATTERY-NOTES.md) "The cure exists", and two owners' phones on #252), a boot from slot A, a slot B that isn't active or is +marked unbootable, and a storage guard that isn't holding (the main LUN's +whole-disk node usable, or any disk or partition outside `UFS_RW` writable). +It prints the devinfo version and the eight slot bytes 0x30-0x37, decoded, +and nothing else from the partition. + +**Its read-write window.** The kernel can't write a partition of a read-only +disk: `bdev_read_only()` is the partition's own flag OR its disk's +(`include/linux/blkdev.h`), and the write path (`blkdev_write_iter()`), the +`BLKROGET` ioctl and sysfs `ro` all use it. So `devinfo` can't be made +writable while its boot LUN stays read-only, and the tool clears the LUN's +flag too, for as long as the one byte takes. **That exposes the whole LUN:** +while the disk's flag is clear, the whole-disk node is writable, and raw +writes through it reach every byte of the LUN, the other partitions on it +(`pinfo`, `blenv` and `mfg_data`) included; their own flags guard only their own nodes. Whether +that is acceptable is the maintainer's ruling on #252 and this tool waits +for it. The recommendation is to guard the boot LUNs as the main LUN is +guarded (whole-disk node removed, each partition's own flag set) in a +separate change tested on the 7 Pro; with that in place the window becomes +devinfo's flag alone. + +The window, in order: refuse if devinfo, its LUN or a sibling is mounted or +held, or open for writing by any other process (checked again right before +the window, after the codename); the disk writable, and checked; each +sibling's and devinfo's own flag checked (the only moment a partition's own +flag can be read; any clear or unreadable one closes the window); devinfo +writable; devinfo read again and compared with what the checks saw; the +byte at 0x35 (slot B's flags) changed by OR 0x02 with `O_DSYNC` (the kernel +writes the 4 KiB block that holds it); the whole partition read back past the +page cache (`O_DIRECT`) and compared with the prediction (on a mismatch the +original is written back and read back, and the tool fails); devinfo +read-only and checked; the disk read-only and checked. ^C, SIGTERM and SIGHUP +are blocked. A relock child, started before the window, sets both flags back +the moment the tool exits or is killed, and from the moment the window +opens it also sets them back every 10 s for as long as the tool lives (a +stopped or hung tool), so the window can't stay open unwatched. + +Each step: risk, command, expect / pass, stop, rollback. Record the results +here with the date and `uname -r`. Post only the version and the eight slot +bytes, never a dump. + +1. **Preconditions** (none; read-only). The installed image set has booted + cleanly at least once and `tools/phone-smoke` passed on it (keep the + report). `pacman -Q omamobile-device-husky` shows the version with the tool, + built from the merged source. The layout evidence the maintainer asked for on #252 is + posted for this phone: the version, the eight slot bytes and `fastboot + getvar slot-successful:b`, `slot-unbootable:b` and `slot-retry-count:b` + read together, across one change ABL makes itself (a boot that spends a + try). + **Stop:** any of these missing. **Rollback:** none. +2. **Status** (none; read-only). `omamobile-bootctl status`. + **Expect:** `devinfo version 3.15 (the layout recorded for husky)`, `booted + from slot b`, `storage guard: holding`, slot b active, not successful, not + unbootable. **Stop:** any refusal, another version, slot a booted, the + guard not holding. **Rollback:** none. +3. **Dry run** (none; read-only: nothing is opened for writing). + `omamobile-bootctl mark-b-successful`. **Expect:** `planned: byte 0x35 XX + -> YY (slot b successful), nothing else`, where YY is XX OR 02, and the + write command with this boot's eight bytes. Post the output on #252 and + wait for the maintainer's go. **Stop:** any other plan, a refusal, no go. + **Rollback:** none. +4. **Read-only backup** (none; read-only). From the laptop, + `tools/nv-backup DIR` (devinfo is in the descriptor's `NV_BACKUP_EXTRA`), + then `tools/nv-backup --check DIR` right before step 5. Keep it off the + repository. **Expect:** every copy verified, and the check matches live + storage. **Stop:** a failed copy or a mismatch. **Rollback:** none. +5. **The write** (medium: one bit of `devinfo`, outside the allowlist). With a + kernel log stream to the laptop running and nobody about to reboot the + phone: `omamobile-bootctl mark-b-successful --write --codename husky + --expect ""`. Nothing changes on the screen. + **Expect:** exit 0, `before` and `after` lines that differ only in byte + 0x35 by 0x02, then `slot b marked successful: written, read back, devinfo + and read-only again`. **Stop:** any other exit, and don't run it + again: exit 1 or 2 refused before anything was opened; 3, the write + failed or was put back and devinfo reads as before; 4, devinfo may differ + from the backup (don't reboot; post the output and wait); 5, a read-only + flag could not be restored (`systemctl reboot`: the initramfs sets it + again). **Rollback:** the mark is undone by flashing slot B's images + (`bin/omamobile flash` with a known-good set), which clears it; the + step 4 backup is for exit 4, and writing it back is the maintainer's call. +6. **Read back** (none; read-only). `omamobile-bootctl status` again, then + `tools/nv-backup --check DIR`. **Expect:** slot b successful, the guard + holding; the check differs only in `devinfo`, and a fresh read-only copy + of it differs from the backup in byte 0x35 alone (`cmp -l` prints one + line, offset 54). **Stop:** anything else. **Rollback:** as in step 5. +7. **ABL's view** (low: one trip to fastboot, which spends no try with B + marked). `reboot-to bootloader`, then, with this phone's serial pinned, + `fastboot -s getvar slot-successful:b`, `slot-unbootable:b` and + `slot-retry-count:b` (each with `-s `), then + `fastboot -s reboot`. + **Expect:** `yes`, `no`, and the phone boots slot B again. **Stop:** `no` + for successful: post it and don't repeat the write. **Rollback:** as in + step 5. + ## Open questions - ~~Does a bare DWC3 enumerate on the PHY and repeater state ABL leaves behind?~~ No: the PHY is off (test 17); with the eUSB2 PHY driven, the repeater as ABL leaves it works (test 18). diff --git a/device/tegu/BRINGUP-M1.md b/device/tegu/BRINGUP-M1.md index c6864741b..ca6df6587 100644 --- a/device/tegu/BRINGUP-M1.md +++ b/device/tegu/BRINGUP-M1.md @@ -205,6 +205,117 @@ fails, preserve the first discriminating trace and discuss it before any new kernel workaround. This PR must retain the outstanding status until that evidence exists. +## 6. Slot B marked successful by hand + +**Status (2026-11-07):** tool written, **never run on a phone**; it waits for +the maintainer's review of its pull request. The 9a's hold in AGENTS.md ("Pixel 9a: a fallback to slot A costs the Linux root") still stands: nothing here may run until the maintainer has merged the tool and lifted it. + +The decision on [#252](https://github.com/derekross/omarchy-mobile/issues/252): +slot B is marked successful by hand, attended, once per install of slot B's +images, and only after that image set has booted cleanly and passed +`tools/phone-smoke`. Never on the first boot of an untested image, and never +from a unit, a hook or the installer. Once B is marked, ABL no longer falls +back to slot A, so a broken image after that means fastboot by the buttons +(with the phone off, Volume Down then Power, both held about 20 s). Any fastboot flash of slot B's images clears the mark again +([NOTES](NOTES.md) 2026-10-31); mark again only after the new set passes the smoke test. + +The tool is `omamobile-bootctl` from `omamobile-device-tegu` +(`packages/omamobile-device-tegu/bootctl/omamobile-bootctl.c`, the same source as +the husky package; this phone's values in `bootctl/bootctl-device.h`). It +refuses another board, a devinfo version other than 3.15 (the one recorded +for tegu: [NOTES](NOTES.md) "Read-only layout evidence after official OTA maintenance", the pair across a boot that spent a try, and the three marks of 2026-10-22 to 10-31), a boot from slot A, a slot B that isn't active or is +marked unbootable, and a storage guard that isn't holding (the main LUN's +whole-disk node usable, or any disk or partition outside `UFS_RW` writable). +It prints the devinfo version and the eight slot bytes 0x30-0x37, decoded, +and nothing else from the partition. + +**Its read-write window.** The kernel can't write a partition of a read-only +disk: `bdev_read_only()` is the partition's own flag OR its disk's +(`include/linux/blkdev.h`), and the write path (`blkdev_write_iter()`), the +`BLKROGET` ioctl and sysfs `ro` all use it. So `devinfo` can't be made +writable while its boot LUN stays read-only, and the tool clears the LUN's +flag too, for as long as the one byte takes. **That exposes the whole LUN:** +while the disk's flag is clear, the whole-disk node is writable, and raw +writes through it reach every byte of the LUN, the other partitions on it +(`mfg_data`, per FINGERPRINT-PLAN; the LUN's other partitions aren't +recorded here yet) included; their own flags guard only their own nodes. Whether +that is acceptable is the maintainer's ruling on #252 and this tool waits +for it. The recommendation is to guard the boot LUNs as the main LUN is +guarded (whole-disk node removed, each partition's own flag set) in a +separate change tested on the 7 Pro; with that in place the window becomes +devinfo's flag alone. + +The window, in order: refuse if devinfo, its LUN or a sibling is mounted or +held, or open for writing by any other process (checked again right before +the window, after the codename); the disk writable, and checked; each +sibling's and devinfo's own flag checked (the only moment a partition's own +flag can be read; any clear or unreadable one closes the window); devinfo +writable; devinfo read again and compared with what the checks saw; the +byte at 0x35 (slot B's flags) changed by OR 0x02 with `O_DSYNC` (the kernel +writes the 4 KiB block that holds it); the whole partition read back past the +page cache (`O_DIRECT`) and compared with the prediction (on a mismatch the +original is written back and read back, and the tool fails); devinfo +read-only and checked; the disk read-only and checked. ^C, SIGTERM and SIGHUP +are blocked. A relock child, started before the window, sets both flags back +the moment the tool exits or is killed, and from the moment the window +opens it also sets them back every 10 s for as long as the tool lives (a +stopped or hung tool), so the window can't stay open unwatched. + +Each step: risk, command, expect / pass, stop, rollback. Record the results +here with the date and `uname -r`. Post only the version and the eight slot +bytes, never a dump. + +1. **Preconditions** (none; read-only). The installed image set has booted + cleanly at least once and `tools/phone-smoke` passed on it (keep the + report). `pacman -Q omamobile-device-tegu` shows the version with the tool, + built from the merged source. The layout pair is recorded + ([NOTES](NOTES.md), 2026-10-22); repeat it if the bootloader was updated + since. + **Stop:** any of these missing. **Rollback:** none. +2. **Status** (none; read-only). `omamobile-bootctl status`. + **Expect:** `devinfo version 3.15 (the layout recorded for tegu)`, `booted + from slot b`, `storage guard: holding`, slot b active, not successful, not + unbootable. **Stop:** any refusal, another version, slot a booted, the + guard not holding. **Rollback:** none. +3. **Dry run** (none; read-only: nothing is opened for writing). + `omamobile-bootctl mark-b-successful`. **Expect:** `planned: byte 0x35 XX + -> YY (slot b successful), nothing else`, where YY is XX OR 02, and the + write command with this boot's eight bytes. Post the output on #252 and + wait for the maintainer's go. **Stop:** any other plan, a refusal, no go. + **Rollback:** none. +4. **Read-only backup** (none; read-only). From the laptop, + `tools/nv-backup DIR` (devinfo is in the descriptor's `NV_BACKUP_EXTRA`), + then `tools/nv-backup --check DIR` right before step 5. Keep it off the + repository. **Expect:** every copy verified, and the check matches live + storage. **Stop:** a failed copy or a mismatch. **Rollback:** none. +5. **The write** (medium: one bit of `devinfo`, outside the allowlist). With a + kernel log stream to the laptop running and nobody about to reboot the + phone: `omamobile-bootctl mark-b-successful --write --codename tegu + --expect ""`. Nothing changes on the screen. + **Expect:** exit 0, `before` and `after` lines that differ only in byte + 0x35 by 0x02, then `slot b marked successful: written, read back, devinfo + and read-only again`. **Stop:** any other exit, and don't run it + again: exit 1 or 2 refused before anything was opened; 3, the write + failed or was put back and devinfo reads as before; 4, devinfo may differ + from the backup (don't reboot; post the output and wait); 5, a read-only + flag could not be restored (`systemctl reboot`: the initramfs sets it + again). **Rollback:** the mark is undone by flashing slot B's images + (`bin/omamobile flash` with a known-good set), which clears it; the + step 4 backup is for exit 4, and writing it back is the maintainer's call. +6. **Read back** (none; read-only). `omamobile-bootctl status` again, then + `tools/nv-backup --check DIR`. **Expect:** slot b successful, the guard + holding; the check differs only in `devinfo`, and a fresh read-only copy + of it differs from the backup in byte 0x35 alone (`cmp -l` prints one + line, offset 54). **Stop:** anything else. **Rollback:** as in step 5. +7. **ABL's view** (low: one trip to fastboot, which spends no try with B + marked). `reboot-to bootloader`, then, with this phone's serial pinned, + `fastboot -s getvar slot-successful:b`, `slot-unbootable:b` and + `slot-retry-count:b` (each with `-s `), then + `fastboot -s reboot`. + **Expect:** `yes`, `no`, and the phone boots slot B again. **Stop:** `no` + for successful: post it and don't repeat the write. **Rollback:** as in + step 5. + ## Recorded control result, 2026-10-22 Both official OTA passes, stock-A build properties, both-slot signed AVB diff --git a/packages/omamobile-device-husky/LICENSE.Apache-2.0 b/packages/omamobile-device-husky/LICENSE.Apache-2.0 new file mode 100644 index 000000000..137069b82 --- /dev/null +++ b/packages/omamobile-device-husky/LICENSE.Apache-2.0 @@ -0,0 +1,73 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/packages/omamobile-device-husky/PKGBUILD b/packages/omamobile-device-husky/PKGBUILD index 0f167a611..dde4131bc 100644 --- a/packages/omamobile-device-husky/PKGBUILD +++ b/packages/omamobile-device-husky/PKGBUILD @@ -6,7 +6,7 @@ pkgrel=1 pkgdesc="Omarchy Mobile support for the Google Pixel 8 Pro (husky): storage guard, USB networking and the USB replug rescue" arch=(aarch64) url="https://github.com/derekross/omarchy-mobile" -license=(MIT) +license=(MIT Apache-2.0) depends=(bash systemd omamobile-keyring i2c-tools 'omamobile-audio>=0.5.18') provides=(omamobile-device) conflicts=(omamobile-device) diff --git a/packages/omamobile-device-husky/README.md b/packages/omamobile-device-husky/README.md index 645ef820b..0a44589ed 100644 --- a/packages/omamobile-device-husky/README.md +++ b/packages/omamobile-device-husky/README.md @@ -1,6 +1,6 @@ # omamobile-device-husky -Omarchy Mobile's first userspace package for the Google Pixel 8 Pro (codename husky, Tensor G3 / zuma). Like the Pixel Fold's, it hides the Android partitions from desktop tools, holds the USB address, and gives pacman the same `[omamobile]` repository as the Pixel 7 Pro. It does not drive the radio, the charger, or a camera, and it does not mark a boot slot successful. +Omarchy Mobile's first userspace package for the Google Pixel 8 Pro (codename husky, Tensor G3 / zuma). Like the Pixel Fold's, it hides the Android partitions from desktop tools, holds the USB address, and gives pacman the same `[omamobile]` repository as the Pixel 7 Pro. It does not drive the radio, the charger, or a camera, and nothing in it marks a boot slot successful on its own: `omamobile-bootctl` is there for the owner to run by hand. | Path | Installs to | What it does | | --- | --- | --- | @@ -22,11 +22,12 @@ Omarchy Mobile's first userspace package for the Google Pixel 8 Pro (codename hu | `etc/omamobile-mirrorlist` | `/etc/pacman.d/omamobile-mirrorlist` | Where pacman finds the `[omamobile]` repository. Same file as the Pixel 7 Pro package | | `omamobile-device-husky.install` | pacman hook | Adds `[omamobile]` to `pacman.conf` before `[omarchy]`, once. Same script as the Pixel 7 Pro package | | `src/reboot-to.c` | `/usr/bin/reboot-to` | Reboot with a reason the bootloader understands. Same bytes as the Pixel 7 Pro package; the test checks | +| `bootctl/omamobile-bootctl.c`, `bootctl/bootctl-device.h`, `LICENSE.Apache-2.0` | `/usr/bin/omamobile-bootctl` | Marks slot B successful in `devinfo`, by hand and attended, from the runbook in [BRINGUP-M1.md#slot-b-marked-successful-by-hand](../../device/husky/BRINGUP-M1.md#slot-b-marked-successful-by-hand) (#252). Dry run by default; `--write` needs the dry run's eight slot bytes (`--expect`) and the codename typed or passed. It refuses another board, a devinfo layout other than the one recorded for this phone (3.15), a boot from slot A, and a storage guard that isn't holding. It makes devinfo and its boot LUN writable only for the one byte (the kernel won't write a partition of a read-only disk; for that moment the whole LUN is writable through its whole-disk node, which waits on the maintainer's ruling on #252), with a relock child that sets both read-only again if it dies, stops or hangs. The source is in `bootctl/`, not `src/`, so `bin/omamobile initramfs` never builds it into the boot image (test/all checks). No unit, hook or installer calls it. Apache-2.0, see `LICENSE.Apache-2.0` (the devinfo layout is Google's boot-control HAL); one source and one test (`test/bootctl`) with the tegu package | | `device.conf` | `/usr/share/omamobile/device.conf` | The descriptor, the same bytes as `device/husky/device.conf` | -`./build [DIR]` compiles `reboot-to` from this directory, `./install DESTDIR [DIR]` stages the files, and `test/all` checks the copies when it is run from the repository. +`./build [DIR]` compiles `reboot-to` and `omamobile-bootctl` from this directory, `./install DESTDIR [DIR]` stages the files, and `test/all` checks the copies when it is run from the repository. -Not in this package: the boot-success marker, the charger, cameras, and the slot-B image hook. Those stay out until each one has its own runbook. There is no lid drop-in: husky has no hinge. +Not in this package: a boot-success marker that runs at boot (marking is by hand, #252), the charger, cameras, and the slot-B image hook. Those stay out until each one has its own runbook. There is no lid drop-in: husky has no hinge. ## Firmware the phone needs diff --git a/packages/omamobile-device-husky/bootctl/bootctl-device.h b/packages/omamobile-device-husky/bootctl/bootctl-device.h new file mode 100644 index 000000000..c02412d4d --- /dev/null +++ b/packages/omamobile-device-husky/bootctl/bootctl-device.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: MIT */ +/* + * omamobile-bootctl's values for the Pixel 8 Pro (husky). The tool refuses a + * board or a devinfo layout other than these. The version is the one read on + * husky phones (device/husky/BATTERY-NOTES.md, "The cure exists": magic DEVI, + * version 3.15, three backups; issue #252: two owners' phones). test/all + * checks the codename and compatible against device.conf. + */ +#define BOOTCTL_CODENAME "husky" +#define BOOTCTL_COMPATIBLE "google,zuma-husky" +#define BOOTCTL_VER_MAJOR 3 +#define BOOTCTL_VER_MINOR 15 diff --git a/packages/omamobile-device-husky/bootctl/omamobile-bootctl.c b/packages/omamobile-device-husky/bootctl/omamobile-bootctl.c new file mode 100644 index 000000000..0e6dd393f --- /dev/null +++ b/packages/omamobile-device-husky/bootctl/omamobile-bootctl.c @@ -0,0 +1,1230 @@ +// SPDX-License-Identifier: Apache-2.0 +/* + * omamobile-bootctl (Pixel 8 Pro and Pixel 9a): mark slot B successful in + * the bootloader's "devinfo" partition, by hand and attended (#252). + * + * The same file is in omamobile-device-husky and omamobile-device-tegu; the + * only per-phone values are in bootctl/bootctl-device.h (codename, board + * compatible, and the devinfo layout version recorded for that phone). The + * 7 Pro's omamobile-bootctl (omamobile-device-cheetah) is a different file + * and is not changed by this one. + * + * The devinfo layout comes from Google's Pixel boot-control HAL: + * + * https://android.googlesource.com/device/google/gs-common + * tag android-14.0.0_r75 (commit ddbc3a43bcad1db516c114aca87df90d1780e728) + * bootctrl/aidl/DevInfo.h Copyright (C) 2021 The Android Open Source Project + * bootctrl/aidl/BootControl.cpp Copyright (C) 2023 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Modifications (Omarchy Mobile, 2026): a standalone C tool with one write, + * markBootSuccessful() for slot B (successful = 1), nothing else. It finds + * devinfo itself by PARTNAME, checks the storage guard and the phone, and + * opens and closes the read-write window itself: + * + * The kernel lets a partition be written only if its whole disk is + * writable too: bdev_read_only() is the partition's own BD_READ_ONLY flag + * OR the disk's (part0's) flag (include/linux/blkdev.h), and both + * blkdev_write_iter() and the BLKROGET ioctl and sysfs "ro" use it. So + * devinfo can't be written while its disk (the boot LUN, sdd) is read-only, + * and no ioctl makes the partition alone writable. Clearing the disk flag + * makes the whole-disk node writable, and through it every byte of the LUN, + * the other partitions (pinfo, blenv, mfg_data on husky) included, for as + * long as the window lasts: their own flags guard only their own nodes. + * The tool keeps that window to the one byte: disk rw (checked), the + * siblings' own flags checked (the only moment they can be read), devinfo + * rw, one byte written and read back, devinfo ro, disk ro, both checked. + * The job-control and termination signals are blocked, and a relock child + * sets both flags back the moment this process dies, and every 10 s from + * the moment the window opens for as long as it stays open (a stopped or + * hung process), until this process has closed the window itself. + * + * The source sits in bootctl/, not src/: bin/omamobile's initramfs builder + * compiles a device package's src/omamobile-bootctl.c into the boot image, + * and this tool belongs in the installed package only. + * + * Usage: + * omamobile-bootctl status + * omamobile-bootctl mark-b-successful (dry run) + * omamobile-bootctl mark-b-successful --write --expect "<8 bytes>" [--codename ] + * Never run from a unit, a hook or an installer. + */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* BLKROSET, BLKROGET (musl and glibc) */ + +#include "bootctl-device.h" + +#if !defined(BOOTCTL_CODENAME) || !defined(BOOTCTL_COMPATIBLE) || \ + !defined(BOOTCTL_VER_MAJOR) || !defined(BOOTCTL_VER_MINOR) +#error "bootctl-device.h must define the codename, compatible and devinfo version" +#endif + +/* From DevInfo.h ("definitions taken from ABL code") */ +#define DEVINFO_MAGIC 0x49564544u /* "DEVI" little-endian */ +#define DEVINFO_HDR 128 /* sizeof(devinfo_t) */ +#define OFF_MAGIC 0x00 +#define OFF_VER_MAJOR 0x04 +#define OFF_VER_MINOR 0x06 +#define OFF_SLOTS 0x30 /* slots[2], 4 bytes each, to 0x37 */ +#define SLOT_BYTES 8 +#define SLOT_RETRY 0 +#define SLOT_FLAGS 1 +#define FLAG_UNBOOTABLE 0x01 +#define FLAG_SUCCESSFUL 0x02 +#define FLAG_ACTIVE 0x04 +#define FLAG_FASTBOOT_OK 0x08 +/* The one byte this tool writes: slot B's flags. */ +#define OFF_B_FLAGS (OFF_SLOTS + 4 + SLOT_FLAGS) + +#define MAX_REGION (1024 * 1024) +#define ALIGN 4096 +#define RELOCK_TIMEOUT_MS 10000 + +/* The storage guard's allowlist (initramfs/init accepts no other names). */ +static const char *const allowlist[] = { + "boot_b", "init_boot_b", "vendor_boot_b", "vendor_kernel_boot_b", "dtbo_b", "userdata", NULL +}; + +static const char *argv0 = "omamobile-bootctl"; + +/* + * Test build (-DBOOTCTL_TEST, test/bootctl only): paths are read under + * $BOOTCTL_TEST_ROOT, block devices are files, and the read-only flags are + * files next to them that follow the kernel's rule (a partition is read-only + * if its own flag or its disk's flag is set). The production build has none + * of this: fixed paths, real ioctls, O_DIRECT reads. + */ +#ifdef BOOTCTL_TEST +static const char *root = ""; +static const char *fault = ""; /* comma-separated test faults */ +static int relock_timeout_ms = RELOCK_TIMEOUT_MS; +#define DIRECT 0 +#else +static const char *const root = ""; +static const int relock_timeout_ms = RELOCK_TIMEOUT_MS; +#define DIRECT O_DIRECT +#endif + +struct node { + char name[32]; /* sdd1 */ + char path[PATH_MAX]; /* /dev/sdd1 (under root in tests) */ + char sys[PATH_MAX]; /* /sys/block/sdd/sdd1 */ + dev_t rdev; +}; + +struct target { + struct node part; /* devinfo */ + struct node disk; /* its whole disk */ + struct node sib[64]; /* the disk's other partitions */ + int nsib; + char main_disk[32]; /* the disk that holds userdata */ +}; + +static void err(const char *fmt, ...) +{ + va_list ap; + fprintf(stderr, "%s: ", argv0); + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); + fputc('\n', stderr); +} + +/* + * snprintf that never truncates silently: a cut-off path could name another + * file, so the tool stops instead (inside the read-write window the relock + * child then sets both flags back, as for any other exit). + */ +static void xfmt(char *out, size_t n, const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + int r = vsnprintf(out, n, fmt, ap); + va_end(ap); + if (r < 0 || (size_t)r >= n) { + err("internal error: a path or name is too long"); + exit(1); + } +} + +static void rp(char *out, size_t n, const char *fmt, ...) +{ + char tmp[PATH_MAX]; + va_list ap; + va_start(ap, fmt); + int r = vsnprintf(tmp, sizeof(tmp), fmt, ap); + va_end(ap); + if (r < 0 || (size_t)r >= sizeof(tmp)) { + err("internal error: a path is too long"); + exit(1); + } + xfmt(out, n, "%s%s", root, tmp); +} + +/* Read a small text file into buf (NUL-terminated); returns length or -1. */ +static ssize_t slurp(const char *path, char *buf, size_t n) +{ + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) + return -1; + ssize_t r = read(fd, buf, n - 1); + close(fd); + if (r < 0) + return -1; + buf[r] = 0; + return r; +} + +#ifdef BOOTCTL_TEST +static int has_fault(const char *name) +{ + size_t n = strlen(name); + for (const char *p = fault; *p; ) { + const char *e = strchr(p, ','); + size_t l = e ? (size_t)(e - p) : strlen(p); + if (l == n && !strncmp(p, name, n)) + return 1; + p += l + (e ? 1 : 0); + } + return 0; +} +#endif + +/* ---- read-only flags ---------------------------------------------------- */ + +#ifdef BOOTCTL_TEST +static int own_flag(const char *path) +{ + char f[PATH_MAX + 4], b[8]; + xfmt(f, sizeof(f), "%s.ro", path); + if (slurp(f, b, sizeof(b)) < 0) + return -1; + return b[0] == '1'; +} + +/* The kernel's bdev_read_only(): own flag OR the disk's flag. */ +static int ro_get(const struct node *n, const struct node *disk) +{ + /* fault: a sibling whose node can't be opened once the window is open */ + if (has_fault("sdd3-unreadable-in-window") && disk && !strcmp(n->name, "sdd3") && + own_flag(disk->path) == 0) + return -1; + int o = own_flag(n->path); + if (o < 0) + return -1; + if (o || !disk || disk == n) + return o; + return own_flag(disk->path) != 0; +} + +static int ro_set(const struct node *n, int v) +{ + char f[PATH_MAX + 4]; + size_t pl = strlen(n->path); + int is_disk = pl && !isdigit((unsigned char)n->path[pl - 1]); + /* faults: a flag that silently doesn't change, as a stuck or lying device would */ + if ((v == 1 && !is_disk && has_fault("part-relock-ignored")) || + (v == 0 && is_disk && has_fault("disk-stays-ro"))) + return 0; + xfmt(f, sizeof(f), "%s/ro.log", root); + FILE *log = fopen(f, "a"); + if (log) { + fprintf(log, "%s %d\n", n->name, v); + fclose(log); + } + xfmt(f, sizeof(f), "%s.ro", n->path); + FILE *fp = fopen(f, "w"); + if (!fp) + return -1; + fprintf(fp, "%d\n", v); + return fclose(fp) ? -1 : 0; +} +#else +static int ro_get(const struct node *n, const struct node *disk) +{ + (void)disk; + int fd = open(n->path, O_RDONLY | O_CLOEXEC); + if (fd < 0) + return -1; + int v = 0; + int r = ioctl(fd, BLKROGET, &v); + close(fd); + return r ? -1 : v != 0; +} + +static int ro_set(const struct node *n, int v) +{ + int fd = open(n->path, O_RDONLY | O_CLOEXEC); + if (fd < 0) + return -1; + int r = ioctl(fd, BLKROSET, &v); + close(fd); + return r; +} +#endif + +/* ---- finding devinfo ---------------------------------------------------- */ + +static int partname(const char *sys, char *out, size_t n) +{ + char f[PATH_MAX + 8], buf[4096]; + xfmt(f, sizeof(f), "%s/uevent", sys); + if (slurp(f, buf, sizeof(buf)) < 0) + return -1; + for (char *l = strtok(buf, "\n"); l; l = strtok(NULL, "\n")) + if (!strncmp(l, "PARTNAME=", 9)) { + xfmt(out, n, "%s", l + 9); + return 0; + } + out[0] = 0; + return 0; +} + +static int fill_node(struct node *nd, const char *name, const char *sys) +{ + xfmt(nd->name, sizeof(nd->name), "%s", name); + xfmt(nd->sys, sizeof(nd->sys), "%s", sys); + rp(nd->path, sizeof(nd->path), "/dev/%s", name); + nd->rdev = 0; +#ifndef BOOTCTL_TEST + char f[PATH_MAX + 8], buf[32]; + unsigned ma, mi; + struct stat st; + xfmt(f, sizeof(f), "%s/dev", sys); + if (slurp(f, buf, sizeof(buf)) < 0 || sscanf(buf, "%u:%u", &ma, &mi) != 2) { + err("%s: no device number in sysfs", name); + return -1; + } + nd->rdev = makedev(ma, mi); + if (stat(nd->path, &st) || !S_ISBLK(st.st_mode) || st.st_rdev != nd->rdev) { + err("%s is not the block device sysfs names (%u:%u)", nd->path, ma, mi); + return -1; + } +#endif + return 0; +} + +static int is_part_dir(const char *sys) +{ + char f[PATH_MAX + 16]; + xfmt(f, sizeof(f), "%s/partition", sys); + return access(f, F_OK) == 0; +} + +static int find_devinfo(struct target *t) +{ + char sysblock[PATH_MAX], dsys[PATH_MAX * 2], psys[PATH_MAX * 3], pn[64]; + char devinfo_disk[32] = ""; + int found = 0, userdata = 0; + memset(t, 0, sizeof(*t)); + rp(sysblock, sizeof(sysblock), "/sys/block"); + DIR *d = opendir(sysblock); + if (!d) { + err("can't list %s: %s", sysblock, strerror(errno)); + return -1; + } + struct dirent *e; + while ((e = readdir(d))) { + if (strncmp(e->d_name, "sd", 2)) + continue; + xfmt(dsys, sizeof(dsys), "%s/%s", sysblock, e->d_name); + DIR *dd = opendir(dsys); + if (!dd) + continue; + struct dirent *p; + while ((p = readdir(dd))) { + if (strncmp(p->d_name, e->d_name, strlen(e->d_name)) || !p->d_name[strlen(e->d_name)]) + continue; + xfmt(psys, sizeof(psys), "%s/%s", dsys, p->d_name); + if (!is_part_dir(psys) || partname(psys, pn, sizeof(pn))) + continue; + if (!strcmp(pn, "devinfo")) { + if (found++ == 0) { + xfmt(devinfo_disk, sizeof(devinfo_disk), "%s", e->d_name); + if (fill_node(&t->part, p->d_name, psys) || + fill_node(&t->disk, e->d_name, dsys)) { + closedir(dd); + closedir(d); + return -1; + } + } + } else if (!strcmp(pn, "userdata")) { + userdata++; + xfmt(t->main_disk, sizeof(t->main_disk), "%s", e->d_name); + } + } + closedir(dd); + } + closedir(d); + if (found != 1) { + err(found ? "%d partitions are named devinfo; refusing" : "no partition is named devinfo", found); + return -1; + } + if (userdata != 1) { + err("expected one userdata partition, found %d; is the storage layout this phone's?", userdata); + return -1; + } + if (!strcmp(devinfo_disk, t->main_disk)) { + err("devinfo is on the main LUN (%s); this tool knows only devinfo on a boot LUN", devinfo_disk); + return -1; + } + /* The disk's other partitions, whose own flags are checked in the window. */ + xfmt(dsys, sizeof(dsys), "%s/%s", sysblock, t->disk.name); + DIR *dd = opendir(dsys); + if (!dd) + return -1; + while ((e = readdir(dd))) { + if (strncmp(e->d_name, t->disk.name, strlen(t->disk.name)) || !e->d_name[strlen(t->disk.name)] || + !strcmp(e->d_name, t->part.name)) + continue; + xfmt(psys, sizeof(psys), "%s/%s", dsys, e->d_name); + if (!is_part_dir(psys)) + continue; + if (t->nsib == (int)(sizeof(t->sib) / sizeof(t->sib[0])) || + fill_node(&t->sib[t->nsib++], e->d_name, psys)) { + closedir(dd); + err("can't list the partitions of %s", t->disk.name); + return -1; + } + } + closedir(dd); + return 0; +} + +/* ---- checks ------------------------------------------------------------- */ + +static int check_phone(void) +{ + char f[PATH_MAX], buf[512]; +#ifndef BOOTCTL_TEST + if (geteuid() != 0) { + err("run as root"); + return -1; + } +#endif + rp(f, sizeof(f), "/sys/firmware/devicetree/base/compatible"); + if (slurp(f, buf, sizeof(buf)) < 0) { + err("can't read the board's compatible string"); + return -1; + } + if (strcmp(buf, BOOTCTL_COMPATIBLE)) { /* the first string, up to its NUL */ + err("this board is \"%s\", not %s (\"%s\"); this build is for %s only", + buf, BOOTCTL_CODENAME, BOOTCTL_COMPATIBLE, BOOTCTL_CODENAME); + return -1; + } + return 0; +} + +static char booted_slot(void) +{ + char f[PATH_MAX], buf[16384]; + rp(f, sizeof(f), "/proc/bootconfig"); + if (slurp(f, buf, sizeof(buf)) < 0) + return 0; + for (char *l = strtok(buf, "\n"); l; l = strtok(NULL, "\n")) { + if (!strcmp(l, "androidboot.slot_suffix = \"_a\"")) + return 'a'; + if (!strcmp(l, "androidboot.slot_suffix = \"_b\"")) + return 'b'; + } + return 0; +} + +static int same_file(const struct stat *st, const struct node *n) +{ +#ifdef BOOTCTL_TEST + struct stat ns; + return !stat(n->path, &ns) && ns.st_dev == st->st_dev && ns.st_ino == st->st_ino; +#else + return S_ISBLK(st->st_mode) && st->st_rdev == n->rdev; +#endif +} + +/* devinfo not mounted, held, or open for writing by anyone else. */ +static int check_unused(const struct target *t) +{ + char f[PATH_MAX], line[4096], src[PATH_MAX]; + int bad = 0; + + rp(f, sizeof(f), "/proc/self/mountinfo"); + FILE *fp = fopen(f, "r"); + if (!fp) { + err("can't read %s", f); + return -1; + } + xfmt(src, sizeof(src), "/dev/%s", t->part.name); + while (fgets(line, sizeof(line), fp)) { + unsigned ma = 0, mi = 0; + char *sep = strstr(line, " - "); + char fstype[64] = "", source[PATH_MAX] = ""; + if (sscanf(line, "%*s %*s %u:%u", &ma, &mi) != 2 || !sep) + continue; + sscanf(sep + 3, "%63s %4095s", fstype, source); + if (!strcmp(source, src) || (t->part.rdev && makedev(ma, mi) == t->part.rdev)) { + err("devinfo (%s) is mounted; refusing", src); + bad = 1; + } + } + fclose(fp); + + /* Nothing stacked on the disk, devinfo or a sibling (dm, md, loop...). */ + const struct node *held[2 + (int)(sizeof(t->sib) / sizeof(t->sib[0]))]; + int nh = 0; + held[nh++] = &t->disk; + held[nh++] = &t->part; + for (int i = 0; i < t->nsib; i++) + held[nh++] = &t->sib[i]; + for (int i = 0; i < nh; i++) { + xfmt(f, sizeof(f), "%s/holders", held[i]->sys); + DIR *d = opendir(f); + if (!d) + continue; + struct dirent *e; + while ((e = readdir(d))) + if (e->d_name[0] != '.') { + err("%s is held by %s; refusing", held[i]->name, e->d_name); + bad = 1; + } + closedir(d); + } + + /* Any process with the disk or one of its partitions open for writing. */ + DIR *d = opendir("/proc"); + if (!d) + return -1; + struct dirent *pe; + pid_t self = getpid(); + while ((pe = readdir(d))) { + if (!isdigit((unsigned char)pe->d_name[0]) || atoi(pe->d_name) == self) + continue; + char fdd[PATH_MAX]; + xfmt(fdd, sizeof(fdd), "/proc/%s/fd", pe->d_name); + DIR *fds = opendir(fdd); + if (!fds) + continue; + struct dirent *fe; + while ((fe = readdir(fds))) { + if (fe->d_name[0] == '.') + continue; + char lp[PATH_MAX * 2], info[PATH_MAX * 2], buf[1024]; + struct stat st; + xfmt(lp, sizeof(lp), "%s/%s", fdd, fe->d_name); + if (stat(lp, &st)) + continue; + int hit = same_file(&st, &t->part) || same_file(&st, &t->disk); + for (int i = 0; !hit && i < t->nsib; i++) + hit = same_file(&st, &t->sib[i]); + if (!hit) + continue; + xfmt(info, sizeof(info), "/proc/%s/fdinfo/%s", pe->d_name, fe->d_name); + char *fl; + unsigned long flags = 0; + if (slurp(info, buf, sizeof(buf)) >= 0 && (fl = strstr(buf, "flags:"))) + flags = strtoul(fl + 6, NULL, 8); + if ((flags & O_ACCMODE) != O_RDONLY) { + err("process %s has %s or one of its partitions open for writing; refusing", + pe->d_name, t->disk.name); + bad = 1; + } + } + closedir(fds); + } + closedir(d); + return bad ? -1 : 0; +} + +static int in_allowlist(const char *name) +{ + for (int i = 0; allowlist[i]; i++) + if (!strcmp(name, allowlist[i])) + return 1; + return 0; +} + +/* + * The storage guard as the initramfs leaves it: the main LUN's whole-disk + * node gone (or mode 0000), every other disk and every partition outside the + * allowlist read-only, devinfo and its disk among them. + */ +static int check_guard(const struct target *t) +{ + char f[PATH_MAX], dsys[PATH_MAX * 2], psys[PATH_MAX * 3], pn[64]; + struct stat st; + int bad = 0; + + rp(f, sizeof(f), "/dev/%s", t->main_disk); + if (!stat(f, &st) && (st.st_mode & 07777)) { + err("the main LUN's whole-disk node %s is usable (mode %o); the storage guard is not holding", + f, st.st_mode & 07777); + bad = 1; + } + rp(f, sizeof(f), "/sys/block"); + DIR *d = opendir(f); + if (!d) + return -1; + struct dirent *e; + while ((e = readdir(d))) { + if (strncmp(e->d_name, "sd", 2)) + continue; + struct node disk; + xfmt(dsys, sizeof(dsys), "%s/%s", f, e->d_name); + xfmt(disk.name, sizeof(disk.name), "%s", e->d_name); + rp(disk.path, sizeof(disk.path), "/dev/%s", e->d_name); + int main_disk = !strcmp(e->d_name, t->main_disk); + if (!main_disk && ro_get(&disk, NULL) != 1) { + err("%s is not read-only; the storage guard is not holding", e->d_name); + bad = 1; + } + DIR *dd = opendir(dsys); + if (!dd) + continue; + struct dirent *p; + while ((p = readdir(dd))) { + if (strncmp(p->d_name, e->d_name, strlen(e->d_name)) || !p->d_name[strlen(e->d_name)]) + continue; + xfmt(psys, sizeof(psys), "%s/%s", dsys, p->d_name); + if (!is_part_dir(psys) || partname(psys, pn, sizeof(pn))) + continue; + if (main_disk && in_allowlist(pn)) + continue; + struct node part; + xfmt(part.name, sizeof(part.name), "%s", p->d_name); + rp(part.path, sizeof(part.path), "/dev/%s", p->d_name); + if (ro_get(&part, &disk) != 1) { + err("%s (%s) is not read-only; the storage guard is not holding", p->d_name, pn); + bad = 1; + } + } + closedir(dd); + } + closedir(d); + return bad ? -1 : 0; +} + +/* ---- devinfo contents --------------------------------------------------- */ + +static uint32_t rd32(const uint8_t *p) { return p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24; } +static uint16_t rd16(const uint8_t *p) { return p[0] | p[1] << 8; } + +/* The whole partition, read past the page cache (O_DIRECT) on the phone. */ +static uint8_t *read_image(const struct node *n, size_t *len) +{ + uint8_t *buf = NULL; + int fd = open(n->path, O_RDONLY | O_CLOEXEC | DIRECT); + if (fd < 0) { + err("open %s: %s", n->path, strerror(errno)); + return NULL; + } + if (posix_memalign((void **)&buf, ALIGN, MAX_REGION + ALIGN)) { + close(fd); + return NULL; + } + size_t got = 0; + for (;;) { + ssize_t r = pread(fd, buf + got, MAX_REGION + ALIGN - got, got); + if (r < 0 && errno == EINTR) + continue; + if (r < 0) { + err("read %s: %s", n->path, strerror(errno)); + goto fail; + } + if (r == 0) + break; + got += r; + if (got > MAX_REGION) { + err("%s is larger than %d bytes; is this really devinfo?", n->path, MAX_REGION); + goto fail; + } + } + close(fd); + if (got < DEVINFO_HDR) { + err("%s: only %zu bytes", n->path, got); + free(buf); + return NULL; + } + *len = got; + return buf; +fail: + close(fd); + free(buf); + return NULL; +} + +static int check_layout(const uint8_t *d) +{ + uint32_t magic = rd32(d + OFF_MAGIC); + unsigned maj = rd16(d + OFF_VER_MAJOR), min = rd16(d + OFF_VER_MINOR); + if (magic != DEVINFO_MAGIC) { + err("bad magic 0x%08x (want 0x%08x \"DEVI\"); refusing", magic, DEVINFO_MAGIC); + return -1; + } + if (maj != BOOTCTL_VER_MAJOR || min != BOOTCTL_VER_MINOR) { + err("devinfo version %u.%u is not the %u.%u recorded for %s; refusing", + maj, min, BOOTCTL_VER_MAJOR, BOOTCTL_VER_MINOR, BOOTCTL_CODENAME); + return -1; + } + return 0; +} + +static void print_bytes(const char *label, const uint8_t *d) +{ + printf("%s 0x30-0x37:", label); + for (int i = 0; i < SLOT_BYTES; i++) + printf(" %02x", d[OFF_SLOTS + i]); + printf("\n"); +} + +static void print_slots(const uint8_t *d) +{ + for (int i = 0; i < 2; i++) { + const uint8_t *s = d + OFF_SLOTS + 4 * i; + uint8_t f = s[SLOT_FLAGS]; + printf("slot %c: retry-count %u, active %s, successful %s, unbootable %s, fastboot-ok %s\n", + 'a' + i, s[SLOT_RETRY], f & FLAG_ACTIVE ? "yes" : "no", + f & FLAG_SUCCESSFUL ? "yes" : "no", f & FLAG_UNBOOTABLE ? "yes" : "no", + f & FLAG_FASTBOOT_OK ? "yes" : "no"); + } +} + +/* ---- the read-write window ---------------------------------------------- */ + +static int relock(const struct target *t) +{ + int ok = 1; + /* devinfo first: while its disk is still writable its own flag reads back */ + if (ro_set(&t->part, 1) || ro_get(&t->part, &t->disk) != 1) + ok = 0; + if (ro_set(&t->disk, 1) || ro_get(&t->disk, NULL) != 1) + ok = 0; + return ok ? 0 : -1; +} + +/* + * The relock child. It holds the read end of a pipe whose write end only the + * parent has. Before the window opens it waits without a timeout (nothing is + * writable yet). The parent writes 'O' just before it clears the first flag; + * from then on the child sets devinfo and its disk read-only every + * RELOCK_TIMEOUT_MS for as long as the pipe stays open (a stopped or hung + * parent: its later steps then fail closed), and once more when the pipe + * closes, whether the parent finished, crashed or was killed. It ignores the + * terminal's signals (blocked before the fork), so ^C on the process group + * can't take it with the parent. + */ +static int child_relock(const struct target *t) +{ +#ifdef BOOTCTL_TEST + if (has_fault("no-child-relock")) /* the parent must relock alone */ + return 0; +#endif + return relock(t); +} + +static void relocker(const struct target *t, int rfd) +{ + int armed = 0, ok = 1; + for (;;) { + struct pollfd pf = { .fd = rfd, .events = POLLIN }; + int r = poll(&pf, 1, armed ? relock_timeout_ms : -1); + if (r < 0 && errno == EINTR) + continue; + if (r == 0) { /* window open too long: close it, re-arm */ + if (child_relock(t)) + ok = 0; + continue; + } + char c; + ssize_t n = read(rfd, &c, 1); + if (n < 0 && errno == EINTR) + continue; + if (n == 1 && c == 'O') { + armed = 1; + continue; + } + break; /* EOF: the parent is done or gone */ + } + if (child_relock(t)) + ok = 0; +#ifdef BOOTCTL_TEST + if (has_fault("child-fails")) + ok = 0; +#endif + _exit(ok ? 0 : 1); +} + +static pid_t start_relocker(const struct target *t, int *wfd) +{ + int p[2]; +#ifdef BOOTCTL_TEST + if (has_fault("fork-fails")) + return -1; +#endif + if (pipe2(p, O_CLOEXEC)) + return -1; + pid_t pid = fork(); + if (pid < 0) { + close(p[0]); + close(p[1]); + return -1; + } + if (pid == 0) { + close(p[1]); + relocker(t, p[0]); + } + close(p[0]); + *wfd = p[1]; + return pid; +} + +/* The child must be alive before every step that opens anything further. */ +static int child_alive(pid_t child, int *reaped, int *st) +{ + if (*reaped) + return 0; + pid_t r = waitpid(child, st, WNOHANG); + if (r == child) { + *reaped = 1; + return 0; + } + return r == 0; +} + +static int write_at(const struct target *t, const uint8_t *buf, size_t len, off_t off) +{ +#ifdef BOOTCTL_TEST + /* the kernel refuses a write to a read-only partition (blkdev_write_iter) */ + if (ro_get(&t->part, &t->disk) != 0) { + errno = EPERM; + return -1; + } + if (has_fault("write-fails")) { + errno = EIO; + return -1; + } + if (has_fault("restore-noop") && off == 0 && len > 2) + return 0; /* the restore "succeeds" without landing */ +#endif + int fd = open(t->part.path, O_WRONLY | O_DSYNC | O_CLOEXEC); + if (fd < 0) + return -1; + ssize_t w = pwrite(fd, buf, len, off); + int e = errno; + if (w == (ssize_t)len && fdatasync(fd) == 0) { + close(fd); + return 0; + } + close(fd); + errno = w < 0 ? e : EIO; + return -1; +} + +#ifdef BOOTCTL_TEST +static void test_fault(const char *where) +{ + if (has_fault(where)) + raise(SIGKILL); + if (!strcmp(where, "kill-before-write") && has_fault("hang-in-window")) + sleep(60); +} + +/* Someone else changes devinfo inside the window (test only). */ +static void test_change_under(const struct target *t) +{ + if (!has_fault("change-under")) + return; + int fd = open(t->part.path, O_WRONLY); + uint8_t x = 0x5a; + if (fd >= 0) { + if (pwrite(fd, &x, 1, 0x100) != 1) + err("test: change-under failed"); + close(fd); + } +} +#else +#define test_fault(x) ((void)0) +#define test_change_under(t) ((void)0) +#endif + +/* + * Returns 0 written and verified, 3 failed with devinfo as it was before, + * 4 failed and devinfo may differ, 5 the read-only flags could not be + * restored (the loudest failure: the guard has a hole until a reboot). + */ +static int window(const struct target *t, const uint8_t *orig, size_t len, uint8_t newval) +{ + int rc = 3, wfd = -1, reaped = 0, st = 0; + uint8_t *after = NULL, *want = NULL, *again = NULL, byte = newval; + size_t alen; + sigset_t block, old; +#ifdef BOOTCTL_TEST + uint8_t bad[2] = { (uint8_t)(orig[OFF_B_FLAGS - 1] ^ 0x01), newval }; +#endif + + sigemptyset(&block); + sigaddset(&block, SIGINT); + sigaddset(&block, SIGTERM); + sigaddset(&block, SIGHUP); + sigaddset(&block, SIGQUIT); + sigaddset(&block, SIGTSTP); + sigaddset(&block, SIGPIPE); + sigprocmask(SIG_BLOCK, &block, &old); + + pid_t child = start_relocker(t, &wfd); + if (child < 0) { + err("can't start the relock child; nothing written"); + sigprocmask(SIG_SETMASK, &old, NULL); + return 3; + } +#ifdef BOOTCTL_TEST + if (has_fault("stop-before-open")) + raise(SIGSTOP); +#endif + /* The child's timer runs from here, as long as the window stays open. */ + if (write(wfd, "O", 1) != 1 || !child_alive(child, &reaped, &st)) { + err("the relock child is not running; nothing written"); + goto close_window; + } +#ifdef BOOTCTL_TEST + if (has_fault("stop-after-open")) + raise(SIGSTOP); +#endif + + /* 1. The disk: the kernel won't write a partition of a read-only disk. */ + if (ro_set(&t->disk, 0) || ro_get(&t->disk, NULL) != 0) { + err("%s did not become writable; nothing written", t->disk.name); + goto close_window; + } + /* 2. With the disk flag clear, each partition reads its own flag: all set. */ + for (int i = 0; i < t->nsib; i++) + if (ro_get(&t->sib[i], &t->disk) != 1) { + err("%s's own read-only flag is clear or unreadable: clearing %s's would expose it; refusing", + t->sib[i].name, t->disk.name); + goto close_window; + } + if (ro_get(&t->part, &t->disk) != 1) { + err("devinfo's own read-only flag was already clear; the guard did not set it; refusing"); + goto close_window; + } + /* 3. devinfo itself. */ + if (!child_alive(child, &reaped, &st)) { + err("the relock child is gone; nothing written"); + goto close_window; + } + if (ro_set(&t->part, 0) || ro_get(&t->part, &t->disk) != 0) { + err("can't make devinfo writable: %s", strerror(errno)); + goto close_window; + } + test_change_under(t); + /* 4. Nothing moved since the checks. */ + again = read_image(&t->part, &alen); + if (!again || alen != len || memcmp(again, orig, len)) { + err("devinfo changed since it was checked; nothing written"); + free(again); + goto close_window; + } + free(again); + test_fault("kill-before-write"); + + /* 5. The one byte (the kernel writes the 4 KiB block that holds it). */ + want = malloc(len); + if (!want) + goto close_window; + memcpy(want, orig, len); + want[OFF_B_FLAGS] = newval; + if (!child_alive(child, &reaped, &st)) { + err("the relock child is gone; nothing written"); + goto close_window; + } +#ifdef BOOTCTL_TEST + if (has_fault("corrupt-write")) { /* a stray change next to ours */ + if (write_at(t, bad, 2, OFF_B_FLAGS - 1)) + goto write_failed; + } else +#endif + if (write_at(t, &byte, 1, OFF_B_FLAGS)) { + goto write_failed; + } + test_fault("kill-after-write"); + + /* 6. Read back past the cache: everything as before but that byte. */ + after = read_image(&t->part, &alen); + if (after && alen == len && !memcmp(after, want, len)) { + rc = 0; + goto close_window; + } + err("VERIFY FAILED: devinfo does not read back as written; restoring the original"); + free(after); + after = NULL; + if (write_at(t, orig, len, 0)) { + err("RESTORE FAILED: %s; devinfo may differ from the backup", strerror(errno)); + rc = 4; + goto close_window; + } + after = read_image(&t->part, &alen); + if (after && alen == len && !memcmp(after, orig, len)) { + err("restored: devinfo reads back as it was before"); + rc = 3; + } else { + err("RESTORE FAILED: devinfo does not read back as before; restore it from the backup"); + rc = 4; + } + goto close_window; + +write_failed: + err("write failed: %s", strerror(errno)); + after = read_image(&t->part, &alen); + rc = (after && alen == len && !memcmp(after, orig, len)) ? 3 : 4; + if (rc == 4) + err("devinfo no longer reads as before; restore it from the backup"); + +close_window: + /* 7. Read-only again, devinfo then the disk, each read back; then the child. */ + if (relock(t)) { + err("FAILED to set devinfo or %s read-only again; reboot to restore the guard", t->disk.name); + rc = 5; + } + close(wfd); + if (!reaped) + while (waitpid(child, &st, 0) < 0 && errno == EINTR) + ; + if (!WIFEXITED(st) || WEXITSTATUS(st)) { + err("the relock child failed; reboot to restore the guard"); + rc = 5; + } + sigprocmask(SIG_SETMASK, &old, NULL); + free(after); + free(want); + return rc; +} + +/* ---- commands ----------------------------------------------------------- */ + +static int parse_expect(const char *s, uint8_t out[SLOT_BYTES]) +{ + int n = 0, half = -1; + for (; *s; s++) { + if (*s == ' ' || *s == ':' || *s == '\t') + continue; + if (!isxdigit((unsigned char)*s) || n == SLOT_BYTES) + return -1; + int v = isdigit((unsigned char)*s) ? *s - '0' : (tolower((unsigned char)*s) - 'a' + 10); + if (half < 0) { + half = v; + } else { + out[n++] = half << 4 | v; + half = -1; + } + } + return n == SLOT_BYTES && half < 0 ? 0 : -1; +} + +static int read_codename(char *out, size_t n) +{ + FILE *tty = fopen("/dev/tty", "r+"); + if (!tty) + return -1; + fprintf(tty, "This writes devinfo on this phone. Type its codename (%s) to go on: ", BOOTCTL_CODENAME); + fflush(tty); + if (!fgets(out, n, tty)) { + fclose(tty); + return -1; + } + fclose(tty); + out[strcspn(out, "\r\n")] = 0; + return 0; +} + +static int prepare(struct target *t, uint8_t **img, size_t *len) +{ + if (check_phone() || find_devinfo(t)) + return -1; + printf("omamobile-bootctl for %s: devinfo is %s on %s\n", BOOTCTL_CODENAME, t->part.name, t->disk.name); + *img = read_image(&t->part, len); + if (!*img || check_layout(*img)) + return -1; + printf("devinfo version %u.%u (the layout recorded for %s)\n", + BOOTCTL_VER_MAJOR, BOOTCTL_VER_MINOR, BOOTCTL_CODENAME); + return 0; +} + +static int cmd_status(void) +{ + struct target t; + uint8_t *img = NULL; + size_t len; + if (prepare(&t, &img, &len)) { + free(img); + return 1; + } + char s = booted_slot(); + printf("booted from slot %c\n", s ? s : '?'); + print_bytes("bytes", img); + print_slots(img); + int g = check_guard(&t); + printf("storage guard: %s\n", g ? "NOT as expected (see above)" : "holding"); + free(img); + return 0; +} + +static int cmd_mark(int do_write, const char *expect, const char *codename) +{ + struct target t; + uint8_t *img = NULL, *after = NULL, exp[SLOT_BYTES], fb, nv; + size_t len, alen; + int rc = 1; + char typed[64] = ""; + + if (do_write && (!expect || parse_expect(expect, exp))) { + err("--write needs --expect with the eight bytes the dry run printed"); + return 2; + } + if (prepare(&t, &img, &len)) + goto out; + if (booted_slot() != 'b') { + err("this boot is not from slot b; mark slot b only from a boot of slot b"); + goto out; + } + if (check_guard(&t) || check_unused(&t)) + goto out; + + fb = img[OFF_B_FLAGS]; + print_bytes("before", img); + print_slots(img); + if (!(fb & FLAG_ACTIVE)) { + err("slot b is not the active slot; refusing"); + goto out; + } + if (fb & FLAG_UNBOOTABLE) { + err("slot b is marked unbootable; refusing"); + goto out; + } + if (fb & FLAG_SUCCESSFUL) { + printf("slot b is already marked successful; nothing to write\n"); + rc = 0; + goto out; + } + nv = fb | FLAG_SUCCESSFUL; + printf("planned: byte 0x%02x %02x -> %02x (slot b successful), nothing else\n", OFF_B_FLAGS, fb, nv); + + if (!do_write) { + printf("dry run: nothing written. To write, after the runbook's backup:\n" + " omamobile-bootctl mark-b-successful --write --codename %s --expect \"", BOOTCTL_CODENAME); + for (int i = 0; i < SLOT_BYTES; i++) + printf("%s%02x", i ? " " : "", img[OFF_SLOTS + i]); + printf("\"\n"); + rc = 0; + goto out; + } + if (memcmp(exp, img + OFF_SLOTS, SLOT_BYTES)) { + err("the slot bytes are not the ones given with --expect; run the dry run again"); + goto out; + } + if (codename) + xfmt(typed, sizeof(typed), "%s", codename); + else if (read_codename(typed, sizeof(typed))) + typed[0] = 0; + if (strcmp(typed, BOOTCTL_CODENAME)) { + err("codename \"%s\" is not %s; nothing written", typed, BOOTCTL_CODENAME); + goto out; + } +#ifdef BOOTCTL_TEST + if (has_fault("hold-after-codename")) { /* stands in for a slow prompt */ + char f[PATH_MAX]; + rp(f, sizeof(f), "/at-prompt"); + close(open(f, O_CREAT | O_WRONLY, 0644)); + rp(f, sizeof(f), "/go"); + for (int i = 0; i < 200 && access(f, F_OK); i++) + usleep(50000); + } +#endif + /* The checks again, right before the window: the prompt can take minutes. */ + if (check_guard(&t) || check_unused(&t)) { + err("the storage guard or a user of the LUN changed since the checks; nothing written"); + goto out; + } + + rc = window(&t, img, len, nv); + after = read_image(&t.part, &alen); + if (after) + print_bytes("after ", after); + if (rc == 0) { + printf("slot b marked successful: written, read back, devinfo and %s read-only again\n", t.disk.name); + } +out: + free(after); + free(img); + return rc; +} + +static int usage(void) +{ + fprintf(stderr, + "usage: %s status\n" + " %s mark-b-successful (dry run, writes nothing)\n" + " %s mark-b-successful --write --expect \"\" [--codename %s]\n" + "Build for %s, devinfo %u.%u. Attended use only, from the device plan's runbook.\n", + argv0, argv0, argv0, BOOTCTL_CODENAME, BOOTCTL_CODENAME, BOOTCTL_VER_MAJOR, BOOTCTL_VER_MINOR); + return 2; +} + +int main(int argc, char **argv) +{ + int do_write = 0; + const char *expect = NULL, *codename = NULL, *cmd = NULL; + +#ifdef BOOTCTL_TEST + if (getenv("BOOTCTL_TEST_ROOT")) + root = getenv("BOOTCTL_TEST_ROOT"); + if (getenv("BOOTCTL_TEST_FAULT")) + fault = getenv("BOOTCTL_TEST_FAULT"); + if (getenv("BOOTCTL_TEST_RELOCK_MS")) + relock_timeout_ms = atoi(getenv("BOOTCTL_TEST_RELOCK_MS")); +#endif + setvbuf(stdout, NULL, _IOLBF, 0); + for (int i = 1; i < argc; i++) { + if (!strcmp(argv[i], "--write")) + do_write = 1; + else if (!strcmp(argv[i], "--expect") && i + 1 < argc) + expect = argv[++i]; + else if (!strcmp(argv[i], "--codename") && i + 1 < argc) + codename = argv[++i]; + else if (!cmd && argv[i][0] != '-') + cmd = argv[i]; + else + return usage(); + } + if (!cmd) + return usage(); + if (!strcmp(cmd, "status") && !do_write && !expect && !codename) + return cmd_status(); + if (!strcmp(cmd, "mark-b-successful")) + return cmd_mark(do_write, expect, codename); + return usage(); +} diff --git a/packages/omamobile-device-husky/build b/packages/omamobile-device-husky/build index 5dacf6c60..22abd91d0 100755 --- a/packages/omamobile-device-husky/build +++ b/packages/omamobile-device-husky/build @@ -1,8 +1,9 @@ #!/bin/bash # SPDX-License-Identifier: MIT -# Compile reboot-to into BUILDDIR (default: build). +# Compile reboot-to and omamobile-bootctl into BUILDDIR (default: build). set -euo pipefail cd -- "$(dirname -- "${BASH_SOURCE[0]}")" out=${1:-build} mkdir -p "$out" ${CC:-cc} ${CFLAGS:--O2} -Wall -Wextra -o "$out/reboot-to" src/reboot-to.c ${LDFLAGS:-} +${CC:-cc} ${CFLAGS:--O2} -Wall -Wextra -Ibootctl -o "$out/omamobile-bootctl" bootctl/omamobile-bootctl.c ${LDFLAGS:-} diff --git a/packages/omamobile-device-husky/install b/packages/omamobile-device-husky/install index 790758918..7e6b049cc 100755 --- a/packages/omamobile-device-husky/install +++ b/packages/omamobile-device-husky/install @@ -1,7 +1,9 @@ #!/bin/bash # SPDX-License-Identifier: MIT # Stage omamobile-device-husky into DESTDIR. Nothing is enabled that would -# mark a slot successful or start the radio, the charger, or a camera. +# mark a slot successful or start the radio, the charger, or a camera: +# omamobile-bootctl is installed for the owner to run by hand (#252), and no +# unit, hook or script calls it. # ./install DESTDIR [BUILDDIR] set -euo pipefail cd -- "$(dirname -- "${BASH_SOURCE[0]}")" @@ -9,6 +11,7 @@ destination=${1:?Usage: ./install DESTDIR [BUILDDIR]} build=${2:-build} [[ $destination == /* && $destination != "/" ]] || { echo "Use an absolute staging directory" >&2; exit 1; } install -Dm755 "$build/reboot-to" "$destination/usr/bin/reboot-to" +install -Dm755 "$build/omamobile-bootctl" "$destination/usr/bin/omamobile-bootctl" install -Dm644 vendor/udev/rules.d/10-omamobile-storage.rules \ "$destination/usr/lib/udev/rules.d/10-omamobile-storage.rules" install -Dm644 vendor/systemd/network/20-usb-gadget.network \ @@ -66,4 +69,5 @@ install -Dm644 device.conf \ install -Dm644 etc/omamobile-mirrorlist \ "$destination/etc/pacman.d/omamobile-mirrorlist" install -Dm644 LICENSE "$destination/usr/share/licenses/omamobile-device-husky/LICENSE" +install -Dm644 LICENSE.Apache-2.0 "$destination/usr/share/licenses/omamobile-device-husky/LICENSE.Apache-2.0" install -Dm644 version "$destination/usr/share/omamobile/device-husky/version" diff --git a/packages/omamobile-device-husky/test/all b/packages/omamobile-device-husky/test/all index 1760d8b79..8524bea02 100755 --- a/packages/omamobile-device-husky/test/all +++ b/packages/omamobile-device-husky/test/all @@ -63,12 +63,47 @@ if [[ -f ../../device/husky/device.conf ]]; then pass "device.conf matches the descriptor" fi +# omamobile-bootctl (#252): one source and one test in the husky and tegu +# packages, byte for byte; the per-phone values are in bootctl/bootctl-device.h. +# It is installed for the owner to run by hand: no unit, hook or script here +# may call it, and nothing enables it. +other=../omamobile-device-tegu +if [[ -d $other ]]; then + cmp -s bootctl/omamobile-bootctl.c "$other/bootctl/omamobile-bootctl.c" \ + || fail "omamobile-bootctl.c drifted from the tegu package" + cmp -s test/bootctl "$other/test/bootctl" || fail "test/bootctl drifted from the tegu package" + pass "omamobile-bootctl.c and test/bootctl match the tegu package" +fi +if [[ -f ../omamobile-device-cheetah/LICENSE.Apache-2.0 ]]; then + cmp -s LICENSE.Apache-2.0 ../omamobile-device-cheetah/LICENSE.Apache-2.0 || fail "LICENSE.Apache-2.0 drifted from the cheetah package" +fi +grep -qx '#define BOOTCTL_CODENAME[[:space:]]*"husky"' bootctl/bootctl-device.h || fail "bootctl-device.h is not husky's" +compat=$(sed -n 's/^COMPATIBLE="\(.*\)"$/\1/p' device.conf) +grep -qx "#define BOOTCTL_COMPATIBLE[[:space:]]*\"$compat\"" bootctl/bootctl-device.h \ + || fail "bootctl-device.h's compatible is not device.conf's ($compat)" +pass "bootctl-device.h names husky and device.conf's compatible" +grep -rlw 'omamobile-bootctl' vendor bin *.install 2>/dev/null && fail "a unit, hook or script calls omamobile-bootctl" +pass "nothing in the package calls omamobile-bootctl" +# bin/omamobile's initramfs builder compiles packages//src/omamobile-bootctl.c +# (and tools/stage-boot-files hashes src/) into the boot image: this tool +# belongs in the installed package only, so nothing may sit where they look. +[[ ! -e src/omamobile-bootctl.c ]] || fail "src/omamobile-bootctl.c would be built into the initramfs" +if [[ -f ../../bin/omamobile ]]; then + while read -r probe; do + [[ -z $probe || ! -e $probe ]] || fail "bin/omamobile would build $probe into the initramfs" + done < <(grep -oh 'packages/\$DEV_PACKAGE/[A-Za-z0-9_./-]*' ../../bin/omamobile | sed 's#^packages/\$DEV_PACKAGE/##' | sort -u) +fi +! ls src/ 2>/dev/null | grep -c bootctl >/dev/null || fail "a bootctl file under src/, where the boot-file tools look" +pass "the tool is outside the paths the initramfs builder and stage-boot-files read" +test/bootctl --mutations || fail "test/bootctl" + ./build "$tmp/build" || fail "reboot-to compiles" -[[ -x $tmp/build/reboot-to ]] || fail "reboot-to is not executable" -pass "reboot-to compiles" +[[ -x $tmp/build/reboot-to && -x $tmp/build/omamobile-bootctl ]] || fail "the C tools are not executable" +pass "reboot-to and omamobile-bootctl compile" ./install "$tmp/root" "$tmp/build" -for f in usr/bin/reboot-to \ +for f in usr/bin/reboot-to usr/bin/omamobile-bootctl \ + usr/share/licenses/omamobile-device-husky/LICENSE.Apache-2.0 \ usr/lib/udev/rules.d/10-omamobile-storage.rules \ usr/lib/systemd/network/20-usb-gadget.network \ usr/lib/systemd/logind.conf.d/10-omamobile-power-key.conf \ @@ -166,13 +201,14 @@ grep -qx 'ExecStart=-/usr/bin/plymouth quit --retain-splash' "$tmp/root/usr/lib/ pass "Plymouth quits with --retain-splash, as on raven" grep -q '^PACKAGE=omamobile-device-husky$' "$tmp/root/usr/share/omamobile/device.conf" \ || fail "the installed descriptor is husky" -for absent in usr/bin/omamobile-boot-success usr/bin/omamobile-bootctl \ +for absent in usr/bin/omamobile-boot-success \ usr/lib/systemd/system/omamobile-boot-success.service \ usr/bin/omamobile-wifi-start usr/bin/omamobile-charge-guard \ usr/bin/omamobile-camera-start; do [[ ! -e $tmp/root/$absent ]] || fail "install includes $absent" done -pass "install stages the udev rule, the USB link, the mirrorlist and the display start, and nothing that marks a slot or starts the radio, the charger or a camera" +! grep -rlw omamobile-bootctl "$tmp/root/usr/lib" "$tmp/root/etc" || fail "a staged unit or hook calls omamobile-bootctl" +pass "install stages the udev rule, the USB link, the mirrorlist, the display start and omamobile-bootctl for use by hand, and nothing that marks a slot or starts the radio, the charger or a camera" [[ ! -e $tmp/root/usr/lib/systemd/logind.conf.d/10-omamobile-lid.conf ]] \ || fail "husky has no lid: no lid drop-in" pass "no lid drop-in" diff --git a/packages/omamobile-device-husky/test/bootctl b/packages/omamobile-device-husky/test/bootctl new file mode 100755 index 000000000..e18fceed2 --- /dev/null +++ b/packages/omamobile-device-husky/test/bootctl @@ -0,0 +1,389 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# Offline tests for omamobile-bootctl (the same file in omamobile-device-husky +# and omamobile-device-tegu). No phone, no block device, no ioctl: the test +# build (-DBOOTCTL_TEST) reads a fake /sys, /proc and /dev under a scratch +# root, its "block devices" are files, and each read-only flag is a file +# beside its device that follows the kernel's rule (a partition is read-only +# when its own flag or its disk's flag is set). The production build is +# compiled too, and checked to carry none of the test hooks. +# +# test/bootctl build and run every case +# test/bootctl --mutations also break each key guard in a copy of the +# source and check that a case catches it +# BOOTCTL_BIN= test/bootctl --cases run the cases on a binary +set -euo pipefail +cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." +fail() { printf 'not ok - %s\n' "$1" >&2; exit 1; } +pass() { [[ -n ${QUIET:-} ]] || printf 'ok - %s\n' "$1"; } +tmp=$(mktemp -d) +bgpids=() +# A case that fails can leave a stopped or hung tool behind: kill it and its +# relock child, so neither outlives the test or holds the binary. +cleanup() { local p; for p in "${bgpids[@]}"; do pkill -KILL -P "$p" 2>/dev/null || true; kill -KILL "$p" 2>/dev/null || true; done; rm -rf "$tmp"; } +trap cleanup EXIT + +codename=$(sed -n 's/^#define BOOTCTL_CODENAME[[:space:]]*"\(.*\)"$/\1/p' bootctl/bootctl-device.h) +compatible=$(sed -n 's/^#define BOOTCTL_COMPATIBLE[[:space:]]*"\(.*\)"$/\1/p' bootctl/bootctl-device.h) +[[ -n $codename && -n $compatible ]] || fail "bootctl/bootctl-device.h names a codename and a compatible" + +build_test() { ${CC:-cc} -O2 -Wall -Wextra ${3:--Werror} -DBOOTCTL_TEST -Ibootctl -o "$2" "$1"; } + +# A phone as the storage guard leaves it: sda (main LUN, node removed) with +# persist and userdata, sdb with abl, sdd with devinfo and three siblings. +# Every flag set except userdata's and the main disk's. +mkroot() { + local r=$1 ver=${2:-15} major=${3:-3} + rm -rf "$r"; mkdir -p "$r/dev" "$r/proc/self" "$r/sys/firmware/devicetree/base" + printf '%s\0google,soc\0' "$compatible" > "$r/sys/firmware/devicetree/base/compatible" + printf 'androidboot.hardware = "x"\nandroidboot.slot_suffix = "_b"\n' > "$r/proc/bootconfig" + echo '25 1 259:34 / / rw,relatime shared:1 - ext4 /dev/sda34 rw' > "$r/proc/self/mountinfo" + local d p n + for d in sda sdb sdd; do mkdir -p "$r/sys/block/$d"; echo 1 > "$r/dev/$d.ro"; done + : > "$r/dev/sdb"; : > "$r/dev/sdd" + echo 0 > "$r/dev/sda.ro" + mkpart() { # disk part name ro + mkdir -p "$r/sys/block/$1/$2/holders"; echo 1 > "$r/sys/block/$1/$2/partition" + printf 'MAJOR=8\nMINOR=1\nDEVNAME=%s\nDEVTYPE=partition\nPARTN=1\nPARTNAME=%s\n' "$2" "$3" > "$r/sys/block/$1/$2/uevent" + head -c 8192 /dev/zero > "$r/dev/$2"; echo "$4" > "$r/dev/$2.ro" + } + mkpart sda sda1 persist 1 + mkpart sda sda34 userdata 0 + mkpart sdb sdb1 abl 1 + mkpart sdd sdd1 devinfo 1 + mkpart sdd sdd2 pinfo 1 + mkpart sdd sdd3 blenv 1 + mkpart sdd sdd4 mfg_data 1 + # devinfo: DEVI, 3., ABL-owned bytes we must never print or change, + # slot A 02 1a 00 00 (successful, fastboot-ok, high bit), slot B 00 1c 00 00 + # (active, fastboot-ok, high bit; not successful): the 9a's 2026-10-22 bytes. + python3 - "$r/dev/sdd1" "$ver" "$major" <<'PY' +import struct, sys +d = bytearray(8192) +for i in range(8192): + d[i] = (i * 37 + 11) & 0xff +d[0:8] = struct.pack('&1) || st=$? + [[ $st == 1 || $st == 2 ]] || fail "$name: exit $st, want a refusal ($out)" + unchanged "$name" + pass "$name" + } + fresh() { mkroot "$r" "${1:-15}" "${2:-3}"; cp "$r/dev/sdd1" "$tmp/orig"; } + opened() { grep -qx 'sdd 0' "$r/ro.log" 2>/dev/null && grep -qx 'sdd1 0' "$r/ro.log"; } + + # status: version and the eight slot bytes, nothing else from the partition + fresh + out=$(run status 2>&1) || fail "status runs ($out)" + grep -q "^bytes 0x30-0x37: $expect_bytes$" <<<"$out" || fail "status prints the slot bytes ($out)" + grep -q '^devinfo version 3.15 ' <<<"$out" || fail "status prints the version" + grep -q '^storage guard: holding$' <<<"$out" || fail "status sees the guard holding" + ! grep -qi 'de ad\|dead\|be ef' <<<"$out" || fail "status prints bytes from outside 0x30-0x37" + unchanged "status" + pass "status prints the version and the eight slot bytes, and nothing else" + + # dry run: plans one byte, writes nothing, leaves every flag set + out=$(run mark-b-successful 2>&1) || fail "the dry run passes its checks ($out)" + grep -q '^planned: byte 0x35 1c -> 1e (slot b successful), nothing else$' <<<"$out" || fail "the dry run plans 0x35 1c -> 1e ($out)" + grep -q -- "--write --codename $codename --expect \"$expect_bytes\"" <<<"$out" || fail "the dry run prints the write command" + ! grep -qi 'de ad\|dead\|be ef' <<<"$out" || fail "the dry run prints bytes from outside 0x30-0x37" + unchanged "dry run" + pass "a dry run plans one byte and writes nothing" + + # refusals before any window + fresh 11; refused "devinfo version 3.11 is refused (dry run)" run mark-b-successful + fresh 11; refused "devinfo version 3.11 is refused (write)" write + fresh 16; refused "devinfo version 3.16 (a newer minor) is refused" write + fresh 15 4; refused "devinfo version 4.15 (another major) is refused" write + fresh; printf 'XXXX' | dd of="$r/dev/sdd1" conv=notrunc status=none; cp "$r/dev/sdd1" "$tmp/orig" + refused "bad magic is refused" write + fresh; printf 'google,other-phone\0' > "$r/sys/firmware/devicetree/base/compatible"; refused "another board is refused" write + fresh; sed -i 's/_b"/_a"/' "$r/proc/bootconfig"; refused "a boot from slot a is refused" write + fresh; refused "--write without --expect is refused" run mark-b-successful --write --codename "$codename" + fresh; refused "--write with other bytes in --expect is refused" run mark-b-successful --write --codename "$codename" --expect "02 1a 00 00 01 1c 00 00" + fresh; refused "a wrong codename is refused" run mark-b-successful --write --codename not-"$codename" --expect "$expect_bytes" + fresh; refused "no codename and no terminal is refused" setsid -w env BOOTCTL_TEST_ROOT="$r" "$bin" mark-b-successful --write --expect "$expect_bytes" + fresh; printf '\x1d' | dd of="$r/dev/sdd1" bs=1 seek=$((0x35)) conv=notrunc status=none; cp "$r/dev/sdd1" "$tmp/orig" + refused "an unbootable slot b is refused" write --expect "02 1a 00 00 00 1d 00 00" + fresh; printf '\x18' | dd of="$r/dev/sdd1" bs=1 seek=$((0x35)) conv=notrunc status=none; cp "$r/dev/sdd1" "$tmp/orig" + refused "an inactive slot b is refused" write --expect "02 1a 00 00 00 18 00 00" + fresh; printf '\x1e' | dd of="$r/dev/sdd1" bs=1 seek=$((0x35)) conv=notrunc status=none; cp "$r/dev/sdd1" "$tmp/orig" + out=$(write --expect "02 1a 00 00 00 1e 00 00" 2>&1) || fail "an already marked slot b is not an error ($out)" + grep -q 'already marked successful' <<<"$out" || fail "an already marked slot b says so" + unchanged "already marked"; pass "an already marked slot b writes nothing" + fresh; echo '30 1 8:49 / /mnt ro - vfat /dev/sdd1 ro' >> "$r/proc/self/mountinfo"; refused "a mounted devinfo is refused" write + fresh; mkdir "$r/sys/block/sdd/sdd1/holders/dm-0"; refused "a held devinfo is refused" write + fresh; mkdir -p "$r/sys/block/sdd/holders/md0"; refused "a held boot LUN is refused" write + fresh; mkdir "$r/sys/block/sdd/sdd3/holders/loop0"; refused "a held sibling is refused" write + fresh; sed -i 's/PARTNAME=pinfo/PARTNAME=devinfo/' "$r/sys/block/sdd/sdd2/uevent"; refused "two devinfo partitions are refused" write + fresh; sed -i 's/PARTNAME=devinfo/PARTNAME=devinfo2/' "$r/sys/block/sdd/sdd1/uevent"; refused "no devinfo partition is refused" write + fresh; echo 0 > "$r/dev/sdd.ro"; st=0; write >/dev/null 2>&1 || st=$? + [[ $st == 1 && $(<"$r/dev/sdd.ro") == 0 ]] && cmp -s "$r/dev/sdd1" "$tmp/orig" || fail "a writable boot LUN is refused" + pass "a writable boot LUN is refused (the guard is not holding)" + fresh; echo 0 > "$r/dev/sda1.ro"; st=0; write >/dev/null 2>&1 || st=$? + [[ $st == 1 ]] && cmp -s "$r/dev/sdd1" "$tmp/orig" || fail "a writable persist is refused" + pass "a writable partition outside the allowlist is refused" + fresh; : > "$r/dev/sda"; chmod 600 "$r/dev/sda"; refused "a usable main-LUN node is refused" write + fresh; : > "$r/dev/sda"; chmod 000 "$r/dev/sda"; out=$(run mark-b-successful 2>&1) || fail "a mode-0000 main-LUN node (the udev rule) is accepted ($out)" + pass "a mode-0000 main-LUN node, as the udev rule leaves it, is accepted" + fresh; exec 7<>"$r/dev/sdd"; refused "another process with the boot LUN open for writing is refused" write; exec 7>&- + fresh; exec 7<>"$r/dev/sdd1"; refused "another process with devinfo open for writing is refused" write; exec 7>&- + fresh; exec 7<>"$r/dev/sdd3"; refused "another process with a sibling open for writing is refused" write; exec 7>&- + fresh; exec 7<"$r/dev/sdd"; out=$(run mark-b-successful 2>&1) || fail "a reader of the boot LUN is no reason to refuse ($out)"; exec 7<&- + pass "a process reading the boot LUN is not a reason to refuse" + + # inside the window: a sibling whose own flag is clear (hidden by the disk's), + # each sibling in turn, so directory order can't hide a skipped one + for sib in sdd2 sdd3 sdd4; do + fresh; echo 0 > "$r/dev/$sib.ro" + out=$(run status 2>&1); grep -q '^storage guard: holding$' <<<"$out" || fail "a sibling's own flag is invisible while its disk is read-only" + st=0; out=$(write 2>&1) || st=$? + [[ $st == 3 ]] || fail "$sib with its own flag clear stops the write (exit $st: $out)" + grep -q "$sib's own read-only flag is clear" <<<"$out" || fail "$sib is named" + opened && fail "$sib: devinfo was made writable" + grep -qx 'sdd 0' "$r/ro.log" || fail "$sib: the disk flag was never cleared, so the check never ran" + cmp -s "$r/dev/sdd1" "$tmp/orig" || fail "the $sib case wrote devinfo" + [[ $(<"$r/dev/sdd.ro") == 1 && $(<"$r/dev/sdd1.ro") == 1 ]] || fail "the $sib case left the disk or devinfo writable" + done + pass "each sibling whose own flag is clear stops the write before devinfo opens, and the disk goes read-only again" + fresh; rm "$r/dev/sdd3.ro"; st=0; write >/dev/null 2>&1 || st=$? + [[ $st == 1 && ! -s $r/ro.log ]] && cmp -s "$r/dev/sdd1" "$tmp/orig" || fail "a sibling whose flag can't be read is refused before the window (exit $st)" + fresh; st=0; out=$(BOOTCTL_TEST_FAULT=sdd3-unreadable-in-window write 2>&1) || st=$? + [[ $st == 3 ]] && grep -q "sdd3's own read-only flag is clear or unreadable" <<<"$out" || fail "a sibling whose flag can't be read in the window stops the write (exit $st: $out)" + opened && fail "an unreadable sibling flag: devinfo was made writable" + cmp -s "$r/dev/sdd1" "$tmp/orig" || fail "an unreadable sibling flag: devinfo written" + [[ $(<"$r/dev/sdd.ro") == 1 && $(<"$r/dev/sdd1.ro") == 1 ]] || fail "an unreadable sibling flag left a flag clear" + pass "a sibling whose flag can't be read stops the write" + fresh; st=0; out=$(BOOTCTL_TEST_FAULT=disk-stays-ro write 2>&1) || st=$? + [[ $st == 3 ]] && grep -q 'sdd did not become writable' <<<"$out" || fail "a disk flag that won't clear stops at step 1 (exit $st: $out)" + unchanged "disk flag stuck"; pass "a disk flag that doesn't clear stops the write at step 1" + fresh; echo 0 > "$r/dev/sdd1.ro"; st=0; out=$(write 2>&1) || st=$? + [[ $st == 3 ]] && grep -q "devinfo's own read-only flag was already clear" <<<"$out" || fail "devinfo with its own flag clear stops the write (exit $st: $out)" + cmp -s "$r/dev/sdd1" "$tmp/orig" || fail "the devinfo-flag case wrote devinfo" + [[ $(flags "$r") == "$all_ro" ]] || fail "the devinfo-flag case left $(flags "$r")" + pass "devinfo with its own flag already clear stops the write, and both flags end set" + + # the write: exactly bit 0x02 of byte 0x35, read back, every flag set again + fresh + out=$(write 2>&1) || fail "the write succeeds ($out)" + diffs=$(cmp -l "$tmp/orig" "$r/dev/sdd1" || true) + [[ $(wc -l <<<"$diffs") == 1 ]] || fail "the write changed more than one byte: $diffs" + read -r off old new <<<"$diffs" + [[ $off == $((0x35 + 1)) ]] || fail "the write changed byte $((off - 1)), not 0x35" + (( (8#$old ^ 8#$new) == 2 )) || fail "the write changed byte 0x35 by more than bit 0x02" + [[ $(flags "$r") == "$all_ro" ]] || fail "after the write the flags are $(flags "$r")" + grep -q "^before 0x30-0x37: $expect_bytes$" <<<"$out" || fail "the write prints the bytes before" + grep -q '^after 0x30-0x37: 02 1a 00 00 00 1e 00 00$' <<<"$out" || fail "the write prints the bytes after" + ! grep -qi 'de ad\|dead\|be ef' <<<"$out" || fail "the write prints bytes from outside 0x30-0x37" + pass "a write flips bit 0x02 of byte 0x35 alone, reads it back, and sets every flag again" + fresh; out=$(BOOTCTL_TEST_FAULT=no-child-relock write 2>&1) || fail "the write succeeds without the child's relock ($out)" + [[ $(flags "$r") == "$all_ro" ]] || fail "without the child's relock the flags are $(flags "$r")" + pass "the tool sets every flag again itself, without the relock child" + out=$(write --expect "02 1a 00 00 00 1e 00 00" 2>&1) || fail "a second run is a no-op ($out)" + grep -q 'already marked successful' <<<"$out" || fail "a second run says already marked" + pass "a second run writes nothing" + + # failures inside the window + fresh; st=0; out=$(BOOTCTL_TEST_FAULT=corrupt-write write 2>&1) || st=$? + [[ $st == 3 ]] || fail "a read-back mismatch fails with 3 (exit $st: $out)" + grep -q 'VERIFY FAILED' <<<"$out" && grep -q 'restored: devinfo reads back as it was before' <<<"$out" || fail "a mismatch says it restored ($out)" + unchanged "read-back mismatch"; pass "a read-back mismatch restores the original, sets every flag, and fails" + fresh; st=0; out=$(BOOTCTL_TEST_FAULT=write-fails write 2>&1) || st=$? + [[ $st == 3 ]] || fail "a failed write fails with 3 (exit $st: $out)" + unchanged "failed write"; pass "a failed write leaves devinfo as it was and sets every flag" + fresh; st=0; out=$(BOOTCTL_TEST_FAULT=corrupt-write,restore-noop write 2>&1) || st=$? + [[ $st == 4 ]] && grep -q 'RESTORE FAILED: devinfo does not read back as before' <<<"$out" || fail "a restore that doesn't land fails with 4 (exit $st: $out)" + [[ $(flags "$r") == "$all_ro" ]] || fail "after a failed restore the flags are $(flags "$r")" + pass "a restore that doesn't read back fails with 4, and every flag is set" + fresh; st=0; out=$(BOOTCTL_TEST_FAULT=change-under write 2>&1) || st=$? + [[ $st == 3 ]] && grep -q 'devinfo changed since it was checked' <<<"$out" || fail "devinfo changed inside the window stops the write (exit $st: $out)" + [[ $(od -An -tx1 -j $((0x35)) -N1 "$r/dev/sdd1" | tr -d ' ') == 1c ]] || fail "devinfo changed underneath, and byte 0x35 was written anyway" + [[ $(flags "$r") == "$all_ro" ]] || fail "after a change underneath the flags are $(flags "$r")" + pass "devinfo changed between the checks and the write: nothing written" + fresh; st=0; out=$(BOOTCTL_TEST_FAULT=part-relock-ignored write 2>&1) || st=$? + [[ $st == 5 ]] && grep -q 'FAILED to set devinfo or sdd read-only again' <<<"$out" || fail "a devinfo flag that won't set again fails with 5 (exit $st: $out)" + pass "a devinfo flag that doesn't read back read-only fails loudly (exit 5)" + fresh; st=0; out=$(BOOTCTL_TEST_FAULT=child-fails write 2>&1) || st=$? + [[ $st == 5 ]] && grep -q 'the relock child failed' <<<"$out" || fail "a failed relock child fails with 5 (exit $st: $out)" + pass "a relock child that fails makes the tool fail loudly (exit 5)" + fresh; st=0; out=$(BOOTCTL_TEST_FAULT=fork-fails write 2>&1) || st=$? + [[ $st == 3 ]] && grep -q "can't start the relock child" <<<"$out" || fail "no relock child, no window (exit $st: $out)" + [[ ! -s $r/ro.log ]] || fail "without a relock child a flag was changed: $(cat "$r/ro.log")" + unchanged "no relock child"; pass "without a relock child no flag changes" + + waitro() { local i; for i in $(seq 50); do [[ $(flags "$r") == "$all_ro" ]] && return 0; sleep 0.1; done; return 1; } + for f in kill-before-write kill-after-write; do + fresh; st=0; BOOTCTL_TEST_FAULT=$f write >/dev/null 2>&1 || st=$? + [[ $st == 137 ]] || fail "$f: the tool was not killed (exit $st)" + opened || fail "$f: the window never opened, so the restore proves nothing" + waitro || fail "$f: the flags stayed $(flags "$r") after the tool was killed" + pass "$f: the relock child sets devinfo and the disk read-only again" + done + cmp -s "$r/dev/sdd1" "$tmp/orig" && fail "kill-after-write: the fake write did not happen" + # exec, so $! is the tool itself and not a subshell around it + bgwrite() { ( exec env BOOTCTL_TEST_ROOT="$r" "$@" "$bin" mark-b-successful --write --codename "$codename" --expect "$expect_bytes" >/dev/null 2>&1 ) & pid=$!; bgpids+=("$pid"); } + waitopen() { local i; for i in $(seq 100); do opened && return 0; sleep 0.05; done; return 1; } + stopped() { local i; for i in $(seq 100); do [[ $(awk '{print $3}' /proc/$1/stat 2>/dev/null) == T ]] && return 0; sleep 0.05; done; return 1; } + fresh; bgwrite BOOTCTL_TEST_FAULT=hang-in-window BOOTCTL_TEST_RELOCK_MS=300 + waitopen || { kill -9 $pid; fail "a hung tool: the window never opened"; } + waitro || { kill -9 $pid; fail "a hung tool: the relock child did not set the flags after its timeout"; } + kill -0 $pid 2>/dev/null || fail "hang-in-window: the tool exited instead of hanging" + kill -9 $pid; wait $pid 2>/dev/null || true + cmp -s "$r/dev/sdd1" "$tmp/orig" || fail "hang-in-window wrote devinfo" + pass "a hung tool: the window opened, and the relock child set both flags after its timeout" + + # Stopped before the window opens, longer than the timeout: the child must + # still be watching when the window opens, and relock at once on SIGKILL. + fresh; bgwrite BOOTCTL_TEST_FAULT=stop-before-open,hang-in-window BOOTCTL_TEST_RELOCK_MS=2000 + stopped $pid || { kill -9 $pid; fail "stop-before-open: the tool never stopped"; } + sleep 2.5 + [[ ! -s $r/ro.log ]] || { kill -9 $pid; fail "stop-before-open: a flag changed while stopped: $(cat "$r/ro.log")"; } + kill -CONT $pid + waitopen || { kill -9 $pid; fail "stop-before-open: the window never opened after SIGCONT"; } + kill -9 $pid; wait $pid 2>/dev/null || true + for i in $(seq 10); do [[ $(flags "$r") == "$all_ro" ]] && break; sleep 0.1; done + [[ $(flags "$r") == "$all_ro" ]] || fail "stopped before the window, then killed in it: the flags are $(flags "$r") 1 s later" + pass "a stop longer than the timeout before the window: the child still relocks at once when the tool is killed in it" + + # Stopped right after arming the child: the child relocks every timeout, so + # the window that opens after SIGCONT is closed again while the tool hangs. + fresh; bgwrite BOOTCTL_TEST_FAULT=stop-after-open,hang-in-window BOOTCTL_TEST_RELOCK_MS=300 + stopped $pid || { kill -9 $pid; fail "stop-after-open: the tool never stopped"; } + sleep 1; kill -CONT $pid + waitopen || { kill -9 $pid; fail "stop-after-open: the window never opened"; } + waitro || { kill -9 $pid; fail "stop-after-open: the window stayed open with the tool hung (the child stopped watching)"; } + kill -0 $pid 2>/dev/null || fail "stop-after-open: the tool exited instead of hanging" + kill -9 $pid; wait $pid 2>/dev/null || true + pass "a stop after the child is armed: the child keeps relocking until the tool is gone" + + # The prompt can take minutes: a writer or a guard change during it stops the write. + for change in writer guard; do + fresh; bgwrite BOOTCTL_TEST_FAULT=hold-after-codename + for i in $(seq 100); do [[ -e $r/at-prompt ]] && break; sleep 0.05; done + [[ -e $r/at-prompt ]] || { kill -9 $pid; fail "hold-after-codename never reached the prompt"; } + if [[ $change == writer ]]; then exec 7<>"$r/dev/sdd1"; else echo 0 > "$r/dev/sda1.ro"; fi + touch "$r/go"; st=0; wait $pid || st=$? + [[ $change == writer ]] && exec 7>&- + [[ $st == 1 ]] || fail "a $change change during the prompt: exit $st, want a refusal" + [[ ! -s $r/ro.log ]] || fail "a $change change during the prompt: a flag changed" + cmp -s "$r/dev/sdd1" "$tmp/orig" || fail "a $change change during the prompt: devinfo written" + done + pass "a writer or a guard change while the codename prompt waits stops the write" + + fresh; bgwrite BOOTCTL_TEST_FAULT=hang-in-window + waitopen || { kill -9 $pid; fail "hang-in-window never opened the window"; } + kill -INT $pid; kill -TERM $pid; kill -HUP $pid; sleep 0.3 + kill -0 $pid 2>/dev/null || fail "SIGINT, SIGTERM or SIGHUP stopped the tool inside the window" + kill -9 $pid; wait $pid 2>/dev/null || true + waitro || fail "after SIGKILL inside the window the flags are $(flags "$r")" + pass "^C, SIGTERM and SIGHUP wait out the window; SIGKILL leaves the relock to the child" +} + +if [[ ${1:-} == --cases ]]; then + QUIET=1 cases "${BOOTCTL_BIN:?}" + exit 0 +fi + +# The production build: real paths, real ioctls, no test hooks. +${CC:-cc} ${CFLAGS:--O2} -Wall -Wextra -Werror -Ibootctl -o "$tmp/omamobile-bootctl" bootctl/omamobile-bootctl.c \ + || fail "omamobile-bootctl compiles without warnings" +! grep -aq 'BOOTCTL_TEST' "$tmp/omamobile-bootctl" || fail "the production build carries a test hook" +grep -aq "$compatible" "$tmp/omamobile-bootctl" || fail "the production build is for $codename" +pass "the production build compiles, is for $codename and has no test hooks" +st=0; "$tmp/omamobile-bootctl" >/dev/null 2>&1 || st=$? +[[ $st == 2 ]] || fail "no arguments prints the usage" +pass "no arguments prints the usage" + +build_test bootctl/omamobile-bootctl.c "$tmp/bootctl-test" || fail "the test build compiles" +cases "$tmp/bootctl-test" + +[[ ${1:-} == --mutations ]] || exit 0 + +# Each mutation breaks one guard in a copy of the source; a case must fail. +mutate() { # name, python replacement (old, new) + local name=$1 old=$2 new=$3 m="$tmp/mut.c" + nmut=$((${nmut:-0} + 1)) + python3 - bootctl/omamobile-bootctl.c "$m" "$old" "$new" <<'PY' +import sys +s = open(sys.argv[1]).read() +if s.count(sys.argv[3]) < 1: + sys.exit("mutation does not apply: " + sys.argv[3]) +open(sys.argv[2], 'w').write(s.replace(sys.argv[3], sys.argv[4])) +PY + build_test "$m" "$tmp/mut$nmut" -w || fail "mutant '$name' compiles" + if BOOTCTL_BIN="$tmp/mut$nmut" "$0" --cases >/dev/null 2>&1; then + fail "mutant '$name' passed every case" + fi + pass "mutation caught: $name" +} +mutate "no version check" 'if (maj != BOOTCTL_VER_MAJOR || min != BOOTCTL_VER_MINOR) {' 'if (0) {' +mutate "version major ignored" 'if (maj != BOOTCTL_VER_MAJOR || min != BOOTCTL_VER_MINOR) {' 'if (min != BOOTCTL_VER_MINOR) {' +mutate "a newer minor accepted" 'if (maj != BOOTCTL_VER_MAJOR || min != BOOTCTL_VER_MINOR) {' 'if (maj != BOOTCTL_VER_MAJOR || min < BOOTCTL_VER_MINOR) {' +mutate "no magic check" 'if (magic != DEVINFO_MAGIC) {' 'if (0) {' +mutate "no board check" 'if (strcmp(buf, BOOTCTL_COMPATIBLE)) {' 'if (0) {' +mutate "no slot check" "if (booted_slot() != 'b') {" 'if (0) {' +mutate "dry run writes" 'if (!do_write) {' 'if (0) {' +mutate "no --expect check" 'if (memcmp(exp, img + OFF_SLOTS, SLOT_BYTES)) {' 'if (0) {' +mutate "no codename check" 'if (strcmp(typed, BOOTCTL_CODENAME)) {' 'if (0) {' +mutate "another bit" 'nv = fb | FLAG_SUCCESSFUL;' 'nv = fb | FLAG_SUCCESSFUL | FLAG_FASTBOOT_OK | 0x20;' +mutate "no guard check" 'if (check_guard(&t) || check_unused(&t))' 'if (check_unused(&t))' +mutate "no writer check" 'if ((flags & O_ACCMODE) != O_RDONLY) {' 'if (0) {' +mutate "no sibling check" 'if (ro_get(&t->sib[i], &t->disk) != 1) {' 'if (0) {' +mutate "first sibling skipped" 'for (int i = 0; i < t->nsib; i++) + if (ro_get(&t->sib[i]' 'for (int i = 1; i < t->nsib; i++) + if (ro_get(&t->sib[i]' +mutate "last sibling skipped" 'for (int i = 0; i < t->nsib; i++) + if (ro_get(&t->sib[i]' 'for (int i = 0; i < t->nsib - 1; i++) + if (ro_get(&t->sib[i]' +mutate "unreadable sibling flag accepted" 'if (ro_get(&t->sib[i], &t->disk) != 1) {' 'if (ro_get(&t->sib[i], &t->disk) == 0) {' +mutate "disk flag not checked after clearing" 'if (ro_set(&t->disk, 0) || ro_get(&t->disk, NULL) != 0) {' 'if (ro_set(&t->disk, 0)) {' +mutate "no step-4 re-read compare" 'if (!again || alen != len || memcmp(again, orig, len)) {' 'if (!again) {' +mutate "writer on devinfo or a sibling missed" 'int hit = same_file(&st, &t->part) || same_file(&st, &t->disk); + for (int i = 0; !hit && i < t->nsib; i++)' 'int hit = same_file(&st, &t->disk); + for (int i = 0; !hit && i < 0; i++)' +mutate "holders checked on devinfo only" 'for (int i = 0; i < nh; i++) {' 'for (int i = 1; i < 2; i++) {' +mutate "no re-check after the prompt" ' if (check_guard(&t) || check_unused(&t)) { + err("the storage guard' ' if (0) { + err("the storage guard' +mutate "no relock read-back of devinfo" 'if (ro_set(&t->part, 1) || ro_get(&t->part, &t->disk) != 1)' 'if (ro_set(&t->part, 1))' +mutate "no restore read-back" 'if (after && alen == len && !memcmp(after, orig, len)) { + err("restored' 'if (1) { + err("restored' +mutate "child status ignored" 'if (!WIFEXITED(st) || WEXITSTATUS(st)) {' 'if (0) {' +mutate "child start failure ignored" 'if (child < 0) {' 'if (0) {' +mutate "child never armed" 'if (write(wfd, "O", 1) != 1 || !child_alive(child, &reaped, &st)) {' 'if (!child_alive(child, &reaped, &st)) {' +mutate "child one-shot after its first timeout" ' if (child_relock(t)) + ok = 0; + continue;' ' _exit(child_relock(t) ? 1 : 0);' +mutate "child times out from the fork, once" 'int r = poll(&pf, 1, armed ? relock_timeout_ms : -1);' 'int r = poll(&pf, 1, relock_timeout_ms); if (r == 0) _exit(child_relock(t) ? 1 : 0);' +mutate "no mount check" 'if (!strcmp(source, src) || (t->part.rdev' 'if (0 && (t->part.rdev' +mutate "no unbootable check" 'if (fb & FLAG_UNBOOTABLE) {' 'if (0) {' +mutate "no restore on mismatch" 'if (write_at(t, orig, len, 0)) {' 'if (0) {' +mutate "no relock child" ' return relock(t); +} + +static void relocker' ' return 0; +} + +static void relocker' +mutate "parent does not relock" ' if (relock(t)) { + err("FAILED' ' if (0) { + err("FAILED' +mutate "signals not blocked" 'sigprocmask(SIG_BLOCK, &block, &old);' 'sigemptyset(&old);' +mutate "disk flag cleared without the sibling check" 'for (int i = 0; i < t->nsib; i++)' 'for (int i = 0; i < 0; i++)' diff --git a/packages/omamobile-device-husky/version b/packages/omamobile-device-husky/version index e8e277f2f..d8a023ec1 100644 --- a/packages/omamobile-device-husky/version +++ b/packages/omamobile-device-husky/version @@ -1 +1 @@ -0.1.16 +0.1.19 diff --git a/packages/omamobile-device-tegu/LICENSE.Apache-2.0 b/packages/omamobile-device-tegu/LICENSE.Apache-2.0 new file mode 100644 index 000000000..137069b82 --- /dev/null +++ b/packages/omamobile-device-tegu/LICENSE.Apache-2.0 @@ -0,0 +1,73 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/packages/omamobile-device-tegu/PKGBUILD b/packages/omamobile-device-tegu/PKGBUILD index 2732b538d..eaf438c29 100644 --- a/packages/omamobile-device-tegu/PKGBUILD +++ b/packages/omamobile-device-tegu/PKGBUILD @@ -6,7 +6,7 @@ pkgrel=1 pkgdesc="Omarchy Mobile support for the Google Pixel 9a (tegu): storage guard, USB networking, hang-safe graphics start" arch=(aarch64) url="https://github.com/derekross/omarchy-mobile" -license=(MIT) +license=(MIT Apache-2.0) depends=(bash systemd kmod bluez-utils omamobile-keyring) optdepends=('omamobile-telephony-tegu: attach Phone and Messages to an attended running sitd') provides=(omamobile-device omamobile-modem-policy omamobile-sitd-policy) diff --git a/packages/omamobile-device-tegu/README.md b/packages/omamobile-device-tegu/README.md index 04a2e32f7..b12fbf66b 100644 --- a/packages/omamobile-device-tegu/README.md +++ b/packages/omamobile-device-tegu/README.md @@ -30,6 +30,7 @@ packaged yet. What is here is what runs on in-tree drivers. | `vendor/udev/rules.d/20-omamobile-torch.rules`, `70-omamobile-dma-heap.rules`, `72-omamobile-feedbackd.rules` | `/usr/lib/udev/rules.d` | The torch tile may set the LED's brightness; libcamera's software ISP gets the DMA-BUF heaps; feedbackd gets the haptics | | `vendor/systemd/network/20-usb-gadget.network`, `vendor/NetworkManager/conf.d/10-omamobile-usb.conf` | `/usr/lib/systemd/network`, `/usr/lib/NetworkManager/conf.d` | USB networking to a host (172.16.42.1, the host as a fallback route behind Wi-Fi); NetworkManager stays off the link | | `src/reboot-to.c` | `/usr/bin/reboot-to` | Reboot with a reason the bootloader understands. One source with the cheetah package | +| `bootctl/omamobile-bootctl.c`, `bootctl/bootctl-device.h`, `LICENSE.Apache-2.0` | `/usr/bin/omamobile-bootctl` | Marks slot B successful in `devinfo`, by hand and attended, from the runbook in [BRINGUP-M1.md#6-slot-b-marked-successful-by-hand](../../device/tegu/BRINGUP-M1.md#6-slot-b-marked-successful-by-hand) (#252). Dry run by default; `--write` needs the dry run's eight slot bytes (`--expect`) and the codename typed or passed. It refuses another board, a devinfo layout other than the one recorded for this phone (3.15), a boot from slot A, and a storage guard that isn't holding. It makes devinfo and its boot LUN writable only for the one byte (the kernel won't write a partition of a read-only disk; for that moment the whole LUN is writable through its whole-disk node, which waits on the maintainer's ruling on #252), with a relock child that sets both read-only again if it dies, stops or hangs. The source is in `bootctl/`, not `src/`, so `bin/omamobile initramfs` never builds it into the boot image (test/all checks). No unit, hook or installer calls it. Apache-2.0, see `LICENSE.Apache-2.0` (the devinfo layout is Google's boot-control HAL); one source and one test (`test/bootctl`) with the husky package | | `device.conf`, `etc/omamobile-mirrorlist` | `/usr/share/omamobile`, `/etc/pacman.d` | The device descriptor (a copy of `device/tegu/device.conf`) and the `[omamobile]` repository | Bluetooth comes up powered at every boot, as on the Pixel 7 Pro @@ -41,8 +42,10 @@ everything and enables nothing beyond the two wants links, and `test/all` runs the package tests in a scratch root (`OMAMOBILE_TEGU_ROOT`), with no phone and no hardware. -The package does not mark the boot slot successful (Derek decides how that -works on the 9a) and does not start the modem. NFC and Wi-Fi come up from +Nothing in the package marks the boot slot successful on its own: since +#252 that is a step the owner runs by hand with `omamobile-bootctl`, once +per install of slot B's images, and only while the hold in AGENTS.md +allows it. The package does not start the modem. NFC and Wi-Fi come up from the graphics start when the device tree describes them, and the charger and the cameras load from the device tree on their own. It carries no vendor files and no per-phone data. diff --git a/packages/omamobile-device-tegu/bootctl/bootctl-device.h b/packages/omamobile-device-tegu/bootctl/bootctl-device.h new file mode 100644 index 000000000..9f8767866 --- /dev/null +++ b/packages/omamobile-device-tegu/bootctl/bootctl-device.h @@ -0,0 +1,13 @@ +/* SPDX-License-Identifier: MIT */ +/* + * omamobile-bootctl's values for the Pixel 9a (tegu). The tool refuses a + * board or a devinfo layout other than these. The version is the one read on + * the 9a (device/tegu/NOTES.md, "devinfo write disclosure and stop" and + * "Read-only layout evidence after official OTA maintenance": layout 3.15, + * the slot bytes paired with ABL's getvars across a boot that spent a try). + * test/all checks the codename and compatible against device.conf. + */ +#define BOOTCTL_CODENAME "tegu" +#define BOOTCTL_COMPATIBLE "google,zumapro-tegu" +#define BOOTCTL_VER_MAJOR 3 +#define BOOTCTL_VER_MINOR 15 diff --git a/packages/omamobile-device-tegu/bootctl/omamobile-bootctl.c b/packages/omamobile-device-tegu/bootctl/omamobile-bootctl.c new file mode 100644 index 000000000..0e6dd393f --- /dev/null +++ b/packages/omamobile-device-tegu/bootctl/omamobile-bootctl.c @@ -0,0 +1,1230 @@ +// SPDX-License-Identifier: Apache-2.0 +/* + * omamobile-bootctl (Pixel 8 Pro and Pixel 9a): mark slot B successful in + * the bootloader's "devinfo" partition, by hand and attended (#252). + * + * The same file is in omamobile-device-husky and omamobile-device-tegu; the + * only per-phone values are in bootctl/bootctl-device.h (codename, board + * compatible, and the devinfo layout version recorded for that phone). The + * 7 Pro's omamobile-bootctl (omamobile-device-cheetah) is a different file + * and is not changed by this one. + * + * The devinfo layout comes from Google's Pixel boot-control HAL: + * + * https://android.googlesource.com/device/google/gs-common + * tag android-14.0.0_r75 (commit ddbc3a43bcad1db516c114aca87df90d1780e728) + * bootctrl/aidl/DevInfo.h Copyright (C) 2021 The Android Open Source Project + * bootctrl/aidl/BootControl.cpp Copyright (C) 2023 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Modifications (Omarchy Mobile, 2026): a standalone C tool with one write, + * markBootSuccessful() for slot B (successful = 1), nothing else. It finds + * devinfo itself by PARTNAME, checks the storage guard and the phone, and + * opens and closes the read-write window itself: + * + * The kernel lets a partition be written only if its whole disk is + * writable too: bdev_read_only() is the partition's own BD_READ_ONLY flag + * OR the disk's (part0's) flag (include/linux/blkdev.h), and both + * blkdev_write_iter() and the BLKROGET ioctl and sysfs "ro" use it. So + * devinfo can't be written while its disk (the boot LUN, sdd) is read-only, + * and no ioctl makes the partition alone writable. Clearing the disk flag + * makes the whole-disk node writable, and through it every byte of the LUN, + * the other partitions (pinfo, blenv, mfg_data on husky) included, for as + * long as the window lasts: their own flags guard only their own nodes. + * The tool keeps that window to the one byte: disk rw (checked), the + * siblings' own flags checked (the only moment they can be read), devinfo + * rw, one byte written and read back, devinfo ro, disk ro, both checked. + * The job-control and termination signals are blocked, and a relock child + * sets both flags back the moment this process dies, and every 10 s from + * the moment the window opens for as long as it stays open (a stopped or + * hung process), until this process has closed the window itself. + * + * The source sits in bootctl/, not src/: bin/omamobile's initramfs builder + * compiles a device package's src/omamobile-bootctl.c into the boot image, + * and this tool belongs in the installed package only. + * + * Usage: + * omamobile-bootctl status + * omamobile-bootctl mark-b-successful (dry run) + * omamobile-bootctl mark-b-successful --write --expect "<8 bytes>" [--codename ] + * Never run from a unit, a hook or an installer. + */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* BLKROSET, BLKROGET (musl and glibc) */ + +#include "bootctl-device.h" + +#if !defined(BOOTCTL_CODENAME) || !defined(BOOTCTL_COMPATIBLE) || \ + !defined(BOOTCTL_VER_MAJOR) || !defined(BOOTCTL_VER_MINOR) +#error "bootctl-device.h must define the codename, compatible and devinfo version" +#endif + +/* From DevInfo.h ("definitions taken from ABL code") */ +#define DEVINFO_MAGIC 0x49564544u /* "DEVI" little-endian */ +#define DEVINFO_HDR 128 /* sizeof(devinfo_t) */ +#define OFF_MAGIC 0x00 +#define OFF_VER_MAJOR 0x04 +#define OFF_VER_MINOR 0x06 +#define OFF_SLOTS 0x30 /* slots[2], 4 bytes each, to 0x37 */ +#define SLOT_BYTES 8 +#define SLOT_RETRY 0 +#define SLOT_FLAGS 1 +#define FLAG_UNBOOTABLE 0x01 +#define FLAG_SUCCESSFUL 0x02 +#define FLAG_ACTIVE 0x04 +#define FLAG_FASTBOOT_OK 0x08 +/* The one byte this tool writes: slot B's flags. */ +#define OFF_B_FLAGS (OFF_SLOTS + 4 + SLOT_FLAGS) + +#define MAX_REGION (1024 * 1024) +#define ALIGN 4096 +#define RELOCK_TIMEOUT_MS 10000 + +/* The storage guard's allowlist (initramfs/init accepts no other names). */ +static const char *const allowlist[] = { + "boot_b", "init_boot_b", "vendor_boot_b", "vendor_kernel_boot_b", "dtbo_b", "userdata", NULL +}; + +static const char *argv0 = "omamobile-bootctl"; + +/* + * Test build (-DBOOTCTL_TEST, test/bootctl only): paths are read under + * $BOOTCTL_TEST_ROOT, block devices are files, and the read-only flags are + * files next to them that follow the kernel's rule (a partition is read-only + * if its own flag or its disk's flag is set). The production build has none + * of this: fixed paths, real ioctls, O_DIRECT reads. + */ +#ifdef BOOTCTL_TEST +static const char *root = ""; +static const char *fault = ""; /* comma-separated test faults */ +static int relock_timeout_ms = RELOCK_TIMEOUT_MS; +#define DIRECT 0 +#else +static const char *const root = ""; +static const int relock_timeout_ms = RELOCK_TIMEOUT_MS; +#define DIRECT O_DIRECT +#endif + +struct node { + char name[32]; /* sdd1 */ + char path[PATH_MAX]; /* /dev/sdd1 (under root in tests) */ + char sys[PATH_MAX]; /* /sys/block/sdd/sdd1 */ + dev_t rdev; +}; + +struct target { + struct node part; /* devinfo */ + struct node disk; /* its whole disk */ + struct node sib[64]; /* the disk's other partitions */ + int nsib; + char main_disk[32]; /* the disk that holds userdata */ +}; + +static void err(const char *fmt, ...) +{ + va_list ap; + fprintf(stderr, "%s: ", argv0); + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); + fputc('\n', stderr); +} + +/* + * snprintf that never truncates silently: a cut-off path could name another + * file, so the tool stops instead (inside the read-write window the relock + * child then sets both flags back, as for any other exit). + */ +static void xfmt(char *out, size_t n, const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + int r = vsnprintf(out, n, fmt, ap); + va_end(ap); + if (r < 0 || (size_t)r >= n) { + err("internal error: a path or name is too long"); + exit(1); + } +} + +static void rp(char *out, size_t n, const char *fmt, ...) +{ + char tmp[PATH_MAX]; + va_list ap; + va_start(ap, fmt); + int r = vsnprintf(tmp, sizeof(tmp), fmt, ap); + va_end(ap); + if (r < 0 || (size_t)r >= sizeof(tmp)) { + err("internal error: a path is too long"); + exit(1); + } + xfmt(out, n, "%s%s", root, tmp); +} + +/* Read a small text file into buf (NUL-terminated); returns length or -1. */ +static ssize_t slurp(const char *path, char *buf, size_t n) +{ + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) + return -1; + ssize_t r = read(fd, buf, n - 1); + close(fd); + if (r < 0) + return -1; + buf[r] = 0; + return r; +} + +#ifdef BOOTCTL_TEST +static int has_fault(const char *name) +{ + size_t n = strlen(name); + for (const char *p = fault; *p; ) { + const char *e = strchr(p, ','); + size_t l = e ? (size_t)(e - p) : strlen(p); + if (l == n && !strncmp(p, name, n)) + return 1; + p += l + (e ? 1 : 0); + } + return 0; +} +#endif + +/* ---- read-only flags ---------------------------------------------------- */ + +#ifdef BOOTCTL_TEST +static int own_flag(const char *path) +{ + char f[PATH_MAX + 4], b[8]; + xfmt(f, sizeof(f), "%s.ro", path); + if (slurp(f, b, sizeof(b)) < 0) + return -1; + return b[0] == '1'; +} + +/* The kernel's bdev_read_only(): own flag OR the disk's flag. */ +static int ro_get(const struct node *n, const struct node *disk) +{ + /* fault: a sibling whose node can't be opened once the window is open */ + if (has_fault("sdd3-unreadable-in-window") && disk && !strcmp(n->name, "sdd3") && + own_flag(disk->path) == 0) + return -1; + int o = own_flag(n->path); + if (o < 0) + return -1; + if (o || !disk || disk == n) + return o; + return own_flag(disk->path) != 0; +} + +static int ro_set(const struct node *n, int v) +{ + char f[PATH_MAX + 4]; + size_t pl = strlen(n->path); + int is_disk = pl && !isdigit((unsigned char)n->path[pl - 1]); + /* faults: a flag that silently doesn't change, as a stuck or lying device would */ + if ((v == 1 && !is_disk && has_fault("part-relock-ignored")) || + (v == 0 && is_disk && has_fault("disk-stays-ro"))) + return 0; + xfmt(f, sizeof(f), "%s/ro.log", root); + FILE *log = fopen(f, "a"); + if (log) { + fprintf(log, "%s %d\n", n->name, v); + fclose(log); + } + xfmt(f, sizeof(f), "%s.ro", n->path); + FILE *fp = fopen(f, "w"); + if (!fp) + return -1; + fprintf(fp, "%d\n", v); + return fclose(fp) ? -1 : 0; +} +#else +static int ro_get(const struct node *n, const struct node *disk) +{ + (void)disk; + int fd = open(n->path, O_RDONLY | O_CLOEXEC); + if (fd < 0) + return -1; + int v = 0; + int r = ioctl(fd, BLKROGET, &v); + close(fd); + return r ? -1 : v != 0; +} + +static int ro_set(const struct node *n, int v) +{ + int fd = open(n->path, O_RDONLY | O_CLOEXEC); + if (fd < 0) + return -1; + int r = ioctl(fd, BLKROSET, &v); + close(fd); + return r; +} +#endif + +/* ---- finding devinfo ---------------------------------------------------- */ + +static int partname(const char *sys, char *out, size_t n) +{ + char f[PATH_MAX + 8], buf[4096]; + xfmt(f, sizeof(f), "%s/uevent", sys); + if (slurp(f, buf, sizeof(buf)) < 0) + return -1; + for (char *l = strtok(buf, "\n"); l; l = strtok(NULL, "\n")) + if (!strncmp(l, "PARTNAME=", 9)) { + xfmt(out, n, "%s", l + 9); + return 0; + } + out[0] = 0; + return 0; +} + +static int fill_node(struct node *nd, const char *name, const char *sys) +{ + xfmt(nd->name, sizeof(nd->name), "%s", name); + xfmt(nd->sys, sizeof(nd->sys), "%s", sys); + rp(nd->path, sizeof(nd->path), "/dev/%s", name); + nd->rdev = 0; +#ifndef BOOTCTL_TEST + char f[PATH_MAX + 8], buf[32]; + unsigned ma, mi; + struct stat st; + xfmt(f, sizeof(f), "%s/dev", sys); + if (slurp(f, buf, sizeof(buf)) < 0 || sscanf(buf, "%u:%u", &ma, &mi) != 2) { + err("%s: no device number in sysfs", name); + return -1; + } + nd->rdev = makedev(ma, mi); + if (stat(nd->path, &st) || !S_ISBLK(st.st_mode) || st.st_rdev != nd->rdev) { + err("%s is not the block device sysfs names (%u:%u)", nd->path, ma, mi); + return -1; + } +#endif + return 0; +} + +static int is_part_dir(const char *sys) +{ + char f[PATH_MAX + 16]; + xfmt(f, sizeof(f), "%s/partition", sys); + return access(f, F_OK) == 0; +} + +static int find_devinfo(struct target *t) +{ + char sysblock[PATH_MAX], dsys[PATH_MAX * 2], psys[PATH_MAX * 3], pn[64]; + char devinfo_disk[32] = ""; + int found = 0, userdata = 0; + memset(t, 0, sizeof(*t)); + rp(sysblock, sizeof(sysblock), "/sys/block"); + DIR *d = opendir(sysblock); + if (!d) { + err("can't list %s: %s", sysblock, strerror(errno)); + return -1; + } + struct dirent *e; + while ((e = readdir(d))) { + if (strncmp(e->d_name, "sd", 2)) + continue; + xfmt(dsys, sizeof(dsys), "%s/%s", sysblock, e->d_name); + DIR *dd = opendir(dsys); + if (!dd) + continue; + struct dirent *p; + while ((p = readdir(dd))) { + if (strncmp(p->d_name, e->d_name, strlen(e->d_name)) || !p->d_name[strlen(e->d_name)]) + continue; + xfmt(psys, sizeof(psys), "%s/%s", dsys, p->d_name); + if (!is_part_dir(psys) || partname(psys, pn, sizeof(pn))) + continue; + if (!strcmp(pn, "devinfo")) { + if (found++ == 0) { + xfmt(devinfo_disk, sizeof(devinfo_disk), "%s", e->d_name); + if (fill_node(&t->part, p->d_name, psys) || + fill_node(&t->disk, e->d_name, dsys)) { + closedir(dd); + closedir(d); + return -1; + } + } + } else if (!strcmp(pn, "userdata")) { + userdata++; + xfmt(t->main_disk, sizeof(t->main_disk), "%s", e->d_name); + } + } + closedir(dd); + } + closedir(d); + if (found != 1) { + err(found ? "%d partitions are named devinfo; refusing" : "no partition is named devinfo", found); + return -1; + } + if (userdata != 1) { + err("expected one userdata partition, found %d; is the storage layout this phone's?", userdata); + return -1; + } + if (!strcmp(devinfo_disk, t->main_disk)) { + err("devinfo is on the main LUN (%s); this tool knows only devinfo on a boot LUN", devinfo_disk); + return -1; + } + /* The disk's other partitions, whose own flags are checked in the window. */ + xfmt(dsys, sizeof(dsys), "%s/%s", sysblock, t->disk.name); + DIR *dd = opendir(dsys); + if (!dd) + return -1; + while ((e = readdir(dd))) { + if (strncmp(e->d_name, t->disk.name, strlen(t->disk.name)) || !e->d_name[strlen(t->disk.name)] || + !strcmp(e->d_name, t->part.name)) + continue; + xfmt(psys, sizeof(psys), "%s/%s", dsys, e->d_name); + if (!is_part_dir(psys)) + continue; + if (t->nsib == (int)(sizeof(t->sib) / sizeof(t->sib[0])) || + fill_node(&t->sib[t->nsib++], e->d_name, psys)) { + closedir(dd); + err("can't list the partitions of %s", t->disk.name); + return -1; + } + } + closedir(dd); + return 0; +} + +/* ---- checks ------------------------------------------------------------- */ + +static int check_phone(void) +{ + char f[PATH_MAX], buf[512]; +#ifndef BOOTCTL_TEST + if (geteuid() != 0) { + err("run as root"); + return -1; + } +#endif + rp(f, sizeof(f), "/sys/firmware/devicetree/base/compatible"); + if (slurp(f, buf, sizeof(buf)) < 0) { + err("can't read the board's compatible string"); + return -1; + } + if (strcmp(buf, BOOTCTL_COMPATIBLE)) { /* the first string, up to its NUL */ + err("this board is \"%s\", not %s (\"%s\"); this build is for %s only", + buf, BOOTCTL_CODENAME, BOOTCTL_COMPATIBLE, BOOTCTL_CODENAME); + return -1; + } + return 0; +} + +static char booted_slot(void) +{ + char f[PATH_MAX], buf[16384]; + rp(f, sizeof(f), "/proc/bootconfig"); + if (slurp(f, buf, sizeof(buf)) < 0) + return 0; + for (char *l = strtok(buf, "\n"); l; l = strtok(NULL, "\n")) { + if (!strcmp(l, "androidboot.slot_suffix = \"_a\"")) + return 'a'; + if (!strcmp(l, "androidboot.slot_suffix = \"_b\"")) + return 'b'; + } + return 0; +} + +static int same_file(const struct stat *st, const struct node *n) +{ +#ifdef BOOTCTL_TEST + struct stat ns; + return !stat(n->path, &ns) && ns.st_dev == st->st_dev && ns.st_ino == st->st_ino; +#else + return S_ISBLK(st->st_mode) && st->st_rdev == n->rdev; +#endif +} + +/* devinfo not mounted, held, or open for writing by anyone else. */ +static int check_unused(const struct target *t) +{ + char f[PATH_MAX], line[4096], src[PATH_MAX]; + int bad = 0; + + rp(f, sizeof(f), "/proc/self/mountinfo"); + FILE *fp = fopen(f, "r"); + if (!fp) { + err("can't read %s", f); + return -1; + } + xfmt(src, sizeof(src), "/dev/%s", t->part.name); + while (fgets(line, sizeof(line), fp)) { + unsigned ma = 0, mi = 0; + char *sep = strstr(line, " - "); + char fstype[64] = "", source[PATH_MAX] = ""; + if (sscanf(line, "%*s %*s %u:%u", &ma, &mi) != 2 || !sep) + continue; + sscanf(sep + 3, "%63s %4095s", fstype, source); + if (!strcmp(source, src) || (t->part.rdev && makedev(ma, mi) == t->part.rdev)) { + err("devinfo (%s) is mounted; refusing", src); + bad = 1; + } + } + fclose(fp); + + /* Nothing stacked on the disk, devinfo or a sibling (dm, md, loop...). */ + const struct node *held[2 + (int)(sizeof(t->sib) / sizeof(t->sib[0]))]; + int nh = 0; + held[nh++] = &t->disk; + held[nh++] = &t->part; + for (int i = 0; i < t->nsib; i++) + held[nh++] = &t->sib[i]; + for (int i = 0; i < nh; i++) { + xfmt(f, sizeof(f), "%s/holders", held[i]->sys); + DIR *d = opendir(f); + if (!d) + continue; + struct dirent *e; + while ((e = readdir(d))) + if (e->d_name[0] != '.') { + err("%s is held by %s; refusing", held[i]->name, e->d_name); + bad = 1; + } + closedir(d); + } + + /* Any process with the disk or one of its partitions open for writing. */ + DIR *d = opendir("/proc"); + if (!d) + return -1; + struct dirent *pe; + pid_t self = getpid(); + while ((pe = readdir(d))) { + if (!isdigit((unsigned char)pe->d_name[0]) || atoi(pe->d_name) == self) + continue; + char fdd[PATH_MAX]; + xfmt(fdd, sizeof(fdd), "/proc/%s/fd", pe->d_name); + DIR *fds = opendir(fdd); + if (!fds) + continue; + struct dirent *fe; + while ((fe = readdir(fds))) { + if (fe->d_name[0] == '.') + continue; + char lp[PATH_MAX * 2], info[PATH_MAX * 2], buf[1024]; + struct stat st; + xfmt(lp, sizeof(lp), "%s/%s", fdd, fe->d_name); + if (stat(lp, &st)) + continue; + int hit = same_file(&st, &t->part) || same_file(&st, &t->disk); + for (int i = 0; !hit && i < t->nsib; i++) + hit = same_file(&st, &t->sib[i]); + if (!hit) + continue; + xfmt(info, sizeof(info), "/proc/%s/fdinfo/%s", pe->d_name, fe->d_name); + char *fl; + unsigned long flags = 0; + if (slurp(info, buf, sizeof(buf)) >= 0 && (fl = strstr(buf, "flags:"))) + flags = strtoul(fl + 6, NULL, 8); + if ((flags & O_ACCMODE) != O_RDONLY) { + err("process %s has %s or one of its partitions open for writing; refusing", + pe->d_name, t->disk.name); + bad = 1; + } + } + closedir(fds); + } + closedir(d); + return bad ? -1 : 0; +} + +static int in_allowlist(const char *name) +{ + for (int i = 0; allowlist[i]; i++) + if (!strcmp(name, allowlist[i])) + return 1; + return 0; +} + +/* + * The storage guard as the initramfs leaves it: the main LUN's whole-disk + * node gone (or mode 0000), every other disk and every partition outside the + * allowlist read-only, devinfo and its disk among them. + */ +static int check_guard(const struct target *t) +{ + char f[PATH_MAX], dsys[PATH_MAX * 2], psys[PATH_MAX * 3], pn[64]; + struct stat st; + int bad = 0; + + rp(f, sizeof(f), "/dev/%s", t->main_disk); + if (!stat(f, &st) && (st.st_mode & 07777)) { + err("the main LUN's whole-disk node %s is usable (mode %o); the storage guard is not holding", + f, st.st_mode & 07777); + bad = 1; + } + rp(f, sizeof(f), "/sys/block"); + DIR *d = opendir(f); + if (!d) + return -1; + struct dirent *e; + while ((e = readdir(d))) { + if (strncmp(e->d_name, "sd", 2)) + continue; + struct node disk; + xfmt(dsys, sizeof(dsys), "%s/%s", f, e->d_name); + xfmt(disk.name, sizeof(disk.name), "%s", e->d_name); + rp(disk.path, sizeof(disk.path), "/dev/%s", e->d_name); + int main_disk = !strcmp(e->d_name, t->main_disk); + if (!main_disk && ro_get(&disk, NULL) != 1) { + err("%s is not read-only; the storage guard is not holding", e->d_name); + bad = 1; + } + DIR *dd = opendir(dsys); + if (!dd) + continue; + struct dirent *p; + while ((p = readdir(dd))) { + if (strncmp(p->d_name, e->d_name, strlen(e->d_name)) || !p->d_name[strlen(e->d_name)]) + continue; + xfmt(psys, sizeof(psys), "%s/%s", dsys, p->d_name); + if (!is_part_dir(psys) || partname(psys, pn, sizeof(pn))) + continue; + if (main_disk && in_allowlist(pn)) + continue; + struct node part; + xfmt(part.name, sizeof(part.name), "%s", p->d_name); + rp(part.path, sizeof(part.path), "/dev/%s", p->d_name); + if (ro_get(&part, &disk) != 1) { + err("%s (%s) is not read-only; the storage guard is not holding", p->d_name, pn); + bad = 1; + } + } + closedir(dd); + } + closedir(d); + return bad ? -1 : 0; +} + +/* ---- devinfo contents --------------------------------------------------- */ + +static uint32_t rd32(const uint8_t *p) { return p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24; } +static uint16_t rd16(const uint8_t *p) { return p[0] | p[1] << 8; } + +/* The whole partition, read past the page cache (O_DIRECT) on the phone. */ +static uint8_t *read_image(const struct node *n, size_t *len) +{ + uint8_t *buf = NULL; + int fd = open(n->path, O_RDONLY | O_CLOEXEC | DIRECT); + if (fd < 0) { + err("open %s: %s", n->path, strerror(errno)); + return NULL; + } + if (posix_memalign((void **)&buf, ALIGN, MAX_REGION + ALIGN)) { + close(fd); + return NULL; + } + size_t got = 0; + for (;;) { + ssize_t r = pread(fd, buf + got, MAX_REGION + ALIGN - got, got); + if (r < 0 && errno == EINTR) + continue; + if (r < 0) { + err("read %s: %s", n->path, strerror(errno)); + goto fail; + } + if (r == 0) + break; + got += r; + if (got > MAX_REGION) { + err("%s is larger than %d bytes; is this really devinfo?", n->path, MAX_REGION); + goto fail; + } + } + close(fd); + if (got < DEVINFO_HDR) { + err("%s: only %zu bytes", n->path, got); + free(buf); + return NULL; + } + *len = got; + return buf; +fail: + close(fd); + free(buf); + return NULL; +} + +static int check_layout(const uint8_t *d) +{ + uint32_t magic = rd32(d + OFF_MAGIC); + unsigned maj = rd16(d + OFF_VER_MAJOR), min = rd16(d + OFF_VER_MINOR); + if (magic != DEVINFO_MAGIC) { + err("bad magic 0x%08x (want 0x%08x \"DEVI\"); refusing", magic, DEVINFO_MAGIC); + return -1; + } + if (maj != BOOTCTL_VER_MAJOR || min != BOOTCTL_VER_MINOR) { + err("devinfo version %u.%u is not the %u.%u recorded for %s; refusing", + maj, min, BOOTCTL_VER_MAJOR, BOOTCTL_VER_MINOR, BOOTCTL_CODENAME); + return -1; + } + return 0; +} + +static void print_bytes(const char *label, const uint8_t *d) +{ + printf("%s 0x30-0x37:", label); + for (int i = 0; i < SLOT_BYTES; i++) + printf(" %02x", d[OFF_SLOTS + i]); + printf("\n"); +} + +static void print_slots(const uint8_t *d) +{ + for (int i = 0; i < 2; i++) { + const uint8_t *s = d + OFF_SLOTS + 4 * i; + uint8_t f = s[SLOT_FLAGS]; + printf("slot %c: retry-count %u, active %s, successful %s, unbootable %s, fastboot-ok %s\n", + 'a' + i, s[SLOT_RETRY], f & FLAG_ACTIVE ? "yes" : "no", + f & FLAG_SUCCESSFUL ? "yes" : "no", f & FLAG_UNBOOTABLE ? "yes" : "no", + f & FLAG_FASTBOOT_OK ? "yes" : "no"); + } +} + +/* ---- the read-write window ---------------------------------------------- */ + +static int relock(const struct target *t) +{ + int ok = 1; + /* devinfo first: while its disk is still writable its own flag reads back */ + if (ro_set(&t->part, 1) || ro_get(&t->part, &t->disk) != 1) + ok = 0; + if (ro_set(&t->disk, 1) || ro_get(&t->disk, NULL) != 1) + ok = 0; + return ok ? 0 : -1; +} + +/* + * The relock child. It holds the read end of a pipe whose write end only the + * parent has. Before the window opens it waits without a timeout (nothing is + * writable yet). The parent writes 'O' just before it clears the first flag; + * from then on the child sets devinfo and its disk read-only every + * RELOCK_TIMEOUT_MS for as long as the pipe stays open (a stopped or hung + * parent: its later steps then fail closed), and once more when the pipe + * closes, whether the parent finished, crashed or was killed. It ignores the + * terminal's signals (blocked before the fork), so ^C on the process group + * can't take it with the parent. + */ +static int child_relock(const struct target *t) +{ +#ifdef BOOTCTL_TEST + if (has_fault("no-child-relock")) /* the parent must relock alone */ + return 0; +#endif + return relock(t); +} + +static void relocker(const struct target *t, int rfd) +{ + int armed = 0, ok = 1; + for (;;) { + struct pollfd pf = { .fd = rfd, .events = POLLIN }; + int r = poll(&pf, 1, armed ? relock_timeout_ms : -1); + if (r < 0 && errno == EINTR) + continue; + if (r == 0) { /* window open too long: close it, re-arm */ + if (child_relock(t)) + ok = 0; + continue; + } + char c; + ssize_t n = read(rfd, &c, 1); + if (n < 0 && errno == EINTR) + continue; + if (n == 1 && c == 'O') { + armed = 1; + continue; + } + break; /* EOF: the parent is done or gone */ + } + if (child_relock(t)) + ok = 0; +#ifdef BOOTCTL_TEST + if (has_fault("child-fails")) + ok = 0; +#endif + _exit(ok ? 0 : 1); +} + +static pid_t start_relocker(const struct target *t, int *wfd) +{ + int p[2]; +#ifdef BOOTCTL_TEST + if (has_fault("fork-fails")) + return -1; +#endif + if (pipe2(p, O_CLOEXEC)) + return -1; + pid_t pid = fork(); + if (pid < 0) { + close(p[0]); + close(p[1]); + return -1; + } + if (pid == 0) { + close(p[1]); + relocker(t, p[0]); + } + close(p[0]); + *wfd = p[1]; + return pid; +} + +/* The child must be alive before every step that opens anything further. */ +static int child_alive(pid_t child, int *reaped, int *st) +{ + if (*reaped) + return 0; + pid_t r = waitpid(child, st, WNOHANG); + if (r == child) { + *reaped = 1; + return 0; + } + return r == 0; +} + +static int write_at(const struct target *t, const uint8_t *buf, size_t len, off_t off) +{ +#ifdef BOOTCTL_TEST + /* the kernel refuses a write to a read-only partition (blkdev_write_iter) */ + if (ro_get(&t->part, &t->disk) != 0) { + errno = EPERM; + return -1; + } + if (has_fault("write-fails")) { + errno = EIO; + return -1; + } + if (has_fault("restore-noop") && off == 0 && len > 2) + return 0; /* the restore "succeeds" without landing */ +#endif + int fd = open(t->part.path, O_WRONLY | O_DSYNC | O_CLOEXEC); + if (fd < 0) + return -1; + ssize_t w = pwrite(fd, buf, len, off); + int e = errno; + if (w == (ssize_t)len && fdatasync(fd) == 0) { + close(fd); + return 0; + } + close(fd); + errno = w < 0 ? e : EIO; + return -1; +} + +#ifdef BOOTCTL_TEST +static void test_fault(const char *where) +{ + if (has_fault(where)) + raise(SIGKILL); + if (!strcmp(where, "kill-before-write") && has_fault("hang-in-window")) + sleep(60); +} + +/* Someone else changes devinfo inside the window (test only). */ +static void test_change_under(const struct target *t) +{ + if (!has_fault("change-under")) + return; + int fd = open(t->part.path, O_WRONLY); + uint8_t x = 0x5a; + if (fd >= 0) { + if (pwrite(fd, &x, 1, 0x100) != 1) + err("test: change-under failed"); + close(fd); + } +} +#else +#define test_fault(x) ((void)0) +#define test_change_under(t) ((void)0) +#endif + +/* + * Returns 0 written and verified, 3 failed with devinfo as it was before, + * 4 failed and devinfo may differ, 5 the read-only flags could not be + * restored (the loudest failure: the guard has a hole until a reboot). + */ +static int window(const struct target *t, const uint8_t *orig, size_t len, uint8_t newval) +{ + int rc = 3, wfd = -1, reaped = 0, st = 0; + uint8_t *after = NULL, *want = NULL, *again = NULL, byte = newval; + size_t alen; + sigset_t block, old; +#ifdef BOOTCTL_TEST + uint8_t bad[2] = { (uint8_t)(orig[OFF_B_FLAGS - 1] ^ 0x01), newval }; +#endif + + sigemptyset(&block); + sigaddset(&block, SIGINT); + sigaddset(&block, SIGTERM); + sigaddset(&block, SIGHUP); + sigaddset(&block, SIGQUIT); + sigaddset(&block, SIGTSTP); + sigaddset(&block, SIGPIPE); + sigprocmask(SIG_BLOCK, &block, &old); + + pid_t child = start_relocker(t, &wfd); + if (child < 0) { + err("can't start the relock child; nothing written"); + sigprocmask(SIG_SETMASK, &old, NULL); + return 3; + } +#ifdef BOOTCTL_TEST + if (has_fault("stop-before-open")) + raise(SIGSTOP); +#endif + /* The child's timer runs from here, as long as the window stays open. */ + if (write(wfd, "O", 1) != 1 || !child_alive(child, &reaped, &st)) { + err("the relock child is not running; nothing written"); + goto close_window; + } +#ifdef BOOTCTL_TEST + if (has_fault("stop-after-open")) + raise(SIGSTOP); +#endif + + /* 1. The disk: the kernel won't write a partition of a read-only disk. */ + if (ro_set(&t->disk, 0) || ro_get(&t->disk, NULL) != 0) { + err("%s did not become writable; nothing written", t->disk.name); + goto close_window; + } + /* 2. With the disk flag clear, each partition reads its own flag: all set. */ + for (int i = 0; i < t->nsib; i++) + if (ro_get(&t->sib[i], &t->disk) != 1) { + err("%s's own read-only flag is clear or unreadable: clearing %s's would expose it; refusing", + t->sib[i].name, t->disk.name); + goto close_window; + } + if (ro_get(&t->part, &t->disk) != 1) { + err("devinfo's own read-only flag was already clear; the guard did not set it; refusing"); + goto close_window; + } + /* 3. devinfo itself. */ + if (!child_alive(child, &reaped, &st)) { + err("the relock child is gone; nothing written"); + goto close_window; + } + if (ro_set(&t->part, 0) || ro_get(&t->part, &t->disk) != 0) { + err("can't make devinfo writable: %s", strerror(errno)); + goto close_window; + } + test_change_under(t); + /* 4. Nothing moved since the checks. */ + again = read_image(&t->part, &alen); + if (!again || alen != len || memcmp(again, orig, len)) { + err("devinfo changed since it was checked; nothing written"); + free(again); + goto close_window; + } + free(again); + test_fault("kill-before-write"); + + /* 5. The one byte (the kernel writes the 4 KiB block that holds it). */ + want = malloc(len); + if (!want) + goto close_window; + memcpy(want, orig, len); + want[OFF_B_FLAGS] = newval; + if (!child_alive(child, &reaped, &st)) { + err("the relock child is gone; nothing written"); + goto close_window; + } +#ifdef BOOTCTL_TEST + if (has_fault("corrupt-write")) { /* a stray change next to ours */ + if (write_at(t, bad, 2, OFF_B_FLAGS - 1)) + goto write_failed; + } else +#endif + if (write_at(t, &byte, 1, OFF_B_FLAGS)) { + goto write_failed; + } + test_fault("kill-after-write"); + + /* 6. Read back past the cache: everything as before but that byte. */ + after = read_image(&t->part, &alen); + if (after && alen == len && !memcmp(after, want, len)) { + rc = 0; + goto close_window; + } + err("VERIFY FAILED: devinfo does not read back as written; restoring the original"); + free(after); + after = NULL; + if (write_at(t, orig, len, 0)) { + err("RESTORE FAILED: %s; devinfo may differ from the backup", strerror(errno)); + rc = 4; + goto close_window; + } + after = read_image(&t->part, &alen); + if (after && alen == len && !memcmp(after, orig, len)) { + err("restored: devinfo reads back as it was before"); + rc = 3; + } else { + err("RESTORE FAILED: devinfo does not read back as before; restore it from the backup"); + rc = 4; + } + goto close_window; + +write_failed: + err("write failed: %s", strerror(errno)); + after = read_image(&t->part, &alen); + rc = (after && alen == len && !memcmp(after, orig, len)) ? 3 : 4; + if (rc == 4) + err("devinfo no longer reads as before; restore it from the backup"); + +close_window: + /* 7. Read-only again, devinfo then the disk, each read back; then the child. */ + if (relock(t)) { + err("FAILED to set devinfo or %s read-only again; reboot to restore the guard", t->disk.name); + rc = 5; + } + close(wfd); + if (!reaped) + while (waitpid(child, &st, 0) < 0 && errno == EINTR) + ; + if (!WIFEXITED(st) || WEXITSTATUS(st)) { + err("the relock child failed; reboot to restore the guard"); + rc = 5; + } + sigprocmask(SIG_SETMASK, &old, NULL); + free(after); + free(want); + return rc; +} + +/* ---- commands ----------------------------------------------------------- */ + +static int parse_expect(const char *s, uint8_t out[SLOT_BYTES]) +{ + int n = 0, half = -1; + for (; *s; s++) { + if (*s == ' ' || *s == ':' || *s == '\t') + continue; + if (!isxdigit((unsigned char)*s) || n == SLOT_BYTES) + return -1; + int v = isdigit((unsigned char)*s) ? *s - '0' : (tolower((unsigned char)*s) - 'a' + 10); + if (half < 0) { + half = v; + } else { + out[n++] = half << 4 | v; + half = -1; + } + } + return n == SLOT_BYTES && half < 0 ? 0 : -1; +} + +static int read_codename(char *out, size_t n) +{ + FILE *tty = fopen("/dev/tty", "r+"); + if (!tty) + return -1; + fprintf(tty, "This writes devinfo on this phone. Type its codename (%s) to go on: ", BOOTCTL_CODENAME); + fflush(tty); + if (!fgets(out, n, tty)) { + fclose(tty); + return -1; + } + fclose(tty); + out[strcspn(out, "\r\n")] = 0; + return 0; +} + +static int prepare(struct target *t, uint8_t **img, size_t *len) +{ + if (check_phone() || find_devinfo(t)) + return -1; + printf("omamobile-bootctl for %s: devinfo is %s on %s\n", BOOTCTL_CODENAME, t->part.name, t->disk.name); + *img = read_image(&t->part, len); + if (!*img || check_layout(*img)) + return -1; + printf("devinfo version %u.%u (the layout recorded for %s)\n", + BOOTCTL_VER_MAJOR, BOOTCTL_VER_MINOR, BOOTCTL_CODENAME); + return 0; +} + +static int cmd_status(void) +{ + struct target t; + uint8_t *img = NULL; + size_t len; + if (prepare(&t, &img, &len)) { + free(img); + return 1; + } + char s = booted_slot(); + printf("booted from slot %c\n", s ? s : '?'); + print_bytes("bytes", img); + print_slots(img); + int g = check_guard(&t); + printf("storage guard: %s\n", g ? "NOT as expected (see above)" : "holding"); + free(img); + return 0; +} + +static int cmd_mark(int do_write, const char *expect, const char *codename) +{ + struct target t; + uint8_t *img = NULL, *after = NULL, exp[SLOT_BYTES], fb, nv; + size_t len, alen; + int rc = 1; + char typed[64] = ""; + + if (do_write && (!expect || parse_expect(expect, exp))) { + err("--write needs --expect with the eight bytes the dry run printed"); + return 2; + } + if (prepare(&t, &img, &len)) + goto out; + if (booted_slot() != 'b') { + err("this boot is not from slot b; mark slot b only from a boot of slot b"); + goto out; + } + if (check_guard(&t) || check_unused(&t)) + goto out; + + fb = img[OFF_B_FLAGS]; + print_bytes("before", img); + print_slots(img); + if (!(fb & FLAG_ACTIVE)) { + err("slot b is not the active slot; refusing"); + goto out; + } + if (fb & FLAG_UNBOOTABLE) { + err("slot b is marked unbootable; refusing"); + goto out; + } + if (fb & FLAG_SUCCESSFUL) { + printf("slot b is already marked successful; nothing to write\n"); + rc = 0; + goto out; + } + nv = fb | FLAG_SUCCESSFUL; + printf("planned: byte 0x%02x %02x -> %02x (slot b successful), nothing else\n", OFF_B_FLAGS, fb, nv); + + if (!do_write) { + printf("dry run: nothing written. To write, after the runbook's backup:\n" + " omamobile-bootctl mark-b-successful --write --codename %s --expect \"", BOOTCTL_CODENAME); + for (int i = 0; i < SLOT_BYTES; i++) + printf("%s%02x", i ? " " : "", img[OFF_SLOTS + i]); + printf("\"\n"); + rc = 0; + goto out; + } + if (memcmp(exp, img + OFF_SLOTS, SLOT_BYTES)) { + err("the slot bytes are not the ones given with --expect; run the dry run again"); + goto out; + } + if (codename) + xfmt(typed, sizeof(typed), "%s", codename); + else if (read_codename(typed, sizeof(typed))) + typed[0] = 0; + if (strcmp(typed, BOOTCTL_CODENAME)) { + err("codename \"%s\" is not %s; nothing written", typed, BOOTCTL_CODENAME); + goto out; + } +#ifdef BOOTCTL_TEST + if (has_fault("hold-after-codename")) { /* stands in for a slow prompt */ + char f[PATH_MAX]; + rp(f, sizeof(f), "/at-prompt"); + close(open(f, O_CREAT | O_WRONLY, 0644)); + rp(f, sizeof(f), "/go"); + for (int i = 0; i < 200 && access(f, F_OK); i++) + usleep(50000); + } +#endif + /* The checks again, right before the window: the prompt can take minutes. */ + if (check_guard(&t) || check_unused(&t)) { + err("the storage guard or a user of the LUN changed since the checks; nothing written"); + goto out; + } + + rc = window(&t, img, len, nv); + after = read_image(&t.part, &alen); + if (after) + print_bytes("after ", after); + if (rc == 0) { + printf("slot b marked successful: written, read back, devinfo and %s read-only again\n", t.disk.name); + } +out: + free(after); + free(img); + return rc; +} + +static int usage(void) +{ + fprintf(stderr, + "usage: %s status\n" + " %s mark-b-successful (dry run, writes nothing)\n" + " %s mark-b-successful --write --expect \"\" [--codename %s]\n" + "Build for %s, devinfo %u.%u. Attended use only, from the device plan's runbook.\n", + argv0, argv0, argv0, BOOTCTL_CODENAME, BOOTCTL_CODENAME, BOOTCTL_VER_MAJOR, BOOTCTL_VER_MINOR); + return 2; +} + +int main(int argc, char **argv) +{ + int do_write = 0; + const char *expect = NULL, *codename = NULL, *cmd = NULL; + +#ifdef BOOTCTL_TEST + if (getenv("BOOTCTL_TEST_ROOT")) + root = getenv("BOOTCTL_TEST_ROOT"); + if (getenv("BOOTCTL_TEST_FAULT")) + fault = getenv("BOOTCTL_TEST_FAULT"); + if (getenv("BOOTCTL_TEST_RELOCK_MS")) + relock_timeout_ms = atoi(getenv("BOOTCTL_TEST_RELOCK_MS")); +#endif + setvbuf(stdout, NULL, _IOLBF, 0); + for (int i = 1; i < argc; i++) { + if (!strcmp(argv[i], "--write")) + do_write = 1; + else if (!strcmp(argv[i], "--expect") && i + 1 < argc) + expect = argv[++i]; + else if (!strcmp(argv[i], "--codename") && i + 1 < argc) + codename = argv[++i]; + else if (!cmd && argv[i][0] != '-') + cmd = argv[i]; + else + return usage(); + } + if (!cmd) + return usage(); + if (!strcmp(cmd, "status") && !do_write && !expect && !codename) + return cmd_status(); + if (!strcmp(cmd, "mark-b-successful")) + return cmd_mark(do_write, expect, codename); + return usage(); +} diff --git a/packages/omamobile-device-tegu/build b/packages/omamobile-device-tegu/build index dbbae3421..1062e7316 100755 --- a/packages/omamobile-device-tegu/build +++ b/packages/omamobile-device-tegu/build @@ -7,3 +7,4 @@ out=${1:-build} mkdir -p "$out" ${CC:-cc} ${CFLAGS:--O2} -Wall -Wextra -o "$out/reboot-to" src/reboot-to.c ${LDFLAGS:-} ${CC:-cc} ${CFLAGS:--O2} -Wall -Wextra -o "$out/tegu-tcpc-switch" src/tegu-tcpc-switch.c ${LDFLAGS:-} +${CC:-cc} ${CFLAGS:--O2} -Wall -Wextra -Ibootctl -o "$out/omamobile-bootctl" bootctl/omamobile-bootctl.c ${LDFLAGS:-} diff --git a/packages/omamobile-device-tegu/install b/packages/omamobile-device-tegu/install index 049fa4c1d..c984ffcc7 100755 --- a/packages/omamobile-device-tegu/install +++ b/packages/omamobile-device-tegu/install @@ -10,7 +10,8 @@ destination=${1:?Usage: ./install DESTDIR [BUILDDIR]} build=${2:-build} [[ $destination == /* && $destination != "/" ]] || { echo "Use an absolute staging directory" >&2; exit 1; } for file in bin/*; do install -Dm755 "$file" "$destination/usr/bin/${file##*/}"; done -for tool in reboot-to tegu-tcpc-switch; do install -Dm755 "$build/$tool" "$destination/usr/bin/$tool"; done +# omamobile-bootctl is for the owner to run by hand (#252); no unit or hook calls it. +for tool in reboot-to tegu-tcpc-switch omamobile-bootctl; do install -Dm755 "$build/$tool" "$destination/usr/bin/$tool"; done while IFS= read -r -d '' file; do mode=644 [[ $file == vendor/systemd/system-sleep/* ]] && mode=755 @@ -26,4 +27,5 @@ install -Dm644 uwsm/env.d/omamobile-tegu-graphics "$destination/usr/share/uwsm/e install -Dm644 device.conf "$destination/usr/share/omamobile/device.conf" install -Dm644 etc/omamobile-mirrorlist "$destination/etc/pacman.d/omamobile-mirrorlist" install -Dm644 LICENSE "$destination/usr/share/licenses/omamobile-device-tegu/LICENSE" +install -Dm644 LICENSE.Apache-2.0 "$destination/usr/share/licenses/omamobile-device-tegu/LICENSE.Apache-2.0" install -Dm644 version "$destination/usr/share/omamobile/device-tegu/version" diff --git a/packages/omamobile-device-tegu/test/all b/packages/omamobile-device-tegu/test/all index 1385230cd..84bbc2f83 100755 --- a/packages/omamobile-device-tegu/test/all +++ b/packages/omamobile-device-tegu/test/all @@ -73,12 +73,47 @@ macs=$(grep -rEn '\b([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}\b' --exclude-dir=build . [[ -z $macs ]] || fail "a MAC or Bluetooth address in the package: $macs" pass "no blobs, no addresses" +# omamobile-bootctl (#252): one source and one test in the husky and tegu +# packages, byte for byte; the per-phone values are in bootctl/bootctl-device.h. +# It is installed for the owner to run by hand: no unit, hook or script here +# may call it, and nothing enables it. +other=../omamobile-device-husky +if [[ -d $other ]]; then + cmp -s bootctl/omamobile-bootctl.c "$other/bootctl/omamobile-bootctl.c" \ + || fail "omamobile-bootctl.c drifted from the husky package" + cmp -s test/bootctl "$other/test/bootctl" || fail "test/bootctl drifted from the husky package" + pass "omamobile-bootctl.c and test/bootctl match the husky package" +fi +if [[ -f ../omamobile-device-cheetah/LICENSE.Apache-2.0 ]]; then + cmp -s LICENSE.Apache-2.0 ../omamobile-device-cheetah/LICENSE.Apache-2.0 || fail "LICENSE.Apache-2.0 drifted from the cheetah package" +fi +grep -qx '#define BOOTCTL_CODENAME[[:space:]]*"tegu"' bootctl/bootctl-device.h || fail "bootctl-device.h is not tegu's" +compat=$(sed -n 's/^COMPATIBLE="\(.*\)"$/\1/p' device.conf) +grep -qx "#define BOOTCTL_COMPATIBLE[[:space:]]*\"$compat\"" bootctl/bootctl-device.h \ + || fail "bootctl-device.h's compatible is not device.conf's ($compat)" +pass "bootctl-device.h names tegu and device.conf's compatible" +grep -rlw 'omamobile-bootctl' vendor bin uwsm *.install 2>/dev/null && fail "a unit, hook or script calls omamobile-bootctl" +pass "nothing in the package calls omamobile-bootctl" +# bin/omamobile's initramfs builder compiles packages//src/omamobile-bootctl.c +# (and tools/stage-boot-files hashes src/) into the boot image: this tool +# belongs in the installed package only, so nothing may sit where they look. +[[ ! -e src/omamobile-bootctl.c ]] || fail "src/omamobile-bootctl.c would be built into the initramfs" +if [[ -f ../../bin/omamobile ]]; then + while read -r probe; do + [[ -z $probe || ! -e $probe ]] || fail "bin/omamobile would build $probe into the initramfs" + done < <(grep -oh 'packages/\$DEV_PACKAGE/[A-Za-z0-9_./-]*' ../../bin/omamobile | sed 's#^packages/\$DEV_PACKAGE/##' | sort -u) +fi +! ls src/ 2>/dev/null | grep -c bootctl >/dev/null || fail "a bootctl file under src/, where the boot-file tools look" +pass "the tool is outside the paths the initramfs builder and stage-boot-files read" +test/bootctl || fail "test/bootctl" + ./build "$tmp/build" || fail "the C tools compile" -[[ -x $tmp/build/reboot-to && -x $tmp/build/tegu-tcpc-switch ]] || fail "the C tools are not executable" +[[ -x $tmp/build/reboot-to && -x $tmp/build/tegu-tcpc-switch && -x $tmp/build/omamobile-bootctl ]] || fail "the C tools are not executable" pass "the C tools compile" ./install "$tmp/root" "$tmp/build" -for f in usr/bin/reboot-to usr/bin/tegu-tcpc-switch \ +for f in usr/bin/reboot-to usr/bin/tegu-tcpc-switch usr/bin/omamobile-bootctl \ + usr/share/licenses/omamobile-device-tegu/LICENSE.Apache-2.0 \ usr/bin/omamobile-tegu-graphics-start usr/lib/systemd/system/omamobile-tegu-graphics.service \ usr/lib/systemd/system/display-manager.service.d/10-omamobile-tegu.conf \ usr/bin/omamobile-tegu-aoc-start usr/lib/systemd/system/omamobile-tegu-aoc.service \ @@ -180,7 +215,7 @@ grep -q 'omamobile-tegu-display-card' "$tmp/root/usr/share/uwsm/env.d/omamobile- || fail "the session reads the graphics start's two files" grep -q 'After=omamobile-tegu-graphics.service' "$tmp/root/usr/lib/systemd/system/display-manager.service.d/10-omamobile-tegu.conf" \ || fail "the display manager waits for the graphics start" -for absent in usr/bin/omamobile-boot-success usr/bin/omamobile-bootctl \ +for absent in usr/bin/omamobile-boot-success \ usr/lib/systemd/system/omamobile-boot-success.service \ usr/bin/omamobile-wifi-start usr/bin/omamobile-charge-guard \ usr/bin/omamobile-camera-start usr/bin/omamobile-aoc-start \ @@ -195,7 +230,8 @@ grep -qx 'Environment=OMAMOBILE_SIT_SCREEN_ON_AT_START=1' vendor/systemd/system/ || fail "the 9a's sitd tells its modem the screen is on at start-up (signal reports)" ! grep -rq OMAMOBILE_SIT_SCREEN_ON_AT_START ../omamobile-device-cheetah ../omamobile-device-raven \ || fail "only the 9a sets the start-up screen-on" -pass "install stages the package, enables only the guards, and nothing that marks a slot" +! grep -rlw omamobile-bootctl "$tmp/root/usr/lib" "$tmp/root/etc" "$tmp/root/usr/share" || fail "a staged unit or hook calls omamobile-bootctl" +pass "install stages the package, enables only the guards, and nothing that marks a slot (omamobile-bootctl is for use by hand)" for m in cpif shm_ipc pcie_gs201_cp gnss_spi gnssif; do grep -qx "blacklist $m" "$tmp/root/usr/lib/modprobe.d/omamobile-tegu-guards.conf" \ diff --git a/packages/omamobile-device-tegu/test/bootctl b/packages/omamobile-device-tegu/test/bootctl new file mode 100755 index 000000000..e18fceed2 --- /dev/null +++ b/packages/omamobile-device-tegu/test/bootctl @@ -0,0 +1,389 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# Offline tests for omamobile-bootctl (the same file in omamobile-device-husky +# and omamobile-device-tegu). No phone, no block device, no ioctl: the test +# build (-DBOOTCTL_TEST) reads a fake /sys, /proc and /dev under a scratch +# root, its "block devices" are files, and each read-only flag is a file +# beside its device that follows the kernel's rule (a partition is read-only +# when its own flag or its disk's flag is set). The production build is +# compiled too, and checked to carry none of the test hooks. +# +# test/bootctl build and run every case +# test/bootctl --mutations also break each key guard in a copy of the +# source and check that a case catches it +# BOOTCTL_BIN= test/bootctl --cases run the cases on a binary +set -euo pipefail +cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." +fail() { printf 'not ok - %s\n' "$1" >&2; exit 1; } +pass() { [[ -n ${QUIET:-} ]] || printf 'ok - %s\n' "$1"; } +tmp=$(mktemp -d) +bgpids=() +# A case that fails can leave a stopped or hung tool behind: kill it and its +# relock child, so neither outlives the test or holds the binary. +cleanup() { local p; for p in "${bgpids[@]}"; do pkill -KILL -P "$p" 2>/dev/null || true; kill -KILL "$p" 2>/dev/null || true; done; rm -rf "$tmp"; } +trap cleanup EXIT + +codename=$(sed -n 's/^#define BOOTCTL_CODENAME[[:space:]]*"\(.*\)"$/\1/p' bootctl/bootctl-device.h) +compatible=$(sed -n 's/^#define BOOTCTL_COMPATIBLE[[:space:]]*"\(.*\)"$/\1/p' bootctl/bootctl-device.h) +[[ -n $codename && -n $compatible ]] || fail "bootctl/bootctl-device.h names a codename and a compatible" + +build_test() { ${CC:-cc} -O2 -Wall -Wextra ${3:--Werror} -DBOOTCTL_TEST -Ibootctl -o "$2" "$1"; } + +# A phone as the storage guard leaves it: sda (main LUN, node removed) with +# persist and userdata, sdb with abl, sdd with devinfo and three siblings. +# Every flag set except userdata's and the main disk's. +mkroot() { + local r=$1 ver=${2:-15} major=${3:-3} + rm -rf "$r"; mkdir -p "$r/dev" "$r/proc/self" "$r/sys/firmware/devicetree/base" + printf '%s\0google,soc\0' "$compatible" > "$r/sys/firmware/devicetree/base/compatible" + printf 'androidboot.hardware = "x"\nandroidboot.slot_suffix = "_b"\n' > "$r/proc/bootconfig" + echo '25 1 259:34 / / rw,relatime shared:1 - ext4 /dev/sda34 rw' > "$r/proc/self/mountinfo" + local d p n + for d in sda sdb sdd; do mkdir -p "$r/sys/block/$d"; echo 1 > "$r/dev/$d.ro"; done + : > "$r/dev/sdb"; : > "$r/dev/sdd" + echo 0 > "$r/dev/sda.ro" + mkpart() { # disk part name ro + mkdir -p "$r/sys/block/$1/$2/holders"; echo 1 > "$r/sys/block/$1/$2/partition" + printf 'MAJOR=8\nMINOR=1\nDEVNAME=%s\nDEVTYPE=partition\nPARTN=1\nPARTNAME=%s\n' "$2" "$3" > "$r/sys/block/$1/$2/uevent" + head -c 8192 /dev/zero > "$r/dev/$2"; echo "$4" > "$r/dev/$2.ro" + } + mkpart sda sda1 persist 1 + mkpart sda sda34 userdata 0 + mkpart sdb sdb1 abl 1 + mkpart sdd sdd1 devinfo 1 + mkpart sdd sdd2 pinfo 1 + mkpart sdd sdd3 blenv 1 + mkpart sdd sdd4 mfg_data 1 + # devinfo: DEVI, 3., ABL-owned bytes we must never print or change, + # slot A 02 1a 00 00 (successful, fastboot-ok, high bit), slot B 00 1c 00 00 + # (active, fastboot-ok, high bit; not successful): the 9a's 2026-10-22 bytes. + python3 - "$r/dev/sdd1" "$ver" "$major" <<'PY' +import struct, sys +d = bytearray(8192) +for i in range(8192): + d[i] = (i * 37 + 11) & 0xff +d[0:8] = struct.pack('&1) || st=$? + [[ $st == 1 || $st == 2 ]] || fail "$name: exit $st, want a refusal ($out)" + unchanged "$name" + pass "$name" + } + fresh() { mkroot "$r" "${1:-15}" "${2:-3}"; cp "$r/dev/sdd1" "$tmp/orig"; } + opened() { grep -qx 'sdd 0' "$r/ro.log" 2>/dev/null && grep -qx 'sdd1 0' "$r/ro.log"; } + + # status: version and the eight slot bytes, nothing else from the partition + fresh + out=$(run status 2>&1) || fail "status runs ($out)" + grep -q "^bytes 0x30-0x37: $expect_bytes$" <<<"$out" || fail "status prints the slot bytes ($out)" + grep -q '^devinfo version 3.15 ' <<<"$out" || fail "status prints the version" + grep -q '^storage guard: holding$' <<<"$out" || fail "status sees the guard holding" + ! grep -qi 'de ad\|dead\|be ef' <<<"$out" || fail "status prints bytes from outside 0x30-0x37" + unchanged "status" + pass "status prints the version and the eight slot bytes, and nothing else" + + # dry run: plans one byte, writes nothing, leaves every flag set + out=$(run mark-b-successful 2>&1) || fail "the dry run passes its checks ($out)" + grep -q '^planned: byte 0x35 1c -> 1e (slot b successful), nothing else$' <<<"$out" || fail "the dry run plans 0x35 1c -> 1e ($out)" + grep -q -- "--write --codename $codename --expect \"$expect_bytes\"" <<<"$out" || fail "the dry run prints the write command" + ! grep -qi 'de ad\|dead\|be ef' <<<"$out" || fail "the dry run prints bytes from outside 0x30-0x37" + unchanged "dry run" + pass "a dry run plans one byte and writes nothing" + + # refusals before any window + fresh 11; refused "devinfo version 3.11 is refused (dry run)" run mark-b-successful + fresh 11; refused "devinfo version 3.11 is refused (write)" write + fresh 16; refused "devinfo version 3.16 (a newer minor) is refused" write + fresh 15 4; refused "devinfo version 4.15 (another major) is refused" write + fresh; printf 'XXXX' | dd of="$r/dev/sdd1" conv=notrunc status=none; cp "$r/dev/sdd1" "$tmp/orig" + refused "bad magic is refused" write + fresh; printf 'google,other-phone\0' > "$r/sys/firmware/devicetree/base/compatible"; refused "another board is refused" write + fresh; sed -i 's/_b"/_a"/' "$r/proc/bootconfig"; refused "a boot from slot a is refused" write + fresh; refused "--write without --expect is refused" run mark-b-successful --write --codename "$codename" + fresh; refused "--write with other bytes in --expect is refused" run mark-b-successful --write --codename "$codename" --expect "02 1a 00 00 01 1c 00 00" + fresh; refused "a wrong codename is refused" run mark-b-successful --write --codename not-"$codename" --expect "$expect_bytes" + fresh; refused "no codename and no terminal is refused" setsid -w env BOOTCTL_TEST_ROOT="$r" "$bin" mark-b-successful --write --expect "$expect_bytes" + fresh; printf '\x1d' | dd of="$r/dev/sdd1" bs=1 seek=$((0x35)) conv=notrunc status=none; cp "$r/dev/sdd1" "$tmp/orig" + refused "an unbootable slot b is refused" write --expect "02 1a 00 00 00 1d 00 00" + fresh; printf '\x18' | dd of="$r/dev/sdd1" bs=1 seek=$((0x35)) conv=notrunc status=none; cp "$r/dev/sdd1" "$tmp/orig" + refused "an inactive slot b is refused" write --expect "02 1a 00 00 00 18 00 00" + fresh; printf '\x1e' | dd of="$r/dev/sdd1" bs=1 seek=$((0x35)) conv=notrunc status=none; cp "$r/dev/sdd1" "$tmp/orig" + out=$(write --expect "02 1a 00 00 00 1e 00 00" 2>&1) || fail "an already marked slot b is not an error ($out)" + grep -q 'already marked successful' <<<"$out" || fail "an already marked slot b says so" + unchanged "already marked"; pass "an already marked slot b writes nothing" + fresh; echo '30 1 8:49 / /mnt ro - vfat /dev/sdd1 ro' >> "$r/proc/self/mountinfo"; refused "a mounted devinfo is refused" write + fresh; mkdir "$r/sys/block/sdd/sdd1/holders/dm-0"; refused "a held devinfo is refused" write + fresh; mkdir -p "$r/sys/block/sdd/holders/md0"; refused "a held boot LUN is refused" write + fresh; mkdir "$r/sys/block/sdd/sdd3/holders/loop0"; refused "a held sibling is refused" write + fresh; sed -i 's/PARTNAME=pinfo/PARTNAME=devinfo/' "$r/sys/block/sdd/sdd2/uevent"; refused "two devinfo partitions are refused" write + fresh; sed -i 's/PARTNAME=devinfo/PARTNAME=devinfo2/' "$r/sys/block/sdd/sdd1/uevent"; refused "no devinfo partition is refused" write + fresh; echo 0 > "$r/dev/sdd.ro"; st=0; write >/dev/null 2>&1 || st=$? + [[ $st == 1 && $(<"$r/dev/sdd.ro") == 0 ]] && cmp -s "$r/dev/sdd1" "$tmp/orig" || fail "a writable boot LUN is refused" + pass "a writable boot LUN is refused (the guard is not holding)" + fresh; echo 0 > "$r/dev/sda1.ro"; st=0; write >/dev/null 2>&1 || st=$? + [[ $st == 1 ]] && cmp -s "$r/dev/sdd1" "$tmp/orig" || fail "a writable persist is refused" + pass "a writable partition outside the allowlist is refused" + fresh; : > "$r/dev/sda"; chmod 600 "$r/dev/sda"; refused "a usable main-LUN node is refused" write + fresh; : > "$r/dev/sda"; chmod 000 "$r/dev/sda"; out=$(run mark-b-successful 2>&1) || fail "a mode-0000 main-LUN node (the udev rule) is accepted ($out)" + pass "a mode-0000 main-LUN node, as the udev rule leaves it, is accepted" + fresh; exec 7<>"$r/dev/sdd"; refused "another process with the boot LUN open for writing is refused" write; exec 7>&- + fresh; exec 7<>"$r/dev/sdd1"; refused "another process with devinfo open for writing is refused" write; exec 7>&- + fresh; exec 7<>"$r/dev/sdd3"; refused "another process with a sibling open for writing is refused" write; exec 7>&- + fresh; exec 7<"$r/dev/sdd"; out=$(run mark-b-successful 2>&1) || fail "a reader of the boot LUN is no reason to refuse ($out)"; exec 7<&- + pass "a process reading the boot LUN is not a reason to refuse" + + # inside the window: a sibling whose own flag is clear (hidden by the disk's), + # each sibling in turn, so directory order can't hide a skipped one + for sib in sdd2 sdd3 sdd4; do + fresh; echo 0 > "$r/dev/$sib.ro" + out=$(run status 2>&1); grep -q '^storage guard: holding$' <<<"$out" || fail "a sibling's own flag is invisible while its disk is read-only" + st=0; out=$(write 2>&1) || st=$? + [[ $st == 3 ]] || fail "$sib with its own flag clear stops the write (exit $st: $out)" + grep -q "$sib's own read-only flag is clear" <<<"$out" || fail "$sib is named" + opened && fail "$sib: devinfo was made writable" + grep -qx 'sdd 0' "$r/ro.log" || fail "$sib: the disk flag was never cleared, so the check never ran" + cmp -s "$r/dev/sdd1" "$tmp/orig" || fail "the $sib case wrote devinfo" + [[ $(<"$r/dev/sdd.ro") == 1 && $(<"$r/dev/sdd1.ro") == 1 ]] || fail "the $sib case left the disk or devinfo writable" + done + pass "each sibling whose own flag is clear stops the write before devinfo opens, and the disk goes read-only again" + fresh; rm "$r/dev/sdd3.ro"; st=0; write >/dev/null 2>&1 || st=$? + [[ $st == 1 && ! -s $r/ro.log ]] && cmp -s "$r/dev/sdd1" "$tmp/orig" || fail "a sibling whose flag can't be read is refused before the window (exit $st)" + fresh; st=0; out=$(BOOTCTL_TEST_FAULT=sdd3-unreadable-in-window write 2>&1) || st=$? + [[ $st == 3 ]] && grep -q "sdd3's own read-only flag is clear or unreadable" <<<"$out" || fail "a sibling whose flag can't be read in the window stops the write (exit $st: $out)" + opened && fail "an unreadable sibling flag: devinfo was made writable" + cmp -s "$r/dev/sdd1" "$tmp/orig" || fail "an unreadable sibling flag: devinfo written" + [[ $(<"$r/dev/sdd.ro") == 1 && $(<"$r/dev/sdd1.ro") == 1 ]] || fail "an unreadable sibling flag left a flag clear" + pass "a sibling whose flag can't be read stops the write" + fresh; st=0; out=$(BOOTCTL_TEST_FAULT=disk-stays-ro write 2>&1) || st=$? + [[ $st == 3 ]] && grep -q 'sdd did not become writable' <<<"$out" || fail "a disk flag that won't clear stops at step 1 (exit $st: $out)" + unchanged "disk flag stuck"; pass "a disk flag that doesn't clear stops the write at step 1" + fresh; echo 0 > "$r/dev/sdd1.ro"; st=0; out=$(write 2>&1) || st=$? + [[ $st == 3 ]] && grep -q "devinfo's own read-only flag was already clear" <<<"$out" || fail "devinfo with its own flag clear stops the write (exit $st: $out)" + cmp -s "$r/dev/sdd1" "$tmp/orig" || fail "the devinfo-flag case wrote devinfo" + [[ $(flags "$r") == "$all_ro" ]] || fail "the devinfo-flag case left $(flags "$r")" + pass "devinfo with its own flag already clear stops the write, and both flags end set" + + # the write: exactly bit 0x02 of byte 0x35, read back, every flag set again + fresh + out=$(write 2>&1) || fail "the write succeeds ($out)" + diffs=$(cmp -l "$tmp/orig" "$r/dev/sdd1" || true) + [[ $(wc -l <<<"$diffs") == 1 ]] || fail "the write changed more than one byte: $diffs" + read -r off old new <<<"$diffs" + [[ $off == $((0x35 + 1)) ]] || fail "the write changed byte $((off - 1)), not 0x35" + (( (8#$old ^ 8#$new) == 2 )) || fail "the write changed byte 0x35 by more than bit 0x02" + [[ $(flags "$r") == "$all_ro" ]] || fail "after the write the flags are $(flags "$r")" + grep -q "^before 0x30-0x37: $expect_bytes$" <<<"$out" || fail "the write prints the bytes before" + grep -q '^after 0x30-0x37: 02 1a 00 00 00 1e 00 00$' <<<"$out" || fail "the write prints the bytes after" + ! grep -qi 'de ad\|dead\|be ef' <<<"$out" || fail "the write prints bytes from outside 0x30-0x37" + pass "a write flips bit 0x02 of byte 0x35 alone, reads it back, and sets every flag again" + fresh; out=$(BOOTCTL_TEST_FAULT=no-child-relock write 2>&1) || fail "the write succeeds without the child's relock ($out)" + [[ $(flags "$r") == "$all_ro" ]] || fail "without the child's relock the flags are $(flags "$r")" + pass "the tool sets every flag again itself, without the relock child" + out=$(write --expect "02 1a 00 00 00 1e 00 00" 2>&1) || fail "a second run is a no-op ($out)" + grep -q 'already marked successful' <<<"$out" || fail "a second run says already marked" + pass "a second run writes nothing" + + # failures inside the window + fresh; st=0; out=$(BOOTCTL_TEST_FAULT=corrupt-write write 2>&1) || st=$? + [[ $st == 3 ]] || fail "a read-back mismatch fails with 3 (exit $st: $out)" + grep -q 'VERIFY FAILED' <<<"$out" && grep -q 'restored: devinfo reads back as it was before' <<<"$out" || fail "a mismatch says it restored ($out)" + unchanged "read-back mismatch"; pass "a read-back mismatch restores the original, sets every flag, and fails" + fresh; st=0; out=$(BOOTCTL_TEST_FAULT=write-fails write 2>&1) || st=$? + [[ $st == 3 ]] || fail "a failed write fails with 3 (exit $st: $out)" + unchanged "failed write"; pass "a failed write leaves devinfo as it was and sets every flag" + fresh; st=0; out=$(BOOTCTL_TEST_FAULT=corrupt-write,restore-noop write 2>&1) || st=$? + [[ $st == 4 ]] && grep -q 'RESTORE FAILED: devinfo does not read back as before' <<<"$out" || fail "a restore that doesn't land fails with 4 (exit $st: $out)" + [[ $(flags "$r") == "$all_ro" ]] || fail "after a failed restore the flags are $(flags "$r")" + pass "a restore that doesn't read back fails with 4, and every flag is set" + fresh; st=0; out=$(BOOTCTL_TEST_FAULT=change-under write 2>&1) || st=$? + [[ $st == 3 ]] && grep -q 'devinfo changed since it was checked' <<<"$out" || fail "devinfo changed inside the window stops the write (exit $st: $out)" + [[ $(od -An -tx1 -j $((0x35)) -N1 "$r/dev/sdd1" | tr -d ' ') == 1c ]] || fail "devinfo changed underneath, and byte 0x35 was written anyway" + [[ $(flags "$r") == "$all_ro" ]] || fail "after a change underneath the flags are $(flags "$r")" + pass "devinfo changed between the checks and the write: nothing written" + fresh; st=0; out=$(BOOTCTL_TEST_FAULT=part-relock-ignored write 2>&1) || st=$? + [[ $st == 5 ]] && grep -q 'FAILED to set devinfo or sdd read-only again' <<<"$out" || fail "a devinfo flag that won't set again fails with 5 (exit $st: $out)" + pass "a devinfo flag that doesn't read back read-only fails loudly (exit 5)" + fresh; st=0; out=$(BOOTCTL_TEST_FAULT=child-fails write 2>&1) || st=$? + [[ $st == 5 ]] && grep -q 'the relock child failed' <<<"$out" || fail "a failed relock child fails with 5 (exit $st: $out)" + pass "a relock child that fails makes the tool fail loudly (exit 5)" + fresh; st=0; out=$(BOOTCTL_TEST_FAULT=fork-fails write 2>&1) || st=$? + [[ $st == 3 ]] && grep -q "can't start the relock child" <<<"$out" || fail "no relock child, no window (exit $st: $out)" + [[ ! -s $r/ro.log ]] || fail "without a relock child a flag was changed: $(cat "$r/ro.log")" + unchanged "no relock child"; pass "without a relock child no flag changes" + + waitro() { local i; for i in $(seq 50); do [[ $(flags "$r") == "$all_ro" ]] && return 0; sleep 0.1; done; return 1; } + for f in kill-before-write kill-after-write; do + fresh; st=0; BOOTCTL_TEST_FAULT=$f write >/dev/null 2>&1 || st=$? + [[ $st == 137 ]] || fail "$f: the tool was not killed (exit $st)" + opened || fail "$f: the window never opened, so the restore proves nothing" + waitro || fail "$f: the flags stayed $(flags "$r") after the tool was killed" + pass "$f: the relock child sets devinfo and the disk read-only again" + done + cmp -s "$r/dev/sdd1" "$tmp/orig" && fail "kill-after-write: the fake write did not happen" + # exec, so $! is the tool itself and not a subshell around it + bgwrite() { ( exec env BOOTCTL_TEST_ROOT="$r" "$@" "$bin" mark-b-successful --write --codename "$codename" --expect "$expect_bytes" >/dev/null 2>&1 ) & pid=$!; bgpids+=("$pid"); } + waitopen() { local i; for i in $(seq 100); do opened && return 0; sleep 0.05; done; return 1; } + stopped() { local i; for i in $(seq 100); do [[ $(awk '{print $3}' /proc/$1/stat 2>/dev/null) == T ]] && return 0; sleep 0.05; done; return 1; } + fresh; bgwrite BOOTCTL_TEST_FAULT=hang-in-window BOOTCTL_TEST_RELOCK_MS=300 + waitopen || { kill -9 $pid; fail "a hung tool: the window never opened"; } + waitro || { kill -9 $pid; fail "a hung tool: the relock child did not set the flags after its timeout"; } + kill -0 $pid 2>/dev/null || fail "hang-in-window: the tool exited instead of hanging" + kill -9 $pid; wait $pid 2>/dev/null || true + cmp -s "$r/dev/sdd1" "$tmp/orig" || fail "hang-in-window wrote devinfo" + pass "a hung tool: the window opened, and the relock child set both flags after its timeout" + + # Stopped before the window opens, longer than the timeout: the child must + # still be watching when the window opens, and relock at once on SIGKILL. + fresh; bgwrite BOOTCTL_TEST_FAULT=stop-before-open,hang-in-window BOOTCTL_TEST_RELOCK_MS=2000 + stopped $pid || { kill -9 $pid; fail "stop-before-open: the tool never stopped"; } + sleep 2.5 + [[ ! -s $r/ro.log ]] || { kill -9 $pid; fail "stop-before-open: a flag changed while stopped: $(cat "$r/ro.log")"; } + kill -CONT $pid + waitopen || { kill -9 $pid; fail "stop-before-open: the window never opened after SIGCONT"; } + kill -9 $pid; wait $pid 2>/dev/null || true + for i in $(seq 10); do [[ $(flags "$r") == "$all_ro" ]] && break; sleep 0.1; done + [[ $(flags "$r") == "$all_ro" ]] || fail "stopped before the window, then killed in it: the flags are $(flags "$r") 1 s later" + pass "a stop longer than the timeout before the window: the child still relocks at once when the tool is killed in it" + + # Stopped right after arming the child: the child relocks every timeout, so + # the window that opens after SIGCONT is closed again while the tool hangs. + fresh; bgwrite BOOTCTL_TEST_FAULT=stop-after-open,hang-in-window BOOTCTL_TEST_RELOCK_MS=300 + stopped $pid || { kill -9 $pid; fail "stop-after-open: the tool never stopped"; } + sleep 1; kill -CONT $pid + waitopen || { kill -9 $pid; fail "stop-after-open: the window never opened"; } + waitro || { kill -9 $pid; fail "stop-after-open: the window stayed open with the tool hung (the child stopped watching)"; } + kill -0 $pid 2>/dev/null || fail "stop-after-open: the tool exited instead of hanging" + kill -9 $pid; wait $pid 2>/dev/null || true + pass "a stop after the child is armed: the child keeps relocking until the tool is gone" + + # The prompt can take minutes: a writer or a guard change during it stops the write. + for change in writer guard; do + fresh; bgwrite BOOTCTL_TEST_FAULT=hold-after-codename + for i in $(seq 100); do [[ -e $r/at-prompt ]] && break; sleep 0.05; done + [[ -e $r/at-prompt ]] || { kill -9 $pid; fail "hold-after-codename never reached the prompt"; } + if [[ $change == writer ]]; then exec 7<>"$r/dev/sdd1"; else echo 0 > "$r/dev/sda1.ro"; fi + touch "$r/go"; st=0; wait $pid || st=$? + [[ $change == writer ]] && exec 7>&- + [[ $st == 1 ]] || fail "a $change change during the prompt: exit $st, want a refusal" + [[ ! -s $r/ro.log ]] || fail "a $change change during the prompt: a flag changed" + cmp -s "$r/dev/sdd1" "$tmp/orig" || fail "a $change change during the prompt: devinfo written" + done + pass "a writer or a guard change while the codename prompt waits stops the write" + + fresh; bgwrite BOOTCTL_TEST_FAULT=hang-in-window + waitopen || { kill -9 $pid; fail "hang-in-window never opened the window"; } + kill -INT $pid; kill -TERM $pid; kill -HUP $pid; sleep 0.3 + kill -0 $pid 2>/dev/null || fail "SIGINT, SIGTERM or SIGHUP stopped the tool inside the window" + kill -9 $pid; wait $pid 2>/dev/null || true + waitro || fail "after SIGKILL inside the window the flags are $(flags "$r")" + pass "^C, SIGTERM and SIGHUP wait out the window; SIGKILL leaves the relock to the child" +} + +if [[ ${1:-} == --cases ]]; then + QUIET=1 cases "${BOOTCTL_BIN:?}" + exit 0 +fi + +# The production build: real paths, real ioctls, no test hooks. +${CC:-cc} ${CFLAGS:--O2} -Wall -Wextra -Werror -Ibootctl -o "$tmp/omamobile-bootctl" bootctl/omamobile-bootctl.c \ + || fail "omamobile-bootctl compiles without warnings" +! grep -aq 'BOOTCTL_TEST' "$tmp/omamobile-bootctl" || fail "the production build carries a test hook" +grep -aq "$compatible" "$tmp/omamobile-bootctl" || fail "the production build is for $codename" +pass "the production build compiles, is for $codename and has no test hooks" +st=0; "$tmp/omamobile-bootctl" >/dev/null 2>&1 || st=$? +[[ $st == 2 ]] || fail "no arguments prints the usage" +pass "no arguments prints the usage" + +build_test bootctl/omamobile-bootctl.c "$tmp/bootctl-test" || fail "the test build compiles" +cases "$tmp/bootctl-test" + +[[ ${1:-} == --mutations ]] || exit 0 + +# Each mutation breaks one guard in a copy of the source; a case must fail. +mutate() { # name, python replacement (old, new) + local name=$1 old=$2 new=$3 m="$tmp/mut.c" + nmut=$((${nmut:-0} + 1)) + python3 - bootctl/omamobile-bootctl.c "$m" "$old" "$new" <<'PY' +import sys +s = open(sys.argv[1]).read() +if s.count(sys.argv[3]) < 1: + sys.exit("mutation does not apply: " + sys.argv[3]) +open(sys.argv[2], 'w').write(s.replace(sys.argv[3], sys.argv[4])) +PY + build_test "$m" "$tmp/mut$nmut" -w || fail "mutant '$name' compiles" + if BOOTCTL_BIN="$tmp/mut$nmut" "$0" --cases >/dev/null 2>&1; then + fail "mutant '$name' passed every case" + fi + pass "mutation caught: $name" +} +mutate "no version check" 'if (maj != BOOTCTL_VER_MAJOR || min != BOOTCTL_VER_MINOR) {' 'if (0) {' +mutate "version major ignored" 'if (maj != BOOTCTL_VER_MAJOR || min != BOOTCTL_VER_MINOR) {' 'if (min != BOOTCTL_VER_MINOR) {' +mutate "a newer minor accepted" 'if (maj != BOOTCTL_VER_MAJOR || min != BOOTCTL_VER_MINOR) {' 'if (maj != BOOTCTL_VER_MAJOR || min < BOOTCTL_VER_MINOR) {' +mutate "no magic check" 'if (magic != DEVINFO_MAGIC) {' 'if (0) {' +mutate "no board check" 'if (strcmp(buf, BOOTCTL_COMPATIBLE)) {' 'if (0) {' +mutate "no slot check" "if (booted_slot() != 'b') {" 'if (0) {' +mutate "dry run writes" 'if (!do_write) {' 'if (0) {' +mutate "no --expect check" 'if (memcmp(exp, img + OFF_SLOTS, SLOT_BYTES)) {' 'if (0) {' +mutate "no codename check" 'if (strcmp(typed, BOOTCTL_CODENAME)) {' 'if (0) {' +mutate "another bit" 'nv = fb | FLAG_SUCCESSFUL;' 'nv = fb | FLAG_SUCCESSFUL | FLAG_FASTBOOT_OK | 0x20;' +mutate "no guard check" 'if (check_guard(&t) || check_unused(&t))' 'if (check_unused(&t))' +mutate "no writer check" 'if ((flags & O_ACCMODE) != O_RDONLY) {' 'if (0) {' +mutate "no sibling check" 'if (ro_get(&t->sib[i], &t->disk) != 1) {' 'if (0) {' +mutate "first sibling skipped" 'for (int i = 0; i < t->nsib; i++) + if (ro_get(&t->sib[i]' 'for (int i = 1; i < t->nsib; i++) + if (ro_get(&t->sib[i]' +mutate "last sibling skipped" 'for (int i = 0; i < t->nsib; i++) + if (ro_get(&t->sib[i]' 'for (int i = 0; i < t->nsib - 1; i++) + if (ro_get(&t->sib[i]' +mutate "unreadable sibling flag accepted" 'if (ro_get(&t->sib[i], &t->disk) != 1) {' 'if (ro_get(&t->sib[i], &t->disk) == 0) {' +mutate "disk flag not checked after clearing" 'if (ro_set(&t->disk, 0) || ro_get(&t->disk, NULL) != 0) {' 'if (ro_set(&t->disk, 0)) {' +mutate "no step-4 re-read compare" 'if (!again || alen != len || memcmp(again, orig, len)) {' 'if (!again) {' +mutate "writer on devinfo or a sibling missed" 'int hit = same_file(&st, &t->part) || same_file(&st, &t->disk); + for (int i = 0; !hit && i < t->nsib; i++)' 'int hit = same_file(&st, &t->disk); + for (int i = 0; !hit && i < 0; i++)' +mutate "holders checked on devinfo only" 'for (int i = 0; i < nh; i++) {' 'for (int i = 1; i < 2; i++) {' +mutate "no re-check after the prompt" ' if (check_guard(&t) || check_unused(&t)) { + err("the storage guard' ' if (0) { + err("the storage guard' +mutate "no relock read-back of devinfo" 'if (ro_set(&t->part, 1) || ro_get(&t->part, &t->disk) != 1)' 'if (ro_set(&t->part, 1))' +mutate "no restore read-back" 'if (after && alen == len && !memcmp(after, orig, len)) { + err("restored' 'if (1) { + err("restored' +mutate "child status ignored" 'if (!WIFEXITED(st) || WEXITSTATUS(st)) {' 'if (0) {' +mutate "child start failure ignored" 'if (child < 0) {' 'if (0) {' +mutate "child never armed" 'if (write(wfd, "O", 1) != 1 || !child_alive(child, &reaped, &st)) {' 'if (!child_alive(child, &reaped, &st)) {' +mutate "child one-shot after its first timeout" ' if (child_relock(t)) + ok = 0; + continue;' ' _exit(child_relock(t) ? 1 : 0);' +mutate "child times out from the fork, once" 'int r = poll(&pf, 1, armed ? relock_timeout_ms : -1);' 'int r = poll(&pf, 1, relock_timeout_ms); if (r == 0) _exit(child_relock(t) ? 1 : 0);' +mutate "no mount check" 'if (!strcmp(source, src) || (t->part.rdev' 'if (0 && (t->part.rdev' +mutate "no unbootable check" 'if (fb & FLAG_UNBOOTABLE) {' 'if (0) {' +mutate "no restore on mismatch" 'if (write_at(t, orig, len, 0)) {' 'if (0) {' +mutate "no relock child" ' return relock(t); +} + +static void relocker' ' return 0; +} + +static void relocker' +mutate "parent does not relock" ' if (relock(t)) { + err("FAILED' ' if (0) { + err("FAILED' +mutate "signals not blocked" 'sigprocmask(SIG_BLOCK, &block, &old);' 'sigemptyset(&old);' +mutate "disk flag cleared without the sibling check" 'for (int i = 0; i < t->nsib; i++)' 'for (int i = 0; i < 0; i++)' diff --git a/packages/omamobile-device-tegu/version b/packages/omamobile-device-tegu/version index 599028f5f..109a20f1d 100644 --- a/packages/omamobile-device-tegu/version +++ b/packages/omamobile-device-tegu/version @@ -1 +1 @@ -0.2.21 +0.2.22