Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Check the disk before rebinding a machine in Launchpad's set-bundle

Jackyc36e7d622712
diff --git a/Documents/Guides/launchpad-cli.md b/Documents/Guides/launchpad-cli.md
index d9ee8f08..b8b6a5e5 100644
--- a/Documents/Guides/launchpad-cli.md
+++ b/Documents/Guides/launchpad-cli.md
@@ -114,7 +114,7 @@ version while a machine is bound to it; rebind or delete those machines first.
| `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. `--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, `--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 |
+| `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`). |
| `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 |
diff --git a/VPhoneLaunchpad/Tests/TemplatesTests.sh b/VPhoneLaunchpad/Tests/TemplatesTests.sh
index 8dbbc12b..405467c7 100755
--- a/VPhoneLaunchpad/Tests/TemplatesTests.sh
+++ b/VPhoneLaunchpad/Tests/TemplatesTests.sh
@@ -13,6 +13,7 @@ trap '/bin/rm -rf "$temporary"' EXIT
"$launchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskUsage.swift" \
"$launchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskExtents.swift" \
"$launchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskHolder.swift" \
+ "$launchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadBundleChange.swift" \
"$launchpad/Tests/TemplatesTests.swift" \
-o "$temporary/templates-tests"
"$temporary/templates-tests" "$@"
diff --git a/VPhoneLaunchpad/Tests/TemplatesTests.swift b/VPhoneLaunchpad/Tests/TemplatesTests.swift
index b196b912..f72d7136 100644
--- a/VPhoneLaunchpad/Tests/TemplatesTests.swift
+++ b/VPhoneLaunchpad/Tests/TemplatesTests.swift
@@ -14,6 +14,7 @@ struct TemplatesTests {
notices()
try templateOrigins()
try await diskUsage()
+ try await bundleChange()
}
// MARK: - Switches
@@ -674,6 +675,58 @@ struct TemplatesTests {
precondition(Holder.holders(lsofOutput: "", diskOwners: owners, excluding: 900).isEmpty, "Nothing held")
}
+ /// The order of a Core Bundle change (retest: `vm set-bundle
+ /// --update-environment` on a disk `tail -f` held rebound the machine,
+ /// then refused the update).
+ @MainActor
+ static func bundleChange() async throws {
+ struct Unwritable: Error {}
+ typealias Change = VPhoneLaunchpadBundleChange
+ let tail = VPhoneLaunchpadDiskHolder(pid: 12925, executablePath: "/usr/bin/tail")
+ var steps: [String] = []
+ func perform(
+ updates: Bool,
+ held: [VPhoneLaunchpadDiskHolder] = [],
+ bindFails: Bool = false,
+ updateSucceeds: Bool = true,
+ ) async throws -> Change {
+ steps = []
+ return try await Change.perform(
+ updatesEnvironment: updates,
+ otherDiskHolders: {
+ steps.append("holders")
+ return held
+ },
+ bind: {
+ steps.append("bind")
+ if bindFails { throw Unwritable() }
+ },
+ updateEnvironment: {
+ steps.append("update")
+ return updateSucceeds
+ },
+ )
+ }
+
+ var change = try await perform(updates: true, held: [tail])
+ precondition(change == .refused([tail]) && steps == ["holders"], "A held disk refuses before the binding: \(change) \(steps)")
+ change = try await perform(updates: true)
+ precondition(change == .updated && steps == ["holders", "bind", "update"], "Checked, bound, updated: \(change) \(steps)")
+ change = try await perform(updates: true, updateSucceeds: false)
+ precondition(change == .boundButNotUpdated && steps == ["holders", "bind", "update"], "A failed update keeps the binding: \(change)")
+ // Without an update the disk is not asked about, so a reader of it
+ // does not stop a rebinding that leaves the guest alone.
+ change = try await perform(updates: false, held: [tail])
+ precondition(change == .bound && steps == ["bind"], "Bound only: \(change) \(steps)")
+ do {
+ _ = try await perform(updates: true, bindFails: true)
+ preconditionFailure("An unwritable binding throws")
+ } catch is Unwritable {
+ precondition(steps == ["holders", "bind"], "No update without the binding: \(steps)")
+ }
+ print("Bundle change tests passed")
+ }
+
/// The folders `mayOpenNow` was asked about.
actor AskedFolders {
private(set) var folders: [String] = []
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift
index 1b170dc6..4140c802 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift
@@ -772,6 +772,8 @@ struct VPhoneLaunchpadControlCommands {
/// Rebinds one machine. `setBundle` skips the environment update of a
/// running machine without saying so, so that is refused here instead.
+ /// A disk held by another process it refuses itself, before rebinding;
+ /// an update that fails after rebinding is reported as such.
private func setBundle(_ request: VPhoneLaunchpadControlRequest, emit: @escaping Emit) async throws -> Any {
let machine = try await machine(request)
let version = request.arguments[1]
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
index 0fa101ea..a9b92f3c 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
@@ -171,6 +171,40 @@
}
}
},
+ "%@ now runs with Core Bundle %@, but its guest environment was not updated. Update its guest environment to finish the change." : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ now runs with Core Bundle %@, but its guest environment was not updated. Update its guest environment to finish the change."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%1$@ はコアバンドル %2$@ で動作するようになりましたが、ゲスト環境は更新されていません。変更を完了するには、ゲスト環境を更新してください。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%1$@은(는) 이제 코어 번들 %2$@(으)로 실행되지만 게스트 환경은 업데이트되지 않았습니다. 변경을 마치려면 게스트 환경을 업데이트하세요."
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%1$@ giờ chạy bằng Bundle lõi %2$@, nhưng môi trường máy khách chưa được cập nhật. Hãy cập nhật môi trường máy khách để hoàn tất thay đổi."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%1$@ 现在使用核心 Bundle %2$@ 运行,但其客户机环境未更新。请更新客户机环境以完成更改。"
+ }
+ }
+ }
+ },
"%lld could not be changed." : {
"localizations" : {
"en" : {
@@ -10117,6 +10151,15 @@
"zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "无法更新客户机环境。" } }
}
},
+ "Unable to Update the Guest Environment of %@" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Unable to Update the Guest Environment of %@" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%@ のゲスト環境を更新できません" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "%@의 게스트 환경을 업데이트할 수 없음" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Không thể cập nhật môi trường máy khách của %@" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "无法更新 %@ 的客户机环境" } }
+ }
+ },
"Install Custom Firmware" : {
"localizations" : {
"en" : {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadBundleChange.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadBundleChange.swift
new file mode 100644
index 00000000..92d6a396
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadBundleChange.swift
@@ -0,0 +1,46 @@
+import Foundation
+
+/// The outcome of moving one machine to another Core Bundle, and the order of
+/// its steps, kept apart from the library so a test can hold it to that order.
+///
+/// Updating the guest environment needs the disk to itself, so another
+/// process holding the disk refuses the whole change before the binding is
+/// written: a refused change leaves the machine as it was. Only an update that
+/// fails once it has started leaves the two layers apart. The binding stays
+/// then, since undoing it would not undo what the update already copied into
+/// the guest: `bundle` names the new version while `guestEnvironment` still
+/// names the bundle whose environment was installed last, as `vm list` and the
+/// inspector show, and updating the guest environment again finishes the move.
+nonisolated enum VPhoneLaunchpadBundleChange: Equatable, Sendable {
+ /// Bound; the guest environment was not to be updated.
+ case bound
+ /// Bound, and the guest environment updated.
+ case updated
+ /// Bound, but the update of the guest environment failed.
+ case boundButNotUpdated
+ /// Nothing written: these processes, which do not run the machine, have
+ /// its disk open.
+ case refused([VPhoneLaunchpadDiskHolder])
+
+ /// Checks the disk when the environment is to be updated, then binds,
+ /// then updates. A failure to bind is thrown, with nothing else done.
+ @MainActor
+ static func perform(
+ updatesEnvironment: Bool,
+ otherDiskHolders: () async -> [VPhoneLaunchpadDiskHolder],
+ bind: () throws -> Void,
+ updateEnvironment: () async -> Bool,
+ ) async throws -> Self {
+ if updatesEnvironment {
+ let others = await otherDiskHolders()
+ guard others.isEmpty else {
+ return .refused(others)
+ }
+ }
+ try bind()
+ guard updatesEnvironment else {
+ return .bound
+ }
+ return await updateEnvironment() ? .updated : .boundButNotUpdated
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
index 21c5eb57..d45e9251 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
@@ -348,6 +348,8 @@ final class VPhoneLaunchpadMachineLibrary {
/// on the next start. With `updateEnvironment`, each stopped machine also
/// gets that version's guest environment; a running one keeps its own
/// until it is updated later. Boot chain and patches stay as created.
+ /// A machine whose disk another process holds is left as it was rather
+ /// than rebound without its update (`VPhoneLaunchpadBundleChange`).
func setBundle(_ version: String, for machines: [Path], updateEnvironment: Bool) async {
guard bundles.commandLine(version: version) != nil else {
actionError = VPhoneLaunchpadError(String(localized: "VPhone.bundle \(version) is not installed."))
@@ -357,8 +359,31 @@ final class VPhoneLaunchpadMachineLibrary {
var binding = currentBinding(of: machine)
?? VPhoneLaunchpadMachineBinding(bundle: version)
binding.bundle = version
+ // A machine not restored yet, or whose custom firmware install
+ // did not finish, has no guest environment to update.
+ let listed = self.machines.first { $0.path == machine }
+ let updates = updateEnvironment && state(of: machine) == .stopped
+ && listed?.restoreInfo != nil && listed?.customFirmwareInstalled != false
+ let change: VPhoneLaunchpadBundleChange
do {
- try bind(machine, binding)
+ change = try await VPhoneLaunchpadBundleChange.perform(
+ updatesEnvironment: updates,
+ otherDiskHolders: { await currentOtherDiskHolders(of: machine) },
+ bind: { try bind(machine, binding) },
+ // A failed update says first which layer moved.
+ updateEnvironment: {
+ await updateGuestEnvironment(machine) { failure in
+ VPhoneLaunchpadError(
+ String(localized: "Unable to Update the Guest Environment of \(machine.name)"),
+ detail: [
+ String(localized: "\(machine.name) now runs with Core Bundle \(version), but its guest environment was not updated. Update its guest environment to finish the change."),
+ failure.message,
+ failure.detail,
+ ].compactMap(\.self).joined(separator: "\n\n"),
+ )
+ }
+ },
+ )
} catch {
actionError = VPhoneLaunchpadError(
String(localized: "Unable to Change the Core Bundle of \(machine.name)"),
@@ -366,13 +391,11 @@ final class VPhoneLaunchpadMachineLibrary {
)
continue
}
- // A machine not restored yet, or whose custom firmware install
- // did not finish, has no guest environment to update.
- let listed = self.machines.first { $0.path == machine }
- if updateEnvironment, state(of: machine) == .stopped,
- listed?.restoreInfo != nil, listed?.customFirmwareInstalled != false
- {
- await updateGuestEnvironment(machine)
+ if case let .refused(others) = change {
+ actionError = VPhoneLaunchpadError(
+ String(localized: "Unable to Change the Core Bundle of \(machine.name)"),
+ detail: Self.diskHeldDetail(machine, others),
+ )
}
}
}
@@ -493,18 +516,23 @@ final class VPhoneLaunchpadMachineLibrary {
/// False, with `actionError` set, while a process that does not run the
/// machine has its disk open. `cfw install` and the updates refuse such a
/// disk, but say so only in the console log; this names the holder here.
- private func requireDiskUnheld(_ machine: Path) async -> Bool {
+ private func requireDiskUnheld(
+ _ machine: Path,
+ explain: (VPhoneLaunchpadError) -> VPhoneLaunchpadError = { $0 },
+ ) async -> Bool {
let others = await currentOtherDiskHolders(of: machine)
guard !others.isEmpty else {
return true
}
- actionError = VPhoneLaunchpadError(
- String(localized: "Unable to Complete Action"),
- detail: String(localized: "The disk of \(machine.name) is open in process \(VPhoneLaunchpadDiskHolder.describe(others)), which does not run it. Try again once that process closes it."),
- )
+ actionError = explain(VPhoneLaunchpadError(String(localized: "Unable to Complete Action"), detail: Self.diskHeldDetail(machine, others)))
return false
}
+ /// Names the processes that hold a machine's disk without running it.
+ private static func diskHeldDetail(_ machine: Path, _ others: [VPhoneLaunchpadDiskHolder]) -> String {
+ String(localized: "The disk of \(machine.name) is open in process \(VPhoneLaunchpadDiskHolder.describe(others)), which does not run it. Try again once that process closes it.")
+ }
+
/// Runs `cfw install` again through the helper, for a machine whose last
/// install did not finish. Output goes to the machine's console log.
func installCustomFirmware(_ machine: Path) async {
@@ -548,14 +576,21 @@ final class VPhoneLaunchpadMachineLibrary {
/// machine's own bundle into it while it is stopped, through the helper,
/// and nothing else. This is how a machine created by an older bundle
/// gets newer hooks, since its restore tree is gone after the first boot.
- func updateGuestEnvironment(_ machine: Path) async {
+ /// True once the environment is recorded as updated. `explain` rewords a
+ /// failure before it is shown.
+ @discardableResult
+ func updateGuestEnvironment(
+ _ machine: Path,
+ explain: (VPhoneLaunchpadError) -> VPhoneLaunchpadError = { $0 },
+ ) async -> Bool {
guard let version = bundleVersion(for: machine) else {
- actionError = VPhoneLaunchpadError(String(localized: "No Core Bundle version is installed. Install one in Core Bundle."))
- return
+ actionError = explain(VPhoneLaunchpadError(String(localized: "No Core Bundle version is installed. Install one in Core Bundle.")))
+ return false
}
- guard await requireDiskUnheld(machine) else {
- return
+ guard await requireDiskUnheld(machine, explain: explain) else {
+ return false
}
+ var updated = false
activities[machine] = String(localized: "Updating guest environment…")
defer { activities[machine] = nil }
appendConsoleLog(machine, "$ vphone-cli cfw update-environment \(machine.name)")
@@ -568,20 +603,22 @@ final class VPhoneLaunchpadMachineLibrary {
onLine: { line in Self.append(line, to: log) },
)
if status != 0 {
- actionError = VPhoneLaunchpadError(
+ actionError = explain(VPhoneLaunchpadError(
String(localized: "Unable to update the guest environment."),
detail: String(localized: "Choose Show Console Log for the full output."),
- )
+ ))
} else {
recordGuestEnvironment(machine, version)
+ updated = true
}
} catch {
if !(error is CancellationError) {
- actionError = error as? VPhoneLaunchpadError
- ?? VPhoneLaunchpadError(String(localized: "Unable to update the guest environment."), detail: error.localizedDescription)
+ actionError = explain(error as? VPhoneLaunchpadError
+ ?? VPhoneLaunchpadError(String(localized: "Unable to update the guest environment."), detail: error.localizedDescription))
}
}
await refresh()
+ return updated
}
/// Replaces the machine's Preboot kernelcache with the one its current