Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Add the Launchpad Update Kernel action for cfw update-kernel

Jacky04a13e47c74c
diff --git a/Documents/Guides/launchpad-cli.md b/Documents/Guides/launchpad-cli.md
index e0988373..dea232f8 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`, 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. |
+| 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, no restore tree needed), 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,7 +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 |
+| `cfw update-kernel <name>` | Re-patch the kernelcache from the machine's current selection and swap it into Preboot, keeping the data (VM off); the data-preserving way to change a kernel patch on an installed VM, no restore tree needed |
| `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.md
index fc65f6a8..18a5bb03 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -2762,17 +2762,21 @@ repartitions whatever the host asks — `restore --no-erase` refuses; see
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`) →
+mode `.kernelUpdate`) host-mounts Preboot on a clone and swaps in a re-patched
+kernelcache, keeping every volume. It re-patches the pristine kernelcache kept in
+`FirmwareOriginals` with the VM's current selection
+(`FirmwarePipeline.patchKernelcacheFile`, in the `.jb` variant — `.regular`
+omits the AMFI/JB kernel patches and CS_KILLs launchd), so it needs no restore
+tree and no prior `fw patch`. The splice is
+`CustomFirmwarePostRestoreDeviceTree.kernelcacheReplacingPayload`, which carries
+the whole IM4P (compression and any PAYP tail) verbatim and keeps the IMG4's
+manifest.
+
+Proven on test VMs (iPhone 27.0 24A435 + cloudOS 26.4) 2026-10-05, including a VM
+with no restore tree, through the Launchpad helper: a marker in
+`/var/mobile/Documents`, `kernel-exp-display_refresh_120hz` toggled with
+`fw set-patches`, `cfw update-kernel`, then boot — the guest booted the
+re-patched kernelcache and the marker survived. Flow: `fw set-patches` →
`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
diff --git a/Research/Firmware/post_creation_patch_changes.md b/Research/Firmware/post_creation_patch_changes.md
index 7f9e5f63..c683643f 100644
--- a/Research/Firmware/post_creation_patch_changes.md
+++ b/Research/Firmware/post_creation_patch_changes.md
@@ -144,13 +144,15 @@ is off:
patches plus the late ones the old installer added.
**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
+host-mounts Preboot and swaps in a re-patched kernelcache under 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. It re-patches the pristine kernelcache kept in `FirmwareOriginals`
+with the VM's current selection, so it needs no restore tree and no prior
+`fw patch`: flow is `fw set-patches` (or the Launchpad patch editor) then
+`cfw update-kernel` (proven on test VMs 2026-10-05, including a VM with no
+restore tree — guest booted the re-patched kernel with its
+`/var/mobile/Documents` marker intact). 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.
diff --git a/Research/Restore/native_restore_architecture.md b/Research/Restore/native_restore_architecture.md
index 62a31d8f..3eb4d2cf 100644
--- a/Research/Restore/native_restore_architecture.md
+++ b/Research/Restore/native_restore_architecture.md
@@ -319,10 +319,14 @@ 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
+clone and swaps in a re-patched kernelcache, keeping every volume. It re-patches
+the pristine kernelcache kept in `FirmwareOriginals` with the VM's current
+selection (`FirmwarePipeline.patchKernelcacheFile`, in the `.jb` variant), so it
+needs no restore tree and no prior `fw patch` — a VM in normal use has its
+restore tree deleted but keeps `FirmwareOriginals`. Proven on test VMs
+2026-10-05: with a kernel patch toggled by `fw set-patches` and no restore tree,
+`cfw update-kernel` 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
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchDrift.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchDrift.swift
index 1c66e04d..b5740356 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchDrift.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchDrift.swift
@@ -22,10 +22,10 @@ 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"
- /// 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"
+ /// The kernelcache lives in Preboot as an IMG4; `cfw update-kernel`
+ /// re-patches it from the VM's FirmwareOriginals and swaps its IM4P into
+ /// Preboot under the signed manifest, with no restore and no erase.
+ case updateKernel = "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.
@@ -38,7 +38,7 @@ public enum FirmwarePatchDelivery: String, Sendable, Hashable, CaseIterable, Cod
case .firmware(.avpBooter):
self = .firmwarePatch
case .firmware(.kernelcache):
- self = .firmwarePatchThenUpdateKernel
+ self = .updateKernel
case .firmware:
// iBSS, iBEC, LLB, TXM, DeviceTree, and the restore-only
// Filesystem/Manifest.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift
index dc3a2caf..31b44c12 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift
@@ -213,6 +213,46 @@ public final class FirmwarePipeline {
return allRecords
}
+ /// Patch a kernelcache file in place with this VM's selection, without a
+ /// restore tree. For `cfw update-kernel`: the pristine kernelcache is kept
+ /// in `FirmwareOriginals`, and only the Preboot copy needs replacing, so the
+ /// full restore-tree pipeline is not run — just the kernelcache component's
+ /// patchers, resolved and gated exactly as `patchAll` would, over the one
+ /// file. `url` is a writable copy of the pristine kernelcache (a bare IM4P);
+ /// it is left patched and re-wrapped in its own container. The versions come
+ /// from the plan `fw patch` recorded, since the live BuildManifest reads the
+ /// cloudOS version, not the iOS base. Returns whether any patch applied.
+ @discardableResult
+ public func patchKernelcacheFile(at url: URL, iOSBase: VPhoneVersion?, cloudOS: VPhoneVersion?) throws -> Bool {
+ baseProductVersion = iOSBase
+ cloudOSProductVersion = cloudOS
+ let plan = try resolvePlan(iOSBase: iOSBase, cloudOS: cloudOS)
+ resolvedPlan = plan
+ let gate = plan.map { VPhonePatchGate(plan: $0) } ?? .unrestricted
+ // restoreDir is unused when building the kernelcache component's
+ // patchers (they take the gate and versions, not files), so the VM
+ // directory stands in for the parameter.
+ let components = buildComponentList(restoreDir: vmDirectory, iOSBase: iOSBase, plan: plan, gate: gate)
+ guard let kernel = components.first(where: { $0.name == "kernelcache" }) else {
+ throw PatcherError.invalidFormat("this build has no kernelcache component to patch")
+ }
+ guard !kernel.patcherFactories.isEmpty else {
+ // The preset turns every kernel patch off: the pristine kernelcache
+ // is already the wanted one.
+ return false
+ }
+ let payload = try loader.load(from: url)
+ let (patched, records) = try patchData(
+ payload,
+ componentName: "kernelcache",
+ patcherFactories: kernel.patcherFactories,
+ expectsPatches: expectsPatches(for: "kernelcache", plan: plan),
+ )
+ guard !records.isEmpty else { return false }
+ try loader.save(patched, to: url)
+ return true
+ }
+
/// Patch every component in order, against the files under `restoreDir` and the
/// VM directory root.
///
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchDriftTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchDriftTests.swift
index 3b389bb0..68504e66 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 == .firmwarePatchThenUpdateKernel)
+#expect(result["kernel-b"]?.delivery == .updateKernel)
#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,7 @@ struct FirmwarePatchDriftTests {
@Test
func `Each target is delivered by the step that owns its bytes`() {
#expect(FirmwarePatchDelivery(target: .firmware(.avpBooter)) == .firmwarePatch)
- #expect(FirmwarePatchDelivery(target: .firmware(.kernelcache)) == .firmwarePatchThenUpdateKernel)
+ #expect(FirmwarePatchDelivery(target: .firmware(.kernelcache)) == .updateKernel)
for component in [VPhoneFirmwareComponent.iBSS, .iBEC, .llb, .txm, .deviceTree] {
#expect(FirmwarePatchDelivery(target: .firmware(component)) == .restore)
}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
index faed50fa..ac46545a 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
@@ -46,14 +46,14 @@ 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`).
+ /// Only the Preboot kernelcache: replace its IM4P with one re-patched
+ /// from the VM's selection, 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. The kernelcache is re-patched from the pristine copy in
+ /// FirmwareOriginals, so no restore tree or prior `fw patch` is needed.
case kernelUpdate
var summary: String {
@@ -480,19 +480,6 @@ struct VPhoneCustomFirmwareInstaller {
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 {
@@ -501,6 +488,10 @@ struct VPhoneCustomFirmwareInstaller {
}
try requireFreeSpace(at: [bundlePath, work.url.path])
+ let (patched, enabledKernelPatches) = try patchedKernelcacheForUpdate(
+ in: bundleDirectory, path: bundlePath, owner: callerUID, work: work,
+ )
+
let image: URL
let cloned = try work.directory.clone(disk, to: "Disk.img")
if cloned {
@@ -612,18 +603,96 @@ struct VPhoneCustomFirmwareInstaller {
try work.directory.rename("Disk.img", to: "Disk.img", in: bundleDirectory)
}
if changed {
- recordKernelcacheReceipt(in: bundleDirectory, owner: invokingUser.map { ($0.uid, $0.gid) })
+ recordKernelcacheReceipt(enabled: enabledKernelPatches, in: bundleDirectory, owner: invokingUser.map { ($0.uid, $0.gid) })
}
print("[+] Guest kernel updated; start the VM to boot the re-patched kernelcache")
}
+ /// The patched kernelcache (a bare IM4P) to install into Preboot, for the
+ /// VM's current selection.
+ ///
+ /// Preferred source: the pristine kernelcache in `FirmwareOriginals`,
+ /// re-patched here with the selection. This needs no restore tree, so it
+ /// works on a VM in normal use, and reflects a `fw set-patches` made since
+ /// the last `fw patch`. Root re-patches only for a bundled preset; a preset
+ /// naming an external `.vphonepatchset` is not loaded here (root loads no
+ /// external set), and falls back to the restore tree `fw patch` wrote as the
+ /// user. A VM with neither is refused.
+ private func patchedKernelcacheForUpdate(
+ in bundleDirectory: VPhoneConfinedDirectory,
+ path bundlePath: String,
+ owner: uid_t?,
+ work: WorkDirectory,
+ ) throws -> (payload: Data, enabledKernelPatches: Set<String>) {
+ let selection = (try? bundleDirectory.readData(VPhonePatchPresetStore.selectionFileName))
+ .flatMap { try? PropertyListDecoder().decode(VPhoneVirtualMachinePatchSelection.self, from: $0) }
+ ?? VPhoneVirtualMachinePatchSelection()
+ let plan = readPatchPlan(in: bundleDirectory)
+ if let pristine = try firmwareOriginalsKernelcache(in: bundleDirectory),
+ let preset = VPhonePatchPresetStore.preset(named: selection.presetIdentifier),
+ !preset.patchSets.contains(where: { if case .external = $0 { true } else { false } })
+ {
+ try pristine.directory.copyFile(from: pristine.name, to: "kernelcache.im4p", in: work.directory)
+ let copy = work.file("kernelcache.im4p")
+ let pipeline = FirmwarePipeline(
+ vmDirectory: URL(fileURLWithPath: bundlePath, isDirectory: true),
+ // The public firmware mode is JB; .regular would leave out the
+ // AMFI and other custom-firmware kernel patches and CS_KILL launchd.
+ variant: .jb,
+ verbose: true,
+ preset: preset,
+ blockedPatches: Set(selection.blockedPatches),
+ allowedPatches: Set(selection.allowedPatches),
+ )
+ let changed = try pipeline.patchKernelcacheFile(
+ at: copy,
+ iOSBase: plan?.iOSBaseVersion.flatMap(VPhoneVersion.init),
+ cloudOS: plan?.cloudOSVersion.flatMap(VPhoneVersion.init),
+ )
+ print(" [*] kernelcache re-patched from \(VPhoneBundleOperations.firmwareOriginalsDirectoryName)"
+ + (changed ? "" : " (preset leaves every kernel patch off)"))
+ return (try Data(contentsOf: copy), Set(pipeline.resolvedPlan?.enabled ?? []))
+ }
+ // No originals, or an external-set preset: the restore tree's kernelcache
+ // was patched by `fw patch` running as the user.
+ if let restore = try? restoreTree(in: bundleDirectory, path: bundlePath, owner: owner),
+ let data = try? restore.readData("kernelcache.research.vphone600")
+ {
+ print(" [*] kernelcache taken from the restore tree")
+ return (data, Set(plan?.enabledPatches ?? []))
+ }
+ throw ValidationError(
+ "No kernelcache to install: this VM has no \(VPhoneBundleOperations.firmwareOriginalsDirectoryName) and no restore tree. Remove the restore tree and run `fw prepare` + `fw patch`, or recreate the VM.",
+ )
+ }
+
+ /// The pristine kernelcache kept in `FirmwareOriginals/<tree>/`, or nil when
+ /// the VM was patched by a build that kept no originals. Reached without a
+ /// link anywhere on the way.
+ private func firmwareOriginalsKernelcache(
+ in bundleDirectory: VPhoneConfinedDirectory,
+ ) throws -> (directory: VPhoneConfinedDirectory, name: String)? {
+ let originalsName = VPhoneBundleOperations.firmwareOriginalsDirectoryName
+ guard (try? bundleDirectory.isDirectory(originalsName)) == true,
+ let originals = try? bundleDirectory.directory(originalsName)
+ else { return nil }
+ for tree in (try? originals.entries()) ?? [] {
+ guard (try? originals.isDirectory(tree)) == true,
+ let treeDir = try? originals.directory(tree),
+ (try? treeDir.isRegularFile("kernelcache.research.vphone600")) == true
+ else { continue }
+ return (treeDir, "kernelcache.research.vphone600")
+ }
+ return nil
+ }
+
/// Record the kernelcache part of the receipt with the kernel patches the
/// plan `fw patch` resolved. Best-effort, like `recordGuestReceipt`.
private func recordKernelcacheReceipt(
+ enabled: Set<String>,
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)
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift
index 2b17fbb6..2fb85027 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift
@@ -466,8 +466,8 @@ struct VPhoneFirmwareSetPatchesCommand: ParsableCommand {
AVPBooter `fw patch`; read at the next boot. Needs
the restore tree (`--keep-artifacts`).
- kernelcache `fw patch`, then `cfw update-kernel`
- (root), which keeps the guest's data.
+ kernelcache `cfw update-kernel` (root), which keeps the
+ guest's data (no restore).
Guest (system, dyld cache, `cfw update-environment` (root), which
Preboot device tree) applies this choice both on and off.
LLB, TXM, DeviceTree only a restore, which erases the guest's data.
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchCatalogReport.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchCatalogReport.swift
index 9b20e4be..94d5f13a 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchCatalogReport.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchCatalogReport.swift
@@ -405,10 +405,9 @@ 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 .updateKernel:
+ "run `sudo vphone-cli cfw update-kernel \(vm)` with the machine off;"
+ + " it re-patches the kernelcache and keeps the guest's data (no restore)."
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.swift
index b3061e9b..c87b41e5 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift
@@ -381,18 +381,19 @@ struct VPhoneCustomFirmwareUpdateKernelCommand: ParsableCommand {
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.
+ Replaces the kernel the guest boots with one re-patched from the VM's
+ current selection, 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`).
+
+ The kernelcache is re-patched from the pristine copy kept in
+ FirmwareOriginals, so no restore tree and no prior `fw patch` is needed:
+ change the selection with `fw set-patches` (or the Launchpad patch
+ editor), then run this. Needs root, and the VM must be powered off.
""",
)
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
index 53660f92..0a1eb673 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
@@ -326,7 +326,16 @@
let blocked = machine ? #"["kernel-cfw-debugger","dyld-cfw-camera"]"# : "[]"
let records = machine ? #""installed":true,"receiptRecorded":true,"pendingPatches":2,"# : ""
func pending(_ part: String, _ value: Bool = false) -> String {
- machine ? #","part":"\#(part)","pending":\#(value)"# : ""
+ guard machine else { return "" }
+ // delivery is reported only for a pending patch, by part.
+ let deliveryKind: String = switch part {
+ case "kernelcache": "update-kernel"
+ case "Guest": "update-environment"
+ case "AVPBooter": "fw-patch"
+ default: "restore"
+ }
+ let delivery = value ? #","delivery":"\#(deliveryKind)""# : ""
+ return #","part":"\#(part)","pending":\#(value)"# + delivery
}
let json = """
{"activePreset":"\(active)","blockedPatches":\(blocked),"allowedPatches":[],\(records)
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift
index c0d09bf3..18d5506c 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift
@@ -60,6 +60,7 @@ struct VPhoneLaunchpadControlCommands {
case "vm.leases": return try await leases(request)
case "cfw.install": return try await installCustomFirmware(request, emit: emit)
case "cfw.update-environment": return try await updateGuestEnvironment(request, emit: emit)
+ case "cfw.update-kernel": return try await updateKernelControl(request, emit: emit)
case "guest.send": return try await sendToGuest(request)
case "guest.rpc": return try await callGuest(request)
case "guest.unlock": return try await unlockGuest(request)
@@ -697,6 +698,24 @@ struct VPhoneLaunchpadControlCommands {
return ["name": machine.name, "bundle": version, "status": status]
}
+ private func updateKernelControl(_ request: VPhoneLaunchpadControlRequest, emit: @escaping Emit) async throws -> Any {
+ let machine = try await machine(request)
+ let version = try bundleVersion(of: machine)
+ guard library.state(of: machine) == .stopped else {
+ throw VPhoneLaunchpadError("Stop \(machine.name) before updating its kernel.")
+ }
+ let status = try await model.helper.updateKernel(
+ bundleVersion: version,
+ machineName: machine.name,
+ libraryRoot: machine.libraryRoot,
+ onLine: emit,
+ )
+ guard status == 0 else {
+ throw VPhoneLaunchpadError("Unable to update the kernel. Check the log for details.")
+ }
+ return ["name": machine.name, "bundle": version, "status": status]
+ }
+
// MARK: - DHCP leases
private func leases(_ request: VPhoneLaunchpadControlRequest) async throws -> Any {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift
index 0a9a3956..9d65c834 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift
@@ -312,6 +312,39 @@ final class VPhoneLaunchpadHelperClient {
}
}
+ /// Runs `cfw update-kernel` as root: swaps the Preboot kernelcache for the
+ /// re-patched one, keeping the guest's data. Output lines go to `onLine`.
+ func updateKernel(
+ bundleVersion: String,
+ machineName: String,
+ libraryRoot: String,
+ onLine: @escaping @Sendable (String) -> Void,
+ ) async throws -> Int32 {
+ let authorization = try await authorizationSession.externalForm()
+ guard receiver.claim(onLine) else {
+ throw Self.firmwareBusy
+ }
+ defer { receiver.release() }
+ return try await withTaskCancellationHandler {
+ try await request { proxy, done in
+ proxy.updateKernel(
+ authorization: authorization,
+ bundleVersion: bundleVersion,
+ machineName: machineName,
+ libraryRoot: libraryRoot,
+ ) { status, message in
+ if let message {
+ done(.failure(VPhoneLaunchpadError(message)))
+ } else {
+ done(.success(status))
+ }
+ }
+ }
+ } onCancel: {
+ Task { @MainActor in self.cancelCustomFirmware() }
+ }
+ }
+
/// Runs `vm leases --release-orphans --json` as root against the machines
/// of `libraryRoots`, and returns the command's JSON output.
func releaseOrphanedLeases(bundleVersion: String, libraryRoots: [String]) async throws -> Data {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift.new b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift.new
new file mode 100644
index 00000000..e69de29b
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
index dde07146..3d987c99 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
@@ -13199,13 +13199,67 @@
"zh-Hans" : { "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." : {
+ "Boot chain: ^[%lld patch](inflect: true) (TXM, device tree, LLB) not applied; only a restore applies them, which erases the data. Run `vphone-cli fw patches %@` for each." : {
"localizations" : {
- "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$@` 查看各自步骤。" } }
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Boot chain: ^[%lld patch](inflect: true) (TXM, device tree, LLB) not applied; only a restore applies them, which erases the data. Run `vphone-cli fw patches %@` for each." } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "起動チェーン:未反映 %lld 件(TXM・デバイスツリー・LLB)。復元でのみ反映され、復元するとデータは消去されます。各手順は `vphone-cli fw patches %@` で確認してください。" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "부트 체인: 미반영 %lld개(TXM, 디바이스 트리, LLB). 복원으로만 반영되며 복원하면 데이터가 지워집니다. 각 단계는 `vphone-cli fw patches %@`로 확인하세요." } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Chuỗi khởi động: %lld bản vá (TXM, cây thiết bị, LLB) chưa áp dụng; chỉ khôi phục mới áp dụng, việc này xoá dữ liệu. Chạy `vphone-cli fw patches %@` để xem từng bước." } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "启动链:%lld 个补丁(TXM、设备树、LLB)未应用;只有重新恢复才会生效,而恢复会清除数据。运行 `vphone-cli fw patches %@` 查看各自步骤。" } }
+ }
+ },
+ "Update Kernel" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Update Kernel" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "カーネルを更新" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "커널 업데이트" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Cập nhật kernel" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "更新内核" } }
+ }
+ },
+ "Updating kernel…" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Updating kernel…" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "カーネルを更新中…" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "커널 업데이트 중…" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Đang cập nhật kernel…" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "正在更新内核…" } }
+ }
+ },
+ "Unable to update the kernel." : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Unable to update the kernel." } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "カーネルを更新できません。" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "커널을 업데이트할 수 없습니다." } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Không thể cập nhật kernel." } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "无法更新内核。" } }
+ }
+ },
+ "Swaps the Preboot kernelcache for the one this machine's patches resolve to, keeping the data (no restore)." : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Swaps the Preboot kernelcache for the one this machine's patches resolve to, keeping the data (no restore)." } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "Preboot のカーネルキャッシュをこのマシンのパッチ選択に合うものに入れ替えます。データは保持され、復元は不要です。" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "Preboot 커널 캐시를 이 머신의 패치 선택에 맞는 것으로 교체합니다. 데이터는 유지되며 복원이 필요 없습니다." } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Thay kernelcache trong Preboot bằng bản khớp với lựa chọn bản vá của máy này, giữ nguyên dữ liệu (không khôi phục)." } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "把 Preboot 的内核缓存换成与此虚拟机补丁选择匹配的版本,保留数据(无需恢复)。" } }
+ }
+ },
+ "Stop the machine to update its kernel." : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Stop the machine to update its kernel." } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "カーネルを更新するにはマシンを停止してください。" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "커널을 업데이트하려면 머신을 중지하십시오." } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Hãy dừng máy để cập nhật kernel." } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "停止虚拟机后才能更新其内核。" } }
+ }
+ },
+ "^[%lld kernel patch](inflect: true) to apply with Update Kernel (keeps the data)." : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "^[%lld kernel patch](inflect: true) to apply with Update Kernel (keeps the data)." } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "「カーネルを更新」で反映するカーネルのパッチ:%lld 件(データは保持)。" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "‘커널 업데이트’로 반영할 커널 패치 %lld개(데이터 유지)." } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "%lld bản vá kernel sẽ áp dụng bằng Cập nhật kernel (giữ dữ liệu)." } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "%lld 个内核补丁可用“更新内核”生效(保留数据)。" } }
}
},
"Apply to Guest" : {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift
index d447d30a..6c5a33a7 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift
@@ -292,11 +292,10 @@ struct VPhoneLaunchpadMachineInspector: View {
}
.help(pendingHelp(catalog, pending: pending))
}
- // Said in the open rather than only in the tooltip:
- // 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) 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.")
+ // The kernelcache has its own button below; only the
+ // restore-only patches need this spelled-out dead-end.
+ if catalog.pendingRestorePatches > 0 {
+ Text("Boot chain: ^[\(catalog.pendingRestorePatches) patch](inflect: true) (TXM, device tree, LLB) not applied; only a restore applies them, which erases the data. Run `vphone-cli fw patches \(machine.name)` for each.")
.font(.caption)
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
@@ -304,6 +303,18 @@ struct VPhoneLaunchpadMachineInspector: View {
}
HStack {
Spacer()
+ if catalog.installed == true, catalog.pendingKernelPatches > 0 {
+ Button("Update Kernel") {
+ Task {
+ await library.updateKernel(machine.path)
+ patchRevision += 1
+ }
+ }
+ .disabled(library.state(of: machine.path) != .stopped)
+ .help(library.state(of: machine.path) == .stopped
+ ? String(localized: "Swaps the Preboot kernelcache for the one this machine's patches resolve to, keeping the data (no restore).")
+ : String(localized: "Stop the machine to update its kernel."))
+ }
if catalog.installed == true, catalog.pendingGuestPatches > 0 {
Button("Apply to Guest") {
Task {
@@ -339,8 +350,11 @@ struct VPhoneLaunchpadMachineInspector: View {
if catalog.pendingGuestPatches > 0 {
lines.append(String(localized: "^[\(catalog.pendingGuestPatches) guest patch](inflect: true) to apply with Apply to Guest."))
}
- if catalog.pendingBootChainPatches > 0 {
- lines.append(String(localized: "^[\(catalog.pendingBootChainPatches) boot chain patch](inflect: true) that only a restore applies."))
+ if catalog.pendingKernelPatches > 0 {
+ lines.append(String(localized: "^[\(catalog.pendingKernelPatches) kernel patch](inflect: true) to apply with Update Kernel (keeps the data)."))
+ }
+ if catalog.pendingRestorePatches > 0 {
+ lines.append(String(localized: "^[\(catalog.pendingRestorePatches) boot chain patch](inflect: true) that only a restore applies."))
}
lines.append(String(localized: "vphone-cli fw patches \(machine.name) lists each one."))
return lines.joined(separator: "\n")
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
index 59374363..37046ab3 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
@@ -527,6 +527,40 @@ final class VPhoneLaunchpadMachineLibrary {
await refresh()
}
+ /// Replaces the machine's Preboot kernelcache with the one its current
+ /// patch selection resolves to, keeping the guest's data (no restore). The
+ /// data-preserving way to apply a kernel patch change to an installed VM.
+ func updateKernel(_ machine: Path) async {
+ guard let version = bundleVersion(for: machine) else {
+ actionError = VPhoneLaunchpadError(String(localized: "No Core Bundle version is installed. Install one in Core Bundle."))
+ return
+ }
+ activities[machine] = String(localized: "Updating kernel…")
+ defer { activities[machine] = nil }
+ appendConsoleLog(machine, "$ vphone-cli cfw update-kernel \(machine.name)")
+ let log = Self.consoleLog(machine)
+ do {
+ let status = try await helper.updateKernel(
+ bundleVersion: version,
+ machineName: machine.name,
+ libraryRoot: machine.libraryRoot,
+ onLine: { line in Self.append(line, to: log) },
+ )
+ if status != 0 {
+ actionError = VPhoneLaunchpadError(
+ String(localized: "Unable to update the kernel."),
+ detail: String(localized: "Choose Show Console Log for the full output."),
+ )
+ }
+ } catch {
+ if !(error is CancellationError) {
+ actionError = error as? VPhoneLaunchpadError
+ ?? VPhoneLaunchpadError(String(localized: "Unable to update the kernel."), detail: error.localizedDescription)
+ }
+ }
+ await refresh()
+ }
+
/// Stops a machine. The guest is asked to shut down first, so it quits its
/// apps and unmounts its volumes. `vm stop`, which ends the virtual
/// machine the way cutting the power would, follows only when the guest
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swift
index 74e741f9..a82f34c2 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swift
@@ -56,6 +56,13 @@ nonisolated struct VPhoneLaunchpadPatchCatalog: Decodable, Sendable {
/// Where the patch lives in a machine: a boot-chain component's name,
/// or `Guest`. Reported only for a named machine; nil otherwise.
let part: String?
+ /// The step that delivers this patch to an installed guest, reported by
+ /// the machine's own bundle only for a pending patch:
+ /// `update-environment`, `update-kernel`, `fw-patch` or
+ /// `restore`. A bundle without `cfw update-kernel` never reports
+ /// `update-kernel`, so the kernel button keyed on it simply
+ /// does not appear there. Nil when not pending or not reported.
+ let delivery: String?
var id: String {
identifier
@@ -69,6 +76,11 @@ nonisolated struct VPhoneLaunchpadPatchCatalog: Decodable, Sendable {
Self.bootChainParts.contains(part ?? target)
}
+ /// The kernelcache, which `cfw update-kernel` changes without a restore.
+ var isKernel: Bool {
+ (part ?? target) == "kernelcache"
+ }
+
private static let bootChainParts: Set<String> = [
"AVPBooter", "iBSS", "iBEC", "LLB", "TXM", "kernelcache", "DeviceTree",
]
@@ -149,14 +161,23 @@ nonisolated struct VPhoneLaunchpadPatchCatalog: Decodable, Sendable {
)
}
- /// Pending patches a guest environment update brings in line.
+ /// Pending patches `cfw update-environment` brings in line (the bundle's
+ /// own classification; falls back to the part for a bundle that does not
+ /// report delivery).
var pendingGuestPatches: Int {
- patches.count { $0.pending == true && !$0.isBootChain }
+ patches.count { $0.pending == true && ($0.delivery ?? (!$0.isBootChain ? "update-environment" : "")) == "update-environment" }
+ }
+
+ /// Pending kernelcache patches `cfw update-kernel` applies without a
+ /// restore. Keyed on the delivery the machine's bundle reports, so a bundle
+ /// without the verb never counts any here and the button stays hidden.
+ var pendingKernelPatches: Int {
+ patches.count { $0.pending == true && $0.delivery == "update-kernel" }
}
- /// Pending patches only a restore brings in line.
- var pendingBootChainPatches: Int {
- patches.count { $0.pending == true && $0.isBootChain }
+ /// Pending boot-chain patches that only an erasing restore applies.
+ var pendingRestorePatches: Int {
+ patches.count { $0.pending == true && ($0.delivery ?? (($0.isBootChain && !$0.isKernel) ? "restore" : "")) == "restore" }
}
func preset(_ identifier: String) -> Preset? {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swift
index c23dc0e7..3db81b21 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swift
@@ -11,6 +11,8 @@ struct VPhoneLaunchpadHelperFirmwareRequest {
/// Redeploys the bundle's guest resources into a stopped machine and
/// nothing else.
case updateEnvironment
+ /// Swaps the Preboot kernelcache for the re-patched one, keeping data.
+ case updateKernel
}
let executable: URL
@@ -56,6 +58,8 @@ struct VPhoneLaunchpadHelperFirmwareRequest {
}
case .updateEnvironment:
arguments = ["cfw", "update-environment", machineName, "--library-root", libraryRoot]
+ case .updateKernel:
+ arguments = ["cfw", "update-kernel", machineName, "--library-root", libraryRoot]
}
self.executable = executable
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swift
index 3d6e9e5d..3415d392 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swift
@@ -108,6 +108,23 @@ final class VPhoneLaunchpadHelperService: NSObject, VPhoneLaunchpadHelperProtoco
)
}
+ func updateKernel(
+ authorization: Data,
+ bundleVersion: String,
+ machineName: String,
+ libraryRoot: String,
+ reply: @escaping @Sendable (Int32, String?) -> Void,
+ ) {
+ runFirmware(
+ .updateKernel,
+ authorization: authorization,
+ bundleVersion: bundleVersion,
+ machineName: machineName,
+ libraryRoot: libraryRoot,
+ reply: reply,
+ )
+ }
+
/// Both operations share one slot, so an install and an environment
/// update never write the same machine at once, and one cancel stops
/// either.
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadControl.swift b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadControl.swift
index 181332d3..e3cd1a10 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadControl.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadControl.swift
@@ -180,6 +180,9 @@ nonisolated struct VPhoneLaunchpadControlCommand: Sendable {
Self(name: "cfw.update-environment", arguments: ["name"], options: ["root"], flags: [],
summary: "Redeploy the machine's own bundle's guest resources (vphoned and hook dylibs) into it while stopped, and nothing else."),
+ Self(name: "cfw.update-kernel", arguments: ["name"], options: ["root"], flags: [],
+ summary: "Swap the stopped machine's Preboot kernelcache for the one its patches resolve to, keeping the data (no restore)."),
+
Self(name: "guest.send", arguments: ["name", "json"], options: ["root"], flags: [],
summary: "Send one raw vphone.sock request, such as {\"t\":\"tap\",\"x\":645,\"y\":1398}."),
Self(name: "guest.rpc", arguments: ["name", "method", "params..."], options: ["root"], flags: ["screen"],
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swift b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swift
index 3e658122..63804f8e 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swift
@@ -70,6 +70,18 @@ nonisolated protocol VPhoneLaunchpadHelperProtocol {
reply: @escaping @Sendable (Int32, String?) -> Void,
)
+ /// Runs `vphone-cli cfw update-kernel` from a store bundle as root: swaps
+ /// the Preboot kernelcache for the re-patched one and nothing else, keeping
+ /// the guest's data. Same output channel and reply as `installCustomFirmware`,
+ /// and `cancelCustomFirmware` stops it.
+ func updateKernel(
+ authorization: Data,
+ bundleVersion: String,
+ machineName: String,
+ libraryRoot: String,
+ reply: @escaping @Sendable (Int32, String?) -> Void,
+ )
+
/// Runs `vphone-cli vm leases --release-orphans --json` from a store
/// bundle as root, against the machines of `libraryRoots`, each of which
/// the caller must own. It removes the DHCP leases on the shared NAT