Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

feat: drive the whole workflow through the vphone-cli binary

zqxwcecce78984944f
diff --git a/sources/vphone-cli/VPhoneCLI.swift b/sources/vphone-cli/VPhoneCLI.swift
index 38e5f904..e2e61d99 100644
--- a/sources/vphone-cli/VPhoneCLI.swift
+++ b/sources/vphone-cli/VPhoneCLI.swift
@@ -1,12 +1,16 @@
import ArgumentParser
import FirmwarePatcher
import Foundation
+import VPhoneCore
struct VPhoneCLI: ParsableCommand {
static let configuration = CommandConfiguration(
commandName: "vphone-cli",
abstract: "Boot a virtual iPhone or patch firmware with the Swift pipeline",
- subcommands: [VPhoneBootCLI.self, PatchFirmwareCLI.self, PatchComponentCLI.self],
+ subcommands: [
+ VPhoneBootCLI.self, PatchFirmwareCLI.self, PatchComponentCLI.self, VPhoneVMCommand.self,
+ VPhoneFWCommand.self, VPhoneRestoreCommand.self, VPhoneCFWCommand.self, VPhoneSetupCommand.self,
+ ],
defaultSubcommand: VPhoneBootCLI.self
)
}
@@ -30,12 +34,13 @@ struct VPhoneBootCLI: ParsableCommand {
)
@Option(
+ name: .shortAndLong,
help: "Path to VM manifest plist (config.plist). Required.",
transform: URL.init(fileURLWithPath:)
)
var config: URL
- @Flag(help: "Boot into DFU mode")
+ @Flag(name: .shortAndLong, help: "Boot into DFU mode")
var dfu: Bool = false
@Option(help: "Kernel GDB debug stub port on host (omit for system-assigned port; valid: 6000...65535)")
@@ -43,8 +48,8 @@ struct VPhoneBootCLI: ParsableCommand {
@Option(help: "Path to signed vphoned binary for guest auto-update")
var vphonedBin: String = ".vphoned.signed"
-
- @Option(help: "Firmware variant to execute.")
+
+ @Option(name: [.customShort("V"), .long], help: "Firmware variant to execute.")
var variant: PatchFirmwareCLI.VariantOption = .regular
@Option(
@@ -155,7 +160,7 @@ struct PatchFirmwareCLI: ParsableCommand {
)
var vmDirectory: URL
- @Option(help: "Firmware variant to patch.")
+ @Option(name: [.customShort("V"), .long], help: "Firmware variant to patch.")
var variant: VariantOption = .regular
@Option(
@@ -164,7 +169,7 @@ struct PatchFirmwareCLI: ParsableCommand {
)
var recordsOut: String?
- @Flag(name: .customLong("quiet"), help: "Suppress per-component progress output.")
+ @Flag(name: [.customShort("q"), .customLong("quiet")], help: "Suppress per-component progress output.")
var quiet: Bool = false
@Flag(name: .customLong("no-binpack"), help: "Exclude the SSH, VNC, ... binaries from being installed (patchless-only).")
@@ -223,20 +228,20 @@ struct PatchComponentCLI: ParsableCommand {
var component: ComponentOption
@Option(
- name: .customLong("input"),
+ name: [.customShort("i"), .customLong("input")],
help: "Path to the source firmware file (IM4P or raw).",
transform: URL.init(fileURLWithPath:)
)
var input: URL
@Option(
- name: .customLong("output"),
+ name: [.customShort("o"), .customLong("output")],
help: "Path to write the patched raw payload bytes.",
transform: URL.init(fileURLWithPath:)
)
var output: URL
- @Flag(name: .customLong("quiet"), help: "Suppress per-patch progress output.")
+ @Flag(name: [.customShort("q"), .customLong("quiet")], help: "Suppress per-patch progress output.")
var quiet: Bool = false
@Option(
diff --git a/sources/vphone-cli/VPhoneControl.swift b/sources/vphone-cli/VPhoneControl.swift
index 47a4054d..e5982b72 100644
--- a/sources/vphone-cli/VPhoneControl.swift
+++ b/sources/vphone-cli/VPhoneControl.swift
@@ -1,6 +1,7 @@
import CryptoKit
import Foundation
import Virtualization
+import VPhoneCore
/// Host-side client for the vphoned guest agent.
///
@@ -118,23 +119,8 @@ class VPhoneControl {
}
private static func signCertURL() -> URL? {
- let fm = FileManager.default
- let candidates = [
- Bundle.main.resourceURL?.appendingPathComponent("signcert.p12"),
- Bundle.main.bundleURL.appendingPathComponent("Contents/Resources/signcert.p12"),
- URL(fileURLWithPath: fm.currentDirectoryPath).appendingPathComponent(
- "scripts/vphoned/signcert.p12"
- ),
- URL(fileURLWithPath: fm.currentDirectoryPath).appendingPathComponent(
- "../scripts/vphoned/signcert.p12"
- ),
- ]
- for candidate in candidates.compactMap(\.self) {
- if fm.fileExists(atPath: candidate.path) {
- return candidate
- }
- }
- return nil
+ let signcert = VPhoneResources.resolve().signcert
+ return FileManager.default.fileExists(atPath: signcert.path) ? signcert : nil
}
// MARK: - Guest Binary Hash
diff --git a/sources/vphone-cli/VPhoneCreateOrchestrator.swift b/sources/vphone-cli/VPhoneCreateOrchestrator.swift
new file mode 100644
index 00000000..485437f2
--- /dev/null
+++ b/sources/vphone-cli/VPhoneCreateOrchestrator.swift
@@ -0,0 +1,535 @@
+import FirmwarePatcher
+import Foundation
+import VPhoneCore
+
+// MARK: - VPhoneCreateError
+
+/// Failure points across the native `vm create` pipeline — the `die()` call
+/// sites of `scripts/setup_machine.sh`'s `main()` / `load_device_identity` /
+/// `wait_for_recovery` / `wait_for_first_boot_prompt_auto` / `run_boot_analysis`.
+private enum VPhoneCreateError: Error, CustomStringConvertible {
+ case nestedVirtualization
+ case unknownVariant(String)
+ case lessRequiresRoot
+ case fwPrepareFailed(Int32)
+ case identityTimedOut(URL)
+ case invalidUDID(String)
+ case invalidECID(String)
+ case udidECIDMismatch(udid: String, ecid: String)
+ case recoveryTimeout
+ case restoreGetSHSHFailed(Int32)
+ case restoreUpdateFailed(Int32)
+ case cfwInstallFailed(Int32)
+ case firstBootPanic
+ case firstBootExitedBeforePrompt(Int32)
+ case bootAnalysisPanic
+ case bootAnalysisExited(Int32)
+ case bootAnalysisTimeout
+ case lessBootFailed(Int32)
+
+ var description: String {
+ switch self {
+ case .nestedVirtualization:
+ "Virtualization.framework guest boot is unavailable inside a VM — run vm create on a non-nested macOS 15+ host"
+ case let .unknownVariant(v):
+ "unknown variant '\(v)' (regular|dev|jb|exp|less)"
+ case .lessRequiresRoot:
+ "fw patch for 'less' must be run as root (matches Makefile's `fw_patch_less must be run via sudo`)"
+ case let .fwPrepareFailed(code):
+ "fw prepare failed (exit \(code))"
+ case let .identityTimedOut(path):
+ "missing \(path.path); rebuild and retry to regenerate it"
+ case let .invalidUDID(v):
+ "invalid UDID in udid-prediction.txt: '\(v)'"
+ case let .invalidECID(v):
+ "invalid ECID in udid-prediction.txt: '\(v)'"
+ case let .udidECIDMismatch(udid, ecid):
+ "UDID/ECID mismatch in udid-prediction.txt: \(udid) vs 0x\(ecid)"
+ case .recoveryTimeout:
+ "timed out waiting for the recovery/DFU endpoint"
+ case let .restoreGetSHSHFailed(code):
+ "restore-get-shsh failed (exit \(code))"
+ case let .restoreUpdateFailed(code):
+ "restore-update failed (exit \(code))"
+ case let .cfwInstallFailed(code):
+ "CFW install failed (exit \(code))"
+ case .firstBootPanic:
+ "first boot panicked before command injection"
+ case let .firstBootExitedBeforePrompt(code):
+ "first boot exited before command injection (exit \(code))"
+ case .bootAnalysisPanic:
+ "boot analysis: panic detected"
+ case let .bootAnalysisExited(code):
+ "boot analysis: process exited before success marker (exit \(code))"
+ case .bootAnalysisTimeout:
+ "boot analysis timed out"
+ case let .lessBootFailed(code):
+ "start VM (less) failed (exit \(code))"
+ }
+ }
+}
+
+extension VPhoneCreateError: LocalizedError {
+ var errorDescription: String? { description }
+}
+
+// MARK: - VPhoneCreateOrchestrator
+
+/// Native port of `scripts/setup_machine.sh`'s `main()` — runs the full
+/// `vm create` pipeline (prepare → patch → restore → CFW → first boot → boot
+/// analysis) with no `make`/`setup_machine.sh` shell-out.
+///
+/// Lives in the EXECUTABLE target rather than VPhoneCore because it composes
+/// `FirmwarePatcher.FirmwarePipeline`, and `FirmwarePatcher` already depends on
+/// `VPhoneCore` (Package.swift) — VPhoneCore importing FirmwarePatcher back
+/// would be a package dependency cycle. The regex/ECID primitives this type
+/// needs to be independently unit-testable live in VPhoneCore instead, as
+/// `VPhoneBootPatterns`, where `VPhoneCoreTests` (which depends only on
+/// VPhoneCore) can reach them.
+public struct VPhoneCreateOrchestrator {
+ public struct Options {
+ public var name: String
+ public var variant: String
+ public var iphoneSource: String?
+ public var cloudosSource: String?
+ public var sudoPassword: String?
+ public var spoofBuild: String?
+ public var forceDSCMaxSlide: Bool
+ public var interactive: Bool
+ public var cpuCount: UInt
+ public var memoryMB: UInt64
+ public var diskSizeGB: UInt64
+ public var verbosity: VPhoneVerbosity
+
+ public init(
+ name: String,
+ variant: String,
+ iphoneSource: String? = nil,
+ cloudosSource: String? = nil,
+ sudoPassword: String? = nil,
+ spoofBuild: String? = nil,
+ forceDSCMaxSlide: Bool = false,
+ interactive: Bool = false,
+ cpuCount: UInt = 8,
+ memoryMB: UInt64 = 8192,
+ diskSizeGB: UInt64 = 64,
+ verbosity: VPhoneVerbosity = .quiet
+ ) {
+ self.name = name
+ self.variant = variant
+ self.iphoneSource = iphoneSource
+ self.cloudosSource = cloudosSource
+ self.sudoPassword = sudoPassword
+ self.spoofBuild = spoofBuild
+ self.forceDSCMaxSlide = forceDSCMaxSlide
+ self.interactive = interactive
+ self.cpuCount = cpuCount
+ self.memoryMB = memoryMB
+ self.diskSizeGB = diskSizeGB
+ self.verbosity = verbosity
+ }
+ }
+
+ private let library: VPhoneLibrary
+ private let resources: VPhoneResources
+ private let selfExecutable: URL
+
+ public init(library: VPhoneLibrary, resources: VPhoneResources, selfExecutable: URL) {
+ self.library = library
+ self.resources = resources
+ self.selfExecutable = selfExecutable
+ }
+
+ // MARK: - run
+
+ public func run(_ options: Options) throws {
+ let v = options.verbosity
+ // Fail fast on a nested-VM host — PV=3 guest boot can't nest, and the whole
+ // create pipeline (download + patch + restore) is wasted otherwise. Mirrors
+ // the boot_host_preflight gate that `make boot` applied.
+ if try Self.isNestedVMHost() {
+ throw VPhoneCreateError.nestedVirtualization
+ }
+
+ guard let variantOption = PatchFirmwareCLI.VariantOption(rawValue: options.variant) else {
+ throw VPhoneCreateError.unknownVariant(options.variant)
+ }
+ let isLess = variantOption == .less
+
+ let bundleURL = library.url(forName: options.name)
+ if FileManager.default.fileExists(atPath: bundleURL.path) {
+ throw VPhoneLibraryError.alreadyExists(name: options.name)
+ }
+
+ // setup_sudo_noninteractive: preload an askpass helper so CFW install's
+ // internal `sudo -A` re-exec can run unattended.
+ var sudoEnvExtras: [String: String] = [:]
+ var askpassScript: URL?
+ defer { if let askpassScript { try? FileManager.default.removeItem(at: askpassScript) } }
+ if let password = options.sudoPassword, !password.isEmpty {
+ let script = try makeSudoAskpassScript(password: password)
+ askpassScript = script
+ sudoEnvExtras = ["SUDO_ASKPASS": script.path, "SUDO_PASSWORD": password]
+ preloadSudoCredential(env: sudoEnvExtras, verbosity: v)
+ }
+
+ print("\n=== vm new ===")
+ let spec = VPhoneBundleOps.NewBundleSpec(
+ name: options.name, cpuCount: options.cpuCount, memoryMB: options.memoryMB,
+ diskSizeGB: options.diskSizeGB,
+ romSource: VPhoneBundleOps.defaultROMSource(), sepromSource: VPhoneBundleOps.defaultSEPROMSource())
+ let bundle = try VPhoneBundleOps.create(spec, in: library)
+ print("created \(bundle.url.path)")
+
+ print("\n=== fw prepare ===")
+ try runFWPrepare(options: options, isLess: isLess, bundleURL: bundleURL)
+
+ print("\n=== fw patch ===")
+ try runFWPatch(variant: variantOption, isLess: isLess, bundleURL: bundleURL, verbosity: v)
+
+ print("\n=== Restore phase ===")
+ try runRestorePhase(bundleURL: bundleURL, verbosity: v)
+
+ if !isLess {
+ print("[*] Waiting 5s for cleanup before CFW install...")
+ Thread.sleep(forTimeInterval: 5)
+ print("\n=== CFW install (host-mount) ===")
+ try runCFWInstall(options: options, bundleURL: bundleURL, sudoEnvExtras: sudoEnvExtras)
+ }
+
+ print("\n=== First boot ===")
+ try runFirstBoot(options: options, isLess: isLess, bundleURL: bundleURL)
+
+ if variantOption == .jb || variantOption == .exp {
+ print("\n=== JB Finalize ===")
+ print("[*] JB finalization will run automatically on first normal boot")
+ print(" via /cores/vphone_jb_setup.sh (LaunchDaemon).")
+ print(" Monitor progress via vphoned file browser: /var/log/vphone_jb_setup.log")
+ }
+
+ print("\n=== Done ===")
+ print("Setup completed.")
+
+ print("\n=== Boot analysis ===")
+ if isLess {
+ try startVMForeground(bundleURL: bundleURL, verbosity: v)
+ } else {
+ try runBootAnalysis(bundleURL: bundleURL, verbosity: v)
+ }
+ }
+
+ // MARK: - trace
+
+ /// Internal spawn/outcome trace, gated on `.trace` (`-vvv`). Never prints
+ /// secret env VALUES (e.g. SUDO_PASSWORD) — callers pass only key names.
+ private func trace(_ msg: String, _ v: VPhoneVerbosity) {
+ guard v.tracesInternals else { return }
+ print("[trace] \(msg)")
+ }
+
+ /// `-v` repeated `min(v.rawValue, 2)` times, for the pmd3 bridge's own
+ /// `--verbose`/`-v` count option (`.info`→1 INFO / pmd3's colorful default,
+ /// `.debug`/`.trace`→2 DEBUG). `-v` on `vm create` thus surfaces the pmd3
+ /// restore logs, which is the whole point of asking for verbosity.
+ private func pmd3VerbosityArgs(_ v: VPhoneVerbosity) -> [String] {
+ Array(repeating: "-v", count: min(v.rawValue, 2))
+ }
+
+ // MARK: - nested-VM preflight
+
+ /// True when running inside an Apple VM (`kern.hv_vmm_present == 1`),
+ /// where Virtualization.framework PV=3 guest boot is unavailable.
+ static func isNestedVMHost() throws -> Bool {
+ let r = try VPhoneProcessRunner.runCapturing(
+ URL(fileURLWithPath: "/usr/sbin/sysctl"), ["-n", "kern.hv_vmm_present"])
+ return VPhoneBootPatterns.parseHVVmmPresent(r.stdout)
+ }
+
+ // MARK: - sudo askpass
+
+ private func makeSudoAskpassScript(password: String) throws -> URL {
+ let url = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vphone-sudo-askpass-\(UUID().uuidString)")
+ let script = "#!/bin/sh\nprintf '%s\\n' \"${SUDO_PASSWORD:-}\"\n"
+ try script.write(to: url, atomically: true, encoding: .utf8)
+ try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: url.path)
+ return url
+ }
+
+ private func preloadSudoCredential(env extras: [String: String], verbosity v: VPhoneVerbosity) {
+ var env = ProcessInfo.processInfo.environment
+ for (key, value) in extras { env[key] = value }
+ trace("spawn /usr/bin/sudo -A -v (env keys added: \(extras.keys.sorted().joined(separator: ", ")))", v)
+ let result = try? VPhoneProcessRunner.runCapturing(URL(fileURLWithPath: "/usr/bin/sudo"), ["-A", "-v"], env: env)
+ if result?.succeeded == true {
+ print("[+] sudo credential preloaded via SUDO_PASSWORD")
+ } else {
+ print("[!] SUDO_PASSWORD provided but sudo -A validation failed; continuing without preload")
+ }
+ }
+
+ // MARK: - fw prepare / fw patch
+
+ private func runFWPrepare(options: Options, isLess: Bool, bundleURL: URL) throws {
+ let v = options.verbosity
+ try FileManager.default.createDirectory(at: resources.ipswCacheDir, withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: resources.sealVolumeCacheDir, withIntermediateDirectories: true)
+
+ var env = ProcessInfo.processInfo.environment
+ if let iphoneSource = options.iphoneSource { env["IPHONE_SOURCE"] = iphoneSource }
+ if let cloudosSource = options.cloudosSource { env["CLOUDOS_SOURCE"] = cloudosSource }
+ env["VPHONE_PYTHON"] = try resources.pythonExecutable().path
+ env["IPSW_DIR"] = resources.ipswCacheDir.path
+ env["VPHONE_SEAL_DIR"] = resources.sealVolumeCacheDir.path
+ if isLess { env["VARIANT"] = "less" }
+
+ trace("spawn /bin/bash \(resources.fwPrepareScript.path) (env keys: VPHONE_PYTHON, IPSW_DIR, VPHONE_SEAL_DIR)", v)
+ let code = try VPhoneProcessRunner.runStreaming(
+ URL(fileURLWithPath: "/bin/bash"), [resources.fwPrepareScript.path], cwd: bundleURL, env: env,
+ echo: v.showsToolDetail)
+ guard code == 0 else { throw VPhoneCreateError.fwPrepareFailed(code) }
+ print("[+] Firmware prepared (iPhone + cloudOS merged into bundle).")
+ }
+
+ private func runFWPatch(
+ variant: PatchFirmwareCLI.VariantOption, isLess: Bool, bundleURL: URL, verbosity v: VPhoneVerbosity
+ ) throws {
+ // Mirrors the Makefile's `ifeq ($(UID),0)` gate on `fw_patch_less` —
+ // only the `less` variant requires root.
+ if isLess, getuid() != 0 {
+ throw VPhoneCreateError.lessRequiresRoot
+ }
+
+ // In-process pipeline (no subprocess) — CryptexFilesystemPatcher's
+ // apfs_sealvolume read honors VPHONE_SEAL_DIR from *this* process's
+ // environment, so set it here to agree with `fw prepare`'s write.
+ try FileManager.default.createDirectory(at: resources.sealVolumeCacheDir, withIntermediateDirectories: true)
+ setenv("VPHONE_SEAL_DIR", resources.sealVolumeCacheDir.path, 1)
+
+ trace("in-process FirmwarePipeline.patchAll variant=\(variant.rawValue)", v)
+ let pipeline = FirmwarePipeline(
+ vmDirectory: bundleURL, variant: variant.pipelineVariant, verbose: v.showsToolDetail,
+ noBinpack: false, noVphoned: false, forceExcGuard: false)
+ let records = try pipeline.patchAll()
+ print("[fw patch] applied \(records.count) patches for \(variant.rawValue)")
+ }
+
+ // MARK: - restore phase
+
+ private func runRestorePhase(bundleURL: URL, verbosity v: VPhoneVerbosity) throws {
+ let configURL = bundleURL.appendingPathComponent("config.plist")
+ print("[*] Starting DFU boot in background...")
+ // Guest serial is never teed during `vm create` (echo: false); the
+ // managed process still reads it internally for panic/prompt matching.
+ trace("spawn \(selfExecutable.path) --config \(configURL.path) --dfu (guest serial: off)", v)
+ let dfu = VPhoneManagedProcess(
+ selfExecutable, ["--config", configURL.path, "--dfu"], cwd: bundleURL, echo: false)
+ try dfu.start()
+ defer { dfu.terminate() }
+
+ let (udid, ecid) = try loadDeviceIdentity(bundleURL: bundleURL)
+ print("[+] Device identity loaded: UDID=\(udid) ECID=0x\(ecid)")
+
+ try waitForRecovery(ecid: ecid, verbosity: v)
+
+ let python = try resources.pythonExecutable()
+ let verbosityArgs = pmd3VerbosityArgs(v)
+ print("[*] Fetching SHSH blob...")
+ let shshArgs =
+ [resources.pmd3Bridge.path, "restore-get-shsh", "--vm-dir", ".", "--udid", udid, "--ecid", "0x\(ecid)"]
+ + verbosityArgs
+ trace("spawn \(python.path) \(shshArgs.joined(separator: " "))", v)
+ let shshCode = try VPhoneProcessRunner.runStreaming(python, shshArgs, cwd: bundleURL, echo: v.showsToolDetail)
+ guard shshCode == 0 else { throw VPhoneCreateError.restoreGetSHSHFailed(shshCode) }
+
+ print("[*] Restoring...")
+ let restoreArgs =
+ [resources.pmd3Bridge.path, "restore-update", "--vm-dir", ".", "--udid", udid, "--ecid", "0x\(ecid)"]
+ + verbosityArgs
+ trace("spawn \(python.path) \(restoreArgs.joined(separator: " "))", v)
+ let restoreCode = try VPhoneProcessRunner.runStreaming(
+ python, restoreArgs, cwd: bundleURL, echo: v.showsToolDetail)
+ guard restoreCode == 0 else { throw VPhoneCreateError.restoreUpdateFailed(restoreCode) }
+
+ // wait_for_post_restore_reboot: a plain case-insensitive 'panic' grep —
+ // distinct from (narrower than) BOOT_PANIC_REGEX used elsewhere.
+ print("[*] Restore complete; waiting up to 30s for reboot/panic before stopping DFU...")
+ let dfuOutcome = dfu.waitForOutput(matching: "(?i)panic|kernel panic", timeout: 30)
+ trace("DFU managed-process outcome: \(dfuOutcome)", v)
+ switch dfuOutcome {
+ case .matched:
+ print("[+] Panic marker observed; stopping DFU now.")
+ case .exited:
+ print("[*] DFU process exited during post-restore reboot window.")
+ case .timedOut:
+ print("[*] No panic marker observed in 30s; stopping DFU anyway.")
+ }
+ // `defer` above terminates the DFU process on every exit path.
+ }
+
+ private func loadDeviceIdentity(bundleURL: URL) throws -> (udid: String, ecid: String) {
+ let predictionFile = bundleURL.appendingPathComponent("udid-prediction.txt")
+ let deadline = Date().addingTimeInterval(30)
+ while !FileManager.default.fileExists(atPath: predictionFile.path), Date() < deadline {
+ Thread.sleep(forTimeInterval: 1)
+ }
+ guard FileManager.default.fileExists(atPath: predictionFile.path) else {
+ throw VPhoneCreateError.identityTimedOut(predictionFile)
+ }
+
+ let text = (try? String(contentsOf: predictionFile, encoding: .utf8)) ?? ""
+ var udid = ""
+ var ecid = ""
+ for line in text.split(whereSeparator: \.isNewline) {
+ guard let eq = line.firstIndex(of: "=") else { continue }
+ let key = line[line.startIndex..<eq]
+ let value = String(line[line.index(after: eq)...])
+ if key == "UDID" { udid = value.uppercased() }
+ if key == "ECID" { ecid = VPhoneBootPatterns.normalizeECID(value) ?? "" }
+ }
+
+ guard udid.range(of: "^[0-9A-F]{8}-[0-9A-F]{16}$", options: .regularExpression) != nil else {
+ throw VPhoneCreateError.invalidUDID(udid)
+ }
+ if ecid.isEmpty {
+ ecid = udid.split(separator: "-", maxSplits: 1).last.map(String.init) ?? ""
+ }
+ guard ecid.range(of: "^[0-9A-F]{16}$", options: .regularExpression) != nil else {
+ throw VPhoneCreateError.invalidECID(ecid)
+ }
+ let udidSuffix = udid.split(separator: "-", maxSplits: 1).last.map(String.init) ?? ""
+ guard udidSuffix == ecid else {
+ throw VPhoneCreateError.udidECIDMismatch(udid: udid, ecid: ecid)
+ }
+ return (udid, ecid)
+ }
+
+ private func waitForRecovery(ecid: String, verbosity v: VPhoneVerbosity) throws {
+ print("[*] Waiting for recovery/DFU endpoint...")
+ let python = try resources.pythonExecutable()
+ for _ in 1...90 {
+ let result = try? VPhoneProcessRunner.runCapturing(
+ python, [resources.pmd3Bridge.path, "recovery-probe", "--ecid", "0x\(ecid)", "--timeout", "2"])
+ if result?.succeeded == true {
+ print("[+] Device endpoint is reachable")
+ return
+ }
+ Thread.sleep(forTimeInterval: 2)
+ }
+ trace("recovery-probe: exhausted 90 retries", v)
+ throw VPhoneCreateError.recoveryTimeout
+ }
+
+ // MARK: - CFW install
+
+ private func runCFWInstall(options: Options, bundleURL: URL, sudoEnvExtras: [String: String]) throws {
+ let v = options.verbosity
+ var env = ProcessInfo.processInfo.environment
+ if let spoofBuild = options.spoofBuild { env["SPOOF_BUILD"] = spoofBuild }
+ if options.forceDSCMaxSlide { env["FORCE_DSC_MAXSLIDE"] = "1" }
+ try FileManager.default.createDirectory(at: resources.ipswCacheDir, withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: resources.sealVolumeCacheDir, withIntermediateDirectories: true)
+ env["VPHONE_PYTHON"] = try resources.pythonExecutable().path
+ env["IPSW_DIR"] = resources.ipswCacheDir.path
+ env["VPHONE_SEAL_DIR"] = resources.sealVolumeCacheDir.path
+ for (key, value) in sudoEnvExtras { env[key] = value }
+
+ let args = [resources.cfwInstallHostScript.path, "--variant", options.variant, bundleURL.path]
+ let envKeys = (["VPHONE_PYTHON", "IPSW_DIR", "VPHONE_SEAL_DIR"] + sudoEnvExtras.keys.sorted()).joined(separator: ", ")
+ trace("spawn /bin/zsh \(args.joined(separator: " ")) (env keys: \(envKeys))", v)
+ let code = try VPhoneProcessRunner.runStreaming(
+ URL(fileURLWithPath: "/bin/zsh"), args, env: env, echo: v.showsToolDetail)
+ guard code == 0 else { throw VPhoneCreateError.cfwInstallFailed(code) }
+ print("[+] CFW installed (\(options.variant)).")
+ }
+
+ // MARK: - first boot
+
+ private func runFirstBoot(options: Options, isLess: Bool, bundleURL: URL) throws {
+ let v = options.verbosity
+ let configURL = bundleURL.appendingPathComponent("config.plist")
+ var args = ["--config", configURL.path]
+ if isLess { args += ["--variant", "less"] }
+
+ if options.interactive {
+ print("[*] press Enter to start VM, after the VM has finished booting, press Enter again to finish last stage")
+ _ = readLine()
+ } else {
+ print("[*] non-interactive (default): auto-starting first boot")
+ }
+
+ trace("spawn \(selfExecutable.path) \(args.joined(separator: " ")) (guest serial: off)", v)
+ let boot = VPhoneManagedProcess(selfExecutable, args, cwd: bundleURL, echo: false)
+ try boot.start()
+ defer { boot.terminate() }
+
+ if options.interactive {
+ print("[*] Press Enter once the VM is fully booted")
+ _ = readLine()
+ } else {
+ let outcome = boot.waitForOutput(matching: VPhoneBootPatterns.panicOrPromptRegex, timeout: 60)
+ trace("first-boot managed-process outcome: \(outcome)", v)
+ switch outcome {
+ case .matched:
+ if case .matched = boot.waitForOutput(matching: "(?i:\(VPhoneBootPatterns.panicRegex))", timeout: 0) {
+ print("[-] Panic detected while waiting for first-boot shell prompt.")
+ throw VPhoneCreateError.firstBootPanic
+ }
+ print("[+] First-boot shell prompt detected")
+ case let .exited(code):
+ print("[-] make boot exited before first-boot command injection.")
+ throw VPhoneCreateError.firstBootExitedBeforePrompt(code)
+ case .timedOut:
+ print("[!] Shell prompt not detected within 60s; fallback to timed continue.")
+ }
+ }
+
+ for cmd in VPhoneBootPatterns.firstBootCommands {
+ boot.send(cmd)
+ }
+
+ print("[*] Commands sent. Waiting for VM shutdown...")
+ _ = boot.waitUntilExit()
+ }
+
+ // MARK: - boot analysis
+
+ private func runBootAnalysis(bundleURL: URL, verbosity v: VPhoneVerbosity) throws {
+ let configURL = bundleURL.appendingPathComponent("config.plist")
+ trace("spawn \(selfExecutable.path) --config \(configURL.path) (guest serial: off)", v)
+ let vm = VPhoneManagedProcess(
+ selfExecutable, ["--config", configURL.path], cwd: bundleURL, echo: false)
+ try vm.start()
+ defer { vm.terminate() }
+
+ let outcome = vm.waitForOutput(matching: VPhoneBootPatterns.panicOrPromptRegex, timeout: 300)
+ trace("boot-analysis managed-process outcome: \(outcome)", v)
+ switch outcome {
+ case .matched:
+ if case .matched = vm.waitForOutput(matching: "(?i:\(VPhoneBootPatterns.panicRegex))", timeout: 0) {
+ print("[-] Boot analysis: panic detected, stopping VM.")
+ throw VPhoneCreateError.bootAnalysisPanic
+ }
+ print("[+] Boot analysis: bash prompt detected, boot success.")
+ case let .exited(code):
+ print("[-] Boot analysis: VM process exited before success marker.")
+ throw VPhoneCreateError.bootAnalysisExited(code)
+ case .timedOut:
+ print("[-] Boot analysis timeout (300s); stopping VM.")
+ throw VPhoneCreateError.bootAnalysisTimeout
+ }
+ }
+
+ /// `less` variant: `run_make "Start VM" boot_less` — a plain foreground
+ /// boot, no panic/prompt analysis (patchless compat mode has no CFW-driven
+ /// success marker to watch for).
+ private func startVMForeground(bundleURL: URL, verbosity v: VPhoneVerbosity) throws {
+ let configURL = bundleURL.appendingPathComponent("config.plist")
+ print("\n=== Start VM ===")
+ let args = ["--config", configURL.path, "--variant", "less"]
+ trace("spawn \(selfExecutable.path) \(args.joined(separator: " ")) (echo=\(v.showsToolDetail))", v)
+ let code = try VPhoneProcessRunner.runStreaming(
+ selfExecutable, args, cwd: bundleURL, echo: v.showsToolDetail)
+ guard code == 0 else { throw VPhoneCreateError.lessBootFailed(code) }
+ }
+}
diff --git a/sources/vphone-cli/VPhoneError.swift b/sources/vphone-cli/VPhoneError.swift
index 76459bfe..a24b3e2a 100644
--- a/sources/vphone-cli/VPhoneError.swift
+++ b/sources/vphone-cli/VPhoneError.swift
@@ -5,9 +5,6 @@ enum VPhoneError: Error, CustomStringConvertible {
case romNotFound(String)
case diskNotFound(String)
case invalidKernelDebugPort(Int)
- case manifestLoadFailed(path: String, underlying: Error)
- case manifestParseFailed(path: String, underlying: Error)
- case manifestWriteFailed(path: String, underlying: Error)
var description: String {
switch self {
@@ -25,12 +22,6 @@ enum VPhoneError: Error, CustomStringConvertible {
"Disk image not found: \(p)"
case let .invalidKernelDebugPort(port):
"Invalid kernel debug port: \(port) (expected 6000...65535)"
- case let .manifestLoadFailed(path: path, underlying: _):
- "Failed to load manifest from \(path)"
- case let .manifestParseFailed(path: path, underlying: _):
- "Failed to parse manifest at \(path)"
- case let .manifestWriteFailed(path: path, underlying: _):
- "Failed to write manifest to \(path)"
}
}
}
diff --git a/sources/vphone-cli/VPhoneFWCLI.swift b/sources/vphone-cli/VPhoneFWCLI.swift
new file mode 100644
index 00000000..e1518943
--- /dev/null
+++ b/sources/vphone-cli/VPhoneFWCLI.swift
@@ -0,0 +1,95 @@
+import ArgumentParser
+import Foundation
+import FirmwarePatcher
+import VPhoneCore
+
+struct VPhoneFWCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "fw",
+ abstract: "Firmware pipeline: prepare (download/merge IPSWs) and patch",
+ subcommands: [VPhoneFWPrepareCommand.self, VPhoneFWPatchCommand.self])
+}
+
+// MARK: - prepare
+
+struct VPhoneFWPrepareCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "prepare", abstract: "Download + merge IPSWs into a VM bundle")
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Argument(help: "VM name") var name: String?
+ @Option(name: .shortAndLong, help: "iPhone IPSW URL or local path") var iphoneSource: String?
+ @Option(name: .shortAndLong, help: "cloudOS IPSW URL or local path") var cloudosSource: String?
+ @Option(help: "iPhone version to resolve to an IPSW") var iphoneVersion: String?
+ @Option(help: "iPhone build to resolve to an IPSW") var iphoneBuild: String?
+ @Flag(help: "List downloadable IPSWs and exit") var list = false
+ @Option(name: .shortAndLong, help: "Resource base override (default: inferred from the running binary path)")
+ var projectRoot: String?
+ @Flag(name: .customShort("v"), help: "Increase verbosity: -v tool detail, -vv guest serial, -vvv internal trace")
+ var verboseCount: Int
+
+ func run() throws {
+ let v = max(VPhoneVerbosity.info, VPhoneVerbosity(count: verboseCount))
+ let name = try VPhoneVMSelection.resolveExisting(name, in: lib.library)
+ let bundle = try lib.library.bundle(named: name)
+ let resources = projectRoot.map { VPhoneResources(base: URL(fileURLWithPath: $0)) } ?? .resolve()
+
+ var env = ProcessInfo.processInfo.environment
+ if let iphoneSource { env["IPHONE_SOURCE"] = iphoneSource }
+ if let cloudosSource { env["CLOUDOS_SOURCE"] = cloudosSource }
+ if let iphoneVersion { env["IPHONE_VERSION"] = iphoneVersion }
+ if let iphoneBuild { env["IPHONE_BUILD"] = iphoneBuild }
+ if list { env["LIST_FIRMWARES"] = "1" }
+
+ // Redirect the three things a read-only bundle can't provide (python,
+ // IPSW cache, extracted apfs_sealvolume) to the writable user cache.
+ try FileManager.default.createDirectory(at: resources.ipswCacheDir, withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: resources.sealVolumeCacheDir, withIntermediateDirectories: true)
+ env["VPHONE_PYTHON"] = try resources.pythonExecutable().path
+ env["IPSW_DIR"] = resources.ipswCacheDir.path
+ env["VPHONE_SEAL_DIR"] = resources.sealVolumeCacheDir.path
+
+ if v.tracesInternals {
+ print("[trace] spawning: /bin/bash \(resources.fwPrepareScript.path) (env keys: VPHONE_PYTHON, IPSW_DIR, VPHONE_SEAL_DIR)")
+ }
+ let code = try VPhoneProcessRunner.runStreaming(
+ URL(fileURLWithPath: "/bin/bash"), [resources.fwPrepareScript.path], cwd: bundle.url, env: env,
+ echo: v.showsToolDetail)
+ throw ExitCode(code)
+ }
+}
+
+// MARK: - patch
+
+struct VPhoneFWPatchCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "patch", abstract: "Patch the boot chain (native Swift FirmwarePipeline)")
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Argument(help: "VM name") var name: String?
+ @Option(name: [.customShort("V"), .long], help: "variant: regular | dev | jb | exp | less") var variant: PatchFirmwareCLI.VariantOption = .regular
+ @Flag(name: .customLong("force-exc-guard"), help: "Force the EXC_GUARD disable patch") var forceExcGuard = false
+ @Flag(name: .shortAndLong, help: "Suppress per-component progress") var quiet = false
+
+ func run() throws {
+ let name = try VPhoneVMSelection.resolveExisting(name, in: lib.library)
+ let bundle = try lib.library.bundle(named: name)
+
+ // In-process pipeline (no subprocess) — CryptexFilesystemPatcher's
+ // apfs_sealvolume read honors VPHONE_SEAL_DIR from *this* process's
+ // environment, so set it here to agree with `fw prepare`'s write.
+ let resources = VPhoneResources.resolve()
+ try FileManager.default.createDirectory(at: resources.sealVolumeCacheDir, withIntermediateDirectories: true)
+ setenv("VPHONE_SEAL_DIR", resources.sealVolumeCacheDir.path, 1)
+
+ let pipeline = FirmwarePipeline(
+ vmDirectory: bundle.url,
+ variant: variant.pipelineVariant,
+ verbose: !quiet,
+ noBinpack: false,
+ noVphoned: false,
+ forceExcGuard: forceExcGuard)
+ let records = try pipeline.patchAll()
+ print("[fw patch] applied \(records.count) patches for \(variant.rawValue)")
+ }
+}
diff --git a/sources/vphone-cli/VPhoneRestoreCLI.swift b/sources/vphone-cli/VPhoneRestoreCLI.swift
new file mode 100644
index 00000000..2cd9f899
--- /dev/null
+++ b/sources/vphone-cli/VPhoneRestoreCLI.swift
@@ -0,0 +1,120 @@
+import ArgumentParser
+import Foundation
+import VPhoneCore
+
+// MARK: - restore
+
+struct VPhoneRestoreCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "restore",
+ abstract: "DFU-restore firmware into a VM bundle (requires a running DFU boot)")
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Argument(help: "VM name") var name: String?
+ @Flag(name: .shortAndLong, help: "Only fetch the SHSH blob, do not restore") var getShsh = false
+ @Flag(name: .shortAndLong, help: "Offline restore (decrypt AEA images in place, use the cached .shsh)") var offline = false
+ @Option(name: .shortAndLong, help: "Device UDID (optional)") var udid: String?
+ @Option(name: .shortAndLong, help: "Device ECID (default: read from the bundle's udid-prediction.txt)") var ecid: String?
+ @Option(name: .shortAndLong, help: "Resource base override (default: inferred from the running binary path)")
+ var projectRoot: String?
+ @Flag(name: .customShort("v"), help: "Increase verbosity: -v tool detail, -vv guest serial, -vvv internal trace")
+ var verboseCount: Int
+
+ func run() throws {
+ let v = max(VPhoneVerbosity.info, VPhoneVerbosity(count: verboseCount))
+ let name = try VPhoneVMSelection.resolveExisting(name, in: lib.library)
+ let bundle = try lib.library.bundle(named: name)
+ let resources = projectRoot.map { VPhoneResources(base: URL(fileURLWithPath: $0)) } ?? .resolve()
+ guard let ecidValue = VPhoneRestoreOps.resolveECID(explicit: ecid, bundle: bundle) else {
+ throw VPhoneRestoreError.ecidUnresolved
+ }
+
+ func pmd3(_ subcommand: String, extra: [String]) throws -> Int32 {
+ var args = [resources.pmd3Bridge.path, subcommand, "--vm-dir", "."]
+ if let udid { args += ["--udid", udid] }
+ args += ["--ecid", ecidValue] + extra
+ // -v (.info) → pmd3 INFO (its colorful log level), -vv/-vvv → DEBUG.
+ args += Array(repeating: "-v", count: min(v.rawValue, 2))
+ let python = try resources.pythonExecutable()
+ if v.tracesInternals {
+ print("[trace] spawning: \(python.path) \(args.joined(separator: " "))")
+ }
+ return try VPhoneProcessRunner.runStreaming(python, args, cwd: bundle.url, echo: v.showsToolDetail)
+ }
+
+ if getShsh {
+ throw ExitCode(try pmd3("restore-get-shsh", extra: []))
+ }
+ if offline {
+ let fm = FileManager.default
+ let shshes = ((try? fm.contentsOfDirectory(at: bundle.url, includingPropertiesForKeys: nil)) ?? [])
+ .filter { $0.pathExtension == "shsh" }.sorted { $0.lastPathComponent < $1.lastPathComponent }
+ guard let shsh = shshes.first else { throw VPhoneRestoreError.noSHSH }
+ let restoreDir = ((try? fm.contentsOfDirectory(at: bundle.url, includingPropertiesForKeys: nil)) ?? [])
+ .filter { $0.lastPathComponent.hasPrefix("iPhone") && $0.lastPathComponent.hasSuffix("_Restore") }
+ .sorted { $0.lastPathComponent < $1.lastPathComponent }
+ .first
+ guard let restoreDir else { throw VPhoneRestoreError.noRestoreDir }
+ print("[restore] decrypting AEA images in \(restoreDir.lastPathComponent)...")
+ try VPhoneRestoreOps.decryptAEAImages(inRestoreDir: restoreDir)
+ throw ExitCode(try pmd3("restore-update", extra: ["--tss", shsh.path]))
+ }
+ throw ExitCode(try pmd3("restore-update", extra: []))
+ }
+}
+
+// MARK: - cfw
+
+struct VPhoneCFWCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "cfw",
+ abstract: "Custom-firmware install (host-mount; VM must be off; re-execs sudo)",
+ subcommands: [VPhoneCFWInstallCommand.self])
+}
+
+struct VPhoneCFWInstallCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "install", abstract: "Install CFW into a VM bundle via host mount")
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Argument(help: "VM name") var name: String?
+ @Option(name: [.customShort("V"), .long], help: "variant: regular | dev | jb | exp") var variant: String = "exp"
+ @Option(name: [.customShort("b"), .long], help: "(exp only) rewrite ProductBuildVersion to this build id") var spoofBuild: String?
+ @Flag(name: .customLong("force-dsc-maxslide"), help: "Zero the dyld cache maxSlide on non-27 bases (opt-in DSC-map fit)") var forceDSCMaxSlide = false
+ @Option(name: .shortAndLong, help: "Resource base override (default: inferred from the running binary path)")
+ var projectRoot: String?
+ @Flag(name: .customShort("v"), help: "Increase verbosity: -v tool detail, -vv guest serial, -vvv internal trace")
+ var verboseCount: Int
+
+ func run() throws {
+ let v = max(VPhoneVerbosity.info, VPhoneVerbosity(count: verboseCount))
+ guard ["regular", "dev", "jb", "exp"].contains(variant) else {
+ throw ValidationError("unknown cfw variant '\(variant)' (regular|dev|jb|exp)")
+ }
+ let name = try VPhoneVMSelection.resolveExisting(name, in: lib.library)
+ let bundle = try lib.library.bundle(named: name)
+ let resources = projectRoot.map { VPhoneResources(base: URL(fileURLWithPath: $0)) } ?? .resolve()
+
+ var env = ProcessInfo.processInfo.environment
+ if let spoofBuild { env["SPOOF_BUILD"] = spoofBuild }
+ if forceDSCMaxSlide { env["FORCE_DSC_MAXSLIDE"] = "1" }
+
+ // Same redirect as `fw prepare`: VPHONE_PYTHON/IPSW_DIR/VPHONE_SEAL_DIR are
+ // exported for the bundled scripts (cfw_install_host.sh's PY/P lines honor
+ // VPHONE_PYTHON); the apfs_sealvolume read itself only happens on the
+ // `fw patch` path (CryptexFilesystemPatcher).
+ try FileManager.default.createDirectory(at: resources.ipswCacheDir, withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: resources.sealVolumeCacheDir, withIntermediateDirectories: true)
+ env["VPHONE_PYTHON"] = try resources.pythonExecutable().path
+ env["IPSW_DIR"] = resources.ipswCacheDir.path
+ env["VPHONE_SEAL_DIR"] = resources.sealVolumeCacheDir.path
+
+ let args = [resources.cfwInstallHostScript.path, "--variant", variant, bundle.url.path]
+ if v.tracesInternals {
+ print("[trace] spawning: /bin/zsh \(args.joined(separator: " ")) (env keys: VPHONE_PYTHON, IPSW_DIR, VPHONE_SEAL_DIR)")
+ }
+ let code = try VPhoneProcessRunner.runStreaming(
+ URL(fileURLWithPath: "/bin/zsh"), args, env: env, echo: v.showsToolDetail)
+ throw ExitCode(code)
+ }
+}
diff --git a/sources/vphone-cli/VPhoneSetupCLI.swift b/sources/vphone-cli/VPhoneSetupCLI.swift
new file mode 100644
index 00000000..1ec80c06
--- /dev/null
+++ b/sources/vphone-cli/VPhoneSetupCLI.swift
@@ -0,0 +1,30 @@
+import ArgumentParser
+import Foundation
+import VPhoneCore
+
+// MARK: - setup
+
+/// Provision (or verify) the host Python environment the guest pipeline needs.
+/// Runs implicitly on first use, but this makes it an explicit, up-front step
+/// so a freshly-copied .app can be prepared before a long `vm create`.
+struct VPhoneSetupCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "setup",
+ abstract: "Provision/verify the host Python environment (~/.vphone/venv)")
+
+ @Flag(name: .shortAndLong, help: "Recreate the managed venv even if one already works")
+ var force = false
+ @Option(name: .shortAndLong, help: "Resource base override (default: inferred from the running binary path)")
+ var projectRoot: String?
+
+ func run() throws {
+ let resources = projectRoot.map { VPhoneResources(base: URL(fileURLWithPath: $0)) } ?? .resolve()
+ if force { try? FileManager.default.removeItem(at: resources.managedVenvDir) }
+ // pythonExecutable() provisions ~/.vphone/venv on demand if none is
+ // usable — running any python-backed command does this automatically;
+ // `setup` just makes it explicit. It prints its own progress on a first
+ // provision, so here only report the resolved interpreter.
+ let python = try resources.pythonExecutable()
+ print("python: \(python.path)")
+ }
+}
diff --git a/sources/vphone-cli/VPhoneVMCLI.swift b/sources/vphone-cli/VPhoneVMCLI.swift
new file mode 100644
index 00000000..6cacb64f
--- /dev/null
+++ b/sources/vphone-cli/VPhoneVMCLI.swift
@@ -0,0 +1,169 @@
+import ArgumentParser
+import Foundation
+import VPhoneCore
+
+// MARK: - Command group
+
+struct VPhoneVMCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "vm",
+ abstract: "Manage vphone VM bundles",
+ subcommands: [
+ VPhoneVMListCommand.self,
+ VPhoneVMInfoCommand.self,
+ VPhoneVMNewCommand.self,
+ VPhoneVMConfigCommand.self,
+ VPhoneVMRenameCommand.self,
+ VPhoneVMDeleteCommand.self,
+ VPhoneVMCloneCommand.self,
+ VPhoneVMExportCommand.self,
+ VPhoneVMImportCommand.self,
+ VPhoneVMLaunchCommand.self,
+ VPhoneVMStopCommand.self,
+ VPhoneVMCreateCommand.self,
+ ]
+ )
+}
+
+// MARK: - Shared options
+
+struct VPhoneLibraryOption: ParsableArguments {
+ @Option(name: [.customShort("l"), .long], help: "VM library root (default: ~/.vphone/VMs or $VPHONE_LIBRARY_ROOT)")
+ var libraryRoot: String?
+
+ var library: VPhoneLibrary {
+ let root = libraryRoot.map { URL(fileURLWithPath: $0, isDirectory: true) }
+ ?? VPhoneLibrary.defaultRoot()
+ return VPhoneLibrary(root: root)
+ }
+}
+
+// MARK: - list
+
+struct VPhoneVMListCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(commandName: "list", abstract: "List VM bundles")
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Flag(name: .shortAndLong, help: "Emit JSON") var json = false
+
+ func run() throws {
+ let library = lib.library
+ let scan = try library.scan()
+ for skip in scan.skipped {
+ FileHandle.standardError.write(Data("warning: skipping \(skip.name): \(skip.reason)\n".utf8))
+ }
+ let reports = scan.bundles.map(VPhoneBundleReport.init)
+ if json {
+ let data = try JSONEncoder().encode(reports)
+ print(String(decoding: data, as: UTF8.self))
+ } else if reports.isEmpty {
+ print("(no VMs in \(library.root.path))")
+ } else {
+ for r in reports {
+ print("\(r.name) \(r.cpuCount) CPU \(r.memoryMB) MB \(r.diskSizeBytes / (1024*1024*1024)) GB disk")
+ }
+ }
+ }
+}
+
+// MARK: - info
+
+struct VPhoneVMInfoCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(commandName: "info", abstract: "Show one VM bundle")
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Argument(help: "VM name") var name: String?
+ @Flag(name: .shortAndLong, help: "Emit JSON") var json = false
+
+ func run() throws {
+ let name = try VPhoneVMSelection.resolveExisting(name, in: lib.library)
+ let report = VPhoneBundleReport(bundle: try lib.library.bundle(named: name))
+ if json {
+ print(String(decoding: try JSONEncoder().encode(report), as: UTF8.self))
+ } else {
+ print("name: \(report.name)")
+ print("cpu: \(report.cpuCount)")
+ print("mem: \(report.memoryMB) MB")
+ print("disk: \(report.diskSizeBytes) bytes")
+ }
+ }
+}
+
+// MARK: - new
+
+struct VPhoneVMNewCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(commandName: "new", abstract: "Create a VM bundle")
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Argument(help: "VM name") var name: String
+ @Option(name: .shortAndLong, help: "CPU cores") var cpu: UInt = 8
+ @Option(name: .shortAndLong, help: "Memory (MB)") var memory: UInt64 = 8192
+ @Option(name: .shortAndLong, help: "Disk size (GB)") var diskSize: UInt64 = 64
+ @Option(name: .shortAndLong, help: "AVPBooter ROM (default: framework built-in)") var rom: String?
+ @Option(name: .shortAndLong, help: "AVPSEPBooter ROM (default: framework built-in)") var seprom: String?
+
+ func run() throws {
+ let spec = VPhoneBundleOps.NewBundleSpec(
+ name: name, cpuCount: cpu, memoryMB: memory, diskSizeGB: diskSize,
+ romSource: rom.map { URL(fileURLWithPath: $0) } ?? VPhoneBundleOps.defaultROMSource(),
+ sepromSource: seprom.map { URL(fileURLWithPath: $0) } ?? VPhoneBundleOps.defaultSEPROMSource())
+ let bundle = try VPhoneBundleOps.create(spec, in: lib.library)
+ print("created \(bundle.url.path)")
+ }
+}
+
+// MARK: - config
+
+struct VPhoneVMConfigCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "config", abstract: "Edit VM manifest fields (cpu/memory)")
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Argument(help: "VM name") var name: String?
+ @Option(name: .shortAndLong, help: "CPU cores") var cpu: UInt?
+ @Option(name: .shortAndLong, help: "Memory (MB)") var memory: UInt64?
+
+ func run() throws {
+ let name = try VPhoneVMSelection.resolveExisting(name, in: lib.library)
+ let updated = try VPhoneBundleOps.updateConfig(
+ bundleNamed: name, in: lib.library, cpuCount: cpu, memoryMB: memory)
+ print("updated \(updated.name): \(updated.manifest.cpuCount) CPU, \(updated.manifest.memorySize / (1024*1024)) MB")
+ }
+}
+
+// MARK: - rename
+
+struct VPhoneVMRenameCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(commandName: "rename", abstract: "Rename a VM bundle")
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Argument(help: "current name") var name: String?
+ @Argument(help: "new name") var newName: String?
+
+ func run() throws {
+ let name = try VPhoneVMSelection.resolveExisting(name, in: lib.library)
+ let newName = try VPhoneVMSelection.resolveNewName(newName, prompt: "New VM name:")
+ let b = try VPhoneBundleOps.rename(bundleNamed: name, to: newName, in: lib.library)
+ print("renamed to \(b.name)")
+ }
+}
+
+// MARK: - delete
+
+struct VPhoneVMDeleteCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(commandName: "delete", abstract: "Delete a VM bundle")
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Argument(help: "VM name") var name: String?
+ @Flag(name: .shortAndLong, help: "Do not prompt") var force = false
+
+ func run() throws {
+ let name = try VPhoneVMSelection.resolveExisting(name, in: lib.library)
+ if !force {
+ print("Delete '\(name)' and all its files? [y/N] ", terminator: "")
+ guard (readLine() ?? "").lowercased() == "y" else { print("aborted"); return }
+ }
+ try VPhoneBundleOps.delete(bundleNamed: name, in: lib.library)
+ print("deleted \(name)")
+ }
+}
diff --git a/sources/vphone-cli/VPhoneVMCreateCLI.swift b/sources/vphone-cli/VPhoneVMCreateCLI.swift
new file mode 100644
index 00000000..bec390b7
--- /dev/null
+++ b/sources/vphone-cli/VPhoneVMCreateCLI.swift
@@ -0,0 +1,39 @@
+import ArgumentParser
+import Foundation
+import VPhoneCore
+
+struct VPhoneVMCreateCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "create",
+ abstract: "Create a VM end-to-end (prepare → patch → restore → CFW → first boot)",
+ discussion: "Runs the full pipeline for a fresh VM. Needs an internet connection "
+ + "(IPSW download), a non-nested macOS host, and sudo (CFW host-mount). "
+ + "The 'less' (patchless) variant must itself be run with sudo — the whole "
+ + "create runs as root, not just the fw-patch stage.")
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Argument(help: "new VM name") var name: String
+ @Option(name: [.customShort("V"), .long], help: "variant: regular | dev | jb | exp | less") var variant: String = "regular"
+ @Option(name: .shortAndLong, help: "iPhone IPSW URL or local path") var iphoneSource: String?
+ @Option(name: .shortAndLong, help: "cloudOS IPSW URL or local path") var cloudosSource: String?
+ @Option(name: .shortAndLong, help: "sudo password for the CFW host-mount install (via askpass; never logged)")
+ var sudoPassword: String?
+ @Option(name: [.customShort("b"), .long], help: "(exp only) rewrite ProductBuildVersion to this build id") var spoofBuild: String?
+ @Flag(name: .customLong("force-dsc-maxslide"), help: "Zero the dyld cache maxSlide on non-27 bases (opt-in DSC-map fit)") var forceDSCMaxSlide = false
+ @Flag(help: "Prompt at first-boot stages instead of running non-interactively") var interactive = false
+ @Option(name: .shortAndLong, help: "Resource base override (default: inferred from the running binary path)")
+ var projectRoot: String?
+ @Flag(name: .customShort("v"), help: "Increase verbosity: -v tool detail, -vv guest serial, -vvv internal trace")
+ var verboseCount: Int
+
+ func run() throws {
+ let resources = projectRoot.map { VPhoneResources(base: URL(fileURLWithPath: $0)) } ?? .resolve()
+ let selfExe = URL(fileURLWithPath: CommandLine.arguments[0]).resolvingSymlinksInPath()
+ let orchestrator = VPhoneCreateOrchestrator(
+ library: lib.library, resources: resources, selfExecutable: selfExe)
+ try orchestrator.run(.init(
+ name: name, variant: variant, iphoneSource: iphoneSource, cloudosSource: cloudosSource,
+ sudoPassword: sudoPassword, spoofBuild: spoofBuild, forceDSCMaxSlide: forceDSCMaxSlide,
+ interactive: interactive, verbosity: VPhoneVerbosity(count: verboseCount)))
+ }
+}
diff --git a/sources/vphone-cli/VPhoneVMLaunchCLI.swift b/sources/vphone-cli/VPhoneVMLaunchCLI.swift
new file mode 100644
index 00000000..39dff3a9
--- /dev/null
+++ b/sources/vphone-cli/VPhoneVMLaunchCLI.swift
@@ -0,0 +1,126 @@
+import ArgumentParser
+import Foundation
+import VPhoneCore
+
+struct VPhoneVMLaunchCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "launch", abstract: "Boot a VM bundle (runs host preflight first)")
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Argument(help: "VM name") var name: String?
+ @Flag(name: .shortAndLong, help: "Boot into DFU mode (headless)") var dfu = false
+ @Option(name: [.customShort("V"), .long], help: "Firmware variant") var variant: String?
+ @Flag(name: .customLong("no-vphoned"), help: "Do not stage/use vphoned") var noVphoned = false
+ @Option(help: "Kernel GDB debug stub port on host (omit for system-assigned; valid: 6000...65535)")
+ var kernelDebugPort: Int?
+ @Option(name: .shortAndLong, help: "Resource base override (default: inferred from the running binary path)")
+ var projectRoot: String?
+ @Flag(name: .customShort("v"), help: "Increase verbosity: -v tool detail, -vv guest serial, -vvv internal trace")
+ var verboseCount: Int
+
+ func run() throws {
+ let v = VPhoneVerbosity(count: verboseCount)
+ let name = try VPhoneVMSelection.resolveExisting(name, in: lib.library)
+ let bundle = try lib.library.bundle(named: name)
+ let resources = projectRoot.map { VPhoneResources(base: URL(fileURLWithPath: $0)) } ?? .resolve()
+ let layout = VPhoneLaunchLayout(resources: resources)
+
+ // Host preflight — same gate make boot applies.
+ var preflightArgs = ["--assert-bootable"]
+ if variant == "less" { preflightArgs.append("--less") }
+ let pre = try VPhoneProcessRunner.runCapturing(
+ URL(fileURLWithPath: "/bin/zsh"), [layout.preflightScript.path] + preflightArgs,
+ cwd: resources.base)
+ if !pre.stdout.isEmpty { print(pre.stdout, terminator: "") }
+ guard pre.succeeded else {
+ FileHandle.standardError.write(Data(pre.stderr.utf8))
+ throw ExitCode(pre.exitCode == 0 ? 1 : pre.exitCode)
+ }
+
+ // A bundled .app is its own boot binary — self-spawn the running executable
+ // for both the GUI and --dfu (headless) boot paths.
+ let bootBinary = URL(fileURLWithPath: CommandLine.arguments[0]).resolvingSymlinksInPath()
+ guard FileManager.default.isExecutableFile(atPath: bootBinary.path) else {
+ FileHandle.standardError.write(Data(
+ "error: \(bootBinary.path) not found — build it first (make build/bundle).\n".utf8))
+ throw ExitCode(1)
+ }
+
+ if !dfu && !noVphoned {
+ do {
+ _ = try layout.stageVphoned(into: bundle)
+ } catch {
+ FileHandle.standardError.write(Data(
+ "warning: could not stage vphoned into \(bundle.name): \(error)\n".utf8))
+ }
+ }
+
+ var args = ["--config", bundle.configURL.path]
+ if dfu { args.append("--dfu") }
+ if let variant { args += ["--variant", variant] }
+ if noVphoned { args.append("--no-vphoned") }
+ if let kernelDebugPort { args += ["--kernel-debug-port", String(kernelDebugPort)] }
+
+ if v.tracesInternals {
+ print("[trace] spawning: \(bootBinary.path) \(args.joined(separator: " "))")
+ }
+
+ let child = Process()
+ child.executableURL = bootBinary
+ child.arguments = args
+ child.currentDirectoryURL = bundle.url
+ // `vm launch` always streams the guest serial console (inherits our
+ // stdio); it is intentionally not gated on verbosity.
+ try child.run()
+
+ // Forward SIGINT to the child so Ctrl+C stops the VM cleanly.
+ let sigint = DispatchSource.makeSignalSource(signal: SIGINT, queue: .main)
+ signal(SIGINT, SIG_IGN)
+ sigint.setEventHandler { child.interrupt() }
+ sigint.resume()
+
+ child.waitUntilExit()
+ throw ExitCode(child.terminationStatus)
+ }
+}
+
+// MARK: - vm stop
+
+struct VPhoneVMStopCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "stop", abstract: "Stop a running VM bundle")
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Argument(help: "VM name") var name: String?
+ @Option(name: .shortAndLong, help: "Seconds to wait for graceful shutdown before SIGKILL") var timeout: Int = 20
+
+ func run() throws {
+ let name = try VPhoneVMSelection.resolveExisting(name, in: lib.library)
+ let bundle = try lib.library.bundle(named: name)
+ let disk = bundle.url.appendingPathComponent(bundle.manifest.diskImage)
+
+ func runningPIDs() -> [Int32] {
+ guard let r = try? VPhoneProcessRunner.runCapturing(
+ URL(fileURLWithPath: "/usr/sbin/lsof"), ["-t", "--", disk.path]) else { return [] }
+ return VPhoneLsof.parsePIDs(r.stdout)
+ }
+
+ let pids = runningPIDs()
+ guard !pids.isEmpty else { print("\(name): not running"); return }
+
+ print("\(name): sending SIGINT to \(pids.map(String.init).joined(separator: ", "))")
+ for pid in pids { kill(pid, SIGINT) }
+
+ var waited = 0
+ while waited < timeout, !runningPIDs().isEmpty {
+ Thread.sleep(forTimeInterval: 1)
+ waited += 1
+ }
+ let survivors = runningPIDs()
+ if !survivors.isEmpty {
+ print("\(name): force-killing \(survivors.map(String.init).joined(separator: ", "))")
+ for pid in survivors { kill(pid, SIGKILL) }
+ }
+ print("\(name): stopped")
+ }
+}
diff --git a/sources/vphone-cli/VPhoneVMSelection.swift b/sources/vphone-cli/VPhoneVMSelection.swift
new file mode 100644
index 00000000..5aca7209
--- /dev/null
+++ b/sources/vphone-cli/VPhoneVMSelection.swift
@@ -0,0 +1,30 @@
+import Foundation
+import VPhoneCore
+
+enum VPhoneVMSelection {
+ private static var isTTY: Bool { isatty(FileHandle.standardInput.fileDescriptor) != 0 }
+ private static func err(_ s: String) { FileHandle.standardError.write(Data((s + "\n").utf8)) }
+
+ /// Resolve an existing-VM name, prompting with a numbered picker when omitted.
+ static func resolveExisting(_ provided: String?, in library: VPhoneLibrary) throws -> String {
+ if let provided, !provided.isEmpty { return provided } // supplied name → no library scan
+ let names = try library.bundles().map(\.name).sorted() // no-name path: propagate real scan errors
+ return try VPhoneVMPicker.resolve(
+ provided: nil, names: names, libraryRoot: library.root.path,
+ isInteractive: isTTY,
+ read: { readLine(strippingNewline: true) },
+ write: { err($0) })
+ }
+
+ /// Resolve a NEW name (rename/clone destination): return it if given, else prompt for text.
+ static func resolveNewName(_ provided: String?, prompt: String) throws -> String {
+ if let provided, !provided.isEmpty { return provided }
+ guard isTTY else { throw VPhoneVMPickerError.notInteractive }
+ FileHandle.standardError.write(Data((prompt + " ").utf8))
+ guard let line = readLine(strippingNewline: true)?
+ .trimmingCharacters(in: .whitespacesAndNewlines), !line.isEmpty else {
+ throw VPhoneVMPickerError.aborted
+ }
+ return line
+ }
+}
diff --git a/sources/vphone-cli/VPhoneVMTransferCLI.swift b/sources/vphone-cli/VPhoneVMTransferCLI.swift
new file mode 100644
index 00000000..72be1806
--- /dev/null
+++ b/sources/vphone-cli/VPhoneVMTransferCLI.swift
@@ -0,0 +1,54 @@
+import ArgumentParser
+import Foundation
+import VPhoneCore
+
+struct VPhoneVMCloneCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "clone",
+ abstract: "Clone a VM bundle (fast APFS clone; resets device identity)",
+ discussion: "The clone boots as a fresh device (nvram/machineIdentifier/shsh cleared). "
+ + "SEPStorage is copied as-is; a cloned, already-restored VM may need re-restoring.")
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Argument(help: "source VM name") var name: String?
+ @Argument(help: "new VM name") var newName: String?
+
+ func run() throws {
+ let name = try VPhoneVMSelection.resolveExisting(name, in: lib.library)
+ let newName = try VPhoneVMSelection.resolveNewName(newName, prompt: "New VM name:")
+ let clone = try VPhoneBundleOps.clone(bundleNamed: name, to: newName, in: lib.library)
+ print("cloned \(name) → \(clone.name)")
+ }
+}
+
+struct VPhoneVMExportCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "export", abstract: "Export a VM bundle to a .tgz archive")
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Argument(help: "VM name") var name: String?
+ @Option(name: .shortAndLong, help: "output archive path") var out: String
+ @Flag(help: "include the *_Restore* IPSW directory") var includeIpsw = false
+
+ func run() throws {
+ let name = try VPhoneVMSelection.resolveExisting(name, in: lib.library)
+ try VPhoneBundleOps.export(
+ bundleNamed: name, to: URL(fileURLWithPath: out), includeIPSW: includeIpsw, in: lib.library)
+ print("exported \(name) → \(out)")
+ }
+}
+
+struct VPhoneVMImportCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "import", abstract: "Import a VM bundle from a .tgz archive")
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Option(name: [.customShort("i"), .customLong("in")], help: "input archive path") var input: String
+ @Option(name: .shortAndLong, help: "name for the imported VM (default: the archive's own name)") var name: String?
+
+ func run() throws {
+ let bundle = try VPhoneBundleOps.importArchive(
+ from: URL(fileURLWithPath: input), name: name, in: lib.library)
+ print("imported → \(bundle.name)")
+ }
+}
diff --git a/sources/vphone-cli/VPhoneVirtualMachine.swift b/sources/vphone-cli/VPhoneVirtualMachine.swift
index d292b449..6f477fda 100644
--- a/sources/vphone-cli/VPhoneVirtualMachine.swift
+++ b/sources/vphone-cli/VPhoneVirtualMachine.swift
@@ -1,6 +1,7 @@
import Dynamic
import Foundation
import Virtualization
+import VPhoneCore
/// Minimal VM for booting a vphone (virtual iPhone) in DFU mode.
@MainActor
diff --git a/sources/vphone-cli/main.swift b/sources/vphone-cli/main.swift
index 50255a4c..0b8b7255 100644
--- a/sources/vphone-cli/main.swift
+++ b/sources/vphone-cli/main.swift
@@ -12,14 +12,9 @@ do {
app.delegate = delegate
app.run()
- case var patch as PatchFirmwareCLI:
- try patch.run()
-
- case var patch as PatchComponentCLI:
- try patch.run()
-
default:
- break
+ var runnable = command
+ try runnable.run()
}
} catch {
VPhoneCLI.exit(withError: error)