Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Save and revert a stopped machine's disk state with vm snapshot

Jackyead66d10153d
diff --git a/Documents/Guides/snapshots.md b/Documents/Guides/snapshots.md
new file mode 100644
index 00000000..c32fa9f9
--- /dev/null
+++ b/Documents/Guides/snapshots.md
@@ -0,0 +1,71 @@
+# Snapshots
+
+[Documentation](../README.md) · [Create a VM](create-and-run.md) · [Troubleshooting](troubleshooting.md)
+
+A snapshot saves a stopped VM's disk and boot state so you can return to it
+later: take one after a clean install, try something destructive in the guest,
+then revert.
+
+```sh
+vphone-cli vm snapshot create myphone clean --note "fresh install"
+vphone-cli vm snapshot list myphone
+vphone-cli vm snapshot revert myphone clean
+vphone-cli vm snapshot delete myphone clean
+```
+
+`revert` and `delete` ask before they change anything; `--force` skips the
+question. A revert keeps the snapshot, so you can go back to it again.
+`list --json` prints an array of `{"name", "created", "note"}` objects, oldest
+first, with `created` in ISO 8601 and `note` left out when there is none.
+
+## Stop the VM first
+
+`create` and `revert` refuse while the VM is running, and so does anything that
+holds its disk image, `SEPStorage` or `nvram.bin` open. Stop it with
+`vphone-cli vm stop myphone` or from its window, then try again.
+
+The three files move together. The Secure Enclave's anti-replay counters live in
+`SEPStorage`, and the disk holds the matching state. A disk from one moment with
+a `SEPStorage` from another makes the SEP panic on the next boot, so a snapshot
+always takes all three at once and a revert always puts all three back.
+
+`list` and `delete` work while the VM runs; neither touches its live files.
+
+## What a snapshot holds
+
+| Captured | Why |
+| --- | --- |
+| The disk image (`Disk.img`) | The guest's system and data |
+| `SEPStorage`, `nvram.bin` | Secure Enclave state and the boot chain's NVRAM, which must match the disk |
+| `PatchReceipt.plist` | Which patches are live in the guest |
+| `restore-info.json` | The iOS version on the disk, and whether `cfw install` finished |
+
+The last two are taken when present. If one did not exist when the snapshot was
+taken, a revert removes it, so the records describe the restored disk rather
+than a later install.
+
+Not captured, and unchanged by a revert:
+
+- `config.plist`: the device identity, CPU, memory, network and other settings.
+ Change them with `vm config` whenever you like; a revert does not undo that.
+- Patch choices (`PatchSelection.plist`), the restore tree, `FirmwareOriginals/`
+ and the ROMs. These are inputs on the Mac, not guest state.
+- `launchpad.json`. Launchpad saves its own copy in the snapshot folder and puts
+ it back itself. The CLI keeps any extra file in a snapshot folder untouched and
+ deletes it with the snapshot.
+
+## Disk space
+
+Snapshots live in `<vm>/Snapshots/<name>/` as APFS clones. Taking one is instant
+and costs no space; the VM and its snapshots share every block until the guest
+writes to it, and then only the changed blocks take new space. Because of this,
+`du` and Finder count each snapshot at the full size of the disk and overstate
+what it really uses. Free space on the volume is the honest measure.
+
+The VM must be on an APFS volume. Elsewhere `create` refuses rather than copying
+a disk image that can be tens of gigabytes.
+
+## Clones and exports
+
+`vm clone` and `vm export` leave snapshots behind: a clone or an imported VM
+starts with none. Deleting or renaming a VM takes its snapshots with it.
diff --git a/Documents/README.md b/Documents/README.md
index 90ff627e..bdf32934 100644
--- a/Documents/README.md
+++ b/Documents/README.md
@@ -7,6 +7,7 @@ Start with the [Launchpad quick start](../README.md#get-started). For terminal u
| [Downloads](Downloads/README.md) | Notarized Launchpad versions and matching `VPhone.bundle` versions |
| [Host Setup](Guides/host-setup.md) | Apple Silicon, SIP and AMFI settings, signing and preflight |
| [Create and Run](Guides/create-and-run.md) | Firmware inputs, full or manual pipeline, vphoned, storage and backups |
+| [Snapshots](Guides/snapshots.md) | Saving a stopped VM's disk state and reverting to it |
| [Compatibility](Guides/compatibility.md) | Verified firmware pairs and what the checks prove |
| [iPadOS Guests](Guides/ipados.md) | Running iPadOS from an iPad restore IPSW instead of iOS |
| [Other iPhone Models](Guides/iphone-models.md) | Running iOS from an iPhone 16 Pro, 17, 17 Pro, Air or other model's IPSW |
diff --git a/README.md b/README.md
index 9f12ef15..cb3f86ec 100644
--- a/README.md
+++ b/README.md
@@ -76,6 +76,7 @@ To turn on the automation API, add `--api-listen 127.0.0.1:8765` at launch and u
| [Downloads](Documents/Downloads/README.md) | Notarized Launchpad versions and matching `VPhone.bundle` versions |
| [Host Setup](Documents/Guides/host-setup.md) | SIP and AMFI settings, building from source, environment checks |
| [Create and Run](Documents/Guides/create-and-run.md) | Firmware sources, the creation process, storage and backups |
+| [Snapshots](Documents/Guides/snapshots.md) | Save a stopped VM's disk state and revert to it |
| [Compatibility](Documents/Guides/compatibility.md) | Verified firmware pairings |
| [iPadOS Guests](Documents/Guides/ipados.md) | Run iPadOS (iPad mini A17 Pro) instead of iOS |
| [Package Environment](Documents/Guides/package-environment.md) | Installing and removing a package manager in the VM |
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift
index c97680ff..ddcec0a7 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift
@@ -18,6 +18,7 @@ struct VPhoneVirtualMachineCommand: ParsableCommand {
VPhoneVirtualMachineRenameCommand.self,
VPhoneVirtualMachineDeleteCommand.self,
VPhoneVirtualMachineCloneCommand.self,
+ VPhoneVirtualMachineSnapshotCommand.self,
VPhoneVirtualMachineExportCommand.self,
VPhoneVirtualMachineImportCommand.self,
VPhoneVirtualMachineLaunchCommand.self,
@@ -159,6 +160,9 @@ struct VPhoneVirtualMachineInfoCommand: ParsableCommand {
print("disk: \(report.diskSizeBytes) bytes")
print("net: \(describeNetwork(report.network))")
print("unlock: \(report.unlocksAtStartup ? "on" : "off")")
+ if let snapshots = try? VPhoneMachineSnapshots.list(of: bundle), !snapshots.isEmpty {
+ print("snapshots: \(snapshots.count)")
+ }
if let udid = report.udid {
print("udid: \(udid)")
}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineSnapshotCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineSnapshotCommand.swift
new file mode 100644
index 00000000..7365a590
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineSnapshotCommand.swift
@@ -0,0 +1,176 @@
+import ArgumentParser
+import Foundation
+import VPhoneCoreKit
+
+// MARK: - snapshot
+
+/// `vm snapshot`: save and restore a stopped machine's disk, SEP and NVRAM
+/// together. Launchpad drives these verbs and reads `list --json`, so their
+/// arguments and output are a contract with it.
+struct VPhoneVirtualMachineSnapshotCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "snapshot",
+ abstract: "Save a stopped VM's disk state, and revert to it later",
+ discussion: """
+ A snapshot holds the disk image, SEPStorage and nvram.bin from one moment, plus the \
+ records that describe them (PatchReceipt.plist, restore-info.json). They are APFS \
+ clones in <vm>/Snapshots/<name>/, so a snapshot costs no space until the VM writes \
+ to its disk, and the VM must be on an APFS volume.
+
+ The VM must be stopped to take or revert to a snapshot: the SEP's state and the \
+ disk advance together, and a mismatched pair panics the guest.
+
+ config.plist is not part of a snapshot: the VM keeps its identity, CPU, memory, \
+ network and settings across a revert. vm export and vm clone leave snapshots behind.
+ """,
+ subcommands: [
+ VPhoneVirtualMachineSnapshotCreateCommand.self,
+ VPhoneVirtualMachineSnapshotListCommand.self,
+ VPhoneVirtualMachineSnapshotRevertCommand.self,
+ VPhoneVirtualMachineSnapshotDeleteCommand.self,
+ ],
+ )
+
+ /// Local time, to the second: what `list` shows a person.
+ static func describe(_ date: Date) -> String {
+ let formatter = DateFormatter()
+ formatter.locale = Locale(identifier: "en_US_POSIX")
+ formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
+ return formatter.string(from: date)
+ }
+
+ static func confirm(_ question: String) -> Bool {
+ print("\(question) [y/N] ", terminator: "")
+ return (readLine() ?? "").lowercased() == "y"
+ }
+}
+
+// MARK: - create
+
+struct VPhoneVirtualMachineSnapshotCreateCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "create",
+ abstract: "Take a snapshot of a stopped VM",
+ )
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Argument(help: "VM name") var vm: String
+ @Argument(help: "Snapshot name") var name: String
+ @Option(name: .long, help: "A note to keep with the snapshot") var note: String?
+
+ func run() throws {
+ let bundle = try lib.library.bundle(named: vm)
+ let snapshot = try VPhoneMachineSnapshots.create(name, note: note, of: bundle)
+ print("created snapshot '\(snapshot.name)' of \(bundle.name)")
+ }
+}
+
+// MARK: - list
+
+struct VPhoneVirtualMachineSnapshotListCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "list",
+ abstract: "List a VM's snapshots, oldest first",
+ )
+
+ /// One `--json` element. A missing note is left out of the object.
+ struct Entry: Encodable {
+ let name: String
+ let created: Date
+ let note: String?
+ }
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Argument(help: "VM name") var vm: String
+ @Flag(name: .shortAndLong, help: "Emit JSON") var json = false
+
+ func run() throws {
+ let bundle = try lib.library.bundle(named: vm)
+ let snapshots = try VPhoneMachineSnapshots.list(of: bundle)
+ if json {
+ let encoder = JSONEncoder()
+ encoder.dateEncodingStrategy = .iso8601
+ encoder.outputFormatting = [.sortedKeys]
+ let entries = snapshots.map { Entry(name: $0.name, created: $0.created, note: $0.note) }
+ try print(String(decoding: encoder.encode(entries), as: UTF8.self))
+ return
+ }
+ guard !snapshots.isEmpty else {
+ print("No snapshots of \(bundle.name). Take one with vm snapshot create \(bundle.name) <name>.")
+ return
+ }
+ let width = max(4, snapshots.map(\.name.count).max() ?? 0)
+ print("NAME".padding(toLength: width, withPad: " ", startingAt: 0) + " CREATED NOTE")
+ for snapshot in snapshots {
+ let name = snapshot.name.padding(toLength: width, withPad: " ", startingAt: 0)
+ let created = VPhoneVirtualMachineSnapshotCommand.describe(snapshot.created)
+ print("\(name) \(created) \(snapshot.note ?? "")")
+ }
+ }
+}
+
+// MARK: - revert
+
+struct VPhoneVirtualMachineSnapshotRevertCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "revert",
+ abstract: "Put a stopped VM back to a snapshot; the snapshot is kept",
+ )
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Argument(help: "VM name") var vm: String
+ @Argument(help: "Snapshot name") var name: String
+ @Flag(name: .shortAndLong, help: "Do not prompt") var force = false
+
+ func run() throws {
+ let bundle = try lib.library.bundle(named: vm)
+ // Refuse before asking, not after.
+ let snapshot = try VPhoneMachineSnapshots.snapshot(named: name, of: bundle)
+ try VPhoneBundleActivity.requireStopped(bundle)
+ if !force {
+ let taken = VPhoneVirtualMachineSnapshotCommand.describe(snapshot.created)
+ guard VPhoneVirtualMachineSnapshotCommand.confirm(
+ "Revert '\(bundle.name)' to snapshot '\(snapshot.name)' from \(taken)? Everything the VM wrote since is lost.",
+ ) else {
+ print("Canceled. Nothing was changed.")
+ return
+ }
+ }
+ try VPhoneMachineSnapshots.revert(to: name, of: bundle)
+ print("reverted \(bundle.name) to snapshot '\(snapshot.name)'")
+ }
+}
+
+// MARK: - delete
+
+struct VPhoneVirtualMachineSnapshotDeleteCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "delete",
+ abstract: "Delete a snapshot",
+ )
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Argument(help: "VM name") var vm: String
+ @Argument(help: "Snapshot name") var name: String
+ @Flag(name: .shortAndLong, help: "Do not prompt") var force = false
+
+ func run() throws {
+ let bundle = try lib.library.bundle(named: vm)
+ try VPhoneMachineSnapshots.requireValidName(name)
+ guard FileManager.default.fileExists(
+ atPath: VPhoneMachineSnapshots.directory(of: bundle).appendingPathComponent(name).path,
+ ) else {
+ throw VPhoneMachineSnapshotError.notFound(machine: bundle.name, name: name)
+ }
+ if !force {
+ guard VPhoneVirtualMachineSnapshotCommand.confirm(
+ "Delete snapshot '\(name)' of '\(bundle.name)'?",
+ ) else {
+ print("Canceled. Nothing was deleted.")
+ return
+ }
+ }
+ try VPhoneMachineSnapshots.delete(name, of: bundle)
+ print("deleted snapshot '\(name)' of \(bundle.name)")
+ }
+}
diff --git a/VPhoneKit/VPhoneArchiveKitTests/BundleTransferTests.swift b/VPhoneKit/VPhoneArchiveKitTests/BundleTransferTests.swift
index 0677c37f..a271b007 100644
--- a/VPhoneKit/VPhoneArchiveKitTests/BundleTransferTests.swift
+++ b/VPhoneKit/VPhoneArchiveKitTests/BundleTransferTests.swift
@@ -161,6 +161,26 @@ struct BundleTransferTests {
#expect(members.contains("orig/config.plist"))
}
+ /// Snapshots are clones on the machine's own volume; in an archive each
+ /// would be another full disk image. They stay out even with
+ /// `--include-ipsw`.
+ @Test func `export leaves snapshots behind`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let lib = VPhoneLibrary(root: root)
+ let b = try makeBundle("orig", in: lib)
+ try Data([1]).write(to: b.url.appendingPathComponent("nvram.bin"))
+ try VPhoneMachineSnapshots.create("clean", of: b)
+
+ 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(VPhoneMachineSnapshots.directoryName) })
+ #expect(members.contains("orig/Disk.img"))
+ }
+ }
+
/// 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.
diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift
index 71d8bd34..ce1e2696 100644
--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift
+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift
@@ -194,6 +194,9 @@ public enum VPhoneBundleOperations {
/// 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.
+ /// Snapshots stay with the machine they were taken on: in an archive each
+ /// one would be another full copy of the disk. A revert's staging folder
+ /// is left behind only by a revert that was killed.
///
/// Export itself is `VPhoneBundleTransfer` in `VPhoneArchiveKit` — it needs
/// libarchive, and this does not. The list stays here because it describes
@@ -204,6 +207,8 @@ public enum VPhoneBundleOperations {
".firmware-prepare-*",
".pcc-restoration-*",
".pcc-system-*",
+ VPhoneMachineSnapshots.directoryName,
+ ".snapshot-revert-*",
]
/// The directory holding each boot-chain file exactly as the restore tree laid
diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineSnapshots.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineSnapshots.swift
new file mode 100644
index 00000000..0fadaf56
--- /dev/null
+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineSnapshots.swift
@@ -0,0 +1,374 @@
+import Darwin
+import Foundation
+
+// MARK: - Snapshot
+
+/// One saved moment of a machine's guest state, in
+/// `<machine>/Snapshots/<name>/`. Not to be confused with
+/// `VPhoneAPFSSnapshot`, which renames the guest's own APFS root snapshot
+/// inside the disk image.
+public struct VPhoneMachineSnapshot: Codable, Equatable, Sendable {
+ public let name: String
+ public let created: Date
+ public let note: String?
+ /// The state files copied into the snapshot, by their names in the
+ /// machine folder.
+ public let files: [String]
+ /// State files the machine did not have when the snapshot was taken.
+ /// Revert removes them, so the restored set describes the same moment:
+ /// a `restore-info.json` written by a later `cfw install` must not
+ /// survive a revert to before it.
+ public let absentFiles: [String]
+
+ public init(name: String, created: Date, note: String?, files: [String], absentFiles: [String]) {
+ self.name = name
+ self.created = created
+ self.note = note
+ self.files = files
+ self.absentFiles = absentFiles
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case name = "Name"
+ case created = "Created"
+ case note = "Note"
+ case files = "Files"
+ case absentFiles = "AbsentFiles"
+ }
+}
+
+// MARK: - Snapshots
+
+/// Machine disk snapshots: APFS clones of the files that describe the guest,
+/// taken and put back only while the machine is stopped.
+///
+/// The disk image, `SEPStorage` and `nvram.bin` are one unit. The SEP's
+/// anti-replay counters and the xART gigalocker on the disk advance as a pair,
+/// so a disk from one moment with a `SEPStorage` from another panics the SEP.
+/// Every operation that copies or replaces them first checks
+/// `VPhoneBundleActivity.requireStopped`.
+///
+/// Snapshots are clones, never copies: `clonefile(2)` costs nothing on APFS,
+/// and a full copy of a 60 GB image is not what anyone asked for. Off APFS the
+/// operation is refused.
+///
+/// A snapshot directory is the CLI's metadata file and state files, plus
+/// whatever else a client put there (Launchpad keeps its `launchpad.json`
+/// binding beside them). Unknown files are never read, kept as they are, and
+/// removed with the snapshot.
+public enum VPhoneMachineSnapshots {
+ /// Inside the machine folder. `vm export` leaves it out, and a clone
+ /// starts without it.
+ public static let directoryName = "Snapshots"
+ public static let metadataFileName = "Snapshot.plist"
+
+ // MARK: State files
+
+ /// The files that must be captured, by their names in the machine folder.
+ public static func requiredStateFileNames(of bundle: VPhoneBundle) -> [String] {
+ [bundle.manifest.diskImage, bundle.manifest.sepStorage, bundle.manifest.nvramStorage]
+ }
+
+ /// Captured when present, and recorded as absent otherwise.
+ ///
+ /// The set is what changes after creation to describe the guest rather
+ /// than the machine:
+ ///
+ /// - `PatchReceipt.plist` records which patches are live in the guest.
+ /// `restore`, `cfw install` and `cfw update-environment` / `update-kernel`
+ /// rewrite it as they put bytes on the disk or in the boot chain.
+ /// - `restore-info.json` records the OS restored onto the disk, and its
+ /// variant is how `cfw install` marks the guest bootable (Launchpad's
+ /// "custom firmware installed").
+ ///
+ /// Left out on purpose:
+ ///
+ /// - `config.plist`: identity (ECID, MAC), CPU, memory, network and
+ /// settings must survive a revert.
+ /// - `launchpad.json`: Launchpad's, which keeps its own copy in the
+ /// snapshot directory.
+ /// - `PatchSelection.plist` is what the owner wants, a setting.
+ /// `PatchPlan.plist` and `FirmwareOriginals/` describe the restore tree
+ /// and boot chain `fw patch` built on the host, which a snapshot does
+ /// not carry either; the receipt is what records what the guest runs.
+ /// - `udid-prediction.txt` follows the identity; the ROMs are the
+ /// machine's hardware; `.vphoned.signed` is staged at every launch.
+ public static let optionalStateFileNames = ["PatchReceipt.plist", "restore-info.json"]
+
+ public static func directory(of bundle: VPhoneBundle) -> URL {
+ bundle.url.appendingPathComponent(directoryName, isDirectory: true)
+ }
+
+ // MARK: Names
+
+ /// The same rules as a machine name: not empty, no `/`, not starting
+ /// with `.` (the staging directories are hidden).
+ public static func requireValidName(_ name: String) throws {
+ guard !name.isEmpty, !name.contains("/"), !name.hasPrefix("."), !name.contains("\0") else {
+ throw VPhoneMachineSnapshotError.invalidName(name)
+ }
+ }
+
+ // MARK: List
+
+ /// Every snapshot, oldest first. A directory whose metadata cannot be read
+ /// is not listed; `delete` still removes it.
+ public static func list(of bundle: VPhoneBundle) throws -> [VPhoneMachineSnapshot] {
+ let root = directory(of: bundle)
+ let fm = FileManager.default
+ guard fm.fileExists(atPath: root.path) else { return [] }
+ let names = try fm.contentsOfDirectory(atPath: root.path)
+ return names
+ .filter { !$0.hasPrefix(".") }
+ .compactMap { try? readMetadata(named: $0, in: root) }
+ .sorted { ($0.created, $0.name) < ($1.created, $1.name) }
+ }
+
+ public static func snapshot(named name: String, of bundle: VPhoneBundle) throws -> VPhoneMachineSnapshot {
+ try requireValidName(name)
+ let root = directory(of: bundle)
+ guard isDirectory(root.appendingPathComponent(name)) else {
+ throw VPhoneMachineSnapshotError.notFound(machine: bundle.name, name: name)
+ }
+ return try readMetadata(named: name, in: root)
+ }
+
+ // MARK: Create
+
+ /// Clones the state files into `Snapshots/<name>/`. The snapshot is built
+ /// in a hidden staging directory and renamed into place, so a failure
+ /// leaves nothing behind and a listed snapshot is always complete.
+ @discardableResult
+ public static func create(
+ _ name: String,
+ note: String? = nil,
+ of bundle: VPhoneBundle,
+ now: Date = Date(),
+ ) throws -> VPhoneMachineSnapshot {
+ try requireValidName(name)
+ let root = directory(of: bundle)
+ let destination = root.appendingPathComponent(name, isDirectory: true)
+ if FileManager.default.fileExists(atPath: destination.path) {
+ throw VPhoneMachineSnapshotError.alreadyExists(machine: bundle.name, name: name)
+ }
+ try VPhoneBundleActivity.requireStopped(bundle)
+
+ var files: [String] = []
+ var absent: [String] = []
+ for file in requiredStateFileNames(of: bundle) {
+ guard isRegularFile(bundle.url.appendingPathComponent(file)) else {
+ throw VPhoneMachineSnapshotError.missingStateFile(machine: bundle.name, file: file)
+ }
+ files.append(file)
+ }
+ for file in optionalStateFileNames {
+ if isRegularFile(bundle.url.appendingPathComponent(file)) {
+ files.append(file)
+ } else {
+ absent.append(file)
+ }
+ }
+
+ let fm = FileManager.default
+ try fm.createDirectory(at: root, withIntermediateDirectories: true)
+ let staging = root.appendingPathComponent(".creating-\(UUID().uuidString)", isDirectory: true)
+ try fm.createDirectory(at: staging, withIntermediateDirectories: false)
+ do {
+ for file in files {
+ try cloneFile(
+ bundle.url.appendingPathComponent(file),
+ to: staging.appendingPathComponent(file),
+ )
+ }
+ let snapshot = VPhoneMachineSnapshot(
+ name: name,
+ created: now,
+ note: note.flatMap { $0.isEmpty ? nil : $0 },
+ files: files,
+ absentFiles: absent,
+ )
+ let encoder = PropertyListEncoder()
+ encoder.outputFormat = .xml
+ try encoder.encode(snapshot).write(to: staging.appendingPathComponent(metadataFileName))
+ try VPhoneHostFilePermissions.makeAccessible(at: staging)
+ // Exclusive: a snapshot of the same name made meanwhile is not replaced.
+ guard renamex_np(staging.path, destination.path, UInt32(RENAME_EXCL)) == 0 else {
+ if errno == EEXIST {
+ throw VPhoneMachineSnapshotError.alreadyExists(machine: bundle.name, name: name)
+ }
+ throw VPhoneMachineSnapshotError.failed(path: destination.path, reason: currentErrorText())
+ }
+ try VPhoneHostFilePermissions.makeDirectoryAccessible(at: root)
+ return snapshot
+ } catch {
+ try? fm.removeItem(at: staging)
+ removeIfEmpty(root)
+ throw error
+ }
+ }
+
+ // MARK: Revert
+
+ /// Puts the snapshot's state files back over the live ones and keeps the
+ /// snapshot.
+ ///
+ /// Every file is cloned into a hidden directory in the machine folder
+ /// first; only when all of them are there does each one replace its live
+ /// file with `rename(2)`. A failure while cloning leaves the live set
+ /// untouched, and the switch itself is a handful of renames on one volume.
+ @discardableResult
+ public static func revert(to name: String, of bundle: VPhoneBundle) throws -> VPhoneMachineSnapshot {
+ let snapshot = try snapshot(named: name, of: bundle)
+ let source = directory(of: bundle).appendingPathComponent(name, isDirectory: true)
+ for file in snapshot.files + snapshot.absentFiles {
+ try requireStateFileName(file, snapshot: name)
+ }
+ try VPhoneBundleActivity.requireStopped(bundle)
+
+ let fm = FileManager.default
+ let staging = bundle.url.appendingPathComponent(".snapshot-revert-\(UUID().uuidString)", isDirectory: true)
+ try fm.createDirectory(at: staging, withIntermediateDirectories: false)
+ defer { try? fm.removeItem(at: staging) }
+
+ for file in snapshot.files {
+ let from = source.appendingPathComponent(file)
+ guard isRegularFile(from) else {
+ throw VPhoneMachineSnapshotError.damaged(
+ name: name,
+ reason: "\(file) is missing from the snapshot",
+ )
+ }
+ try cloneFile(from, to: staging.appendingPathComponent(file))
+ }
+ try VPhoneHostFilePermissions.makeAccessible(at: staging)
+
+ // Checked again just before the live files change: the clones above
+ // take a moment, and nothing may open the machine meanwhile.
+ try VPhoneBundleActivity.requireStopped(bundle)
+ for file in snapshot.files {
+ let live = bundle.url.appendingPathComponent(file)
+ guard rename(staging.appendingPathComponent(file).path, live.path) == 0 else {
+ throw VPhoneMachineSnapshotError.failed(path: live.path, reason: currentErrorText())
+ }
+ }
+ for file in snapshot.absentFiles {
+ let live = bundle.url.appendingPathComponent(file)
+ if unlink(live.path) != 0, errno != ENOENT {
+ throw VPhoneMachineSnapshotError.failed(path: live.path, reason: currentErrorText())
+ }
+ }
+ return snapshot
+ }
+
+ // MARK: Delete
+
+ /// Removes the snapshot directory and everything in it. The live state is
+ /// not touched, so a running machine does not prevent it.
+ public static func delete(_ name: String, of bundle: VPhoneBundle) throws {
+ try requireValidName(name)
+ let root = directory(of: bundle)
+ let target = root.appendingPathComponent(name, isDirectory: true)
+ guard isDirectory(target) else {
+ throw VPhoneMachineSnapshotError.notFound(machine: bundle.name, name: name)
+ }
+ try FileManager.default.removeItem(at: target)
+ removeIfEmpty(root)
+ }
+
+ // MARK: - Files
+
+ private static func readMetadata(named name: String, in root: URL) throws -> VPhoneMachineSnapshot {
+ let url = root.appendingPathComponent(name).appendingPathComponent(metadataFileName)
+ let decoded: VPhoneMachineSnapshot
+ do {
+ decoded = try PropertyListDecoder().decode(VPhoneMachineSnapshot.self, from: Data(contentsOf: url))
+ } catch {
+ throw VPhoneMachineSnapshotError.damaged(name: name, reason: "\(metadataFileName) is unreadable")
+ }
+ // The directory is the snapshot's name; the recorded one is informative.
+ return VPhoneMachineSnapshot(
+ name: name,
+ created: decoded.created,
+ note: decoded.note,
+ files: decoded.files,
+ absentFiles: decoded.absentFiles,
+ )
+ }
+
+ /// A file named in a snapshot's metadata is written into the machine
+ /// folder on revert, so it must be one plain name and never the manifest.
+ private static func requireStateFileName(_ file: String, snapshot: String) throws {
+ guard !file.isEmpty, !file.contains("/"), file != ".", file != "..",
+ file != "config.plist", file != metadataFileName, file != directoryName
+ else {
+ throw VPhoneMachineSnapshotError.damaged(name: snapshot, reason: "it names the file '\(file)'")
+ }
+ }
+
+ /// An APFS clone, never a copy. Symbolic links are not followed.
+ private static func cloneFile(_ source: URL, to destination: URL) throws {
+ guard clonefile(source.path, destination.path, UInt32(CLONE_NOFOLLOW)) == 0 else {
+ let code = errno
+ if code == ENOTSUP || code == EXDEV {
+ throw VPhoneMachineSnapshotError.notCloneable(path: source.path)
+ }
+ throw VPhoneMachineSnapshotError.failed(path: source.path, reason: String(cString: strerror(code)))
+ }
+ }
+
+ private static func isRegularFile(_ url: URL) -> Bool {
+ var info = stat()
+ return lstat(url.path, &info) == 0 && info.st_mode & S_IFMT == S_IFREG
+ }
+
+ private static func isDirectory(_ url: URL) -> Bool {
+ var info = stat()
+ return lstat(url.path, &info) == 0 && info.st_mode & S_IFMT == S_IFDIR
+ }
+
+ /// `rmdir` only succeeds on an empty directory, which is the point.
+ private static func removeIfEmpty(_ url: URL) {
+ rmdir(url.path)
+ }
+
+ private static func currentErrorText() -> String {
+ String(cString: strerror(errno))
+ }
+}
+
+// MARK: - Error
+
+public enum VPhoneMachineSnapshotError: Error, Equatable {
+ case invalidName(String)
+ case alreadyExists(machine: String, name: String)
+ case notFound(machine: String, name: String)
+ case missingStateFile(machine: String, file: String)
+ case notCloneable(path: String)
+ case damaged(name: String, reason: String)
+ case failed(path: String, reason: String)
+}
+
+extension VPhoneMachineSnapshotError: CustomStringConvertible, LocalizedError {
+ public var description: String {
+ switch self {
+ case let .invalidName(name):
+ "Invalid snapshot name '\(name)'. Use a name that is not empty, has no '/', and does not start with '.'."
+ case let .alreadyExists(machine, name):
+ "VM '\(machine)' already has a snapshot named '\(name)'. Choose a different name."
+ case let .notFound(machine, name):
+ "VM '\(machine)' has no snapshot named '\(name)'. List them with vm snapshot list."
+ case let .missingStateFile(machine, file):
+ "VM '\(machine)' has no \(file) yet. Boot it once, then take the snapshot."
+ case let .notCloneable(path):
+ "Cannot clone \(path): snapshots need the VM on an APFS volume, and a full copy is not made."
+ case let .damaged(name, reason):
+ "Snapshot '\(name)' is damaged: \(reason). Delete it."
+ case let .failed(path, reason):
+ "Snapshot operation failed at \(path): \(reason)."
+ }
+ }
+
+ public var errorDescription: String? {
+ description
+ }
+}
diff --git a/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleSnapshotsTests.swift b/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleSnapshotsTests.swift
new file mode 100644
index 00000000..e789760d
--- /dev/null
+++ b/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleSnapshotsTests.swift
@@ -0,0 +1,238 @@
+import Darwin
+import Foundation
+import Testing
+@testable import VPhoneCoreKit
+
+/// Machine disk snapshots: the state files cloned aside and put back while the
+/// machine is stopped. The temporary directory is on the boot volume, which is
+/// APFS, so every clone here is a real `clonefile`.
+struct BundleSnapshotsTests {
+ // MARK: - Fixtures
+
+ private func makeBundle() throws -> (root: URL, bundle: VPhoneBundle) {
+ let fm = FileManager.default
+ let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ try fm.createDirectory(at: root, withIntermediateDirectories: true)
+ let rom = root.appendingPathComponent("rom.bin")
+ try Data([0xAA]).write(to: rom)
+ let bundle = try VPhoneBundleOperations.create(
+ .init(name: "vm", cpuCount: 2, memoryMB: 1024, diskSizeGB: 1, romSource: rom, sepromSource: rom),
+ in: VPhoneLibrary(root: root),
+ )
+ try write([1, 2, 3], to: "Disk.img", in: bundle)
+ try write([4, 5, 6], to: "SEPStorage", in: bundle)
+ try write([7, 8, 9], to: "nvram.bin", in: bundle)
+ try write(Array("receipt-1".utf8), to: "PatchReceipt.plist", in: bundle)
+ return (root, bundle)
+ }
+
+ private func write(_ bytes: [UInt8], to name: String, in bundle: VPhoneBundle) throws {
+ try Data(bytes).write(to: bundle.url.appendingPathComponent(name))
+ }
+
+ private func read(_ name: String, in directory: URL) throws -> Data {
+ try Data(contentsOf: directory.appendingPathComponent(name))
+ }
+
+ private func snapshotDirectory(_ name: String, of bundle: VPhoneBundle) -> URL {
+ VPhoneMachineSnapshots.directory(of: bundle).appendingPathComponent(name)
+ }
+
+ // MARK: - Create
+
+ @Test func `create clones every present state file byte for byte`() throws {
+ let (root, bundle) = try makeBundle()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let snapshot = try VPhoneMachineSnapshots.create("clean", note: "fresh install", of: bundle)
+ let directory = snapshotDirectory("clean", of: bundle)
+ for name in ["Disk.img", "SEPStorage", "nvram.bin", "PatchReceipt.plist"] {
+ #expect(try read(name, in: directory) == read(name, in: bundle.url), "\(name)")
+ }
+ #expect(snapshot.files == ["Disk.img", "SEPStorage", "nvram.bin", "PatchReceipt.plist"])
+ #expect(snapshot.absentFiles == ["restore-info.json"])
+ #expect(snapshot.note == "fresh install")
+ // Settings and Launchpad's binding are not part of it.
+ #expect(!FileManager.default.fileExists(atPath: directory.appendingPathComponent("config.plist").path))
+ #expect(FileManager.default.fileExists(
+ atPath: directory.appendingPathComponent(VPhoneMachineSnapshots.metadataFileName).path,
+ ))
+ // No staging directory is left beside it.
+ let entries = try FileManager.default.contentsOfDirectory(atPath: VPhoneMachineSnapshots.directory(of: bundle).path)
+ #expect(entries == ["clean"])
+ }
+
+ @Test func `create refuses a machine with no nvram yet`() throws {
+ let (root, bundle) = try makeBundle()
+ defer { try? FileManager.default.removeItem(at: root) }
+ try FileManager.default.removeItem(at: bundle.url.appendingPathComponent("nvram.bin"))
+
+ #expect(throws: VPhoneMachineSnapshotError.missingStateFile(machine: "vm", file: "nvram.bin")) {
+ try VPhoneMachineSnapshots.create("early", of: bundle)
+ }
+ #expect(!FileManager.default.fileExists(atPath: VPhoneMachineSnapshots.directory(of: bundle).path))
+ }
+
+ @Test func `duplicate and invalid names are refused`() throws {
+ let (root, bundle) = try makeBundle()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ try VPhoneMachineSnapshots.create("one", of: bundle)
+ #expect(throws: VPhoneMachineSnapshotError.alreadyExists(machine: "vm", name: "one")) {
+ try VPhoneMachineSnapshots.create("one", of: bundle)
+ }
+ for bad in ["", "a/b", ".hidden", ".."] {
+ #expect(throws: VPhoneMachineSnapshotError.invalidName(bad)) {
+ try VPhoneMachineSnapshots.create(bad, of: bundle)
+ }
+ }
+ #expect(try VPhoneMachineSnapshots.list(of: bundle).map(\.name) == ["one"])
+ }
+
+ @Test func `create and revert refuse while a state file is held open`() throws {
+ let (root, bundle) = try makeBundle()
+ defer { try? FileManager.default.removeItem(at: root) }
+ try VPhoneMachineSnapshots.create("before", of: bundle)
+
+ let fd = open(bundle.url.appendingPathComponent("SEPStorage").path, O_RDONLY)
+ #expect(fd >= 0)
+ defer { close(fd) }
+ let running = VPhoneBundleActivityError.running(name: "vm", pids: [getpid()])
+ #expect(throws: running) {
+ try VPhoneMachineSnapshots.create("during", of: bundle)
+ }
+ #expect(throws: running) {
+ try VPhoneMachineSnapshots.revert(to: "before", of: bundle)
+ }
+ #expect(try VPhoneMachineSnapshots.list(of: bundle).map(\.name) == ["before"])
+ // Nothing staged in the machine folder either.
+ let hidden = try FileManager.default.contentsOfDirectory(atPath: bundle.url.path).filter { $0.hasPrefix(".snapshot") }
+ #expect(hidden.isEmpty)
+ }
+
+ // MARK: - List
+
+ @Test func `list is oldest first with metadata`() throws {
+ let (root, bundle) = try makeBundle()
+ defer { try? FileManager.default.removeItem(at: root) }
+ #expect(try VPhoneMachineSnapshots.list(of: bundle).isEmpty)
+
+ let base = Date(timeIntervalSince1970: 1_800_000_000)
+ try VPhoneMachineSnapshots.create("zeta", note: "first", of: bundle, now: base)
+ try VPhoneMachineSnapshots.create("alpha", of: bundle, now: base.addingTimeInterval(60))
+ try VPhoneMachineSnapshots.create("mid", note: "", of: bundle, now: base.addingTimeInterval(30))
+ // Something that is not a snapshot is not listed.
+ try FileManager.default.createDirectory(
+ at: snapshotDirectory("stray", of: bundle),
+ withIntermediateDirectories: true,
+ )
+
+ let listed = try VPhoneMachineSnapshots.list(of: bundle)
+ #expect(listed.map(\.name) == ["zeta", "mid", "alpha"])
+ #expect(listed.map(\.created) == [base, base.addingTimeInterval(30), base.addingTimeInterval(60)])
+ #expect(listed.map(\.note) == ["first", nil, nil])
+ }
+
+ // MARK: - Revert
+
+ @Test func `revert restores the state files and leaves config alone`() throws {
+ let (root, bundle) = try makeBundle()
+ defer { try? FileManager.default.removeItem(at: root) }
+ try VPhoneMachineSnapshots.create("before", of: bundle)
+
+ // The guest runs on: the disk, SEP and NVRAM move, a later install
+ // records itself, and the owner changes a setting.
+ try write([9, 9, 9, 9], to: "Disk.img", in: bundle)
+ try write([8, 8], to: "SEPStorage", in: bundle)
+ try write([7], to: "nvram.bin", in: bundle)
+ try write(Array("receipt-2".utf8), to: "PatchReceipt.plist", in: bundle)
+ try write(Array("{}".utf8), to: "restore-info.json", in: bundle)
+ let updated = try VPhoneBundleOperations.updateConfig(
+ bundleNamed: "vm",
+ in: VPhoneLibrary(root: root),
+ cpuCount: 6,
+ memoryMB: nil,
+ )
+ let config = try read("config.plist", in: bundle.url)
+
+ try VPhoneMachineSnapshots.revert(to: "before", of: updated)
+
+ #expect(try read("Disk.img", in: bundle.url) == Data([1, 2, 3]))
+ #expect(try read("SEPStorage", in: bundle.url) == Data([4, 5, 6]))
+ #expect(try read("nvram.bin", in: bundle.url) == Data([7, 8, 9]))
+ #expect(try read("PatchReceipt.plist", in: bundle.url) == Data("receipt-1".utf8))
+ // Absent when the snapshot was taken, so absent again.
+ #expect(!FileManager.default.fileExists(atPath: bundle.url.appendingPathComponent("restore-info.json").path))
+ #expect(try read("config.plist", in: bundle.url) == config)
+ #expect(try VPhoneBundle.load(at: bundle.url).manifest.cpuCount == 6)
+
+ // The snapshot is kept, unchanged, and can be used again.
+ #expect(try VPhoneMachineSnapshots.list(of: bundle).map(\.name) == ["before"])
+ #expect(try read("Disk.img", in: snapshotDirectory("before", of: bundle)) == Data([1, 2, 3]))
+ try write([0], to: "Disk.img", in: bundle)
+ try VPhoneMachineSnapshots.revert(to: "before", of: bundle)
+ #expect(try read("Disk.img", in: bundle.url) == Data([1, 2, 3]))
+
+ let hidden = try FileManager.default.contentsOfDirectory(atPath: bundle.url.path).filter { $0.hasPrefix(".") }
+ #expect(hidden.isEmpty)
+ }
+
+ @Test func `revert of a damaged snapshot leaves the live files intact`() throws {
+ let (root, bundle) = try makeBundle()
+ defer { try? FileManager.default.removeItem(at: root) }
+ try VPhoneMachineSnapshots.create("broken", of: bundle)
+ try FileManager.default.removeItem(at: snapshotDirectory("broken", of: bundle).appendingPathComponent("nvram.bin"))
+ try write([5, 5], to: "Disk.img", in: bundle)
+
+ #expect(throws: VPhoneMachineSnapshotError.self) {
+ try VPhoneMachineSnapshots.revert(to: "broken", of: bundle)
+ }
+ #expect(try read("Disk.img", in: bundle.url) == Data([5, 5]))
+ let hidden = try FileManager.default.contentsOfDirectory(atPath: bundle.url.path).filter { $0.hasPrefix(".") }
+ #expect(hidden.isEmpty)
+ }
+
+ @Test func `unknown snapshots are reported`() throws {
+ let (root, bundle) = try makeBundle()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let missing = VPhoneMachineSnapshotError.notFound(machine: "vm", name: "nope")
+ #expect(throws: missing) { try VPhoneMachineSnapshots.revert(to: "nope", of: bundle) }
+ #expect(throws: missing) { try VPhoneMachineSnapshots.delete("nope", of: bundle) }
+ }
+
+ // MARK: - Delete
+
+ @Test func `delete removes the snapshot with files a client added`() throws {
+ let (root, bundle) = try makeBundle()
+ defer { try? FileManager.default.removeItem(at: root) }
+ try VPhoneMachineSnapshots.create("keep", of: bundle)
+ try VPhoneMachineSnapshots.create("drop", of: bundle)
+ let extra = snapshotDirectory("drop", of: bundle).appendingPathComponent("launchpad.json")
+ try Data(#"{"bundle":"2.7.0"}"#.utf8).write(to: extra)
+
+ // A revert keeps the client's file where it was.
+ try VPhoneMachineSnapshots.revert(to: "drop", of: bundle)
+ #expect(FileManager.default.fileExists(atPath: extra.path))
+ #expect(FileManager.default.fileExists(atPath: bundle.url.appendingPathComponent("launchpad.json").path) == false)
+
+ try VPhoneMachineSnapshots.delete("drop", of: bundle)
+ #expect(!FileManager.default.fileExists(atPath: snapshotDirectory("drop", of: bundle).path))
+ #expect(try VPhoneMachineSnapshots.list(of: bundle).map(\.name) == ["keep"])
+
+ // The last one takes the empty Snapshots folder with it.
+ try VPhoneMachineSnapshots.delete("keep", of: bundle)
+ #expect(!FileManager.default.fileExists(atPath: VPhoneMachineSnapshots.directory(of: bundle).path))
+ #expect(try read("Disk.img", in: bundle.url) == Data([1, 2, 3]))
+ }
+
+ // MARK: - Export
+
+ @Test func `snapshots are excluded from export`() {
+ let patterns = VPhoneBundleOperations.exportExcludePatterns
+ #expect(patterns.contains { fnmatch($0, VPhoneMachineSnapshots.directoryName, 0) == 0 })
+ #expect(patterns.contains { fnmatch($0, ".snapshot-revert-1234", 0) == 0 })
+ for kept in ["Disk.img", "SEPStorage", "nvram.bin", "config.plist", "PatchReceipt.plist"] {
+ #expect(!patterns.contains { fnmatch($0, kept, 0) == 0 }, "\(kept)")
+ }
+ }
+}