Run a virtual iPhone on an Apple Silicon Mac.
Swift
feat: require v2 VM manifests for vphone 2.0.0
Lakr7155bbd1ede8
diff --git a/Sources/Info.plist b/Sources/Info.plistindex 1aed738d..760842d5 100644--- a/Sources/Info.plist+++ b/Sources/Info.plist@@ -16,9 +16,9 @@<key>CFBundlePackageType</key><string>APPL</string><key>CFBundleVersion</key>- <string>1</string>+ <string>2</string><key>CFBundleShortVersionString</key>- <string>1.0</string>+ <string>2.0.0</string><key>LSUIElement</key><true/><key>CFBundleIconFile</key>diff --git a/Sources/VPhoneCLI/VPhoneVirtualMachineCLI.swift b/Sources/VPhoneCLI/VPhoneVirtualMachineCLI.swiftindex 64d9afb2..e1516f50 100644--- a/Sources/VPhoneCLI/VPhoneVirtualMachineCLI.swift+++ b/Sources/VPhoneCLI/VPhoneVirtualMachineCLI.swift@@ -67,6 +67,16 @@ struct VPhoneVirtualMachineWriteManifestCommand: ParsableCommand {platformFusing: platformFusing,)let configURL = vmDirectory.appendingPathComponent("config.plist")+ if FileManager.default.fileExists(atPath: configURL.path) {+ // An existing VM must already be v2; do not turn a legacy VM into+ // a v2 VM by replacing only its manifest.+ _ = try VPhoneVirtualMachineManifest.load(from: configURL)+ } else if !((try FileManager.default.contentsOfDirectory(atPath: vmDirectory.path)).isEmpty) {+ throw ValidationError(+ "The VM directory contains data but has no config.plist. Recreate the VM in a new directory; "+ + "write-manifest cannot upgrade an existing VM.",+ )+ }try manifest.write(to: configURL)print("Created VM manifest: \(configURL.path)")}diff --git a/Sources/VPhoneCLI/VPhoneVirtualMachineLaunchCLI.swift b/Sources/VPhoneCLI/VPhoneVirtualMachineLaunchCLI.swiftindex da326b6c..d68ac0a1 100644--- a/Sources/VPhoneCLI/VPhoneVirtualMachineLaunchCLI.swift+++ b/Sources/VPhoneCLI/VPhoneVirtualMachineLaunchCLI.swift@@ -29,6 +29,12 @@ struct VPhoneVirtualMachineLaunchCommand: ParsableCommand {func run() throws {let v = VPhoneVerbosity(count: verboseCount)+ if name == nil {+ let scan = try lib.library.scan()+ if scan.bundles.isEmpty, let incompatible = scan.skipped.first {+ throw ValidationError("VM '\(incompatible.name)' cannot launch: \(incompatible.reason)")+ }+ }let name = try VPhoneVirtualMachineSelection.resolveExisting(name, in: lib.library)let bundle = try lib.library.bundle(named: name)let resources = projectRoot.map { VPhoneResources(base: URL(fileURLWithPath: $0)) } ?? .resolve()diff --git a/Sources/VPhoneCore/VPhoneBootCLI.swift b/Sources/VPhoneCore/VPhoneBootCLI.swiftindex 04b32b7a..9cd5f04d 100644--- a/Sources/VPhoneCore/VPhoneBootCLI.swift+++ b/Sources/VPhoneCore/VPhoneBootCLI.swift@@ -84,8 +84,9 @@ public struct VPhoneBootCLI: ParsableCommand {}public mutating func validate() throws {+ let manifest = try VPhoneVirtualMachineManifest.load(from: config)+ let bundle = VPhoneBundle(url: config.deletingLastPathComponent(), manifest: manifest)if !dfu,- let bundle = try? VPhoneBundle.load(at: config.deletingLastPathComponent()),let existingVariant = VPhoneRestoreInfo.load(fromBundle: bundle)?.variant,existingVariant != "jb"{diff --git a/Sources/VPhoneCore/VPhoneVirtualMachineManifest.swift b/Sources/VPhoneCore/VPhoneVirtualMachineManifest.swiftindex a3d5229e..5a39fb04 100644--- a/Sources/VPhoneCore/VPhoneVirtualMachineManifest.swift+++ b/Sources/VPhoneCore/VPhoneVirtualMachineManifest.swift@@ -5,6 +5,8 @@ import Foundationpublic enum VPhoneManifestError: Error {case loadFailed(path: String)case parseFailed(path: String)+ case unsupportedSchema(path: String, found: Int?)+ case unsupportedRuntimeVersion(String)case writeFailed(path: String)}@@ -15,6 +17,12 @@ extension VPhoneManifestError: CustomStringConvertible, LocalizedError {"Unable to read the VM configuration at \(path). Check that the file exists and try again."case let .parseFailed(path):"The VM configuration at \(path) is not valid. Recreate the VM, or restore a backup of config.plist."+ case let .unsupportedSchema(path, found):+ "The VM configuration at \(path) has \(found.map { "schema version \($0)" } ?? "no valid schema version"). "+ + "vphone 2.x requires schema version 2. Recreate this VM with `vphone-cli vm create`."+ case let .unsupportedRuntimeVersion(version):+ "This vphone build reports version \(version). VMs with schema version 2 require vphone 2.x. "+ + "Install a vphone 2.x build before launching this VM."case let .writeFailed(path):"Unable to save the VM configuration to \(path). Check that the file is writable and try again."}@@ -25,9 +33,40 @@ extension VPhoneManifestError: CustomStringConvertible, LocalizedError {}}+enum VPhoneRuntimeVersion {+ /// A plain `swift build` executable has no app bundle Info.plist.+ private static let unbundledVersion = "2.0.0"++ static var current: String {+ let contents = VPhoneResources.runningExecutable().deletingLastPathComponent().deletingLastPathComponent()+ guard contents.lastPathComponent == "Contents",+ contents.deletingLastPathComponent().pathExtension == "app"+ else { return unbundledVersion }++ let infoURL = contents.appendingPathComponent("Info.plist")+ guard let data = try? Data(contentsOf: infoURL),+ let plist = (try? PropertyListSerialization.propertyList(from: data, format: nil)) as? [String: Any],+ let version = plist["CFBundleShortVersionString"] as? String+ else { return "unknown" }+ return version+ }++ static func requireVersion2() throws {+ let parts = current.split(separator: ".", omittingEmptySubsequences: false)+ guard parts.count >= 2, parts[0] == "2", parts.dropFirst().allSatisfy({ Int($0) != nil }) else {+ throw VPhoneManifestError.unsupportedRuntimeVersion(current)+ }+ }+}+/// VPhoneVirtualMachineManifest represents the on-disk VM configuration manifest.-/// Structure is compatible with security-pcc's VMBundle.Config format.+/// Structure extends security-pcc's VMBundle.Config format with a vphone schema marker.public struct VPhoneVirtualMachineManifest: Codable, Sendable {+ public static let currentSchemaVersion = 2++ /// The VM layout version. Old bundles without this marker cannot be booted.+ public let schemaVersion: Int+// MARK: - Platform/// Platform type (fixed to vresearch101 for vphone)@@ -162,6 +201,7 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {romImages: ROMImages?,sepStorage: String = "SEPStorage",) {+ self.schemaVersion = Self.currentSchemaVersionself.platformType = platformTypeself.platformFusing = platformFusingself.machineIdentifier = machineIdentifier@@ -212,6 +252,12 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {}let decoder = PropertyListDecoder()+ struct SchemaMarker: Decodable { let schemaVersion: Int? }+ let marker = try? decoder.decode(SchemaMarker.self, from: data)+ guard marker?.schemaVersion == Self.currentSchemaVersion else {+ throw VPhoneManifestError.unsupportedSchema(path: url.path, found: marker?.schemaVersion)+ }+ try VPhoneRuntimeVersion.requireVersion2()do {return try decoder.decode(VPhoneVirtualMachineManifest.self, from: data)} catch {diff --git a/Tests/VPhoneCoreTests/NewVirtualMachineManifestTests.swift b/Tests/VPhoneCoreTests/NewVirtualMachineManifestTests.swiftindex 58f8efc9..74cf4b88 100644--- a/Tests/VPhoneCoreTests/NewVirtualMachineManifestTests.swift+++ b/Tests/VPhoneCoreTests/NewVirtualMachineManifestTests.swift@@ -4,14 +4,14 @@ import Testing/// `VPhoneVirtualMachineManifest.newVM` replaces `scripts/vm_manifest.py`.///-/// These assert the values the Python produced, because the file they write is-/// what every later boot reads: a wrong type or a missing key here surfaces as-/// a VM that will not start, some distance from the cause.+/// These assert the legacy values and the v2 schema marker, because the file+/// they write is what every later boot reads: a wrong type or a missing key+/// here surfaces as a VM that will not start, some distance from the cause.////// The equivalence itself was checked by running both versions and comparing/// the parsed plists key by key — identical for the default arguments and for-/// `--cpu 4 --memory 4096 --platform-fusing dev`. What is pinned below is the-/// result of that comparison, so it cannot drift once the Python is gone.+/// `--cpu 4 --memory 4096 --platform-fusing dev`. The v2 marker is deliberately+/// additional; the other values remain pinned to that comparison.@Suite("Fresh VM manifest")struct NewVirtualMachineManifestTests {@Test@@ -82,7 +82,7 @@ struct NewVirtualMachineManifestTests {}@Test- func `the exact key set the Python wrote`() throws {+ func `the exact v2 key set is written`() throws {let url = FileManager.default.temporaryDirectory.appendingPathComponent("vphone-manifest-\(UUID().uuidString).plist")defer { try? FileManager.default.removeItem(at: url) }@@ -96,8 +96,39 @@ struct NewVirtualMachineManifestTests {#expect(parsed.keys.sorted() == ["cpuCount", "diskImage", "machineIdentifier", "memorySize","networkConfig", "nvramStorage", "platformType", "romImages",- "screenConfig", "sepStorage",+ "schemaVersion", "screenConfig", "sepStorage",])+ #expect(parsed["schemaVersion"] as? Int == 2)+ }++ @Test+ func `manifest without v2 marker requires VM recreation`() throws {+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("vphone-manifest-\(UUID().uuidString).plist")+ defer { try? FileManager.default.removeItem(at: url) }++ try VPhoneVirtualMachineManifest.newVM().write(to: url)+ var parsed = try #require(PropertyListSerialization.propertyList(+ from: Data(contentsOf: url),+ format: nil,+ ) as? [String: Any])+ parsed.removeValue(forKey: "schemaVersion")+ let legacy = try PropertyListSerialization.data(fromPropertyList: parsed, format: .xml, options: 0)+ try legacy.write(to: url)++ do {+ _ = try VPhoneVirtualMachineManifest.load(from: url)+ Issue.record("A manifest without schemaVersion was accepted")+ } catch let error as VPhoneManifestError {+ if case let .unsupportedSchema(_, found) = error {+ #expect(found == nil)+ #expect(error.description.contains("Recreate this VM"))+ } else {+ Issue.record("Expected an unsupported schema error, got \(error)")+ }+ } catch {+ Issue.record("Expected a manifest error, got \(error)")+ }}@Test