Run a virtual iPhone on an Apple Silicon Mac.
Swift
Share downloaded IPSWs and recovered GPU drivers across machines (#516)
Lakr835c4db23d27
diff --git a/Documents/Guides/create-and-run.md b/Documents/Guides/create-and-run.mdindex 88fdc41e..7086a2c2 100644--- a/Documents/Guides/create-and-run.md+++ b/Documents/Guides/create-and-run.md@@ -17,7 +17,7 @@ vphone-cli vm create myphone \Creation runs prepare → firmware patch → online DFU restore → host-mounted CFW installation → first GUI boot. It needs network access for the restore ticket. The caller must provide root privileges for CFW installation; this bundle has no authorization dialog or privilege helper. The default virtual disk is 64 GB. `--keep-artifacts` retains the large prepared restore tree; omit it when disk space matters.-`fw prepare` 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 without the temporary restore. The CLI checks its iPhoneOS platform version against the selected cloudOS version. Each restore obtains its own ticket online.+`fw prepare` 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. The extracted bundle is cached per cloudOS build in `~/.vphone/gpu-drivers/`, so later machines on the same cloudOS skip the temporary restore. `vm create` and `fw prepare` also accept `--gpu-driver-bundle /path/to/AppleParavirtGPUMetalIOGPUFamily.bundle` to reuse a previously extracted bundle without the temporary restore. The CLI checks its iPhoneOS platform version against the selected cloudOS version. Each restore obtains its own ticket online.The build also ships an arm64e GPU compiler plugin in the bundle. `fw prepare` copies it into the staged GPU bundle before firmware patching and installation.@@ -56,9 +56,10 @@ The online restore obtains its ticket in process. For an offline restore, see `v| Default path | Contents || --- | --- || `~/.vphone/machines/<name>/` | One VM, including its disk, `config.plist`, and patch work files |-| `~/.vphone/machines/<name>/.ipsw-cache/` | Remote source IPSWs downloaded for that VM; local IPSWs are read in place |+| `~/.vphone/ipsws/` | Remote source IPSWs, shared by every VM; local IPSWs are read in place |+| `~/.vphone/gpu-drivers/<version>_<build>/` | GPU driver bundles extracted from cloudOS, shared by every VM |-`VPHONE_ROOT` relocates the VM library. `VPHONE_LIBRARY_ROOT` takes precedence for the library alone. Downloaded IPSWs remain cached inside their VM; the prepared restore tree is removed after a successful `vm create` unless `--keep-artifacts` is set.+`VPHONE_ROOT` relocates the VM library and both caches. `VPHONE_LIBRARY_ROOT` takes precedence for the library alone, and `--ipsw-cache <dir>` on `vm create` and `fw prepare` for the IPSW cache alone. Downloaded IPSWs stay cached until you delete them, so a second VM from the same URL downloads nothing; the prepared restore tree is removed after a successful `vm create` unless `--keep-artifacts` is set. VMs prepared by an earlier build may still hold a `.ipsw-cache/` directory; it is safe to delete, and `vm export` leaves it out.```shvphone-cli vm listdiff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swiftindex 9c1a8021..c67ddbf3 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift@@ -202,6 +202,8 @@ struct VPhoneFirmwarePrepareCommand: ParsableCommand {@Option(name: .shortAndLong, help: "cloudOS IPSW URL or local path") var cloudosSource: String?@Option(help: "GPU driver bundle from the same cloudOS build, for offline AEA recovery")var gpuDriverBundle: String?+ @Option(help: "Directory for downloaded IPSWs, shared by every VM (default: ~/.vphone/ipsws or $VPHONE_ROOT/ipsws)")+ var ipswCache: 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@@ -269,6 +271,9 @@ struct VPhoneFirmwarePrepareCommand: ParsableCommand {iPhoneSource: phone,cloudOSSource: cloud,gpuDriverBundle: gpuDriverBundle.map { URL(fileURLWithPath: ($0 as NSString).expandingTildeInPath) },+ ipswCacheDirectory: ipswCache.map {+ URL(fileURLWithPath: ($0 as NSString).expandingTildeInPath, isDirectory: true)+ } ?? VPhoneResources.ipswCacheDirectory(),bundle: bundle,resources: resources,)diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swiftindex d5f59bb9..5cdf0ac2 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift@@ -30,6 +30,7 @@ enum VPhoneFirmwarePreparer {iPhoneSource: String,cloudOSSource: String,gpuDriverBundle: URL? = nil,+ ipswCacheDirectory: URL = VPhoneResources.ipswCacheDirectory(),bundle: VPhoneBundle,resources: VPhoneResources,) throws {@@ -44,16 +45,16 @@ enum VPhoneFirmwarePreparer {}}- // Remote IPSWs belong to this VM, not a writable shared directory.+ // Remote IPSWs go to one cache shared by every machine; keeping them+ // inside the machine downloaded both again for each new one (#513).// Local IPSWs are read in place and are never copied into the cache.- let cacheDirectory = bundle.url.appendingPathComponent(".ipsw-cache", isDirectory: true)print("[*] Resolving iPhone IPSW...")let phone = try vphoneRunBlocking {- try await VPhoneIPSWCache.resolve(iPhoneSource, in: cacheDirectory)+ try await VPhoneIPSWCache.resolve(iPhoneSource, in: ipswCacheDirectory)}print("[*] Resolving cloudOS IPSW...")let cloud = try vphoneRunBlocking {- try await VPhoneIPSWCache.resolve(cloudOSSource, in: cacheDirectory)+ try await VPhoneIPSWCache.resolve(cloudOSSource, in: ipswCacheDirectory)}try VPhoneIPSWCache.checkPair(iPhone: phone, cloudOS: cloud)try checkIPhoneName(iPhoneSource, archive: phone)@@ -86,6 +87,7 @@ enum VPhoneFirmwarePreparer {let originalManifest = phoneTree.appendingPathComponent("BuildManifest.plist")try clone(originalManifest, to: phoneTree.appendingPathComponent("iPhone-BuildManifest.plist"))try FirmwareManifest.generate(iPhoneDir: phoneTree, cloudOSDir: cloudTree, verbose: true)+ let cachedDriver = cachedGPUDriver(for: cloud)if let gpuDriverBundle {print("[*] Staging GPU driver from local bundle...")try VPhonePCCGPUDriver.stage(@@ -93,6 +95,12 @@ enum VPhoneFirmwarePreparer {into: phoneTree,expectedPlatformVersion: cloud.version,)+ } else if (try? VPhonePCCGPUDriver.stage(+ from: cachedDriver,+ into: phoneTree,+ expectedPlatformVersion: cloud.version,+ )) != nil {+ print("[+] GPU driver reused from cloudOS \(cloud.version) (\(cloud.build)) cache")} else {print("[*] Restoring cloudOS in a temporary vphone VM to extract its GPU driver...")try VPhonePCCGPURecovery.stage(@@ -100,6 +108,12 @@ enum VPhoneFirmwarePreparer {into: phoneTree,expectedPlatformVersion: cloud.version,)+ // Every later machine on this cloudOS build skips the restore.+ do {+ try storeGPUDriver(VPhonePCCGPUDriver.stagedBundle(in: phoneTree), at: cachedDriver)+ } catch {+ fputs("warning: could not cache the GPU driver at \(cachedDriver.path): \(error.localizedDescription)\n", stderr)+ }}let source = resources.gpuCompilerPlugin@@ -120,6 +134,48 @@ enum VPhoneFirmwarePreparer {print("[+] Restore tree ready: \(destination.path)")}+ // MARK: - GPU driver cache++ /// Where the driver recovered from this cloudOS build is kept. The bundle+ /// is cached as the System volume has it, before the compiler plugin merge.+ static func cachedGPUDriver(+ for cloud: VPhoneIPSWCache.Archive,+ in cacheDirectory: URL = VPhoneResources.gpuDriverCacheDirectory(),+ ) -> URL {+ cacheDirectory+ .appendingPathComponent("\(cloud.version)_\(cloud.build)", isDirectory: true)+ .appendingPathComponent(VPhonePCCGPUDriver.name, isDirectory: true)+ }++ /// Copies into a private directory, then renames it into place, so a+ /// concurrent prepare never sees half a bundle. If another prepare stores+ /// the same build in between, its copy is kept.+ static func storeGPUDriver(_ bundle: URL, at destination: URL) throws {+ let fm = FileManager.default+ let buildDirectory = destination.deletingLastPathComponent()+ let cacheDirectory = buildDirectory.deletingLastPathComponent()+ try fm.createDirectory(at: cacheDirectory, withIntermediateDirectories: true)+ try VPhoneHostFilePermissions.makeDirectoryAccessible(at: cacheDirectory)+ let pending = cacheDirectory.appendingPathComponent(".\(UUID().uuidString).partial", isDirectory: true)+ defer { try? fm.removeItem(at: pending) }+ try fm.createDirectory(at: pending, withIntermediateDirectories: false)+ try fm.copyItem(at: bundle, to: pending.appendingPathComponent(destination.lastPathComponent))+ try VPhoneHostFilePermissions.makeAccessible(at: pending)+ // This runs only when the cached copy did not stage, so whatever is+ // there is incomplete or damaged and would block the rename for good.+ if fm.fileExists(atPath: buildDirectory.path) {+ try fm.removeItem(at: buildDirectory)+ }+ do {+ try fm.moveItem(at: pending, to: buildDirectory)+ } catch {+ if fm.fileExists(atPath: destination.path) {+ return+ }+ throw error+ }+ }+private static func checkIPhoneName(_ source: String, archive: VPhoneIPSWCache.Archive) throws {let basename = URL(string: source)?.lastPathComponent?? URL(fileURLWithPath: source).lastPathComponentdiff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swiftindex c0169db8..b9242673 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift@@ -15,6 +15,8 @@ struct VPhoneVirtualMachineCreateCommand: ParsableCommand {@Option(name: .shortAndLong, help: "cloudOS IPSW URL or local path") var cloudosSource: String?@Option(help: "GPU driver bundle from the same cloudOS build, for offline AEA recovery")var gpuDriverBundle: String?+ @Option(help: "Directory for downloaded IPSWs, shared by every VM (default: ~/.vphone/ipsws or $VPHONE_ROOT/ipsws)")+ var ipswCache: String?@Option(name: .shortAndLong, help: "Disk size (GB)") var diskSize: UInt64 = 64@Flag(name: .customLong("force-dsc-maxslide"),@@ -28,7 +30,7 @@ struct VPhoneVirtualMachineCreateCommand: ParsableCommand {var frida = false@Flag(name: .customLong("keep-artifacts"),- help: "Keep the prepared restore tree after installation. Source IPSWs are always kept.",+ help: "Keep the prepared restore tree after installation. Downloaded IPSWs always stay in the IPSW cache.",)var keepArtifacts = false@Flag(name: .customShort("v"), help: "Increase verbosity: -v tool detail, -vv guest serial, -vvv internal trace")@@ -55,6 +57,9 @@ struct VPhoneVirtualMachineCreateCommand: ParsableCommand {iphoneSource: sources.iphoneSource,cloudosSource: sources.cloudosSource,gpuDriverBundle: gpuDriverBundle.map { URL(fileURLWithPath: ($0 as NSString).expandingTildeInPath) },+ ipswCacheDirectory: ipswCache.map {+ URL(fileURLWithPath: ($0 as NSString).expandingTildeInPath, isDirectory: true)+ } ?? VPhoneResources.ipswCacheDirectory(),forceDyldSharedCacheMaxSlide: forceDyldSharedCacheMaxSlide,enableFrida: frida,diskSizeGB: diskSize,diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swiftindex 1e0d3794..f9ac9a07 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swift@@ -9,6 +9,7 @@ public extension VPhoneVirtualMachineCreator {public var iphoneSource: String?public var cloudosSource: String?public var gpuDriverBundle: URL?+ public var ipswCacheDirectory: URLpublic var forceDyldSharedCacheMaxSlide: Boolpublic var enableFrida: Boolpublic var cpuCount: UInt@@ -22,6 +23,7 @@ public extension VPhoneVirtualMachineCreator {iphoneSource: String? = nil,cloudosSource: String? = nil,gpuDriverBundle: URL? = nil,+ ipswCacheDirectory: URL = VPhoneResources.ipswCacheDirectory(),forceDyldSharedCacheMaxSlide: Bool = false,enableFrida: Bool = false,cpuCount: UInt = 8,@@ -34,6 +36,7 @@ public extension VPhoneVirtualMachineCreator {self.iphoneSource = iphoneSourceself.cloudosSource = cloudosSourceself.gpuDriverBundle = gpuDriverBundle+ self.ipswCacheDirectory = ipswCacheDirectoryself.forceDyldSharedCacheMaxSlide = forceDyldSharedCacheMaxSlideself.enableFrida = enableFridaself.cpuCount = cpuCountdiff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swiftindex 536bf282..f92a4366 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift@@ -231,6 +231,7 @@ public struct VPhoneVirtualMachineCreator {try VPhoneFirmwarePreparer.prepare(iPhoneSource: phone, cloudOSSource: cloud,gpuDriverBundle: options.gpuDriverBundle,+ ipswCacheDirectory: options.ipswCacheDirectory,bundle: bundle, resources: resources,)print("[+] Firmware prepared (iPhone + cloudOS merged into bundle).")diff --git a/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneBundleTransfer.swift b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneBundleTransfer.swiftindex 51be1e9b..9cbfd538 100644--- a/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneBundleTransfer.swift+++ b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneBundleTransfer.swift@@ -135,8 +135,13 @@ public enum VPhoneBundleTransfer {if !includeIPSW, rel.contains("_Restore") {en.skipDescendants(); continue}- if VPhoneBundleOperations.exportExcludePatterns.contains(where: { fnmatch($0, rel, 0) == 0 }) {- continue+ // The same match as VPhoneArchiveWriter's: the relative path or its+ // last component, and an excluded directory takes its subtree.+ let name = url.lastPathComponent+ if VPhoneBundleOperations.exportExcludePatterns.contains(where: {+ fnmatch($0, rel, 0) == 0 || fnmatch($0, name, 0) == 0+ }) {+ en.skipDescendants(); continue}guard let vals = try? url.resourceValues(forKeys: Set(keys)),vals.isRegularFile == true else { continue }diff --git a/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swift b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swiftindex 1284c3a0..9d4f74c5 100644--- a/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swift+++ b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swift@@ -61,14 +61,13 @@ public enum VPhoneIPSWCache {let fm = FileManager.defaulttry fm.createDirectory(at: cacheDirectory, withIntermediateDirectories: true)+ // Before anything can fail: the directory is shared, and one made by a+ // sudo run must stay writable for the next run without sudo.+ try VPhoneHostFilePermissions.makeDirectoryAccessible(at: cacheDirectory)+ removeAbandonedDownloads(in: cacheDirectory)let cache = cacheDirectory.appendingPathComponent(cacheName(for: url))- if fm.fileExists(atPath: cache.path) {- if let valid = try? inspect(cache) {- try VPhoneHostFilePermissions.makeAccessible(at: cache)- try VPhoneHostFilePermissions.makeDirectoryAccessible(at: cacheDirectory)- return valid- }- try fm.removeItem(at: cache)+ if let valid = try reuse(cache, in: cacheDirectory) {+ return valid}var request = URLRequest(url: url)@@ -108,9 +107,16 @@ public enum VPhoneIPSWCache {}let metadata = try inspect(pending)- try fm.moveItem(at: pending, to: cache)+ do {+ try fm.moveItem(at: pending, to: cache)+ } catch {+ // Another machine's prepare finished the same URL first.+ if let valid = try reuse(cache, in: cacheDirectory) {+ return valid+ }+ throw error+ }try VPhoneHostFilePermissions.makeAccessible(at: cache)- try VPhoneHostFilePermissions.makeDirectoryAccessible(at: cacheDirectory)return Archive(file: cache,version: metadata.version,@@ -120,6 +126,33 @@ public enum VPhoneIPSWCache {)}+ /// The cached archive when it is readable; an unreadable one is removed.+ private static func reuse(_ cache: URL, in cacheDirectory: URL) throws -> Archive? {+ guard FileManager.default.fileExists(atPath: cache.path) else { return nil }+ guard let valid = try? inspect(cache) else {+ try FileManager.default.removeItem(at: cache)+ return nil+ }+ try VPhoneHostFilePermissions.makeAccessible(at: cache)+ return valid+ }++ /// A download still in progress writes to its `.partial` file continuously.+ /// One untouched for an hour belongs to a process that was killed, and in a+ /// shared cache nothing else would ever remove it.+ private static func removeAbandonedDownloads(in cacheDirectory: URL) {+ let fm = FileManager.default+ let names = (try? fm.contentsOfDirectory(atPath: cacheDirectory.path)) ?? []+ let cutoff = Date().addingTimeInterval(-60 * 60)+ for name in names where name.hasPrefix(".") && name.hasSuffix(".partial") {+ let file = cacheDirectory.appendingPathComponent(name)+ guard let modified = try? fm.attributesOfItem(atPath: file.path)[.modificationDate] as? Date,+ modified < cutoff+ else { continue }+ try? fm.removeItem(at: file)+ }+ }+public static func inspect(_ file: URL) throws -> Archive {guard FileManager.default.fileExists(atPath: file.path) else {throw Error.missingFile(file)diff --git a/VPhoneKit/VPhoneArchiveKitTests/BundleTransferTests.swift b/VPhoneKit/VPhoneArchiveKitTests/BundleTransferTests.swiftindex d7a55514..0677c37f 100644--- a/VPhoneKit/VPhoneArchiveKitTests/BundleTransferTests.swift+++ b/VPhoneKit/VPhoneArchiveKitTests/BundleTransferTests.swift@@ -161,6 +161,34 @@ struct BundleTransferTests {#expect(members.contains("orig/config.plist"))}+ /// A machine prepared while IPSWs were cached inside it still carries them.+ /// They are a cache, so they stay out even with `--include-ipsw`, which is+ /// about the restore tree; so do staging directories left by a failed detach.+ @Test func `export excludes the IPSW cache and staging leftovers`() throws {+ let root = try makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let lib = VPhoneLibrary(root: root)+ let b = try makeBundle("orig", in: lib)+ let fm = FileManager.default+ for directory in [".ipsw-cache", ".firmware-prepare-A", ".pcc-restoration-B", ".pcc-system-C"] {+ let url = b.url.appendingPathComponent(directory)+ try fm.createDirectory(at: url, withIntermediateDirectories: true)+ try Data([0]).write(to: url.appendingPathComponent("payload"))+ }+ let gpu = b.url.appendingPathComponent("iPhone_Restore/.pcc-gpu")+ try fm.createDirectory(at: gpu, withIntermediateDirectories: true)+ try Data([0]).write(to: gpu.appendingPathComponent("marker"))++ for includeIPSW in [false, true] {+ let archive = root.appendingPathComponent("orig-\(includeIPSW).tgz")+ try VPhoneBundleTransfer.export(bundleNamed: "orig", to: archive, includeIPSW: includeIPSW, in: lib)+ let members = try VPhoneArchiveReader.entries(of: archive).map(\.path)+ #expect(!members.contains { $0.contains("payload") })+ #expect(members.contains("orig/Disk.img"))+ #expect(members.contains("orig/iPhone_Restore/.pcc-gpu/marker") == includeIPSW)+ }+ }+// MARK: - Malformed input@Test func `import rejects multi top level archive`() throws {diff --git a/VPhoneKit/VPhoneArchiveKitTests/IPSWCacheTests.swift b/VPhoneKit/VPhoneArchiveKitTests/IPSWCacheTests.swiftindex 6135ead3..b5cab31f 100644--- a/VPhoneKit/VPhoneArchiveKitTests/IPSWCacheTests.swift+++ b/VPhoneKit/VPhoneArchiveKitTests/IPSWCacheTests.swift@@ -120,6 +120,40 @@ struct IPSWCacheTests {))}+ /// The cache is shared by every machine, so a download killed midway would+ /// otherwise leave its partial file there for good.+ @Test func `abandoned partial downloads are removed and live ones kept`() async throws {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let source = try fixture(in: root)+ IPSWStubProtocol.payload = try Data(contentsOf: source)+ IPSWStubProtocol.status = 200+ let configuration = URLSessionConfiguration.ephemeral+ configuration.protocolClasses = [IPSWStubProtocol.self]+ let session = URLSession(configuration: configuration)+ defer { session.invalidateAndCancel() }++ let cacheDir = root.appendingPathComponent("cache")+ try FileManager.default.createDirectory(at: cacheDir, withIntermediateDirectories: true)+ let abandoned = cacheDir.appendingPathComponent(".other.ipsw.A.partial")+ let live = cacheDir.appendingPathComponent(".other.ipsw.B.partial")+ try Data("stale".utf8).write(to: abandoned)+ try Data("live".utf8).write(to: live)+ try FileManager.default.setAttributes(+ [.modificationDate: Date().addingTimeInterval(-2 * 60 * 60)],+ ofItemAtPath: abandoned.path,+ )++ _ = try await VPhoneIPSWCache.resolve(+ "https://example.invalid/input.ipsw",+ in: cacheDir,+ session: session,+ )+ #expect(!FileManager.default.fileExists(atPath: abandoned.path))+ #expect(FileManager.default.fileExists(atPath: live.path))+ }+// MARK: - Pairingprivate func ipsw(in root: URL, _ name: String, productTypes: [String], deviceClasses: [String]) throws -> VPhoneIPSWCache.Archive {diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swiftindex 6d14d6b7..04fcda78 100644--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift@@ -176,9 +176,20 @@ public enum VPhoneBundleOperations {// MARK: - Export/// `.vphoned.signed` is re-staged on the next launch and need not be exported.+ /// `.ipsw-cache` holds the downloaded IPSWs of machines prepared before the+ /// cache moved to `VPhoneResources.ipswCacheDirectory()`; it is a cache,+ /// not part of the machine. The staging directories are left behind only+ /// when a disk image could not be detached, and one can hold a whole+ /// temporary cloudOS VM. None of these is `--include-ipsw`'s restore tree.////// Export itself is `VPhoneBundleTransfer` in `VPhoneArchiveKit` — it needs/// libarchive, and this does not. The list stays here because it describes/// what a bundle is, and `VPhoneRestoreInfo` is checked against it.- public static let exportExcludePatterns = ["*.vphoned.signed"]+ public static let exportExcludePatterns = [+ "*.vphoned.signed",+ ".ipsw-cache",+ ".firmware-prepare-*",+ ".pcc-restoration-*",+ ".pcc-system-*",+ ]}diff --git a/VPhoneKit/VPhoneCoreKit/Firmware/VPhoneResources.swift b/VPhoneKit/VPhoneCoreKit/Firmware/VPhoneResources.swiftindex d1f6f1ec..2f84118d 100644--- a/VPhoneKit/VPhoneCoreKit/Firmware/VPhoneResources.swift+++ b/VPhoneKit/VPhoneCoreKit/Firmware/VPhoneResources.swift@@ -118,7 +118,8 @@ public struct VPhoneResources: Sendable {// MARK: - Cache dirs- /// The per-user VM library root: `$VPHONE_ROOT` when set, else `~/.vphone`.+ /// The per-user data root: `$VPHONE_ROOT` when set, else `~/.vphone`. The+ /// default VM library and the shared firmware caches live under it.public static func userDataRoot() -> URL {if let root = ProcessInfo.processInfo.environment["VPHONE_ROOT"], !root.isEmpty {return URL(fileURLWithPath: root, isDirectory: true)@@ -127,6 +128,18 @@ public struct VPhoneResources: Sendable {return home.appendingPathComponent(".vphone")}+ /// Remote IPSWs, shared by every machine. Each file is named after its+ /// source URL, so a second machine from the same URL downloads nothing.+ public static func ipswCacheDirectory() -> URL {+ userDataRoot().appendingPathComponent("ipsws", isDirectory: true)+ }++ /// GPU driver bundles recovered from cloudOS, one directory per build.+ /// Recovering one restores cloudOS into a temporary VM.+ public static func gpuDriverCacheDirectory() -> URL {+ userDataRoot().appendingPathComponent("gpu-drivers", isDirectory: true)+ }+// MARK: - No interpreter// There is deliberately nothing here any more.diff --git a/VPhoneKit/VPhoneCoreKitTests/Firmware/ResourcesTests.swift b/VPhoneKit/VPhoneCoreKitTests/Firmware/ResourcesTests.swiftindex 17ef9aef..0a47faa7 100644--- a/VPhoneKit/VPhoneCoreKitTests/Firmware/ResourcesTests.swift+++ b/VPhoneKit/VPhoneCoreKitTests/Firmware/ResourcesTests.swift@@ -54,6 +54,18 @@ struct ResourcesTests {}}+ /// Firmware caches are shared by every machine, not kept inside one, so a+ /// second machine from the same source does not download it again.+ @Test func `firmware caches sit under the user data root`() {+ ProcessEnvironment.withOverrides([+ "VPHONE_ROOT": "/tmp/vphone-test-root",+ "VPHONE_LIBRARY_ROOT": "/tmp/vphone-test-library",+ ]) {+ #expect(VPhoneResources.ipswCacheDirectory().path == "/tmp/vphone-test-root/ipsws")+ #expect(VPhoneResources.gpuDriverCacheDirectory().path == "/tmp/vphone-test-root/gpu-drivers")+ }+ }+/// `VPhoneResources` resolves programs as siblings of the running image and/// scripts under `scriptsDir`, and nothing else — no `PATH` walk, no/// interpreter. That claim is what the deleted venv tests used to guard