Run a virtual iPhone on an Apple Silicon Mac.
Swift
Skip Setup Assistant without restarting SpringBoard during data migration
Jackyeebe68083a1c
diff --git a/Research/Guest/setup_assistant_skip.md b/Research/Guest/setup_assistant_skip.mdindex 688e8ae7..c975fbbb 100644--- a/Research/Guest/setup_assistant_skip.md+++ b/Research/Guest/setup_assistant_skip.md@@ -56,6 +56,54 @@ SpringBoard. The write has to go through cfprefsd (`CFPreferencesSetValue`for user mobile, then synchronize). Editing the plist file directly leavescfprefsd holding the old values.+## The first boot after a restore++Measured on `ss-raw` (iPhone17,3 27.0 24A435, cloudOS 26.4, never booted,+standard trim) on 2026-10-09, reverting a snapshot between runs.++On the first boot DataMigrator runs its migration plugins, starting with the+boot: `SystemAppMigrator` expands the removable system apps (the+`staged_system_apps` count falls to 0, 18 s), and the last one,+`SpringBoard.migrator` ("concurrent after WiFiDataMigrator"), ran 27 s on a+quiet guest and 67 s on one busy with log streaming. When it ends,+SpringBoard logs `[FBServiceFacilityServer] Milestone reached:+FBSServiceMilestoneDataMigrationCompleted` and only then carries on starting+up (`MobileActivation says the device is: [Activated]` and so on). At the same+moment DataMigrator records the build in `com.apple.migration` for user mobile:+`LastSystemVersion = 24A435` and `DMLastMigrationResults = {buildVersion:+24A435, success: 1}`. Before that the domain is empty. The milestone came+62–183 s after the VM started.++Until the milestone:++- Setup.app is not running (`setup.status` `running: false` throughout), so+ SpringBoard has not decided yet.+- FrontBoard ignores `SBSRelaunchAction` from `FBSSystemService` (icli's+ `respring()`): SpringBoard keeps its pid. icli's fallback, `launchctl stop+ com.apple.SpringBoard`, fails on the guest with launchd status 144+ ("Requestor lacks required entitlement"), as `services.stop/unload` do. So+ a `setup.skip` that restarts SpringBoard failed with "relaunch action+ ignored and launchd stop failed: 144 Requestor lacks required entitlement"+ until migration ended (5–11 attempts, 45–98 s, in template setup boots).+ The 144 is the fallback's error; no entitlement on vphoned changes when+ FrontBoard takes the relaunch.+- Writing the three keys is enough. With the keys written right after vphoned+ first answered and SpringBoard left alone, Setup never started after the+ milestone and the guest went to the Lock Screen.++So `setup.skip` writes the keys and leaves SpringBoard alone while data+migration is running for the running build: `kern.osversion` is not recorded+as `LastSystemVersion` or as `DMLastMigrationResults.buildVersion`, and+DataMigrator's XPC service (`…/com.apple.datamigrator.xpc/com.apple.datamigrator`,+process name `com.apple.datami`) runs. It holds its transactions for the+whole migration, from the start of the boot on. It then answers with+`respring: {restarted: false, reason: "data_migration_pending"}`. With+neither the record nor DataMigrator, it restarts SpringBoard as before, so a+guest that records elsewhere is never left waiting. When the restart fails anyway, the refusal says+the keys are written and carries `retryable: true`. `setup.settle` waits for+the same record, so a template is not frozen before migration ends (a clone+would migrate again).+## Detection`setup_pending` in `/v1/health` is `SetupDone != true || SetupVersion <diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.mdindex dfeca446..236663f2 100644--- a/Research/vphoned_http_api.md+++ b/Research/vphoned_http_api.md@@ -314,7 +314,7 @@ request carries `"force": true`.| Bootstrap | `bootstrap.install {layout}`, `bootstrap.status`, `bootstrap.inspect`, `bootstrap.uninstall {jbroot, force}`, `bootstrap.firmware` (see above) || Environment | `environment.status` (SHA-256 of each vphone library in `/usr/lib`, or null when absent, plus the staging directory), `environment.install {libraries: [{name, sha256}]}` (see below) || Profile UDID | `udid.get`, `udid.set {udid}`, `udid.clear` — each returns `{udid, path}`, the UDID the guest gives its profile checks and the host (null: the guest's own) and the settings file it came from; `set` and `clear` also return `restarted_pids`, `usb_serial` and `usb_reenumerated` (see below) |-| Setup Assistant | `setup.status` (`{pending, running, pid, setup_done, setup_version, current_version}`), `setup.skip` **force** (sets `SetupDone`, `SetupFinishedAllSteps` and `SetupVersion` in `com.apple.purplebuddy`, restarts SpringBoard, returns the status plus `respring`); `setup.settle {timeout_s?, poll_s?, stable_polls?}` (read-only wait for first-boot work, see below); `/v1/health` carries `setup_pending` — see `Research/Guest/setup_assistant_skip.md` |+| Setup Assistant | `setup.status` (`{pending, running, pid, setup_done, setup_version, current_version, data_migration_done}`), `setup.skip` **force** (sets `SetupDone`, `SetupFinishedAllSteps` and `SetupVersion` in `com.apple.purplebuddy`, restarts SpringBoard, returns the status plus `respring`; while the first boot's data migration is still running it does not restart SpringBoard, which reads the keys when migration ends, and `respring` is `{restarted: false, reason: "data_migration_pending"}`; a restart FrontBoard ignored is refused with `reason: busy`, `retryable: true`, the keys already written); `setup.settle {timeout_s?, poll_s?, stable_polls?}` (read-only wait for first-boot work, see below); `/v1/health` carries `setup_pending` — see `Research/Guest/setup_assistant_skip.md` |`display.auto_lock` reads Settings' Auto-Lock (`maxInactivity` in profiled's`EffectiveUserSettings.plist`) and SpringBoard's `SBMinimumLockscreenIdleTime`.@@ -491,15 +491,23 @@ work has settled and returns, without changing anything1–30) and is settled when, over the last `stable_polls` polls (default 3,2–20), `/private/var/staged_system_apps` is empty or absent (installd expandsthe removable system apps from it on the first boot), the number of-registered apps did not change, and installd used less than 0.2 s of CPU-between polls or was not running. `timeout_s` defaults to 90 and is capped at+registered apps did not change, installd used less than 0.2 s of CPU+between polls or was not running, and in the latest poll data migration is+not running: `com.apple.migration` for user mobile records+`kern.osversion` as `LastSystemVersion` or as `DMLastMigrationResults`'s+`buildVersion`, or, with neither recorded, DataMigrator's XPC service+(`com.apple.datamigrator`) is not running. The domain is empty until a fresh+restore's first migration ends. `timeout_s` defaults to 90 and is capped at110, because the host waits at most 120 s for one answer; a caller that needslonger calls again. A timeout is not an error: it returns `{settled, elapsed_s,polls, timeout_s, poll_s, stable_polls, reasons, signals}` with `settled:false` and `reasons` naming the conditions still unmet; `signals` holds`staged_system_apps` (entries, null when unreadable), `app_count`,`app_counts` (the window), `installd_pid`, `installd_cpu_seconds`,-`installd_cpu_delta` and `setup_pending`.+`installd_cpu_delta`, `setup_pending` and `data_migration_done` (`false`+while the record is missing and DataMigrator runs; null when the build is+unknown, or nothing is recorded and DataMigrator is not running, which does+not hold the verdict back).`VPhoneDaemon/Tests/run-logic-tests.sh` builds the guest-independent parts ofthese three (the lists and their bookkeeping, the settle verdict, the devicediff --git a/VPhoneDaemon/Daemon/GuestAPI+FirstBoot.swift b/VPhoneDaemon/Daemon/GuestAPI+FirstBoot.swiftindex bf7a8ef5..077adc49 100644--- a/VPhoneDaemon/Daemon/GuestAPI+FirstBoot.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+FirstBoot.swift@@ -61,12 +61,14 @@ extension GuestAPI {"installd_cpu_seconds": latest.installdCPUSeconds.map { $0 as Any } ?? NSNull(),"installd_cpu_delta": verdict.installdCPUDelta.map { $0 as Any } ?? NSNull(),"setup_pending": setupAssistantPending(),+ "data_migration_done": latest.dataMigrationDone.map { $0 as Any } ?? NSNull(),] as [String: Any],]}private static func firstBootSample(time: Double) -> GuestFirstBootSettle.Sample {var sample = GuestFirstBootSettle.Sample(time: time)+ sample.dataMigrationDone = dataMigrationDone()let staged = GuestFirstBootSettle.stagedSystemAppsPathif !FileManager.default.fileExists(atPath: staged) {sample.stagedSystemApps = 0diff --git a/VPhoneDaemon/Daemon/GuestAPI+SetupAssistant.swift b/VPhoneDaemon/Daemon/GuestAPI+SetupAssistant.swiftindex a4863772..b669edfa 100644--- a/VPhoneDaemon/Daemon/GuestAPI+SetupAssistant.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+SetupAssistant.swift@@ -12,7 +12,13 @@ import IcliSystem/// `BYBuddyIOSCurrentVersion`. Writing the keys while Setup is on screen does/// not dismiss it, and killing Setup only makes SpringBoard start it again,/// so a skip writes the keys and then restarts SpringBoard.-/// `Research/Guest/setup_assistant_skip.md` has the experiments behind this.+///+/// On the first boot after a restore, SpringBoard decides only once data+/// migration has finished (FrontBoard's `DataMigrationCompleted` milestone),+/// and FrontBoard ignores a relaunch request until then. The keys written+/// before that point are read when it decides, so the skip writes them and+/// leaves SpringBoard alone. `Research/Guest/setup_assistant_skip.md` has the+/// experiments behind this.extension GuestAPI {static func executeSetupAssistant(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {switch method {@@ -64,12 +70,50 @@ extension GuestAPI {"setup_done": buddyValue("SetupDone") as? Bool ?? false,"setup_version": buddySetupVersion.map { $0 as Any } ?? NSNull(),"current_version": setupAssistantCurrentVersion.map { $0 as Any } ?? NSNull(),+ "data_migration_done": dataMigrationDone().map { $0 as Any } ?? NSNull(),]}+ /// `kern.osversion`, the running build (`24A435`).+ static let systemBuildVersion: String? = {+ var size = 0+ guard sysctlbyname("kern.osversion", nil, &size, nil, 0) == 0, size > 0 else { return nil }+ var buffer = [CChar](repeating: 0, count: size)+ guard sysctlbyname("kern.osversion", &buffer, &size, nil, 0) == 0 else { return nil }+ let build = String(decoding: buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self)+ return build.isEmpty ? nil : build+ }()++ /// Whether DataMigrator finished migrating for the running build; nil when+ /// that cannot be told. See `GuestFirstBootSettle.dataMigrationDone`.+ static func dataMigrationDone() -> Bool? {+ func value(_ key: String) -> Any? {+ CFPreferencesCopyValue(+ key as CFString, GuestFirstBootSettle.migrationDomain as CFString,+ "mobile" as CFString, kCFPreferencesAnyHost,+ )+ }+ let results = value(GuestFirstBootSettle.migrationResultsKey) as? [String: Any]+ return GuestFirstBootSettle.dataMigrationDone(+ build: systemBuildVersion,+ lastSystemVersion: value(GuestFirstBootSettle.migrationLastSystemVersionKey) as? String,+ lastResultsBuild: results?["buildVersion"] as? String,+ migratorRunning: dataMigratorRunning(),+ )+ }++ /// The process name is cut to `com.apple.datami`; the path is not.+ private static func dataMigratorRunning() -> Bool {+ let processes = (try? listProcesses(filter: "com.apple.datami"))?["processes"] as? [[String: Any]] ?? []+ return processes.contains { ($0["executable"] as? String)?.hasSuffix(GuestFirstBootSettle.dataMigratorSuffix) == true }+ }+/// Marks setup finished for this iOS version and restarts SpringBoard./// These three keys are all Setup needs: with every other key absent,/// SpringBoard starts to the Home Screen and no later panes appear.+ /// While data migration is still running SpringBoard has not decided yet+ /// and would ignore the restart, so it is not restarted; `respring` then+ /// says so.private static func skipSetupAssistant() throws -> [String: Any] {guard let current = setupAssistantCurrentVersion else {throw GuestAPIError.operationFailed("SetupAssistant.framework does not export BYBuddyIOSCurrentVersion")@@ -78,7 +122,24 @@ extension GuestAPI {_ = try writePreference(domain: buddyDomain, key: "SetupDone", value: .bool(true))_ = try writePreference(domain: buddyDomain, key: "SetupFinishedAllSteps", value: .bool(true))_ = try writePreference(domain: buddyDomain, key: "SetupVersion", value: .int(Int64(version)))- let springBoard = try respring()+ let springBoard: [String: Any]+ if dataMigrationDone() == false {+ springBoard = ["restarted": false, "reason": "data_migration_pending"]+ } else {+ do {+ springBoard = try respring()+ } catch let error as IcliError {+ // FrontBoard ignored the relaunch and launchd refused to stop+ // SpringBoard (status 144 on the guest). The keys are written;+ // asking again restarts it once FrontBoard takes the request.+ throw IcliError.commandFailed([+ "error": "springboard_restart_failed",+ "message": "Setup Assistant's keys are written, but SpringBoard did not restart: \(error.message)",+ "reason": "busy",+ "retryable": true,+ ])+ }+ }var status = try setupAssistantStatus()status["respring"] = springBoardreturn statusdiff --git a/VPhoneDaemon/Daemon/GuestFirstBootSettle.swift b/VPhoneDaemon/Daemon/GuestFirstBootSettle.swiftindex 4fd25695..6bddabce 100644--- a/VPhoneDaemon/Daemon/GuestFirstBootSettle.swift+++ b/VPhoneDaemon/Daemon/GuestFirstBootSettle.swift@@ -14,10 +14,21 @@ import Foundation/// - `staged_system_apps` is empty (or absent),/// - the number of registered apps did not change,/// - installd used less than `installdBusyCPUSeconds` of CPU between polls,-/// or was not running.+/// or was not running;+/// - in the latest poll, data migration has finished for the running build.////// Measured on an iOS 27.0 template (P0, 2026-10-07): 92 s after `setup.skip`-/// all three held.+/// the first three held.+///+/// The app expansion is one plugin of the first boot's data migration+/// (DataMigrator's `SystemAppMigrator`). The last plugin, `SpringBoard.migrator`,+/// ran 26–67 s on 27.0 (2026-10-09). Until it ends, FrontBoard has not+/// reached `FBSServiceMilestoneDataMigrationCompleted`: SpringBoard has not+/// decided whether to run Setup, and ignores a relaunch request. DataMigrator+/// then records the build in `com.apple.migration` (user mobile):+/// `LastSystemVersion` and `DMLastMigrationResults.buildVersion`. Before the+/// first migration the domain is empty. A template frozen before that point+/// would make every clone migrate again.////// Nothing here touches the guest, so `VPhoneDaemon/Tests/run-logic-tests.sh`/// builds this file on the Mac.@@ -38,6 +49,35 @@ enum GuestFirstBootSettle {/// installd's pid and CPU time, nil when it is not running.var installdPID: Int?var installdCPUSeconds: Double?+ /// Whether data migration finished for the running build, nil when+ /// that could not be told (no build version); only false holds the+ /// verdict back.+ var dataMigrationDone: Bool?+ }++ /// The domain and keys DataMigrator records a finished migration in.+ static let migrationDomain = "com.apple.migration"+ static let migrationLastSystemVersionKey = "LastSystemVersion"+ static let migrationResultsKey = "DMLastMigrationResults"++ /// DataMigrator's XPC service; it runs, holding its transactions, for+ /// the whole migration.+ static let dataMigratorSuffix = "/com.apple.datamigrator.xpc/com.apple.datamigrator"++ /// Data migration has finished for `build` (`kern.osversion`) when+ /// DataMigrator recorded it as the last system version or as the build of+ /// its last results, and is still running while the record is missing and+ /// DataMigrator runs. Nil when that cannot be told: the build is unknown,+ /// or nothing is recorded and DataMigrator is not running (a guest that+ /// records elsewhere then never waits for it).+ static func dataMigrationDone(+ build: String?, lastSystemVersion: String?, lastResultsBuild: String?, migratorRunning: Bool,+ ) -> Bool? {+ guard let build, !build.isEmpty else { return nil }+ if lastSystemVersion == build || lastResultsBuild == build {+ return true+ }+ return migratorRunning ? false : nil}struct Verdict: Equatable, Sendable {@@ -91,6 +131,9 @@ enum GuestFirstBootSettle {break}}+ if window.last?.dataMigrationDone == false {+ reasons.append("data migration has not finished")+ }return Verdict(settled: reasons.isEmpty, reasons: reasons, installdCPUDelta: lastDelta)}}diff --git a/VPhoneDaemon/Tests/LogicTests.swift b/VPhoneDaemon/Tests/LogicTests.swiftindex 78a0d30b..81b61eec 100644--- a/VPhoneDaemon/Tests/LogicTests.swift+++ b/VPhoneDaemon/Tests/LogicTests.swift@@ -3,8 +3,9 @@ import Foundation// MARK: - Harness/// Checks the guest-independent parts of vphoned on the Mac: the service-/// profile lists and bookkeeping, the first-boot settle verdict and the device-/// name rule. `run-logic-tests.sh` builds this file with those sources.+/// profile lists and bookkeeping, the first-boot settle verdict (data+/// migration included) and the device name rule. `run-logic-tests.sh` builds+/// this file with those sources.nonisolated(unsafe) var failures = 0nonisolated(unsafe) var checks = 0@@ -30,6 +31,7 @@ enum LogicTests {noneRestoresOnlyRecorded()recordRoundTrip()settleVerdicts()+ dataMigrationRecord()deviceNameRule()print("\(checks) checks, \(failures) failures")exit(failures == 0 ? 0 : 1)@@ -243,6 +245,47 @@ enum LogicTests {expectEqual(restarted.reasons, ["installd used 0.90 s CPU between polls"])let restartedIdle = GuestFirstBootSettle.evaluate([sample(0), sample(5, pid: 120, cpu: 0.05), sample(10, pid: 120, cpu: 0.06)], stablePolls: 3)expect(restartedIdle.settled, "a new, idle installd: \(restartedIdle.reasons)")++ // Data migration holds the verdict back until the latest poll has it+ // done; an unknown state (no build version) does not.+ func migrating(_ time: Double, _ done: Bool?) -> Sample {+ var polled = sample(time)+ polled.dataMigrationDone = done+ return polled+ }+ let pending = GuestFirstBootSettle.evaluate([migrating(0, false), migrating(5, false), migrating(10, false)], stablePolls: 3)+ expectEqual(pending.reasons, ["data migration has not finished"])+ let finished = GuestFirstBootSettle.evaluate([migrating(0, false), migrating(5, false), migrating(10, true)], stablePolls: 3)+ expect(finished.settled, "migration done in the latest poll: \(finished.reasons)")+ expect(GuestFirstBootSettle.evaluate([migrating(0, nil), migrating(5, nil), migrating(10, nil)], stablePolls: 3).settled, "unknown is not pending")+ let stillStaging = GuestFirstBootSettle.evaluate([migrating(0, false), migrating(5, false), {+ var polled = migrating(10, false)+ polled.stagedSystemApps = 30+ return polled+ }()], stablePolls: 3)+ expectEqual(stillStaging.reasons, ["staged_system_apps has 30 entries", "data migration has not finished"])+ }++ static func dataMigrationRecord() {+ func done(_ build: String?, _ last: String?, _ results: String?, running: Bool = true) -> Bool? {+ GuestFirstBootSettle.dataMigrationDone(+ build: build, lastSystemVersion: last, lastResultsBuild: results, migratorRunning: running,+ )+ }+ // A fresh restore: com.apple.migration is empty until DataMigrator ends.+ expectEqual(done("24A435", nil, nil), false)+ expectEqual(done("24A435", "24A435", "24A435"), true)+ expectEqual(done("24A435", "24A435", nil), true)+ expectEqual(done("24A435", nil, "24A435"), true)+ expectEqual(done("24A435", "24A435", "24A435", running: false), true)+ // The build changed (an update): the old record is not this build's.+ expectEqual(done("24A446", "24A435", "24A435"), false)+ // Nothing recorded and DataMigrator not running: unknown, never waited for.+ expectEqual(done("24A435", nil, nil, running: false), nil)+ expectEqual(done(nil, "24A435", "24A435"), nil)+ expectEqual(done("", nil, nil), nil)+ let migrator = "/System/Library/PrivateFrameworks/DataMigration.framework/XPCServices/com.apple.datamigrator.xpc/com.apple.datamigrator"+ expect(migrator.hasSuffix(GuestFirstBootSettle.dataMigratorSuffix), "the path seen on 27.0")}// MARK: - Device Name