Run a virtual iPhone on an Apple Silicon Mac.
Swift
Restore PCC GPU through vphone VM and native restore
Lakrbc795861b3f0
diff --git a/docs/guides/create-and-run.md b/docs/guides/create-and-run.mdindex b702fe18..a805c977 100644--- a/docs/guides/create-and-run.md+++ b/docs/guides/create-and-run.md@@ -17,7 +17,7 @@ vphone-cli vm create myphone \Creation runs prepare → JB patch → online DFU restore → host-mounted CFW installation → first GUI boot. It needs network access for the restore ticket. CFW installation needs administrator authentication; on a host without an interactive terminal, `--root-popup` uses a macOS authentication dialog. The default virtual disk is 64 GB. `--keep-artifacts` retains the large prepared restore tree; omit it when disk space matters.-If Apple's WKMS server no longer serves the AEA key for the selected PCC image, `vm create` and `fw prepare` accept `--gpu-driver-bundle /path/to/AppleParavirtGPUMetalIOGPUFamily.bundle`. Supply a complete bundle previously extracted from **the same cloudOS build**. The CLI validates its files and identifier, then stages it in the restore tree without decrypting the PCC OS image. The iPhone restore still uses its own AEA keys and an online restore ticket.+If Apple's WKMS server no longer serves the AEA key for the selected PCC image, `fw prepare` automatically creates a temporary vphone VM, starts it in DFU, and restores the selected cloudOS IPSW using this project's restore backend. It mounts the restored System volume read-only, extracts the GPU bundle, then removes the temporary VM. This first restore supplies the GPU driver for the second, hybrid iPhone restore. `vm create` and `fw prepare` also accept `--gpu-driver-bundle /path/to/AppleParavirtGPUMetalIOGPUFamily.bundle` to reuse a previously extracted bundle. The CLI checks its iPhoneOS platform version against the selected cloudOS version. Each restore obtains its own ticket online.Success ends with `First boot: vphoned ping succeeded` and `JB VM created; vphoned connected`. **The verification VM is then stopped.** The ping proves the daemon answered over the host control socket during that boot; it does not leave a running VM behind.diff --git a/research/0_binary_patch_comparison.md b/research/0_binary_patch_comparison.mdindex 53d02b30..b24bd4fb 100644--- a/research/0_binary_patch_comparison.md+++ b/research/0_binary_patch_comparison.md@@ -1227,13 +1227,19 @@ passed (the filter is detected, and libzstd is static in the xcframework).The application no longer ships `AppleParavirtGPUMetalIOGPUFamily.tar`. During`fw prepare`, the PCC `BuildManifest.plist` selects the vphone600 OS image. The-preparer decrypts and read-only mounts that image, copies its complete-`AppleParavirtGPUMetalIOGPUFamily.bundle` into the VM restore tree, then removes-the temporary decrypted image. Both the JB host-mount installer and the legacy-filesystem merge copy this staged bundle into the guest. The executable,-compiler-plugin dylib, plist, and signature resources therefore come from the-same PCC release as the selected kernel; no separately downloaded GPU binary is-required. This is a payload-source change, not a new binary patch.+preparer decrypts and read-only mounts that image when Apple serves its AEA+key, copies its complete `AppleParavirtGPUMetalIOGPUFamily.bundle` into the VM+restore tree, then removes the temporary image. When WKMS returns 403,+`vphone-cli` creates a temporary PV=3 VM, boots it in DFU, and restores the+selected cloudOS IPSW through its own `VPhoneRestoreBridge`. The preparer+copies the bundle from its sealed System volume and removes the temporary VM.+Both the JB host-mount installer and the filesystem merge copy this staged+bundle into the iPhone guest. The 26.4 `23E5207q` restored bundle has+`DTPlatformVersion=26.4`, `CFBundleVersion=64.4.4`, and binary SHA-256+`29ba36c7bc87d82c40fa1cecdf357e7a383fa70eb46df0d75869f5ac562aedbc`.+It lacks the compiler-plugin dylib present in the 26.1 bundle, so the installer+only sets that file's permissions if it exists. This is a payload-source and+installation change, not a new binary patch.**`find -name '._*' -delete` → `deleteAppleDoubleFiles`,** and this one was nearly asilent regression worth writing down. On a volume with native extended attributes,diff --git a/siblings/gpu/README.md b/siblings/gpu/README.mdindex 8952ffa8..f973f5ba 100644--- a/siblings/gpu/README.md+++ b/siblings/gpu/README.md@@ -4,8 +4,17 @@no source here to compile and no binary to package in `vphone-cli.app`.`vphone-cli fw prepare` reads the vphone600 OS path from the selected PCC-`BuildManifest.plist`, decrypts and mounts that image with macOS system tools,-and stages the complete bundle inside the VM restore tree. JB installation-copies the staged bundle into the guest. The compiler-plugin dylib and driver-executable therefore always come from the same PCC release used for the VM's-kernel.+`BuildManifest.plist`, decrypts and mounts that image when Apple serves its AEA+key, and stages the complete bundle inside the VM restore tree. If that key is+unavailable, `vphone-cli` creates its own temporary PV=3 VM, boots it into DFU,+and restores the selected cloudOS IPSW with the project's in-process+idevicerestore backend. The CLI mounts its sealed System volume read-only,+copies the bundle, and removes the temporary VM. JB installation copies the+staged bundle into the iPhone guest. The driver therefore comes from the same+PCC release used for the VM's kernel.++The cloudOS 26.4 `23E5207q` bundle recovered from its restored System volume+has `DTPlatformVersion=26.4`, `CFBundleVersion=64.4.4`, and no+`libAppleParavirtCompilerPluginIOGPUFamily.dylib`. The older 26.1 bundle has+that dylib. Neither is compiled by this project; the installer preserves the+files Apple actually provides for the selected release.diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swiftindex c5aebd45..9a1c54d5 100644--- a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift@@ -121,12 +121,15 @@ extension CryptexFilesystemPatcher {try chownRecursively(uid: 0, gid: 0, at: bundle)for path in [bundle,- bundle.appending(path: "/libAppleParavirtCompilerPluginIOGPUFamily.dylib"),bundle.appending(path: "/AppleParavirtGPUMetalIOGPUFamily"),bundle.appending(path: "/_CodeSignature"),] {try setMode(0o755, at: path)}+ let compilerPlugin = bundle.appending(path: "libAppleParavirtCompilerPluginIOGPUFamily.dylib")+ if FileManager.default.fileExists(atPath: compilerPlugin.path) {+ try setMode(0o755, at: compilerPlugin)+ }for path in [bundle.appending(path: "/_CodeSignature/CodeResources"),bundle.appending(path: "/Info.plist"),diff --git a/sources/VPhoneCore/VPhonePCCGPUDriver.swift b/sources/VPhoneCore/VPhonePCCGPUDriver.swiftindex ea130eaa..37c38218 100644--- a/sources/VPhoneCore/VPhonePCCGPUDriver.swift+++ b/sources/VPhoneCore/VPhonePCCGPUDriver.swift@@ -10,6 +10,7 @@ public enum VPhonePCCGPUDriver {case unsafeOSPath(String)case missingBundle(URL)case invalidCachedBundle(URL)+ case wrongPlatformVersion(URL, expected: String, actual: String)case toolFailed(String, String)public var errorDescription: String? {@@ -22,6 +23,8 @@ public enum VPhonePCCGPUDriver {"PCC OS image has no GPU driver bundle at \(path.path)"case let .invalidCachedBundle(path):"GPU driver bundle is incomplete or has the wrong identifier: \(path.path)"+ case let .wrongPlatformVersion(path, expected, actual):+ "GPU driver at \(path.path) is for iPhoneOS \(actual), expected cloudOS \(expected)"case let .toolFailed(tool, detail):"\(tool) failed while extracting the PCC GPU driver: \(detail)"}@@ -60,12 +63,13 @@ public enum VPhonePCCGPUDriver {from cloudOSDirectory: URL,into restoreDirectory: URL,cachedBundle: URL? = nil,+ expectedPlatformVersion: String? = nil,) throws {let fm = FileManager.defaultlet destination = stagedBundle(in: restoreDirectory)if let cachedBundle {let source = cachedBundle.standardizedFileURL.resolvingSymlinksInPath()- try validateBundle(at: source)+ try validateBundle(at: source, expectedPlatformVersion: expectedPlatformVersion)try fm.createDirectory(at: destination.deletingLastPathComponent(),withIntermediateDirectories: true)if fm.fileExists(atPath: destination.path) {@@ -99,12 +103,7 @@ public enum VPhonePCCGPUDriver {let source = mount.appending(path: "System/Library/Extensions/\(name)")guard fm.fileExists(atPath: source.path) else { throw Error.missingBundle(source) }- for file in ["AppleParavirtGPUMetalIOGPUFamily",- "libAppleParavirtCompilerPluginIOGPUFamily.dylib", "Info.plist"]- {- let member = source.appendingPathComponent(file)- guard fm.fileExists(atPath: member.path) else { throw Error.missingBundle(member) }- }+ try validateBundle(at: source, expectedPlatformVersion: expectedPlatformVersion)try fm.createDirectory(at: destination.deletingLastPathComponent(),withIntermediateDirectories: true)if fm.fileExists(atPath: destination.path) {@@ -114,14 +113,14 @@ public enum VPhonePCCGPUDriver {print("[+] GPU driver staged from PCC OS: \(destination.path)")}- private static func validateBundle(at source: URL) throws {+ static func validateBundle(at source: URL, expectedPlatformVersion: String?) throws {let fm = FileManager.defaultvar isDirectory: ObjCBool = falseguard fm.fileExists(atPath: source.path, isDirectory: &isDirectory), isDirectory.boolValue else {throw Error.invalidCachedBundle(source)}for file in ["AppleParavirtGPUMetalIOGPUFamily",- "libAppleParavirtCompilerPluginIOGPUFamily.dylib", "Info.plist",+ "Info.plist","_CodeSignature/CodeResources"]{guard fm.fileExists(atPath: source.appendingPathComponent(file).path) else {@@ -135,6 +134,14 @@ public enum VPhonePCCGPUDriver {properties["CFBundleIdentifier"] as? String =="com.apple.driver.AppleParavirtGPUMetalIOGPUFamily"else { throw Error.invalidCachedBundle(source) }+ if let expectedPlatformVersion {+ let actual = properties["DTPlatformVersion"] as? String ?? "unknown"+ guard actual == expectedPlatformVersion else {+ throw Error.wrongPlatformVersion(+ source, expected: expectedPlatformVersion, actual: actual,+ )+ }+ }}private static func run(_ tool: String, _ args: [String]) throws {diff --git a/sources/vphone-cli/VPhoneCFWInstaller.swift b/sources/vphone-cli/VPhoneCFWInstaller.swiftindex e9a49c21..dd534bf5 100644--- a/sources/vphone-cli/VPhoneCFWInstaller.swift+++ b/sources/vphone-cli/VPhoneCFWInstaller.swift@@ -71,8 +71,8 @@ struct VPhoneCFWInstaller {}let capacity = try bundle.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey]).volumeAvailableCapacityForImportantUsage ?? 0- guard capacity > 100 * 1024 * 1024 * 1024 else {- throw ValidationError("Less than 100 GiB available; CFW install stopped before mounting")+ guard capacity > 50 * 1024 * 1024 * 1024 else {+ throw ValidationError("Less than 50 GiB available; CFW install stopped before mounting")}let attached = try tool("/usr/bin/hdiutil", [@@ -165,11 +165,14 @@ struct VPhoneCFWInstaller {try fm.copyItem(at: gpuSource, to: gpu)try tool("/usr/sbin/chown", ["-R", "0:0", gpu.path])for file in [gpu, gpu.appendingPathComponent("AppleParavirtGPUMetalIOGPUFamily"),- gpu.appendingPathComponent("libAppleParavirtCompilerPluginIOGPUFamily.dylib"),gpu.appendingPathComponent("_CodeSignature")]{try fm.setAttributes([.posixPermissions: NSNumber(value: 0o755)], ofItemAtPath: file.path)}+ let compilerPlugin = gpu.appendingPathComponent("libAppleParavirtCompilerPluginIOGPUFamily.dylib")+ if fm.fileExists(atPath: compilerPlugin.path) {+ try fm.setAttributes([.posixPermissions: NSNumber(value: 0o755)], ofItemAtPath: compilerPlugin.path)+ }for file in [gpu.appendingPathComponent("Info.plist"),gpu.appendingPathComponent("_CodeSignature/CodeResources")]{diff --git a/sources/vphone-cli/VPhoneFirmwarePreparer.swift b/sources/vphone-cli/VPhoneFirmwarePreparer.swiftindex a6477c79..e0dba36e 100644--- a/sources/vphone-cli/VPhoneFirmwarePreparer.swift+++ b/sources/vphone-cli/VPhoneFirmwarePreparer.swift@@ -76,9 +76,19 @@ enum VPhoneFirmwarePreparer {print(gpuDriverBundle == nil? "[*] Extracting GPU driver from cloudOS PCC image...": "[*] Staging GPU driver from local bundle...")- try VPhonePCCGPUDriver.stage(- from: cloudTree, into: phoneTree, cachedBundle: gpuDriverBundle,- )+ do {+ try VPhonePCCGPUDriver.stage(+ from: cloudTree, into: phoneTree, cachedBundle: gpuDriverBundle,+ expectedPlatformVersion: cloud.version,+ )+ } catch let failure as VPhoneAEA.Error {+ guard case .keyFetchFailed = failure, gpuDriverBundle == nil else { throw failure }+ print("[*] PCC AEA key unavailable; restoring cloudOS in a temporary vphone VM...")+ try VPhonePCCGPURecovery.stage(+ cloudOSDirectory: cloudTree, into: phoneTree,+ expectedPlatformVersion: cloud.version,+ )+ }// The destination did not exist at entry and the staging directory is// on the same volume. One rename exposes the complete restore tree.diff --git a/sources/vphone-cli/VPhonePCCGPURecovery.swift b/sources/vphone-cli/VPhonePCCGPURecovery.swiftnew file mode 100644index 00000000..5f5c534d--- /dev/null+++ b/sources/vphone-cli/VPhonePCCGPURecovery.swift@@ -0,0 +1,144 @@+import Foundation+import VPhoneCore+import VPhoneRestore++/// Restores the selected cloudOS firmware with this project's own VM and+/// idevicerestore backend when Apple's public AEA key is unavailable.+enum VPhonePCCGPURecovery {+ enum Error: Swift.Error, LocalizedError {+ case identityTimedOut+ case recoveryTimedOut+ case toolFailed(String, String)++ var errorDescription: String? {+ switch self {+ case .identityTimedOut:+ "Temporary PCC VM did not report its ECID"+ case .recoveryTimedOut:+ "Temporary PCC VM did not enter DFU/recovery mode"+ case let .toolFailed(tool, detail):+ "\(tool) failed while reading the restored PCC System volume: \(detail)"+ }+ }+ }++ static func stage(+ cloudOSDirectory: URL,+ into restoreDirectory: URL,+ expectedPlatformVersion: String,+ ) throws {+ let fm = FileManager.default+ let temporaryLibrary = restoreDirectory.deletingLastPathComponent()+ .appending(path: ".pcc-restoration")+ let library = VPhoneLibrary(root: temporaryLibrary)+ let name = "pcc-\(UUID().uuidString.lowercased())"+ let vm = try VPhoneBundleOps.create(.init(+ name: name, cpuCount: 8, memoryMB: 8192, diskSizeGB: 64,+ romSource: VPhoneBundleOps.defaultROMSource(),+ sepromSource: VPhoneBundleOps.defaultSEPROMSource(),+ ), in: library)+ defer { try? fm.removeItem(at: temporaryLibrary) }++ // The restore backend accepts a linked directory. Reuse the already+ // extracted cloudOS tree instead of writing a second copy of its OS image.+ try fm.createSymbolicLink(+ at: vm.url.appending(path: "iPhonePCC_Restore"),+ withDestinationURL: cloudOSDirectory,+ )+ let launcher = try VPhoneGuestLaunchPlanner()+ let (executable, arguments) = launcher.plan(["--config", vm.configURL.path, "--dfu"])+ let dfu = VPhoneManagedProcess(executable, arguments, cwd: vm.url, echo: false)+ try dfu.start()+ defer { dfu.terminate(); _ = dfu.waitUntilExit() }++ let deadline = Date().addingTimeInterval(30)+ var ecid: UInt64?+ while Date() < deadline {+ if let value = VPhoneRestoreOps.resolveECID(explicit: nil, bundle: vm),+ let parsed = try VPhoneRestoreIdentity.parseECID(value) {+ ecid = parsed+ break+ }+ Thread.sleep(forTimeInterval: 1)+ }+ guard let ecid else { throw Error.identityTimedOut }+ var reachable = false+ for _ in 1 ... 90 {+ if (try? VPhoneRestoreBridge.recoveryProbe(ecid: ecid, timeout: 2)) != nil {+ reachable = true+ break+ }+ Thread.sleep(forTimeInterval: 2)+ }+ guard reachable else { throw Error.recoveryTimedOut }++ print("[*] Restoring cloudOS to temporary vphone VM (ECID 0x\(VPhoneRestoreIdentity.formatECID(ecid)))...")+ try VPhoneRestoreBridge.restore(+ vmDir: vm.url, ecid: ecid, udid: VPhoneRestoreOps.resolveUDID(bundle: vm),+ erase: true, ticketPath: nil,+ onEvent: VPhoneRestoreConsole.handler(level: .info),+ )+ dfu.terminate()+ _ = dfu.waitUntilExit()++ try stageFromSystemDisk(+ vm.url.appending(path: "Disk.img"), cloudOSDirectory: cloudOSDirectory,+ into: restoreDirectory, expectedPlatformVersion: expectedPlatformVersion,+ )+ }++ private static func stageFromSystemDisk(+ _ diskImage: URL,+ cloudOSDirectory: URL,+ into restoreDirectory: URL,+ expectedPlatformVersion: String,+ ) throws {+ let fm = FileManager.default+ let attached = try run("/usr/bin/hdiutil", [+ "attach", "-readonly", "-nomount", "-imagekey",+ "diskimage-class=CRawDiskImage", diskImage.path,+ ])+ guard let baseDisk = attached.split(whereSeparator: \.isNewline).first?+ .split(whereSeparator: \.isWhitespace).first.map(String.init),+ baseDisk.hasPrefix("/dev/disk")+ else { throw Error.toolFailed("hdiutil", "attached no disk device") }+ defer { _ = try? run("/usr/bin/hdiutil", ["detach", baseDisk]) }++ let info = try run("/usr/sbin/diskutil", ["info", "-plist", "\(baseDisk)s1"])+ guard let plist = try PropertyListSerialization.propertyList(+ from: Data(info.utf8), format: nil,+ ) as? [String: Any],+ let container = plist["APFSContainerReference"] as? String,+ container.hasPrefix("disk")+ else { throw Error.toolFailed("diskutil", "could not locate the restored APFS container") }++ let mount = restoreDirectory.deletingLastPathComponent()+ .appending(path: ".pcc-system-\(UUID().uuidString)")+ try fm.createDirectory(at: mount, withIntermediateDirectories: true)+ defer { try? fm.removeItem(at: mount) }+ try run("/sbin/mount_apfs", ["-o", "rdonly", "/dev/\(container)s1", mount.path])+ defer { _ = try? run("/sbin/umount", [mount.path]) }++ let source = mount.appending(+ path: "System/Library/Extensions/\(VPhonePCCGPUDriver.name)",+ )+ try VPhonePCCGPUDriver.stage(+ from: cloudOSDirectory, into: restoreDirectory, cachedBundle: source,+ expectedPlatformVersion: expectedPlatformVersion,+ )+ print("[+] GPU driver staged from cloudOS restored by vphone-cli")+ }++ @discardableResult+ private static func run(_ executable: String, _ arguments: [String]) throws -> String {+ let result = try VPhoneProcessRunner.runCapturing(+ URL(fileURLWithPath: executable), arguments,+ )+ guard result.succeeded else {+ let detail = result.stderr.isEmpty ? result.stdout : result.stderr+ throw Error.toolFailed(URL(fileURLWithPath: executable).lastPathComponent,+ detail.trimmingCharacters(in: .whitespacesAndNewlines))+ }+ return result.stdout+ }+}diff --git a/tests/VPhoneCoreTests/PCCGPUDriverTests.swift b/tests/VPhoneCoreTests/PCCGPUDriverTests.swiftindex a3d33bd5..fc086e35 100644--- a/tests/VPhoneCoreTests/PCCGPUDriverTests.swift+++ b/tests/VPhoneCoreTests/PCCGPUDriverTests.swift@@ -49,14 +49,14 @@ struct PCCGPUDriverTests {at: source.appendingPathComponent("_CodeSignature"), withIntermediateDirectories: true,)for file in ["AppleParavirtGPUMetalIOGPUFamily",- "libAppleParavirtCompilerPluginIOGPUFamily.dylib","_CodeSignature/CodeResources"]{try Data(file.utf8).write(to: source.appendingPathComponent(file))}let info = try PropertyListSerialization.data(fromPropertyList: ["CFBundleIdentifier":- "com.apple.driver.AppleParavirtGPUMetalIOGPUFamily"],+ "com.apple.driver.AppleParavirtGPUMetalIOGPUFamily",+ "DTPlatformVersion": "26.4"],format: .binary, options: 0,)try info.write(to: source.appendingPathComponent("Info.plist"))@@ -66,11 +66,19 @@ struct PCCGPUDriverTests {from: root.appendingPathComponent("missing-cloudos"),into: restore,cachedBundle: source,+ expectedPlatformVersion: "26.4",)let staged = VPhonePCCGPUDriver.stagedBundle(in: restore)#expect(try Data(contentsOf: staged.appendingPathComponent("AppleParavirtGPUMetalIOGPUFamily"))== Data("AppleParavirtGPUMetalIOGPUFamily".utf8))+ #expect(throws: VPhonePCCGPUDriver.Error.self) {+ try VPhonePCCGPUDriver.stage(+ from: root, into: restore, cachedBundle: source,+ expectedPlatformVersion: "26.1",+ )+ }+try FileManager.default.removeItem(at: source.appendingPathComponent("_CodeSignature/CodeResources"))#expect(throws: VPhonePCCGPUDriver.Error.self) {try VPhonePCCGPUDriver.stage(from: root, into: restore, cachedBundle: source)