Run a virtual iPhone on an Apple Silicon Mac.
Swift
Update an installed VM's kernel without erasing it (cfw update-kernel)
Jackyfdb00934c34e
diff --git a/Documents/Guides/launchpad-cli.md b/Documents/Guides/launchpad-cli.mdindex 6c2f74a1..e0988373 100644--- a/Documents/Guides/launchpad-cli.md+++ b/Documents/Guides/launchpad-cli.md@@ -37,7 +37,7 @@ each from a bundle at a different time:| --- | --- | --- || Host Programs | `vphone-cli`, `vphone-vm` | The bound bundle, on every command. A new binding applies at the next start. || Guest Environment | vphoned and the hook dylibs | `cfw install` at creation, and `cfw update-environment` (stopped machine) later. |-| Boot Chain | Patched firmware, restore, CFW patches | `fw patch`, `restore` and `cfw install` at creation. After that, `vphone-cli fw set-patches` changes the choice and `vphone-cli fw patches <vm>` lists what has not reached the guest: guest patches apply at the next `cfw update-environment`, AVPBooter at the next `fw patch` while the restore tree is kept, and the rest of the boot chain only with a restore, which erases the guest (an in-place restore cannot keep its data). Launchpad shows the count in the inspector. |+| Boot Chain | Patched firmware, restore, CFW patches | `fw patch`, `restore` and `cfw install` at creation. After that, `vphone-cli fw set-patches` changes the choice and `vphone-cli fw patches <vm>` lists what has not reached the guest: guest patches apply at the next `cfw update-environment`, AVPBooter at the next `fw patch`, a kernel patch with `cfw update-kernel` (data-preserving, needs the restore tree), and the rest of the boot chain (TXM, DeviceTree, LLB) only with a restore, which erases the guest. Launchpad shows the count in the inspector. |The **default** bundle (formerly "active") decides only the version`vm create` binds when `--bundle` is not given, and what `exec` and@@ -118,6 +118,7 @@ version while a machine is bound to it; rebind or delete those machines first.| `vm leases [--release]` | DHCP leases on the shared NAT network and the machine that owns each. `--release` frees the ones no machine in any library uses, through the helper (see [Networking](networking.md#addresses-held-by-old-macs)) || `cfw install <name>` | Install CFW into a stopped machine with its own bundle, through the helper || `cfw update-environment <name>` | Redeploy the machine's own bundle's guest resources (vphoned, hook dylibs) into it while stopped, through the helper; nothing else changes |+| `cfw update-kernel <name>` | Swap the Preboot kernelcache for the `fw patch`ed one, keeping the data (VM off); the data-preserving way to change a kernel patch on an installed VM || `guest send <name> <json>` | One raw `vphone.sock` request (tap, swipe, key, screenshot) || `guest rpc <name> <method> [params]` | Any vphoned method, see `Research/vphoned_http_api.md` || `guest unlock <name> [--passcode <code>] [--timeout <seconds>]` | Turn the screen on and unlock the guest, whatever state it was in (vphoned `screen.unlock`). `--passcode` is needed only when the guest has one |diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex 1d1ab019..fc65f6a8 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -2749,3 +2749,31 @@ Action Button's long press (HID 0x0B/0x2D) runs Flashlight and Camera with theDynamic Island, with no tweak; the search field gains dictation. The guest bootsnormally. Not yet measured: the change on a VM without the identity patches, oniOS 18.x, and a Camera Control press.++## The kernelcache reaches an installed guest without a restore (2026-10-05)++No new Apple binary patch. This adds a way to deliver the existing kernelcache+patches to a VM that is already installed, so it is recorded here.++A kernel patch toggled with `fw set-patches` could only reach an installed guest+through a restore, and a restore erases it (restored in the cloudOS ramdisk+repartitions whatever the host asks — `restore --no-erase` refuses; see+`Research/Restore/native_restore_architecture.md`). But the booting kernel lives+in Preboot as an IMG4, and iBoot accepts a modified IM4P under the original+signed IM4M — the same image4 bypass that lets `cfw install` rewrite+`devicetree.img4` there. `cfw update-kernel` (`VPhoneCustomFirmwareInstaller`+mode `.kernelUpdate`) host-mounts Preboot on a clone and swaps the kernelcache's+IM4P for the one `fw patch` built in the restore tree, keeping every volume. The+splice is `CustomFirmwarePostRestoreDeviceTree.kernelcacheReplacingPayload`,+which carries the whole IM4P (compression and any PAYP tail) verbatim and keeps+the IMG4's manifest.++Proven on a test VM (iPhone 27.0 24A435 + cloudOS 26.4) 2026-10-05: with a+marker in `/var/mobile/Documents`, `fw set-patches` to drop+`kernel-exp-display_refresh_120hz`, `fw patch`, `cfw update-kernel`, then boot —+the guest booted the re-patched kernelcache and the marker survived. Flow:+`fw set-patches` → `fw patch` (restore tree kept, `--keep-artifacts`) →+`cfw update-kernel`. `fw set-patches`, `fw patches` and the Launchpad inspector+route a kernel patch through `cfw update-kernel` and the rest of the boot chain+(TXM, DeviceTree, LLB, iBSS, iBEC) through the erasing restore. TXM and+DeviceTree are also in Preboot and could follow the same path later.diff --git a/Research/Firmware/post_creation_patch_changes.md b/Research/Firmware/post_creation_patch_changes.mdindex eb74b096..7f9e5f63 100644--- a/Research/Firmware/post_creation_patch_changes.md+++ b/Research/Firmware/post_creation_patch_changes.md@@ -52,7 +52,8 @@ Counts are declarations in `FirmwarePatcher/PatchSets/*.swift`.| AVPBooter | 1 | VM root, `romImages.avpBooter`, read every boot | `fw patch` itself | works, but `fw patch` refuses without a restore tree || iBSS, iBEC | 7 | restore tree only | DFU during a restore | irrelevant to an installed guest; only the next restore uses them || LLB | 6 | NOR (personalized by idevicerestore, `LlbImageData`) | restore | needs a restore, which erases the guest: an in-place one cannot keep its data (`native_restore_architecture.md`, 2026-10-05) |-| kernelcache, DeviceTree, TXM | 54 + 30 + 6 | Preboot (personalized) | restore | Preboot can be rewritten by a host mount — `cfw install` already edits `devicetree.img4` there; nothing does it for the kernelcache or TXM |+| kernelcache | 54 | Preboot (personalized) | `cfw update-kernel` | Host-mounts Preboot and swaps the kernelcache IM4P under the original IM4M (the image4 bypass), data-preserving, no restore |+| DeviceTree, TXM | 30 + 6 | Preboot (personalized) | restore | Preboot can be rewritten by a host mount (as the kernelcache now is); not yet wired for these two || Guest (dyld cache, Mach-O, files, entitlements, Preboot DT) | 34 | System / Preboot volumes of `Disk.img` | `cfw install`, partly `cfw update-environment` | turning on works by re-running; turning off does nothing |Why turning a guest patch off does nothing today:@@ -142,14 +143,23 @@ is off:"Prior live" is the receipt's `Guest` part; for a VM with none, the plan's guestpatches plus the late ones the old installer added.-**Not built: the boot chain without a restore.** Writing a re-patched-kernelcache, TXM or DeviceTree into Preboot was dropped before implementation;-those three, LLB, iBSS and iBEC change only through a restore, and AVPBooter only-through `fw patch`, which needs the restore tree (`--keep-artifacts`).-A restore always erases the guest: `restore --no-erase` was tried on a test VM-on 2026-10-05 and replaces the kernel but erases the Data volume as well,-so it now refuses (row 4 and "An in-place restore cannot keep a guest's data"-in `Research/Restore/native_restore_architecture.md`).+**The kernel reaches an installed guest without a restore.** `cfw update-kernel`+host-mounts Preboot and swaps the kernelcache's IM4P for the one `fw patch`+built, keeping the original signed IM4M — iBoot accepts it, the same image4+bypass that lets `cfw install` rewrite `devicetree.img4` there — so no volume is+reformatted and the data survives (proven on a test VM 2026-10-05:+`fw set-patches` + `fw patch` + `cfw update-kernel`, guest booted the re-patched+kernel with its `/var/mobile/Documents` marker intact). It needs the restore+tree for the patched kernelcache (`fw patch`, `--keep-artifacts`). TXM and+DeviceTree live in Preboot too and could follow; the kernelcache was done first+because a kernel patch is the common reason to change the boot chain.++**A restore still erases, so the rest of the boot chain needs one.** TXM,+DeviceTree, LLB, iBSS and iBEC change only through a restore, and AVPBooter only+through `fw patch`. `restore --no-erase` cannot keep data: tried on a test VM on+2026-10-05, restored in the cloudOS ramdisk repartitions whatever the host+sends, so it now refuses (row 4 and "An in-place restore cannot keep a guest's+data" in `Research/Restore/native_restore_architecture.md`).**Paired DeviceTree patches.** `devicetree-cfw-ipad_audio`,`devicetree-cfw-product_haptics_node` and@@ -160,7 +170,7 @@ before them. `FirmwareGuestSystemPatchSet.prebootRepairs` names the pairs, andthe drift report reads the tree patch as applied when its Preboot repair islive, so a VM restored before the tree patches no longer shows them as needinga restore. The Launchpad inspector says in the open how many boot-chain patches-are pending and that only a restore, which erases the guest, applies them.+are pending and that a kernel patch applies with `cfw update-kernel` (keeping the data) while the rest need a restore that erases.## Validation (2026-10-04)diff --git a/Research/Restore/native_restore_architecture.md b/Research/Restore/native_restore_architecture.mdindex 2c7bd441..62a31d8f 100644--- a/Research/Restore/native_restore_architecture.md+++ b/Research/Restore/native_restore_architecture.md@@ -151,7 +151,7 @@ it is not checked and needs a phone or VM in DFU.| 1 | `restore` (online, default) | `pmd3 restore-update` | `erase=true, ticket_path=NULL` | VM boots | **device**, but both halves are now proven separately: the online TSS fetch by row 2 and the erase-and-flash by row 3. What has not been run is the two in one invocation. Options mapping is `unit`: `RestoreOptionsTests.defaultsAreAnOnlineEraseRestore` || 2 | `restore --get-shsh` | `pmd3 restore-get-shsh` | `shsh_only=true` | `.shsh` semantically equal to the Python's, same filename | ✅ **DONE 2026-09-23.** Real TSS round trip against a DFU-booted `dfu-spike`: ApNonce and SepNonce read from the device, `Received SHSH blobs`, saved as `206C763772858301.shsh` — the `%016X` name `VPhoneRestoreLayout.shshOutput` promises. The blob is a TSS response (`@ServerVersion 2.1.0`, 5,803-byte `ApImg4Ticket`), binary plist where the Python wrote XML — a serialization difference, not a semantic one || 3 | `restore --offline` | AEA decrypt in place → `--tss <first .shsh>` | AEA decrypt in place → `ticket_path=<same file>` | ① `noSHSH` with no blob ② `noRestoreDir` with no tree ③ multiple `.shsh` → sorted first ④ VM boots | ✅ **DONE 2026-09-23.** ①②③ `unit` and also run through the CLI (see below); ④ a full flash of `dfu-spike` from the 26.1/23B85 tree with the cached ticket: four `.dmg.aea` decrypted in place, filesystem sent, system volume sealed, `Status: Restore Finished`, exit 0, and the device left DFU |-| 4 | `restore --no-erase` | `Behavior.Update` | `erase=false` | user data survives | ❌ **Not possible (2026-10-05), and the flag now refuses.** Run on a test VM, an in-place restore replaces the kernel but erases the Data volume — see "An in-place restore cannot keep a guest's data" below. The library mapping is still `unit`: `RestoreOptionsTests.updateInPlaceClearsErase` |+| 4 | `restore --no-erase` | `Behavior.Update` | `erase=false` | user data survives | ❌ **Not possible (2026-10-05); the flag refuses.** restored in the cloudOS ramdisk repartitions whatever the host sends, so an in-place restore erases the Data volume — see "An in-place restore cannot keep a guest's data" below. A kernel patch instead reaches an installed guest data-preserving through `cfw update-kernel` (no restore). Library mapping still `unit`: `RestoreOptionsTests.updateInPlaceClearsErase` || 5 | metadata on success | writes `restore-info.json` | same | contents identical | ✅ **DONE 2026-09-23.** Written only after the restore returned: `{"ios":{"version":"26.1","build":"23B85"},"cloudOS":{"version":"26.1","build":"23B85"}}` || 6 | failure | no `restore-info.json`, exit code passed through | same | exit codes match | **device.** The bridge's own rejections are `unit` (`RestoreRunnerTests`); a failure from inside idevicerestore is not || 7 | verbosity | `-v` → one, `-vv`/`-vvv` → two `-v` | `debug_level` | logs comparably detailed | **device.** The level enum matches upstream's one for one and that is `unit` (`RestoreEventTests.levelsMatchIdevicerestoresEnum`) |@@ -299,14 +299,35 @@ then `vm launch --dfu`, `restore --no-erase`, `cfw install` and a boot.installed system would without the dyld cache patches `cfw install` applies,which a ramdisk does not get.-So a restore always erases a vphone guest. `restore --no-erase` now refuses-with that reason instead of re-imaging the system volume and failing (it stays-as a hidden flag so a script gets the reason rather than a usage error), and-`fw set-patches`, `fw patches` and the Launchpad inspector say that a-boot-chain change reaches an existing guest only through a restore that erases-it. Making it possible would mean an update ramdisk that boots on the cloudOS-restore kernel — patching the iPhone's, as the installed system is patched —-which was not attempted.+4. **The erase is `restored`'s, not the host's.** A fourth round cleared the+ one host option that directly orders a reformat — `CreateFilesystemPartitions`,+ which `restore.c` hardcodes to 1 — *and* handed restored the Update identity.+ restored still ran `Creating partition map` / `filesystem` / `system key bag`+ and the marker was gone. So restored in the cloudOS (erase) ramdisk+ repartitions whatever the host sends; no host-side change reaches it.++So a restore always erases a vphone guest, and that is restored's decision in+the ramdisk, not a host flag. `restore --no-erase` refuses with that reason+instead of re-imaging the system volume and failing (a hidden flag, so a script+gets the reason rather than a usage error). Making a restore itself keep data+would mean an update ramdisk that boots on the cloudOS restore kernel — patching+the iPhone's, as the installed system is patched — which was not attempted.++**But the kernel can be changed without a restore.** The one boot-chain change+that matters for a patch toggle is the kernelcache, and it does not need a+restore at all: the booting kernel lives in Preboot as an IMG4, and iBoot+accepts a modified IM4P under the original signed IM4M — the same image4 bypass+that lets `cfw install` rewrite `devicetree.img4` there. `cfw update-kernel`+(`VPhoneCustomFirmwareInstaller` mode `.kernelUpdate`) host-mounts Preboot on a+clone and swaps the kernelcache's IM4P for the one `fw patch` built, keeping+every volume. Proven on the test VM 2026-10-05: `fw set-patches` to drop a+kernel patch, `fw patch`, `cfw update-kernel`, boot — the guest booted the+re-patched kernel and the `/var/mobile/Documents` marker survived. So+`fw set-patches`, `fw patches` and the Launchpad inspector now send a kernel+patch through `cfw update-kernel` (data-preserving) and only TXM, DeviceTree,+LLB, iBSS and iBEC through the erasing restore. TXM and DeviceTree live in+Preboot too and could follow the same path later; the kernelcache was done+first because a kernel patch is the common reason to change the boot chain.**The exit-status bug.** `restore_device` in `Transfer/restore.c` sets`FLAG_QUIT` on the first handler error, reads one more message, and thatdiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swiftindex 43cc03b4..992e4d2c 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift@@ -155,6 +155,34 @@ public enum CustomFirmwarePostRestoreDeviceTree {}}+ /// The Preboot kernelcache IMG4 with its IM4P replaced by the patched+ /// kernelcache's IM4P, keeping the IM4M; nil when they already match.+ ///+ /// `prebootIMG4` must be an IMG4 (IM4P + signed IM4M). `patchedKernelcache`+ /// is the restore tree's `fw patch`ed kernelcache, a bare IM4P (an IMG4 is+ /// also accepted and its IM4P taken). Both must be `krnl`. The whole IM4P —+ /// its compression and any PAYP tail included — is carried over verbatim,+ /// so this assumes nothing about how the payload is stored.+ public static func kernelcacheReplacingPayload(+ prebootIMG4: Data,+ patchedKernelcache: Data,+ ) throws -> Data? {+ let container = try Container(prebootIMG4)+ guard container.isIMG4 else {+ throw PatcherError.invalidFormat("the Preboot kernelcache is a bare IM4P; expected an IMG4 with a manifest")+ }+ let sourceIM4P = try Container(patchedKernelcache).im4pBytes+ let targetFourcc = try IM4P(container.im4pBytes).fourcc+ let sourceFourcc = try IM4P(sourceIM4P).fourcc+ guard targetFourcc == "krnl", sourceFourcc == "krnl" else {+ throw PatcherError.invalidFormat(+ "kernelcache fourcc mismatch: Preboot '\(targetFourcc)', source '\(sourceFourcc)' — expected 'krnl'",+ )+ }+ guard container.im4pBytes != sourceIM4P else { return nil }+ return try container.rebuilt(im4pBytes: sourceIM4P)+ }+/// The container, payload and flat tree of a device tree file. Refuses a/// payload that is not a device tree, is encrypted, or came back still/// compressed.diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchDrift.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchDrift.swiftindex a5d8074b..1c66e04d 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchDrift.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchDrift.swift@@ -22,9 +22,13 @@ public enum FirmwarePatchDelivery: String, Sendable, Hashable, CaseIterable, Cod/// `fw patch` alone delivers it. `fw patch` still needs the VM's restore/// tree, which is kept only with `--keep-artifacts`.case firmwarePatch = "fw-patch"- /// iBSS and iBEC are used only while restoring, LLB lives in NOR, and- /// kernelcache, TXM and DeviceTree are personalized into Preboot by the- /// restore. Nothing else writes them.+ /// The kernelcache lives in Preboot as an IMG4; `fw patch` rebuilds it and+ /// `cfw update-kernel` swaps its IM4P into Preboot under the signed+ /// manifest, with no restore and no erase.+ case firmwarePatchThenUpdateKernel = "fw-patch+update-kernel"+ /// iBSS and iBEC are used only while restoring, LLB lives in NOR, and TXM+ /// and DeviceTree are personalized into Preboot by the restore, which+ /// erases. Nothing else writes them.case restore/// Everything `cfw install` writes into the guest volumes.case updateEnvironment = "update-environment"@@ -33,8 +37,10 @@ public enum FirmwarePatchDelivery: String, Sendable, Hashable, CaseIterable, Codswitch target {case .firmware(.avpBooter):self = .firmwarePatch+ case .firmware(.kernelcache):+ self = .firmwarePatchThenUpdateKernelcase .firmware:- // Every other boot-chain component, and the restore-only+ // iBSS, iBEC, LLB, TXM, DeviceTree, and the restore-only// Filesystem/Manifest.self = .restorecase .dyldSharedCache, .guestExecutable, .guestEntitlements, .guestFile, .prebootDeviceTree:diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareKernelcacheSwapTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareKernelcacheSwapTests.swiftnew file mode 100644index 00000000..9f15bff0--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareKernelcacheSwapTests.swift@@ -0,0 +1,89 @@+@testable import FirmwarePatcher+import Foundation+import Img4tool+import Testing+import VPhonePatchKit++/// Swapping a Preboot kernelcache's IM4P while keeping its signed IM4M, the+/// basis of `cfw update-kernel`. The pure function makes no disk or mount+/// assumptions, so it is tested directly with built IMG4/IM4P fixtures+/// (DERTestEncoder lives in CustomFirmwarePlistPatchTests.swift, same target).+@Suite("Preboot kernelcache swap")+struct CustomFirmwareKernelcacheSwapTests {+ private func im4p(_ fourcc: String, _ payload: [UInt8]) throws -> Data {+ try IM4P(fourcc: fourcc, description: "test", payload: Data(payload)).data+ }++ private func img4(im4p: Data, manifest: Data, restoreInfo: Data? = nil) -> Data {+ var elements = [DERTestEncoder.ia5String("IMG4"), im4p, DERTestEncoder.element(tag: 0xA0, value: manifest)]+ if let restoreInfo {+ elements.append(DERTestEncoder.element(tag: 0xA1, value: restoreInfo))+ }+ return DERTestEncoder.sequence(elements)+ }++ @Test+ func `the IM4P is replaced and the manifest and restore info are kept byte for byte`() throws {+ let manifest = Data((0 ..< 96).map { UInt8(truncatingIfNeeded: $0 * 7 + 3) })+ let restoreInfo = Data((0 ..< 32).map { UInt8(truncatingIfNeeded: $0 * 11 + 5) })+ let old = try im4p("krnl", Array(repeating: 0xAA, count: 4096))+ let new = try im4p("krnl", Array(repeating: 0xBB, count: 4096))+ let preboot = img4(im4p: old, manifest: manifest, restoreInfo: restoreInfo)++ let output = try #require(try CustomFirmwarePostRestoreDeviceTree.kernelcacheReplacingPayload(+ prebootIMG4: preboot, patchedKernelcache: new,+ ))+ let children = try DERTestEncoder.children(of: output)+ #expect(children.count == 4)+ #expect(children[0] == DERTestEncoder.ia5String("IMG4"))+ #expect(children[1] == new) // the patched IM4P, verbatim+ #expect(children[2] == DERTestEncoder.element(tag: 0xA0, value: manifest))+ #expect(children[3] == DERTestEncoder.element(tag: 0xA1, value: restoreInfo))+ }++ @Test+ func `an IMG4 source is accepted and only its IM4P is taken`() throws {+ let old = try im4p("krnl", Array(repeating: 0xAA, count: 2048))+ let new = try im4p("krnl", Array(repeating: 0xCC, count: 2048))+ let preboot = img4(im4p: old, manifest: Data(repeating: 1, count: 32))+ // The source is itself an IMG4 with a different manifest; its IM4P wins,+ // its manifest is ignored.+ let sourceIMG4 = img4(im4p: new, manifest: Data(repeating: 9, count: 48))++ let output = try #require(try CustomFirmwarePostRestoreDeviceTree.kernelcacheReplacingPayload(+ prebootIMG4: preboot, patchedKernelcache: sourceIMG4,+ ))+ let children = try DERTestEncoder.children(of: output)+ #expect(children[1] == new)+ #expect(children[2] == DERTestEncoder.element(tag: 0xA0, value: Data(repeating: 1, count: 32)))+ }++ @Test+ func `an identical kernelcache is a no-op`() throws {+ let kc = try im4p("krnl", Array(repeating: 0xAA, count: 1024))+ let preboot = img4(im4p: kc, manifest: Data(repeating: 2, count: 16))+ #expect(try CustomFirmwarePostRestoreDeviceTree.kernelcacheReplacingPayload(+ prebootIMG4: preboot, patchedKernelcache: kc,+ ) == nil)+ }++ @Test+ func `a non-kernel source is refused`() throws {+ let preboot = img4(im4p: try im4p("krnl", [1, 2, 3, 4]), manifest: Data(repeating: 3, count: 16))+ #expect(throws: PatcherError.self) {+ _ = try CustomFirmwarePostRestoreDeviceTree.kernelcacheReplacingPayload(+ prebootIMG4: preboot, patchedKernelcache: try im4p("dtre", [1, 2, 3, 4]),+ )+ }+ }++ @Test+ func `a bare IM4P target is refused`() throws {+ let bare = try im4p("krnl", [1, 2, 3, 4])+ #expect(throws: PatcherError.self) {+ _ = try CustomFirmwarePostRestoreDeviceTree.kernelcacheReplacingPayload(+ prebootIMG4: bare, patchedKernelcache: try im4p("krnl", [5, 6, 7, 8]),+ )+ }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchDriftTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchDriftTests.swiftindex 7d35c112..3b389bb0 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchDriftTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchDriftTests.swift@@ -147,7 +147,7 @@ struct FirmwarePatchDriftTests {// kernel-b was turned off after the restore put it in.#expect(result["kernel-b"]?.applied == true)#expect(result["kernel-b"]?.isPending == true)- #expect(result["kernel-b"]?.delivery == .restore)+#expect(result["kernel-b"]?.delivery == .firmwarePatchThenUpdateKernel)#expect(result["kernel-a"]?.isPending == false)#expect(result["avp"]?.isPending == false)// No Guest part in the receipt: the plan says what the install wrote.@@ -218,7 +218,8 @@ struct FirmwarePatchDriftTests {@Testfunc `Each target is delivered by the step that owns its bytes`() {#expect(FirmwarePatchDelivery(target: .firmware(.avpBooter)) == .firmwarePatch)- for component in [VPhoneFirmwareComponent.iBSS, .iBEC, .llb, .txm, .kernelcache, .deviceTree] {+ #expect(FirmwarePatchDelivery(target: .firmware(.kernelcache)) == .firmwarePatchThenUpdateKernel)+ for component in [VPhoneFirmwareComponent.iBSS, .iBEC, .llb, .txm, .deviceTree] {#expect(FirmwarePatchDelivery(target: .firmware(component)) == .restore)}let guest: [VPhonePatchTarget] = [diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex eff7559d..faed50fa 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -46,11 +46,21 @@ struct VPhoneCustomFirmwareInstaller {/// Refuses a VM that has never had a full install: with nothing to put/// files back *over*, this would be laying down half an install.case environmentOnly+ /// Only the Preboot kernelcache: replace its IM4P with the one+ /// `fw patch` built in the restore tree, keeping the original IM4M, so+ /// iBoot boots a re-patched kernel (the image4 bypass accepts a+ /// modified payload under the signed manifest, as it does for the+ /// Preboot device tree). No volume is reformatted and the Data volume+ /// is untouched — the one boot-chain change that reaches an installed+ /// guest without the erasing restore. Needs the restore tree for the+ /// patched kernelcache, so `fw patch` must have run (`--keep-artifacts`).+ case kernelUpdatevar summary: String {switch self {case .full: "CFW system install"case .environmentOnly: "guest environment update"+ case .kernelUpdate: "guest kernel update"}}}@@ -133,6 +143,10 @@ struct VPhoneCustomFirmwareInstaller {// at a time, as in a terminal.fflush(stdout)setvbuf(stdout, nil, _IOLBF, 0)+ if mode == .kernelUpdate {+ try runKernelUpdate()+ return+ }// Ownership checks apply when the caller is known (SUDO_UID, which// the Launchpad helper also sets). Plain root trusts its own files.let invokingUser = VPhoneInvokingUser.current@@ -312,6 +326,8 @@ struct VPhoneCustomFirmwareInstaller {let wasInstalled = (try? systemRoot.exists("System/Library/xpc/launchd.plist.bak")) ?? falsepriorGuest = receiptGuest ?? (wasInstalled ? priorFallback : [])switch mode {+ case .kernelUpdate:+ break // handled by runKernelUpdate, never reached herecase .full:guard let restore else {throw ValidationError("A full CFW install needs a prepared restore tree.")@@ -429,6 +445,206 @@ struct VPhoneCustomFirmwareInstaller {print("[+] CFW system install complete; vphoned is installed, no package bootstrap was staged")case .environmentOnly:print("[+] Guest environment updated; start the VM to pick it up")+ case .kernelUpdate:+ break // handled by runKernelUpdate+ }+ }++ /// Replace only the Preboot kernelcache, keeping every volume.+ ///+ /// The booting kernel lives in Preboot as an IMG4. `fw patch` has already+ /// rebuilt `kernelcache.research.vphone600` in the restore tree with the+ /// current selection; this swaps that IM4P into the Preboot IMG4 under its+ /// signed IM4M (the image4 bypass accepts it, as for the device tree) and+ /// nothing else. No volume is reformatted, so the guest's data survives —+ /// the one boot-chain change that reaches an installed guest without the+ /// erasing restore.+ ///+ /// The disk plumbing (clone, attach, find the container, swap the clone+ /// back) mirrors `run()`; it is kept separate so this cannot affect the+ /// full install or the environment update, and does not mount the System or+ /// xART volumes or touch the root snapshot — iBoot reads the kernelcache+ /// from Preboot directly.+ private func runKernelUpdate() throws {+ let invokingUser = VPhoneInvokingUser.current+ let callerUID = invokingUser?.uid+ let bundleDirectory = try pinBundle(owner: callerUID)+ let bundlePath = try bundleDirectory.path++ let disk = try openDiskImage(in: bundleDirectory, path: bundlePath, owner: callerUID)+ let diskPath = (bundlePath as NSString).appendingPathComponent("Disk.img")+ let busy = try VPhoneProcessRunner.runCapturing(+ URL(fileURLWithPath: "/usr/sbin/lsof"), ["-t", "--", diskPath],+ )+ guard !VPhoneLsof.parsePIDs(busy.stdout).contains(where: { $0 != getpid() }) else {+ throw ValidationError("The VM disk is in use. Stop the VM, then run the kernel update again.")+ }++ // The patched kernelcache comes from the restore tree `fw patch` wrote.+ // Without it there is nothing to install, so this needs the tree kept+ // (`--keep-artifacts`) and `fw patch` run.+ let restore = try restoreTree(in: bundleDirectory, path: bundlePath, owner: callerUID)+ let patched: Data+ do {+ patched = try restore.readData("kernelcache.research.vphone600")+ } catch {+ throw ValidationError(+ "No patched kernelcache in the restore tree. Run `vphone-cli fw patch` first (the VM needs its restore tree kept with --keep-artifacts).",+ )+ }++ let work = try makeWorkDirectory()+ defer {+ do { try removeWorkDirectory(work) } catch {+ fputs("warning: left CFW work directory at \(work.url.path): \(error)\n", stderr)+ }+ }+ try requireFreeSpace(at: [bundlePath, work.url.path])++ let image: URL+ let cloned = try work.directory.clone(disk, to: "Disk.img")+ if cloned {+ image = work.file("Disk.img")+ } else {+ guard try bundleDirectory.refersTo("Disk.img", file: disk) else {+ throw ValidationError("The VM disk image changed during the kernel update. Try again.")+ }+ image = try URL(fileURLWithPath: bundleDirectory.path).appendingPathComponent("Disk.img")+ }++ let attached = try tool(+ "/usr/bin/hdiutil",+ ["attach", "-nomount", "-imagekey", "diskimage-class=CRawDiskImage", image.path],+ )+ let devices = attached.split(whereSeparator: \.isNewline).compactMap { line -> (device: String, type: String)? in+ let fields = line.split(whereSeparator: \.isWhitespace)+ guard fields.count >= 2, fields[0].hasPrefix("/dev/disk") else { return nil }+ return (String(fields[0]), String(fields[1]))+ }+ let store = devices.first(where: { $0.type == "Apple_APFS" })?.device+ let wholeDisk = devices.first(where: { $0.type == "GUID_partition_scheme" })?.device+ let baseDisk = store.flatMap { device in+ device.range(of: "s", options: .backwards).map { String(device[..<$0.lowerBound]) }+ } ?? wholeDisk ?? devices.first?.device+ guard let baseDisk, baseDisk.hasPrefix("/dev/disk") else {+ if let range = attached.range(of: #"/dev/disk[0-9]+"#, options: .regularExpression) {+ _ = try? tool("/usr/bin/hdiutil", ["detach", "-force", String(attached[range])], quiet: true)+ }+ throw ValidationError("Unable to attach the VM disk image. Try again.")+ }+ var diskAttached = true+ defer {+ if diskAttached,+ (try? tool("/usr/bin/hdiutil", ["detach", baseDisk], quiet: true)) == nil+ {+ _ = try? tool("/usr/bin/hdiutil", ["detach", "-force", baseDisk], quiet: true)+ }+ }++ let info = try tool("/usr/sbin/diskutil", ["info", "-plist", "\(baseDisk)s1"], quiet: true)+ guard+ let plist = try PropertyListSerialization.propertyList(from: Data(info.utf8), format: nil) as? [String: Any],+ let container = plist["APFSContainerReference"] as? String,+ container.hasPrefix("disk")+ else {+ throw ValidationError("Unable to read the VM disk image. Try again.")+ }+ let volumes = try containerVolumes(container, physicalStore: "\(baseDisk.dropFirst("/dev/".count))s1")+ guard+ let preboot = volumes.first(where: { ($0["Roles"] as? [String])?.contains("Preboot") == true }),+ let device = preboot["DeviceIdentifier"] as? String+ else {+ throw ValidationError("Unable to find the VM's Preboot volume. Restore the VM, then install CFW again.")+ }++ print("[*] \(mode.summary.capitalized): \(bundle.lastPathComponent)")+ let mount = work.file("preboot")+ _ = try work.directory.directory("preboot", create: true, mode: 0o700)+ var prebootMounted = false+ defer {+ if prebootMounted,+ (try? tool("/sbin/umount", [mount.path], quiet: true)) == nil+ {+ _ = try? tool("/sbin/umount", ["-f", mount.path], quiet: true)+ }+ }+ prebootMounted = true+ try mountGuestVolume(device, at: mount)+ let changed: Bool = try {+ let root = try openGuestVolume("preboot", device: device, in: work)+ // The one kernelcache, reached without a link anywhere on the way.+ let candidates = try root.entries().compactMap { name -> String? in+ let path = "\(name)/System/Library/Caches/com.apple.kernelcaches/kernelcache"+ guard (try? root.isDirectory(name)) == true, (try? root.isRegularFile(path)) == true else {+ return nil+ }+ return path+ }+ guard candidates.count == 1, let kernelcache = candidates.first else {+ throw ValidationError("Expected one kernelcache in the Preboot volume but found \(candidates.count). Restore the VM, then install CFW again.")+ }+ guard let meta = try root.status(kernelcache), meta.st_mode & S_IFMT == S_IFREG else {+ throw ValidationError("The Preboot kernelcache is missing or not a regular file. Restore the VM again.")+ }+ let current = try root.readData(kernelcache)+ guard let newBytes = try CustomFirmwarePostRestoreDeviceTree.kernelcacheReplacingPayload(+ prebootIMG4: current, patchedKernelcache: patched,+ ) else {+ print(" [.] Preboot kernelcache already matches the patched one — no change")+ return false+ }+ let staged = work.file("kernelcache.new")+ try newBytes.write(to: staged)+ try root.replaceFile(kernelcache, fromFileAt: staged, mode: meta.st_mode & 0o7777, owner: (meta.st_uid, meta.st_gid))+ print(" [+] Preboot kernelcache replaced (\(current.count) -> \(newBytes.count) bytes), manifest kept")+ return true+ }()++ _ = try tool("/sbin/umount", [mount.path])+ prebootMounted = false+ _ = try tool("/usr/bin/hdiutil", ["detach", baseDisk], quiet: true)+ diskAttached = false+ // No snapshot rename: the kernelcache is read from Preboot, not from the+ // System volume's root snapshot, so nothing on System changed.+ if cloned, changed {+ try work.directory.setOwner("Disk.img", uid: disk.owner, gid: disk.group)+ try work.directory.setMode("Disk.img", disk.mode & 0o777)+ try work.directory.rename("Disk.img", to: "Disk.img", in: bundleDirectory)+ }+ if changed {+ recordKernelcacheReceipt(in: bundleDirectory, owner: invokingUser.map { ($0.uid, $0.gid) })+ }+ print("[+] Guest kernel updated; start the VM to boot the re-patched kernelcache")+ }++ /// Record the kernelcache part of the receipt with the kernel patches the+ /// plan `fw patch` resolved. Best-effort, like `recordGuestReceipt`.+ private func recordKernelcacheReceipt(+ in bundleDirectory: VPhoneConfinedDirectory,+ owner: (uid: uid_t, gid: gid_t)?,+ ) {+ let enabled = Set(readPatchPlan(in: bundleDirectory)?.enabledPatches ?? [])+ let kernelPatches = FirmwarePatchSetCatalog.allDeclarations+ .filter { $0.target == .firmware(.kernelcache) && enabled.contains($0.identifier) }+ .map(\.identifier)+ do {+ var receipt = (try? bundleDirectory.readData(VPhonePatchPresetStore.receiptFileName))+ .flatMap { try? VPhoneVirtualMachinePatchReceipt.decode($0) }+ ?? VPhoneVirtualMachinePatchReceipt()+ receipt.record(+ VPhoneFirmwareComponent.kernelcache.rawValue,+ patches: kernelPatches,+ writer: "cfw update-kernel",+ bundleVersion: bundleVersion,+ )+ try bundleDirectory.writeFile(+ VPhonePatchPresetStore.receiptFileName,+ contents: receipt.encoded(),+ mode: 0o777,+ owner: owner,+ )+ } catch {+ fputs("warning: could not record the kernelcache receipt: \(error)\n", stderr)}}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swiftindex 03eff513..2b17fbb6 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift@@ -466,10 +466,11 @@ struct VPhoneFirmwareSetPatchesCommand: ParsableCommand {AVPBooter `fw patch`; read at the next boot. Needsthe restore tree (`--keep-artifacts`).+ kernelcache `fw patch`, then `cfw update-kernel`+ (root), which keeps the guest's data.Guest (system, dyld cache, `cfw update-environment` (root), whichPreboot device tree) applies this choice both on and off.- LLB, kernelcache, TXM, only a restore, which erases the guest's data.- DeviceTree+ LLB, TXM, DeviceTree only a restore, which erases the guest's data.iBSS, iBEC used only while restoring.`fw patches <vm>` shows the same comparison at any time.diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchCatalogReport.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchCatalogReport.swiftindex 9212327c..9b20e4be 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchCatalogReport.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchCatalogReport.swift@@ -405,6 +405,10 @@ public struct VPhonePatchCatalogReport: Sendable {case .firmwarePatch:"run `vphone-cli fw patch \(vm)`; it takes effect at the next boot."+ " It needs the VM's restore tree (kept with `--keep-artifacts`)."+ case .firmwarePatchThenUpdateKernel:+ "run `vphone-cli fw patch \(vm)`, then `sudo vphone-cli cfw update-kernel \(vm)`"+ + " with the machine off; it keeps the guest's data. Both need the restore tree"+ + " (kept with `--keep-artifacts`)."case .restore where part == VPhoneFirmwareComponent.iBSS.rawValue|| part == VPhoneFirmwareComponent.iBEC.rawValue:"used only while restoring, so the change matters at the next restore and not to this guest."diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swiftindex b21e24ff..b3061e9b 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift@@ -65,7 +65,7 @@ struct VPhoneRestoreCommand: ParsableCommand {func validate() throws {if noErase {throw ValidationError(- "An in-place restore cannot keep this guest's data: the cloudOS restore ramdisk a vphone guest restores with only erases. Restore without --no-erase.",+ "An in-place restore cannot keep this guest's data: restored in the cloudOS restore ramdisk recreates the partition map whatever the host asks. To change the kernel on an installed VM without erasing it, use `cfw update-kernel`.",)}}@@ -231,6 +231,7 @@ struct VPhoneCustomFirmwareCommand: ParsableCommand {abstract: "Custom-firmware install (host-mount; VM must be off)",subcommands: [VPhoneCustomFirmwareInstallCommand.self,+ VPhoneCustomFirmwareUpdateKernelCommand.self,VPhoneCustomFirmwareInstallRootCommand.self,VPhoneCustomFirmwareUpdateEnvironmentCommand.self,VPhoneCustomFirmwareFlipSnapshotCommand.self,@@ -375,6 +376,41 @@ struct VPhoneCustomFirmwareInstallCommand: ParsableCommand {/// the restore tree, the cryptex copy and the GPU bundle, are skipped (an/// installed guest already carries both); the recorded `jb` variant is left/// alone. A VM that was never installed is refused rather than half-filled.+struct VPhoneCustomFirmwareUpdateKernelCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "update-kernel",+ abstract: "Replace an installed VM's Preboot kernelcache without erasing its data (VM must be off)",+ discussion: """+ Swaps the kernel the guest boots for the one `fw patch` built, keeping+ every volume. The booting kernelcache lives in Preboot as an IMG4;+ iBoot accepts a modified IM4P under the original signed IM4M — the same+ image4 bypass that lets `cfw install` rewrite the Preboot device tree —+ so this replaces the kernelcache's payload and nothing else. No volume+ is reformatted, so the guest's data survives. It is the one boot-chain+ change that reaches an installed guest without a restore, which always+ erases (see `restore --no-erase`).++ It needs the patched kernelcache from the restore tree, so run+ `fw set-patches` then `fw patch` first, with the restore tree kept+ (`--keep-artifacts`). Needs root, and the VM must be powered off.+ """,+ )++ @OptionGroup var lib: VPhoneLibraryOption+ @Argument(help: "VM name") var name: String?++ func run() throws {+ let name = try VPhoneVirtualMachineSelection.resolveExisting(name, in: lib.library)+ let bundle = try lib.library.bundle(named: name)+ let code = try VPhoneCustomFirmwareInstaller.elevate(+ bundle: bundle.url,+ resources: VPhoneResources.resolve(),+ mode: .kernelUpdate,+ )+ throw ExitCode(code)+ }+}+struct VPhoneCustomFirmwareUpdateEnvironmentCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "update-environment",diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstringsindex c4aa3cda..dde07146 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings@@ -13199,13 +13199,13 @@"zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "客户机已包含为此虚拟机设定的全部补丁。" } }}},- "Boot chain: ^[%lld patch](inflect: true), applied only by restoring the machine, which erases its data." : {+ "Boot chain: ^[%lld patch](inflect: true) not applied. A kernel patch applies with `cfw update-kernel` and keeps the data; the rest need a restore, which erases. Run `vphone-cli fw patches %@` for each." : {"localizations" : {- "en" : { "stringUnit" : { "state" : "translated", "value" : "Boot chain: ^[%lld patch](inflect: true), applied only by restoring the machine, which erases its data." } },- "ja" : { "stringUnit" : { "state" : "translated", "value" : "起動チェーン:%lld 件のパッチ。マシンを復元した場合にのみ反映され、復元するとデータは消去されます。" } },- "ko" : { "stringUnit" : { "state" : "translated", "value" : "부트 체인: 패치 %lld개. 머신을 복원해야만 반영되며, 복원하면 데이터가 지워집니다." } },- "vi" : { "stringUnit" : { "state" : "translated", "value" : "Chuỗi khởi động: %lld bản vá, chỉ được áp dụng khi khôi phục máy, việc này sẽ xoá dữ liệu của máy." } },- "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "启动链:%lld 个补丁,只有重新恢复虚拟机才会生效,而恢复会清除其数据。" } }+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Boot chain: ^[%lld patch](inflect: true) not applied. A kernel patch applies with `cfw update-kernel` and keeps the data; the rest need a restore, which erases. Run `vphone-cli fw patches %@` for each." } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "起動チェーン:未反映 %1$lld 件。カーネルのパッチは `cfw update-kernel` で反映でき、データは保持されます。それ以外は復元が必要で、復元するとデータは消去されます。各手順は `vphone-cli fw patches %2$@` で確認してください。" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "부트 체인: 미반영 %1$lld개. 커널 패치는 `cfw update-kernel`로 반영되며 데이터가 유지됩니다. 나머지는 복원이 필요하고 복원하면 데이터가 지워집니다. 각 단계는 `vphone-cli fw patches %2$@`로 확인하세요." } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Chuỗi khởi động: %1$lld bản vá chưa áp dụng. Bản vá kernel áp dụng bằng `cfw update-kernel` và giữ nguyên dữ liệu; phần còn lại cần khôi phục, việc này sẽ xoá dữ liệu. Chạy `vphone-cli fw patches %2$@` để xem từng bước." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "启动链:%1$lld 个补丁未应用。内核补丁可用 `cfw update-kernel` 应用并保留数据;其余需要重新恢复,恢复会清除数据。运行 `vphone-cli fw patches %2$@` 查看各自步骤。" } }}},"Apply to Guest" : {diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swiftindex dd9ae550..d447d30a 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift@@ -296,7 +296,7 @@ struct VPhoneLaunchpadMachineInspector: View {// nothing in this section applies a boot-chain patch,// so a count with no button would read as a dead end.if catalog.pendingBootChainPatches > 0 {- Text("Boot chain: ^[\(catalog.pendingBootChainPatches) patch](inflect: true), applied only by restoring the machine, which erases its data.")+ Text("Boot chain: ^[\(catalog.pendingBootChainPatches) patch](inflect: true) not applied. A kernel patch applies with `cfw update-kernel` and keeps the data; the rest need a restore, which erases. Run `vphone-cli fw patches \(machine.name)` for each.").font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)