Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Count only VM processes holding a disk as a running machine in Launchpad

Jacky5952484b6799
diff --git a/Documents/Guides/launchpad-cli.md b/Documents/Guides/launchpad-cli.md
index e55708fb..d9ee8f08 100644
--- a/Documents/Guides/launchpad-cli.md
+++ b/Documents/Guides/launchpad-cli.md
@@ -110,13 +110,13 @@ version while a machine is bound to it; rebind or delete those machines first.
| `bundle install-release <version\|latest> [--keep-default]` | Download and install a GitHub release |
| `bundle set-default <version>` / `bundle verify <version>` | Make a version the default, or re-check it. `bundle use` is the old name of `set-default` |
| `bundle accept <version> [--off]` / `bundle remove <version>` | Skip failed checks, or remove a version no machine is bound to |
-| `vm list` | Machines in every library with run state, Core Bundle and log path |
-| `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 |
+| `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. `--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 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. |
+| `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 |
| `cfw update-kernel <name>` | Re-patch the kernelcache from the machine's current selection and swap it into Preboot, keeping the data (VM off); the data-preserving way to change a kernel patch on an installed VM, no restore tree needed |
| `guest send <name> <json>` | One raw `vphone.sock` request (tap, swipe, key, screenshot) |
diff --git a/Research/Host/machine_templates.md b/Research/Host/machine_templates.md
index b45a9052..4a707886 100644
--- a/Research/Host/machine_templates.md
+++ b/Research/Host/machine_templates.md
@@ -212,6 +212,19 @@ not standing still. Their refusals name each holder (`process 900
vphone-launchpad`) and say when none of them runs the VM, so a reader is not
taken for a running machine.
+Launchpad judges the holders `lsof` lists the same way
+(`VPhoneLaunchpadDiskHolder`, a copy of the `VPhoneProcessHolder` rule, since
+Launchpad does not link VPhoneCoreKit). Only a VM holder makes a machine
+running. Until 2026-10-09 any holder did, so a `tail -f` on `Disk.img` showed
+the machine as running and `vphone-launchpad-cli vm start` refused it as
+"already running or busy" (PR #633 retest, L1). Any other holder leaves the
+machine stopped. It still counts as held for the disk meter
+(`VPhoneLaunchpadDiskAccess.isHeld`), and Launchpad refuses `cfw install`,
+`update-environment` and `update-kernel` by name before the helper runs them.
+`vm list` reports such holders as `diskOpenIn`. A start is not refused, because
+`vphone-cli vm launch` does not refuse one either: Virtualization opens the
+disk itself. The Launchpad CLI prints a note naming the holder.
+
Blocks shared with a file outside the libraries (a `cp -c` copy elsewhere)
count as the folder's own; the CLI's `vm template list/show` print only the
allocated size.
diff --git a/VPhoneLaunchpad/Tests/TemplatesTests.sh b/VPhoneLaunchpad/Tests/TemplatesTests.sh
index 87e299c3..8dbbc12b 100755
--- a/VPhoneLaunchpad/Tests/TemplatesTests.sh
+++ b/VPhoneLaunchpad/Tests/TemplatesTests.sh
@@ -12,6 +12,7 @@ trap '/bin/rm -rf "$temporary"' EXIT
"$launchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPlan.swift" \
"$launchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskUsage.swift" \
"$launchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskExtents.swift" \
+ "$launchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskHolder.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 c39b6ca8..cf49b508 100644
--- a/VPhoneLaunchpad/Tests/TemplatesTests.swift
+++ b/VPhoneLaunchpad/Tests/TemplatesTests.swift
@@ -498,6 +498,7 @@ struct TemplatesTests {
precondition(VPhoneLaunchpadDiskUsage(allocated: 1_000_000_000, exclusive: nil).summary(locale: english) == "1 GB", "Without an exclusive size")
extentArithmetic()
diskAccess()
+ diskHolders()
try await sharedExtents()
print("Disk use tests passed")
}
@@ -531,6 +532,86 @@ struct TemplatesTests {
precondition(Meter.use(isCurrent: false, hasLast: false, mayOpen: false, hasTime: false) == .unknown, "Nothing")
}
+ /// Which holders of a disk make a machine running (retest L1: `tail -f`
+ /// on a `Disk.img` made Launchpad refuse to start the machine as running).
+ static func diskHolders() {
+ typealias Holder = VPhoneLaunchpadDiskHolder
+ let service = "/System/Library/Frameworks/Virtualization.framework/Versions/A/XPCServices/"
+ + "com.apple.Virtualization.VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine"
+ let executables: [pid_t: String] = [
+ 410: "/Library/Application Support/vphone-launchpad/Bundles/2.9.0/VPhone.bundle/Contents/MacOS/vphone-vm",
+ 412: service,
+ 900: "/Applications/vphone-launchpad.app/Contents/MacOS/vphone-launchpad",
+ 12925: "/usr/bin/tail",
+ 13000: "/tmp/com.apple.Virtualization.VirtualMachine",
+ 13001: "/tmp/vphone-vm-helper",
+ ]
+ let disks = ["vm-a", "vm-b", "nt-a", "own", "lab", "fake"]
+ let owners = Dictionary(uniqueKeysWithValues: disks.map { ("/lib/\($0)/Disk.img", $0) })
+ // The shape `lsof -F pn` prints: a `p` line per process, then an `f`
+ // and an `n` line per file. 77 is gone by the time it is looked up.
+ let output = """
+ p410
+ ftxt
+ n/Library/Application Support/vphone-launchpad/Bundles/2.9.0/VPhone.bundle/Contents/MacOS/vphone-vm
+ p412
+ f9
+ n/lib/vm-b/Disk.img
+ p900
+ f12
+ n/lib/own/Disk.img
+ f13
+ n/lib/nt-a/Disk.img
+ p12925
+ f3
+ n/lib/nt-a/Disk.img
+ p77
+ f4
+ n/lib/lab/Disk.img
+ p410
+ f20
+ n/lib/vm-a/Disk.img
+ p13000
+ f5
+ n/lib/fake/Disk.img
+ p13001
+ f6
+ n/lib/fake/Disk.img
+ p412
+ f10
+ n/lib/lab/Disk.img
+ """
+ var lookups: [pid_t] = []
+ let held = Holder.holders(lsofOutput: output, diskOwners: owners, excluding: 900) { pid in
+ lookups.append(pid)
+ return executables[pid]
+ }
+ func running(_ disk: String) -> Bool {
+ held[disk, default: []].contains(where: \.runsMachine)
+ }
+ func others(_ disk: String) -> String {
+ Holder.describe(held[disk, default: []].filter { !$0.runsMachine })
+ }
+ precondition(running("vm-a") && others("vm-a").isEmpty, "vphone-vm runs the machine: \(held["vm-a"] ?? [])")
+ precondition(running("vm-b") && others("vm-b").isEmpty, "The VM service runs the machine: \(held["vm-b"] ?? [])")
+ precondition(!running("nt-a"), "tail does not run the machine")
+ precondition(others("nt-a") == "12925 tail", "A reader is named, Launchpad is not: \(others("nt-a"))")
+ precondition(held["own"] == nil, "Launchpad's own meter holds nothing")
+ precondition(running("lab") && others("lab") == "77 unknown", "A gone process is named, the VM still runs: \(held["lab"] ?? [])")
+ precondition(!running("fake") && others("fake") == "13000 com.apple.Virtualization.VirtualMachine, 13001 vphone-vm-helper",
+ "Look-alikes do not run a machine: \(others("fake"))")
+ precondition(held.count == 5, "Only listed disks, and only the ones held: \(held.keys.sorted())")
+ precondition(lookups.sorted() == [77, 410, 412, 12925, 13000, 13001], "Each process is looked up once: \(lookups.sorted())")
+
+ precondition(!Holder(pid: 1, executablePath: nil).runsMachine && !Holder(pid: 1, executablePath: "").runsMachine,
+ "An unknown process never runs a machine")
+ precondition(Holder(pid: 1, executablePath: nil).description == "1 unknown", "An unknown process by name")
+ // The real lookup, on this process.
+ let me = Holder(pid: getpid(), executablePath: Holder.executablePath(of: getpid()))
+ precondition(me.executablePath != nil && me.name == "templates-tests" && !me.runsMachine, "This process: \(me)")
+ precondition(Holder.holders(lsofOutput: "", diskOwners: owners, excluding: 900).isEmpty, "Nothing held")
+ }
+
/// 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 34d8683d..1b170dc6 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift
@@ -306,6 +306,12 @@ struct VPhoneLaunchpadControlCommands {
if let udid = machine.udid {
report["udid"] = udid
}
+ // Processes that have the disk open without running the machine, as
+ // `vm stop` names them: `12925 tail`. The state stays `stopped`.
+ let others = library.otherDiskHolders(of: path)
+ if !others.isEmpty {
+ report["diskOpenIn"] = others.map(\.description)
+ }
report["unlocksAtStartup"] = machine.unlocksAtStartup ?? false
report["syncsHostLocation"] = machine.syncsHostLocation ?? false
if let info = machine.restoreInfo {
@@ -352,8 +358,21 @@ struct VPhoneLaunchpadControlCommands {
private func startMachine(_ request: VPhoneLaunchpadControlRequest, emit: @escaping Emit) async throws -> Any {
let machine = try await machine(request)
- guard library.state(of: machine) == .stopped else {
- throw VPhoneLaunchpadError("\(machine.name) is already running or busy.")
+ switch library.state(of: machine) {
+ case .stopped:
+ break
+ case .running:
+ throw VPhoneLaunchpadError("\(machine.name) is already running.")
+ case let .busy(activity):
+ throw VPhoneLaunchpadError("\(machine.name) is busy: \(activity)")
+ }
+ // A process that has the disk open without running the machine does
+ // not stop the start, as it does not stop `vphone-cli vm launch`:
+ // Virtualization opens the disk itself and fails the start if it
+ // cannot. It is named, so a start that fails is not a mystery.
+ let others = await library.currentOtherDiskHolders(of: machine)
+ if !others.isEmpty {
+ emit("note: the disk of \(machine.name) is open in \(VPhoneLaunchpadDiskHolder.describe(others)), which does not run it")
}
library.actionError = nil
// Checks the machine's own bundle first, once per Launchpad session.
@@ -796,12 +815,26 @@ struct VPhoneLaunchpadControlCommands {
return version
}
+ /// `cfw install` and the updates need the disk to themselves and refuse
+ /// any other holder, so a process that only reads it refuses them here
+ /// too, by name, before the helper is asked.
+ private func requireDiskUnheld(_ machine: VPhoneLaunchpadMachinePath) async throws {
+ let others = await library.currentOtherDiskHolders(of: machine)
+ guard others.isEmpty else {
+ throw VPhoneLaunchpadError(
+ "The disk of \(machine.name) is open in \(VPhoneLaunchpadDiskHolder.describe(others)), which does not run it. "
+ + "Try again once that process closes it.",
+ )
+ }
+ }
+
private func installCustomFirmware(_ request: VPhoneLaunchpadControlRequest, emit: @escaping Emit) async throws -> Any {
let machine = try await machine(request)
let version = try bundleVersion(of: machine)
guard library.state(of: machine) == .stopped else {
throw VPhoneLaunchpadError("Stop \(machine.name) before installing CFW.")
}
+ try await requireDiskUnheld(machine)
let status = try await model.helper.installCustomFirmware(
bundleVersion: version,
machineName: machine.name,
@@ -822,6 +855,7 @@ struct VPhoneLaunchpadControlCommands {
guard library.state(of: machine) == .stopped else {
throw VPhoneLaunchpadError("Stop \(machine.name) before updating its guest environment.")
}
+ try await requireDiskUnheld(machine)
let status = try await model.helper.updateGuestEnvironment(
bundleVersion: version,
machineName: machine.name,
@@ -841,6 +875,7 @@ struct VPhoneLaunchpadControlCommands {
guard library.state(of: machine) == .stopped else {
throw VPhoneLaunchpadError("Stop \(machine.name) before updating its kernel.")
}
+ try await requireDiskUnheld(machine)
let status = try await model.helper.updateKernel(
bundleVersion: version,
machineName: machine.name,
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
index fabb6970..e51755b9 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
@@ -17410,6 +17410,15 @@
"zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "无法更新内核。" } }
}
},
+ "The disk of %@ is open in process %@, which does not run it. Try again once that process closes it." : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "The disk of %@ is open in process %@, which does not run it. Try again once that process closes it." } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%1$@ のディスクはプロセス %2$@ が開いていますが、このプロセスはマシンを実行していません。そのプロセスがディスクを閉じてから、もう一度お試しください。" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "%1$@의 디스크를 프로세스 %2$@이(가) 열고 있지만, 이 프로세스는 머신을 실행하지 않습니다. 해당 프로세스가 디스크를 닫은 후 다시 시도하세요." } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Đĩa của %1$@ đang được mở bởi tiến trình %2$@, tiến trình này không chạy máy. Hãy thử lại sau khi tiến trình đó đóng đĩa." } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "%1$@ 的磁盘正被进程 %2$@ 打开,该进程并未运行这台机器。请等该进程关闭磁盘后再试。" } }
+ }
+ },
"Swaps the Preboot kernelcache for the one this machine's patches resolve to, keeping the data (no restore)." : {
"localizations" : {
"en" : { "stringUnit" : { "state" : "translated", "value" : "Swaps the Preboot kernelcache for the one this machine's patches resolve to, keeping the data (no restore)." } },
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskHolder.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskHolder.swift
new file mode 100644
index 00000000..656e2cd4
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskHolder.swift
@@ -0,0 +1,86 @@
+import Darwin
+import Foundation
+
+/// A process other than Launchpad that `lsof` lists for a machine's disk
+/// image, and whether it runs the machine, judged by its executable.
+///
+/// Many processes open a disk image without running it: `tail`, Spotlight, a
+/// backup tool, a `vm template trim` attaching it. Only `vphone-vm` (from any
+/// copy of the bundle) and Virtualization's VM service, which holds the disk
+/// for it, make a machine running. This is the CLI's `VPhoneProcessHolder`
+/// (VPhoneCoreKit, which Launchpad does not link), and the two must judge a
+/// path the same way: `vm stop` signals only the holders the CLI calls VM
+/// processes, and Launchpad offers Stop only for a machine it calls running.
+nonisolated struct VPhoneLaunchpadDiskHolder: Hashable, Sendable, CustomStringConvertible {
+ var pid: pid_t
+ /// From `proc_pidpath`; nil for a process that is gone or cannot be
+ /// inspected.
+ var executablePath: String?
+
+ /// Whether this process runs a machine. A path that only takes the name of
+ /// the VM service, outside Virtualization.framework, does not.
+ var runsMachine: Bool {
+ guard let executablePath, !executablePath.isEmpty else { return false }
+ let components = (executablePath as NSString).pathComponents
+ switch components.last {
+ case "vphone-vm":
+ return true
+ case "com.apple.Virtualization.VirtualMachine":
+ return components.contains("Virtualization.framework")
+ default:
+ return false
+ }
+ }
+
+ /// The executable's file name, or `unknown`.
+ var name: String {
+ executablePath.map { ($0 as NSString).lastPathComponent } ?? "unknown"
+ }
+
+ /// `12925 tail`, as the CLI names a holder.
+ var description: String {
+ "\(pid) \(name)"
+ }
+
+ /// `410 vphone-vm, 12925 tail`.
+ static func describe(_ holders: [VPhoneLaunchpadDiskHolder]) -> String {
+ holders.map(\.description).joined(separator: ", ")
+ }
+
+ static func executablePath(of pid: pid_t) -> String? {
+ var buffer = [CChar](repeating: 0, count: Int(4 * MAXPATHLEN))
+ let length = proc_pidpath(pid, &buffer, UInt32(buffer.count))
+ guard length > 0 else { return nil }
+ return String(decoding: buffer.prefix(Int(length)).map { UInt8(bitPattern: $0) }, as: UTF8.self)
+ }
+
+ /// The processes `lsof -F pn` lists for each disk in `diskOwners`, by the
+ /// owner of that disk and in PID order. Launchpad itself (`excluding`)
+ /// holds a disk only while its meter maps the extents, and is left out.
+ static func holders<Owner: Hashable>(
+ lsofOutput output: String,
+ diskOwners: [String: Owner],
+ excluding ownProcess: pid_t,
+ executablePath: (pid_t) -> String? = Self.executablePath(of:),
+ ) -> [Owner: [VPhoneLaunchpadDiskHolder]] {
+ var pids: [Owner: Set<pid_t>] = [:]
+ var process: pid_t?
+ for line in output.split(separator: "\n") {
+ if line.hasPrefix("p") {
+ process = pid_t(line.dropFirst())
+ } else if line.hasPrefix("n"), let process, process != ownProcess,
+ let owner = diskOwners[String(line.dropFirst())]
+ {
+ pids[owner, default: []].insert(process)
+ }
+ }
+ // Each process is looked up once, however many disks it holds.
+ var paths: [pid_t: String] = [:]
+ for pid in Set(pids.values.joined()) {
+ paths[pid] = executablePath(pid)
+ }
+ return pids.mapValues { held in
+ held.sorted().map { VPhoneLaunchpadDiskHolder(pid: $0, executablePath: paths[$0]) }
+ }
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
index 654d8975..d87205a7 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
@@ -42,7 +42,9 @@ final class VPhoneLaunchpadMachineLibrary {
private let bundles: VPhoneLaunchpadCoreBundle
private let helper: VPhoneLaunchpadHelperClient
private var launched: [Path: VPhoneLaunchpadChildProcess] = [:]
- private var externallyRunning: Set<Path> = []
+ /// The processes other than Launchpad that the last `lsof` listed for each
+ /// machine's disk image, the machine's own VM included.
+ private var diskHolders: [Path: [VPhoneLaunchpadDiskHolder]] = [:]
private var activities: [Path: String] = [:]
private var isRefreshing = false
private var timer: Timer?
@@ -112,12 +114,27 @@ final class VPhoneLaunchpadMachineLibrary {
if exports[machine]?.isWaiting == true {
return .busy(String(localized: "Waiting to export…"))
}
- if launched[machine]?.isRunning == true || externallyRunning.contains(machine) {
+ // Only a VM process holding the disk runs the machine; a reader such
+ // as `tail` or a backup tool leaves it stopped (see `otherDiskHolders`).
+ if launched[machine]?.isRunning == true || diskHolders[machine]?.contains(where: \.runsMachine) == true {
return .running
}
return .stopped
}
+ /// The processes the last `lsof` listed for the machine's disk that do not
+ /// run it. The machine is not running for them, but its disk is not
+ /// standing still either: the meter leaves it alone, and operations that
+ /// need the disk to themselves refuse.
+ func otherDiskHolders(of machine: Path) -> [VPhoneLaunchpadDiskHolder] {
+ diskHolders[machine, default: []].filter { !$0.runsMachine }
+ }
+
+ /// `otherDiskHolders`, asked of `lsof` now rather than at the last refresh.
+ func currentOtherDiskHolders(of machine: Path) async -> [VPhoneLaunchpadDiskHolder] {
+ await Task.detached { Self.diskHolders([machine])[machine, default: []] }.value.filter { !$0.runsMachine }
+ }
+
func launchedProcess(_ machine: Path) -> VPhoneLaunchpadChildProcess? {
launched[machine]
}
@@ -221,16 +238,18 @@ final class VPhoneLaunchpadMachineLibrary {
selection = [first.id]
}
let paths = machines.map(\.path)
- externallyRunning = await Task.detached { Self.machinesHoldingDisks(paths) }.value
+ diskHolders = await Task.detached { Self.diskHolders(paths) }.value
// A stopped machine's guest boots afresh when it starts again.
pendingGuestRestarts = pendingGuestRestarts.filter { state(of: $0.key) != .stopped }
await loadBindings(paths)
refreshDiskUsage()
}
- /// The same test `vm stop` uses: a machine runs while some process holds
- /// its disk image open. This also finds guests started outside Launchpad.
- private nonisolated static func machinesHoldingDisks(_ machines: [Path]) -> Set<Path> {
+ /// Every process other than Launchpad holding each machine's disk image,
+ /// by executable. The same test `vm stop` uses: a machine runs while a VM
+ /// process holds its disk, which also finds guests started outside
+ /// Launchpad.
+ private nonisolated static func diskHolders(_ machines: [Path]) -> [Path: [VPhoneLaunchpadDiskHolder]] {
var diskOwners: [String: Path] = [:]
for machine in machines {
let bundle = machine.url
@@ -241,7 +260,7 @@ final class VPhoneLaunchpadMachineLibrary {
diskOwners[bundle.appendingPathComponent(disk).path] = machine
}
guard !diskOwners.isEmpty else {
- return []
+ return [:]
}
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/sbin/lsof")
@@ -250,27 +269,11 @@ final class VPhoneLaunchpadMachineLibrary {
process.standardOutput = pipe
process.standardError = FileHandle.nullDevice
guard (try? process.run()) != nil else {
- return []
+ return [:]
}
let output = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
process.waitUntilExit()
- return runningMachines(lsofOutput: output, diskOwners: diskOwners, excluding: getpid())
- }
-
- /// The machines whose disks `lsof -F pn` lists a process for. Launchpad
- /// itself (`excluding`) holds a disk only while measuring its extents,
- /// which does not make the machine run.
- nonisolated static func runningMachines(lsofOutput output: String, diskOwners: [String: Path], excluding ownProcess: pid_t) -> Set<Path> {
- var running: Set<Path> = []
- var process: pid_t?
- for line in output.split(separator: "\n") {
- if line.hasPrefix("p") {
- process = pid_t(line.dropFirst())
- } else if line.hasPrefix("n"), process != ownProcess, let machine = diskOwners[String(line.dropFirst())] {
- running.insert(machine)
- }
- }
- return running
+ return VPhoneLaunchpadDiskHolder.holders(lsofOutput: output, diskOwners: diskOwners, excluding: getpid())
}
/// `name` when it is one path component, otherwise nil.
@@ -487,6 +490,21 @@ 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 {
+ 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."),
+ )
+ return false
+ }
+
/// 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 {
@@ -494,6 +512,9 @@ final class VPhoneLaunchpadMachineLibrary {
actionError = VPhoneLaunchpadError(String(localized: "No Core Bundle version is installed. Install one in Core Bundle."))
return
}
+ guard await requireDiskUnheld(machine) else {
+ return
+ }
activities[machine] = String(localized: "Installing custom firmware…")
defer { activities[machine] = nil }
appendConsoleLog(machine, "$ vphone-cli cfw install \(machine.name)")
@@ -532,6 +553,9 @@ final class VPhoneLaunchpadMachineLibrary {
actionError = VPhoneLaunchpadError(String(localized: "No Core Bundle version is installed. Install one in Core Bundle."))
return
}
+ guard await requireDiskUnheld(machine) else {
+ return
+ }
activities[machine] = String(localized: "Updating guest environment…")
defer { activities[machine] = nil }
appendConsoleLog(machine, "$ vphone-cli cfw update-environment \(machine.name)")
@@ -568,6 +592,9 @@ final class VPhoneLaunchpadMachineLibrary {
actionError = VPhoneLaunchpadError(String(localized: "No Core Bundle version is installed. Install one in Core Bundle."))
return
}
+ guard await requireDiskUnheld(machine) else {
+ return
+ }
activities[machine] = String(localized: "Updating kernel…")
defer { activities[machine] = nil }
appendConsoleLog(machine, "$ vphone-cli cfw update-kernel \(machine.name)")
@@ -639,12 +666,13 @@ final class VPhoneLaunchpadMachineLibrary {
}
/// Whether the machine's virtual machine is still up: the process
- /// Launchpad started, or for one started elsewhere, whoever holds its disk.
+ /// Launchpad started, or for one started elsewhere, a VM process holding
+ /// its disk.
func isMachineRunning(_ machine: Path) async -> Bool {
if let child = launched[machine] {
return child.isRunning
}
- return await Task.detached { !Self.machinesHoldingDisks([machine]).isEmpty }.value
+ return await Task.detached { Self.diskHolders([machine])[machine, default: []].contains(where: \.runsMachine) }.value
}
// MARK: - Edits
@@ -807,7 +835,7 @@ final class VPhoneLaunchpadMachineLibrary {
let isBusy = if case .busy = state(of: machine) { true } else { false }
return VPhoneLaunchpadDiskAccess(
isLaunched: launched[machine] != nil,
- isHeld: externallyRunning.contains(machine),
+ isHeld: diskHolders[machine]?.isEmpty == false,
isBusy: isBusy || creation(for: machine)?.isRunning == true || exports[machine] != nil,
isLibraryBusy: globalActivity != nil,
)
@@ -1213,7 +1241,9 @@ final class VPhoneLaunchpadMachineLibrary {
func applyPreview(creation: VPhoneLaunchpadCreationPipeline) {
machines = VPhoneLaunchpadPreview.machines
hasListed = true
- externallyRunning = [VPhoneLaunchpadPreview.path("research-01")]
+ diskHolders = [VPhoneLaunchpadPreview.path("research-01"): [
+ VPhoneLaunchpadDiskHolder(pid: 4101, executablePath: "/Library/Application Support/vphone-launchpad/Bundles/2.9.0/VPhone.bundle/Contents/MacOS/vphone-vm"),
+ ]]
startedAt = [VPhoneLaunchpadPreview.path("research-01"): Date().addingTimeInterval(-6130)]
creations = [creation.machine: creation]
selection = [VPhoneLaunchpadPreview.path("research-01")]