Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Stop Launchpad copying the template match and pin its holder rule copy

Jacky9700aa5cf6f8
diff --git a/Research/Host/machine_templates.md b/Research/Host/machine_templates.md
index a11e2930..56d0b949 100644
--- a/Research/Host/machine_templates.md
+++ b/Research/Host/machine_templates.md
@@ -113,7 +113,12 @@ re-resolves with the template's own `PatchSelection.plist`.
rebuilt template counted the old build's clones as its users, in `vm
template list/show`, Launchpad's "N machine(s) use it" and the delete notes
(PR #633 retest, N1). `vm template list/show --json` add `build` and
- `frozenAt`. `vm template list/show` print the users with the template's
+ `frozenAt`. `vm list --json` and `vm info --json` report each clone's
+ `template` and `templateMatch` (`current`, `earlierBuild` or `deleted`,
+ `VPhoneMachineTemplates.match`), and Launchpad's inspector shows that
+ instead of reading `TemplateSource.plist` and `Template.plist` itself (see
+ [Rules Launchpad shares with the CLI](#rules-launchpad-shares-with-the-cli)).
+ `vm template list/show` print the users with the template's
allocated size; `vm delete` of the last machine cloned from the template
that exists now prints a note to delete it (`unusedTemplate(after:in:)`;
deleting a clone of an earlier build prints nothing), never deleting it
@@ -222,7 +227,8 @@ 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
+Launchpad does not link VPhoneCoreKit; both are tested against one table, see
+[Rules Launchpad shares with the CLI](#rules-launchpad-shares-with-the-cli)). 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
@@ -237,6 +243,61 @@ 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.
+### Rules Launchpad shares with the CLI
+
+PR #633 left two rules written twice, once in VPhoneCoreKit for `vphone-cli`
+and once in Launchpad: which disk holder runs a machine, and whether a clone
+came from the template that has its identifier now. Launchpad does not link
+VPhoneCoreKit on purpose. It ships apart from `VPhone.bundle`, works with
+every bundle of its series, and drives each machine through the `vphone-cli`
+of the bundle that machine is bound to; VPhoneCoreKit is that bundle's
+implementation and changes with every bundle build. Linking it (or a slice
+of it, through a project reference from `VPhoneLaunchpad.xcodeproj` to
+`VPhoneKit.xcodeproj`) would compile Launchpad's build-time copy of the rule
+in place of the answer of the bundle it is talking to, and would pull the
+kit's package graph (ArgumentParser, libarchive) into Launchpad's build. It
+moves the copy into the linker rather than removing it. So, as of
+2026-10-09:
+
+- **Template match: asked of the CLI.** `vm list --json` already read each
+ machine's `TemplateSource.plist` (`template`), and Launchpad already runs it
+ every 5 s for each library. It now also reports `templateMatch`, decided by
+ `VPhoneMachineTemplateSource.isClone(of:)` against the template that
+ `VPhoneMachineTemplates.template(_:in:)` loads, and Launchpad only decodes
+ it (`VPhoneLaunchpadMachine.templateOrigin`). Launchpad no longer reads
+ either plist. The copy had already drifted: it took any frozen
+ `Template.plist` whose identifier matched its folder, while the CLI also
+ requires the key to match and the folder to load as a machine, so a
+ damaged template counted as present in Launchpad and as deleted in the CLI.
+ A bundle that does not report `templateMatch`, or reports a value this
+ Launchpad does not know, leaves the Template row out. 2.9 was not released
+ when the field was added, so it is part of the 2.9 series contract
+ (`minimumBundleComponents`), not a new series.
+- **Disk holder kind: one table, two copies.** Launchpad runs `lsof` itself
+ over every listed machine on each refresh, every second while it waits for
+ a machine it did not start to stop, and right before an operation that
+ needs the disk, and it leaves its own disk meter out by PID. Asking
+ `vphone-cli` would add a process and a library-wide `lsof` to every
+ `vphone-cli vm list` for a ten-line path test that is a host fact, not bundle data.
+ The two copies stay, and both are tested against
+ `VPhoneKit/VPhoneCoreKitTests/VirtualMachine/ProcessHolderKinds.json`:
+ `LaunchLayoutTests` checks `VPhoneProcessHolder.kind`, and
+ `VPhoneLaunchpad/Tests/TemplatesTests.sh` checks
+ `VPhoneLaunchpadDiskHolder.runsMachine` (running for `virtualMachine` and
+ `virtualizationService`). Changing either copy without the table, or the
+ table without both copies, fails a test.
+
+Other places where Launchpad reads the bundle's own files or repeats its
+values, found while doing this and left as they are: `config.plist`
+(`diskImage` for `lsof`, `guestProductType` with a `FirmwareOriginals`
+fallback, read in both `VPhoneLaunchpadMachine` and `VPhoneLaunchpadIPSWCache`),
+`restore-info.json` (`variant`, for the unfinished-install check that
+mirrors `vm launch`), the `.templates` layout for the disk meter, the
+`vm delete` note text (`VPhoneLaunchpadTemplateNotice`), and New Machine's
+removable apps and default languages, which repeat
+`VPhoneTemplateSlimmingRequest.defaultRemovedApps` and
+`VPhoneSystemTrim.defaultKeptLanguages`.
+
## Never booting once frozen
The P0 measurement: booting a template after clones exist raised one clone's
diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleReport.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleReport.swift
index 05d503d7..89546191 100644
--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleReport.swift
+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleReport.swift
@@ -17,6 +17,12 @@ public struct VPhoneBundleReport: Codable, Equatable, Sendable {
/// The template the machine was cloned from (`TemplateSource.plist`),
/// or nil.
public let template: String?
+ /// Whether `template` is the build the machine was cloned from, an
+ /// earlier build since deleted, or deleted; nil when `template` is.
+ /// Launchpad reads it rather than the template records, so the rule
+ /// (``VPhoneMachineTemplateSource/isClone(of:)``) has one home. Added in
+ /// 2.9.0.
+ public let templateMatch: VPhoneMachineTemplateMatch?
/// Whether vphone-vm forwards the Mac's location to the guest. Always
/// present, like `unlocksAtStartup`.
public let syncsHostLocation: Bool
@@ -31,7 +37,11 @@ public struct VPhoneBundleReport: Codable, Equatable, Sendable {
customFirmwareInstalled = VPhoneRestoreInfo.customFirmwareInstalled(inBundle: bundle)
udid = VPhoneRestoreOperations.resolveUDID(bundle: bundle)
unlocksAtStartup = bundle.manifest.unlocksScreenAtStartup
- template = VPhoneMachineTemplates.readSource(inBundle: bundle.url)?.identifier
+ let source = VPhoneMachineTemplates.readSource(inBundle: bundle.url)
+ template = source?.identifier
+ // A machine lives directly in its library's root.
+ let library = VPhoneLibrary(root: bundle.url.deletingLastPathComponent())
+ templateMatch = source.map { VPhoneMachineTemplates.match(of: $0, in: library) }
syncsHostLocation = bundle.manifest.sharesHostLocation
}
}
diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineTemplates.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineTemplates.swift
index 6147b6fd..7fca9bc4 100644
--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineTemplates.swift
+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineTemplates.swift
@@ -140,6 +140,21 @@ public struct VPhoneMachineTemplateSource: Codable, Equatable, Sendable {
}
}
+/// How a machine's ``VPhoneMachineTemplateSource`` stands to the template
+/// that has its identifier in the library now. `vm list --json` and `vm info
+/// --json` report it as `templateMatch`, and Launchpad's inspector shows it
+/// from there, so the match is decided only here
+/// (``VPhoneMachineTemplateSource/isClone(of:)``).
+public enum VPhoneMachineTemplateMatch: String, Codable, Equatable, Sendable {
+ /// Cloned from the template that has the identifier now.
+ case current
+ /// Cloned from an earlier build with the same key, since deleted.
+ case earlierBuild
+ /// No template has the identifier now (or its record cannot be read, so
+ /// `vm template list` does not list it).
+ case deleted
+}
+
// MARK: - Sources
/// The IPSW sources a template was built from, as the create named them: a
@@ -867,6 +882,13 @@ public enum VPhoneMachineTemplates {
return source
}
+ /// Whether the template `source` names is still in `library` and is the
+ /// build the machine was cloned from.
+ public static func match(of source: VPhoneMachineTemplateSource, in library: VPhoneLibrary) -> VPhoneMachineTemplateMatch {
+ guard let template = try? template(source.identifier, in: library) else { return .deleted }
+ return source.isClone(of: template.record) ? .current : .earlierBuild
+ }
+
static func writeSource(_ source: VPhoneMachineTemplateSource, inBundle url: URL) throws {
let encoder = PropertyListEncoder()
encoder.outputFormat = .xml
diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift
index a0fb99cf..5c57b981 100644
--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift
+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift
@@ -117,6 +117,11 @@ public struct VPhoneProcessHolder: Equatable, Sendable, CustomStringConvertible
/// 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`.
+ ///
+ /// Launchpad, which does not link this kit, judges the holders its own
+ /// `lsof` finds with a copy (`VPhoneLaunchpadDiskHolder.runsMachine`).
+ /// Both are tested against `VPhoneCoreKitTests/VirtualMachine/
+ /// ProcessHolderKinds.json`: change the table and both copies together.
public static func kind(executablePath: String?) -> Kind {
guard let executablePath, !executablePath.isEmpty else { return .other }
let components = (executablePath as NSString).pathComponents
diff --git a/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleReportTests.swift b/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleReportTests.swift
index 8ba35ee7..501438f8 100644
--- a/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleReportTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleReportTests.swift
@@ -16,6 +16,8 @@ struct BundleReportTests {
#expect(report.cpuCount == 6)
#expect(report.memoryMB == 4096)
#expect(report.network.mode == .nat)
+ // Not cloned from a template.
+ #expect(report.template == nil && report.templateMatch == nil)
}
@Test func `carries network config`() throws {
diff --git a/VPhoneKit/VPhoneCoreKitTests/Bundle/MachineTemplatesTests.swift b/VPhoneKit/VPhoneCoreKitTests/Bundle/MachineTemplatesTests.swift
index b63f9bcc..80b36647 100644
--- a/VPhoneKit/VPhoneCoreKitTests/Bundle/MachineTemplatesTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/Bundle/MachineTemplatesTests.swift
@@ -688,10 +688,16 @@ struct MachineTemplatesTests {
let old = try VPhoneMachineTemplates.cloneMachine(from: first, to: "old", in: fixture.library)
#expect(VPhoneMachineTemplates.readSource(inBundle: old.url)?.build == firstBuild)
#expect(VPhoneMachineTemplates.usage(in: fixture.library) == [first.identifier: ["old"]])
+ // What `vm list --json` reports as `templateMatch`, and Launchpad shows.
+ func match(_ machine: VPhoneBundle) -> VPhoneMachineTemplateMatch? {
+ VPhoneBundleReport(bundle: machine).templateMatch
+ }
+ #expect(match(old) == .current)
// Deleted and built again under the same identifier, with a new build.
try VPhoneMachineTemplates.delete(first.identifier, in: fixture.library)
#expect(VPhoneMachineTemplates.usage(in: fixture.library) == [first.identifier: ["old"]])
+ #expect(match(old) == .deleted)
try makeMachine("src2", in: fixture)
let second = try VPhoneMachineTemplates.adopt(machineNamed: "src2", in: fixture.library, record: record(source: "src2"))
#expect(second.identifier == first.identifier)
@@ -700,6 +706,11 @@ struct MachineTemplatesTests {
let new = try VPhoneMachineTemplates.cloneMachine(from: second, to: "new", in: fixture.library)
#expect(VPhoneMachineTemplates.usage(in: fixture.library) == [second.identifier: ["new"]])
+ #expect(match(old) == .earlierBuild)
+ // The spelling Launchpad decodes.
+ let json = try String(decoding: JSONEncoder().encode(VPhoneBundleReport(bundle: old)), as: UTF8.self)
+ #expect(json.contains(#""templateMatch":"earlierBuild""#))
+ #expect(match(new) == .current)
// Deleting the old build's clone says nothing about the new template;
// deleting the new one's last clone does.
let oldSource = VPhoneMachineTemplates.readSource(inBundle: old.url)
@@ -755,6 +766,8 @@ struct MachineTemplatesTests {
VPhoneMachineTemplateSource(identifier: template.identifier, cloned: frozenAt + 1), inBundle: current.url,
)
#expect(VPhoneMachineTemplates.usage(in: fixture.library) == [template.identifier: ["current"]])
+ #expect(VPhoneBundleReport(bundle: earlier).templateMatch == .earlierBuild)
+ #expect(VPhoneBundleReport(bundle: current).templateMatch == .current)
}
@Test func `a record without a build reads, and a frozen one gets one`() throws {
diff --git a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/LaunchLayoutTests.swift b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/LaunchLayoutTests.swift
index b69e774b..9adfe377 100644
--- a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/LaunchLayoutTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/LaunchLayoutTests.swift
@@ -19,22 +19,35 @@ struct LaunchLayoutTests {
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)
+ /// `ProcessHolderKinds.json`, beside this file: the cases Launchpad's
+ /// copy of the rule (`VPhoneLaunchpadDiskHolder.runsMachine`) is tested
+ /// against too, so neither copy can change alone.
+ struct HolderKindCase: Decodable {
+ let path: String?
+ let kind: String
+ }
+
+ static func holderKindCases() throws -> [HolderKindCase] {
+ struct Table: Decodable {
+ let cases: [HolderKindCase]
+ }
+ let url = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("ProcessHolderKinds.json")
+ return try JSONDecoder().decode(Table.self, from: Data(contentsOf: url)).cases
+ }
+
+ @Test func `only vphone-vm and Virtualization's VM service count as running a machine`() throws {
+ let cases = try Self.holderKindCases()
+ #expect(cases.count >= 10)
+ for entry in cases {
+ let expected: VPhoneProcessHolder.Kind? = switch entry.kind {
+ case "virtualMachine": .virtualMachine
+ case "virtualizationService": .virtualizationService
+ case "other": .other
+ default: nil
+ }
+ #expect(expected != nil, "unknown kind \(entry.kind)")
+ #expect(VPhoneProcessHolder.kind(executablePath: entry.path) == expected, "\(entry.path ?? "nil")")
+ }
}
@Test func `holders split into the machine's processes and the rest, in PID order`() {
diff --git a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/ProcessHolderKinds.json b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/ProcessHolderKinds.json
new file mode 100644
index 00000000..9119f076
--- /dev/null
+++ b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/ProcessHolderKinds.json
@@ -0,0 +1,17 @@
+{
+ "about": "Which process holding a machine's disk runs the machine, judged by its executable path (proc_pidpath). The CLI's rule is VPhoneProcessHolder.kind(executablePath:) in VPhoneCoreKit; Launchpad, which does not link VPhoneCoreKit, has its own copy in VPhoneLaunchpadDiskHolder.runsMachine. VPhoneCoreKitTests (LaunchLayoutTests) and VPhoneLaunchpad/Tests/TemplatesTests.sh both run every case here against their copy, so a change to one copy fails the other's test until both agree. Kind is virtualMachine, virtualizationService or other; Launchpad counts the first two as running the machine. A null path is a process that is gone or cannot be inspected.",
+ "cases": [
+ { "path": "/Library/Application Support/vphone-launchpad/Bundles/2.9.0/VPhone.bundle/Contents/MacOS/vphone-vm", "kind": "virtualMachine" },
+ { "path": "/Users/me/vphone-cli/.build/XcodeBundle/Build/Products/Release/VPhone.bundle/Contents/MacOS/vphone-vm", "kind": "virtualMachine" },
+ { "path": "/System/Library/Frameworks/Virtualization.framework/Versions/A/XPCServices/com.apple.Virtualization.VirtualMachine.xpc/Contents/MacOS/com.apple.Virtualization.VirtualMachine", "kind": "virtualizationService" },
+ { "path": "/Applications/vphone-launchpad.app/Contents/MacOS/vphone-launchpad", "kind": "other" },
+ { "path": "/System/Library/Frameworks/CoreServices.framework/Frameworks/Metadata.framework/Versions/A/Support/mds_stores", "kind": "other" },
+ { "path": "/usr/bin/tail", "kind": "other" },
+ { "path": "/usr/sbin/lsof", "kind": "other" },
+ { "path": "/Library/Application Support/vphone-launchpad/Bundles/2.9.0/VPhone.bundle/Contents/MacOS/vphone-cli", "kind": "other" },
+ { "path": "/tmp/com.apple.Virtualization.VirtualMachine", "kind": "other" },
+ { "path": "/tmp/vphone-vm-helper", "kind": "other" },
+ { "path": "", "kind": "other" },
+ { "path": null, "kind": "other" }
+ ]
+}
diff --git a/VPhoneLaunchpad/Tests/TemplatesTests.sh b/VPhoneLaunchpad/Tests/TemplatesTests.sh
index 405467c7..67f3b748 100755
--- a/VPhoneLaunchpad/Tests/TemplatesTests.sh
+++ b/VPhoneLaunchpad/Tests/TemplatesTests.sh
@@ -8,6 +8,7 @@ trap '/bin/rm -rf "$temporary"' EXIT
/usr/bin/xcrun swiftc -swift-version 6 -strict-concurrency=complete \
-parse-as-library \
"$launchpad/VPhoneLaunchpadShared/VPhoneLaunchpadBundleStore.swift" \
+ "$launchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift" \
"$launchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift" \
"$launchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPlan.swift" \
"$launchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskUsage.swift" \
diff --git a/VPhoneLaunchpad/Tests/TemplatesTests.swift b/VPhoneLaunchpad/Tests/TemplatesTests.swift
index dcdece3e..fbeb4d14 100644
--- a/VPhoneLaunchpad/Tests/TemplatesTests.swift
+++ b/VPhoneLaunchpad/Tests/TemplatesTests.swift
@@ -489,61 +489,27 @@ struct TemplatesTests {
// MARK: - Template of a machine
/// Retest L2: a template deleted and built again keeps its identifier,
- /// so the inspector matches a machine to the build, as `vphone-cli` does.
+ /// so the inspector shows which build a machine came from. `vphone-cli`
+ /// decides it and `vm list --json` reports it as `templateMatch`
+ /// (`VPhoneMachineTemplates.match` in VPhoneCoreKit, tested there);
+ /// Launchpad only decodes it.
static func templateOrigins() throws {
- typealias Origin = VPhoneLaunchpadTemplateOrigin
- let id = "3c16c372ca03"
- let frozen = Date(timeIntervalSince1970: 1_791_453_600)
- let template = Origin.Template(identifier: id, build: "B2", created: frozen.addingTimeInterval(-3600), frozenAt: frozen)
-
- // Both records name a build: the build decides, not the dates.
- let current = Origin.Source(identifier: id, build: "B2", cloned: frozen.addingTimeInterval(60))
- precondition(Origin(current, template: template).match == .current, "Current build")
- let earlier = Origin.Source(identifier: id, build: "B1", cloned: frozen.addingTimeInterval(60))
- precondition(Origin(earlier, template: template).match == .earlierBuild, "Earlier build, cloned after the new one froze")
- precondition(Origin(earlier, template: template).identifier == id, "Identifier kept")
-
- // A clone record from before builds were recorded: the dates decide.
- let legacyAfter = Origin.Source(identifier: id, cloned: frozen)
- precondition(Origin(legacyAfter, template: template).match == .current, "Legacy clone at or after FrozenAt")
- let legacyBefore = Origin.Source(identifier: id, cloned: frozen.addingTimeInterval(-1))
- precondition(Origin(legacyBefore, template: template).match == .earlierBuild, "Legacy clone before FrozenAt")
- // A legacy template on the other side, with no FrozenAt: Created.
- let legacyTemplate = Origin.Template(identifier: id, created: frozen)
- precondition(Origin(current, template: legacyTemplate).match == .current, "Build on one side only, cloned after Created")
- precondition(Origin(legacyBefore, template: legacyTemplate).match == .earlierBuild, "Cloned before Created")
-
- precondition(Origin(current, template: nil).match == .deleted, "Template missing")
- precondition(!Origin.isClone(current, of: Origin.Template(identifier: "52b1fcc75e0c", build: "B2", created: frozen)), "Another identifier")
-
- // Read from the folders, as the library does.
- let root = FileManager.default.temporaryDirectory.appendingPathComponent("templates-origin-\(UUID().uuidString)", isDirectory: true)
- defer { try? FileManager.default.removeItem(at: root) }
- let machine = root.appendingPathComponent("e2e-a", isDirectory: true)
- let templateFolder = root.appendingPathComponent(".templates/\(id)", isDirectory: true)
- try FileManager.default.createDirectory(at: machine, withIntermediateDirectories: true)
- func write(_ plist: [String: Any], to file: URL) throws {
- try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0).write(to: file)
+ func machine(_ fields: String) throws -> VPhoneLaunchpadMachine {
+ let json = #"{"name":"e2e-a","cpuCount":8,"memoryMB":8192,"diskSizeBytes":64000000000,"network":{"mode":"nat","macAddress":"9a:84:18:78:7a:31"}"#
+ + fields + "}"
+ return try JSONDecoder().decode(VPhoneLaunchpadMachine.self, from: Data(json.utf8))
}
- func read() -> Origin? {
- Origin.read(machine: machine, libraryRoot: root.path)
+ let id = "3c16c372ca03"
+ for match in [VPhoneLaunchpadTemplateOrigin.Match.current, .earlierBuild, .deleted] {
+ let origin = try machine(#","template":"\#(id)","templateMatch":"\#(match.rawValue)""#).templateOrigin
+ precondition(origin == VPhoneLaunchpadTemplateOrigin(identifier: id, match: match), "\(match): \(String(describing: origin))")
}
- precondition(read() == nil, "Not a clone")
- try write(["Identifier": id, "Build": "B1", "Cloned": frozen.addingTimeInterval(60)], to: machine.appendingPathComponent("TemplateSource.plist"))
- precondition(read() == Origin(identifier: id, match: .deleted), "Template folder missing: \(String(describing: read()))")
- try FileManager.default.createDirectory(at: templateFolder, withIntermediateDirectories: true)
- let record: [String: Any] = ["Identifier": id, "Build": "B2", "Created": frozen, "Frozen": true, "FrozenAt": frozen]
- try write(record, to: templateFolder.appendingPathComponent("Template.plist"))
- precondition(read()?.match == .earlierBuild, "Rebuilt template")
- try write(record.merging(["Build": "B1"]) { $1 }, to: templateFolder.appendingPathComponent("Template.plist"))
- precondition(read()?.match == .current, "Same build")
- try write(record.merging(["Build": "B1", "Frozen": false]) { $1 }, to: templateFolder.appendingPathComponent("Template.plist"))
- precondition(read()?.match == .deleted, "A template never frozen is not listed")
- try write(["Identifier": id, "Cloned": frozen.addingTimeInterval(-60)], to: machine.appendingPathComponent("TemplateSource.plist"))
- try write(record.merging(["Build": "B1"]) { $1 }, to: templateFolder.appendingPathComponent("Template.plist"))
- precondition(read()?.match == .earlierBuild, "Legacy record read without Build, cloned before FrozenAt")
- try write(["Identifier": id], to: machine.appendingPathComponent("TemplateSource.plist"))
- precondition(read() == nil, "No Cloned: unreadable, as the CLI decodes it")
+ let plain = try machine("")
+ precondition(plain.templateOrigin == nil, "Not a clone")
+ let unsaid = try machine(#","template":"\#(id)""#)
+ precondition(unsaid.template == id && unsaid.templateOrigin == nil, "A bundle that does not say how it matches")
+ let unknown = try machine(#","template":"\#(id)","templateMatch":"later""#)
+ precondition(unknown.templateOrigin == nil, "A match this Launchpad does not know leaves the row out")
print("Template origin tests passed")
}
@@ -668,6 +634,27 @@ struct TemplatesTests {
precondition(!Holder(pid: 1, executablePath: nil).runsMachine && !Holder(pid: 1, executablePath: "").runsMachine,
"An unknown process never runs a machine")
+ // The table the CLI's `VPhoneProcessHolder.kind` is tested against.
+ struct Table: Decodable {
+ struct Case: Decodable {
+ let path: String?
+ let kind: String
+ }
+
+ let cases: [Case]
+ }
+ let tableURL = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
+ .appendingPathComponent("VPhoneKit/VPhoneCoreKitTests/VirtualMachine/ProcessHolderKinds.json")
+ guard let tableData = try? Data(contentsOf: tableURL), let table = try? JSONDecoder().decode(Table.self, from: tableData) else {
+ preconditionFailure("Cannot read \(tableURL.path)")
+ }
+ precondition(table.cases.count >= 10, "The shared table has its cases: \(table.cases.count)")
+ for entry in table.cases {
+ precondition(["virtualMachine", "virtualizationService", "other"].contains(entry.kind), "Unknown kind \(entry.kind)")
+ let runs = Holder(pid: 1, executablePath: entry.path).runsMachine
+ precondition(runs == (entry.kind != "other"), "\(entry.path ?? "nil") is \(entry.kind), runsMachine is \(runs)")
+ }
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()))
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
index be531db5..18b738ea 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
@@ -311,13 +311,15 @@
"network":{"mode":"nat","macAddress":"5a:94:ef:12:30:01"},
"restoreInfo":{"ios":{"version":"26.4.2","build":"23E261"},"cloudOS":{"version":"26.4","build":"23E224"},"variant":"jb","device":"iPhone99,11"},
"udid":"00008140-001A2B3C4D5E6F70",
- "unlocksAtStartup":true, "syncsHostLocation":true},
+ "unlocksAtStartup":true, "syncsHostLocation":true,
+ "template":"52b1fcc75e0c","templateMatch":"current"},
{"name":"ios27-rc","cpuCount":8,"memoryMB":12288,"diskSizeBytes":128000000000,
"network":{"mode":"nat","macAddress":"5a:94:ef:12:30:02"}},
{"name":"frida-lab","cpuCount":6,"memoryMB":8192,"diskSizeBytes":64000000000,
"network":{"mode":"bridged","macAddress":"5a:94:ef:12:30:03","bridgeInterface":"en0"},
"restoreInfo":{"ios":{"version":"26.6.2","build":"23G90"},"cloudOS":{"version":"26.4","build":"23E224"},"variant":"jb","device":"iPhone99,11"},
- "udid":"00008140-0011223344556677"}
+ "udid":"00008140-0011223344556677",
+ "template":"2246f982776c","templateMatch":"current"}
]
"""
var machines = (try? JSONDecoder().decode([VPhoneLaunchpadMachine].self, from: Data(json.utf8))) ?? []
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskHolder.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskHolder.swift
index 656e2cd4..dad32818 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskHolder.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadDiskHolder.swift
@@ -11,6 +11,14 @@ import Foundation
/// (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.
+///
+/// The rule is copied rather than asked of `vphone-cli`: Launchpad runs
+/// `lsof` itself on every refresh, while waiting for a stop and before an
+/// operation that needs the disk, and leaves its own meter out by PID. Both
+/// copies are tested against one table,
+/// `VPhoneKit/VPhoneCoreKitTests/VirtualMachine/ProcessHolderKinds.json`
+/// (`Tests/TemplatesTests.sh` here, `LaunchLayoutTests` there), so neither
+/// can change alone. See Research/Host/machine_templates.md.
nonisolated struct VPhoneLaunchpadDiskHolder: Hashable, Sendable, CustomStringConvertible {
var pid: pid_t
/// From `proc_pidpath`; nil for a process that is gone or cannot be
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift
index 969915dc..1367907a 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift
@@ -99,6 +99,14 @@ nonisolated struct VPhoneLaunchpadMachine: Decodable, Hashable, Identifiable, Se
/// Whether vphone-vm forwards the Mac's location to the guest. Nil from a
/// bundle older than the setting.
let syncsHostLocation: Bool?
+ /// The template the machine was cloned from, or nil.
+ let template: String?
+ /// How `template` stands to the template with that identifier now:
+ /// `current`, `earlierBuild` or `deleted`. `vphone-cli` decides it
+ /// (`VPhoneMachineTemplateSource.isClone(of:)`), so Launchpad never reads
+ /// the template records itself. A String, so a value this Launchpad
+ /// does not know leaves the row out rather than failing the list.
+ let templateMatch: String?
/// The library `vm list` was run on. Not part of the JSON.
var libraryRoot = ""
/// The guest's product type, such as iPad16,1, read by the library from
@@ -108,7 +116,7 @@ nonisolated struct VPhoneLaunchpadMachine: Decodable, Hashable, Identifiable, Se
private enum CodingKeys: String, CodingKey {
case name, cpuCount, memoryMB, diskSizeBytes, network, restoreInfo, customFirmwareInstalled, udid, unlocksAtStartup,
- syncsHostLocation
+ syncsHostLocation, template, templateMatch
}
/// The inspector's firmware line. A restore whose CFW install never
@@ -132,6 +140,15 @@ nonisolated struct VPhoneLaunchpadMachine: Decodable, Hashable, Identifiable, Se
return info["variant"] == nil
}
+ /// The inspector's Template row: nil for a machine not cloned from a
+ /// template, or when the bundle did not say how it matches.
+ var templateOrigin: VPhoneLaunchpadTemplateOrigin? {
+ guard let template, let match = templateMatch.flatMap(VPhoneLaunchpadTemplateOrigin.Match.init(rawValue:)) else {
+ return nil
+ }
+ return VPhoneLaunchpadTemplateOrigin(identifier: template, match: match)
+ }
+
var path: VPhoneLaunchpadMachinePath {
VPhoneLaunchpadMachinePath(libraryRoot: libraryRoot, name: name)
}
@@ -190,6 +207,30 @@ nonisolated struct VPhoneLaunchpadMachine: Decodable, Hashable, Identifiable, Se
}
}
+/// The template a machine was cloned from, as `vm list --json` reports it
+/// (`template` and `templateMatch`).
+///
+/// The identifier names a key, and a template deleted and built again gets
+/// the same one, but a clone of the earlier build shares no block and no key
+/// with the new template. Which of the two a machine came from is
+/// `vphone-cli`'s call (`VPhoneMachineTemplateSource.isClone(of:)`), made
+/// from `TemplateSource.plist` and `Template.plist`, which Launchpad does not
+/// read.
+nonisolated struct VPhoneLaunchpadTemplateOrigin: Hashable, Sendable {
+ /// `VPhoneMachineTemplateMatch`.
+ enum Match: String, Hashable, Sendable {
+ /// Cloned from the template that has the identifier now.
+ case current
+ /// Cloned from an earlier build with the same key, since deleted.
+ case earlierBuild
+ /// No template has the identifier now.
+ case deleted
+ }
+
+ let identifier: String
+ let match: Match
+}
+
// MARK: - fw catalog
/// Mirrors `VPhoneFirmwareCatalogReport` from `vphone-cli fw catalog --json`.
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift
index f8f7b003..f685b547 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift
@@ -171,7 +171,7 @@ struct VPhoneLaunchpadMachineInspector: View {
if let udid = machine.udid {
value("UDID", udid)
}
- if let origin = library.templateSources[machine.path] {
+ if let origin = machine.templateOrigin {
LabeledContent("Template") {
templateLabel(origin)
.textSelection(.enabled)
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
index eb1e241e..fd1c8c08 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
@@ -815,9 +815,6 @@ final class VPhoneLaunchpadMachineLibrary {
/// What each listed machine takes on disk, measured off the main actor
/// at most every `diskUsageInterval` seconds.
private(set) var diskUsage: [Path: VPhoneLaunchpadDiskUsage] = [:]
- /// The template each machine was cloned from (its `TemplateSource.plist`),
- /// and whether it is the build that has that identifier now.
- private(set) var templateSources: [Path: VPhoneLaunchpadTemplateOrigin] = [:]
private var diskUsageMeasured: Date?
private var isMeasuringDiskUsage = false
/// A forced measurement asked for while one ran.
@@ -861,7 +858,6 @@ final class VPhoneLaunchpadMachineLibrary {
mayOpenNow: mayOpenNow,
)
diskUsage = measured.usage
- templateSources = measured.sources
templateUsage = measured.templates
diskUsageMeasured = Date()
isMeasuringDiskUsage = false
@@ -910,7 +906,7 @@ final class VPhoneLaunchpadMachineLibrary {
templatesMayOpen: Bool,
meter: VPhoneLaunchpadDiskMeter,
mayOpenNow: @escaping @Sendable (String) async -> Bool,
- ) async -> (usage: [Path: VPhoneLaunchpadDiskUsage], sources: [Path: VPhoneLaunchpadTemplateOrigin], templates: [String: VPhoneLaunchpadDiskUsage]) {
+ ) async -> (usage: [Path: VPhoneLaunchpadDiskUsage], templates: [String: VPhoneLaunchpadDiskUsage]) {
// Templates are keyed as `usage(of:)` looks them up.
var templateKeys: [String: String] = [:]
for root in libraryRoots {
@@ -921,16 +917,14 @@ final class VPhoneLaunchpadMachineLibrary {
let folders = machineFolders + templateKeys.keys.sorted().map { VPhoneLaunchpadDiskMeter.Folder(path: $0, mayOpen: templatesMayOpen) }
let measured = await meter.measure(folders, mayOpenNow: mayOpenNow)
var usage: [Path: VPhoneLaunchpadDiskUsage] = [:]
- var sources: [Path: VPhoneLaunchpadTemplateOrigin] = [:]
for path in paths {
usage[path] = measured[path.url.path]
- sources[path] = VPhoneLaunchpadTemplateOrigin.read(machine: path.url, libraryRoot: path.libraryRoot)
}
var templates: [String: VPhoneLaunchpadDiskUsage] = [:]
for (folder, key) in templateKeys {
templates[key] = measured[folder]
}
- return (usage, sources, templates)
+ return (usage, templates)
}
// MARK: - Templates
@@ -1295,17 +1289,13 @@ final class VPhoneLaunchpadMachineLibrary {
})
}
- /// Disk use and template origins for the mock machines.
+ /// Disk use for the mock machines.
func applyPreviewDiskUsage() {
let research = VPhoneLaunchpadPreview.path("research-01")
diskUsage = [
research: VPhoneLaunchpadDiskUsage(allocated: 17_812_000_000, exclusive: 612_000_000),
VPhoneLaunchpadPreview.labMachine: VPhoneLaunchpadDiskUsage(allocated: 21_406_000_000, exclusive: 3_240_000_000),
]
- templateSources = [
- research: VPhoneLaunchpadTemplateOrigin(identifier: "52b1fcc75e0c", match: .current),
- VPhoneLaunchpadPreview.labMachine: VPhoneLaunchpadTemplateOrigin(identifier: "2246f982776c", match: .current),
- ]
diskUsageMeasured = Date()
}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift
index edf6516b..8642741c 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift
@@ -517,139 +517,6 @@ nonisolated struct VPhoneLaunchpadTemplateFind: Decodable, Sendable {
}
}
-// MARK: - Template of a machine
-
-/// The template a machine was cloned from, read from its
-/// `TemplateSource.plist`, and whether it is the template that has that
-/// identifier in its library now.
-///
-/// The identifier names a key, and a template deleted and built again gets
-/// the same one, but a clone of the earlier build shares no block and no key
-/// with the new template. The match is `vphone-cli`'s
-/// (`VPhoneMachineTemplateSource.isClone(of:)`).
-nonisolated struct VPhoneLaunchpadTemplateOrigin: Hashable, Sendable {
- enum Match: Hashable, Sendable {
- /// Cloned from the template that has the identifier now.
- case current
- /// Cloned from an earlier build with the same key, since deleted.
- case earlierBuild
- /// No template has the identifier now.
- case deleted
- }
-
- /// `TemplateSource.plist` (`VPhoneMachineTemplateSource`).
- struct Source: Hashable, Sendable {
- let identifier: String
- /// The build cloned from; nil in a record written before builds
- /// were recorded.
- let build: String?
- let cloned: Date
-
- init(identifier: String, build: String? = nil, cloned: Date) {
- self.identifier = identifier
- self.build = build
- self.cloned = cloned
- }
-
- init?(_ plist: [String: Any]) {
- guard let identifier = plist["Identifier"] as? String,
- identifier.wholeMatch(of: /[0-9a-f]{12}/) != nil,
- let cloned = plist["Cloned"] as? Date
- else {
- return nil
- }
- self.init(identifier: identifier, build: plist["Build"] as? String, cloned: cloned)
- }
- }
-
- /// What the match needs of a frozen template's `Template.plist`
- /// (`VPhoneMachineTemplateRecord`).
- struct Template: Hashable, Sendable {
- let identifier: String
- /// Nil for a template frozen before builds were recorded.
- let build: String?
- let created: Date
- let frozenAt: Date?
-
- init(identifier: String, build: String? = nil, created: Date, frozenAt: Date? = nil) {
- self.identifier = identifier
- self.build = build
- self.created = created
- self.frozenAt = frozenAt
- }
-
- /// Nil for a template the CLI does not list: never frozen, or not
- /// matching its folder name.
- init?(_ plist: [String: Any], folderName: String) {
- guard let identifier = plist["Identifier"] as? String, identifier == folderName,
- plist["Frozen"] as? Bool == true,
- let created = plist["Created"] as? Date
- else {
- return nil
- }
- self.init(identifier: identifier, build: plist["Build"] as? String, created: created, frozenAt: plist["FrozenAt"] as? Date)
- }
- }
-
- let identifier: String
- let match: Match
-
- init(identifier: String, match: Match) {
- self.identifier = identifier
- self.match = match
- }
-
- /// `template` is the one with the source's identifier in the machine's
- /// library, or nil when there is none.
- init(_ source: Source, template: Template?) {
- let match: Match = if let template {
- Self.isClone(source, of: template) ? .current : .earlierBuild
- } else {
- .deleted
- }
- self.init(identifier: source.identifier, match: match)
- }
-
- /// Both builds known decide it. Otherwise (a record on either side
- /// written before builds were recorded) a machine cloned before the
- /// template was frozen cannot have come from it.
- static func isClone(_ source: Source, of template: Template) -> Bool {
- guard source.identifier == template.identifier else {
- return false
- }
- if let build = source.build, let other = template.build {
- return build == other
- }
- return source.cloned >= (template.frozenAt ?? template.created)
- }
-
- /// The origin of the machine in `folder`, nil when it was not cloned
- /// from a template or its record cannot be read.
- static func read(machine folder: URL, libraryRoot: String) -> Self? {
- guard let source = plist(folder.appendingPathComponent("TemplateSource.plist")).flatMap(Source.init) else {
- return nil
- }
- let templateFolder = URL(fileURLWithPath: libraryRoot, isDirectory: true)
- .appendingPathComponent(".templates", isDirectory: true)
- .appendingPathComponent(source.identifier, isDirectory: true)
- let template = plist(templateFolder.appendingPathComponent("Template.plist")).flatMap {
- Template($0, folderName: source.identifier)
- }
- return Self(source, template: template)
- }
-
- /// A regular file's property list dictionary, not through a link.
- private static func plist(_ file: URL) -> [String: Any]? {
- guard let values = try? file.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey]),
- values.isRegularFile == true, values.isSymbolicLink != true,
- let data = try? Data(contentsOf: file)
- else {
- return nil
- }
- return (try? PropertyListSerialization.propertyList(from: data, format: nil)) as? [String: Any]
- }
-}
-
// MARK: - Last machine of a template
/// What `vm delete` notes when the machine was the last one cloned from a
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadBundleStore.swift b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadBundleStore.swift
index 6481195f..77a856e4 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadBundleStore.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadBundleStore.swift
@@ -84,7 +84,9 @@ nonisolated enum VPhoneLaunchpadNames {
/// `--work-parent` on `cfw install`, `update-environment` and
/// `update-kernel`, which the helper passes, and `vm template
/// find|trim|setup|adopt --json|list --json|delete` and `vm create
- /// --template --skip-first-boot`, which New Machine and Templates run.
+ /// --template --skip-first-boot`, which New Machine and Templates run,
+ /// and `template` and `templateMatch` in `vm list --json`, which a
+ /// machine's inspector shows.
private static let minimumBundleComponents = (2, 9, 0)
static let minimumBundleVersion =
"\(minimumBundleComponents.0).\(minimumBundleComponents.1).\(minimumBundleComponents.2)"