Run a virtual iPhone on an Apple Silicon Mac.
Swift
Create, install and patch minimal VMs
Maximilian Paßb77021fb55fe
diff --git a/Documents/Guides/launchpad-cli.md b/Documents/Guides/launchpad-cli.mdindex a09c984b..343fb62b 100644--- a/Documents/Guides/launchpad-cli.md+++ b/Documents/Guides/launchpad-cli.md@@ -113,7 +113,7 @@ version while a machine is bound to it; rebind or delete those machines first.| `vm list` | Machines in every library with run state, Core Bundle and log path. Only a VM process holding the disk (`vphone-vm`, or Virtualization's VM service) makes a machine `running`; any other process that has it open (`tail`, Spotlight, a backup tool) is listed in `diskOpenIn` (`12925 tail`) and leaves it `stopped` || `vm start <name> [--headless] [--wait]` / `vm stop <name>` | Launch with the machine's bundle, or stop; `--wait` waits for vphoned. Stop asks the guest to shut down (vphoned `system.shutdown`) and waits up to 30 s; when the guest cannot be asked or does not stop, it ends the virtual machine as before. Like `vphone-cli vm launch`, start is not refused by a process that only has the disk open; it prints a note naming it || `vm wait <name>` / `vm log <name> [--kind create\|dfu\|patch]` | Wait for vphoned; read a console log |-| `vm create <name> [--bundle <version>] [...] [--device <product-type>] [--preset <preset>] [--block <patch>]... [--allow <patch>]... [--no-template \| --slim on\|off --trim … --keep-languages … --service-profile … --remove-apps … --keep-apps … --accounts-off] [--from <step>]` | The New Machine pipeline, bound to `--bundle` or the default: cloned from a template, built first when missing (2.9), or restored on its own with `--no-template`; the slimming switches are `vphone-cli vm create`'s, except that Apple Account goes with the trimmed service profile as in New Machine (`--accounts-off` is accepted and changes nothing). `--block`/`--allow` (repeatable) turn one patch of the preset off or on, as New Machine's patch list and `vphone-cli fw set-patches` do (see below). `--device` makes an iPad guest, or with `AppleTV5,3` an Apple TV HD guest, which is always restored on its own without slimming and takes the `tvos` preset unless `--preset` names another, and with `AppleTV14,1` an Apple TV 4K guest, the same with the `tvos-4k` preset and its userland from the catalog's OTA; `--from` retries from a step (`findTemplate` … `firstBoot`) with the options the creation started with; the result names the template, whether this creation built it, and the patches it used |+| `vm create <name> [--bundle <version>] [...] [--device <product-type>] [--preset <preset>] [--block <patch>]... [--allow <patch>]... [--no-template \| --slim on\|off --trim … --keep-languages … --service-profile … --remove-apps … --keep-apps … --accounts-off] [--from <step>]` | The New Machine pipeline, bound to `--bundle` or the default: cloned from a template, built first when missing (2.9), or restored on its own with `--no-template`; the slimming switches are `vphone-cli vm create`'s, except that Apple Account goes with the trimmed service profile as in New Machine (`--accounts-off` is accepted and changes nothing). `--block`/`--allow` (repeatable) turn one patch of the preset off or on, as New Machine's patch list and `vphone-cli fw set-patches` do (see below). `--device` makes an iPad guest, or with `AppleTV5,3` an Apple TV HD guest, which is always restored on its own without slimming and takes the `tvos` preset unless `--preset` names another, and with `AppleTV14,1` an Apple TV 4K guest, the same with the `tvos-4k` preset and its userland from the catalog's OTA; `--preset minimal` (Minimal: a stock boot chain, kernel and TXM, with the system customised before the restore) is also restored on its own without slimming, and its `fw patch` runs as root through the helper; `--from` retries from a step (`findTemplate` … `firstBoot`) with the options the creation started with; the result names the template, whether this creation built it, and the patches it used || `vm set-bundle <name> <version> [--update-environment]` | Bind a machine to another installed version. `--update-environment` also redeploys that version's guest environment and needs a stopped machine; a disk another process has open refuses it, naming that process, before the binding changes. If the update itself fails, the machine stays bound to the new version and `vm list` still shows the old `guestEnvironmentBundle`: run `cfw update-environment` to finish || `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. The helper puts temporary work files on the VM library's external volume when applicable. It and the two updates below refuse a disk another process has open, naming it (`12925 tail`). |diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex e5642060..97d25500 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -1970,9 +1970,10 @@ the restore left it.`BuildManifest.plist`, but neither is a patcher over that one file — the firstrewrites cryptex images across the restore tree, the second rewrites hashes thatdescribe files other steps produced. Restoring the manifest alone would describe-a tree that no longer exists. Both are `.less`-only, and `.less` is excluded from-the mechanism outright so a `.less` run over a CFW-patched VM cannot read "this-variant builds no boot-chain patchers" as "put the boot chain back".+a tree that no longer exists. Both run only for the `minimal` preset (see "The `minimal`+preset" below), which names no boot chain, kernel or TXM set: a `minimal` run over+a CFW-patched VM puts that boot chain back, which is what the restore image+expects.**Existing VMs.** A machine patched by an earlier build has no stash, so thefirst run under the new code would adopt its already-patched bytes as the@@ -3261,3 +3262,59 @@ in `fw patch`. The SEP firmware (`sep-firmware.vphone600.RELEASE.im4p`, sent asbefore keep Apple's SEP ROM; `vm config --seprom opensep|apple` switches onewithout a restore. `Firmware/opensep_sep_rom.md` has the contract and thevalidation.++## The `minimal` preset: a restore image instead of patches (2026-10-19)++The patchless variant (`FirmwarePipeline.Variant.less`) was unreachable: every+caller passed `.jb`. It is a preset now, `minimal`, and the variant is+gone. The preset names three sets:++- `com.vphone.patchset.bootchain`, allowing only iBEC's and LLB's patches,+ which the old `.less` variant applied too ("for the serial logs"). AVPBooter,+ iBSS, TXM and the restore ramdisk stay stock, and the pipeline builds no+ patcher for a boot chain component none of whose patches is on. A stock LLB+ does not get the restored guest to its kernel: on 26.6 with cloudOS+ 23E5207q it restarts right after its banner, with Apple's ROMs as with+ OpenAVB and OpenSEP (2026-10-19). Which of LLB's patches it needs is open.+- `com.vphone.patchset.devicetree`, allowing only the board presentation+ (`devicetree-cfw-serial_number`, `-home_button_type`,+ `-artwork_device_subtype`, `-island_notch_location`) and the haptics and+ microphone-array removals. They change no code.+- `com.vphone.patchset.restore.image` (`FirmwareRestoreImagePatchSet`), new,+ named by no other preset:++| Identifier | What `fw patch` does |+| --- | --- |+| `filesystem-boot-cryptex_merge` | Merges the AppOS and SystemOS cryptexes into the OS image, adds the dyld symlinks, then rebuilds the static trust cache, the mtree and the digest database and root hash (`apfs_sealvolume`) |+| `filesystem-boot-gpu_driver` | Installs the PCC paravirtual GPU driver `fw prepare` staged |+| `filesystem-boot-mobileactivationd_should_hactivate` | The `should_hactivate` patch, in the image |+| `filesystem-boot-vphoned` | vphoned and its launch daemon, in the image |+| `filesystem-boot-launchd_cache_loader_unsecure_cache_gate` | Lets launchd read the launch daemons from the volume |+| `manifest-boot-digest_rehash` | Rewrites every BuildManifest digest to the files the restore now sends |++The kernel and TXM stay stock, and the restore installs a system whose seal+the stock kernel verifies. `CryptexFilesystemPatcher` and `ManifestHashPatcher` used+to emit `filesystem.cryptex.merge` and `manifest.hash`, which no set declared;+they emit the identifiers above, and the pipeline builds each patcher only when+its patch is enabled.++Nothing may write the System volume after the restore, because that breaks the+seal. So for a VM whose plan enables `filesystem-boot-cryptex_merge`:++- `cfw install` touches no disk: it records an empty `Guest` receipt part and+ the install, so the boot gate (`restore-info.json`) passes as for any VM.+ `cfw update-environment` and `cfw update-kernel` refuse.+- `vm create` builds without a template (the offline trim and setup boot write+ the system) and refuses `--template` and the slimming switches, as for an+ Apple TV.+- `fw patch` needs root for the merge (owner-preserving copies on a mounted+ image) and says so. Launchpad runs it through its helper's new+ `patchRestoreImage` verb, which runs `fw patch <vm> --restore-image-only`+ from the receipt-checked store bundle; that flag refuses any selection that+ does not merge the restore image.+- `fw prepare` stages `apfs_sealvolume_<iOS version>` into `<restore>/.tools`+ (the `fw seal-tool` fetch) and the GPU driver for+ `filesystem-boot-gpu_driver` as for `system-extensions-boot-gpu_bundle`.+ `vm create` and Launchpad now record the preset before `fw prepare`, which+ read `standard` before: the GPU staging followed the wrong selection for any+ other preset as well.diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherManifest.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherManifest.swiftindex 42cfb206..862c5659 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherManifest.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherManifest.swift@@ -97,10 +97,14 @@ extension CryptexFilesystemPatcher {return remaining.joined(separator: "/")}+ /// The iOS version of the system being merged, which picks the seal tool.+ /// The hybrid `BuildManifest.plist` carries the cloudOS version; the+ /// iPhone's own manifest, which `fw prepare` keeps beside it, the iOS one.func getProductVersion() throws -> String {- let root = try parsePlist(data: buildManiest)+ let data = try Data(contentsOf: restoreDir.appending(path: "iPhone-BuildManifest.plist"))+ let root = try parsePlist(data: data)guard let productVersion = root["ProductVersion"] as? String else {- throw FirmwareManifest.ManifestError.missingKey("ProductVersion in BuildManifest")+ throw FirmwareManifest.ManifestError.missingKey("ProductVersion in iPhone-BuildManifest")}return productVersion}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex ba10510a..a883c48c 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -165,6 +165,17 @@ struct VPhoneCustomFirmwareInstaller {// both ways. Read through the pinned descriptor so root never follows a// link out of the bundle.let rawPlan = readPatchPlan(in: bundleDirectory)+ if Self.restoredCustomisedSystem(rawPlan) {+ // The restore installed the finished system (the restore image+ // patches): there is nothing to add, and writing the System volume+ // would break the seal its stock boot chain checks.+ guard mode == .full else {+ throw Self.restoreImageRefusal(mode)+ }+ print("[cfw] The restore installed this VM's customised system; nothing to install.")+ recordGuestReceipt(live: [], notApplicable: [], in: bundleDirectory, owner: invokingUser.map { ($0.uid, $0.gid) })+ return+ }let plan = resolveGuestSelection(rawPlan, in: bundleDirectory)// What was live in the guest before this run, so a now-off patch this run// cannot revert (no backup, no undo record) stays honestly recorded.@@ -539,6 +550,9 @@ struct VPhoneCustomFirmwareInstaller {let callerUID = invokingUser?.uidlet bundleDirectory = try pinBundle(owner: callerUID)let bundlePath = try bundleDirectory.path+ if Self.restoredCustomisedSystem(readPatchPlan(in: bundleDirectory)) {+ throw Self.restoreImageRefusal(mode)+ }let disk = try openDiskImage(in: bundleDirectory, path: bundlePath, owner: callerUID)let diskPath = (bundlePath as NSString).appendingPathComponent("Disk.img")@@ -795,6 +809,19 @@ struct VPhoneCustomFirmwareInstaller {}}+ /// Whether the VM's restore installed a system customised by `fw patch`+ /// (``FirmwareRestoreImagePatchSet``), which nothing may write afterwards.+ static func restoredCustomisedSystem(_ plan: VPhoneVirtualMachinePatchPlan?) -> Bool {+ plan?.enabledPatches.contains(FirmwareRestoreImagePatchSet.cryptexMerge) == true+ }++ static func restoreImageRefusal(_ mode: Mode) -> ValidationError {+ ValidationError(+ "This VM's system was customised before its restore (the \(VPhonePatchPreset.minimalIdentifier) preset), "+ + "and a \(mode.summary) would break its seal. Patch and restore the VM again instead.",+ )+ }+/// The verb to credit a receipt write to.private var receiptWriter: String {mode == .full ? "cfw install" : "cfw update-environment"diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swiftindex b34444b7..93c5ac7b 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift@@ -348,6 +348,11 @@ struct VPhoneFirmwarePatchCommand: ParsableCommand {)var preset: String?@Flag(name: .shortAndLong, help: "Suppress per-component progress") var quiet = false+ @Flag(help: ArgumentHelp(+ "Refuse unless the selection merges the restore image (the Launchpad helper's root run)",+ visibility: .hidden,+ ))+ var restoreImageOnly = falsefunc run() throws {let name = try VPhoneVirtualMachineSelection.resolveExisting(name, in: lib.library)@@ -369,6 +374,17 @@ struct VPhoneFirmwarePatchCommand: ParsableCommand {)}+ // The restore image patches merge and reseal the system image, which+ // needs root; nothing else here does.+ let mergesRestoreImage = resolved.patchSets.contains { $0.identifier == FirmwareRestoreImagePatchSet.identifier }+ && !selection.blockedPatches.contains(FirmwareRestoreImagePatchSet.cryptexMerge)+ if restoreImageOnly, !mergesRestoreImage {+ throw ValidationError("\(name) is not set to a preset that customises its system before the restore.")+ }+ if mergesRestoreImage, geteuid() != 0 {+ throw ValidationError("The \(selection.presetIdentifier) preset rebuilds the system image, which needs root. Run this command with sudo.")+ }+let pipeline = FirmwarePipeline(vmDirectory: bundle.url,variant: .jb,diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareDownloadCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareDownloadCommand.swiftindex eafcd2fe..a8afa748 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareDownloadCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareDownloadCommand.swift@@ -73,6 +73,13 @@ struct VPhoneFirmwareSealToolCommand: ParsableCommand {var output: URLfunc run() throws {+ try Self.stage(version: version, into: output)+ }++ /// Write `apfs_sealvolume_<version>` into `output` unless it is already+ /// there. `fw prepare` stages it into the restore tree for the restore+ /// image patches, which seal the merged system with it.+ static func stage(version: String, into output: URL) throws {let destination = output.appendingPathComponent("apfs_sealvolume_\(version)")if FileManager.default.fileExists(atPath: destination.path) {print("apfs_sealvolume_\(version) already present")diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swiftindex 2ca6f71d..5d467436 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift@@ -163,9 +163,12 @@ enum VPhoneFirmwarePreparer {try PropertyListSerialization.data(fromPropertyList: version, format: .xml, options: 0).write(to: phoneTree.appendingPathComponent(FirmwarePipeline.otaVersionFileName))}- // A plain-arm64 Apple TV cannot load the arm64e paravirtual GPU driver,- // and a creation may record its patch selection only after preparing.- if !device.hasPlainArm64Userland, plan.isEnabled("system-extensions-boot-gpu_bundle") {+ // A plain-arm64 Apple TV cannot load the arm64e paravirtual GPU driver.+ // `cfw install` installs the driver after the restore, the restore image+ // (the `minimal` preset) before it; both take it from here.+ if !device.hasPlainArm64Userland,+ plan.isEnabled("system-extensions-boot-gpu_bundle") || plan.isEnabled(FirmwareRestoreImagePatchSet.gpuDriver)+ {let cachedDriver = cachedGPUDriver(for: cloud)if let gpuDriverBundle {print("[*] Staging GPU driver from local bundle...")@@ -209,6 +212,16 @@ enum VPhoneFirmwarePreparer {print("[*] GPU bundle is off for this guest; skipping driver recovery and compiler plugin staging")}+ // The restore image patches reseal the merged system with the macOS+ // tool of the same version, which `fw patch` finds in the tree.+ if plan.isEnabled(FirmwareRestoreImagePatchSet.cryptexMerge) {+ print("[*] Staging apfs_sealvolume for \(phone.version)...")+ try VPhoneFirmwareSealToolCommand.stage(+ version: phone.version,+ into: phoneTree.appendingPathComponent(".tools"),+ )+ }+// The destination did not exist at entry and the staging directory is// on the same volume. One rename exposes the complete restore tree.guard !fm.fileExists(atPath: destination.path) else { throw Error.existingRestore(destination) }diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swiftindex e38749d8..a31f2d7a 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift@@ -1,4 +1,5 @@import ArgumentParser+import FirmwarePatcherimport Foundationimport VPhoneCoreKitimport VPhonePatchKit@@ -90,6 +91,14 @@ struct VPhoneVirtualMachineCreateCommand: ParsableCommand {VPhoneGuestDevice.named(device)?.family == .appleTV}+ /// A preset that customises the system before the restore (`minimal`): the+ /// offline trim and the setup boot of a template write the System volume,+ /// which would break that system's seal.+ private var customisesRestoredSystem: Bool {+ VPhonePatchPresetStore.preset(named: preset ?? defaultPreset)?.patchSets+ .contains { $0.identifier == FirmwareRestoreImagePatchSet.identifier } ?? false+ }+/// An Apple TV takes the TV preset; one whose userland comes from an OTA/// takes the arm64e one, with the GPU driver and the userland swap.private var defaultPreset: String {@@ -118,6 +127,14 @@ struct VPhoneVirtualMachineCreateCommand: ParsableCommand {throw ValidationError("An Apple TV guest is built without a template; the slimming switches do not apply.")}}+ if customisesRestoredSystem {+ if template != nil {+ throw ValidationError("The \(preset ?? defaultPreset) preset builds a VM without a template; --template cannot be used.")+ }+ if try !slimming.request.isEmpty {+ throw ValidationError("The \(preset ?? defaultPreset) preset builds a VM without a template; the slimming switches do not apply.")+ }+ }_ = try slimming.resolve()if template != nil {let firmware = [@@ -142,7 +159,7 @@ struct VPhoneVirtualMachineCreateCommand: ParsableCommand {let unlocks = try unlockAtStartup.map { try VPhoneVirtualMachineConfigCommand.parseSwitch($0, option: "--unlock-at-startup") }let templateUse: VPhoneVirtualMachineCreator.TemplateUse = if let template {.identifier(template)- } else if noTemplate || isAppleTV {+ } else if noTemplate || isAppleTV || customisesRestoredSystem {.none} else {.automaticdiff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swiftindex f16e1d2f..05c85a89 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift@@ -188,6 +188,12 @@ public struct VPhoneVirtualMachineCreator {outputs: VPhoneCreatedOutputs,) throws {let v = options.verbosity+ // `fw prepare` stages what the selection needs (the GPU driver, the seal+ // tool), so the preset has to be on record before it runs.+ try VPhonePatchPresetStore.write(+ VPhoneVirtualMachinePatchSelection(presetIdentifier: options.patchPreset),+ forVM: bundleURL,+ )print("\n=== fw prepare ===")try runFWPrepare(options: options, bundleURL: bundleURL)diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLaunchCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLaunchCommand.swiftindex 5439bee9..4c43aabb 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLaunchCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLaunchCommand.swift@@ -57,7 +57,15 @@ struct VPhoneVirtualMachineLaunchCommand: ParsableCommand {throw ExitCode(1)}if !dfu {- _ = try layout.stageVphoned(into: bundle)+ // A system the restore installed customised (`minimal`) is sealed and+ // boots on a stock AMFI: a vphoned the host pushed would never run,+ // and the host would push it again on every probe. Without the+ // staged copy, vphone-vm pushes none.+ if VPhoneCustomFirmwareInstaller.restoredCustomisedSystem(VPhonePatchPresetStore.plan(forVM: bundle.url)) {+ try? FileManager.default.removeItem(at: bundle.url.appendingPathComponent(".vphoned.signed"))+ } else {+ _ = try layout.stageVphoned(into: bundle)+ }}let boot = VPhoneBootCommand(diff --git a/VPhoneLaunchpad/Configuration/Version.xcconfig b/VPhoneLaunchpad/Configuration/Version.xcconfigindex 523423f0..05d75559 100644--- a/VPhoneLaunchpad/Configuration/Version.xcconfig+++ b/VPhoneLaunchpad/Configuration/Version.xcconfig@@ -1,4 +1,4 @@MARKETING_VERSION = 2.10.1// Bump whenever the helper changes. The app blesses the helper again when the// installed helper's version or bytes differ from the copy it embeds.-CURRENT_PROJECT_VERSION = 17+CURRENT_PROJECT_VERSION = 18diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swiftindex 7df20d1e..5e83326c 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift@@ -596,11 +596,16 @@ struct VPhoneLaunchpadControlCommands {defaultPreset: VPhoneLaunchpadPatchSelection.defaultPreset(forDevice: device),emit: emit,)- let usesTemplate = !request.flag("no-template") && !isAppleTV+ // The Minimal preset seals the system it restores, which a template's+ // trim and setup boot would write.+ let restoredSystem = patches.customisesRestoredSystem+ let usesTemplate = !request.flag("no-template") && !isAppleTV && !restoredSystemlet slimming: VPhoneLaunchpadSlimming- if isAppleTV {+ if isAppleTV || restoredSystem {if !Self.slimmingSwitches(request).isEmpty {- throw VPhoneLaunchpadError("An Apple TV is created without a template; the slimming switches do not apply.")+ throw VPhoneLaunchpadError(isAppleTV+ ? "An Apple TV is created without a template; the slimming switches do not apply."+ : "The \(patches.preset) preset creates a machine without a template; the slimming switches do not apply.")}var off = VPhoneLaunchpadSlimming()off.slim = falsediff --git a/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swiftindex cc7badf8..627e08c9 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift@@ -266,6 +266,25 @@ final class VPhoneLaunchpadHelperClient {}}+ /// Runs `fw patch` as root for a machine on the Minimal preset, which+ /// merges and reseals its system image. Output lines go to `onLine`.+ func patchRestoreImage(+ bundleVersion: String,+ machineName: String,+ libraryRoot: String,+ onLine: @escaping @Sendable (String) -> Void,+ ) async throws -> Int32 {+ try await runFirmware(machineName: machineName, libraryRoot: libraryRoot, onLine: onLine) { proxy, authorization, reply in+ proxy.patchRestoreImage(+ authorization: authorization,+ bundleVersion: bundleVersion,+ machineName: machineName,+ libraryRoot: libraryRoot,+ reply: reply,+ )+ }+ }+/// Runs `cfw update-environment` as root: redeploys the given bundle's/// guest resources into a stopped machine. Output lines go to `onLine`.func updateGuestEnvironment(diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swiftindex 0e8b06cd..e695abb3 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift@@ -7,7 +7,8 @@ import Observation/// `vphone-cli vm create` runs the same stages in one process and asks for/// sudo partway through, which a GUI cannot answer. Running the stages here/// keeps every step visible and retryable, and keeps root to the one step-/// that needs it: `cfw install`, run by the helper. The waits mirror+/// that needs it: `cfw install`, run by the helper (or, for the Minimal preset,+/// which customises the system before the restore, `fw patch`). The waits mirror/// VPhoneVirtualMachineCreator: the device identity file, 90 recovery probes,/// up to 30 seconds for the post-restore panic, 5 seconds before CFW, and up/// to 300 seconds for vphoned to answer on first boot.@@ -403,6 +404,11 @@ final class VPhoneLaunchpadCreationPipeline {// step has moved on, so only the firmware step takes it. A finished// download clears it: extraction follows with no progress of its own.defer { downloadFraction = nil }+ // `fw prepare` stages what the selection needs (the GPU driver, the+ // seal tool), so the preset is on record before it runs.+ if !options.patches.presetArguments.isEmpty {+ try await run(["fw", "set-patches", name] + options.patches.presetArguments + library)+ }try await run(["fw", "prepare", name, "--iphone-source", options.iphoneSource,"--cloudos-source", options.cloudOSSource] + deviceArguments + library,onProgress: { [weak self] fraction in@@ -434,7 +440,22 @@ final class VPhoneLaunchpadCreationPipeline {onLine: tee,)}- try await run(patchArguments(name) + library, onLine: tee)+ guard options.patches.customisesRestoredSystem else {+ try await run(patchArguments(name) + library, onLine: tee)+ return+ }+ // The Minimal preset merges and reseals the system image, which+ // needs root: the helper runs `fw patch` with the selection+ // recorded before `fw prepare` and above, as it runs `cfw install`.+ let status = try await helper.patchRestoreImage(+ bundleVersion: version,+ machineName: name,+ libraryRoot: Self.canonicalPath(URL(fileURLWithPath: options.libraryRoot, isDirectory: true)),+ onLine: tee,+ )+ guard status == 0 else {+ throw VPhoneLaunchpadError(String(localized: "Unable to patch the firmware. Check the log for details."), detail: log.tail)+ }case .bootDFU:let arguments = ["vm", "launch", name, "--dfu"] + librarydiff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swiftindex 536fb50e..27e8127e 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift@@ -198,10 +198,21 @@ struct VPhoneLaunchpadNewMachineView: View {// Off when there is no template to clone; it can still be turned on// to build one..onChange(of: templateAvailable, initial: true) {- if let templateAvailable, !isAppleTVGuest {+ if let templateAvailable, !isAppleTVGuest, !patches.customisesRestoredSystem {usesTemplate = templateAvailable}}+ // The Minimal preset is restored on its own and not slimmed.+ .onChange(of: patches.customisesRestoredSystem) { _, restored in+ guard !isAppleTVGuest else { return }+ if restored {+ usesTemplate = false+ slimming.slim = false+ } else {+ usesTemplate = templateAvailable ?? true+ slimming = VPhoneLaunchpadSlimming()+ }+ }.onAppear {if let version = bundleVersion, let known = Self.catalogs[version] {apply(known)@@ -240,9 +251,9 @@ struct VPhoneLaunchpadNewMachineView: View {hardwarePageadvancedSections(.hardware)case .template:- VPhoneLaunchpadSlimmingSections(part: .template, usesTemplate: $usesTemplate, templateAvailable: templateAvailable, slimming: $slimming, forAppleTV: isAppleTVGuest)+ VPhoneLaunchpadSlimmingSections(part: .template, usesTemplate: $usesTemplate, templateAvailable: templateAvailable, slimming: $slimming, forAppleTV: isAppleTVGuest, forRestoredSystem: patches.customisesRestoredSystem)case .slimming:- VPhoneLaunchpadSlimmingSections(part: .slimming, usesTemplate: $usesTemplate, templateAvailable: templateAvailable, slimming: $slimming, forAppleTV: isAppleTVGuest)+ VPhoneLaunchpadSlimmingSections(part: .slimming, usesTemplate: $usesTemplate, templateAvailable: templateAvailable, slimming: $slimming, forAppleTV: isAppleTVGuest, forRestoredSystem: patches.customisesRestoredSystem)case .firmware:bundleSectionfirmwareSourceSectiondiff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swiftindex 0f8e270f..34b38c16 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swift@@ -283,6 +283,10 @@ nonisolated struct VPhoneLaunchpadPatchSelection: Hashable, Sendable {/// `VPhonePatchPreset.tvOS4KIdentifier`: its arm64e userland comes from/// the OTA, with the paravirtual GPU driver.static let tvOS4KPreset = "tvos-4k"+ /// The preset that customises the system before the restore and patches+ /// no boot chain: `fw patch` runs as root, and nothing writes the system+ /// afterwards, so there is no template and no slimming.+ static let minimalPreset = "minimal"/// The preset a new machine of `productType` starts from.static func defaultPreset(forDevice productType: String?) -> String {@@ -316,6 +320,10 @@ nonisolated struct VPhoneLaunchpadPatchSelection: Hashable, Sendable {}/// The `--preset` flag `fw patch` and `fw patches` carry, if any.+ var customisesRestoredSystem: Bool {+ preset == Self.minimalPreset+ }+var presetArguments: [String] {preset == Self.defaultPreset ? [] : ["--preset", preset]}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadSlimmingView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadSlimmingView.swiftindex 94eda07c..04cd6b3e 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadSlimmingView.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadSlimmingView.swift@@ -18,6 +18,9 @@ struct VPhoneLaunchpadSlimmingSections: View {/// An Apple TV is restored on its own and not slimmed: templates and/// slimming drive iOS Setup Assistant and its apps.var forAppleTV = false+ /// The `minimal` preset seals the system it restores, which the trim and+ /// setup boot of a template would write.+ var forRestoredSystem = false@State private var choosesApps = falsevar body: some View {@@ -27,11 +30,14 @@ struct VPhoneLaunchpadSlimmingSections: View {case .slimming:Section {Toggle("Slim System", isOn: $slimming.slim)- .disabled(forAppleTV)+ .disabled(forAppleTV || forRestoredSystem)} footer: {if forAppleTV {Text("An Apple TV keeps every file, service and app.").foregroundStyle(.secondary)+ } else if forRestoredSystem {+ Text("The Minimal preset keeps the restored system exactly as sealed.")+ .foregroundStyle(.secondary)} else if !usesTemplate, slimming.slim {Text("Without a template the machine is slimmed on its own, with a setup boot of its own. Setup Assistant is skipped.").foregroundStyle(.secondary)@@ -45,13 +51,15 @@ struct VPhoneLaunchpadSlimmingSections: View {private var templateSection: some View {Section {Toggle("Use Template", isOn: $usesTemplate)- .disabled(forAppleTV)+ .disabled(forAppleTV || forRestoredSystem)} header: {Text("Template")} footer: {VStack(alignment: .leading, spacing: 4) {if forAppleTV {Text("An Apple TV is restored on its own, with keys of its own. Templates are made for iPhone and iPad.")+ } else if forRestoredSystem {+ Text("The Minimal preset restores the machine on its own, with keys of its own: building a template writes the system it seals.")} else {if templateAvailable == false {Text("No template is available for this firmware. Turning this on saves a sample of the machine in the template library.")diff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swiftindex 69d5b098..1e052271 100644--- a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swift@@ -1,8 +1,8 @@import Darwinimport Foundation-/// A validated `vphone-cli cfw install` or `cfw update-environment`-/// invocation. Built only from a store bundle whose cdhash still matches its+/// A validated `vphone-cli cfw install`, `cfw update-environment`, `cfw+/// update-kernel` or `fw patch` invocation. Built only from a store bundle whose cdhash still matches its/// receipt, and only for a VM directory the calling user owns.struct VPhoneLaunchpadHelperFirmwareRequest {enum Operation {@@ -13,6 +13,10 @@ struct VPhoneLaunchpadHelperFirmwareRequest {case updateEnvironment/// Swaps the Preboot kernelcache for the re-patched one, keeping data.case updateKernel+ /// `fw patch` with the machine's recorded selection, for a preset that+ /// merges and reseals the system image before the restore. `fw patch`+ /// refuses to run as root for any other selection.+ case patchRestoreImage}typealias MachineKey = VPhoneLaunchpadHelperFirmwareAdmission.MachineKey@@ -83,6 +87,8 @@ struct VPhoneLaunchpadHelperFirmwareRequest {case .updateKernel:arguments = ["cfw", "update-kernel", machineName, "--library-root", libraryRoot,"--work-parent", workParent]+ case .patchRestoreImage:+ arguments = ["fw", "patch", machineName, "--library-root", libraryRoot, "--restore-image-only"]}self.executable = executablediff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swiftindex 5632e0d9..b3d0ef9c 100644--- a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swift@@ -98,6 +98,23 @@ final class VPhoneLaunchpadHelperService: NSObject, VPhoneLaunchpadHelperProtoco)}+ func patchRestoreImage(+ authorization: Data,+ bundleVersion: String,+ machineName: String,+ libraryRoot: String,+ reply: @escaping @Sendable (Int32, String?) -> Void,+ ) {+ runFirmware(+ .patchRestoreImage,+ authorization: authorization,+ bundleVersion: bundleVersion,+ machineName: machineName,+ libraryRoot: libraryRoot,+ reply: reply,+ )+ }+func updateGuestEnvironment(authorization: Data,bundleVersion: String,@@ -132,7 +149,7 @@ final class VPhoneLaunchpadHelperService: NSObject, VPhoneLaunchpadHelperProtoco)}- /// All three operations share one slot per machine, so an install and+ /// All four operations share one slot per machine, so an install and/// an update never write the same machine at once, and one cancel for/// that machine stops whichever is running.private func runFirmware(diff --git a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swift b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swiftindex 84dd9f50..96aae7b6 100644--- a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swift@@ -64,6 +64,18 @@ nonisolated protocol VPhoneLaunchpadHelperProtocol {reply: @escaping @Sendable (Int32, String?) -> Void,)+ /// Runs `vphone-cli fw patch` from a store bundle as root, for a machine+ /// whose recorded preset customises the system before the restore (`minimal`):+ /// merging and resealing the system image needs root. Same output channel+ /// and reply as `installCustomFirmware`, and `cancelCustomFirmware` stops it.+ func patchRestoreImage(+ authorization: Data,+ bundleVersion: String,+ machineName: String,+ libraryRoot: String,+ reply: @escaping @Sendable (Int32, String?) -> Void,+ )+/// Runs `vphone-cli cfw update-environment` from a store bundle as root:/// redeploys the bundle's guest resources into a stopped machine and/// nothing else. Same output channel and reply as `installCustomFirmware`,