Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Give a cloned machine its own device identity on request

Jackyba2ea419d808
diff --git a/Documents/Guides/create-and-run.md b/Documents/Guides/create-and-run.md
index 3d8e2b84..e41d6536 100644
--- a/Documents/Guides/create-and-run.md
+++ b/Documents/Guides/create-and-run.md
@@ -65,10 +65,15 @@ The online restore obtains its ticket in process. For an offline restore, see `v
vphone-cli vm list
vphone-cli vm info myphone
vphone-cli vm clone myphone copy
+vphone-cli vm clone myphone second --new-identity
vphone-cli vm export myphone --out myphone.tzst
vphone-cli vm import myphone.tzst --name restored
```
-`vm clone` copies the complete machine state, including its device identity and boot files. It uses APFS copy-on-write when available. Edit the identity yourself if you need a different device.
+`vm clone` copies a stopped machine, using APFS copy-on-write when available; it refuses while the source runs. A plain copy keeps everything, including the device identity (machine identifier and MAC address), so it is a backup and cannot run beside the original.
+
+`--new-identity` makes a second device instead. The copy gets a new machine identifier (ECID), and with it a new UDID, and a new MAC address on its first start. Its fixed IPv4 address, port forwards and a hand-chosen mDNS name are cleared, since they would collide with the original's; an mDNS name `--mdns on` derived from the original's name follows the new name, as on rename. Set new ones with `vm config` if you need them. The guest keeps the original's data, apps and settings, and no restore is needed. Before lockdown tools such as `ideviceinstaller` work, unlock the copy and trust this Mac again. On APFS a copy shares its disk blocks with the original and holds only what it changes, about 0.35 GB after its first boots, although `du` and Finder report the full size for each.
+
+Do not swap `SEPStorage`, `nvram.bin` or the disk image between machines: they were made together by one restore, and a guest whose SEP storage does not match its disk panics at boot.
Run resource-heavy creations **one at a time**. Both the IPSWs and temporary restore tree consume substantial disk space, and patching large caches can be memory intensive. Check free space before starting a second VM.
diff --git a/Documents/Guides/networking.md b/Documents/Guides/networking.md
index cc3d59bc..e5928929 100644
--- a/Documents/Guides/networking.md
+++ b/Documents/Guides/networking.md
@@ -104,7 +104,9 @@ vphone-cli vm config <name> --mac auto # a new one at the next launch
```
A cloned machine keeps the MAC of the original, like its machine identifier.
-Give the clone a new one before running both at once.
+Clone with `vm clone --new-identity` to give the copy new ones, or give it a
+new MAC before running both at once. `--new-identity` also clears the copy's
+fixed address, port forwards and mDNS name.
## Addresses held by old MACs
diff --git a/Research/Host/machine_identity_and_clone.md b/Research/Host/machine_identity_and_clone.md
new file mode 100644
index 00000000..ea839f50
--- /dev/null
+++ b/Research/Host/machine_identity_and_clone.md
@@ -0,0 +1,148 @@
+# Machine identity and `vm clone --new-identity`
+
+Where a machine's device identity lives, what `vm clone --new-identity`
+changes, and why it changes nothing else. The implementation is
+`VPhoneBundleOperations.clone` and `resetIdentity` in
+`VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift`; user-facing
+behaviour is in `Documents/Guides/create-and-run.md`.
+
+Tested on 2026-10-06 from one stopped source machine (iPhone17,3 guest, iOS
+27.0 24A435 with cloudOS 26.4 23E5207q, bundle 2.6.0, standard preset), cloned
+five times with `clonefile` and edited by hand before the command existed.
+The source was never started; its files kept their modification times.
+
+## Summary
+
+The identity is the ECID, and only the ECID. Clearing `machineIdentifier`
+(and `networkConfig.macAddress`) in the copy's `config.plist` makes
+`vphone-vm` create new ones on the next start. The guest then boots with a new
+`UniqueDeviceID` and `UniqueChipID`, its data unlocked, vphoned answering and
+lockdown reporting `ActivationState: Activated`. It survives a second boot and
+runs beside another clone of the same source.
+
+`nvram.bin`, `SEPStorage` and the disk image must stay exactly as copied. They
+come from one restore and cannot be regenerated separately.
+
+## Where identity lives
+
+### In the machine folder
+
+| File | What it binds | `--new-identity` |
+| --- | --- | --- |
+| `config.plist` `machineIdentifier` | The ECID: a binary plist `{ECID = <u64>}`, the data representation of `VZMacMachineIdentifier`. `VPhoneVirtualMachine.init` creates and saves one when it is empty or invalid. | Cleared |
+| `config.plist` `networkConfig.macAddress` | The NIC's MAC, and with it the NAT DHCP lease. Generated and saved on first start when empty. | Cleared |
+| `config.plist` `ipv4`, `portForwards`, `localHostName` | A fixed address, host ports and a `.local` name. Two running machines cannot share any of them. | Cleared; a `.local` name derived from the old machine name is re-derived from the new one |
+| `udid-prediction.txt` | Output derived from the ECID, rewritten on every start. | Deleted |
+| `nvram.bin` (`VZMacAuxiliaryStorage`, 33 MB) | The NOR boot images restore wrote (LLB, iBoot, with their IM4M, whose `ECID` property holds the old ECID) and the NVRAM variables. An empty one has no boot firmware. | Kept |
+| `SEPStorage` (512 KB) | The virtual SEP's persistent store: a 32-byte per-machine secret at 0x20, A/B records at 0x1000 and 0x8000 holding the ECID and boot-manifest hash, anti-replay records from 0x2000. | Kept |
+| Patch receipts, `restore-info.json`, `FirmwareOriginals/`, ROMs, `launchpad.json` | Nothing identity related. | Kept |
+| `vphone.sock`, `Snapshots/` | The source's control socket and its snapshot history. | Deleted by every clone |
+
+### Inside the disk image
+
+Attached read-only, a restored disk has System, Data (FileVault, locked),
+xART, Hardware, Preboot, Update and User (FileVault, locked) volumes.
+
+- **Preboot** `/<boot-manifest-hash>/` holds `apticket.der`, the SEP firmware,
+ device tree, root hash, kernelcache and FUD images. Every IM4M names the old
+ ECID. They still boot under a new one (next section).
+- **Hardware** holds a copy of the ticket and `mobileactivationd.uuid`, a UUID
+ not derived from the ECID. Every clone shares it.
+- **xART** holds the gigalocker `AA.gl`. CFW fixes its name
+ (`renameGigalocker` in `VPhoneCustomFirmwareInstaller.swift`) instead of
+ letting it follow the device UUID. It is bound to the SEP secret in
+ `SEPStorage`.
+- **Data and User** volume keys are wrapped by the SEP (`nx_keybag_lookup_vek:
+ successfully loaded volume class keys` at boot). Lockdown state under
+ `/private/var/root/Library/Lockdown/` has no activation record, since the
+ guest is hacktivated, and `data_ark.plist` holds no UDID or ECID. The
+ MobileGestalt cache holds neither in any byte order.
+
+The guest computes `UniqueDeviceID`, `UniqueChipID`, its Wi-Fi, Bluetooth and
+Ethernet MACs and the USB serial from the ECID Virtualization presents, so all
+of them change with it. Only libignition's `ecid :` log line still shows the
+old value, because it reads the ticket.
+
+## No re-personalization is needed
+
+The boot chain already ignores the ECID in its tickets
+([iBoot patches](../Firmware/iboot_patches.md),
+[firmware manifest and origins](../Firmware/firmware_manifest_and_origins.md)):
+
+- AVPBooter's DGST bypass loads LLB from `nvram.bin`.
+- iBSS, iBEC and LLB force `image4_validate_property_callback` to return 0.
+ That callback checks `ECID`, `BNCH`, `BORD`, `CHIP` and the rest, so a
+ mismatched ECID passes with them. LLB and iBoot load the kernel, device tree,
+ TXM and SPTM from Preboot through the same callback.
+- The SEP firmware is checked by the unpatched AVPSEPBooter, which still logs
+ `AppleSEPBooter: SEP accepted IMG4` under a new ECID: the virtual SEP ROM
+ does not enforce it.
+
+A new-identity clone's serial log shows the new ECID in `USB_SERIAL_NUMBER`.
+Its error and failure lines, normalized, are identical to those of a clone that
+kept the old identity.
+
+## Replacing `SEPStorage` panics the guest
+
+| Clone | ECID | `SEPStorage` | xART | Result |
+| --- | --- | --- | --- | --- |
+| a | kept | kept | kept | Boots; old UDID; the host's pairing still works |
+| b | **new** | kept | kept | **Boots**; SEP alive, Data and User mounted, vphoned answers; new UDID, so the host must be trusted again; second boot fine; runs beside a |
+| c | new | deleted (Virtualization makes a new one) | kept | `SEP accepted IMG4`, gigalocker initialized, then `panic: SEP Panic: :AESS/AESS` after mount phase 2, before Data mounts |
+| d | **kept** | deleted | kept | The same AESS panic: it comes from the new SEP secret, not the ECID |
+| e | new | deleted | `AA.gl` deleted on the host | `init_data_protection: Gigalocker file … doesn't exist`, then `panic: seputil[6] exited … exit status 2` |
+
+iOS never obliterates for a changed identity or SEP: Obliterator reports `No
+obliteration needed` and the guest panics instead of hanging. `SEPStorage`, the
+xART gigalocker and the Data and User volume keys are made together by one
+restore. The host can write xART but cannot mount the encrypted Data volume,
+so there is no offline way to reset Data alone; a fresh SEP needs restored's
+data-protection setup, which is an erasing restore.
+
+It follows that `SEPStorage` and the disk image must be taken at the same
+moment. The gigalocker and the anti-replay records advance together, so a copy
+of a running machine can pair a disk with SEP state from another moment.
+`vm clone` refuses while the source runs (`VPhoneBundleActivity.requireStopped`
+looks for a process holding the disk image, `SEPStorage` or `nvram.bin` open, or
+a control socket that answers). Host-side writes to the disk image by `cfw
+install` or `--update-environment` do not break the pairing: a source whose
+disk image was modified hours after its `SEPStorage` cloned and booted fine.
+
+## Disk cost
+
+Measured with `F_LOG2PHYS_EXT`, comparing the physical blocks of the source's
+and a clone's disk image:
+
+| Comparison | Shared | Clone's own |
+| --- | --- | --- |
+| After clone, before boot | 20.32 GB | 0.00 GB |
+| Same-identity clone, one boot | 20.04 GB | 0.34 GB |
+| Same-identity clone, two boots | 19.98 GB | 0.36 GB |
+| New-identity clone, two boots | 19.94 GB | 0.34 GB |
+| Two clones against each other | 19.94 GB | about 0.4 GB each |
+| Panicking clones c, d, e | 20.28 GB | 0.00 GB (guest TRIM punched holes, freeing about 0.03 GB) |
+
+`nvram.bin` and `SEPStorage` are cloned too and diverge by a few blocks.
+A clone therefore costs about 0.35 GB after its first boots and grows with
+use, where a restore writes about 20 GB plus an 11 GB temporary restore tree.
+`du` and Launchpad's size column report the full 20 GB for every clone, and
+deleting the source frees no shared blocks while a clone remains.
+
+## Shared state and caveats
+
+- Every clone of one source shares its SEP root secret (in principle one clone
+ could decrypt another's Data volume), `mobileactivationd.uuid`, and whatever
+ the source's Data volume held: trusted hosts, Developer Mode, Setup
+ Assistant state, device-bound keychain items. Research guests are
+ hacktivated and show no functional effect. Signing a clone into Apple
+ services, where servers could see several devices with one set of device
+ keys, was not tested.
+- The host trusts each guest by UDID, so lockdown tools need the guest's
+ "Trust This Computer" prompt again after a new identity. Tapping Trust and
+ then `idevicepair pair` worked.
+- A clone that later runs `restore` is personalized for its new ECID, as
+ usual. `cfw update-kernel` and `--update-environment` write through a host
+ mount and do not involve the ECID.
+- Deleting clones leaves their DHCP bindings to unused MACs;
+ `vm leases --release-orphans` returns them (see
+ [network notes](network_fixed_address.md)).
diff --git a/Research/Host/network_fixed_address.md b/Research/Host/network_fixed_address.md
index 30e04da6..bdec1ac0 100644
--- a/Research/Host/network_fixed_address.md
+++ b/Research/Host/network_fixed_address.md
@@ -26,7 +26,8 @@ saves `machineIdentifier`. With `aa:73:76:98:a7:06`:
Whatever broke before was not a fixed MAC as such. One likely cause is the same
MAC on several VMs, for example from a manifest template: two guests on one
L2 network with one MAC cannot both work. Each VM now gets its own, and a clone
-keeps the original's, like its machine identifier.
+keeps the original's, like its machine identifier, unless made with
+`vm clone --new-identity` ([machine identity and clone](machine_identity_and_clone.md)).
## Leases held by MACs no machine uses
diff --git a/Research/README.md b/Research/README.md
index f5cde6cd..fd78e49d 100644
--- a/Research/README.md
+++ b/Research/README.md
@@ -19,7 +19,7 @@ This directory keeps the evidence behind firmware patches, restore and the self-
| Kernel | [CFW overview](Kernel/kernel_jb_patch_notes.md), [patcher verification](Kernel/kernel_patcher_verification.md), [FairPlay kexts](Kernel/kernel_fairplay_kexts.md), [base validation 1–5](Kernel/kernel_patch_base_first5_validation.md), [11–15](Kernel/kernel_patch_base_11_15_validation.md), [16–20](Kernel/kernel_patch_base_16_20_validation.md), [sandbox hooks](Kernel/kernel_patch_sandbox_hooks_17_26_validation.md), [individual patch notes](KernelCustomFirmwarePatches/README.md) |
| Other patches and captures | [Launchd jetsam](Patches/cfw_patch_launchd_jetsam.md), [user-mode hypervisor references](Patches/hv_vmm_present_usermode_xrefs.md), [reference capture](Patches/patch_reference_capture.md) |
| Restore | [DFU probe](Restore/virtual_dfu_probe.md), [in-process restore](Restore/native_restore_architecture.md) |
-| Host and archives | [Binary split](Host/host_binary_split.md), [runtime dependency tiers](Host/runtime_dependency_tiers.md), [archive extraction contracts](Host/archive_extraction_contracts.md), [libarchive validation](Host/libarchive_xcframework_validation.md), [guest MAC, fixed address, port forwarding and names](Host/network_fixed_address.md) |
+| Host and archives | [Binary split](Host/host_binary_split.md), [runtime dependency tiers](Host/runtime_dependency_tiers.md), [archive extraction contracts](Host/archive_extraction_contracts.md), [libarchive validation](Host/libarchive_xcframework_validation.md), [guest MAC, fixed address, port forwarding and names](Host/network_fixed_address.md), [machine identity and `vm clone --new-identity`](Host/machine_identity_and_clone.md) |
| Guest interaction and VM identity | [DevMode XPC](Guest/devmode_xpc_protocol.md), [keyboard events](Guest/keyboard_event_pipeline.md), [machine identifier](Guest/machine_identifier_storage_analysis.md), [Auto-Lock on the Lock Screen](Guest/lock_screen_idle_timer.md), [display refresh rate](Guest/display_refresh_rate.md), [GPU acceleration](Guest/gpu_acceleration.md), [RootHide bootstrap base](Guest/roothide_bootstrap_base.md), [the Mac's .local name](Guest/mac_name_resolution.md) |
| Historical project records | [Migration ledger](History/intg_update_status.md), [manifest refactoring summary](History/manifest_and_refactoring_summary.md) |
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineTransferCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineTransferCommand.swift
index d0be3565..db9f9f36 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineTransferCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineTransferCommand.swift
@@ -7,18 +7,44 @@ struct VPhoneVirtualMachineCloneCommand: ParsableCommand {
static let configuration = CommandConfiguration(
commandName: "clone",
abstract: "Copy a VM bundle (using APFS copy-on-write when available)",
- discussion: "The copy keeps the machine identifier, NVRAM, SEP storage, and SHSH blobs unchanged. Edit the device identity yourself if you need a different one.",
+ discussion: """
+ The source VM must be stopped. Its snapshots are not copied.
+
+ By default the copy keeps the machine identifier (ECID), MAC address, NVRAM, SEP \
+ storage and every setting, so it cannot run beside its source: use it as a backup.
+
+ --new-identity clears the machine identifier and MAC address, so the copy gets new \
+ ones, and with them a new UDID, on its first start. It also clears the fixed IPv4 \
+ address, port forwards and a hand-chosen mDNS name, which would collide with the \
+ source's; a derived mDNS name follows the new name. NVRAM, \
+ SEP storage and the disk image are kept: they were made together by one restore, and \
+ the guest panics if SEP storage is replaced. No restore or re-personalization is \
+ needed. The host must be trusted again in the guest before lockdown tools work.
+ """,
)
@OptionGroup var lib: VPhoneLibraryOption
@Argument(help: "source VM name") var name: String?
@Argument(help: "new VM name") var newName: String?
+ @Flag(help: "give the copy a new machine identifier and MAC address on its first start")
+ var newIdentity = false
func run() throws {
let name = try VPhoneVirtualMachineSelection.resolveExisting(name, in: lib.library)
let newName = try VPhoneVirtualMachineSelection.resolveNewName(newName, prompt: "New VM name:")
- let clone = try VPhoneBundleOperations.clone(bundleNamed: name, to: newName, in: lib.library)
+ let source = try lib.library.bundle(named: name)
+ let clone = try VPhoneBundleOperations.clone(
+ bundleNamed: name,
+ to: newName,
+ in: lib.library,
+ newIdentity: newIdentity,
+ )
print("cloned \(name) → \(clone.name)")
+ guard newIdentity else { return }
+ print("new identity: machine identifier and MAC address are generated on first start")
+ for setting in VPhoneBundleOperations.networkSettingsClearedByNewIdentity(source.manifest.networkConfig, sourceName: source.name) {
+ print("cleared \(setting)")
+ }
}
}
diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift
index ce1e2696..d7a43a64 100644
--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift
+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift
@@ -163,27 +163,122 @@ public enum VPhoneBundleOperations {
// MARK: - Clone
/// Copy the whole bundle, using APFS copy-on-write when available. The
- /// machine identifier and boot state remain unchanged in the copy.
+ /// source must be stopped, so its disk image, `SEPStorage` and `nvram.bin`
+ /// are copied from one moment.
+ ///
+ /// Without `newIdentity` the copy keeps the machine identifier, MAC address
+ /// and every other setting, so it cannot run beside its source: it is a
+ /// backup. With `newIdentity` the copy gets a new identity on its first
+ /// start (see `resetIdentity`) and drops the network settings that would
+ /// collide with the source's, listed by `networkSettingsClearedByNewIdentity`.
+ @discardableResult
public static func clone(
bundleNamed name: String,
to newName: String,
in library: VPhoneLibrary,
+ newIdentity: Bool = false,
) throws -> VPhoneBundle {
try requireValidName(newName)
- let src = try library.bundle(named: name).url
+ let source = try library.bundle(named: name)
+ let src = source.url
let dst = library.url(forName: newName)
let fm = FileManager.default
if fm.fileExists(atPath: dst.path) {
throw VPhoneLibraryError.alreadyExists(name: newName)
}
+ try VPhoneBundleActivity.requireStopped(source)
// APFS CoW clone; fall back to a plain recursive copy off-APFS.
if clonefile(src.path, dst.path, 0) != 0 {
try? fm.removeItem(at: dst) // clear any partial clonefile output first
try fm.copyItem(at: src, to: dst)
}
- try VPhoneHostFilePermissions.makeAccessible(at: dst)
- return try VPhoneBundle.load(at: dst)
+ // Roll back a half-made copy, so a retry with the same name is not
+ // blocked by the alreadyExists check.
+ do {
+ // A clone starts without snapshots: they record the source's
+ // history, not the copy's.
+ try removeIfPresent(dst.appendingPathComponent(VPhoneMachineSnapshots.directoryName))
+ // The source's control socket, stale since it stopped.
+ try removeIfPresent(dst.appendingPathComponent("vphone.sock"))
+ if newIdentity {
+ try resetIdentity(of: VPhoneBundle.load(at: dst), clonedFrom: name)
+ }
+ try VPhoneHostFilePermissions.makeAccessible(at: dst)
+ return try VPhoneBundle.load(at: dst)
+ } catch {
+ try? fm.removeItem(at: dst)
+ throw error
+ }
+ }
+
+ /// The network settings a new-identity clone drops, described for display.
+ /// Each would collide with the source's when both run: a fixed address,
+ /// host ports, and a `.local` name chosen by hand. A name `--mdns on`
+ /// derived from the source's name is not cleared: it follows the new name,
+ /// as it does on rename. The MAC address is not listed; it is always
+ /// regenerated along with the machine identifier.
+ public static func networkSettingsClearedByNewIdentity(
+ _ network: VPhoneVirtualMachineManifest.NetworkConfig,
+ sourceName: String,
+ ) -> [String] {
+ var cleared: [String] = []
+ if let ipv4 = network.ipv4 {
+ cleared.append("fixed IPv4 address \(ipv4.address)/\(ipv4.prefixLength)")
+ }
+ if let forwards = network.portForwards, !forwards.isEmpty {
+ cleared.append("port forwards \(forwards.map(\.description).joined(separator: ", "))")
+ }
+ if let name = network.localHostName, !name.isEmpty,
+ name != VPhoneNetworking.localHostName(forVMName: sourceName)
+ {
+ cleared.append("mDNS name \(name)")
+ }
+ return cleared
+ }
+
+ /// Give a copied bundle a new identity on its next start.
+ ///
+ /// The identity is the ECID, kept in `config.plist` as `machineIdentifier`.
+ /// `vphone-vm` creates a new one, and a new MAC address, when either is
+ /// empty, and the guest derives its UDID, Wi-Fi/Bluetooth MACs and USB
+ /// serial from that ECID at boot. `udid-prediction.txt` only records the
+ /// old one and is rewritten on every start.
+ ///
+ /// `nvram.bin`, `SEPStorage` and the disk image stay exactly as copied.
+ /// The SEP's root secret lives in `SEPStorage`, and the xART gigalocker
+ /// and the Data and User volume keys on the disk were all made from it by
+ /// one restore: a fresh `SEPStorage` panics the SEP in AESS on the next
+ /// boot, and only an erasing restore can make a new matching set.
+ /// `nvram.bin` holds the boot firmware that restore wrote. Neither needs
+ /// the new ECID: the boot chain's patched image4 property callback already
+ /// ignores the ECID in the old tickets, and the SEP ROM accepts them too,
+ /// so no re-personalization is needed. See
+ /// `Research/Host/machine_identity_and_clone.md`.
+ static func resetIdentity(of bundle: VPhoneBundle, clonedFrom sourceName: String) throws {
+ let current = bundle.manifest.networkConfig
+ // A derived mDNS name follows the new machine name; one chosen by hand
+ // would collide with the source's and is dropped.
+ let derived = current.localHostName == VPhoneNetworking.localHostName(forVMName: sourceName)
+ let network = current.with(
+ macAddress: "",
+ ipv4: .some(nil),
+ portForwards: .some(nil),
+ localHostName: .some(derived ? VPhoneNetworking.localHostName(forVMName: bundle.name) : nil),
+ )
+ let updated = bundle.manifest.updating(machineIdentifier: Data(), networkConfig: network)
+ try updated.write(to: bundle.configURL)
+ try removeIfPresent(bundle.url.appendingPathComponent("udid-prediction.txt"))
+ }
+
+ /// Remove a file, directory or link without following it; a missing one
+ /// is fine.
+ private static func removeIfPresent(_ url: URL) throws {
+ do {
+ try FileManager.default.removeItem(at: url)
+ } catch CocoaError.fileNoSuchFile {
+ return
+ }
}
// MARK: - Export
diff --git a/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleOperationsTests.swift b/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleOperationsTests.swift
index 9d09dfd3..f3236452 100644
--- a/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleOperationsTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleOperationsTests.swift
@@ -398,4 +398,157 @@ struct BundleOperationsTests {
_ = try VPhoneBundleOperations.clone(bundleNamed: "a", to: "b", in: lib)
}
}
+
+ // MARK: - Clone state and identity
+
+ /// A stopped machine with the files a booted one has: state files with
+ /// distinct bytes, an identity, fixed network settings, a stale control
+ /// socket and a snapshot.
+ private func makeBootedSource(named name: String, in lib: VPhoneLibrary) throws -> VPhoneBundle {
+ let rom = try fakeROM()
+ defer { try? FileManager.default.removeItem(at: rom) }
+ let created = try VPhoneBundleOperations.create(
+ .init(name: name, cpuCount: 8, memoryMB: 4096, diskSizeGB: 1, romSource: rom, sepromSource: rom),
+ in: lib,
+ )
+ let url = created.url
+ // A small disk image keeps the byte comparisons cheap.
+ try Data([0xD1, 0x5C, 0x00, 0x01]).write(to: url.appendingPathComponent("Disk.img"))
+ try Data([0x5E, 0x90]).write(to: url.appendingPathComponent("SEPStorage"))
+ try Data([1, 2, 3]).write(to: url.appendingPathComponent("nvram.bin"))
+ try Data([4]).write(to: url.appendingPathComponent("udid-prediction.txt"))
+ try Data([5]).write(to: url.appendingPathComponent("launchpad.json"))
+ // A regular file stands in for the socket a stopped VM leaves behind;
+ // nothing accepts a connection on it.
+ try Data().write(to: url.appendingPathComponent("vphone.sock"))
+ let snapshot = url.appendingPathComponent("Snapshots/before-update")
+ try FileManager.default.createDirectory(at: snapshot, withIntermediateDirectories: true)
+ try Data([0xD1]).write(to: snapshot.appendingPathComponent("Disk.img"))
+
+ typealias Network = VPhoneVirtualMachineManifest.NetworkConfig
+ let network = Network(
+ mode: .nat,
+ macAddress: "aa:bb:cc:dd:ee:ff",
+ ipv4: .init(address: "192.168.64.20", prefixLength: 24),
+ portForwards: [.init(hostPort: 8022, guestPort: 22)],
+ localHostName: "src-phone",
+ resolvesMacName: false,
+ )
+ let manifest = created.manifest.updating(
+ machineIdentifier: Data([9, 9]),
+ networkConfig: network,
+ unlocksAtStartup: true,
+ )
+ try manifest.write(to: created.configURL)
+ return VPhoneBundle(url: url, manifest: manifest)
+ }
+
+ @Test func `clone with a new identity clears the identity and colliding network settings`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let lib = VPhoneLibrary(root: root)
+ let src = try makeBootedSource(named: "src", in: lib)
+ let sourceConfig = try Data(contentsOf: src.configURL)
+
+ let clone = try VPhoneBundleOperations.clone(bundleNamed: "src", to: "dst", in: lib, newIdentity: true)
+
+ // The identity and the settings that would collide with the source are gone.
+ let manifest = try lib.bundle(named: "dst").manifest
+ #expect(manifest.machineIdentifier.isEmpty)
+ #expect(manifest.networkConfig.macAddress.isEmpty)
+ #expect(manifest.networkConfig.ipv4 == nil)
+ #expect(manifest.networkConfig.portForwards == nil)
+ #expect(manifest.networkConfig.localHostName == nil)
+ // Everything else is kept.
+ #expect(manifest.networkConfig.mode == .nat)
+ #expect(manifest.networkConfig.resolvesMacName == false)
+ #expect(manifest.cpuCount == 8)
+ #expect(manifest.memorySize == 4096 * 1024 * 1024)
+ #expect(manifest.unlocksAtStartup == true)
+ #expect(manifest.romImages?.avpBooter == src.manifest.romImages?.avpBooter)
+ #expect(manifest.screenConfig == src.manifest.screenConfig)
+
+ // The ECID's record goes; the state files made by one restore stay byte for byte.
+ let fm = FileManager.default
+ #expect(!fm.fileExists(atPath: clone.url.appendingPathComponent("udid-prediction.txt").path))
+ #expect(!fm.fileExists(atPath: clone.url.appendingPathComponent("vphone.sock").path))
+ #expect(!fm.fileExists(atPath: clone.url.appendingPathComponent("Snapshots").path))
+ for name in ["Disk.img", "SEPStorage", "nvram.bin", "launchpad.json", "AVPBooter.vresearch1.bin"] {
+ #expect(try Data(contentsOf: clone.url.appendingPathComponent(name))
+ == Data(contentsOf: src.url.appendingPathComponent(name)))
+ }
+
+ // The source is untouched.
+ #expect(try Data(contentsOf: src.configURL) == sourceConfig)
+ #expect(fm.fileExists(atPath: src.url.appendingPathComponent("udid-prediction.txt").path))
+ #expect(fm.fileExists(atPath: src.url.appendingPathComponent("Snapshots/before-update/Disk.img").path))
+ }
+
+ @Test func `a plain clone keeps the identity but not snapshots or the control socket`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let lib = VPhoneLibrary(root: root)
+ let src = try makeBootedSource(named: "src", in: lib)
+
+ let clone = try VPhoneBundleOperations.clone(bundleNamed: "src", to: "dst", in: lib)
+
+ #expect(clone.manifest.machineIdentifier == Data([9, 9]))
+ #expect(clone.manifest.networkConfig == src.manifest.networkConfig)
+ let fm = FileManager.default
+ #expect(fm.fileExists(atPath: clone.url.appendingPathComponent("udid-prediction.txt").path))
+ #expect(!fm.fileExists(atPath: clone.url.appendingPathComponent("vphone.sock").path))
+ #expect(!fm.fileExists(atPath: clone.url.appendingPathComponent("Snapshots").path))
+ }
+
+ @Test func `clone refuses while the source holds a state file open`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let lib = VPhoneLibrary(root: root)
+ let src = try makeBootedSource(named: "src", in: lib)
+
+ let fd = open(src.url.appendingPathComponent("Disk.img").path, O_RDONLY)
+ #expect(fd >= 0)
+ defer { close(fd) }
+ for newIdentity in [false, true] {
+ #expect(throws: VPhoneBundleActivityError.running(name: "src", pids: [getpid()])) {
+ try VPhoneBundleOperations.clone(bundleNamed: "src", to: "dst", in: lib, newIdentity: newIdentity)
+ }
+ #expect(!FileManager.default.fileExists(atPath: lib.url(forName: "dst").path))
+ }
+ }
+
+ @Test func `lists the network settings a new identity clears`() {
+ typealias Network = VPhoneVirtualMachineManifest.NetworkConfig
+ #expect(VPhoneBundleOperations.networkSettingsClearedByNewIdentity(.default, sourceName: "src").isEmpty)
+ let network = Network(
+ mode: .tunnel,
+ macAddress: "aa:bb:cc:dd:ee:ff",
+ ipv4: .init(address: "10.0.0.5", prefixLength: 24),
+ portForwards: [.init(hostPort: 8022, guestPort: 22)],
+ localHostName: "phone",
+ )
+ #expect(VPhoneBundleOperations.networkSettingsClearedByNewIdentity(network, sourceName: "src") == [
+ "fixed IPv4 address 10.0.0.5/24",
+ "port forwards tcp:127.0.0.1:8022:22",
+ "mDNS name phone",
+ ])
+ // A name derived from the source's name is not listed: it follows the clone.
+ let derived = network.with(localHostName: .some(VPhoneNetworking.localHostName(forVMName: "lab_a")))
+ #expect(!VPhoneBundleOperations.networkSettingsClearedByNewIdentity(derived, sourceName: "lab_a")
+ .contains { $0.hasPrefix("mDNS name") })
+ }
+
+ @Test func `clone with a new identity carries a derived mDNS name over to the new name`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let lib = VPhoneLibrary(root: root)
+ let src = try makeBootedSource(named: "lab_a", in: lib)
+ let derived = src.manifest.networkConfig.with(localHostName: .some(VPhoneNetworking.localHostName(forVMName: "lab_a")))
+ try src.manifest.updating(networkConfig: derived).write(to: src.configURL)
+
+ let clone = try VPhoneBundleOperations.clone(bundleNamed: "lab_a", to: "lab_b", in: lib, newIdentity: true)
+
+ #expect(clone.manifest.networkConfig.localHostName == "lab-b")
+ #expect(try lib.bundle(named: "lab_a").manifest.networkConfig.localHostName == "lab-a")
+ }
}