Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Stop the VM's vphone-vm in vm stop, not Virtualization's service

Jackybef54d354634
diff --git a/Research/Host/network_fixed_address.md b/Research/Host/network_fixed_address.md
index 9421ba74..30e04da6 100644
--- a/Research/Host/network_fixed_address.md
+++ b/Research/Host/network_fixed_address.md
@@ -97,6 +97,11 @@ its choosing. Three findings:
`192.168.72.0/24` was refused straight after one stop too. Only
`/usr/libexec/InternetSharing` (root) was involved; nothing in `vphone-vm`
was still alive.
+ (2026-10-05: the unexpected stop came from `vm stop` sending SIGINT to
+ Virtualization's service, the process holding the disk, rather than to
+ `vphone-vm`. `vm stop` now finds `vphone-vm` by its `--config` and stops
+ it, and the VM exits with status 0. Whether a subnet stays reserved after
+ such a stop has not been tested again.)
A fixed address that works for one launch is not a fixed address, so nat
accepts addresses on the shared network only (`Shared_Net_Address` and
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLaunchCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLaunchCommand.swift
index e1ca3123..77fd9109 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLaunchCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLaunchCommand.swift
@@ -113,20 +113,31 @@ struct VPhoneVirtualMachineStopCommand: ParsableCommand {
return VPhoneLsof.parsePIDs(r.stdout)
}
- let pids = runningPIDs()
- guard !pids.isEmpty else { print("\(name): not running"); return }
-
- print("\(name): sending SIGINT to \(pids.map(String.init).joined(separator: ", "))")
- for pid in pids {
+ // The disk is held by Virtualization's service, not by vphone-vm. A
+ // SIGINT to the service ends the VM under vphone-vm, which then exits
+ // 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 }
+
+ // 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
+ 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()
+ }
var waited = 0
- while waited < timeout, !runningPIDs().isEmpty {
+ while waited < timeout, !remaining().isEmpty {
Thread.sleep(forTimeInterval: 1)
waited += 1
}
- let survivors = runningPIDs()
+ let survivors = remaining()
if !survivors.isEmpty {
print("\(name): force-killing \(survivors.map(String.init).joined(separator: ", "))")
for pid in survivors {
diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift
index 11de75c5..1d890beb 100644
--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift
+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift
@@ -55,3 +55,87 @@ public enum VPhoneLsof {
return pids.sorted()
}
}
+
+// MARK: - VPhoneGuestProcesses
+
+/// Finds the `vphone-vm` that runs one machine.
+///
+/// The disk image is held open only by Virtualization's own XPC service, not
+/// by `vphone-vm`, so the processes `lsof` names for it are the wrong ones to
+/// stop: a SIGINT ends the service, and `vphone-vm` then sees its machine stop
+/// with an error. `vphone-vm` is told which machine to run by `--config`, and
+/// that argument is how it is found here.
+public enum VPhoneGuestProcesses {
+ /// Every `vphone-vm` of this user whose `--config` is `config`, compared
+ /// after resolving symbolic links on both sides.
+ public static func virtualMachinePIDs(config: URL) -> [Int32] {
+ let target = config.resolvingSymlinksInPath().standardizedFileURL.path
+ return allPIDs().filter { pid in
+ guard pid != getpid(), let arguments = arguments(of: pid) else { return false }
+ return runsMachine(arguments, configPath: target)
+ }
+ }
+
+ /// Whether an argument vector is a `vphone-vm` started with `--config`
+ /// at `configPath` (already resolved and standardized).
+ static func runsMachine(_ arguments: [String], configPath: String) -> Bool {
+ guard let executable = arguments.first,
+ (executable as NSString).lastPathComponent == "vphone-vm"
+ else { return false }
+ for (index, argument) in arguments.enumerated().dropFirst() {
+ let value: String
+ if argument == "--config", index + 1 < arguments.count {
+ value = arguments[index + 1]
+ } else if argument.hasPrefix("--config=") {
+ value = String(argument.dropFirst("--config=".count))
+ } else {
+ continue
+ }
+ let path = URL(fileURLWithPath: value).resolvingSymlinksInPath().standardizedFileURL.path
+ return path == configPath
+ }
+ return false
+ }
+
+ /// The argument vector in a `KERN_PROCARGS2` buffer: a 32-bit `argc`,
+ /// the executable path, NUL padding, then `argc` NUL-terminated strings.
+ static func parseProcessArguments(_ buffer: [UInt8]) -> [String]? {
+ guard buffer.count >= MemoryLayout<Int32>.size else { return nil }
+ let argc = buffer.withUnsafeBytes { Int($0.loadUnaligned(as: Int32.self)) }
+ guard argc > 0 else { return nil }
+ var index = MemoryLayout<Int32>.size
+ // Skip the executable path, then the padding after it.
+ while index < buffer.count, buffer[index] != 0 { index += 1 }
+ while index < buffer.count, buffer[index] == 0 { index += 1 }
+ var arguments: [String] = []
+ while arguments.count < argc, index < buffer.count {
+ let start = index
+ while index < buffer.count, buffer[index] != 0 { index += 1 }
+ arguments.append(String(decoding: buffer[start ..< index], as: UTF8.self))
+ index += 1
+ }
+ return arguments.count == argc ? arguments : nil
+ }
+
+ private static func allPIDs() -> [Int32] {
+ let count = proc_listallpids(nil, 0)
+ guard count > 0 else { return [] }
+ // Room for processes started between the two calls.
+ var pids = [Int32](repeating: 0, count: Int(count) + 64)
+ let filled = pids.withUnsafeMutableBytes {
+ proc_listallpids($0.baseAddress, Int32($0.count))
+ }
+ guard filled > 0 else { return [] }
+ return Array(pids.prefix(Int(filled))).filter { $0 > 0 }
+ }
+
+ /// Nil for a process that is gone or belongs to another user.
+ private static func arguments(of pid: Int32) -> [String]? {
+ var mib: [Int32] = [CTL_KERN, KERN_PROCARGS2, pid]
+ var size = 0
+ guard sysctl(&mib, 3, nil, &size, nil, 0) == 0, size > 0 else { return nil }
+ var buffer = [UInt8](repeating: 0, count: size)
+ guard sysctl(&mib, 3, &buffer, &size, nil, 0) == 0 else { return nil }
+ return parseProcessArguments(Array(buffer.prefix(size)))
+ }
+}
diff --git a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/LaunchLayoutTests.swift b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/LaunchLayoutTests.swift
index 199f251d..938fcf43 100644
--- a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/LaunchLayoutTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/LaunchLayoutTests.swift
@@ -14,6 +14,75 @@ struct LaunchLayoutTests {
#expect(VPhoneLsof.parsePIDs("") == [])
}
+ // MARK: - Guest processes
+
+ /// A KERN_PROCARGS2 buffer as the kernel lays it out.
+ private func processArguments(_ executable: String, _ arguments: [String], padding: Int = 3) -> [UInt8] {
+ var buffer = withUnsafeBytes(of: Int32(arguments.count).littleEndian, Array.init)
+ buffer += Array(executable.utf8) + [UInt8](repeating: 0, count: padding)
+ for argument in arguments {
+ buffer += Array(argument.utf8) + [0]
+ }
+ // The environment follows the arguments.
+ buffer += Array("HOME=/Users/test".utf8) + [0]
+ return buffer
+ }
+
+ @Test func `parses process arguments`() {
+ let path = "/Library/Bundles/VPhone.bundle/Contents/MacOS/vphone-vm"
+ let buffer = processArguments(path, [path, "--config", "/vms/a/config.plist"])
+ #expect(VPhoneGuestProcesses.parseProcessArguments(buffer) == [path, "--config", "/vms/a/config.plist"])
+ #expect(VPhoneGuestProcesses.parseProcessArguments([]) == nil)
+ #expect(VPhoneGuestProcesses.parseProcessArguments(Array(buffer.prefix(12))) == nil)
+ }
+
+ @Test func `matches only the vphone-vm of one machine`() throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ let machine = root.appendingPathComponent("machines/a")
+ try FileManager.default.createDirectory(at: machine, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let config = machine.appendingPathComponent("config.plist")
+ try Data().write(to: config)
+ let link = root.appendingPathComponent("link")
+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: root.appendingPathComponent("machines"))
+ let target = config.resolvingSymlinksInPath().standardizedFileURL.path
+ let vm = "/B/VPhone.bundle/Contents/MacOS/vphone-vm"
+
+ #expect(VPhoneGuestProcesses.runsMachine([vm, "--config", config.path], configPath: target))
+ #expect(VPhoneGuestProcesses.runsMachine([vm, "--headless", "--config=\(config.path)"], configPath: target))
+ // Another spelling of the same file.
+ #expect(VPhoneGuestProcesses.runsMachine([vm, "--config", link.path + "/a/config.plist"], configPath: target))
+ #expect(VPhoneGuestProcesses.runsMachine([vm, "--config", machine.path + "/../a/config.plist"], configPath: target))
+ // Another machine, another program, or no --config.
+ #expect(!VPhoneGuestProcesses.runsMachine([vm, "--config", root.path + "/machines/b/config.plist"], configPath: target))
+ #expect(!VPhoneGuestProcesses.runsMachine(["/usr/bin/vim", "--config", config.path], configPath: target))
+ #expect(!VPhoneGuestProcesses.runsMachine([vm, "--dfu"], configPath: target))
+ #expect(!VPhoneGuestProcesses.runsMachine([vm, "--config"], configPath: target))
+ #expect(!VPhoneGuestProcesses.runsMachine([], configPath: target))
+ }
+
+ @Test func `finds a running vphone-vm by its config`() throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ // A stand-in that lives long enough to be found under the right name.
+ let program = root.appendingPathComponent("vphone-vm")
+ try FileManager.default.copyItem(at: URL(fileURLWithPath: "/usr/bin/yes"), to: program)
+ let config = root.appendingPathComponent("config.plist")
+ let other = root.appendingPathComponent("other.plist")
+ let process = Process()
+ process.executableURL = program
+ // yes prints its arguments and blocks once the unread pipe fills.
+ process.arguments = ["--config", config.path]
+ process.standardOutput = Pipe()
+ try process.run()
+ defer { process.terminate() }
+ Thread.sleep(forTimeInterval: 0.2)
+
+ #expect(VPhoneGuestProcesses.virtualMachinePIDs(config: config) == [process.processIdentifier])
+ #expect(VPhoneGuestProcesses.virtualMachinePIDs(config: other).isEmpty)
+ }
+
@Test func `stage vphoned copies when source exists`() throws {
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
try FileManager.default.createDirectory(