Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Tell a running machine from a stopped one before touching its state

Jacky673e9e9a9fe8
diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleActivity.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleActivity.swift
new file mode 100644
index 00000000..aee1c909
--- /dev/null
+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleActivity.swift
@@ -0,0 +1,136 @@
+import Darwin
+import Foundation
+
+// MARK: - Activity
+
+/// Whether a machine is in use, for operations that read or replace its state
+/// files and need them to stand still: cloning, snapshotting and reverting.
+///
+/// A running `vphone-vm` keeps the disk image, `SEPStorage` and `nvram.bin`
+/// open, and they move together: the SEP's anti-replay counters and the xART
+/// gigalocker on the disk advance as a pair. A copy of a running machine can
+/// take one at a different moment from the other, and the guest then panics in
+/// the SEP on its next boot. So the check looks for any process holding one of
+/// the three open, by device and inode rather than path. Another user's process
+/// (a VM started under sudo) cannot be inspected without root, so a live
+/// `vphone.sock` counts as running too.
+public enum VPhoneBundleActivity {
+ /// The files a running VM holds open, by their names inside the bundle.
+ public static func stateFileNames(of bundle: VPhoneBundle) -> [String] {
+ [bundle.manifest.diskImage, "SEPStorage", "nvram.bin"]
+ }
+
+ /// The processes of this user that have `url` open. Empty when the file is
+ /// missing or nobody holds it.
+ public static func processesHolding(_ url: URL) -> [pid_t] {
+ var target = stat()
+ guard stat(url.path, &target) == 0 else { return [] }
+ return allProcessIDs().filter { pid in
+ holds(pid: pid, device: target.st_dev, inode: target.st_ino)
+ }
+ }
+
+ /// True when a process holds one of the machine's state files open, or its
+ /// control socket answers.
+ public static func isRunning(_ bundle: VPhoneBundle) -> Bool {
+ !holders(of: bundle).isEmpty || controlSocketAnswers(bundle.url.appendingPathComponent("vphone.sock"))
+ }
+
+ /// Throws `VPhoneBundleActivityError.running` unless the machine is stopped.
+ public static func requireStopped(_ bundle: VPhoneBundle) throws {
+ let pids = holders(of: bundle)
+ if !pids.isEmpty || controlSocketAnswers(bundle.url.appendingPathComponent("vphone.sock")) {
+ throw VPhoneBundleActivityError.running(name: bundle.name, pids: pids)
+ }
+ }
+
+ // MARK: - Processes
+
+ private static func holders(of bundle: VPhoneBundle) -> [pid_t] {
+ var pids = Set<pid_t>()
+ for name in stateFileNames(of: bundle) {
+ pids.formUnion(processesHolding(bundle.url.appendingPathComponent(name)))
+ }
+ return pids.sorted()
+ }
+
+ private static func allProcessIDs() -> [pid_t] {
+ let count = proc_listallpids(nil, 0)
+ guard count > 0 else { return [] }
+ // Room for processes started between the two calls.
+ var pids = [pid_t](repeating: 0, count: Int(count) + 64)
+ let filled = pids.withUnsafeMutableBytes { buffer in
+ proc_listallpids(buffer.baseAddress, Int32(buffer.count))
+ }
+ guard filled > 0 else { return [] }
+ return Array(pids.prefix(Int(filled))).filter { $0 > 0 }
+ }
+
+ private static func holds(pid: pid_t, device: dev_t, inode: ino_t) -> Bool {
+ // EPERM for another user's process: it is skipped, and the socket
+ // probe covers the case that matters.
+ let size = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, nil, 0)
+ guard size > 0 else { return false }
+ let stride = MemoryLayout<proc_fdinfo>.stride
+ var fds = [proc_fdinfo](repeating: proc_fdinfo(), count: Int(size) / stride + 16)
+ let filled = fds.withUnsafeMutableBytes { buffer in
+ proc_pidinfo(pid, PROC_PIDLISTFDS, 0, buffer.baseAddress, Int32(buffer.count))
+ }
+ guard filled > 0 else { return false }
+ for fd in fds.prefix(Int(filled) / stride) where fd.proc_fdtype == UInt32(PROX_FDTYPE_VNODE) {
+ var info = vnode_fdinfo()
+ let got = proc_pidfdinfo(pid, fd.proc_fd, PROC_PIDFDVNODEINFO, &info, Int32(MemoryLayout<vnode_fdinfo>.size))
+ guard got == Int32(MemoryLayout<vnode_fdinfo>.size) else { continue }
+ let st = info.pvi.vi_stat
+ if dev_t(st.vst_dev) == device, ino_t(st.vst_ino) == inode {
+ return true
+ }
+ }
+ return false
+ }
+
+ // MARK: - Control socket
+
+ /// A stale socket file from a VM that exited refuses the connection.
+ private static func controlSocketAnswers(_ url: URL) -> Bool {
+ let path = url.path
+ var address = sockaddr_un()
+ let capacity = MemoryLayout.size(ofValue: address.sun_path)
+ guard path.utf8.count < capacity else { return false }
+ address.sun_family = sa_family_t(AF_UNIX)
+ withUnsafeMutableBytes(of: &address.sun_path) { buffer in
+ for (index, byte) in path.utf8.enumerated() {
+ buffer[index] = byte
+ }
+ }
+ let fd = socket(AF_UNIX, SOCK_STREAM, 0)
+ guard fd >= 0 else { return false }
+ defer { close(fd) }
+ let result = withUnsafePointer(to: &address) { pointer in
+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {
+ connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size))
+ }
+ }
+ return result == 0
+ }
+}
+
+// MARK: - Error
+
+public enum VPhoneBundleActivityError: Error, Equatable {
+ case running(name: String, pids: [pid_t])
+}
+
+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."
+ }
+ }
+
+ public var errorDescription: String? {
+ description
+ }
+}
diff --git a/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleActivityTests.swift b/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleActivityTests.swift
new file mode 100644
index 00000000..a6be6996
--- /dev/null
+++ b/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleActivityTests.swift
@@ -0,0 +1,89 @@
+import Darwin
+import Foundation
+import Testing
+@testable import VPhoneCoreKit
+
+/// Telling a running machine from a stopped one before its state files are
+/// copied or replaced.
+struct BundleActivityTests {
+ private func makeBundle() throws -> (root: URL, bundle: VPhoneBundle) {
+ let fm = FileManager.default
+ let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ try fm.createDirectory(at: root, withIntermediateDirectories: true)
+ let rom = root.appendingPathComponent("rom.bin")
+ try Data([0xAA]).write(to: rom)
+ let bundle = try VPhoneBundleOperations.create(
+ .init(name: "vm", cpuCount: 2, memoryMB: 1024, diskSizeGB: 1, romSource: rom, sepromSource: rom),
+ in: VPhoneLibrary(root: root),
+ )
+ try Data([1, 2, 3]).write(to: bundle.url.appendingPathComponent("nvram.bin"))
+ return (root, bundle)
+ }
+
+ @Test func `finds this process holding an open file`() throws {
+ let (root, bundle) = try makeBundle()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let disk = bundle.url.appendingPathComponent("Disk.img")
+
+ #expect(!VPhoneBundleActivity.processesHolding(disk).contains(getpid()))
+ let fd = open(disk.path, O_RDONLY)
+ #expect(fd >= 0)
+ #expect(VPhoneBundleActivity.processesHolding(disk).contains(getpid()))
+ close(fd)
+ #expect(!VPhoneBundleActivity.processesHolding(disk).contains(getpid()))
+ }
+
+ @Test func `a missing file has no holders`() {
+ let missing = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ #expect(VPhoneBundleActivity.processesHolding(missing).isEmpty)
+ }
+
+ @Test func `a stopped machine passes and a held state file refuses`() throws {
+ let (root, bundle) = try makeBundle()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ try VPhoneBundleActivity.requireStopped(bundle)
+ #expect(!VPhoneBundleActivity.isRunning(bundle))
+
+ for name in ["Disk.img", "SEPStorage", "nvram.bin"] {
+ let fd = open(bundle.url.appendingPathComponent(name).path, O_RDONLY)
+ #expect(fd >= 0)
+ #expect(VPhoneBundleActivity.isRunning(bundle))
+ #expect(throws: VPhoneBundleActivityError.running(name: "vm", pids: [getpid()])) {
+ try VPhoneBundleActivity.requireStopped(bundle)
+ }
+ close(fd)
+ }
+ }
+
+ @Test func `a listening control socket counts as running and a stale one does not`() throws {
+ let (root, bundle) = try makeBundle()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let path = bundle.url.appendingPathComponent("vphone.sock").path
+ // A socket path must fit sun_path; the temporary directory usually does.
+ try #require(path.utf8.count < 104)
+
+ let fd = socket(AF_UNIX, SOCK_STREAM, 0)
+ #expect(fd >= 0)
+ var address = sockaddr_un()
+ address.sun_family = sa_family_t(AF_UNIX)
+ withUnsafeMutableBytes(of: &address.sun_path) { buffer in
+ for (index, byte) in path.utf8.enumerated() {
+ buffer[index] = byte
+ }
+ }
+ let bound = withUnsafePointer(to: &address) { pointer in
+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {
+ bind(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size))
+ }
+ }
+ #expect(bound == 0)
+ #expect(listen(fd, 1) == 0)
+ #expect(VPhoneBundleActivity.isRunning(bundle))
+
+ // The socket file outlives the listener, as it does after a crash.
+ close(fd)
+ #expect(FileManager.default.fileExists(atPath: path))
+ #expect(!VPhoneBundleActivity.isRunning(bundle))
+ }
+}