Run a virtual iPhone on an Apple Silicon Mac.
Swift
Share one state-file list and one new-identity rule across clone and snapshots
Jacky8f2010074573
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineSnapshotCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineSnapshotCommand.swiftindex 7365a590..790bd150 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineSnapshotCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineSnapshotCommand.swift@@ -32,11 +32,15 @@ struct VPhoneVirtualMachineSnapshotCommand: ParsableCommand {)/// Local time, to the second: what `list` shows a person.- static func describe(_ date: Date) -> String {+ private static let dateFormatter: DateFormatter = {let formatter = DateFormatter()formatter.locale = Locale(identifier: "en_US_POSIX")formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"- return formatter.string(from: date)+ return formatter+ }()++ static func describe(_ date: Date) -> String {+ dateFormatter.string(from: date)}static func confirm(_ question: String) -> Bool {@@ -124,10 +128,10 @@ struct VPhoneVirtualMachineSnapshotRevertCommand: ParsableCommand {func run() throws {let bundle = try lib.library.bundle(named: vm)- // Refuse before asking, not after.let snapshot = try VPhoneMachineSnapshots.snapshot(named: name, of: bundle)- try VPhoneBundleActivity.requireStopped(bundle)if !force {+ // Refuse before asking, not after; revert checks again itself.+ try VPhoneBundleActivity.requireStopped(bundle)let taken = VPhoneVirtualMachineSnapshotCommand.describe(snapshot.created)guard VPhoneVirtualMachineSnapshotCommand.confirm("Revert '\(bundle.name)' to snapshot '\(snapshot.name)' from \(taken)? Everything the VM wrote since is lost.",@@ -156,12 +160,7 @@ struct VPhoneVirtualMachineSnapshotDeleteCommand: ParsableCommand {func run() throws {let bundle = try lib.library.bundle(named: vm)- try VPhoneMachineSnapshots.requireValidName(name)- guard FileManager.default.fileExists(- atPath: VPhoneMachineSnapshots.directory(of: bundle).appendingPathComponent(name).path,- ) else {- throw VPhoneMachineSnapshotError.notFound(machine: bundle.name, name: name)- }+ _ = try VPhoneMachineSnapshots.folder(named: name, of: bundle)if !force {guard VPhoneVirtualMachineSnapshotCommand.confirm("Delete snapshot '\(name)' of '\(bundle.name)'?",diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleActivity.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleActivity.swiftindex aee1c909..3ce0e45c 100644--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleActivity.swift+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleActivity.swift@@ -15,30 +15,16 @@ import Foundation/// (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.+ /// The files a running VM holds open, and the ones a clone, snapshot or+ /// revert must take together, 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"))+ [bundle.manifest.diskImage, bundle.manifest.sepStorage, bundle.manifest.nvramStorage]}/// Throws `VPhoneBundleActivityError.running` unless the machine is stopped.public static func requireStopped(_ bundle: VPhoneBundle) throws {- let pids = holders(of: bundle)+ let urls = stateFileNames(of: bundle).map { bundle.url.appendingPathComponent($0) }+ let pids = processesHolding(urls)if !pids.isEmpty || controlSocketAnswers(bundle.url.appendingPathComponent("vphone.sock")) {throw VPhoneBundleActivityError.running(name: bundle.name, pids: pids)}@@ -46,27 +32,27 @@ public enum VPhoneBundleActivity {// 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)))+ /// The processes of this user that have any of `urls` open, sorted. One+ /// pass over the process table, whatever the number of files; a missing+ /// file is held by nobody.+ static func processesHolding(_ urls: [URL]) -> [pid_t] {+ var targets = Set<FileID>()+ for url in urls {+ var info = stat()+ if stat(url.path, &info) == 0 {+ targets.insert(FileID(device: info.st_dev, inode: info.st_ino))+ }}- return pids.sorted()+ guard !targets.isEmpty else { return [] }+ return VPhoneGuestProcesses.allPIDs().filter { holds(pid: $0, anyOf: targets) }}- 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 struct FileID: Hashable {+ let device: dev_t+ let inode: ino_t}- private static func holds(pid: pid_t, device: dev_t, inode: ino_t) -> Bool {+ private static func holds(pid: pid_t, anyOf targets: Set<FileID>) -> 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)@@ -82,7 +68,7 @@ public enum VPhoneBundleActivity {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 {+ if targets.contains(FileID(device: dev_t(st.vst_dev), inode: ino_t(st.vst_ino))) {return true}}diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swiftindex d7a43a64..0dfcc4e2 100644--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift@@ -143,18 +143,26 @@ public enum VPhoneBundleOperations {}try FileManager.default.moveItem(at: src, to: dst)let renamed = try VPhoneBundle.load(at: dst)- // An mDNS name that `--mdns on` derived from the old name follows it;- // one chosen by hand stays.+ // A derived mDNS name follows the machine; one chosen by hand stays.let network = renamed.manifest.networkConfig- guard network.localHostName == VPhoneNetworking.localHostName(forVMName: name) else { return renamed }- let updated = renamed.manifest.updating(- networkConfig: network.with(localHostName: .some(VPhoneNetworking.localHostName(forVMName: newName))),- )+ guard let followed = localHostName(following: network.localHostName, from: name, to: newName) else {+ return renamed+ }+ let updated = renamed.manifest.updating(networkConfig: network.with(localHostName: .some(followed)))try updated.write(to: renamed.configURL)try VPhoneHostFilePermissions.makeAccessible(at: renamed.configURL)return VPhoneBundle(url: renamed.url, manifest: updated)}+ /// The mDNS name for a machine renamed or cloned from `oldName` to+ /// `newName`, when `name` is the one `--mdns on` derived from `oldName`.+ /// Nil for a name chosen by hand, or none.+ static func localHostName(following name: String?, from oldName: String, to newName: String) -> String? {+ name == VPhoneNetworking.localHostName(forVMName: oldName)+ ? VPhoneNetworking.localHostName(forVMName: newName)+ : nil+ }+public static func delete(bundleNamed name: String, in library: VPhoneLibrary) throws {let url = try library.bundle(named: name).urltry FileManager.default.removeItem(at: url)@@ -188,30 +196,39 @@ public enum VPhoneBundleOperations {}try VPhoneBundleActivity.requireStopped(source)- // APFS CoW clone; fall back to a plain recursive copy off-APFS.- if clonefile(src.path, dst.path, 0) != 0 {- try? fm.removeItem(at: dst) // clear any partial clonefile output first- try fm.copyItem(at: src, to: dst)- }// Roll back a half-made copy, so a retry with the same name is not// blocked by the alreadyExists check.do {- // A clone starts without snapshots: they record the source's- // history, not the copy's.- try removeIfPresent(dst.appendingPathComponent(VPhoneMachineSnapshots.directoryName))- // The source's control socket, stale since it stopped.- try removeIfPresent(dst.appendingPathComponent("vphone.sock"))+ // APFS CoW clone of the whole folder, then the entries a clone+ // drops are removed. Off APFS every byte is copied, so those are+ // never copied in the first place.+ if clonefile(src.path, dst.path, 0) == 0 {+ for entry in droppedFromClone {+ try removeIfPresent(dst.appendingPathComponent(entry))+ }+ } else {+ try? fm.removeItem(at: dst) // clear any partial clonefile output first+ try fm.createDirectory(at: dst, withIntermediateDirectories: false)+ for entry in try fm.contentsOfDirectory(atPath: src.path) where !droppedFromClone.contains(entry) {+ try fm.copyItem(at: src.appendingPathComponent(entry), to: dst.appendingPathComponent(entry))+ }+ }+ var clone = try VPhoneBundle.load(at: dst)if newIdentity {- try resetIdentity(of: VPhoneBundle.load(at: dst), clonedFrom: name)+ clone = try resetIdentity(of: clone, clonedFrom: name)}try VPhoneHostFilePermissions.makeAccessible(at: dst)- return try VPhoneBundle.load(at: dst)+ return clone} catch {try? fm.removeItem(at: dst)throw error}}+ /// Left out of every clone: snapshots record the source's history, not+ /// the copy's, and the control socket is the stopped source's.+ private static let droppedFromClone: Set<String> = [VPhoneMachineSnapshots.directoryName, "vphone.sock"]+/// The network settings a new-identity clone drops, described for display./// Each would collide with the source's when both run: a fixed address,/// host ports, and a `.local` name chosen by hand. A name `--mdns on`@@ -222,6 +239,17 @@ public enum VPhoneBundleOperations {_ network: VPhoneVirtualMachineManifest.NetworkConfig,sourceName: String,) -> [String] {+ newIdentityNetwork(network, from: sourceName, to: sourceName).cleared+ }++ /// The network settings of a new-identity clone named `newName`, and a+ /// description of each one dropped. One rule for both, so what the CLI+ /// reports is what was written.+ private static func newIdentityNetwork(+ _ network: VPhoneVirtualMachineManifest.NetworkConfig,+ from sourceName: String,+ to newName: String,+ ) -> (network: VPhoneVirtualMachineManifest.NetworkConfig, cleared: [String]) {var cleared: [String] = []if let ipv4 = network.ipv4 {cleared.append("fixed IPv4 address \(ipv4.address)/\(ipv4.prefixLength)")@@ -229,12 +257,17 @@ public enum VPhoneBundleOperations {if let forwards = network.portForwards, !forwards.isEmpty {cleared.append("port forwards \(forwards.map(\.description).joined(separator: ", "))")}- if let name = network.localHostName, !name.isEmpty,- name != VPhoneNetworking.localHostName(forVMName: sourceName)- {+ let followed = localHostName(following: network.localHostName, from: sourceName, to: newName)+ if followed == nil, let name = network.localHostName, !name.isEmpty {cleared.append("mDNS name \(name)")}- return cleared+ let updated = network.with(+ macAddress: "",+ ipv4: .some(nil),+ portForwards: .some(nil),+ localHostName: .some(followed),+ )+ return (updated, cleared)}/// Give a copied bundle a new identity on its next start.@@ -255,20 +288,12 @@ public enum VPhoneBundleOperations {/// ignores the ECID in the old tickets, and the SEP ROM accepts them too,/// so no re-personalization is needed. See/// `Research/Host/machine_identity_and_clone.md`.- static func resetIdentity(of bundle: VPhoneBundle, clonedFrom sourceName: String) throws {- let current = bundle.manifest.networkConfig- // A derived mDNS name follows the new machine name; one chosen by hand- // would collide with the source's and is dropped.- let derived = current.localHostName == VPhoneNetworking.localHostName(forVMName: sourceName)- let network = current.with(- macAddress: "",- ipv4: .some(nil),- portForwards: .some(nil),- localHostName: .some(derived ? VPhoneNetworking.localHostName(forVMName: bundle.name) : nil),- )+ static func resetIdentity(of bundle: VPhoneBundle, clonedFrom sourceName: String) throws -> VPhoneBundle {+ let network = newIdentityNetwork(bundle.manifest.networkConfig, from: sourceName, to: bundle.name).networklet updated = bundle.manifest.updating(machineIdentifier: Data(), networkConfig: network)try updated.write(to: bundle.configURL)try removeIfPresent(bundle.url.appendingPathComponent("udid-prediction.txt"))+ return VPhoneBundle(url: bundle.url, manifest: updated)}/// Remove a file, directory or link without following it; a missing onediff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineSnapshots.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineSnapshots.swiftindex 0fadaf56..08f779a3 100644--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineSnapshots.swift+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineSnapshots.swift@@ -7,7 +7,8 @@ import Foundation/// `<machine>/Snapshots/<name>/`. Not to be confused with/// `VPhoneAPFSSnapshot`, which renames the guest's own APFS root snapshot/// inside the disk image.-public struct VPhoneMachineSnapshot: Codable, Equatable, Sendable {+public struct VPhoneMachineSnapshot: Equatable, Sendable {+ /// The snapshot's folder name, which is not stored in its metadata.public let name: Stringpublic let created: Datepublic let note: String?@@ -20,20 +21,27 @@ public struct VPhoneMachineSnapshot: Codable, Equatable, Sendable {/// survive a revert to before it.public let absentFiles: [String]- public init(name: String, created: Date, note: String?, files: [String], absentFiles: [String]) {- self.name = name- self.created = created- self.note = note- self.files = files- self.absentFiles = absentFiles+ /// `Snapshot.plist`: everything but the name.+ fileprivate struct Metadata: Codable {+ let created: Date+ let note: String?+ let files: [String]+ let absentFiles: [String]++ enum CodingKeys: String, CodingKey {+ case created = "Created"+ case note = "Note"+ case files = "Files"+ case absentFiles = "AbsentFiles"+ }}- private enum CodingKeys: String, CodingKey {- case name = "Name"- case created = "Created"- case note = "Note"- case files = "Files"- case absentFiles = "AbsentFiles"+ fileprivate init(_ metadata: Metadata, name: String) {+ self.name = name+ created = metadata.created+ note = metadata.note+ files = metadata.files+ absentFiles = metadata.absentFiles}}@@ -64,12 +72,9 @@ public enum VPhoneMachineSnapshots {// MARK: State files- /// The files that must be captured, by their names in the machine folder.- public static func requiredStateFileNames(of bundle: VPhoneBundle) -> [String] {- [bundle.manifest.diskImage, bundle.manifest.sepStorage, bundle.manifest.nvramStorage]- }-- /// Captured when present, and recorded as absent otherwise.+ /// The disk image, `SEPStorage` and `nvram.bin` are always captured:+ /// `VPhoneBundleActivity.stateFileNames(of:)`. The files below are+ /// captured when present, and recorded as absent otherwise.////// The set is what changes after creation to describe the guest rather/// than the machine:@@ -101,14 +106,26 @@ public enum VPhoneMachineSnapshots {// MARK: Names- /// The same rules as a machine name: not empty, no `/`, not starting- /// with `.` (the staging directories are hidden).+ /// The same rules as a machine name (the staging directories are hidden,+ /// so a name cannot start with `.`), and one plain path component.public static func requireValidName(_ name: String) throws {- guard !name.isEmpty, !name.contains("/"), !name.hasPrefix("."), !name.contains("\0") else {+ guard (try? VPhoneBundleOperations.requireValidName(name)) != nil,+ VPhoneVirtualMachineManifest.isPlainFileName(name)+ else {throw VPhoneMachineSnapshotError.invalidName(name)}}+ /// The folder of an existing snapshot, whether or not its metadata reads.+ public static func folder(named name: String, of bundle: VPhoneBundle) throws -> URL {+ try requireValidName(name)+ let folder = directory(of: bundle).appendingPathComponent(name, isDirectory: true)+ guard isDirectory(folder) else {+ throw VPhoneMachineSnapshotError.notFound(machine: bundle.name, name: name)+ }+ return folder+ }+// MARK: List/// Every snapshot, oldest first. A directory whose metadata cannot be read@@ -125,12 +142,8 @@ public enum VPhoneMachineSnapshots {}public static func snapshot(named name: String, of bundle: VPhoneBundle) throws -> VPhoneMachineSnapshot {- try requireValidName(name)- let root = directory(of: bundle)- guard isDirectory(root.appendingPathComponent(name)) else {- throw VPhoneMachineSnapshotError.notFound(machine: bundle.name, name: name)- }- return try readMetadata(named: name, in: root)+ _ = try folder(named: name, of: bundle)+ return try readMetadata(named: name, in: directory(of: bundle))}// MARK: Create@@ -155,7 +168,7 @@ public enum VPhoneMachineSnapshots {var files: [String] = []var absent: [String] = []- for file in requiredStateFileNames(of: bundle) {+ for file in VPhoneBundleActivity.stateFileNames(of: bundle) {guard isRegularFile(bundle.url.appendingPathComponent(file)) else {throw VPhoneMachineSnapshotError.missingStateFile(machine: bundle.name, file: file)}@@ -180,8 +193,7 @@ public enum VPhoneMachineSnapshots {to: staging.appendingPathComponent(file),)}- let snapshot = VPhoneMachineSnapshot(- name: name,+ let metadata = VPhoneMachineSnapshot.Metadata(created: now,note: note.flatMap { $0.isEmpty ? nil : $0 },files: files,@@ -189,7 +201,7 @@ public enum VPhoneMachineSnapshots {)let encoder = PropertyListEncoder()encoder.outputFormat = .xml- try encoder.encode(snapshot).write(to: staging.appendingPathComponent(metadataFileName))+ try encoder.encode(metadata).write(to: staging.appendingPathComponent(metadataFileName))try VPhoneHostFilePermissions.makeAccessible(at: staging)// Exclusive: a snapshot of the same name made meanwhile is not replaced.guard renamex_np(staging.path, destination.path, UInt32(RENAME_EXCL)) == 0 else {@@ -199,7 +211,7 @@ public enum VPhoneMachineSnapshots {throw VPhoneMachineSnapshotError.failed(path: destination.path, reason: currentErrorText())}try VPhoneHostFilePermissions.makeDirectoryAccessible(at: root)- return snapshot+ return VPhoneMachineSnapshot(metadata, name: name)} catch {try? fm.removeItem(at: staging)removeIfEmpty(root)@@ -265,40 +277,26 @@ public enum VPhoneMachineSnapshots {/// Removes the snapshot directory and everything in it. The live state is/// not touched, so a running machine does not prevent it.public static func delete(_ name: String, of bundle: VPhoneBundle) throws {- try requireValidName(name)- let root = directory(of: bundle)- let target = root.appendingPathComponent(name, isDirectory: true)- guard isDirectory(target) else {- throw VPhoneMachineSnapshotError.notFound(machine: bundle.name, name: name)- }- try FileManager.default.removeItem(at: target)- removeIfEmpty(root)+ try FileManager.default.removeItem(at: folder(named: name, of: bundle))+ removeIfEmpty(directory(of: bundle))}// MARK: - Filesprivate static func readMetadata(named name: String, in root: URL) throws -> VPhoneMachineSnapshot {let url = root.appendingPathComponent(name).appendingPathComponent(metadataFileName)- let decoded: VPhoneMachineSnapshotdo {- decoded = try PropertyListDecoder().decode(VPhoneMachineSnapshot.self, from: Data(contentsOf: url))+ let metadata = try PropertyListDecoder().decode(VPhoneMachineSnapshot.Metadata.self, from: Data(contentsOf: url))+ return VPhoneMachineSnapshot(metadata, name: name)} catch {throw VPhoneMachineSnapshotError.damaged(name: name, reason: "\(metadataFileName) is unreadable")}- // The directory is the snapshot's name; the recorded one is informative.- return VPhoneMachineSnapshot(- name: name,- created: decoded.created,- note: decoded.note,- files: decoded.files,- absentFiles: decoded.absentFiles,- )}/// A file named in a snapshot's metadata is written into the machine/// folder on revert, so it must be one plain name and never the manifest.private static func requireStateFileName(_ file: String, snapshot: String) throws {- guard !file.isEmpty, !file.contains("/"), file != ".", file != "..",+ guard VPhoneVirtualMachineManifest.isPlainFileName(file),file != "config.plist", file != metadataFileName, file != directoryNameelse {throw VPhoneMachineSnapshotError.damaged(name: snapshot, reason: "it names the file '\(file)'")@@ -317,8 +315,7 @@ public enum VPhoneMachineSnapshots {}private static func isRegularFile(_ url: URL) -> Bool {- var info = stat()- return lstat(url.path, &info) == 0 && info.st_mode & S_IFMT == S_IFREG+ VPhoneVirtualMachineManifest.fileKind(at: url) == .regularFile}private static func isDirectory(_ url: URL) -> Bool {diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swiftindex 1d890beb..c12e1859 100644--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift@@ -117,7 +117,7 @@ public enum VPhoneGuestProcesses {return arguments.count == argc ? arguments : nil}- private static func allPIDs() -> [Int32] {+ static func allPIDs() -> [Int32] {let count = proc_listallpids(nil, 0)guard count > 0 else { return [] }// Room for processes started between the two calls.diff --git a/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleActivityTests.swift b/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleActivityTests.swiftindex a6be6996..73e968b8 100644--- a/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleActivityTests.swift+++ b/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleActivityTests.swift@@ -20,22 +20,26 @@ struct BundleActivityTests {return (root, bundle)}+ private func isRunning(_ bundle: VPhoneBundle) -> Bool {+ (try? VPhoneBundleActivity.requireStopped(bundle)) == nil+ }+@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()))+ #expect(!VPhoneBundleActivity.processesHolding([disk]).contains(getpid()))let fd = open(disk.path, O_RDONLY)#expect(fd >= 0)- #expect(VPhoneBundleActivity.processesHolding(disk).contains(getpid()))+ #expect(VPhoneBundleActivity.processesHolding([disk]).contains(getpid()))close(fd)- #expect(!VPhoneBundleActivity.processesHolding(disk).contains(getpid()))+ #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)+ #expect(VPhoneBundleActivity.processesHolding([missing]).isEmpty)}@Test func `a stopped machine passes and a held state file refuses`() throws {@@ -43,12 +47,12 @@ struct BundleActivityTests {defer { try? FileManager.default.removeItem(at: root) }try VPhoneBundleActivity.requireStopped(bundle)- #expect(!VPhoneBundleActivity.isRunning(bundle))+ #expect(!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(isRunning(bundle))#expect(throws: VPhoneBundleActivityError.running(name: "vm", pids: [getpid()])) {try VPhoneBundleActivity.requireStopped(bundle)}@@ -79,11 +83,11 @@ struct BundleActivityTests {}#expect(bound == 0)#expect(listen(fd, 1) == 0)- #expect(VPhoneBundleActivity.isRunning(bundle))+ #expect(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))+ #expect(!isRunning(bundle))}}diff --git a/VPhoneLaunchpad/Tests/MachineSnapshotsTests.swift b/VPhoneLaunchpad/Tests/MachineSnapshotsTests.swiftindex febd4d7a..d6e4f729 100644--- a/VPhoneLaunchpad/Tests/MachineSnapshotsTests.swift+++ b/VPhoneLaunchpad/Tests/MachineSnapshotsTests.swift@@ -25,13 +25,6 @@ struct MachineSnapshotsTests {let empty = try VPhoneLaunchpadMachineSnapshot.list(from: Data("[]".utf8))precondition(empty.isEmpty, "An empty list decodes")- // Fractional seconds and offsets are ISO 8601 too.- precondition(VPhoneLaunchpadMachineSnapshot.date(from: "2026-10-06T14:30:00.250Z")- == Date(timeIntervalSince1970: 1_791_297_000.25), "Fractional seconds")- precondition(VPhoneLaunchpadMachineSnapshot.date(from: "2026-10-06T22:30:00+08:00")- == Date(timeIntervalSince1970: 1_791_297_000), "A time zone offset")- precondition(VPhoneLaunchpadMachineSnapshot.date(from: "yesterday") == nil, "Not a date")-for bad in [#"[{"created":"yesterday","name":"x"}]"#,#"[{"created":"2026-10-06T14:30:00Z"}]"#,diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadCommandLine.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadCommandLine.swiftindex c3bfee14..97708b1f 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadCommandLine.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadCommandLine.swift@@ -12,6 +12,13 @@ nonisolated struct VPhoneLaunchpadError: LocalizedError {self.detail = detail}+ /// `error` as an action's failure: itself when it already is one, else+ /// "Unable to Complete Action" with the error's text under it.+ init(actionFailure error: any Error) {+ self = error as? VPhoneLaunchpadError+ ?? VPhoneLaunchpadError(String(localized: "Unable to Complete Action"), detail: error.localizedDescription)+ }+var errorDescription: String? {message}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swiftindex 9b7e2bdf..2b83e7df 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift@@ -307,6 +307,11 @@ final class VPhoneLaunchpadMachineLibrary {machines.filter { bundleVersion(for: $0.path) == version }.map(\.name)}+ /// The binding on disk, or the listed copy when the file cannot be read.+ private func currentBinding(of machine: Path) -> VPhoneLaunchpadMachineBinding? {+ VPhoneLaunchpadMachineBinding.load(machine) ?? bindings[machine]+ }+/// Writes a machine's binding and keeps the listed copy in step.func bind(_ machine: Path, _ binding: VPhoneLaunchpadMachineBinding) throws {try binding.save(to: machine)@@ -323,8 +328,7 @@ final class VPhoneLaunchpadMachineLibrary {return}for machine in machines {- var binding = VPhoneLaunchpadMachineBinding.load(machine)- ?? bindings[machine]+ var binding = currentBinding(of: machine)?? VPhoneLaunchpadMachineBinding(bundle: version)binding.bundle = versiondo {@@ -770,8 +774,7 @@ final class VPhoneLaunchpadMachineLibrary {return true} catch {if !(error is CancellationError) {- actionError = error as? VPhoneLaunchpadError- ?? VPhoneLaunchpadError(String(localized: "Unable to Complete Action"), detail: error.localizedDescription)+ actionError = VPhoneLaunchpadError(actionFailure: error)}return false}@@ -848,7 +851,7 @@ final class VPhoneLaunchpadMachineLibrary {)// The snapshot is taken either way; without the copy a revert only// leaves the binding as it is then.- if let binding = VPhoneLaunchpadMachineBinding.load(machine) ?? bindings[machine] {+ if let binding = currentBinding(of: machine) {try? binding.save(to: machine, snapshot: name)}}@@ -866,7 +869,7 @@ final class VPhoneLaunchpadMachineLibrary {// the copy saved with the snapshot. The bundle is not on the disk:// the machine keeps running with the one chosen now.if let saved = VPhoneLaunchpadMachineBinding.load(machine, snapshot: name),- let current = VPhoneLaunchpadMachineBinding.load(machine) ?? bindings[machine]+ let current = currentBinding(of: machine){try? bind(machine, current.reverted(to: saved))}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSnapshot.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSnapshot.swiftindex b7cc673f..65573679 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSnapshot.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSnapshot.swift@@ -14,26 +14,14 @@ nonisolated struct VPhoneLaunchpadMachineSnapshot: Decodable, Hashable, Identifiname}- /// Decodes the array `vm snapshot list --json` prints. `created` is- /// ISO 8601, with or without fractional seconds.+ /// Decodes the array `vm snapshot list --json` prints, whose `created`+ /// is written with JSONEncoder's `.iso8601`.static func list(from data: Data) throws -> [Self] {let decoder = JSONDecoder()- decoder.dateDecodingStrategy = .custom { decoder in- let container = try decoder.singleValueContainer()- let text = try container.decode(String.self)- guard let date = date(from: text) else {- throw DecodingError.dataCorruptedError(in: container, debugDescription: "Not an ISO 8601 date: \(text)")- }- return date- }+ decoder.dateDecodingStrategy = .iso8601return try decoder.decode([Self].self, from: data)}- static func date(from text: String) -> Date? {- (try? Date(text, strategy: .iso8601))- ?? (try? Date(text, strategy: Date.ISO8601FormatStyle(includingFractionalSeconds: true)))- }-/// The name Take Snapshot offers: the local date and time to the minute,/// `2026-10-06-2230`, with `-2`, `-3`… when that is taken. It follows the/// machine name rules, which snapshot names share.diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadSnapshotsView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadSnapshotsView.swiftindex a63d1003..5452365e 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadSnapshotsView.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadSnapshotsView.swift@@ -211,8 +211,7 @@ struct VPhoneLaunchpadSnapshotsView: View {try await action()} catch is CancellationError {} catch {- actionError = error as? VPhoneLaunchpadError- ?? VPhoneLaunchpadError(String(localized: "Unable to Complete Action"), detail: error.localizedDescription)+ actionError = VPhoneLaunchpadError(actionFailure: error)}await reload()}