Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Keep template builds on the key Find computed; guest overrides go to the clone

Jacky1029b237e1a5
diff --git a/Documents/Guides/create-and-run.md b/Documents/Guides/create-and-run.md
index 69c484e8..1cca1635 100644
--- a/Documents/Guides/create-and-run.md
+++ b/Documents/Guides/create-and-run.md
@@ -130,7 +130,9 @@ It works out the key as `vm create` does. The builds come from the IPSWs when th
Launchpad 2.9 creates machines from templates by default. New Machine has a Slim System switch on its General page and the parts on its Template page: the trim tier and kept languages, the service profile, Apple Account, and which system apps go. Turning off Create from a template restores the machine on its own, as `--no-template` does, with keys of its own and without slimming.
-The creation runs `vm template find` first. When a current template matches, it clones the machine (`vm create --template <id> --skip-first-boot`) and boots it. When none does, it builds the template in a temporary machine of the same library, named `template-` and eight hex digits, with its usual steps (restore, then `cfw install` through the helper), then `vm template trim`, the headless `vm template setup` and `vm template adopt --iphone-source … --cloudos-source …`, and clones the machine from the result. Each is a step of its own with its duration, and a failed one shows the reason `vphone-cli` gave. Once it has built a template, the creation offers to delete the two IPSWs it came from; nothing is deleted without confirming.
+The creation runs `vm template find` first. When a current template matches, it clones the machine (`vm create --template <id> --skip-first-boot`) and boots it. When none does, it builds the template in a temporary machine of the same library, named `template-` and eight hex digits, with its usual steps (restore, then `cfw install` through the helper), then `vm template trim`, the headless `vm template setup --strict` and `vm template adopt --iphone-source … --cloudos-source … --expect <id>`, and clones the machine from the result. The setup boot fails when an app it should remove stays, and the adopt fails when the build's key comes out other than the one `find` computed, so a build is never saved under an id later creations would not find. Each is a step of its own with its duration, and a failed one shows the reason `vphone-cli` gave.
+
+Per-patch overrides from New Machine's Patch Settings are split the way the template key splits them. Boot-chain overrides are part of the key: the template is built with them, and `find` looks for one with them. Guest patch overrides are not: the template is built without them, and after the clone the creation records them on the new machine with `fw set-patches` and writes them with `cfw update-environment` through the helper (the Apply guest patches step) before its first boot. A template therefore never hands one creation's guest patch choice to another. Once it has built a template, the creation offers to delete the two IPSWs it came from; nothing is deleted without confirming.
File > Templates… lists every library's templates with their machines, slimming, size and state, and deletes them. Guest System… (in a machine's Actions menu and inspector) switches a running machine's service profile and restores system apps the template removed. The inspector and the machine list show each machine's exclusive disk use beside what its files allocate: the blocks no other machine or template holds, which deleting it frees (a local Time Machine snapshot taken before keeps them until it expires).
diff --git a/Research/Host/machine_templates.md b/Research/Host/machine_templates.md
index b2223795..1deff556 100644
--- a/Research/Host/machine_templates.md
+++ b/Research/Host/machine_templates.md
@@ -57,8 +57,11 @@ either direction. The preset itself is a field because `standard` and
Not in the key: CPU, memory, screen, network, unlock at startup. They are
`config.plist` settings that `vm create` sets on the clone.
-A machine Launchpad created with per-patch overrides has a digest of its own,
-so it never serves a create without them. A template's staleness check
+A machine Launchpad created with boot-chain overrides has a digest of its
+own, so it never serves a create without them. Launchpad builds a template
+with the boot-chain overrides only and applies guest overrides to the clone
+(see Lifecycle), so no template carries a guest override in its
+`PatchSelection.plist`. A template's staleness check
re-resolves with the template's own `PatchSelection.plist`.
## Storage
@@ -431,19 +434,28 @@ made after the latest one, as these clones were.
the lock and freezes the build on success.
- **Launchpad** (2.9, `VPhoneLaunchpadCreationPipeline`, steps in
`VPhoneLaunchpadCreationPlan`) first runs `vm template find --json` with
- the request (IPSW sources, device, preset and per-patch overrides, disk
+ the request (IPSW sources, device, preset and boot-chain overrides, disk
size, slimming switches). A usable template is cloned at once. Otherwise it
builds one in a temporary library machine `template-<8 hex>`: `vm new`,
- `fw prepare`, `fw patch`, the DFU restore and `cfw install` through the
- helper, without its own first boot; then `vm template trim <name> --tier …`
- (left out for trim none), `vm template setup <name> [switches]` (headless),
- `vm template adopt <name> --json --iphone-source … --cloudos-source …`, then
+ `fw prepare`, `fw set-patches` with the boot-chain overrides only,
+ `fw patch`, the DFU restore and `cfw install` through the helper, without
+ its own first boot; then `vm template trim <name> --tier …` (left out for
+ trim none), `vm template setup <name> --strict [switches]` (headless; fails
+ when an app it should remove stays), `vm template adopt <name> --json
+ --iphone-source … --cloudos-source … --expect <id>` (the id `find`
+ computed, or a second `find` once the restore downloaded the IPSWs; a
+ build whose key differs fails the step with the differing fields), then
`vm create <name> --template <id> --skip-first-boot --cpu … --memory …
- --network …` and its own first boot. An adopt refused because another
+ --network …`. When the request has guest patch overrides (the bundle's
+ `fw patches` catalog places the patch outside the boot chain), the clone
+ then gets `fw set-patches <name>` with every override and `cfw
+ update-environment <name>` through the helper's existing verb, before its
+ own first boot. An adopt refused because another
create saved the same key meanwhile falls back to that template and deletes
the build. The helper's root surface is unchanged: `cfw install` runs on
- the temporary machine, a visible library machine, before it is adopted;
- trim, setup and adopt run as the user. The setup boot's `vphone-vm` is
+ the temporary machine, a visible library machine, before it is adopted,
+ and the guest overrides go through its existing `cfw update-environment`
+ on the clone; trim, setup and adopt run as the user. The setup boot's `vphone-vm` is
spawned by `vphone-cli`, itself a pipe child of Launchpad like the
pipeline's DFU boot, not through `vphone-launchpad-launcher`, so Launchpad
is its responsible process while it runs: a privacy prompt would be
diff --git a/VPhoneLaunchpad/Tests/TemplatesTests.swift b/VPhoneLaunchpad/Tests/TemplatesTests.swift
index fcf528fe..2580271b 100644
--- a/VPhoneLaunchpad/Tests/TemplatesTests.swift
+++ b/VPhoneLaunchpad/Tests/TemplatesTests.swift
@@ -6,6 +6,7 @@ struct TemplatesTests {
static func main() async throws {
slimmingArguments()
commandArguments()
+ patchOverrides()
creationPlan()
try templateList()
try templateFind()
@@ -105,10 +106,17 @@ struct TemplatesTests {
var untrimmed = slimming
untrimmed.trim = .none
precondition(VPhoneLaunchpadTemplateCommands.trim("t", untrimmed) == nil, "No trim command for tier none")
+ // Strict: an app the setup boot cannot remove fails the step.
precondition(VPhoneLaunchpadTemplateCommands.setup("template-1a2b3c4d", slimming)
- == ["vm", "template", "setup", "template-1a2b3c4d", "--service-profile", "none"], "setup")
- precondition(VPhoneLaunchpadTemplateCommands.adopt("template-1a2b3c4d", iphoneSource: "i", cloudOSSource: "c")
- == ["vm", "template", "adopt", "template-1a2b3c4d", "--json", "--iphone-source", "i", "--cloudos-source", "c"], "adopt")
+ == ["vm", "template", "setup", "template-1a2b3c4d", "--strict", "--service-profile", "none"], "setup")
+ precondition(VPhoneLaunchpadTemplateCommands.setup("t", VPhoneLaunchpadSlimming()) == ["vm", "template", "setup", "t", "--strict"],
+ "setup with the defaults")
+ // The adopt expects the id Find Template computed.
+ precondition(VPhoneLaunchpadTemplateCommands.adopt("template-1a2b3c4d", iphoneSource: "i", cloudOSSource: "c", expect: "2847ec2a3e3e")
+ == ["vm", "template", "adopt", "template-1a2b3c4d", "--json", "--iphone-source", "i", "--cloudos-source", "c",
+ "--expect", "2847ec2a3e3e"], "adopt")
+ precondition(VPhoneLaunchpadTemplateCommands.adopt("t", iphoneSource: "i", cloudOSSource: "c", expect: nil)
+ == ["vm", "template", "adopt", "t", "--json", "--iphone-source", "i", "--cloudos-source", "c"], "adopt without an id")
precondition(VPhoneLaunchpadTemplateCommands.clone("lab-01", template: "52b1fcc75e0c", cpuCount: 6, memoryMB: 6144, network: "tunnel")
== ["vm", "create", "lab-01", "--template", "52b1fcc75e0c", "--skip-first-boot",
"--cpu", "6", "--memory", "6144", "--network", "tunnel"], "clone")
@@ -121,6 +129,49 @@ struct TemplatesTests {
print("Command argument tests passed")
}
+ // MARK: - Patch overrides
+
+ static func patchOverrides() {
+ let overrides = VPhoneLaunchpadPatchOverrides(
+ preset: "standard",
+ blocked: ["ibss-cfw-serial_label", "system-debugserver-cfw-install"],
+ allowed: ["dyld-cfw-camera", "external-x"],
+ guestPatches: ["system-debugserver-cfw-install", "dyld-cfw-camera"],
+ )
+ precondition(overrides.bootChainBlocked == ["ibss-cfw-serial_label"], "Boot-chain blocks: \(overrides.bootChainBlocked)")
+ // One the catalog does not know counts as boot chain, as the key counts it.
+ precondition(overrides.bootChainAllowed == ["external-x"], "Boot-chain allows: \(overrides.bootChainAllowed)")
+ precondition(overrides.hasBootChainOverrides && overrides.hasGuestOverrides, "Both kinds")
+
+ // The template build records the boot chain's; the clone gets all.
+ precondition(VPhoneLaunchpadTemplateCommands.setPatches("template-1a2b3c4d", overrides, includingGuest: false)
+ == ["fw", "set-patches", "template-1a2b3c4d", "--preset", "standard",
+ "--block", "ibss-cfw-serial_label", "--allow", "external-x"], "Build overrides")
+ precondition(VPhoneLaunchpadTemplateCommands.setPatches("lab-01", overrides, includingGuest: true)
+ == ["fw", "set-patches", "lab-01", "--preset", "standard",
+ "--block", "ibss-cfw-serial_label", "--block", "system-debugserver-cfw-install",
+ "--allow", "dyld-cfw-camera", "--allow", "external-x"], "Clone overrides")
+
+ // Find keys on what the template is built with.
+ var request = VPhoneLaunchpadTemplateCommands.Request(
+ iphoneSource: "i", cloudOSSource: "c", preset: overrides.preset,
+ blocked: overrides.bootChainBlocked, allowed: overrides.bootChainAllowed,
+ diskSizeGB: 64, slimming: VPhoneLaunchpadSlimming(),
+ )
+ let find = VPhoneLaunchpadTemplateCommands.find(request)
+ precondition(!find.contains("system-debugserver-cfw-install") && !find.contains("dyld-cfw-camera"), "Find leaves guest overrides out: \(find)")
+ precondition(find.contains("ibss-cfw-serial_label") && find.contains("external-x"), "Find keeps boot-chain overrides")
+
+ let guestOnly = VPhoneLaunchpadPatchOverrides(preset: "standard", blocked: ["dyld-cfw-camera"], guestPatches: ["dyld-cfw-camera"])
+ precondition(!guestOnly.hasBootChainOverrides && guestOnly.hasGuestOverrides, "Guest only")
+ request.blocked = guestOnly.bootChainBlocked
+ request.allowed = guestOnly.bootChainAllowed
+ precondition(!VPhoneLaunchpadTemplateCommands.find(request).contains("--block"), "Guest-only overrides find the plain template")
+ let none = VPhoneLaunchpadPatchOverrides(preset: "experimental", guestPatches: ["dyld-cfw-camera"])
+ precondition(!none.hasGuestOverrides && !none.hasBootChainOverrides, "A guest patch not overridden is no override")
+ print("Patch override tests passed")
+ }
+
// MARK: - Plan
static func creationPlan() {
@@ -146,6 +197,7 @@ struct TemplatesTests {
"The clone and its boot are the new machine")
precondition(plan.machineName(for: .findTemplate) == "lab-01", "Find names the new machine")
precondition(plan.steps.allSatisfy { $0.needsRoot == ($0 == .installCFW) }, "Only CFW needs root")
+ precondition(plan.buildingName == build, "A build is under way")
plan.slimming.slim = false
precondition(!plan.steps.contains(.trimTemplate), "Slim off: no trim step")
@@ -155,9 +207,29 @@ struct TemplatesTests {
precondition(plan.steps == [.findTemplate, .cloneTemplate, .firstBoot], "A template found: \(plan.steps)")
precondition(plan.step(after: .findTemplate) == .cloneTemplate, "Straight to the clone")
precondition(plan.step(after: .firstBoot) == nil, "First boot is last")
+ // A found template builds nothing: the create report names no build machine.
+ precondition(plan.buildingName == nil, "No build when a template is found")
+ plan.foundTemplate = nil
+ precondition(plan.buildingName == nil, "No build before Find answers")
+ precondition(alone.buildingName == nil, "No build without a template")
+
+ // Guest patch overrides: a step of the new machine's, after the clone.
+ var guest = VPhoneLaunchpadCreationPlan(name: "lab-01", buildName: build, slimming: VPhoneLaunchpadSlimming(), appliesGuestPatches: true)
+ guest.foundTemplate = true
+ precondition(guest.steps == [.findTemplate, .cloneTemplate, .applyGuestPatches, .firstBoot], "Found, with guest patches: \(guest.steps)")
+ precondition(guest.machineName(for: .applyGuestPatches) == "lab-01" && !guest.buildsTemplate(.applyGuestPatches),
+ "Guest patches go to the clone")
+ precondition(Step.applyGuestPatches.needsRoot, "cfw update-environment runs through the helper")
+ guest.foundTemplate = false
+ precondition(Array(guest.steps.suffix(4)) == [.adoptTemplate, .cloneTemplate, .applyGuestPatches, .firstBoot],
+ "Built, with guest patches: \(guest.steps)")
+ let withoutTemplate = VPhoneLaunchpadCreationPlan(name: "lab-01", buildName: nil, slimming: VPhoneLaunchpadSlimming(), appliesGuestPatches: true)
+ precondition(!withoutTemplate.steps.contains(.applyGuestPatches), "cfw install applies them without a template")
print("Creation plan tests passed")
}
+ typealias Step = VPhoneLaunchpadCreationStep
+
// MARK: - JSON
/// `vm template list --json` as 2.9.0 prints it: pretty, keys sorted,
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
index 01da018f..9b977694 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
@@ -20,6 +20,8 @@
/// The pages New Machine and machine settings open on.
static var newMachinePage = VPhoneLaunchpadNewMachineView.Page.general
static var machineSettingsPage = VPhoneLaunchpadMachineSettingsView.Page.general
+ /// The patch choice New Machine opens with.
+ static var newMachinePatches = VPhoneLaunchpadPatchSelection()
// MARK: - Driver
@@ -100,6 +102,11 @@
await sheet(.newMachine, "07-new-machine-hardware", suffix)
newMachinePage = .advanced
await sheet(.newMachine, "07-new-machine-advanced", suffix)
+ // One boot-chain and one guest patch off: the guest one is
+ // applied to the clone, not built into the template.
+ newMachinePatches = VPhoneLaunchpadPatchSelection(blocked: ["ibss-cfw-serial_label", "dyld-cfw-camera"])
+ await sheet(.newMachine, "07c-new-machine-guest-patches", suffix)
+ newMachinePatches = VPhoneLaunchpadPatchSelection()
newMachinePage = .template
await sheet(.newMachine, "07b-new-machine-template", suffix)
newMachinePage = .general
@@ -116,6 +123,8 @@
await sheet(.creation(path("ios27-rc")), "08f-creation-template-built", suffix)
creation.applyPreview(.clonedFromTemplate)
await sheet(.creation(path("ios27-rc")), "08g-creation-from-template", suffix)
+ creation.applyPreview(.applyingGuestPatches)
+ await sheet(.creation(path("ios27-rc")), "08h-creation-guest-patches", suffix)
creation.applyPreview(.restoring)
await standalone("08c-creation-log", suffix, size: NSSize(width: 960, height: 700)) {
VPhoneLaunchpadConsoleView(title: "ios27-rc Creation Log", url: creation.logFile)
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift
index ec93e5d1..fd2589a4 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift
@@ -677,7 +677,9 @@ struct VPhoneLaunchpadControlCommands {
"log": pipeline.logFile.path,
"template": pipeline.templateID ?? NSNull(),
"builtTemplate": pipeline.builtTemplate,
- "buildMachine": pipeline.buildMachine?.name ?? NSNull(),
+ // Only once Find Template has decided to build: a creation that
+ // clones a template it found never makes this machine.
+ "buildMachine": pipeline.plan.buildingName ?? NSNull(),
"steps": pipeline.steps.map { step -> [String: Any] in
var item: [String: Any] = ["step": "\(step)", "status": pipeline.status(step).rawValue]
if let duration = pipeline.durations[step] {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
index 09d2d17a..8be81500 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
@@ -613,6 +613,40 @@
}
}
},
+ "Apply guest patches" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Apply guest patches"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ゲストのパッチを適用"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "게스트 패치 적용"
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Áp dụng bản vá máy khách"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "应用客户机补丁"
+ }
+ }
+ }
+ },
"Building template: %@" : {
"localizations" : {
"en" : {
@@ -1497,6 +1531,40 @@
}
}
},
+ "Guest patch changes are applied to this machine after it is cloned. The template keeps the preset’s, so machines that do not change them share it." : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Guest patch changes are applied to this machine after it is cloned. The template keeps the preset’s, so machines that do not change them share it."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ゲストのパッチの変更は、複製後にこのマシンへ適用します。テンプレートはプリセットのままなので、変更しないマシンと共有されます。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "게스트 패치 변경은 복제한 뒤 이 머신에 적용합니다. 템플릿은 프리셋 그대로 유지되므로 변경하지 않는 머신과 공유됩니다."
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Các thay đổi bản vá máy khách được áp dụng cho máy này sau khi nhân bản. Mẫu giữ nguyên theo cấu hình sẵn, nên các máy không thay đổi chúng dùng chung mẫu này."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "客户机补丁的更改会在克隆后应用到此虚拟机。模板保持预设的补丁,因此不更改它们的虚拟机可以共用该模板。"
+ }
+ }
+ }
+ },
"Guest System" : {
"localizations" : {
"en" : {
@@ -3741,6 +3809,40 @@
}
}
},
+ "Unable to apply the guest patches. Check the log for details." : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Unable to apply the guest patches. Check the log for details."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ゲストのパッチを適用できません。詳細はログを確認してください。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "게스트 패치를 적용할 수 없습니다. 자세한 내용은 로그를 확인하십시오."
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Không thể áp dụng các bản vá máy khách. Hãy xem nhật ký để biết chi tiết."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "无法应用客户机补丁。请查看日志了解详情。"
+ }
+ }
+ }
+ },
"Unable to Change the Service Profile" : {
"localizations" : {
"en" : {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift
index 441793c1..19ed4679 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift
@@ -21,6 +21,11 @@ import Observation
/// run as the user. The setup boot's `vphone-vm` is started by `vphone-cli`,
/// a child of Launchpad like the DFU boot, not through the launcher, so it
/// is Launchpad's responsibility while it runs, headless.
+///
+/// The template is built with the boot-chain patch overrides only. Guest
+/// patch overrides are recorded on the clone with `fw set-patches` and
+/// written by `cfw update-environment`, through the helper like `cfw
+/// install`, before its first boot.
@MainActor
@Observable
final class VPhoneLaunchpadCreationPipeline {
@@ -44,6 +49,9 @@ final class VPhoneLaunchpadCreationPipeline {
var network: String
/// The preset and per-patch overrides the boot chain is built with.
var patches: VPhoneLaunchpadPatchSelection
+ /// The overrides of `patches` the guest half of an install writes,
+ /// as the bundle's catalog places them.
+ var guestPatches: Set<String> = []
var keepArtifacts: Bool
/// Clone the machine from a template (built first when missing).
/// Off restores the machine on its own, with SEP and Data volume keys
@@ -55,14 +63,24 @@ final class VPhoneLaunchpadCreationPipeline {
VPhoneLaunchpadMachinePath(libraryRoot: libraryRoot, name: name)
}
+ var patchOverrides: VPhoneLaunchpadPatchOverrides {
+ VPhoneLaunchpadPatchOverrides(
+ preset: patches.preset,
+ blocked: patches.blocked,
+ allowed: patches.allowed,
+ guestPatches: guestPatches,
+ )
+ }
+
+ /// The template key's options: the boot-chain overrides only.
var templateRequest: VPhoneLaunchpadTemplateCommands.Request {
VPhoneLaunchpadTemplateCommands.Request(
iphoneSource: iphoneSource,
cloudOSSource: cloudOSSource,
device: device,
preset: patches.preset,
- blocked: patches.blocked,
- allowed: patches.allowed,
+ blocked: patchOverrides.bootChainBlocked,
+ allowed: patchOverrides.bootChainAllowed,
diskSizeGB: diskSizeGB,
slimming: slimming,
)
@@ -84,6 +102,9 @@ final class VPhoneLaunchpadCreationPipeline {
/// The template the machine is cloned from, once found or adopted.
private(set) var template: VPhoneLaunchpadTemplate?
private(set) var templateID: String?
+ /// The id Find Template computed for these options, which the adopt
+ /// must save the build under.
+ private(set) var expectedTemplateID: String?
/// True when this creation built the template it cloned from, rather
/// than finding one.
private(set) var builtTemplate = false
@@ -111,6 +132,7 @@ final class VPhoneLaunchpadCreationPipeline {
name: options.name,
buildName: options.usesTemplate ? VPhoneLaunchpadCreationPlan.newBuildName() : nil,
slimming: options.slimming,
+ appliesGuestPatches: options.usesTemplate && options.patchOverrides.hasGuestOverrides,
)
self.bundles = bundles
self.helper = helper
@@ -181,9 +203,12 @@ final class VPhoneLaunchpadCreationPipeline {
case .trimTemplate: (VPhoneLaunchpadTemplateCommands.trim(name, options.slimming) ?? []).joined(separator: " ")
case .setUpTemplate: VPhoneLaunchpadTemplateCommands.setup(name, options.slimming).joined(separator: " ")
case .adoptTemplate: "vm template adopt \(name) --json --iphone-source … --cloudos-source …"
+ + (expectedTemplateID.map { " --expect \($0)" } ?? "")
case .cloneTemplate: VPhoneLaunchpadTemplateCommands.clone(
name, template: template, cpuCount: options.cpuCount, memoryMB: options.memoryMB, network: options.network,
).joined(separator: " ")
+ case .applyGuestPatches: VPhoneLaunchpadTemplateCommands.setPatches(name, options.patchOverrides, includingGuest: true)
+ .joined(separator: " ") + "; cfw update-environment \(name)"
case .firstBoot: "vm launch \(name)"
}
}
@@ -199,6 +224,7 @@ final class VPhoneLaunchpadCreationPipeline {
if first <= .findTemplate {
plan.foundTemplate = nil
templateID = nil
+ expectedTemplateID = nil
template = nil
builtTemplate = false
}
@@ -249,7 +275,7 @@ final class VPhoneLaunchpadCreationPipeline {
?? VPhoneLaunchpadError(String(localized: "\(step.title) failed."), detail: error.localizedDescription)
}
append("✕ \(failure?.message ?? step.title)")
- if let detail = failure?.detail, plan.buildsTemplate(step) || step == .findTemplate || step == .cloneTemplate {
+ if let detail = failure?.detail, plan.buildsTemplate(step) || step == .findTemplate || step == .cloneTemplate || step == .applyGuestPatches {
append(" \(detail.replacingOccurrences(of: "\n", with: "\n "))")
}
await library?.refresh()
@@ -398,8 +424,15 @@ final class VPhoneLaunchpadCreationPipeline {
log.write(line)
patchLog.write(line)
}
- if options.patches.hasOverrides {
- try await run(["fw", "set-patches", name] + options.patches.setPatchesArguments + library, onLine: tee)
+ // A template build takes the boot-chain overrides only: they are
+ // what its key holds. The guest ones go to the clone.
+ let overrides = options.patchOverrides
+ let includesGuest = !plan.usesTemplate
+ if includesGuest ? options.patches.hasOverrides : overrides.hasBootChainOverrides {
+ try await run(
+ VPhoneLaunchpadTemplateCommands.setPatches(name, overrides, includingGuest: includesGuest) + library,
+ onLine: tee,
+ )
}
try await run(patchArguments(name) + library, onLine: tee)
@@ -511,6 +544,21 @@ final class VPhoneLaunchpadCreationPipeline {
await self.library?.refresh()
self.library?.selection = [target]
+ case .applyGuestPatches:
+ try await stopIfRunning(target, commandLine: commandLine)
+ try await run(VPhoneLaunchpadTemplateCommands.setPatches(name, options.patchOverrides, includingGuest: true) + library)
+ output("$ vphone-cli cfw update-environment \(name)")
+ let status = try await helper.updateGuestEnvironment(
+ bundleVersion: version,
+ machineName: name,
+ libraryRoot: Self.canonicalPath(URL(fileURLWithPath: options.libraryRoot, isDirectory: true)),
+ onLine: output,
+ )
+ guard status == 0 else {
+ throw VPhoneLaunchpadError(String(localized: "Unable to apply the guest patches. Check the log for details."), detail: log.tail)
+ }
+ self.library?.recordGuestEnvironment(target, version)
+
case .firstBoot:
try await firstBoot()
}
@@ -532,6 +580,7 @@ final class VPhoneLaunchpadCreationPipeline {
guard let data = result.jsonData, let found = try? VPhoneLaunchpadTemplateFind.decode(data) else {
throw VPhoneLaunchpadError(String(localized: "Unable to read the template search."), detail: result.tail)
}
+ expectedTemplateID = found.id
if found.usable, let id = found.id {
templateID = id
template = found.template
@@ -557,7 +606,10 @@ final class VPhoneLaunchpadCreationPipeline {
append("● no template yet (\(found.reason ?? found.id ?? "")); building one in \(plan.buildName ?? "")")
}
- /// `vm template adopt`. When another creation saved the same template
+ /// `vm template adopt`, expecting the id Find Template computed: a build
+ /// that came out with another key (an app its setup boot could not
+ /// remove) fails here, saying why, instead of being saved under an id no
+ /// later creation finds. When another creation saved the same template
/// first, this build is not needed: it is deleted and that template used.
private func adoptTemplate(
_ target: VPhoneLaunchpadMachinePath,
@@ -566,9 +618,18 @@ final class VPhoneLaunchpadCreationPipeline {
) async throws {
let log = log
let output: @Sendable (String) -> Void = { line in log.write(line) }
+ // Find could not compute the key while the IPSWs were not downloaded
+ // and no template recorded them; the restore has downloaded them.
+ if expectedTemplateID == nil {
+ let again = try? await commandLine.run(
+ VPhoneLaunchpadTemplateCommands.find(options.templateRequest) + target.libraryArguments,
+ recordInHistory: false,
+ )
+ expectedTemplateID = again?.jsonData.flatMap { try? VPhoneLaunchpadTemplateFind.decode($0) }?.id
+ }
do {
let result = try await run(VPhoneLaunchpadTemplateCommands.adopt(
- target.name, iphoneSource: options.iphoneSource, cloudOSSource: options.cloudOSSource,
+ target.name, iphoneSource: options.iphoneSource, cloudOSSource: options.cloudOSSource, expect: expectedTemplateID,
) + target.libraryArguments, output)
guard let data = result.jsonData, let adopted = try? VPhoneLaunchpadTemplate.decoder().decode(VPhoneLaunchpadTemplate.self, from: data)
else {
@@ -764,6 +825,9 @@ final class VPhoneLaunchpadCreationPipeline {
case builtTemplate
/// Found a template and cloned from it.
case clonedFromTemplate
+ /// Cloned from a template, writing guest patch overrides into
+ /// the clone.
+ case applyingGuestPatches
/// The setup boot failed.
case setupFailed
}
@@ -777,8 +841,10 @@ final class VPhoneLaunchpadCreationPipeline {
current = nil
isRunning = false
templateID = nil
+ expectedTemplateID = nil
template = nil
builtTemplate = false
+ plan.appliesGuestPatches = false
func passed(_ steps: [(Step, TimeInterval)]) {
for (step, duration) in steps {
statuses[step] = .passed
@@ -829,6 +895,15 @@ final class VPhoneLaunchpadCreationPipeline {
template = VPhoneLaunchpadPreview.templates.first
current = .firstBoot
isRunning = true
+ case .applyingGuestPatches:
+ plan.foundTemplate = true
+ plan.appliesGuestPatches = true
+ passed([(.findTemplate, 0), (.cloneTemplate, 1)])
+ statuses[.applyGuestPatches] = .running
+ templateID = VPhoneLaunchpadPreview.templates.first?.id
+ template = VPhoneLaunchpadPreview.templates.first
+ current = .applyGuestPatches
+ isRunning = true
case .setupFailed:
plan.foundTemplate = false
passed([(.findTemplate, 0)] + restored + [(.trimTemplate, 3)])
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPlan.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPlan.swift
index 427e27dc..cb58fd08 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPlan.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPlan.swift
@@ -22,6 +22,9 @@ nonisolated enum VPhoneLaunchpadCreationStep: Int, CaseIterable, Identifiable, C
case adoptTemplate
/// `vm create --template`: the new machine, cloned in a second.
case cloneTemplate
+ /// `fw set-patches` and `cfw update-environment` on the clone: the guest
+ /// patch overrides, which a template does not carry.
+ case applyGuestPatches
case firstBoot
var id: Int {
@@ -47,12 +50,13 @@ nonisolated enum VPhoneLaunchpadCreationStep: Int, CaseIterable, Identifiable, C
case .setUpTemplate: String(localized: "Set up template")
case .adoptTemplate: String(localized: "Save template")
case .cloneTemplate: String(localized: "Create machine from template")
+ case .applyGuestPatches: String(localized: "Apply guest patches")
case .firstBoot: String(localized: "First boot")
}
}
var needsRoot: Bool {
- self == .installCFW
+ self == .installCFW || self == .applyGuestPatches
}
}
@@ -67,12 +71,20 @@ nonisolated enum VPhoneLaunchpadCreationStep: Int, CaseIterable, Identifiable, C
/// temporary machine name in the same library: restored, custom firmware
/// installed through the helper, trimmed, set up headless and adopted, which
/// moves it into `.templates`. Then the clone and its first boot follow.
+///
+/// A template is built with the boot-chain patch overrides only, the ones its
+/// key holds. Guest patch overrides go to the clone before its first boot, so
+/// a template never hands them to a creation that did not ask for them.
nonisolated struct VPhoneLaunchpadCreationPlan: Hashable, Sendable {
/// The machine New Machine was asked for.
var name: String
/// The temporary machine a template is built in; nil without a template.
var buildName: String?
var slimming: VPhoneLaunchpadSlimming
+ /// Whether the clone gets guest patch overrides of its own. Only a
+ /// template-backed creation has the step: without a template, `cfw
+ /// install` applies them to the machine itself.
+ var appliesGuestPatches = false
/// Nil until Find Template answers; then whether it found a template
/// this creation clones from as it is.
var foundTemplate: Bool?
@@ -81,6 +93,12 @@ nonisolated struct VPhoneLaunchpadCreationPlan: Hashable, Sendable {
buildName != nil
}
+ /// The temporary machine once Find Template has decided to build in it;
+ /// nil before that, when a template was found, and without a template.
+ var buildingName: String? {
+ foundTemplate == false ? buildName : nil
+ }
+
/// Every step this creation runs, in order. Until Find Template has
/// answered, a template-backed creation lists the build too.
var steps: [VPhoneLaunchpadCreationStep] {
@@ -88,14 +106,15 @@ nonisolated struct VPhoneLaunchpadCreationPlan: Hashable, Sendable {
guard usesTemplate else {
return restore + [.firstBoot]
}
+ let machine: [VPhoneLaunchpadCreationStep] = [.cloneTemplate] + (appliesGuestPatches ? [.applyGuestPatches] : []) + [.firstBoot]
if foundTemplate == true {
- return [.findTemplate, .cloneTemplate, .firstBoot]
+ return [.findTemplate] + machine
}
var steps: [VPhoneLaunchpadCreationStep] = [.findTemplate] + restore
if slimming.trimArguments != nil {
steps.append(.trimTemplate)
}
- return steps + [.setUpTemplate, .adoptTemplate, .cloneTemplate, .firstBoot]
+ return steps + [.setUpTemplate, .adoptTemplate] + machine
}
/// The step after `step`, or nil after the last.
@@ -109,7 +128,7 @@ nonisolated struct VPhoneLaunchpadCreationPlan: Hashable, Sendable {
return false
}
switch step {
- case .findTemplate, .cloneTemplate, .firstBoot: return false
+ case .findTemplate, .cloneTemplate, .applyGuestPatches, .firstBoot: return false
default: return true
}
}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineAdvancedView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineAdvancedView.swift
index d5350783..59685e7d 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineAdvancedView.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineAdvancedView.swift
@@ -95,6 +95,10 @@ struct VPhoneLaunchpadNewMachineAdvancedView: View {
Text("Differs from the preset: \(patches.blocked.count) off, \(patches.allowed.count) on.")
.foregroundStyle(.secondary)
}
+ if usesTemplate, let patchCatalog, !patchCatalog.guestOverrides(patches).isEmpty {
+ Text("Guest patch changes are applied to this machine after it is cloned. The template keeps the preset’s, so machines that do not change them share it.")
+ .foregroundStyle(.secondary)
+ }
if !essentialOff.isEmpty {
Label {
Text("^[\(essentialOff.count) boot-essential patch](inflect: true) off: \(essentialOff.map(\.identifier).joined(separator: ", "))")
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift
index dece6216..b0aabe84 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift
@@ -199,6 +199,7 @@ struct VPhoneLaunchpadNewMachineView: View {
#if DEBUG
if VPhoneLaunchpadPreview.isActive {
page = VPhoneLaunchpadPreview.newMachinePage
+ patches = VPhoneLaunchpadPreview.newMachinePatches
}
#endif
}
@@ -527,6 +528,7 @@ struct VPhoneLaunchpadNewMachineView: View {
diskSizeGB: diskSizeGB,
network: network,
patches: patches,
+ guestPatches: patchCatalog?.guestOverrides(patches) ?? [],
keepArtifacts: keepArtifacts,
usesTemplate: usesTemplate,
slimming: slimming,
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swift
index a82f34c2..8e89cde6 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swift
@@ -71,7 +71,8 @@ nonisolated struct VPhoneLaunchpadPatchCatalog: Decodable, Sendable {
/// Whether the patch is in the boot chain, which only a restore
/// changes on a machine that exists. Read from `part` when the bundle
/// reports it, else from `target`, which names the component the same
- /// way for a boot-chain patch.
+ /// way for a boot-chain patch. Every `.firmware` component counts, as
+ /// it does for `fw patch` and the template key.
var isBootChain: Bool {
Self.bootChainParts.contains(part ?? target)
}
@@ -82,7 +83,7 @@ nonisolated struct VPhoneLaunchpadPatchCatalog: Decodable, Sendable {
}
private static let bootChainParts: Set<String> = [
- "AVPBooter", "iBSS", "iBEC", "LLB", "TXM", "kernelcache", "DeviceTree",
+ "AVPBooter", "iBSS", "iBEC", "LLB", "TXM", "kernelcache", "DeviceTree", "Filesystem", "Manifest",
]
/// False when the patch applies to every version, which is not worth a
@@ -180,6 +181,14 @@ nonisolated struct VPhoneLaunchpadPatchCatalog: Decodable, Sendable {
patches.count { $0.pending == true && ($0.delivery ?? (($0.isBootChain && !$0.isKernel) ? "restore" : "")) == "restore" }
}
+ /// The overrides of `selection` the guest half of an install writes. One
+ /// naming a patch this catalog does not list counts as boot chain, as the
+ /// template key counts it.
+ func guestOverrides(_ selection: VPhoneLaunchpadPatchSelection) -> Set<String> {
+ let guest = Set(patches.filter { !$0.isBootChain }.map(\.identifier))
+ return selection.blocked.union(selection.allowed).intersection(guest)
+ }
+
func preset(_ identifier: String) -> Preset? {
presets.first { $0.identifier == identifier }
}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift
index 66ccdf7f..964a6962 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift
@@ -210,12 +210,26 @@ nonisolated enum VPhoneLaunchpadTemplateCommands {
slimming.trimArguments.map { ["vm", "template", "trim", machine] + $0 }
}
+ /// `--strict`: the setup boot fails when an app it should remove stays.
+ /// Without it the app only drops out of the key, the adopted template
+ /// gets another id than Find Template computed, and every later create
+ /// with these options builds a template again.
static func setup(_ machine: String, _ slimming: VPhoneLaunchpadSlimming) -> [String] {
- ["vm", "template", "setup", machine] + slimming.setupArguments
+ ["vm", "template", "setup", machine, "--strict"] + slimming.setupArguments
}
- static func adopt(_ machine: String, iphoneSource: String, cloudOSSource: String) -> [String] {
+ /// `--expect`: the id Find Template computed for this creation. The adopt
+ /// fails, saying which part of the key differs, rather than save the
+ /// build under another id.
+ static func adopt(_ machine: String, iphoneSource: String, cloudOSSource: String, expect: String?) -> [String] {
["vm", "template", "adopt", machine, "--json", "--iphone-source", iphoneSource, "--cloudos-source", cloudOSSource]
+ + (expect.map { ["--expect", $0] } ?? [])
+ }
+
+ /// `fw set-patches`: the template build's boot-chain overrides, or every
+ /// override for a machine of its own (`includingGuest`).
+ static func setPatches(_ machine: String, _ overrides: VPhoneLaunchpadPatchOverrides, includingGuest: Bool) -> [String] {
+ ["fw", "set-patches", machine] + overrides.setPatchesArguments(includingGuest: includingGuest)
}
/// The new machine, cloned with the settings a template does not fix.
@@ -238,6 +252,52 @@ nonisolated enum VPhoneLaunchpadTemplateCommands {
}
}
+// MARK: - Patch overrides
+
+/// New Machine's per-patch overrides, split where the template key splits
+/// them. A boot-chain patch is built into the template by `fw patch`, so its
+/// overrides are part of the key and go to the build. A guest patch is
+/// written by the guest half of an install, which `cfw update-environment`
+/// runs again on a clone, so its overrides stay out of the template and go
+/// to the clone: a template never passes them on to a creation that did not
+/// ask for them, and `vm template find` does not key on them.
+nonisolated struct VPhoneLaunchpadPatchOverrides: Hashable, Sendable {
+ var preset: String
+ var blocked: Set<String> = []
+ var allowed: Set<String> = []
+ /// The overridden patches the bundle's catalog places in the guest
+ /// (`VPhoneLaunchpadPatchCatalog.guestOverrides`). A patch it does not
+ /// list counts as boot chain, as the template key counts it.
+ var guestPatches: Set<String> = []
+
+ var bootChainBlocked: Set<String> {
+ blocked.subtracting(guestPatches)
+ }
+
+ var bootChainAllowed: Set<String> {
+ allowed.subtracting(guestPatches)
+ }
+
+ var hasBootChainOverrides: Bool {
+ !bootChainBlocked.isEmpty || !bootChainAllowed.isEmpty
+ }
+
+ var hasGuestOverrides: Bool {
+ !blocked.isDisjoint(with: guestPatches) || !allowed.isDisjoint(with: guestPatches)
+ }
+
+ /// `fw set-patches` arguments without the machine. Each run writes the
+ /// whole record, so the clone's run repeats the boot-chain overrides it
+ /// already has from its template.
+ func setPatchesArguments(includingGuest: Bool) -> [String] {
+ let blocked = includingGuest ? blocked : bootChainBlocked
+ let allowed = includingGuest ? allowed : bootChainAllowed
+ return ["--preset", preset]
+ + blocked.sorted().flatMap { ["--block", $0] }
+ + allowed.sorted().flatMap { ["--allow", $0] }
+ }
+}
+
// MARK: - vm template list / show / find / adopt --json
/// One template as `vm template list --json`, `show --json` and `adopt