Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Signal only a machine's own processes in vm stop

Jacky5a9db7091994
diff --git a/Documents/Guides/create-and-run.md b/Documents/Guides/create-and-run.md
index 1cca1635..58c00f97 100644
--- a/Documents/Guides/create-and-run.md
+++ b/Documents/Guides/create-and-run.md
@@ -32,7 +32,7 @@ vphone-cli vm launch myphone # start the VM window and keep it running
vphone-cli vm stop myphone # run from another terminal to stop it
```
-Closing the VM window, ⌘Q, `vm stop` and Control-C in the `vm launch` terminal all shut the guest down first (vphoned `system.shutdown`) and end the virtual machine once the guest has stopped, or after 15 seconds if it has not. A guest vphoned cannot answer for, such as one in DFU or still starting up, is turned off at once, as pulling the power would. A second Control-C turns it off without waiting.
+Closing the VM window, ⌘Q, `vm stop` and Control-C in the `vm launch` terminal all shut the guest down first (vphoned `system.shutdown`) and end the virtual machine once the guest has stopped, or after 15 seconds if it has not. A guest vphoned cannot answer for, such as one in DFU or still starting up, is turned off at once, as pulling the power would. A second Control-C turns it off without waiting. `vm stop` only ever signals the machine's own processes, `vphone-vm` and Virtualization's VM service; another program that has the disk open, such as Launchpad measuring its size, Spotlight or a backup tool, is named and left running.
`vm launch` starts the guest without waiting for vphoned; the daemon connects during boot. The VM window and menu provide Home/power keys, app installation and file browsing. The host control socket is `<VM bundle>/vphone.sock`: one JSON line in, one out. Connections are served concurrently, and the socket also exists with `--no-graphics`, where `tap` and `swipe` go through vphoned's touch injection and screen images come from the guest. Besides `tap`, `swipe`, `key` and `screenshot`, `{"t":"rpc","method":"<vphoned method>","params":{…}}` calls any method in `Research/vphoned_http_api.md`. For example, `input.key` with `{"name":"cmd+v"}` pastes and `input.type` types text. No SSH or VNC endpoint is installed by this workflow.
diff --git a/Documents/Guides/snapshots.md b/Documents/Guides/snapshots.md
index 7e61ef8f..3b83cc21 100644
--- a/Documents/Guides/snapshots.md
+++ b/Documents/Guides/snapshots.md
@@ -22,7 +22,9 @@ first, with `created` in ISO 8601 and `note` left out when there is none.
`create` and `revert` refuse while the VM is running, and so does anything that
holds its disk image, `SEPStorage` or `nvram.bin` open. Stop it with
-`vphone-cli vm stop myphone` or from its window, then try again.
+`vphone-cli vm stop myphone` or from its window, then try again. The refusal
+names each process holding them; when none of them runs the VM (a backup tool,
+Spotlight), it says so, and the retry succeeds once that process closes them.
The three files move together. The Secure Enclave's anti-replay counters live in
`SEPStorage`, and the disk holds the matching state. A disk from one moment with
diff --git a/Research/Host/machine_templates.md b/Research/Host/machine_templates.md
index 1deff556..df032de6 100644
--- a/Research/Host/machine_templates.md
+++ b/Research/Host/machine_templates.md
@@ -155,12 +155,32 @@ every 30 s, with a 15 s mapping budget after which the rest is mapped on a
later pass (those folders show no exclusive size meanwhile).
Mapping opens the file (`O_EVTONLY`), and while it is open `lsof` lists
-Launchpad for the image. `vm stop` signals whoever holds a disk, and `cfw
-install` refuses a disk someone holds, so Launchpad never opens a folder it is
-working on (a creation, a template build, an export, an install), keeps a
-stopped machine's last ranges until its files change, and leaves its own
-process out when it asks `lsof` which machines run. A `vphone-cli` run outside
-Launchpad in the ~0.1 s a changed image is being mapped can still see it held.
+Launchpad for the image. `cfw install` refuses a disk someone holds, so
+Launchpad never opens a folder it is working on (a creation, a template build,
+an export, an install), keeps a stopped machine's last ranges until its files
+change, and leaves its own process out when it asks `lsof` which machines run.
+A `vphone-cli` run outside Launchpad in the ~0.1 s a changed image is being
+mapped can still see it held.
+
+What a holder is decides what the CLI does with it
+(`VPhoneProcessHolder`, by `proc_pidpath`). Only `vphone-vm` (any copy of the
+bundle) and Virtualization's VM service
+(`Virtualization.framework/…/com.apple.Virtualization.VirtualMachine`) run a
+machine. `vm stop` asks the machine's `vphone-vm` (found by `--config`) with
+SIGINT, or, without one, the VM processes holding its disk; after the timeout
+it SIGKILLs only VM processes still holding the disk or the `vphone-vm` of
+that config, found again so a reused PID is not hit. Any other holder
+(Launchpad's meter, Spotlight, a backup tool, a trim or rebase attaching the
+image) is named and never signalled. Until 2026-10-09 `vm stop` SIGINTed every
+`lsof` holder when it found no `vphone-vm` and SIGKILLed every holder left
+after the timeout, so a stop that hit the meter's 0.1 s window could kill
+Launchpad (PR #633 retest, N2). `cfw install`, `update-environment` and
+`update-kernel` still refuse any other holder, as do clone, snapshot, revert,
+adopt, trim and the setup boot (`VPhoneBundleActivity.requireStopped`, over
+`Disk.img`, `SEPStorage` and `nvram.bin`): a file another process has open is
+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.
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
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
index df1b0b48..a6675d40 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
@@ -194,9 +194,7 @@ struct VPhoneCustomFirmwareInstaller {
)
// openDiskImage holds our verified descriptor throughout the install,
// so lsof always lists this process even when the VM is stopped.
- guard !VPhoneLsof.parsePIDs(busy.stdout).contains(where: { $0 != getpid() }) else {
- throw ValidationError("The VM disk is in use. Stop the VM, then run \(mode.summary) again.")
- }
+ try Self.requireDiskUnused(lsofOutput: busy.stdout, rerun: "run \(mode.summary) again")
// An environment update is exactly the case where there is no restore
// tree left: it is deleted once the VM has booted.
let restore = mode == .full
@@ -465,6 +463,18 @@ struct VPhoneCustomFirmwareInstaller {
}
}
+ /// Refuses unless no process but this one holds the disk. Any other
+ /// holder refuses, whatever it is: the install rewrites the disk under
+ /// it. The refusal names each holder's executable, so a process that
+ /// only reads the image (Launchpad measuring it, a backup tool) is not
+ /// taken for a running VM.
+ static func requireDiskUnused(lsofOutput: String, rerun: String) throws {
+ let holders = VPhoneLsof.parsePIDs(lsofOutput).filter { $0 != getpid() }.map { VPhoneProcessHolder(pid: $0) }
+ if let refusal = VPhoneProcessHolder.diskRefusal(holders, rerun: rerun) {
+ throw ValidationError(refusal)
+ }
+ }
+
/// Replace only the Preboot kernelcache, keeping every volume.
///
/// The booting kernel lives in Preboot as an IMG4. `fw patch` has already
@@ -491,9 +501,7 @@ struct VPhoneCustomFirmwareInstaller {
let busy = try VPhoneProcessRunner.runCapturing(
URL(fileURLWithPath: "/usr/sbin/lsof"), ["-t", "--", diskPath],
)
- guard !VPhoneLsof.parsePIDs(busy.stdout).contains(where: { $0 != getpid() }) else {
- throw ValidationError("The VM disk is in use. Stop the VM, then run the kernel update again.")
- }
+ try Self.requireDiskUnused(lsofOutput: busy.stdout, rerun: "run the kernel update again")
let work = try makeWorkDirectory()
defer {
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLaunchCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLaunchCommand.swift
index b58c9f72..950f5338 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLaunchCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLaunchCommand.swift
@@ -87,6 +87,12 @@ struct VPhoneVirtualMachineStopCommand: ParsableCommand {
static let configuration = CommandConfiguration(
commandName: "stop",
abstract: "Stop a running VM bundle",
+ discussion: """
+ Sends SIGINT to the machine's vphone-vm, waits, then sends SIGKILL to whatever of the \
+ machine is left. Only processes that run a machine are ever signalled: vphone-vm and \
+ Virtualization's VM service holding this machine's disk. Any other process that has the \
+ disk open (Launchpad measuring it, Spotlight, a backup tool) is named, never signalled.
+ """,
)
@OptionGroup var lib: VPhoneLibraryOption
@@ -96,7 +102,7 @@ struct VPhoneVirtualMachineStopCommand: ParsableCommand {
func run() throws {
let name = try VPhoneVirtualMachineSelection.resolveExisting(name, in: lib.library)
let bundle = try lib.library.bundle(named: name)
- // Every PID lsof reports for this path gets SIGINT and then SIGKILL, so
+ // The holders lsof reports for this path decide what is signalled, so
// it must be the bundle's own disk: a plain name inside the bundle and
// a regular file, never a symbolic link to something shared like
// /dev/null.
@@ -106,12 +112,15 @@ struct VPhoneVirtualMachineStopCommand: ParsableCommand {
return
}
- func runningPIDs() -> [Int32] {
+ /// Every process holding the disk now, by executable. Looked up again
+ /// before each signal, so a PID reused by another program meanwhile is
+ /// not taken for the VM.
+ func holders() -> (machine: [VPhoneProcessHolder], others: [VPhoneProcessHolder]) {
guard let r = try? VPhoneProcessRunner.runCapturing(
URL(fileURLWithPath: "/usr/sbin/lsof"),
["-t", "--", disk.path],
- ) else { return [] }
- return VPhoneLsof.parsePIDs(r.stdout)
+ ) else { return ([], []) }
+ return VPhoneProcessHolder.classify(VPhoneLsof.parsePIDs(r.stdout).map { VPhoneProcessHolder(pid: $0) })
}
// The disk is held by Virtualization's service, not by vphone-vm. A
@@ -119,32 +128,48 @@ struct VPhoneVirtualMachineStopCommand: ParsableCommand {
// with "the virtual machine stopped unexpectedly". vphone-vm quits on
// SIGINT and the service follows it, so vphone-vm is the one asked.
let virtualMachines = VPhoneGuestProcesses.virtualMachinePIDs(config: bundle.configURL)
- let holders = runningPIDs()
- guard !virtualMachines.isEmpty || !holders.isEmpty else { print("\(name): not running"); return }
+ let initial = holders()
+ guard !virtualMachines.isEmpty || !initial.machine.isEmpty else {
+ if !initial.others.isEmpty {
+ print("\(name): not running; its disk is open in \(VPhoneProcessHolder.describe(initial.others)), "
+ + "which does not run it and was not signalled")
+ } else {
+ print("\(name): not running")
+ }
+ return
+ }
- // Without a vphone-vm (one started some other way), only the
- // processes holding the disk are left to ask.
- let asked = virtualMachines.isEmpty ? holders : virtualMachines
+ // Without a vphone-vm of this config (one started some other way),
+ // only the VM processes holding the disk are left to ask.
+ let asked = virtualMachines.isEmpty ? initial.machine.map(\.pid) : virtualMachines
print("\(name): sending SIGINT to \(asked.map(String.init).joined(separator: ", "))")
for pid in asked {
kill(pid, SIGINT)
}
- func remaining() -> [Int32] {
- Array(Set(virtualMachines.filter { kill($0, 0) == 0 } + runningPIDs())).sorted()
+ func remaining() -> (machine: [Int32], others: [VPhoneProcessHolder]) {
+ let held = holders()
+ // Found again by its --config rather than by the PIDs found first,
+ // which another process may have taken once vphone-vm exited.
+ let alive = VPhoneGuestProcesses.virtualMachinePIDs(config: bundle.configURL)
+ return (Array(Set(alive + held.machine.map(\.pid))).sorted(), held.others)
}
var waited = 0
- while waited < timeout, !remaining().isEmpty {
+ while waited < timeout, !remaining().machine.isEmpty {
Thread.sleep(forTimeInterval: 1)
waited += 1
}
- let survivors = remaining()
+ let (survivors, others) = remaining()
if !survivors.isEmpty {
print("\(name): force-killing \(survivors.map(String.init).joined(separator: ", "))")
for pid in survivors {
kill(pid, SIGKILL)
}
}
+ if !others.isEmpty {
+ print("\(name): its disk is also open in \(VPhoneProcessHolder.describe(others)), "
+ + "which does not run it and was not signalled")
+ }
print("\(name): stopped")
}
}
diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleActivity.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleActivity.swift
index 1d66e821..a84cd39e 100644
--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleActivity.swift
+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleActivity.swift
@@ -24,6 +24,11 @@ public enum VPhoneBundleActivity {
}
/// Throws `VPhoneBundleActivityError.running` unless the machine is stopped.
+ ///
+ /// Any holder refuses, not only a process that runs the machine: a file
+ /// another program is reading or writing is not standing still either.
+ /// The error names each holder's executable, so a refusal caused by, say,
+ /// a backup tool reading `Disk.img` is not mistaken for a running VM.
public static func requireStopped(_ bundle: VPhoneBundle) throws {
let urls = stateFileNames(of: bundle).map { bundle.url.appendingPathComponent($0) }
let pids = processesHolding(urls)
@@ -114,15 +119,30 @@ public enum VPhoneBundleActivity {
// MARK: - Error
public enum VPhoneBundleActivityError: Error, Equatable {
- case running(name: String, pids: [pid_t])
+ /// The machine's state files are held open by `holders`, or its control
+ /// socket is live (then `holders` may be empty).
+ case running(name: String, holders: [VPhoneProcessHolder])
+
+ /// `running` with each process's executable looked up now.
+ public static func running(name: String, pids: [pid_t]) -> VPhoneBundleActivityError {
+ .running(name: name, holders: pids.map { VPhoneProcessHolder(pid: $0) })
+ }
}
extension VPhoneBundleActivityError: CustomStringConvertible, LocalizedError {
public var description: String {
switch self {
- case let .running(name, pids):
- let who = pids.isEmpty ? "" : " (process \(pids.map(String.init).joined(separator: ", ")))"
- return "VM '\(name)' is running\(who). Stop it, then try again."
+ case let .running(name, holders):
+ let (machine, others) = VPhoneProcessHolder.classify(holders)
+ guard machine.isEmpty, !others.isEmpty else {
+ let who = holders.isEmpty ? "" : " (process \(VPhoneProcessHolder.describe(machine + others)))"
+ return "VM '\(name)' is running\(who). Stop it, then try again."
+ }
+ // No VM process holds the files: say who does, so a backup tool
+ // or Launchpad's disk meter is not taken for a running VM.
+ return "VM '\(name)' is in use: its disk or state files are open in process "
+ + "\(VPhoneProcessHolder.describe(others)), which does not run it. "
+ + "Try again once that process closes them."
}
}
diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift
index c12e1859..912678b5 100644
--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift
+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift
@@ -56,6 +56,114 @@ public enum VPhoneLsof {
}
}
+// MARK: - VPhoneProcessHolder
+
+/// A process that has one of a machine's files open, and what it is, judged
+/// by its executable.
+///
+/// Many processes open a machine's `Disk.img` without running it: Launchpad's
+/// disk meter maps its extents for a moment every half minute, Spotlight and
+/// backup tools read it, and `vm template trim` or a rebase attach it. Only two
+/// kinds of process run a machine: `vphone-vm` (from any copy of the bundle)
+/// and Virtualization's VM service, which holds the disk for it. Those are the
+/// only ones `vm stop` may signal; every other holder is reported by name.
+public struct VPhoneProcessHolder: Equatable, Sendable, CustomStringConvertible {
+ public enum Kind: Equatable, Sendable {
+ /// `vphone-vm`, which runs the machine.
+ case virtualMachine
+ /// `com.apple.Virtualization.VirtualMachine`, the XPC service that
+ /// holds the machine's disk for its `vphone-vm`.
+ case virtualizationService
+ /// Anything else that has the file open.
+ case other
+ }
+
+ public var pid: pid_t
+ /// From `proc_pidpath`; nil for a process that is gone or cannot be
+ /// inspected.
+ public var executablePath: String?
+
+ public init(pid: pid_t, executablePath: String?) {
+ self.pid = pid
+ self.executablePath = executablePath
+ }
+
+ /// Looks the executable up now.
+ public init(pid: pid_t) {
+ self.init(pid: pid, executablePath: Self.executablePath(of: pid))
+ }
+
+ public var kind: Kind {
+ Self.kind(executablePath: executablePath)
+ }
+
+ /// Whether this process runs a machine, and may be stopped as one.
+ public var runsMachine: Bool {
+ kind != .other
+ }
+
+ /// The executable's file name, or `unknown`.
+ public var name: String {
+ executablePath.map { ($0 as NSString).lastPathComponent } ?? "unknown"
+ }
+
+ public var description: String {
+ "\(pid) \(name)"
+ }
+
+ static let virtualizationServiceName = "com.apple.Virtualization.VirtualMachine"
+
+ /// What an executable path is. `vphone-vm` counts from any folder: every
+ /// installed bundle has its own copy. The VM service counts only from
+ /// inside Virtualization.framework, so another program that takes its name
+ /// is still `other`.
+ public static func kind(executablePath: String?) -> Kind {
+ guard let executablePath, !executablePath.isEmpty else { return .other }
+ let components = (executablePath as NSString).pathComponents
+ switch components.last {
+ case "vphone-vm":
+ return .virtualMachine
+ case virtualizationServiceName where components.contains("Virtualization.framework"):
+ return .virtualizationService
+ default:
+ return .other
+ }
+ }
+
+ /// Splits holders into the ones that run a machine and the rest, each in
+ /// PID order.
+ public static func classify(_ holders: [VPhoneProcessHolder]) -> (machine: [VPhoneProcessHolder], others: [VPhoneProcessHolder]) {
+ let sorted = holders.sorted { $0.pid < $1.pid }
+ return (sorted.filter(\.runsMachine), sorted.filter { !$0.runsMachine })
+ }
+
+ /// `123 vphone-vm, 456 mds_stores`.
+ public static func describe(_ holders: [VPhoneProcessHolder]) -> String {
+ holders.map(\.description).joined(separator: ", ")
+ }
+
+ /// Why an operation that needs a machine's disk to itself (`cfw install`
+ /// and its variants) refuses, or nil when `holders` is empty. Every holder
+ /// refuses; the wording says whether one of them runs the machine.
+ /// `rerun` completes "…, then <rerun>.", for example "run cfw install again".
+ public static func diskRefusal(_ holders: [VPhoneProcessHolder], rerun: String) -> String? {
+ guard !holders.isEmpty else { return nil }
+ let (machine, others) = classify(holders)
+ if !machine.isEmpty {
+ return "The VM is running (process \(describe(machine + others))). Stop the VM, then \(rerun)."
+ }
+ return "The VM disk is open in process \(describe(others)), which does not run the VM. "
+ + "Wait for it to close the disk, then \(rerun)."
+ }
+
+ public 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)
+ }
+}
+
// MARK: - VPhoneGuestProcesses
/// Finds the `vphone-vm` that runs one machine.
diff --git a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/LaunchLayoutTests.swift b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/LaunchLayoutTests.swift
index 938fcf43..b69e774b 100644
--- a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/LaunchLayoutTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/LaunchLayoutTests.swift
@@ -14,6 +14,72 @@ struct LaunchLayoutTests {
#expect(VPhoneLsof.parsePIDs("") == [])
}
+ // MARK: - Disk holders
+
+ private static let service = "/System/Library/Frameworks/Virtualization.framework/Versions/A/XPCServices/"
+ + "com.apple.Virtualization.VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine"
+
+ @Test func `only vphone-vm and Virtualization's VM service count as running a machine`() {
+ let kind = VPhoneProcessHolder.kind(executablePath:)
+ #expect(kind("/Library/Application Support/vphone-launchpad/Bundles/2.9.0/VPhone.bundle/Contents/MacOS/vphone-vm") == .virtualMachine)
+ #expect(kind("/Users/me/vphone-cli/.build/XcodeBundle/Build/Products/Release/VPhone.bundle/Contents/MacOS/vphone-vm") == .virtualMachine)
+ #expect(kind(Self.service) == .virtualizationService)
+ // Processes that only open the disk.
+ #expect(kind("/Applications/vphone-launchpad.app/Contents/MacOS/vphone-launchpad") == .other)
+ #expect(kind("/System/Library/Frameworks/CoreServices.framework/Frameworks/Metadata.framework/Versions/A/Support/mds_stores") == .other)
+ #expect(kind("/usr/sbin/lsof") == .other)
+ #expect(kind("/Library/Application Support/vphone-launchpad/Bundles/2.9.0/VPhone.bundle/Contents/MacOS/vphone-cli") == .other)
+ // Another program that takes the service's name is not it.
+ #expect(kind("/tmp/com.apple.Virtualization.VirtualMachine") == .other)
+ #expect(kind("/tmp/vphone-vm-helper") == .other)
+ // A process that is gone or hidden is never signalled.
+ #expect(kind(nil) == .other)
+ #expect(kind("") == .other)
+ }
+
+ @Test func `holders split into the machine's processes and the rest, in PID order`() {
+ let holders = [
+ VPhoneProcessHolder(pid: 900, executablePath: "/Applications/vphone-launchpad.app/Contents/MacOS/vphone-launchpad"),
+ VPhoneProcessHolder(pid: 412, executablePath: Self.service),
+ VPhoneProcessHolder(pid: 77, executablePath: nil),
+ VPhoneProcessHolder(pid: 410, executablePath: "/opt/VPhone.bundle/Contents/MacOS/vphone-vm"),
+ ]
+ let (machine, others) = VPhoneProcessHolder.classify(holders)
+ #expect(machine.map(\.pid) == [410, 412])
+ #expect(others.map(\.pid) == [77, 900])
+ #expect(VPhoneProcessHolder.describe(others) == "77 unknown, 900 vphone-launchpad")
+ #expect(VPhoneProcessHolder.classify([]).machine.isEmpty)
+ }
+
+ @Test func `a disk refusal says whether the holder runs the machine`() throws {
+ #expect(VPhoneProcessHolder.diskRefusal([], rerun: "run cfw install again") == nil)
+ let meter = VPhoneProcessHolder(pid: 900, executablePath: "/Applications/vphone-launchpad.app/Contents/MacOS/vphone-launchpad")
+ let reader = try #require(VPhoneProcessHolder.diskRefusal([meter], rerun: "run cfw install again"))
+ #expect(reader.contains("900 vphone-launchpad"))
+ #expect(reader.contains("does not run the VM"))
+ #expect(!reader.contains("is running"))
+ #expect(reader.hasSuffix("then run cfw install again."))
+ let vm = VPhoneProcessHolder(pid: 412, executablePath: Self.service)
+ let running = try #require(VPhoneProcessHolder.diskRefusal([meter, vm], rerun: "run cfw install again"))
+ #expect(running.hasPrefix("The VM is running (process 412 com.apple.Virtualization.VirtualMachine, 900 vphone-launchpad)."))
+ }
+
+ @Test func `a running refusal names each holder's executable`() {
+ let meter = VPhoneProcessHolder(pid: 900, executablePath: "/Applications/vphone-launchpad.app/Contents/MacOS/vphone-launchpad")
+ let vm = VPhoneProcessHolder(pid: 410, executablePath: "/opt/VPhone.bundle/Contents/MacOS/vphone-vm")
+ let reader = VPhoneBundleActivityError.running(name: "lab", holders: [meter]).description
+ #expect(reader.hasPrefix("VM 'lab' is in use: its disk or state files are open in process 900 vphone-launchpad, which does not run it."))
+ let running = VPhoneBundleActivityError.running(name: "lab", holders: [meter, vm]).description
+ #expect(running == "VM 'lab' is running (process 410 vphone-vm, 900 vphone-launchpad). Stop it, then try again.")
+ // A live control socket with no visible holder (a VM under sudo).
+ #expect(VPhoneBundleActivityError.running(name: "lab", holders: []).description == "VM 'lab' is running. Stop it, then try again.")
+ // The PID form looks the executable up: this test process is no VM.
+ let me = VPhoneBundleActivityError.running(name: "lab", pids: [getpid()])
+ #expect(me == .running(name: "lab", holders: [VPhoneProcessHolder(pid: getpid())]))
+ #expect(VPhoneProcessHolder(pid: getpid()).executablePath != nil)
+ #expect(VPhoneProcessHolder(pid: getpid()).kind == .other)
+ }
+
// MARK: - Guest processes
/// A KERN_PROCARGS2 buffer as the kernel lays it out.