Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

feat(vm): generate the VM manifest in Swift, drop vm_manifest.py

Lakrb1f5929a961e
diff --git a/scripts/vm_create.sh b/scripts/vm_create.sh
index 1ba93354..3f638c13 100755
--- a/scripts/vm_create.sh
+++ b/scripts/vm_create.sh
@@ -147,7 +147,21 @@ touch "${VM_DIR}/.gitkeep"
# --- Generate VM manifest ---
echo "[5/5] Generating VM manifest (config.plist)"
-"${SCRIPT_DIR}/vm_manifest.py" \
+# VPHONE_CLI_BIN is set when a vphone-cli subcommand invokes this script; the
+# fallbacks cover being run by hand from a dev tree or from inside the .app,
+# where scripts/ sits in Contents/Resources and the binaries are in MacOS.
+PROJ_ROOT="${SCRIPT_DIR:h}"
+VPHONE_CLI="${VPHONE_CLI_BIN:-}"
+if [[ -z "$VPHONE_CLI" ]]; then
+ for candidate in "${PROJ_ROOT}/.build/release/vphone-cli" "${PROJ_ROOT:h}/MacOS/vphone-cli"; do
+ [[ -x "$candidate" ]] && { VPHONE_CLI="$candidate"; break }
+ done
+fi
+[[ -x "$VPHONE_CLI" ]] || {
+ echo "ERROR: cannot find vphone-cli to generate the VM manifest"
+ exit 1
+}
+"$VPHONE_CLI" vm write-manifest \
--vm-dir "${VM_DIR}" \
--cpu "${CPU_COUNT}" \
--memory "${MEMORY_MB}" || {
diff --git a/scripts/vm_manifest.py b/scripts/vm_manifest.py
deleted file mode 100755
index 49a83e01..00000000
--- a/scripts/vm_manifest.py
+++ /dev/null
@@ -1,123 +0,0 @@
-#!/usr/bin/env python3
-"""
-vm_manifest.py — Generate VM manifest plist for vphone-cli.
-
-Compatible with security-pcc's VMBundle.Config format.
-"""
-
-from __future__ import annotations
-
-import argparse
-import plistlib
-import sys
-from pathlib import Path
-
-
-def create_manifest(
- vm_dir: Path,
- cpu_count: int,
- memory_mb: int,
- platform_fusing: str | None = None,
-):
- """
- Create a VM manifest plist file.
-
- Args:
- vm_dir: Path to VM directory
- cpu_count: Number of CPU cores
- memory_mb: Memory size in MB
- platform_fusing: Platform fusing mode (prod/dev) or None for auto-detect
- """
- # Convert to manifest units
- memory_bytes = memory_mb * 1024 * 1024
-
- # ROM filenames
- rom_file = "AVPBooter.vresearch1.bin"
- sep_rom_file = "AVPSEPBooter.vresearch1.bin"
-
- manifest = {
- "platformType": "vresearch101",
- "machineIdentifier": b"", # Generated on first boot, then persisted to manifest
- "cpuCount": cpu_count,
- "memorySize": memory_bytes,
- "screenConfig": {
- "width": 1290,
- "height": 2796,
- "pixelsPerInch": 460,
- "scale": 3.0,
- },
- "networkConfig": {
- "mode": "nat",
- "macAddress": "", # Auto-generated by Virtualization framework
- },
- "diskImage": "Disk.img",
- "nvramStorage": "nvram.bin",
- "romImages": {
- "avpBooter": rom_file,
- "avpSEPBooter": sep_rom_file,
- },
- "sepStorage": "SEPStorage",
- }
-
- if platform_fusing is not None:
- manifest["platformFusing"] = platform_fusing
-
- # Write to config.plist
- config_path = vm_dir / "config.plist"
- with open(config_path, "wb") as f:
- plistlib.dump(manifest, f)
-
- print(f"Created VM manifest: {config_path}")
- return config_path
-
-
-def main():
- parser = argparse.ArgumentParser(
- description="Generate VM manifest plist for vphone-cli"
- )
- parser.add_argument(
- "--vm-dir",
- type=Path,
- default=Path("vm"),
- help="VM directory path (default: vm)",
- )
- parser.add_argument(
- "--cpu",
- type=int,
- default=8,
- help="CPU core count (default: 8)",
- )
- parser.add_argument(
- "--memory",
- type=int,
- default=8192,
- help="Memory size in MB (default: 8192)",
- )
- parser.add_argument(
- "--platform-fusing",
- type=str,
- choices=["prod", "dev"],
- default=None,
- help="Platform fusing mode (default: auto-detect from host OS)",
- )
-
- args = parser.parse_args()
-
- if not args.vm_dir.exists():
- print(f"Error: VM directory does not exist: {args.vm_dir}", file=sys.stderr)
- sys.exit(1)
-
- try:
- create_manifest(
- vm_dir=args.vm_dir,
- cpu_count=args.cpu,
- memory_mb=args.memory,
- platform_fusing=args.platform_fusing,
- )
- except Exception as e:
- print(f"Error creating manifest: {e}", file=sys.stderr)
- sys.exit(1)
-
-
-if __name__ == "__main__":
- main()
diff --git a/sources/VPhoneCore/VPhoneBootCLI.swift b/sources/VPhoneCore/VPhoneBootCLI.swift
index 5e902bc0..6887ffec 100644
--- a/sources/VPhoneCore/VPhoneBootCLI.swift
+++ b/sources/VPhoneCore/VPhoneBootCLI.swift
@@ -19,6 +19,13 @@ public enum VPhoneVariant: String, Sendable, CaseIterable, ExpressibleByArgument
case exp
}
+// MARK: - Manifest values the CLI can take as arguments
+
+// Kept here, with the other ArgumentParser conformances, rather than beside
+// the type: the manifest is a data model and has no other reason to know that
+// a command line exists.
+extension VPhoneVirtualMachineManifest.PlatformFusing: ExpressibleByArgument {}
+
// MARK: - VPhoneBootCLI
/// The options for booting a guest.
diff --git a/sources/VPhoneCore/VPhoneVirtualMachineManifest.swift b/sources/VPhoneCore/VPhoneVirtualMachineManifest.swift
index 32ed5978..d715d27f 100644
--- a/sources/VPhoneCore/VPhoneVirtualMachineManifest.swift
+++ b/sources/VPhoneCore/VPhoneVirtualMachineManifest.swift
@@ -132,6 +132,12 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {
public let avpBooter: String
public let avpSEPBooter: String
+ /// The names `vm create` copies the ROMs in as.
+ public static let `default` = ROMImages(
+ avpBooter: "AVPBooter.vresearch1.bin",
+ avpSEPBooter: "AVPSEPBooter.vresearch1.bin"
+ )
+
public init(avpBooter: String, avpSEPBooter: String) {
self.avpBooter = avpBooter
self.avpSEPBooter = avpSEPBooter
@@ -166,6 +172,31 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {
self.sepStorage = sepStorage
}
+ // MARK: - Creation
+
+ /// The manifest a freshly created VM starts with.
+ ///
+ /// Replaces `scripts/vm_manifest.py`. Everything not named here is a
+ /// default that the guest or the framework fills in later:
+ /// `machineIdentifier` is empty until first boot persists one, and
+ /// `macAddress` is empty so Virtualization assigns it — forcing a MAC
+ /// breaks guest networking.
+ ///
+ /// `platformFusing` stays nil unless asked for, which leaves the key out
+ /// of the plist entirely and lets the host OS decide.
+ public static func newVM(
+ cpuCount: UInt = 8,
+ memoryMB: UInt64 = 8192,
+ platformFusing: PlatformFusing? = nil
+ ) -> VPhoneVirtualMachineManifest {
+ VPhoneVirtualMachineManifest(
+ platformFusing: platformFusing,
+ cpuCount: cpuCount,
+ memorySize: memoryMB * 1024 * 1024,
+ romImages: .default
+ )
+ }
+
// MARK: - Load/Save
/// Load manifest from a plist file
diff --git a/sources/vphone-cli/VPhoneVMCLI.swift b/sources/vphone-cli/VPhoneVMCLI.swift
index 060b680f..889e4feb 100644
--- a/sources/vphone-cli/VPhoneVMCLI.swift
+++ b/sources/vphone-cli/VPhoneVMCLI.swift
@@ -21,10 +21,59 @@ struct VPhoneVMCommand: ParsableCommand {
VPhoneVMLaunchCommand.self,
VPhoneVMStopCommand.self,
VPhoneVMCreateCommand.self,
+ VPhoneVMWriteManifestCommand.self,
]
)
}
+/// Replaces `scripts/vm_manifest.py`, called from `vm_create.sh` as its last
+/// step. Deliberately takes a directory rather than a library name: it runs
+/// while the bundle is still being assembled, before it is something the
+/// library would list.
+struct VPhoneVMWriteManifestCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "write-manifest",
+ abstract: "Write a fresh config.plist into a VM directory"
+ )
+
+ @Option(
+ name: .customLong("vm-dir"),
+ help: "VM directory to write config.plist into",
+ transform: URL.init(fileURLWithPath:)
+ )
+ var vmDirectory: URL = URL(fileURLWithPath: "vm")
+
+ @Option(name: .customLong("cpu"), help: "CPU core count")
+ var cpuCount: UInt = 8
+
+ @Option(name: .customLong("memory"), help: "Memory size in MB")
+ var memoryMB: UInt64 = 8192
+
+ @Option(
+ name: .customLong("platform-fusing"),
+ help: "prod or dev. Omit to let the host OS decide."
+ )
+ var platformFusing: VPhoneVirtualMachineManifest.PlatformFusing?
+
+ func run() throws {
+ var isDirectory: ObjCBool = false
+ guard FileManager.default.fileExists(
+ atPath: vmDirectory.path, isDirectory: &isDirectory
+ ), isDirectory.boolValue else {
+ throw ValidationError("VM directory does not exist: \(vmDirectory.path)")
+ }
+
+ let manifest = VPhoneVirtualMachineManifest.newVM(
+ cpuCount: cpuCount,
+ memoryMB: memoryMB,
+ platformFusing: platformFusing
+ )
+ let configURL = vmDirectory.appendingPathComponent("config.plist")
+ try manifest.write(to: configURL)
+ print("Created VM manifest: \(configURL.path)")
+ }
+}
+
// MARK: - Shared options
struct VPhoneLibraryOption: ParsableArguments {
diff --git a/tests/VPhoneCoreTests/NewVMManifestTests.swift b/tests/VPhoneCoreTests/NewVMManifestTests.swift
new file mode 100644
index 00000000..800d8c8b
--- /dev/null
+++ b/tests/VPhoneCoreTests/NewVMManifestTests.swift
@@ -0,0 +1,133 @@
+import Foundation
+import Testing
+@testable import VPhoneCore
+
+/// `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.
+///
+/// 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.
+@Suite("Fresh VM manifest")
+struct NewVMManifestTests {
+ @Test("defaults match the Python's")
+ func defaults() {
+ let m = VPhoneVirtualMachineManifest.newVM()
+
+ #expect(m.platformType == .vresearch101)
+ #expect(m.cpuCount == 8)
+ #expect(m.memorySize == 8192 * 1024 * 1024)
+ #expect(m.diskImage == "Disk.img")
+ #expect(m.nvramStorage == "nvram.bin")
+ #expect(m.sepStorage == "SEPStorage")
+ #expect(m.romImages?.avpBooter == "AVPBooter.vresearch1.bin")
+ #expect(m.romImages?.avpSEPBooter == "AVPSEPBooter.vresearch1.bin")
+ #expect(m.screenConfig.width == 1290)
+ #expect(m.screenConfig.height == 2796)
+ #expect(m.screenConfig.pixelsPerInch == 460)
+ #expect(m.screenConfig.scale == 3.0)
+ #expect(m.networkConfig.mode == .nat)
+ }
+
+ @Test("machineIdentifier starts empty, for first boot to fill in")
+ func machineIdentifierIsEmpty() {
+ #expect(VPhoneVirtualMachineManifest.newVM().machineIdentifier.isEmpty)
+ }
+
+ @Test("macAddress starts empty so the framework assigns one")
+ func macAddressIsEmpty() {
+ // Not cosmetic: forcing a MAC here breaks guest networking.
+ #expect(VPhoneVirtualMachineManifest.newVM().networkConfig.macAddress.isEmpty)
+ }
+
+ @Test("memory is MB in, bytes out")
+ func memoryConversion() {
+ #expect(VPhoneVirtualMachineManifest.newVM(memoryMB: 4096).memorySize == 4_294_967_296)
+ }
+
+ @Test("platformFusing is absent unless asked for")
+ func platformFusingOmitted() 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)
+ let parsed = try PropertyListSerialization.propertyList(
+ from: Data(contentsOf: url), format: nil
+ ) as? [String: Any]
+
+ // Absent, not null: the host OS decides when the key is missing.
+ #expect(parsed?["platformFusing"] == nil)
+ #expect(parsed?["bridgeInterface"] == nil)
+ }
+
+ @Test("platformFusing is written when asked for")
+ func platformFusingWritten() throws {
+ let url = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vphone-manifest-\(UUID().uuidString).plist")
+ defer { try? FileManager.default.removeItem(at: url) }
+
+ try VPhoneVirtualMachineManifest.newVM(platformFusing: .dev).write(to: url)
+ let parsed = try PropertyListSerialization.propertyList(
+ from: Data(contentsOf: url), format: nil
+ ) as? [String: Any]
+
+ #expect(parsed?["platformFusing"] as? String == "dev")
+ }
+
+ @Test("the exact key set the Python wrote")
+ func keySet() 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)
+ let parsed = try #require(PropertyListSerialization.propertyList(
+ from: Data(contentsOf: url), format: nil
+ ) as? [String: Any])
+
+ #expect(parsed.keys.sorted() == [
+ "cpuCount", "diskImage", "machineIdentifier", "memorySize",
+ "networkConfig", "nvramStorage", "platformType", "romImages",
+ "screenConfig", "sepStorage",
+ ])
+ }
+
+ @Test("what is written can be read back")
+ func roundTrips() throws {
+ let url = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vphone-manifest-\(UUID().uuidString).plist")
+ defer { try? FileManager.default.removeItem(at: url) }
+
+ let written = VPhoneVirtualMachineManifest.newVM(cpuCount: 4, memoryMB: 4096)
+ try written.write(to: url)
+ let read = try VPhoneVirtualMachineManifest.load(from: url)
+
+ #expect(read.cpuCount == 4)
+ #expect(read.memorySize == 4_294_967_296)
+ #expect(read.romImages?.avpBooter == written.romImages?.avpBooter)
+ #expect(read.networkConfig.mode == .nat)
+ }
+
+ @Test("cpuCount stays an integer, not a string")
+ func typesAreNotCoerced() 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)
+ let parsed = try #require(PropertyListSerialization.propertyList(
+ from: Data(contentsOf: url), format: nil
+ ) as? [String: Any])
+
+ // A number that becomes "8" parses fine and fails much later.
+ #expect(parsed["cpuCount"] is NSNumber)
+ #expect(parsed["cpuCount"] as? Int == 8)
+ #expect(parsed["memorySize"] is NSNumber)
+ #expect(parsed["machineIdentifier"] is Data)
+ }
+}
diff --git a/tests/VPhoneCoreTests/PlistEquivalence.swift b/tests/VPhoneCoreTests/PlistEquivalence.swift
new file mode 100644
index 00000000..8ade1204
--- /dev/null
+++ b/tests/VPhoneCoreTests/PlistEquivalence.swift
@@ -0,0 +1,116 @@
+import Foundation
+
+/// Compares two property lists for *semantic* equality.
+///
+/// Byte equality is the wrong bar for the plists in this migration, and not
+/// merely a strict one — it is unreachable. `plistlib.dump` and
+/// `PropertyListEncoder` disagree about `<data>` line width, `<real>`
+/// formatting, indentation and escaping, so matching bytes would mean
+/// reimplementing plistlib's writer to no purpose. Nothing downstream hashes
+/// or signs these files; every consumer parses them.
+///
+/// What does matter, and what this checks:
+///
+/// - **Type identity.** `Int` and `String` are not interchangeable. A version
+/// number that becomes `"26"` instead of `26` parses fine and then fails
+/// somewhere far away.
+/// - **Array order.** `BuildIdentities` and `SystemRestoreImageFileSystems`
+/// are ordered; position carries meaning.
+/// - **`Data` contents**, byte for byte.
+/// - **Exact key sets.** Neither extra keys nor missing ones.
+///
+/// Note `plutil -p` does not do this job: it parses and pretty-prints, so it
+/// is neither a byte comparison nor a typed one.
+enum PlistEquivalence {
+ /// A difference, described by where it is rather than just that it exists.
+ struct Difference: CustomStringConvertible, Equatable {
+ /// Key path into the plist, e.g. `BuildIdentities[0].Info.DeviceClass`.
+ let path: String
+ let detail: String
+
+ var description: String { "\(path.isEmpty ? "<root>" : path): \(detail)" }
+ }
+
+ static func differences(
+ between lhs: Any,
+ and rhs: Any,
+ at path: String = ""
+ ) -> [Difference] {
+ // Dictionaries: compare key sets first so a missing key is reported as
+ // a missing key, not as a mismatch at some deeper path.
+ if let l = lhs as? [String: Any], let r = rhs as? [String: Any] {
+ var found: [Difference] = []
+ let onlyLeft = Set(l.keys).subtracting(r.keys).sorted()
+ let onlyRight = Set(r.keys).subtracting(l.keys).sorted()
+ if !onlyLeft.isEmpty {
+ found.append(Difference(path: path, detail: "only on the left: \(onlyLeft.joined(separator: ", "))"))
+ }
+ if !onlyRight.isEmpty {
+ found.append(Difference(path: path, detail: "only on the right: \(onlyRight.joined(separator: ", "))"))
+ }
+ for key in Set(l.keys).intersection(r.keys).sorted() {
+ found += differences(
+ between: l[key]!, and: r[key]!,
+ at: path.isEmpty ? key : "\(path).\(key)"
+ )
+ }
+ return found
+ }
+
+ if let l = lhs as? [Any], let r = rhs as? [Any] {
+ guard l.count == r.count else {
+ return [Difference(path: path, detail: "\(l.count) elements on the left, \(r.count) on the right")]
+ }
+ return (0..<l.count).flatMap {
+ differences(between: l[$0], and: r[$0], at: "\(path)[\($0)]")
+ }
+ }
+
+ // Scalars. NSNumber is checked before the rest because a plist bool and
+ // a plist integer both arrive as NSNumber, and conflating them is
+ // exactly the class of bug this is here to catch.
+ if let l = lhs as? NSNumber, let r = rhs as? NSNumber {
+ let lIsBool = CFGetTypeID(l) == CFBooleanGetTypeID()
+ let rIsBool = CFGetTypeID(r) == CFBooleanGetTypeID()
+ if lIsBool != rIsBool {
+ return [Difference(
+ path: path,
+ detail: "one is a boolean and the other is a number (\(l) vs \(r))"
+ )]
+ }
+ return l == r ? [] : [Difference(path: path, detail: "\(l) vs \(r)")]
+ }
+
+ if let l = lhs as? String, let r = rhs as? String {
+ return l == r ? [] : [Difference(path: path, detail: "\"\(l)\" vs \"\(r)\"")]
+ }
+
+ if let l = lhs as? Data, let r = rhs as? Data {
+ if l == r { return [] }
+ return [Difference(
+ path: path,
+ detail: "data differs (\(l.count) vs \(r.count) bytes)"
+ )]
+ }
+
+ if let l = lhs as? Date, let r = rhs as? Date {
+ return l == r ? [] : [Difference(path: path, detail: "\(l) vs \(r)")]
+ }
+
+ return [Difference(
+ path: path,
+ detail: "different types: \(type(of: lhs)) vs \(type(of: rhs))"
+ )]
+ }
+
+ /// Parse two plist files and report every semantic difference.
+ static func differences(betweenFileAt lhs: URL, andFileAt rhs: URL) throws -> [Difference] {
+ let left = try PropertyListSerialization.propertyList(
+ from: Data(contentsOf: lhs), format: nil
+ )
+ let right = try PropertyListSerialization.propertyList(
+ from: Data(contentsOf: rhs), format: nil
+ )
+ return differences(between: left, and: right)
+ }
+}