Run a virtual iPhone on an Apple Silicon Mac.
Swift
Give templates a setup boot and slimming switches
Jackya9eb1090e000
diff --git a/Documents/Guides/create-and-run.md b/Documents/Guides/create-and-run.mdindex faa8aeb6..35dcf4f0 100644--- a/Documents/Guides/create-and-run.md+++ b/Documents/Guides/create-and-run.md@@ -42,10 +42,10 @@ The guest shows the VM's name as its device name, in Xcode's device list and `xc## Templates-A template is a complete machine that is never booted, kept in `<library>/.templates/<id>/`. `vm create` without `--no-template` works out the template key from its options and the two IPSWs before anything is restored: the guest device, the iOS and cloudOS versions and builds, the patch preset and the boot-chain patches it resolves to, the bundle series (`2.8` for 2.8.x), the disk size, and what was trimmed from the guest (nothing yet). Then:+A template is a complete machine kept in `<library>/.templates/<id>/`. It boots once while it is built, its setup boot, and never again once it is frozen. `vm create` without `--no-template` works out the template key from its options and the two IPSWs before anything is restored: the guest device, the iOS and cloudOS versions and builds, the patch preset and the boot-chain patches it resolves to, the bundle series (`2.8` for 2.8.x), the disk size, and the slimming switches below. Then:- If a template with that key exists, the VM is cloned from it with a new identity, given the requested CPU, memory and network, and booted once to check vphoned. This takes seconds and needs neither root nor the IPSWs; nothing is downloaded.-- Otherwise the full pipeline runs into a staging folder, `.templates/.building-<id>-<uuid>/`, without the first boot; the result is frozen and renamed to `.templates/<id>/` in one step, and the VM is cloned from it. A second `vm create` with the same key waits for the first instead of restoring a second copy. A failed build stays in its staging folder for inspection.+- Otherwise the full pipeline runs into a staging folder, `.templates/.building-<id>-<uuid>/`, followed by the setup boot; the result is frozen and renamed to `.templates/<id>/` in one step, and the VM is cloned from it. A second `vm create` with the same key waits for the first instead of restoring a second copy. A failed build stays in its staging folder for inspection.```shvphone-cli vm create phone-a --iphone-source … --cloudos-source … # builds the template, clones phone-a@@ -53,20 +53,62 @@ vphone-cli vm create phone-b --iphone-source … --cloudos-source … # clonesvphone-cli vm create phone-c --template 3f2a91c0d4e7 --cpu 4 --memory 6144```-`--template <id>` clones from a template by its identifier (or a unique prefix of four or more digits) and takes no IPSW options. `--device`, `--preset` and `--disk-size`, when given, must match the template's; a clone cannot change them. CPU, memory, screen and network are not part of the key.+`--template <id>` clones from a template by its identifier (or a unique prefix of four or more digits) and takes no IPSW options. `--device`, `--preset`, `--disk-size` and the slimming switches, when given, must match the template's; a clone cannot change them. CPU, memory, screen and network are not part of the key.-Every machine cloned from one template shares, with the template and with each other, its SEP root secret, its Data volume keys and the data the restore wrote. One clone could in principle decrypt another's Data volume. A VM that needs keys of its own, for example to sign in to Apple services for multi-device research, should be created with `--no-template`. Clones get a new ECID, UDID and MAC address on their first start, as with `vm clone --new-identity`, and share every unchanged block with the template on APFS: a new clone costs almost nothing until it starts writing.+### Setup boot and slimming++The setup boot finishes the template the way every clone should start. It boots the template once and, through vphoned, in this order:++1. deletes the `orig-fs.disabled.rn-*` APFS snapshot `cfw install` left (it holds about 20 MB, and every file trimmed from the System volume until it is gone);+2. skips Setup Assistant (`setup.skip`);+3. waits for first-boot work to settle (`setup.settle`, up to 10 minutes): installd expands the removable system apps on the first boot;+4. removes the system apps (`apps.remove_system`, backups kept in the guest);+5. applies the service profile (`services.profile.apply`), which includes turning off the sign-in follow-up daemons (`followupd`, `appleidsetupd`);+6. reboots, then checks: no snapshot left, Setup done, none of the profile's services running, the removed apps gone, vphoned answering;+7. clears the device name `vphone-vm` pinned for this boot, and shuts the guest down cleanly.++Every step has a deadline. A failed step stops the VM, records nothing and leaves the build unfrozen; `vm create` names the step and how to retry it.++| Switch | Default | Effect |+| --- | --- | --- |+| `--slim on\|off` | on | `off` keeps every app and service. The setup boot still runs: Setup is skipped and the snapshot deleted. |+| `--service-profile trimmed\|none` | trimmed | vphoned's trimmed profile: about 140 launchd jobs off, the App Store daemons and sign-in follow-up among them. |+| `--remove-apps on\|off` | on | Removes App Store, Home, TV, News, FaceTime, iTunes Store, Messages, Games, Find My and Wallet. Camera and Phone stay. |+| `--keep-apps <ids>` | none | Bundle IDs from that list to keep, comma-separated (`com.apple.findmy,com.apple.Passbook`). |+| `--accounts-off` | off | Also turns off `akd`, `amsaccountsd` and `appleaccountd`. The guest then cannot sign in to an Apple Account. |++Each choice is part of the key, so templates with different slimming live side by side and each serves only the creates that ask for it. Removed apps and the profile stay reversible on a clone: `apps.restore_system` puts an app back from its backup, and `services.profile.apply {"profile":"none"}` turns back on exactly what the profile turned off (both through `vphone-launchpad-cli guest rpc`).++What every clone inherits from the template: Setup done, the apps and services as the setup boot left them, the first-boot work installd and the indexers did, and the Data volume as of that boot. It does not inherit a device name: the template's pin is cleared, so a clone shows `iPhone` until its own VM connects and pins the clone's name. A new identity also means the Mac asks "Trust This Computer?" again.++### Finishing a VM as a template++Launchpad builds a machine with its own pipeline and boots it once, leaving it at Setup. To turn such a machine (or any VM straight after creating it) into a template, stop it, give it the setup boot, and adopt it:++```sh+vphone-cli vm stop phone-src+vphone-cli vm template setup phone-src # headless; --window to watch, slimming switches as for vm create+vphone-cli vm template adopt phone-src # key from its records and what the setup boot recorded+vphone-cli vm create phone-d --template <id> --skip-first-boot+```++`vm template setup` refuses a running VM and a frozen template. On a VM it reports an app vphoned would not remove and leaves it out of the recorded steps, so the adopted key says what was really done. Given a `.building-…` name from `vm template list` (a `vm create` whose setup boot failed), it sets the build up to its key, which fixes the slimming, and freezes it on success.++### Shared secrets++Every machine cloned from one template shares, with the template and with each other, its SEP root secret, its Data volume keys and the data the restore and the setup boot wrote. One clone could in principle decrypt another's Data volume. A VM that needs keys of its own, for example to sign in to Apple services for multi-device research, should be created with `--no-template` (which takes no slimming switches). Clones get a new ECID, UDID and MAC address on their first start, as with `vm clone --new-identity`, and share every unchanged block with the template on APFS: a new clone costs almost nothing until it starts writing, and a slimmed template leaves it little first-boot work to write.```shvphone-cli vm template list # id, key summary, STALE with the reasonsvphone-cli vm template show <id> --json+vphone-cli vm template setup myphone # the setup boot, on a stopped VMvphone-cli vm template adopt myphone # freeze a stopped, newly created VM into a templatevphone-cli vm template delete <id>```-- **Stale.** A template is listed as stale when this `vphone-cli` belongs to another bundle series, when its preset now resolves to other boot-chain patches, or when its patch receipt disagrees with its plan. A stale template is never used: `vm create` with its key fails and names it. Delete it to have the next `vm create` build a new one.-- **Adopt.** `vm template adopt <vm>` turns a stopped VM into a template, under the key its own records give (`restore-info.json`, `PatchPlan.plist`, `config.plist`, the disk image and Launchpad's `launchpad.json`). The VM leaves `vm list`. Adopt a VM straight after creating it: every clone inherits what its guest has done since its first boot. A VM with snapshots is refused, and so is one that would be stale unless `--force` is given.-- **Never booted.** `vm launch` and `vphone-vm` refuse a template, in DFU too; no machine name reaches into `.templates`, so `vm launch`, `clone`, `export`, `rename` and `delete` cannot pick one up by accident. A template that booted would write first-boot state into the blocks every later clone inherits, and the clones made before it would stop sharing them.+- **Stale.** A template is listed as stale when this `vphone-cli` belongs to another bundle series, when its key has an older format, when its preset now resolves to other boot-chain patches, or when its patch receipt disagrees with its plan. A stale template is never used: `vm create` with its key fails and names it. Delete it to have the next `vm create` build a new one.+- **Adopt.** `vm template adopt <vm>` turns a stopped VM into a template, under the key its own records give (`restore-info.json`, `PatchPlan.plist`, `config.plist`, the disk image, Launchpad's `launchpad.json`, and the steps `vm template setup` recorded in its `Template.plist`). The VM leaves `vm list`. Adopt a VM straight after its setup boot: every clone inherits what its guest has done since. A VM with snapshots is refused, and so is one that would be stale unless `--force` is given.+- **Never booted once frozen.** `vm launch` and `vphone-vm` refuse a frozen template, in DFU too; no machine name reaches into `.templates`, so `vm launch`, `clone`, `export`, `rename` and `delete` cannot pick one up by accident. A template that booted after being frozen would write state into the blocks every later clone inherits, and the clones made before it would stop sharing them.- **Deleting.** `vm template delete <id>` removes the template; machines cloned from it keep working. The blocks they still share with it are freed only when those machines change them or are deleted, so deleting a template frees less than its size while clones remain. Templates take disk space although `vm list` does not show them; look in `~/.vphone/machines/.templates`, keeping in mind that `du` counts a template and each of its clones in full.## Manual stagesdiff --git a/Research/Host/machine_templates.md b/Research/Host/machine_templates.mdindex 59271d5f..0945dddd 100644--- a/Research/Host/machine_templates.md+++ b/Research/Host/machine_templates.md@@ -1,6 +1,7 @@# Machine templates-A template is a complete machine that never boots. New machines are cloned+A template is a complete machine that boots once, for its setup boot, before+it is frozen, and never after. New machines are clonedfrom it with `clonefile(2)` and a new identity (see[machine identity and clone](machine_identity_and_clone.md)), so a secondmachine for the same firmware costs a clone and a few hundred MB of first-boot@@ -9,11 +10,17 @@ writes instead of a 20 GB restore. User-facing behavior is inCode: `VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineTemplateKey.swift` (the key,pure), `VPhoneMachineTemplates.swift` (storage, freeze, adopt, clone, boot-refusal), `VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneMachineTemplateKeys.swift`+refusal), `VPhoneTemplateSlimmingRequest.swift` (switches to slimming),+`VPhoneTemplateSetupBoot.swift` (the setup boot's steps, against a+`VPhoneTemplateSetupMachine`),+`VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneMachineTemplateKeys.swift`(resolving a key from options or from a machine's records),-`VPhoneVirtualMachineCreator.swift` (`vm create`) and-`VPhoneVirtualMachineTemplateCommand.swift` (`vm template`). Tests:-`VPhoneKit/VPhoneCoreKitTests/Bundle/MachineTemplate*Tests.swift`.+`VPhoneTemplateSetup.swift` (the switches, the `vphone-vm` the setup boot+drives over `vphone.sock`), `VPhoneVirtualMachineCreator.swift` (`vm create`)+and `VPhoneVirtualMachineTemplateCommand.swift` (`vm template`). Tests:+`VPhoneKit/VPhoneCoreKitTests/Bundle/MachineTemplate*Tests.swift`,+`TemplateSlimmingRequestTests.swift`, `TemplateSetupBootTests.swift` (the+step machine against a scripted guest).## Key@@ -28,14 +35,15 @@ Everything a clone inherits and could not change without a restore:| boot-chain plan digest | the preset resolved against the two versions | `PatchPlan.plist` `EnabledPatches`, `Parameters` || bundle series | this `vphone-cli`'s `Info.plist` | `launchpad.json` `bootChain`, else the `Guest` receipt part when `cfw install` wrote it, else this `vphone-cli` || disk size (decimal GB) | `--disk-size` | `Disk.img` length |-| slimming: trim tier, setup boot, service profile, removed apps | `none`, no, `none`, none | `Template.plist` steps of a machine still being built, else the same |-| format version | 1 | 1 |+| slimming: trim tier, setup boot, service profile, service groups, removed apps | the slimming switches (below) | `Template.plist` steps `vm template setup` recorded, else nothing done |+| format version | 2 | 2 |The identifier is the first 12 hex digits of the SHA-256 of one`name=value` line per field in a fixed order (`canonicalDescription`); a testpins one value against `shasum`. Any change to what a field means raises theformat version instead, so old templates stop matching rather than matching-wrongly.+wrongly. Format 2 added `service-groups` (P2's format-1 templates, never+booted, list as stale and still serve `--template <id>` with a warning).The plan digest hashes the sorted identifiers of the enabled patches whosecatalog target is `.firmware(*)` (AVPBooter, iBSS, iBEC, LLB, TXM, kernelcache,@@ -68,7 +76,7 @@ re-resolves with the template's own `PatchSelection.plist`.- `Template.plist`: `Identifier`, `Key`, `Created`, `BuiltWithBundleVersion`,`BootChainBundleVersion`, `SourceMachine` (the name a derived mDNS namefollows from), `Frozen`, `FrozenAt`, `Steps` (`SnapshotDeleted`,- `SetupDone`, `ServiceProfile`, `RemovedApps`, `TrimTier`).+ `SetupDone`, `ServiceProfile`, `ServiceGroups`, `RemovedApps`, `TrimTier`).- A build happens in `.building-<id>-<uuid>/<id>/` and is frozen by writing`Frozen = true` and one `renamex_np(RENAME_EXCL)` to `.templates/<id>`. Alisted template is always complete; a race with another build of the same@@ -77,7 +85,7 @@ re-resolves with the template's own `PatchSelection.plist`.promises.- A clone drops `Template.plist`, `Snapshots/` and `vphone.sock`.-## Never booting+## Never booting once frozenThe P0 measurement: booting a template after clones exist raised one clone'sprivate bytes from 0.42 GB to 0.80 GB, and every later clone would inherit@@ -89,20 +97,134 @@ that boot's state. Three layers keep a frozen template from booting:3. `VPhoneBootCommand.validate`, which `vphone-vm` runs on its arguments,checks it too, DFU included: a folder directly in `.templates`, a frozenrecord, or an unreadable one is refused. A machine in a staging folder may- boot; the setup boot of a later stage runs there.--## Lifecycle hooks--- **Offline trim** (later): runs inside the CFW install of a build and records- `Steps.TrimTier` with `VPhoneMachineTemplates.recordSteps(inBundle:)` before- the freeze.-- **Setup boot** (later): boots the staging machine through vphoned RPCs and- records `SetupDone`, `ServiceProfile`, `RemovedApps`, `SnapshotDeleted`.-- The key's slimming fields then come from the requested switches; `freeze`- refuses a build whose steps fell short.-- **Launchpad** builds a machine with its step-by-step pipeline, skips the- first boot, and runs `vm template adopt <name>`; then- `vm create <name> --template <id> --skip-first-boot` and its own first boot.+ boot; the setup boot runs there.++A staging machine's control socket,+`<library>/.templates/.building-<id>-<uuid>/<id>/vphone.sock`, is about 125+bytes for `~/.vphone/machines`, past the 104 bytes of `sun_path`.+`VPhoneUnixSocket.withAddressablePath` binds (in `vphone-vm`) and connects+(`VPhoneUnixSocket.connect`, so every host client) through a symbolic link to+the socket's folder inside a fresh 0700 folder under `/tmp`, removed right+after; the kernel follows the link, so the socket is the one at the long path.++## Slimming switches++`VPhoneTemplateSlimmingRequest.resolve()` maps the switches of `vm create`+and `vm template setup` to the key's slimming:++| Switches | trim | setup boot | services | groups | removed apps |+| --- | --- | --- | --- | --- | --- |+| none (`--slim on`) | `defaultTrimTier` (`none` until offline trim lands) | yes | trimmed | none | list C (10 apps) |+| `--slim off` | none | yes | none | none | none |+| `--service-profile none` | default | yes | none | none | list C |+| `--remove-apps off` | default | yes | trimmed | none | none |+| `--keep-apps a,b` | default | yes | trimmed | none | list C minus a, b |+| `--accounts-off` | default | yes | trimmed | `accounts` | list C |++List C: `com.apple.AppStore`, `Home`, `tv`, `news`, `facetime`, `MobileStore`,+`MobileSMS`, `games`, `findmy`, `Passbook` (P0 and P1 verified each stays+removed across a respring and a reboot on 27.0). Camera stays for camera+passthrough checks; Phone lives on the System volume and vphoned refuses it.+Contradictions are refused, all at once: `--slim off` with any slimming+switch, `--accounts-off` without the trimmed profile, `--keep-apps` naming an+app outside list C or with `--remove-apps off`, an unknown tier or profile.+`--no-template` takes no slimming switch; `--template <id>` takes them only to+check them against the template.++`--slim off` still has a setup boot: skipping Setup and waiting for+first-boot work are not slimming. Without them every clone would start at the+Setup screen and write its own first-boot state (P2 measured 3.2 GB per clone+after seven minutes, P0 0.35 GB with a setup boot). It deletes the orig-fs+snapshot too, which is harmless (CFW's rename and `cfw update-environment`+do not use it) and is what lets an offline trim free its space. The sign-in+follow-up daemons stay on with `--slim off`; a template that went through+`setup.skip` has no follow-up item for them to show (P0).++The services the key promises are fixed per template, although vphoned can+switch the profile on a running machine: a clone of a trimmed template starts+trimmed without a reboot of its own, and `services.profile.apply none` undoes+it on that clone.++## Setup boot++`VPhoneTemplateSetupBoot.run()` drives a `VPhoneTemplateSetupMachine`. The+real one (`VPhoneTemplateSetupVirtualMachine`) starts `vphone-vm` the way+`vm launch` does: `requireBootable` (a frozen template is refused),+`VPhoneBundleActivity.requireStopped`, this bundle's vphoned staged,+`VPhoneBootCommand.validate`; headless for `vm template setup` unless+`--window`, windowed in `vm create` like its first-boot check (the template's+setup boot is the guest's first boot). It talks to vphoned through+`vphone.sock`'s `rpc` verb and reads `guest_error`.++| Step | Calls | Deadline | Passes when |+| --- | --- | --- | --- |+| connect | `ping` every second | 300 s | vphoned answers |+| 0 snapshot | `apfs.snapshot.delete {force}` | 120 s | no `orig-fs.disabled.rn-*` in `remaining`/`after` (none to begin with is fine) |+| a skip | `setup.skip {force}`, any refusal retried | 120 s | `setup_done` |+| b settle | `setup.settle {timeout_s ≤ 110}` repeated | 600 s overall | `settled` |+| c apps | `apps.remove_system {bundle_ids, force}` | 300 s | every app `removed`, `absent` or `unregistered_stale` |+| d/e profile | `services.profile.apply {profile, groups, force}`, `services.profile` | 180 s | no `failed`; the record holds `signin_followup` and the extra groups; followupd and appleidsetupd disabled |+| f reboot | `processes.list` (launchd's `start_time`), `system.reboot {force}` | 300 s | vphoned answers with another launchd start time |+| f verify | `apfs.snapshots`, `setup.status`, `services.profile`, `apps.list`, `ping`, repeated | 120 s | no snapshot, Setup done, the profile recorded with `running` empty, no removed app listed |+| name | `device.name.set {}` | 30 s | (a warning on failure) |+| g stop | SIGINT to `vphone-vm` | 60 s | it exits without "turning it off" (the guest shut down within its 15 s) |++`setup.skip` is retried on any refusal: right after vphoned first answers on+a guest that just finished its first boot, it failed with "Cannot allocate+memory", then for 87 s with "relaunch action ignored and launchd stop failed:+144 Requestor lacks required entitlement" (SpringBoard's restart), before it+went through (p4-src, 27.0, 2026-10-08). The keys it writes are idempotent.++Retries: a call that did not reach vphoned (no socket, guest not connected,+timeout) or that vphoned refused with `retryable: true` or `reason: busy`+(`apfs.snapshot.delete` on EBUSY) is repeated every 3 s until the step's+deadline. Other refusals fail the step, except `apps.remove_system`'s+`remove_incomplete`, whose `results` are read: a template build (key fixed)+fails on any app not removed; a machine to be adopted reports it and leaves it+out of the recorded steps, so the adopted key says what was done.++On any failure the VM is killed, the failure names the step+(`VPhoneTemplateSetupFailure`), and nothing is recorded:+`recordSetupBoot` writes only a complete outcome (`SnapshotDeleted`,+`SetupDone`, `ServiceProfile`, `ServiceGroups`, `RemovedApps`; `TrimTier` is+left to the trim), so `freeze` keeps refusing the build.++The device name: `vphone-vm` pins the guest's name to the machine's name+(`device.name.set`) on every connect, and the pin lives in+`/var/db/vphone/devicename.plist` on the Data volume. Left in place, every+clone would show the template's name (its identifier, or the adopted+machine's name) until its own VM connects, and its first DHCP lease would+carry it (P1). The setup boot clears it last.++Measured on iPhone17,3 27.0 (24A435), 2026-10-08: Launchpad created+`p4-src` (first boot at Setup), `vm template setup p4-src` took 2 min 16 s+(Setup's restart refused for 87 s, settle 25 s, reboot 10 s, stop 4 s), the+image grew from 16.8 to 19.3 GB allocated. Two clones started through+Launchpad came up at the Lock Screen and unlocked to the Home Screen (with+"Trust This Computer?"), Setup done, 249 apps with the ten gone, 141 services+off and none running, no snapshot, device names `p4-a` and `p4-b`. Private+bytes (`ATTR_CMNEXT_PRIVATESIZE`) of each clone: 0.17 and 0.09 GB a minute in,+0.58 GB after seven minutes, against 3.2 GB for P2's never-booted template.+The template's own private bytes were 0.10 GB, the blocks both clones+rewrote. A Time Machine local snapshot counts as sharing, so measure a file+made after the latest one, as these clones were.++## Lifecycle++- **vm create** (default): key from the options and switches → lock →+ restore and `cfw install` into the staging folder (offline file trimming+ belongs inside `cfw install` and records `Steps.TrimTier`) → setup boot →+ recorded key must equal the requested one → `freeze` → clone.+ A setup boot failure leaves the build; `vm template setup .building-…`+ retries it under the lock and freezes it on success.+- **Launchpad** (P5) builds a machine with its step-by-step pipeline, whose+ first boot leaves it running at Setup; it stops it, runs+ `vm template setup <name> [switches]`, then `vm template adopt <name>`,+ then `vm create <name> --template <id> --skip-first-boot` and its own first+ boot. `vm template setup` on a machine writes an unfrozen `Template.plist`+ (key from its records) when it has none, and records the steps there.+- `freeze` and `adopt` refuse a record whose steps did not produce the key's+ slimming.## Staleness@@ -119,6 +241,9 @@ not make a template stale; the clone can take `cfw update-environment`.## Shared secretsEvery clone of a template shares its SEP root secret, gigalocker, Data/User-volume keys, `mobileactivationd.uuid` and the Data contents the restore wrote.-A template that was never booted shares no trusted host, keychain or Setup-state. `vm create --no-template` builds a machine with secrets of its own.+volume keys, `mobileactivationd.uuid`, the Data contents the restore wrote and+what the setup boot wrote: Setup done, the keychain items and caches of one+first boot, the removed-app backups and the service record. The setup boot+never pairs a host, signs in or unlocks with a passcode, so no trusted host or+account is shared. `vm create --no-template` builds a machine with secrets of+its own.diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Host/VPhoneHostAutomationProbe.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Host/VPhoneHostAutomationProbe.swiftindex 38fcd8d1..725e64ab 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Host/VPhoneHostAutomationProbe.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Host/VPhoneHostAutomationProbe.swift@@ -11,8 +11,14 @@ enum VPhoneHostAutomationProbe {}/// One request, one reply line. Nil when the socket is not there or the- /// reply is not JSON.- static func send(_ request: [String: Any], socketPath: String, timeout seconds: Int = 2) -> [String: Any]? {+ /// reply is not JSON. `timeout` bounds each read; `maximumReply` the+ /// reply (an `apps.list` or `processes.list` runs to a few hundred KB).+ static func send(+ _ request: [String: Any],+ socketPath: String,+ timeout seconds: Int = 2,+ maximumReply: Int = 1 << 20,+ ) -> [String: Any]? {guard case let .success(fd) = VPhoneUnixSocket.connect(to: socketPath) else { return nil }defer { close(fd) }@@ -32,8 +38,8 @@ enum VPhoneHostAutomationProbe {guard written == request.count else { return nil }var reply = Data()- var buffer = [UInt8](repeating: 0, count: 512)- while reply.count < 1 << 20 {+ var buffer = [UInt8](repeating: 0, count: 64 * 1024)+ while reply.count < maximumReply {let count = buffer.withUnsafeMutableBytes { bytes inDarwin.read(fd, bytes.baseAddress, bytes.count)}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneTemplateSetup.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneTemplateSetup.swiftnew file mode 100644index 00000000..69f652aa--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneTemplateSetup.swift@@ -0,0 +1,209 @@+import ArgumentParser+import Foundation+import VPhoneCoreKit++// MARK: - Slimming switches++/// The slimming switches `vm create` and `vm template setup` share.+struct VPhoneTemplateSlimmingOptions: ParsableArguments {+ @Option(help: ArgumentHelp(+ "Slim the template: on (default) | off. off keeps every service and app; Setup is skipped either way",+ valueName: "on|off",+ ))+ var slim: String?+ @Option(help: ArgumentHelp("Service profile the template applies: trimmed (default) | none", valueName: "profile"))+ var serviceProfile: String?+ @Option(help: ArgumentHelp("Remove the default system apps (App Store, TV, News, …): on (default) | off", valueName: "on|off"))+ var removeApps: String?+ @Option(+ help: ArgumentHelp("Bundle IDs of default-removed apps to keep, comma-separated (com.apple.findmy,com.apple.Passbook)", valueName: "ids"),+ transform: { $0.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } },+ )+ var keepApps: [String] = []+ @Flag(help: "Also turn off the Apple Account daemons (akd, amsaccountsd, appleaccountd); the guest then cannot sign in")+ var accountsOff = false++ var request: VPhoneTemplateSlimmingRequest {+ get throws {+ try VPhoneTemplateSlimmingRequest(+ slim: slim.map { try VPhoneVirtualMachineConfigCommand.parseSwitch($0, option: "--slim") },+ serviceProfile: serviceProfile,+ removeApps: removeApps.map { try VPhoneVirtualMachineConfigCommand.parseSwitch($0, option: "--remove-apps") },+ keepApps: keepApps,+ accountsOff: accountsOff,+ )+ }+ }++ /// The slimming asked for, as a ValidationError when switches disagree.+ func resolve() throws -> VPhoneMachineTemplateSlimming {+ do {+ return try request.resolve()+ } catch let error as VPhoneTemplateSlimmingError {+ throw ValidationError(error.description)+ }+ }+}++// MARK: - The VM a setup boot drives++/// `vphone-vm` started for a setup boot, driven through its `vphone.sock`.+/// Booted the way `vm launch` boots: refused for a frozen template or a+/// running machine, with this bundle's vphoned staged, and through the same+/// `VPhoneBootCommand` validation `vphone-vm` repeats.+final class VPhoneTemplateSetupVirtualMachine: VPhoneTemplateSetupMachine {+ private let bundle: VPhoneBundle+ private let launcher: VPhoneGuestLaunchPlanner+ private let resources: VPhoneResources+ private let headless: Bool+ private let verbosity: VPhoneVerbosity+ private var process: VPhoneManagedProcess?++ init(bundle: VPhoneBundle, launcher: VPhoneGuestLaunchPlanner, resources: VPhoneResources, headless: Bool, verbosity: VPhoneVerbosity) {+ self.bundle = bundle+ self.launcher = launcher+ self.resources = resources+ self.headless = headless+ self.verbosity = verbosity+ }++ private var socketPath: String {+ bundle.url.appendingPathComponent("vphone.sock").path+ }++ func start() throws {+ try VPhoneMachineTemplates.requireBootable(bundleURL: bundle.url)+ try VPhoneBundleActivity.requireStopped(bundle)+ _ = try VPhoneLaunchLayout(resources: resources).stageVphoned(into: bundle)+ var boot = VPhoneBootCommand(config: bundle.configURL, headless: headless)+ try boot.validate()+ let (executable, arguments) = launcher.plan(boot.bootArguments)+ if verbosity.tracesInternals {+ print("[trace] spawn \(executable.path) \(arguments.joined(separator: " ")) (guest serial: off)")+ }+ let process = VPhoneManagedProcess(executable, arguments, cwd: bundle.url, echo: false)+ try process.start()+ self.process = process+ }++ func failure() -> String? {+ guard let process else { return "the VM was not started" }+ switch process.waitForOutput(matching: "(?i:\(VPhoneBootPatterns.panicRegex))", timeout: 0) {+ case .matched:+ return "the guest panicked"+ case let .exited(code):+ return "vphone-vm exited with status \(code)"+ case .timedOut:+ return nil+ }+ }++ func ping() -> Bool {+ VPhoneHostAutomationProbe.ping(socketPath: socketPath)+ }++ func call(_ method: String, params: [String: Any], timeout: TimeInterval) throws -> [String: Any] {+ let request: [String: Any] = ["t": "rpc", "method": method, "params": params, "screen": false]+ guard let reply = VPhoneHostAutomationProbe.send(+ request,+ socketPath: socketPath,+ timeout: Int(timeout.rounded(.up)),+ maximumReply: 64 << 20,+ ) else {+ throw VPhoneGuestCallError(kind: .transport, message: "no answer from vphone.sock")+ }+ if reply["ok"] as? Bool == true {+ return reply["result"] as? [String: Any] ?? [:]+ }+ let message = reply["error"] as? String ?? "refused"+ if let detail = reply["guest_error"] as? [String: Any] {+ throw VPhoneGuestCallError(kind: .refused, message: message, detail: detail)+ }+ // The VM answered for the guest: not connected yet, or the request+ // to vphoned failed on the way.+ throw VPhoneGuestCallError(kind: .transport, message: message)+ }++ /// SIGINT makes `vphone-vm` ask the guest to shut down and exit once it+ /// has; it turns the guest off after 15 s and says so.+ func stop(timeout: TimeInterval) -> Bool {+ guard let process else { return true }+ guard process.interrupt(waitingUpTo: timeout) else {+ process.terminate()+ return false+ }+ return !process.outputText.contains("turning it off")+ }++ func kill() {+ process?.terminate()+ }+}++// MARK: - Running a setup boot++enum VPhoneTemplateSetupRun {+ /// Runs the setup boot on the machine folder at `bundleURL` and records+ /// what it did in that folder's `Template.plist`, which must exist.+ /// Throws ``VPhoneTemplateSetupFailure`` and records nothing on failure.+ @discardableResult+ static func run(+ bundleURL: URL,+ plan: VPhoneTemplateSetupPlan,+ launcher: VPhoneGuestLaunchPlanner,+ resources: VPhoneResources,+ headless: Bool,+ verbosity: VPhoneVerbosity,+ ) throws -> VPhoneTemplateSetupOutcome {+ let bundle = try VPhoneBundle.load(at: bundleURL)+ let machine = VPhoneTemplateSetupVirtualMachine(+ bundle: bundle,+ launcher: launcher,+ resources: resources,+ headless: headless,+ verbosity: verbosity,+ )+ let outcome = try VPhoneTemplateSetupBoot(machine: machine, plan: plan).run()+ try VPhoneMachineTemplates.recordSetupBoot(outcome, inBundle: bundleURL)+ report(outcome)+ return outcome+ }++ static func report(_ outcome: VPhoneTemplateSetupOutcome) {+ let order = VPhoneTemplateSetupStep.allCases+ let times = order.compactMap { step in outcome.durations[step].map { "\(step.rawValue) \(Int($0.rounded())) s" } }+ print("[+] Setup boot done: \(times.joined(separator: ", "))")+ print(" snapshots deleted: \(outcome.deletedSnapshots.isEmpty ? "none left" : outcome.deletedSnapshots.joined(separator: ", "))")+ var services = outcome.serviceProfile+ if !outcome.serviceGroups.isEmpty {+ services += " +" + outcome.serviceGroups.joined(separator: ",")+ }+ print(" services: \(services)\(outcome.serviceProfile == "none" ? "" : " (\(outcome.servicesOwned) owned)")")+ print(" apps removed: \(outcome.removedApps.isEmpty ? "none" : outcome.removedApps.joined(separator: ", "))")+ for warning in outcome.warnings {+ print(" warning: \(warning)")+ }+ }+}++// MARK: - Finishing a build++enum VPhoneTemplateBuildFinisher {+ /// The key a build's own records give must be the one it is filed under,+ /// or no later create (or adopt) would find it.+ static func requireRecordedKey(_ build: VPhoneMachineTemplateBuild, key: VPhoneMachineTemplateKey) throws {+ let recorded = try VPhoneMachineTemplateKeys.recorded(VPhoneBundle.load(at: build.bundleURL), slimming: key.slimming)+ guard recorded.key == key else {+ throw ValidationError(+ "The built template's records give another key than requested (\(key.differences(from: recorded.key).joined(separator: "; "))).",+ )+ }+ }++ /// Checks the recorded key and freezes the build; `freeze` refuses steps+ /// that fell short of the key.+ static func freeze(_ build: VPhoneMachineTemplateBuild, key: VPhoneMachineTemplateKey) throws -> VPhoneMachineTemplate {+ try requireRecordedKey(build, key: key)+ return try VPhoneMachineTemplates.freeze(build)+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swiftindex 9b62249e..848042c7 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift@@ -21,6 +21,15 @@ struct VPhoneVirtualMachineCreateCommand: ParsableCommand {--no-template builds the VM on its own, with keys of its own, as before. \--template <id> clones from a template listed by vm template list.+ A new template boots once before it is frozen (its setup boot): the orig-fs snapshot \+ is deleted, Setup Assistant skipped, first-boot work waited for, the default system apps \+ removed (App Store, Home, TV, News, FaceTime, iTunes Store, Messages, Games, Find My, \+ Wallet; never Phone or Camera) and the trimmed service profile applied, then it reboots, \+ is checked and shut down. Every clone starts at the Lock Screen with that state. \+ --slim off keeps every app and service (Setup is still skipped); --service-profile, \+ --remove-apps, --keep-apps and --accounts-off pick parts. Each choice is part of the key, \+ so templates with different slimming live side by side.+--cpu, --memory, --network and --unlock-at-startup are set on the new VM, whichever way \it is made.""",@@ -57,6 +66,7 @@ struct VPhoneVirtualMachineCreateCommand: ParsableCommand {var noTemplate = false@Flag(help: "Do not boot the new VM to check that vphoned answers")var skipFirstBoot = false+ @OptionGroup(title: "Template slimming") var slimming: VPhoneTemplateSlimmingOptions@Flag(name: .customLong("keep-artifacts"),help: "Keep the prepared restore tree after installation. Downloaded IPSWs always stay in the IPSW cache.",@@ -69,6 +79,10 @@ struct VPhoneVirtualMachineCreateCommand: ParsableCommand {if template != nil, noTemplate {throw ValidationError("--template and --no-template exclude each other.")}+ if noTemplate, try !slimming.request.isEmpty {+ throw ValidationError("The slimming switches shape a template; --no-template builds the VM without one.")+ }+ _ = try slimming.resolve()if template != nil {let firmware = [("--iphone-source", iphoneSource != nil),@@ -140,8 +154,14 @@ struct VPhoneVirtualMachineCreateCommand: ParsableCommand {verbosity: VPhoneVerbosity(count: verboseCount),keepArtifacts: keepArtifacts,template: templateUse,- templateRequest: VPhoneMachineTemplateRequest(device: device, patchPreset: preset, diskSizeGB: diskSize),+ templateRequest: VPhoneMachineTemplateRequest(+ device: device,+ patchPreset: preset,+ diskSizeGB: diskSize,+ slimming: slimming.request.isEmpty ? nil : slimming.resolve(),+ ),skipsFirstBoot: skipFirstBoot,+ slimming: slimming.resolve(),))}}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swiftindex 660fd472..37c5718f 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swift@@ -40,8 +40,12 @@ public extension VPhoneVirtualMachineCreator {/// template given by identifier. Nil fields were not given.public var templateRequest: VPhoneMachineTemplateRequest/// Leave the first boot to the caller (Launchpad boots the machine- /// itself). A template is never booted either way.+ /// itself). This is the clone's boot; a template boots only for its+ /// setup boot, before it is frozen.public var skipsFirstBoot: Bool+ /// What a template built for this create is slimmed of; part of the+ /// key it is looked up by.+ public var slimming: VPhoneMachineTemplateSlimmingpublic init(name: String,@@ -61,6 +65,7 @@ public extension VPhoneVirtualMachineCreator {template: TemplateUse = .none,templateRequest: VPhoneMachineTemplateRequest = VPhoneMachineTemplateRequest(),skipsFirstBoot: Bool = false,+ slimming: VPhoneMachineTemplateSlimming = VPhoneTemplateSlimmingRequest.defaultSlimming,) {self.name = nameself.iphoneSource = iphoneSource@@ -79,6 +84,7 @@ public extension VPhoneVirtualMachineCreator {self.template = templateself.templateRequest = templateRequestself.skipsFirstBoot = skipsFirstBoot+ self.slimming = slimming}}}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swiftindex f4e364a2..eeef0502 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift@@ -246,6 +246,7 @@ public struct VPhoneVirtualMachineCreator {cloudOS: .init(version: sources.cloud.version, build: sources.cloud.build),preset: options.patchPreset,diskSizeGB: options.diskSizeGB,+ slimming: options.slimming,)print("[*] Template key \(key.identifier): \(key.summary)")@@ -278,9 +279,11 @@ public struct VPhoneVirtualMachineCreator {}/// Builds the template for `key` in a staging folder in `.templates` and- /// freezes it into place. The template is never booted. A failed build- /// is left in its staging folder for inspection; `vm template list`- /// shows it and `vm template delete` removes it.+ /// freezes it into place. After `cfw install` the template boots once, its+ /// setup boot, and never again once frozen. A failed build is left in its+ /// staging folder for inspection; `vm template list` shows it,+ /// `vm template setup` finishes one whose setup boot failed, and+ /// `vm template delete` removes it.private func buildTemplate(_ key: VPhoneMachineTemplateKey,options: Options,@@ -315,26 +318,38 @@ public struct VPhoneVirtualMachineCreator {try buildGuest(at: bundle.url, options: options, outputs: outputs)- // Offline trimming (after cfw install) and the setup boot record- // their work with VPhoneMachineTemplates.recordSteps here, before- // the freeze; freeze refuses steps that do not match the key.-- // The key the template's own records give must be the one it is- // filed under, or no later create (or adopt) would find it.- let recorded = try VPhoneMachineTemplateKeys.recorded(VPhoneBundle.load(at: bundle.url), slimming: key.slimming)- guard recorded.key == key else {- throw ValidationError(- "The built template's records give another key than requested (\(key.differences(from: recorded.key).joined(separator: "; "))).",+ // Offline file trimming runs inside the CFW install above and+ // records Steps.TrimTier there (key.slimming.trimTier says which+ // tier). The snapshot it cannot delete from the host goes in the+ // setup boot's first step, which frees what the trim removed.++ if key.slimming.setupBoot {+ print("\n=== Template setup boot ===")+ // With a window, as the first-boot check: this is the guest's+ // first boot (see runBootAnalysis).+ try VPhoneTemplateSetupRun.run(+ bundleURL: bundle.url,+ plan: VPhoneTemplateSetupPlan(slimming: key.slimming, requiresEveryApp: true),+ launcher: requireLauncher(),+ resources: resources,+ headless: false,+ verbosity: options.verbosity,)}++ // freeze refuses steps that do not match the key.+ try VPhoneTemplateBuildFinisher.requireRecordedKey(build, key: key)try outputs.handBack(build.stagingURL)let template = try VPhoneMachineTemplates.freeze(build)outputs.replace(build.stagingURL, with: template.url)print("[+] Template \(template.identifier) frozen at \(template.url.path)")return template} catch {- print("[-] Template build failed; left at \(build.stagingURL.path). "- + "Remove it with: vphone-cli vm template delete \(build.stagingURL.lastPathComponent)")+ print("[-] Template build failed; left at \(build.stagingURL.path).")+ if error is VPhoneTemplateSetupFailure {+ print(" Retry its setup boot with: vphone-cli vm template setup \(build.stagingURL.lastPathComponent)")+ }+ print(" Remove it with: vphone-cli vm template delete \(build.stagingURL.lastPathComponent)")throw error}}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineTemplateCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineTemplateCommand.swiftindex e6597c7f..ec6b1f95 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineTemplateCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineTemplateCommand.swift@@ -21,11 +21,14 @@ struct VPhoneVirtualMachineTemplateCommand: ParsableCommand {Data volume. Create a machine with --no-template when it needs keys of its own.A template is never listed by vm list and cannot be booted: a boot would write state \- every later clone inherits.+ every later clone inherits. Before it is frozen it gets one setup boot (vm template setup): \+ Setup skipped, first-boot work finished, system apps and services slimmed, then a clean \+ shutdown, so every clone starts at the Lock Screen.""",subcommands: [VPhoneVirtualMachineTemplateListCommand.self,VPhoneVirtualMachineTemplateShowCommand.self,+ VPhoneVirtualMachineTemplateSetupCommand.self,VPhoneVirtualMachineTemplateAdoptCommand.self,VPhoneVirtualMachineTemplateDeleteCommand.self,],@@ -150,8 +153,10 @@ struct VPhoneVirtualMachineTemplateShowCommand: ParsableCommand {print("bundle: series \(key.bundleSeries), boot chain \(report.bootChainBundleVersion ?? "unknown"), "+ "built with \(report.builtWithBundleVersion ?? "unknown")")print("disk: \(key.diskSizeGB) GB")- print("trim: \(key.slimming.trimTier), setup boot \(key.slimming.setupBoot ? "yes" : "no"), "- + "services \(key.slimming.serviceProfile), removed apps \(key.slimming.removedApps.isEmpty ? "none" : key.slimming.removedApps.joined(separator: ","))")+ print("slimming: \(key.slimming.summary)")+ if !key.slimming.removedApps.isEmpty {+ print("removed: \(key.slimming.removedApps.joined(separator: ","))")+ }print("steps: snapshot deleted \(report.steps.snapshotDeleted ? "yes" : "no"), setup done \(report.steps.setupDone ? "yes" : "no")")print("created: \(report.created.formatted(.iso8601))")if let source = report.sourceMachine {@@ -164,6 +169,123 @@ struct VPhoneVirtualMachineTemplateShowCommand: ParsableCommand {}}+// MARK: - setup++struct VPhoneVirtualMachineTemplateSetupCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "setup",+ abstract: "Boot a VM (or an unfinished template build) once to finish it as a template",+ discussion: """+ Boots the target once without a window and, through vphoned, in this order: deletes the \+ orig-fs APFS snapshot CFW install left, skips Setup Assistant, waits for first-boot work \+ to settle, removes the system apps, applies the service profile (its sign-in follow-up \+ group included), reboots, checks the result (no snapshot, Setup done, no profile service \+ running, the apps gone, vphoned answering), clears the device name the boot pinned and \+ shuts the guest down cleanly. Every step has a deadline; a failed step stops the VM and \+ records nothing.++ A VM: stop it first (a machine Launchpad created sits at Setup after its first boot; that \+ is fine). Then vm template adopt <name> freezes it with what this recorded. An app that \+ will not go is reported and left out of the template's key.++ A .building-… name from vm template list: a vm create whose template build failed. Its \+ key fixes the slimming, so switches that disagree are refused, every app must go, and on \+ success the template is frozen and vm create uses it.++ Slimming: --slim off skips the app removal and the service profile; the setup boot still \+ skips Setup and deletes the snapshot.+ """,+ )++ @OptionGroup var lib: VPhoneLibraryOption+ @Argument(help: "VM name, or a .building-… name from vm template list") var target: String+ @OptionGroup var slimming: VPhoneTemplateSlimmingOptions+ @Flag(help: "Show the VM window while it boots") var window = false+ @Flag(name: .customShort("v"), help: "Increase verbosity: -vvv internal trace")+ var verboseCount: Int++ func run() throws {+ let library = lib.library+ let resources = VPhoneResources.resolve()+ let verbosity = VPhoneVerbosity(count: verboseCount)+ if target.hasPrefix(".building-") {+ try finishBuild(in: library, resources: resources, verbosity: verbosity)+ } else {+ try setUpMachine(in: library, resources: resources, verbosity: verbosity)+ }+ }++ /// A machine of the library, to be adopted afterwards.+ private func setUpMachine(in library: VPhoneLibrary, resources: VPhoneResources, verbosity: VPhoneVerbosity) throws {+ let bundle = try library.bundle(named: target)+ try VPhoneMachineTemplates.requireBootable(bundleURL: bundle.url)+ try VPhoneBundleActivity.requireStopped(bundle)+ let wanted = try slimming.resolve()+ if wanted.trimTier != "none" {+ throw ValidationError("--trim applies to vm create: files are trimmed during its cfw install, before the setup boot.")+ }+ // Checked before booting: a machine adopt would refuse is not worth it.+ let recorded = try VPhoneMachineTemplateKeys.recorded(bundle)+ if let snapshots = try? VPhoneMachineSnapshots.list(of: bundle), !snapshots.isEmpty {+ print("warning: \(target) has \(snapshots.count) snapshot(s); vm template adopt refuses it until they are deleted")+ }+ if try VPhoneMachineTemplates.readRecord(inBundle: bundle.url) == nil {+ try VPhoneMachineTemplates.writeRecord(+ VPhoneMachineTemplateRecord(+ key: recorded.key,+ builtWithBundleVersion: VPhoneBundleVersion.current(),+ bootChainBundleVersion: recorded.bootChainBundleVersion,+ sourceMachine: target,+ ),+ inBundle: bundle.url,+ )+ }+ try VPhoneTemplateSetupRun.run(+ bundleURL: bundle.url,+ plan: VPhoneTemplateSetupPlan(slimming: wanted, requiresEveryApp: false),+ launcher: VPhoneHostPreflight.check(),+ resources: resources,+ headless: !window,+ verbosity: verbosity,+ )+ print("freeze it into a template with: vphone-cli vm template adopt \(target)")+ }++ /// An unfinished template build: set up to its key, then frozen.+ private func finishBuild(in library: VPhoneLibrary, resources: VPhoneResources, verbosity: VPhoneVerbosity) throws {+ guard let staging = try VPhoneMachineTemplates.list(in: library).staging.first(where: { $0.name == target }),+ let identifier = staging.identifier+ else {+ throw VPhoneMachineTemplateError.notFound(target)+ }+ let lock = try VPhoneMachineTemplates.lock(identifier, in: library, wait: false)+ defer { lock.release() }+ let build = VPhoneMachineTemplateBuild(identifier: identifier, stagingURL: staging.url)+ guard let record = try VPhoneMachineTemplates.readRecord(inBundle: build.bundleURL) else {+ throw VPhoneMachineTemplateError.notBeingBuilt(path: build.bundleURL.path)+ }+ let request = try slimming.request+ if !request.isEmpty {+ let wanted = try slimming.resolve()+ guard wanted == record.key.slimming else {+ throw ValidationError("\(target) is built to its key: \(record.key.slimming.summary). Leave the slimming switches out.")+ }+ }+ if !record.steps.setupDone {+ try VPhoneTemplateSetupRun.run(+ bundleURL: build.bundleURL,+ plan: VPhoneTemplateSetupPlan(slimming: record.key.slimming, requiresEveryApp: true),+ launcher: VPhoneHostPreflight.check(),+ resources: resources,+ headless: !window,+ verbosity: verbosity,+ )+ }+ let template = try VPhoneTemplateBuildFinisher.freeze(build, key: record.key)+ print("[+] Template \(template.identifier) frozen at \(template.url.path)")+ }+}+// MARK: - adoptstruct VPhoneVirtualMachineTemplateAdoptCommand: ParsableCommand {diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swiftindex 3f86a5d0..df9fc73c 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swift@@ -1,6 +1,7 @@import AppKitimport Foundationimport ImageIO+import VPhoneCoreKit// MARK: - Host Control Socket@@ -109,28 +110,32 @@ class VPhoneHostAutomationServer {return}- var addr = sockaddr_un()- addr.sun_family = sa_family_t(AF_UNIX)- let pathBytes = socketPath.utf8CString- guard pathBytes.count <= MemoryLayout.size(ofValue: addr.sun_path) else {- print("[hostctl] socket path too long")- close(fd)- return- }- withUnsafeMutablePointer(to: &addr.sun_path) { ptr in- ptr.withMemoryRebound(to: CChar.self, capacity: pathBytes.count) { dst in- for (i, byte) in pathBytes.enumerated() {- dst[i] = byte+ // A machine deep in the library (a template being built) has a path+ // longer than sun_path; it is bound through a short link to its folder.+ let bindResult: Int32? = VPhoneUnixSocket.withAddressablePath(socketPath) { path in+ var addr = sockaddr_un()+ addr.sun_family = sa_family_t(AF_UNIX)+ let pathBytes = path.utf8CString+ guard pathBytes.count <= MemoryLayout.size(ofValue: addr.sun_path) else { return nil }+ withUnsafeMutablePointer(to: &addr.sun_path) { ptr in+ ptr.withMemoryRebound(to: CChar.self, capacity: pathBytes.count) { dst in+ for (i, byte) in pathBytes.enumerated() {+ dst[i] = byte+ }}}- }-- let addrLen = socklen_t(MemoryLayout<sockaddr_un>.size)- let bindResult = withUnsafePointer(to: &addr) { ptr in- ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockPtr in- bind(fd, sockPtr, addrLen)+ let addrLen = socklen_t(MemoryLayout<sockaddr_un>.size)+ return withUnsafePointer(to: &addr) { ptr in+ ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockPtr in+ bind(fd, sockPtr, addrLen)+ }}}+ guard let bindResult else {+ print("[hostctl] socket path too long")+ close(fd)+ return+ }guard bindResult == 0 else {print("[hostctl] bind failed: \(String(cString: strerror(errno)))")close(fd)diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineTemplateKey.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineTemplateKey.swiftindex 6f60a932..b774ca40 100644--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineTemplateKey.swift+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineTemplateKey.swift@@ -7,9 +7,10 @@ import Foundation/// key: a machine cloned from a trimmed template cannot get the files back,/// and one cloned from an untrimmed template does not lose them.///-/// Every field has a "nothing done" value, which is all this version builds.-/// Offline file trimming (`trimTier`) and the setup boot (`setupBoot`,-/// `serviceProfile`, `removedApps`) record their work here once they exist.+/// Every field has a "nothing done" value. Offline file trimming records+/// `trimTier`; the setup boot records `setupBoot`, `serviceProfile`,+/// `serviceGroups` and `removedApps` (see `VPhoneTemplateSetupBoot`). What a+/// `vm create` asks for comes from its switches (`VPhoneTemplateSlimmingRequest`).public struct VPhoneMachineTemplateSlimming: Codable, Equatable, Hashable, Sendable {/// The file-trimming tier applied to the System volume: `none`,/// `conservative`, `standard` or `aggressive`.@@ -20,16 +21,26 @@ public struct VPhoneMachineTemplateSlimming: Codable, Equatable, Hashable, Senda/// The vphoned service profile applied during the setup boot: `none` or/// `trimmed`.public var serviceProfile: String+ /// Optional service groups applied on top of the profile's defaults+ /// (`accounts` for `--accounts-off`), sorted. Empty with profile `none`.+ public var serviceGroups: [String]/// Bundle identifiers of the system apps removed during the setup boot,/// sorted.public var removedApps: [String]public static let none = VPhoneMachineTemplateSlimming()- public init(trimTier: String = "none", setupBoot: Bool = false, serviceProfile: String = "none", removedApps: [String] = []) {+ public init(+ trimTier: String = "none",+ setupBoot: Bool = false,+ serviceProfile: String = "none",+ serviceGroups: [String] = [],+ removedApps: [String] = [],+ ) {self.trimTier = trimTierself.setupBoot = setupBootself.serviceProfile = serviceProfile+ self.serviceGroups = Array(Set(serviceGroups)).sorted()self.removedApps = Array(Set(removedApps)).sorted()}@@ -37,8 +48,31 @@ public struct VPhoneMachineTemplateSlimming: Codable, Equatable, Hashable, Sendacase trimTier = "TrimTier"case setupBoot = "SetupBoot"case serviceProfile = "ServiceProfile"+ case serviceGroups = "ServiceGroups"case removedApps = "RemovedApps"}++ /// One phrase for listings: `trim none, setup boot, services trimmed+accounts, 10 apps removed`.+ public var summary: String {+ var services = serviceProfile+ if !serviceGroups.isEmpty {+ services += "+" + serviceGroups.joined(separator: "+")+ }+ return "trim \(trimTier), \(setupBoot ? "setup boot" : "no setup boot"), services \(services), "+ + "\(removedApps.count) apps removed"+ }++ /// A key of format 1 has no `ServiceGroups`; it reads as none.+ public init(from decoder: any Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ try self.init(+ trimTier: container.decode(String.self, forKey: .trimTier),+ setupBoot: container.decode(Bool.self, forKey: .setupBoot),+ serviceProfile: container.decode(String.self, forKey: .serviceProfile),+ serviceGroups: container.decodeIfPresent([String].self, forKey: .serviceGroups) ?? [],+ removedApps: container.decode([String].self, forKey: .removedApps),+ )+ }}// MARK: - Key@@ -60,7 +94,10 @@ public struct VPhoneMachineTemplateSlimming: Codable, Equatable, Hashable, Sendapublic struct VPhoneMachineTemplateKey: Codable, Equatable, Hashable, Sendable {/// Raised whenever a field is added or its meaning changes, so templates/// keyed by an older rule are never matched by a newer one.- public static let currentFormatVersion = 1+ ///+ /// - 1: the first templates (nothing slimmed, never booted).+ /// - 2: `slimming.serviceGroups`; a create now asks for a setup boot.+ public static let currentFormatVersion = 2public var formatVersion: Int/// The guest device's product type, as `fw prepare` picked it.@@ -122,6 +159,7 @@ public struct VPhoneMachineTemplateKey: Codable, Equatable, Hashable, Sendable {"trim=\(slimming.trimTier)","setup=\(slimming.setupBoot ? 1 : 0)","services=\(slimming.serviceProfile)",+ "service-groups=\(slimming.serviceGroups.sorted().joined(separator: ","))","removed-apps=\(slimming.removedApps.sorted().joined(separator: ","))",].joined(separator: "\n")}@@ -189,6 +227,11 @@ public struct VPhoneMachineTemplateKey: Codable, Equatable, Hashable, Sendable {compare("trim tier", slimming.trimTier, other.slimming.trimTier)compare("setup boot", slimming.setupBoot ? "yes" : "no", other.slimming.setupBoot ? "yes" : "no")compare("service profile", slimming.serviceProfile, other.slimming.serviceProfile)+ compare(+ "service groups",+ slimming.serviceGroups.joined(separator: ",").ifEmpty("none"),+ other.slimming.serviceGroups.joined(separator: ",").ifEmpty("none"),+ )compare("removed apps",slimming.removedApps.joined(separator: ",").ifEmpty("none"),@@ -200,7 +243,7 @@ public struct VPhoneMachineTemplateKey: Codable, Equatable, Hashable, Sendable {/// One line for listings.public var summary: String {"\(device) iOS \(iOSVersion) (\(iOSBuild)) / cloudOS \(cloudOSVersion) (\(cloudOSBuild)), "- + "\(patchPreset), \(diskSizeGB) GB, bundle \(bundleSeries), trim \(slimming.trimTier)"+ + "\(patchPreset), \(diskSizeGB) GB, bundle \(bundleSeries), \(slimming.summary)"}// MARK: Coding@@ -232,11 +275,19 @@ public struct VPhoneMachineTemplateRequest: Equatable, Sendable {public var device: String?public var patchPreset: String?public var diskSizeGB: UInt64?+ /// The slimming the switches ask for, when any slimming switch was given.+ public var slimming: VPhoneMachineTemplateSlimming?- public init(device: String? = nil, patchPreset: String? = nil, diskSizeGB: UInt64? = nil) {+ public init(+ device: String? = nil,+ patchPreset: String? = nil,+ diskSizeGB: UInt64? = nil,+ slimming: VPhoneMachineTemplateSlimming? = nil,+ ) {self.device = deviceself.patchPreset = patchPresetself.diskSizeGB = diskSizeGB+ self.slimming = slimming}/// Each option that asks for something the template does not have, as a@@ -252,6 +303,9 @@ public struct VPhoneMachineTemplateRequest: Equatable, Sendable {if let diskSizeGB, diskSizeGB != key.diskSizeGB {lines.append("--disk-size \(diskSizeGB): the template's disk is \(key.diskSizeGB) GB, fixed by its restore")}+ if let slimming, slimming != key.slimming {+ lines.append("the slimming switches ask for \(slimming.summary); the template has \(key.slimming.summary)")+ }return lines}}diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineTemplates.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineTemplates.swiftindex 967eea6d..1e9071f9 100644--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineTemplates.swift+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineTemplates.swift@@ -17,6 +17,7 @@ public struct VPhoneMachineTemplateSteps: Codable, Equatable, Sendable {/// down cleanly.public var setupDone: Boolpublic var serviceProfile: String+ public var serviceGroups: [String]public var removedApps: [String]public var trimTier: String@@ -24,12 +25,14 @@ public struct VPhoneMachineTemplateSteps: Codable, Equatable, Sendable {snapshotDeleted: Bool = false,setupDone: Bool = false,serviceProfile: String = "none",+ serviceGroups: [String] = [],removedApps: [String] = [],trimTier: String = "none",) {self.snapshotDeleted = snapshotDeletedself.setupDone = setupDoneself.serviceProfile = serviceProfile+ self.serviceGroups = Array(Set(serviceGroups)).sorted()self.removedApps = Array(Set(removedApps)).sorted()self.trimTier = trimTier}@@ -40,6 +43,7 @@ public struct VPhoneMachineTemplateSteps: Codable, Equatable, Sendable {trimTier: trimTier,setupBoot: setupDone,serviceProfile: serviceProfile,+ serviceGroups: serviceGroups,removedApps: removedApps,)}@@ -48,6 +52,7 @@ public struct VPhoneMachineTemplateSteps: Codable, Equatable, Sendable {case snapshotDeleted = "SnapshotDeleted"case setupDone = "SetupDone"case serviceProfile = "ServiceProfile"+ case serviceGroups = "ServiceGroups"case removedApps = "RemovedApps"case trimTier = "TrimTier"}@@ -57,6 +62,7 @@ public struct VPhoneMachineTemplateSteps: Codable, Equatable, Sendable {snapshotDeleted = try container.decodeIfPresent(Bool.self, forKey: .snapshotDeleted) ?? falsesetupDone = try container.decodeIfPresent(Bool.self, forKey: .setupDone) ?? falseserviceProfile = try container.decodeIfPresent(String.self, forKey: .serviceProfile) ?? "none"+ serviceGroups = try container.decodeIfPresent([String].self, forKey: .serviceGroups) ?? []removedApps = try container.decodeIfPresent([String].self, forKey: .removedApps) ?? []trimTier = try container.decodeIfPresent(String.self, forKey: .trimTier) ?? "none"}@@ -227,6 +233,11 @@ public struct VPhoneMachineTemplateBuild: Sendable {public let identifier: String/// `.templates/.building-<identifier>-<uuid>`.public let stagingURL: URL++ public init(identifier: String, stagingURL: URL) {+ self.identifier = identifier+ self.stagingURL = stagingURL+ }/// The library the machine folder is created in: the staging folder.public var library: VPhoneLibrary {VPhoneLibrary(root: stagingURL)diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneTemplateSetupBoot.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneTemplateSetupBoot.swiftnew file mode 100644index 00000000..a7f7ec82--- /dev/null+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneTemplateSetupBoot.swift@@ -0,0 +1,697 @@+import Foundation++// MARK: - Machine++/// A refused or undelivered vphoned call, as the setup boot sees it.+public struct VPhoneGuestCallError: Error, CustomStringConvertible, Sendable {+ public enum Kind: Sendable {+ /// The request did not reach vphoned or its answer did not come back:+ /// no control socket, the guest not connected, a timeout.+ case transport+ /// vphoned answered with an error object.+ case refused+ }++ public var kind: Kind+ public var message: String+ /// vphoned's error object (`guest_error` on `vphone.sock`), as JSON.+ public var detailJSON: String?++ public init(kind: Kind, message: String, detail: [String: Any]? = nil) {+ self.kind = kind+ self.message = message+ detailJSON = detail.flatMap { try? JSONSerialization.data(withJSONObject: $0) }+ .map { String(decoding: $0, as: UTF8.self) }+ }++ public var detail: [String: Any]? {+ detailJSON.flatMap { try? JSONSerialization.jsonObject(with: Data($0.utf8)) as? [String: Any] }+ }++ public var code: String? {+ detail?["code"] as? String+ }++ /// Worth asking again: the guest was not reachable, or vphoned said the+ /// operation may succeed later (`retryable`, `reason: busy`).+ public var isRetryable: Bool {+ switch kind {+ case .transport:+ return true+ case .refused:+ let detail = detail+ return detail?["retryable"] as? Bool == true || detail?["reason"] as? String == "busy"+ }+ }++ public var description: String {+ message+ }+}++/// The VM a setup boot drives. `VPhoneCommand` implements it over+/// `vphone-vm` and its `vphone.sock`; tests implement it with a scripted+/// guest.+public protocol VPhoneTemplateSetupMachine: AnyObject {+ /// Starts the VM process. Refuses a frozen template.+ func start() throws+ /// Why the VM can no longer serve the setup boot (its process exited, the+ /// guest panicked), or nil while it runs.+ func failure() -> String?+ /// Whether vphoned answers through the VM's control socket.+ func ping() -> Bool+ /// One vphoned method. Throws ``VPhoneGuestCallError``.+ func call(_ method: String, params: [String: Any], timeout: TimeInterval) throws -> [String: Any]+ /// Asks the guest to shut down and waits for the VM process to exit.+ /// True when it shut down cleanly within `timeout`; false when it had to+ /// be turned off or is still running (it is then killed).+ func stop(timeout: TimeInterval) -> Bool+ /// Ends the VM process at once, after a failure.+ func kill()+}++public protocol VPhoneTemplateSetupClock {+ func now() -> Date+ func sleep(_ seconds: TimeInterval)+}++public struct VPhoneSystemClock: VPhoneTemplateSetupClock {+ public init() {}++ public func now() -> Date {+ Date()+ }++ public func sleep(_ seconds: TimeInterval) {+ Thread.sleep(forTimeInterval: seconds)+ }+}++// MARK: - Plan++/// How long each step of a setup boot may take. Every step has a deadline;+/// a step that misses it fails the setup boot.+public struct VPhoneTemplateSetupTimeouts: Equatable, Sendable {+ /// From the VM start until vphoned answers. A first boot reaches it in a+ /// few seconds; the first-boot check of `vm create` allows 300.+ public var connect: TimeInterval = 300+ public var snapshot: TimeInterval = 120+ public var skipSetup: TimeInterval = 120+ /// Overall, across `setup.settle` calls of at most 110 s each. P0 saw+ /// 92 s after `setup.skip` on a guest whose apps were already expanded.+ public var settle: TimeInterval = 600+ public var removeApps: TimeInterval = 300+ public var serviceProfile: TimeInterval = 180+ /// From `system.reboot` until vphoned of the new boot answers (P1: 20 s).+ public var reboot: TimeInterval = 300+ public var verify: TimeInterval = 120+ public var deviceName: TimeInterval = 30+ /// The VM gives the guest 15 s to shut down before turning it off.+ public var stop: TimeInterval = 60+ /// Between attempts of a retryable call.+ public var retryInterval: TimeInterval = 3+ /// Between polls of the control socket.+ public var pollInterval: TimeInterval = 1++ public init() {}++ public static let standard = VPhoneTemplateSetupTimeouts()+}++/// What a setup boot does to the guest, from the slimming a template's key+/// promises (or the switches of `vm template setup`).+public struct VPhoneTemplateSetupPlan: Equatable, Sendable {+ public var serviceProfile: String+ public var serviceGroups: [String]+ public var removedApps: [String]+ /// Whether an app vphoned does not remove fails the setup boot. A template+ /// being built has its key, and with it the apps it promises, fixed; a+ /// machine to be adopted afterwards gets a key from what was done.+ public var requiresEveryApp: Bool+ /// Clear the device name `vphone-vm` pinned during this boot, so a clone+ /// does not show the template's name before its own VM pins its name.+ public var clearsDeviceName: Bool+ public var timeouts: VPhoneTemplateSetupTimeouts++ public init(+ slimming: VPhoneMachineTemplateSlimming,+ requiresEveryApp: Bool,+ clearsDeviceName: Bool = true,+ timeouts: VPhoneTemplateSetupTimeouts = .standard,+ ) {+ serviceProfile = slimming.serviceProfile+ serviceGroups = slimming.serviceGroups+ removedApps = slimming.removedApps+ self.requiresEveryApp = requiresEveryApp+ self.clearsDeviceName = clearsDeviceName+ self.timeouts = timeouts+ }+}++// MARK: - Steps and outcome++/// The steps of a setup boot, in the order they run. The order is fixed:+/// the snapshot goes before anything writes to the System volume's blocks+/// again; Setup is skipped before first-boot work is waited for; apps are+/// removed only after installd expanded them; the profile (with the sign-in+/// follow-up group) comes after first-boot work, and a reboot makes launchd+/// honor it before the result is checked.+public enum VPhoneTemplateSetupStep: String, CaseIterable, Sendable, CustomStringConvertible {+ case boot+ case connect+ case snapshot+ case skipSetup = "setup-skip"+ case settle+ case removeApps = "remove-apps"+ case serviceProfile = "service-profile"+ case reboot+ case verify+ case deviceName = "device-name"+ case stop++ public var description: String {+ switch self {+ case .boot: "start the VM"+ case .connect: "wait for vphoned"+ case .snapshot: "0. delete the orig-fs snapshot"+ case .skipSetup: "a. skip Setup Assistant"+ case .settle: "b. wait for first-boot work"+ case .removeApps: "c. remove system apps"+ case .serviceProfile: "d/e. apply the service profile"+ case .reboot: "f. reboot"+ case .verify: "f. verify after the reboot"+ case .deviceName: "clear the pinned device name"+ case .stop: "g. shut down"+ }+ }+}++public struct VPhoneTemplateSetupAppResult: Equatable, Sendable {+ public var bundleID: String+ /// vphoned's status: `removed`, `absent`, `unregistered_stale` or `failed`.+ public var status: String+ public var error: String?++ public init(bundleID: String, status: String, error: String? = nil) {+ self.bundleID = bundleID+ self.status = status+ self.error = error+ }++ /// The app is not installed afterwards, whichever way.+ public var isGone: Bool {+ ["removed", "absent", "unregistered_stale"].contains(status)+ }+}++public struct VPhoneTemplateSetupOutcome: Equatable, Sendable {+ public var deletedSnapshots: [String] = []+ /// No `orig-fs.disabled.rn-*` snapshot is left (deleted now or before).+ public var snapshotsGone = false+ public var setupSkipped = false+ public var settled = false+ public var apps: [VPhoneTemplateSetupAppResult] = []+ public var serviceProfile = "none"+ public var serviceGroups: [String] = []+ /// Labels the profile owns after it was applied.+ public var servicesOwned = 0+ public var verified = false+ public var deviceNameCleared = false+ public var stoppedCleanly = false+ public var durations: [VPhoneTemplateSetupStep: TimeInterval] = [:]+ public var warnings: [String] = []++ public init() {}++ public var removedApps: [String] {+ apps.filter(\.isGone).map(\.bundleID).sorted()+ }++ /// Every step ran and the VM shut down cleanly.+ public var isComplete: Bool {+ snapshotsGone && setupSkipped && settled && verified && stoppedCleanly+ }++ /// The steps a template records.+ public func applying(to steps: VPhoneMachineTemplateSteps) -> VPhoneMachineTemplateSteps {+ var steps = steps+ steps.snapshotDeleted = snapshotsGone+ steps.setupDone = isComplete+ steps.serviceProfile = serviceProfile+ steps.serviceGroups = serviceGroups.sorted()+ steps.removedApps = removedApps+ return steps+ }+}++public struct VPhoneTemplateSetupFailure: Error, CustomStringConvertible, LocalizedError {+ public var step: VPhoneTemplateSetupStep+ public var reason: String+ public var outcome: VPhoneTemplateSetupOutcome++ public var description: String {+ "Setup boot failed at step \(step.rawValue) (\(step)): \(reason)"+ }++ public var errorDescription: String? {+ description+ }+}++// MARK: - Setup boot++/// Boots a template (or a machine about to be adopted as one) once and+/// finishes it the way every clone should start: Setup skipped, first-boot+/// work done, the system apps and services the key promises removed and+/// turned off, the `orig-fs` snapshot deleted. Then it reboots, checks the+/// result and shuts down.+///+/// A step that fails stops the run: the VM is killed, the failure names the+/// step, and the caller records nothing, so a template build is never frozen+/// from a failed setup boot. Calls vphoned marks retryable (or that did not+/// reach it) are repeated until the step's deadline.+public final class VPhoneTemplateSetupBoot {+ public static let snapshotPrefix = "orig-fs.disabled.rn-"+ /// The sign-in follow-up group the trimmed profile includes by default+ /// (step e), and the labels it must have turned off.+ public static let signInFollowUpGroup = "signin_followup"+ public static let signInFollowUpLabels = ["com.apple.appleidsetupd", "com.apple.followupd"]+ /// `setup.settle` answers within 110 s; the host waits at most 120 s.+ static let settleCallLimit = 110++ private let machine: VPhoneTemplateSetupMachine+ private let plan: VPhoneTemplateSetupPlan+ private let clock: VPhoneTemplateSetupClock+ private let log: (String) -> Void+ private var outcome = VPhoneTemplateSetupOutcome()+ private var timeouts: VPhoneTemplateSetupTimeouts {+ plan.timeouts+ }++ public init(+ machine: VPhoneTemplateSetupMachine,+ plan: VPhoneTemplateSetupPlan,+ clock: VPhoneTemplateSetupClock = VPhoneSystemClock(),+ log: @escaping (String) -> Void = { print($0) },+ ) {+ self.machine = machine+ self.plan = plan+ self.clock = clock+ self.log = log+ }++ /// Runs every step. Throws ``VPhoneTemplateSetupFailure``.+ public func run() throws -> VPhoneTemplateSetupOutcome {+ outcome = VPhoneTemplateSetupOutcome()+ var current = VPhoneTemplateSetupStep.boot+ var running = false+ func step(_ which: VPhoneTemplateSetupStep, _ body: () throws -> Void) throws {+ current = which+ log("[setup] \(which)")+ let start = clock.now()+ try body()+ outcome.durations[which] = clock.now().timeIntervalSince(start)+ }+ do {+ try step(.boot) {+ try machine.start()+ running = true+ }+ try step(.connect) { try waitForGuest(deadline: deadline(timeouts.connect)) }+ try step(.snapshot) { try deleteSnapshot() }+ try step(.skipSetup) { try skipSetup() }+ try step(.settle) { try settle() }+ try step(.removeApps) { try removeApps() }+ try step(.serviceProfile) { try applyServiceProfile() }+ try step(.reboot) { try reboot() }+ try step(.verify) { try verify() }+ try step(.deviceName) { clearDeviceName() }+ try step(.stop) {+ running = false+ guard machine.stop(timeout: timeouts.stop) else {+ throw StepError("the guest did not shut down cleanly within \(Int(timeouts.stop)) s; the VM was turned off")+ }+ outcome.stoppedCleanly = true+ }+ log("[setup] done")+ return outcome+ } catch {+ if running {+ machine.kill()+ }+ let reason = (error as? StepError)?.message ?? "\(error)"+ log("[setup] failed at \(current.rawValue): \(reason)")+ throw VPhoneTemplateSetupFailure(step: current, reason: reason, outcome: outcome)+ }+ }++ // MARK: Steps++ private func waitForGuest(deadline: Date) throws {+ while true {+ try checkMachine()+ if machine.ping() {+ return+ }+ guard clock.now() < deadline else {+ throw StepError("vphoned did not answer within \(Int(timeouts.connect)) s")+ }+ clock.sleep(timeouts.pollInterval)+ }+ }++ /// 0. `apfs.snapshot.delete` selects every `orig-fs.disabled.rn-*`+ /// snapshot; none there is fine (deleted before, or never made).+ private func deleteSnapshot() throws {+ let result = try call("apfs.snapshot.delete", ["force": true], deadline: deadline(timeouts.snapshot))+ outcome.deletedSnapshots = strings(result["deleted"])+ let left = (strings(result["remaining"]) + strings(result["after"])).filter { $0.hasPrefix(Self.snapshotPrefix) }+ guard left.isEmpty else {+ throw StepError("snapshots still present after deletion: \(Set(left).sorted().joined(separator: ", "))")+ }+ outcome.snapshotsGone = true+ log(outcome.deletedSnapshots.isEmpty+ ? " no orig-fs snapshot left to delete"+ : " deleted \(outcome.deletedSnapshots.joined(separator: ", "))")+ }++ /// a. `setup.skip` writes purplebuddy's keys and restarts SpringBoard.+ /// Right after vphoned first answers, SpringBoard and cfprefsd may not be+ /// up yet: on a fresh 27.0 guest it failed with "Cannot allocate memory"+ /// seconds into the boot, then for 87 s with SpringBoard's restart+ /// refused ("Requestor lacks required entitlement"). It is idempotent, so+ /// any refusal is retried until the deadline.+ private func skipSetup() throws {+ let result = try call("setup.skip", ["force": true], deadline: deadline(timeouts.skipSetup), retryingRefusals: true)+ guard result["setup_done"] as? Bool == true else {+ throw StepError("setup.skip did not report setup_done")+ }+ outcome.setupSkipped = true+ }++ /// b. `setup.settle` waits at most 110 s per call; it is called again+ /// until the overall deadline.+ private func settle() throws {+ let end = deadline(timeouts.settle)+ var reasons: [String] = []+ while true {+ let remaining = end.timeIntervalSince(clock.now())+ guard remaining > 0 else {+ throw StepError("first-boot work did not settle within \(Int(timeouts.settle)) s"+ + (reasons.isEmpty ? "" : ": \(reasons.joined(separator: "; "))"))+ }+ let wait = Int(min(Double(Self.settleCallLimit), max(10, remaining.rounded(.up))))+ let result = try call("setup.settle", ["timeout_s": wait], deadline: end, timeout: Double(wait) + 20)+ if result["settled"] as? Bool == true {+ outcome.settled = true+ log(" settled after \(result["elapsed_s"].map { "\($0)" } ?? "?") s")+ return+ }+ reasons = strings(result["reasons"])+ log(" not settled yet: \(reasons.joined(separator: "; "))")+ }+ }++ /// c. `apps.remove_system` backs each container up, unregisters it and+ /// removes it, then resprings once.+ private func removeApps() throws {+ guard !plan.removedApps.isEmpty else {+ log(" nothing to remove")+ return+ }+ let params: [String: Any] = ["bundle_ids": plan.removedApps, "force": true]+ var rows: [[String: Any]]+ do {+ let result = try call("apps.remove_system", params, deadline: deadline(timeouts.removeApps), timeout: 240)+ rows = result["results"] as? [[String: Any]] ?? []+ } catch let error as VPhoneGuestCallError where error.detail?["results"] != nil {+ // `remove_incomplete`: the same results, with at least one failed.+ rows = error.detail?["results"] as? [[String: Any]] ?? []+ }+ var results = rows.compactMap { row -> VPhoneTemplateSetupAppResult? in+ guard let id = row["bundle_id"] as? String else { return nil }+ return VPhoneTemplateSetupAppResult(bundleID: id, status: row["status"] as? String ?? "failed", error: row["error"] as? String)+ }+ for id in plan.removedApps where !results.contains(where: { $0.bundleID == id }) {+ results.append(VPhoneTemplateSetupAppResult(bundleID: id, status: "failed", error: "vphoned returned no result for it"))+ }+ outcome.apps = results+ let refused = results.filter { !$0.isGone }+ log(" \(results.count - refused.count) of \(results.count) apps removed or absent")+ guard !refused.isEmpty else { return }+ let lines = refused.map { "\($0.bundleID): \($0.error ?? $0.status)" }+ if plan.requiresEveryApp {+ throw StepError("vphoned did not remove \(lines.joined(separator: "; "))")+ }+ for line in lines {+ outcome.warnings.append("not removed: \(line)")+ log(" warning: not removed: \(line)")+ }+ }++ /// d. `services.profile.apply`; e. the trimmed profile includes the+ /// sign-in follow-up group, which turns off followupd and appleidsetupd.+ private func applyServiceProfile() throws {+ let end = deadline(timeouts.serviceProfile)+ if plan.serviceProfile == "none" {+ // Undo a profile only when one is recorded; a fresh guest has none.+ let state = try call("services.profile", [:], deadline: end)+ if state["profile"] as? String ?? "none" != "none" {+ try requireApplied(call("services.profile.apply", ["profile": "none", "force": true], deadline: end))+ }+ outcome.serviceProfile = "none"+ outcome.serviceGroups = []+ log(" service profile none")+ return+ }+ let applied = try call(+ "services.profile.apply",+ ["profile": plan.serviceProfile, "groups": plan.serviceGroups, "force": true],+ deadline: end,+ )+ try requireApplied(applied)+ guard applied["profile"] as? String == plan.serviceProfile else {+ throw StepError("services.profile.apply answered profile \(applied["profile"] ?? "nil"), not \(plan.serviceProfile)")+ }++ let state = try call("services.profile", [:], deadline: end)+ let record = state["record"] as? [String: Any]+ let groups = Set(strings(record?["groups"]))+ let missing = ([Self.signInFollowUpGroup] + plan.serviceGroups).filter { !groups.contains($0) }+ guard missing.isEmpty else {+ throw StepError("the applied profile lacks the group(s) \(missing.joined(separator: ", "))")+ }+ let disabled = Set(strings(state["disabled"]))+ let notOff = Self.signInFollowUpLabels.filter { !disabled.contains($0) }+ guard notOff.isEmpty else {+ throw StepError("the sign-in follow-up services are not disabled: \(notOff.joined(separator: ", "))")+ }+ outcome.serviceProfile = plan.serviceProfile+ outcome.serviceGroups = plan.serviceGroups+ outcome.servicesOwned = applied["owned"] as? Int ?? disabled.count+ log(" profile \(plan.serviceProfile)\(plan.serviceGroups.isEmpty ? "" : " +\(plan.serviceGroups.joined(separator: ","))"): "+ + "\(outcome.servicesOwned) services owned, \(strings(applied["disabled"]).count) disabled now")+ }++ private func requireApplied(_ result: [String: Any]) throws {+ let failed = (result["failed"] as? [[String: Any]] ?? []).map { row in+ "\(row["label"] as? String ?? "?") (\(row["action"] as? String ?? "?"): \(row["error"] as? String ?? "?"))"+ }+ guard failed.isEmpty else {+ throw StepError("services.profile.apply could not change \(failed.joined(separator: "; "))")+ }+ }++ /// f. Reboots the guest and waits for vphoned of the next boot: launchd's+ /// start time (pid 1) tells the boots apart.+ private func reboot() throws {+ let end = deadline(timeouts.reboot)+ let before = try bootMarker(deadline: end)+ do {+ _ = try machine.call("system.reboot", params: ["force": true], timeout: 30)+ } catch let error as VPhoneGuestCallError where error.kind == .transport {+ // The guest can go down before it answers.+ }+ while true {+ try checkMachine()+ if machine.ping(), let after = try? machine.call("processes.list", params: [:], timeout: 30),+ let marker = Self.bootMarker(after), marker != before+ {+ return+ }+ guard clock.now() < end else {+ throw StepError("the guest did not come back from the reboot within \(Int(timeouts.reboot)) s")+ }+ clock.sleep(timeouts.retryInterval)+ }+ }++ private func bootMarker(deadline: Date) throws -> Double {+ let list = try call("processes.list", [:], deadline: deadline)+ guard let marker = Self.bootMarker(list) else {+ throw StepError("processes.list does not list launchd (pid 1) with a start time")+ }+ return marker+ }++ static func bootMarker(_ list: [String: Any]) -> Double? {+ let rows = list["processes"] as? [[String: Any]] ?? []+ let launchd = rows.first { number($0["pid"]) == 1 }+ return number(launchd?["start_time"])+ }++ /// A number from JSON (NSNumber) or from a dictionary built in Swift.+ private static func number(_ value: Any?) -> Double? {+ switch value {+ case let value as Int: Double(value)+ case let value as Double: value+ case let value as NSNumber: value.doubleValue+ default: nil+ }+ }++ /// f. After the reboot: no orig-fs snapshot, Setup done, the profile+ /// recorded and none of its services running, the removed apps absent,+ /// vphoned answering. Checked again until the deadline, since services+ /// started by the boot can still be winding down.+ private func verify() throws {+ let end = deadline(timeouts.verify)+ while true {+ let problems = try verificationProblems(deadline: end)+ if problems.isEmpty {+ outcome.verified = true+ log(" verified")+ return+ }+ guard clock.now().addingTimeInterval(timeouts.retryInterval) < end else {+ throw StepError(problems.joined(separator: "; "))+ }+ log(" not yet: \(problems.joined(separator: "; "))")+ clock.sleep(timeouts.retryInterval)+ }+ }++ private func verificationProblems(deadline end: Date) throws -> [String] {+ var problems: [String] = []+ let snapshots = try strings(call("apfs.snapshots", [:], deadline: end)["snapshots"])+ .filter { $0.hasPrefix(Self.snapshotPrefix) }+ if !snapshots.isEmpty {+ problems.append("snapshots left: \(snapshots.joined(separator: ", "))")+ }+ let status = try call("setup.status", [:], deadline: end)+ if status["setup_done"] as? Bool != true {+ problems.append("Setup Assistant is not done")+ }+ let profile = try call("services.profile", [:], deadline: end)+ let recorded = profile["profile"] as? String ?? "none"+ if recorded != plan.serviceProfile {+ problems.append("service profile is \(recorded), not \(plan.serviceProfile)")+ }+ let running = strings(profile["running"])+ if !running.isEmpty {+ problems.append("\(running.count) profile service(s) still running: \(running.prefix(5).joined(separator: ", "))")+ }+ let removed = Set(outcome.removedApps)+ if !removed.isEmpty {+ let listed = (try call("apps.list", [:], deadline: end)["apps"] as? [[String: Any]] ?? [])+ .compactMap { $0["bundle_id"] as? String }+ let back = listed.filter { removed.contains($0) }+ if !back.isEmpty {+ problems.append("removed apps are installed again: \(back.sorted().joined(separator: ", "))")+ }+ }+ if !machine.ping() {+ problems.append("vphoned does not answer a ping")+ }+ return problems+ }++ /// `vphone-vm` pinned the device name to this machine's name on connect.+ /// A clone would carry that pin until its own VM pins its name, so the+ /// pin goes; the guest's own name (`iPhone`) shows in between.+ private func clearDeviceName() {+ guard plan.clearsDeviceName else { return }+ do {+ _ = try call("device.name.set", [:], deadline: deadline(timeouts.deviceName))+ outcome.deviceNameCleared = true+ } catch {+ outcome.warnings.append("could not clear the pinned device name: \(error)")+ log(" warning: could not clear the pinned device name: \(error)")+ }+ }++ // MARK: Calls++ private struct StepError: Error, CustomStringConvertible {+ let message: String++ init(_ message: String) {+ self.message = message+ }++ var description: String {+ message+ }+ }++ private func deadline(_ seconds: TimeInterval) -> Date {+ clock.now().addingTimeInterval(seconds)+ }++ private func checkMachine() throws {+ if let reason = machine.failure() {+ throw StepError(reason)+ }+ }++ /// One method, repeated while it fails in a way worth retrying and the+ /// deadline allows. Any other refusal is thrown as it came.+ private func call(+ _ method: String,+ _ params: [String: Any],+ deadline: Date,+ timeout: TimeInterval = 60,+ retryingRefusals: Bool = false,+ ) throws -> [String: Any] {+ var attempts = 0+ while true {+ try checkMachine()+ do {+ return try machine.call(method, params: params, timeout: timeout)+ } catch let error as VPhoneGuestCallError where error.isRetryable || retryingRefusals {+ attempts += 1+ guard clock.now().addingTimeInterval(timeouts.retryInterval) < deadline else {+ throw StepError("\(method): \(error.message) (\(attempts) attempt(s))")+ }+ log(" \(method): \(error.message); retrying")+ clock.sleep(timeouts.retryInterval)+ } catch let error as VPhoneGuestCallError {+ // Kept whole for a caller that reads its detail.+ if error.detail?["results"] != nil {+ throw error+ }+ throw StepError("\(method): \(error.message)\(error.code.map { " (\($0))" } ?? "")")+ }+ }+ }++ private func strings(_ value: Any?) -> [String] {+ value as? [String] ?? []+ }+}++// MARK: - Recording++public extension VPhoneMachineTemplates {+ /// Records a finished setup boot in the template record of the machine+ /// at `url`. Only a complete outcome is recorded: a failed setup boot+ /// leaves the record as it was, so the build is never frozen from it.+ static func recordSetupBoot(_ outcome: VPhoneTemplateSetupOutcome, inBundle url: URL) throws {+ guard outcome.isComplete else {+ throw VPhoneMachineTemplateError.failed(path: url.path, reason: "the setup boot did not finish, so nothing was recorded")+ }+ try recordSteps(inBundle: url) { steps in+ steps = outcome.applying(to: steps)+ }+ }+}diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneTemplateSlimmingRequest.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneTemplateSlimmingRequest.swiftnew file mode 100644index 00000000..eeac4101--- /dev/null+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneTemplateSlimmingRequest.swift@@ -0,0 +1,150 @@+import Foundation++// MARK: - Slimming request++/// The slimming switches of `vm create` and `vm template setup`, turned into+/// the slimming a template's key promises.+///+/// `--slim off` turns every slimming switch off: no file trim, no service+/// profile, no app removal. The setup boot still runs, because skipping Setup+/// Assistant and waiting for first-boot work are not slimming: every clone+/// would otherwise start at the Setup screen and redo that work on its own+/// disk. A nil field was not given and takes its default.+public struct VPhoneTemplateSlimmingRequest: Equatable, Sendable {+ /// `--slim on|off`; nil is on.+ public var slim: Bool?+ /// `--trim none|conservative|standard|aggressive` (offline file trim);+ /// nil is ``defaultTrimTier`` when slimming.+ public var trimTier: String?+ /// `--service-profile none|trimmed`; nil is trimmed when slimming.+ public var serviceProfile: String?+ /// `--remove-apps on|off`; nil is on when slimming.+ public var removeApps: Bool?+ /// `--keep-apps`: apps of ``defaultRemovedApps`` to keep.+ public var keepApps: [String]+ /// `--accounts-off`: also turn off the Apple Account daemons.+ public var accountsOff: Bool++ public init(+ slim: Bool? = nil,+ trimTier: String? = nil,+ serviceProfile: String? = nil,+ removeApps: Bool? = nil,+ keepApps: [String] = [],+ accountsOff: Bool = false,+ ) {+ self.slim = slim+ self.trimTier = trimTier+ self.serviceProfile = serviceProfile+ self.removeApps = removeApps+ self.keepApps = keepApps+ self.accountsOff = accountsOff+ }++ // MARK: Defaults++ /// The file-trim tier a slimmed template gets when `--trim` is not given.+ /// Offline trimming is not built yet, so it is `none`; it becomes+ /// `standard` with it.+ public static let defaultTrimTier = "none"++ public static let trimTiers = ["none", "conservative", "standard", "aggressive"]+ public static let serviceProfiles = ["none", "trimmed"]++ /// The removable system apps a slimmed template drops (list C of the+ /// template trim plan), each verified to stay removed across a respring+ /// and a reboot on iOS 27.0. Camera stays for camera passthrough checks;+ /// Phone lives on the System volume and `apps.remove_system` refuses it.+ public static let defaultRemovedApps = [+ "com.apple.AppStore",+ "com.apple.Home",+ "com.apple.tv",+ "com.apple.news",+ "com.apple.facetime",+ "com.apple.MobileStore",+ "com.apple.MobileSMS",+ "com.apple.games",+ "com.apple.findmy",+ "com.apple.Passbook",+ ]++ /// What a create without slimming switches asks for.+ public static var defaultSlimming: VPhoneMachineTemplateSlimming {+ // No switch given, so nothing can contradict another.+ (try? VPhoneTemplateSlimmingRequest().resolve()) ?? .none+ }++ /// The vphoned service group `--accounts-off` adds.+ public static let accountsGroup = "accounts"++ // MARK: Resolution++ /// Whether any switch was given; with none, a named template's own+ /// slimming is taken as it is.+ public var isEmpty: Bool {+ self == VPhoneTemplateSlimmingRequest()+ }++ /// The slimming these switches ask for, or the switches that contradict+ /// each other.+ public func resolve() throws -> VPhoneMachineTemplateSlimming {+ var problems: [String] = []+ if let trimTier, !Self.trimTiers.contains(trimTier) {+ problems.append("--trim must be one of \(Self.trimTiers.joined(separator: ", ")), not \(trimTier)")+ }+ if let serviceProfile, !Self.serviceProfiles.contains(serviceProfile) {+ problems.append("--service-profile must be none or trimmed, not \(serviceProfile)")+ }+ let unknown = keepApps.filter { !Self.defaultRemovedApps.contains($0) }+ if !unknown.isEmpty {+ problems.append(+ "--keep-apps \(unknown.joined(separator: ",")): only apps removed by default can be kept "+ + "(\(Self.defaultRemovedApps.joined(separator: ", ")))",+ )+ }++ if slim == false {+ var contradicted: [String] = []+ if let trimTier, trimTier != "none" { contradicted.append("--trim \(trimTier)") }+ if serviceProfile == "trimmed" { contradicted.append("--service-profile trimmed") }+ if removeApps == true { contradicted.append("--remove-apps on") }+ if !keepApps.isEmpty { contradicted.append("--keep-apps") }+ if accountsOff { contradicted.append("--accounts-off") }+ if !contradicted.isEmpty {+ problems.append("--slim off turns slimming off; it cannot be combined with \(contradicted.joined(separator: ", "))")+ }+ }+ let profile = slim == false ? "none" : serviceProfile ?? "trimmed"+ if accountsOff, profile != "trimmed" {+ problems.append("--accounts-off needs --service-profile trimmed")+ }+ let removes = slim == false ? false : removeApps ?? true+ if !removes, !keepApps.isEmpty, slim != false {+ problems.append("--keep-apps has nothing to keep with --remove-apps off")+ }+ guard problems.isEmpty else {+ throw VPhoneTemplateSlimmingError(problems: problems)+ }++ let keep = Set(keepApps)+ return VPhoneMachineTemplateSlimming(+ trimTier: slim == false ? "none" : trimTier ?? Self.defaultTrimTier,+ setupBoot: true,+ serviceProfile: profile,+ serviceGroups: accountsOff ? [Self.accountsGroup] : [],+ removedApps: removes ? Self.defaultRemovedApps.filter { !keep.contains($0) } : [],+ )+ }+}++public struct VPhoneTemplateSlimmingError: Error, Equatable, CustomStringConvertible, LocalizedError {+ public var problems: [String]++ public var description: String {+ problems.joined(separator: "; ")+ }++ public var errorDescription: String? {+ description+ }+}diff --git a/VPhoneKit/VPhoneCoreKit/Process/VPhoneManagedProcess.swift b/VPhoneKit/VPhoneCoreKit/Process/VPhoneManagedProcess.swiftindex 2a9c9353..914a3e89 100644--- a/VPhoneKit/VPhoneCoreKit/Process/VPhoneManagedProcess.swift+++ b/VPhoneKit/VPhoneCoreKit/Process/VPhoneManagedProcess.swift@@ -148,6 +148,27 @@ public final class VPhoneManagedProcess: @unchecked Sendable {return process.terminationStatus}+ public var isRunning: Bool {+ process.isRunning+ }++ /// Everything the child wrote so far.+ public var outputText: String {+ box.snapshotText()+ }++ /// SIGINT, then waits up to `timeout` for the child to exit on its own.+ /// True when it did; the caller decides what a child still running gets.+ public func interrupt(waitingUpTo timeout: TimeInterval) -> Bool {+ guard process.isRunning else { return true }+ process.interrupt()+ let deadline = Date().addingTimeInterval(timeout)+ while process.isRunning, Date() < deadline {+ Thread.sleep(forTimeInterval: 0.1)+ }+ return !process.isRunning+ }+/// `interrupt()` (SIGINT), then escalate to an unmaskable `SIGKILL` if/// the process is still running after a ~2 s grace period. `SIGKILL` (not/// `Process.terminate()`'s `SIGTERM`) is required here: a child thatdiff --git a/VPhoneKit/VPhoneCoreKit/Process/VPhoneUnixSocket.swift b/VPhoneKit/VPhoneCoreKit/Process/VPhoneUnixSocket.swiftindex 84701745..1d1a6e1f 100644--- a/VPhoneKit/VPhoneCoreKit/Process/VPhoneUnixSocket.swift+++ b/VPhoneKit/VPhoneCoreKit/Process/VPhoneUnixSocket.swift@@ -18,8 +18,38 @@ public enum VPhoneUnixSocket {case connect(Int32)}- /// A connected descriptor, which the caller closes.+ /// A connected descriptor, which the caller closes. A path too long for+ /// `sun_path` is reached through ``withAddressablePath(_:_:)``.public static func connect(to path: String) -> Result<Int32, ConnectError> {+ withAddressablePath(path) { connectDirectly(to: $0) }+ }++ /// The bytes `sun_path` holds, terminating NUL included.+ public static let maximumPathLength = MemoryLayout.size(ofValue: sockaddr_un().sun_path)++ /// Runs `body` with a path to the socket file at `path` that fits+ /// `sun_path`: `path` itself when it does, otherwise the same file reached+ /// through a symbolic link to its folder, in a private (0700) folder under+ /// `/tmp` that is removed afterwards. The kernel follows the link, so a+ /// socket bound or connected through it is the one at `path`. A template+ /// being built lives deep in `.templates/.building-…/`, past the 104 bytes.+ /// When no such folder can be made, `body` gets `path` and fails as before.+ public static func withAddressablePath<T>(_ path: String, _ body: (String) throws -> T) rethrows -> T {+ guard path.utf8CString.count > maximumPathLength else { return try body(path) }+ var template = Array("/tmp/vphone.XXXXXX".utf8CString)+ guard let created = mkdtemp(&template) else { return try body(path) }+ let folder = String(cString: created)+ let link = folder + "/d"+ let target = (path as NSString).deletingLastPathComponent+ defer {+ unlink(link)+ rmdir(folder)+ }+ guard symlink(target, link) == 0 else { return try body(path) }+ return try body(link + "/" + (path as NSString).lastPathComponent)+ }++ private static func connectDirectly(to path: String) -> Result<Int32, ConnectError> {let bytes = path.utf8CStringvar address = sockaddr_un()guard bytes.count <= MemoryLayout.size(ofValue: address.sun_path) else {diff --git a/VPhoneKit/VPhoneCoreKitTests/Bundle/MachineTemplateKeyTests.swift b/VPhoneKit/VPhoneCoreKitTests/Bundle/MachineTemplateKeyTests.swiftindex b6757a64..2bb23b2d 100644--- a/VPhoneKit/VPhoneCoreKitTests/Bundle/MachineTemplateKeyTests.swift+++ b/VPhoneKit/VPhoneCoreKitTests/Bundle/MachineTemplateKeyTests.swift@@ -32,7 +32,7 @@ struct MachineTemplateKeyTests {// A change here orphans every template on disk: raise currentFormatVersion instead.let key = Self.key()#expect(key.canonicalDescription == """- format=1+ format=2device=iPhone17,3ios=27.0/24A435cloudos=26.4/23E5207q@@ -43,9 +43,10 @@ struct MachineTemplateKeyTests {trim=nonesetup=0services=none+ service-groups=removed-apps=""")- #expect(key.identifier == "a5f0340ef865")+ #expect(key.identifier == "d56595ee396f")#expect(VPhoneMachineTemplateKey.isIdentifier(key.identifier))}@@ -64,7 +65,7 @@ struct MachineTemplateKeyTests {change(©)variants.append(copy)}- vary { $0.formatVersion = 2 }+ vary { $0.formatVersion = 3 }vary { $0.device = "iPad16,1" }vary { $0.iOSVersion = "27.0.1" }vary { $0.iOSBuild = "24A446" }@@ -77,6 +78,7 @@ struct MachineTemplateKeyTests {vary { $0.slimming.trimTier = "standard" }vary { $0.slimming.setupBoot = true }vary { $0.slimming.serviceProfile = "trimmed" }+ vary { $0.slimming.serviceGroups = ["accounts"] }vary { $0.slimming.removedApps = ["com.apple.tv"] }let identifiers = Set(variants.map(\.identifier) + [base.identifier])@@ -131,6 +133,26 @@ struct MachineTemplateKeyTests {#expect(conflicts[0].hasPrefix("--device iPad16,1"))#expect(conflicts[1].hasPrefix("--preset experimental"))#expect(conflicts[2].hasPrefix("--disk-size 128"))++ let slimmed = VPhoneTemplateSlimmingRequest.defaultSlimming+ #expect(VPhoneMachineTemplateRequest(slimming: .none).conflicts(with: key).isEmpty)+ let slimming = VPhoneMachineTemplateRequest(slimming: slimmed).conflicts(with: key)+ #expect(slimming.count == 1)+ #expect(slimming.first?.contains("slimming switches") == true)+ }++ @Test func `a format 1 key without service groups still reads`() throws {+ // What P2 wrote: no ServiceGroups in the slimming dictionary.+ let plist = """+ <?xml version="1.0" encoding="UTF-8"?>+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+ <plist version="1.0"><dict>+ <key>RemovedApps</key><array/><key>ServiceProfile</key><string>none</string>+ <key>SetupBoot</key><false/><key>TrimTier</key><string>none</string>+ </dict></plist>+ """+ let slimming = try PropertyListDecoder().decode(VPhoneMachineTemplateSlimming.self, from: Data(plist.utf8))+ #expect(slimming == .none)}// MARK: - Codingdiff --git a/VPhoneKit/VPhoneCoreKitTests/Bundle/TemplateSetupBootTests.swift b/VPhoneKit/VPhoneCoreKitTests/Bundle/TemplateSetupBootTests.swiftnew file mode 100644index 00000000..2cf20de7--- /dev/null+++ b/VPhoneKit/VPhoneCoreKitTests/Bundle/TemplateSetupBootTests.swift@@ -0,0 +1,576 @@+import Darwin+import Foundation+import Testing+@testable import VPhoneCoreKit++// MARK: - Fake guest++/// A clock that only moves when the setup boot waits or the fake guest works.+private final class FakeClock: VPhoneTemplateSetupClock {+ var current = Date(timeIntervalSince1970: 1_800_000_000)++ func now() -> Date {+ current+ }++ func sleep(_ seconds: TimeInterval) {+ current = current.addingTimeInterval(seconds)+ }+}++/// A scripted guest with the state the setup boot reads and changes: the+/// orig-fs snapshot, Setup, installed apps, the service profile and the boot.+private final class FakeGuest: VPhoneTemplateSetupMachine {+ let clock: FakeClock+ var calls: [String] = []+ var started = false+ var stopped = false+ var killed = false++ // Scripted behavior.+ var exitsAfterStart = false+ var connectDelayPolls = 2+ var snapshotBusyAnswers = 0+ var skipFailures = 0+ var unsettledAnswers = 1+ var refusedApps: Set<String> = []+ var servicesKeepRunning = false+ var rebootNeverReturns = false+ var stopsCleanly = true++ // Guest state.+ var snapshots = ["orig-fs.disabled.rn-4EC2"]+ var setupDone = false+ var installed: Set<String> = Set(VPhoneTemplateSlimmingRequest.defaultRemovedApps + [+ "com.apple.mobilephone", "com.apple.camera", "com.apple.Preferences",+ ])+ var profile = "none"+ var groups: [String] = []+ var disabled: Set<String> = []+ var running: [String] = []+ var bootTime = 1000.0+ var downCalls = 0+ var pinnedName: String? = "p4-src"++ init(clock: FakeClock) {+ self.clock = clock+ }++ func start() throws {+ started = true+ }++ func failure() -> String? {+ exitsAfterStart && started ? "vphone-vm exited with status 1" : nil+ }++ func ping() -> Bool {+ clock.sleep(0.1)+ if connectDelayPolls > 0 {+ connectDelayPolls -= 1+ return false+ }+ if downCalls > 0 {+ if !rebootNeverReturns {+ downCalls -= 1+ }+ return false+ }+ return true+ }++ private func refused(_ message: String, _ detail: [String: Any]) -> VPhoneGuestCallError {+ VPhoneGuestCallError(kind: .refused, message: message, detail: detail)+ }++ func call(_ method: String, params: [String: Any], timeout: TimeInterval) throws -> [String: Any] {+ calls.append(method)+ clock.sleep(0.5)+ if downCalls > 0 {+ throw VPhoneGuestCallError(kind: .transport, message: "guest not connected")+ }+ switch method {+ case "apfs.snapshot.delete":+ if snapshotBusyAnswers > 0 {+ snapshotBusyAnswers -= 1+ throw refused("busy", ["code": "command_failed", "reason": "busy", "retryable": true, "errno": 16])+ }+ let deleted = snapshots+ snapshots = []+ return ["mount": "/", "before": deleted, "deleted": deleted, "already_deleted": [String](), "after": [String](), "remaining": [String]()]+ case "apfs.snapshots":+ return ["mount": "/", "snapshots": snapshots]+ case "setup.skip":+ #expect(params["force"] as? Bool == true)+ if skipFailures > 0 {+ skipFailures -= 1+ throw refused("Cannot allocate memory", ["code": "failed", "message": "Cannot allocate memory"])+ }+ setupDone = true+ return ["setup_done": true, "setup_version": 11]+ case "setup.settle":+ let wait = params["timeout_s"] as? Int ?? 90+ #expect(wait <= 110)+ if unsettledAnswers > 0 {+ unsettledAnswers -= 1+ clock.sleep(TimeInterval(wait))+ return ["settled": false, "reasons": ["staged_system_apps not empty"], "elapsed_s": wait]+ }+ return ["settled": true, "elapsed_s": 10.2, "reasons": [String]()]+ case "apps.remove_system":+ let ids = params["bundle_ids"] as? [String] ?? []+ var results: [[String: Any]] = []+ for id in ids {+ if refusedApps.contains(id) {+ results.append(["bundle_id": id, "status": "failed", "removed": false, "error": "not in a bundle container"])+ } else if installed.remove(id) != nil {+ results.append(["bundle_id": id, "status": "removed", "removed": true])+ } else {+ results.append(["bundle_id": id, "status": "absent", "removed": false])+ }+ }+ let failed = results.count(where: { $0["status"] as? String == "failed" })+ if failed > 0 {+ throw refused("\(failed) of \(ids.count) apps were not removed; see results", [+ "code": "command_failed", "error": "remove_incomplete", "results": results, "failed": failed,+ ])+ }+ return ["results": results, "removed": ids.count, "failed": 0]+ case "services.profile.apply":+ let wanted = params["profile"] as? String ?? ""+ profile = wanted+ if wanted == "trimmed" {+ groups = ["app_store", "base", "signin_followup"] + (params["groups"] as? [String] ?? [])+ let labels = ["com.apple.weatherd", "com.apple.followupd", "com.apple.appleidsetupd"]+ + ((params["groups"] as? [String] ?? []).contains("accounts") ? ["com.apple.akd"] : [])+ disabled = Set(labels)+ running = ["com.apple.weatherd"]+ } else {+ groups = []+ disabled = []+ running = []+ }+ return ["profile": wanted, "disabled": Array(disabled), "enabled": [String](), "failed": [[String: Any]](), "owned": disabled.count]+ case "services.profile":+ let record: Any = profile == "none" ? NSNull() : ["profile": profile, "groups": groups, "labels": Array(disabled)]+ return ["profile": profile, "record": record, "disabled": Array(disabled), "running": running]+ case "processes.list":+ return ["processes": [["pid": 1, "start_time": bootTime], ["pid": 53, "start_time": bootTime + 4]], "count": 2]+ case "system.reboot":+ bootTime += 100+ downCalls = 3+ if !servicesKeepRunning {+ running = []+ }+ throw VPhoneGuestCallError(kind: .transport, message: "no answer from vphone.sock")+ case "setup.status":+ return ["setup_done": setupDone, "pending": !setupDone]+ case "apps.list":+ return ["apps": installed.map { ["bundle_id": $0] }]+ case "device.name.set":+ pinnedName = params["name"] as? String+ return ["name": NSNull(), "changed": true]+ default:+ throw refused("unknown method \(method)", ["code": "unknown_method"])+ }+ }++ func stop(timeout _: TimeInterval) -> Bool {+ stopped = true+ return stopsCleanly+ }++ func kill() {+ killed = true+ }+}++// MARK: - Tests++/// The setup boot as a state machine: step order, retries, deadlines and what+/// a failure leaves behind, against a scripted guest. No VM is started.+struct TemplateSetupBootTests {+ private func run(+ _ guest: FakeGuest,+ slimming: VPhoneMachineTemplateSlimming = VPhoneTemplateSlimmingRequest.defaultSlimming,+ requiresEveryApp: Bool = true,+ ) -> Result<VPhoneTemplateSetupOutcome, VPhoneTemplateSetupFailure> {+ let boot = VPhoneTemplateSetupBoot(+ machine: guest,+ plan: VPhoneTemplateSetupPlan(slimming: slimming, requiresEveryApp: requiresEveryApp),+ clock: guest.clock,+ log: { _ in },+ )+ do {+ return try .success(boot.run())+ } catch let failure as VPhoneTemplateSetupFailure {+ return .failure(failure)+ } catch {+ Issue.record("unexpected \(error)")+ return .failure(VPhoneTemplateSetupFailure(step: .boot, reason: "\(error)", outcome: .init()))+ }+ }++ /// Whether `expected` occurs in `calls` in this order (other calls may+ /// come in between).+ private func inOrder(_ calls: [String], _ expected: [String]) -> Bool {+ var index = calls.startIndex+ for method in expected {+ guard let found = calls[index...].firstIndex(of: method) else { return false }+ index = calls.index(after: found)+ }+ return true+ }++ @Test func `a full setup boot runs the steps in the fixed order and records the key's slimming`() throws {+ let guest = FakeGuest(clock: FakeClock())+ let outcome = try run(guest).get()++ #expect(inOrder(guest.calls, [+ "apfs.snapshot.delete", "setup.skip", "setup.settle", "setup.settle",+ "apps.remove_system", "services.profile.apply", "services.profile",+ "processes.list", "system.reboot", "processes.list",+ "apfs.snapshots", "setup.status", "services.profile", "apps.list",+ "device.name.set",+ ]))+ // Nothing slims before Setup is skipped and first-boot work settled.+ let firstRemoval = try #require(guest.calls.firstIndex(of: "apps.remove_system"))+ let lastSettle = try #require(guest.calls.lastIndex(of: "setup.settle"))+ #expect(lastSettle < firstRemoval)+ #expect(guest.calls.firstIndex(of: "apfs.snapshot.delete") == 0)++ #expect(outcome.isComplete)+ #expect(guest.stopped)+ #expect(!guest.killed)+ #expect(outcome.deletedSnapshots == ["orig-fs.disabled.rn-4EC2"])+ #expect(outcome.removedApps == VPhoneTemplateSlimmingRequest.defaultRemovedApps.sorted())+ #expect(guest.installed.contains("com.apple.mobilephone"))+ #expect(outcome.serviceProfile == "trimmed")+ #expect(outcome.deviceNameCleared)+ #expect(guest.pinnedName == nil)+ #expect(Set(outcome.durations.keys) == Set(VPhoneTemplateSetupStep.allCases))++ let steps = outcome.applying(to: VPhoneMachineTemplateSteps())+ #expect(steps.setupDone)+ #expect(steps.snapshotDeleted)+ #expect(steps.slimming == VPhoneTemplateSlimmingRequest.defaultSlimming)+ }++ @Test func `slim off skips the setup but slims nothing`() throws {+ let guest = FakeGuest(clock: FakeClock())+ let slimming = try VPhoneTemplateSlimmingRequest(slim: false).resolve()+ let outcome = try run(guest, slimming: slimming).get()+ #expect(!guest.calls.contains("apps.remove_system"))+ #expect(!guest.calls.contains("services.profile.apply"))+ #expect(!guest.calls.contains("apps.list"))+ #expect(guest.calls.contains("setup.skip"))+ #expect(guest.calls.contains("apfs.snapshot.delete"))+ #expect(outcome.isComplete)+ #expect(outcome.applying(to: VPhoneMachineTemplateSteps()).slimming == slimming)+ }++ @Test func `accounts-off reaches the guest as an extra group`() throws {+ let guest = FakeGuest(clock: FakeClock())+ let slimming = try VPhoneTemplateSlimmingRequest(accountsOff: true).resolve()+ let outcome = try run(guest, slimming: slimming).get()+ #expect(guest.groups.contains("accounts"))+ #expect(outcome.applying(to: VPhoneMachineTemplateSteps()).slimming == slimming)+ }++ @Test func `a busy snapshot deletion is retried`() throws {+ let guest = FakeGuest(clock: FakeClock())+ guest.snapshotBusyAnswers = 2+ let outcome = try run(guest).get()+ #expect(guest.calls.count(where: { $0 == "apfs.snapshot.delete" }) == 3)+ #expect(outcome.isComplete)+ }++ @Test func `setup skip that fails early in the boot is retried`() throws {+ let guest = FakeGuest(clock: FakeClock())+ guest.skipFailures = 3+ let outcome = try run(guest).get()+ #expect(guest.calls.count(where: { $0 == "setup.skip" }) == 4)+ #expect(outcome.setupSkipped)+ }++ @Test func `setup skip that keeps failing fails its step`() throws {+ let guest = FakeGuest(clock: FakeClock())+ guest.skipFailures = 1000+ let failure = try #require(run(guest).failed)+ #expect(failure.step == .skipSetup)+ #expect(failure.reason.contains("Cannot allocate memory"))+ }++ @Test func `no snapshot left is not an error`() throws {+ let guest = FakeGuest(clock: FakeClock())+ guest.snapshots = []+ let outcome = try run(guest).get()+ #expect(outcome.deletedSnapshots.isEmpty)+ #expect(outcome.snapshotsGone)+ }++ @Test func `settle is called again until it settles, each call within 110 s`() throws {+ let guest = FakeGuest(clock: FakeClock())+ guest.unsettledAnswers = 4+ let outcome = try run(guest).get()+ #expect(guest.calls.count(where: { $0 == "setup.settle" }) == 5)+ #expect(outcome.settled)+ }++ @Test func `settle that never settles fails at its deadline and kills the VM`() throws {+ let guest = FakeGuest(clock: FakeClock())+ guest.unsettledAnswers = 1000+ let failure = try #require(run(guest).failed)+ #expect(failure.step == .settle)+ #expect(failure.reason.contains("staged_system_apps"))+ #expect(guest.killed)+ #expect(!guest.stopped)+ #expect(!failure.outcome.isComplete)+ #expect(!guest.calls.contains("apps.remove_system"))+ // Bounded: 600 s of 110 s calls.+ #expect(guest.calls.count(where: { $0 == "setup.settle" }) <= 7)+ }++ @Test func `a refused app fails a build whose key promises it`() throws {+ let guest = FakeGuest(clock: FakeClock())+ guest.refusedApps = ["com.apple.findmy"]+ let failure = try #require(run(guest, requiresEveryApp: true).failed)+ #expect(failure.step == .removeApps)+ #expect(failure.reason.contains("com.apple.findmy"))+ #expect(guest.killed)+ #expect(failure.outcome.apps.count == 10)+ #expect(!guest.calls.contains("services.profile.apply"))+ }++ @Test func `a refused app is a warning for a machine to be adopted, and left out of its steps`() throws {+ let guest = FakeGuest(clock: FakeClock())+ guest.refusedApps = ["com.apple.findmy"]+ let outcome = try run(guest, requiresEveryApp: false).get()+ #expect(outcome.isComplete)+ #expect(outcome.warnings.count == 1)+ #expect(!outcome.removedApps.contains("com.apple.findmy"))+ #expect(outcome.removedApps.count == 9)+ let steps = outcome.applying(to: VPhoneMachineTemplateSteps())+ #expect(steps.slimming != VPhoneTemplateSlimmingRequest.defaultSlimming)+ }++ @Test func `an app that is already gone counts as removed`() throws {+ let guest = FakeGuest(clock: FakeClock())+ guest.installed.remove("com.apple.news")+ let outcome = try run(guest).get()+ #expect(outcome.apps.first(where: { $0.bundleID == "com.apple.news" })?.status == "absent")+ #expect(outcome.removedApps.contains("com.apple.news"))+ }++ @Test func `a VM that exits fails the step it was in`() throws {+ let guest = FakeGuest(clock: FakeClock())+ guest.exitsAfterStart = true+ let failure = try #require(run(guest).failed)+ #expect(failure.step == .connect)+ #expect(failure.reason.contains("exited"))+ #expect(guest.calls.isEmpty)+ }++ @Test func `vphoned that never answers fails the connect step`() throws {+ let guest = FakeGuest(clock: FakeClock())+ guest.connectDelayPolls = Int.max+ let failure = try #require(run(guest).failed)+ #expect(failure.step == .connect)+ #expect(guest.killed)+ }++ @Test func `a reboot that never comes back fails the reboot step`() throws {+ let guest = FakeGuest(clock: FakeClock())+ guest.rebootNeverReturns = true+ let failure = try #require(run(guest).failed)+ #expect(failure.step == .reboot)+ #expect(guest.killed)+ }++ @Test func `services still running after the reboot fail verification`() throws {+ let guest = FakeGuest(clock: FakeClock())+ guest.servicesKeepRunning = true+ let failure = try #require(run(guest).failed)+ #expect(failure.step == .verify)+ #expect(failure.reason.contains("still running"))+ #expect(!failure.outcome.verified)+ }++ @Test func `an unclean shutdown fails the setup boot`() throws {+ let guest = FakeGuest(clock: FakeClock())+ guest.stopsCleanly = false+ let failure = try #require(run(guest).failed)+ #expect(failure.step == .stop)+ #expect(failure.outcome.verified)+ #expect(!failure.outcome.isComplete)+ #expect(!failure.outcome.applying(to: VPhoneMachineTemplateSteps()).setupDone)+ }++ @Test func `retryable means unreachable, busy or marked so`() {+ #expect(VPhoneGuestCallError(kind: .transport, message: "x").isRetryable)+ #expect(VPhoneGuestCallError(kind: .refused, message: "x", detail: ["retryable": true]).isRetryable)+ #expect(VPhoneGuestCallError(kind: .refused, message: "x", detail: ["reason": "busy"]).isRetryable)+ #expect(!VPhoneGuestCallError(kind: .refused, message: "x", detail: ["code": "invalid_operation"]).isRetryable)+ #expect(!VPhoneGuestCallError(kind: .refused, message: "x").isRetryable)+ #expect(VPhoneGuestCallError(kind: .refused, message: "x", detail: ["code": "c"]).code == "c")+ }++ @Test func `launchd's start time tells boots apart`() {+ #expect(VPhoneTemplateSetupBoot.bootMarker(["processes": [["pid": 1, "start_time": 12.5]]]) == 12.5)+ #expect(VPhoneTemplateSetupBoot.bootMarker(["processes": [["pid": 2, "start_time": 12.5]]]) == nil)+ #expect(VPhoneTemplateSetupBoot.bootMarker([:]) == nil)+ }+}++// MARK: - Recording++/// A setup boot's outcome in `Template.plist`: a complete one lets the build+/// freeze, a failed one is never recorded and the build stays unfrozen.+struct TemplateSetupRecordingTests {+ private func makeBuild(slimming: VPhoneMachineTemplateSlimming) throws -> (root: URL, build: VPhoneMachineTemplateBuild, lock: VPhoneMachineTemplateLock) {+ 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 library = VPhoneLibrary(root: root.appendingPathComponent("machines"))+ let key = MachineTemplateKeyTests.key(slimming: slimming)+ let lock = try VPhoneMachineTemplates.lock(key.identifier, in: library, wait: false)+ let build = try VPhoneMachineTemplates.beginBuild(key, in: library)+ let bundle = try VPhoneBundleOperations.create(+ .init(name: key.identifier, cpuCount: 4, memoryMB: 4096, diskSizeGB: 1, romSource: rom, sepromSource: rom),+ in: build.library,+ )+ try Data([0xD1]).write(to: bundle.url.appendingPathComponent("Disk.img"))+ try VPhoneMachineTemplates.writeRecord(VPhoneMachineTemplateRecord(key: key, sourceMachine: "p4-a"), inBundle: build.bundleURL)+ return (root, build, lock)+ }++ private func outcome(complete: Bool) throws -> VPhoneTemplateSetupOutcome {+ let guest = FakeGuest(clock: FakeClock())+ guest.stopsCleanly = complete+ let boot = VPhoneTemplateSetupBoot(+ machine: guest,+ plan: VPhoneTemplateSetupPlan(slimming: VPhoneTemplateSlimmingRequest.defaultSlimming, requiresEveryApp: true),+ clock: guest.clock,+ log: { _ in },+ )+ do {+ return try boot.run()+ } catch let failure as VPhoneTemplateSetupFailure {+ return failure.outcome+ }+ }++ @Test func `a complete setup boot is recorded and the build freezes`() throws {+ let (root, build, lock) = try makeBuild(slimming: VPhoneTemplateSlimmingRequest.defaultSlimming)+ defer {+ lock.release()+ try? FileManager.default.removeItem(at: root)+ }+ // Before the setup boot the key's promise is not kept.+ #expect(throws: VPhoneMachineTemplateError.self) { try VPhoneMachineTemplates.freeze(build) }++ try VPhoneMachineTemplates.recordSetupBoot(outcome(complete: true), inBundle: build.bundleURL)+ let record = try #require(try VPhoneMachineTemplates.readRecord(inBundle: build.bundleURL))+ #expect(record.steps.setupDone)+ #expect(record.steps.snapshotDeleted)+ #expect(record.steps.serviceProfile == "trimmed")+ #expect(record.steps.removedApps.count == 10)+ #expect(record.steps.trimTier == "none")++ let template = try VPhoneMachineTemplates.freeze(build)+ #expect(template.record.frozen)+ #expect(template.record.steps.slimming == template.key.slimming)+ }++ @Test func `a failed setup boot records nothing and the build never freezes`() throws {+ let (root, build, lock) = try makeBuild(slimming: VPhoneTemplateSlimmingRequest.defaultSlimming)+ defer {+ lock.release()+ try? FileManager.default.removeItem(at: root)+ }+ let failed = try outcome(complete: false)+ #expect(!failed.isComplete)+ #expect(throws: VPhoneMachineTemplateError.self) {+ try VPhoneMachineTemplates.recordSetupBoot(failed, inBundle: build.bundleURL)+ }+ let record = try #require(try VPhoneMachineTemplates.readRecord(inBundle: build.bundleURL))+ #expect(record.steps == VPhoneMachineTemplateSteps())+ #expect(throws: VPhoneMachineTemplateError.self) { try VPhoneMachineTemplates.freeze(build) }+ #expect(try VPhoneMachineTemplates.readRecord(inBundle: build.bundleURL)?.frozen == false)+ }++ @Test func `a file trim recorded before the setup boot survives it`() throws {+ var slimming = VPhoneTemplateSlimmingRequest.defaultSlimming+ slimming.trimTier = "standard"+ let (root, build, lock) = try makeBuild(slimming: slimming)+ defer {+ lock.release()+ try? FileManager.default.removeItem(at: root)+ }+ try VPhoneMachineTemplates.recordSteps(inBundle: build.bundleURL) { $0.trimTier = "standard" }+ try VPhoneMachineTemplates.recordSetupBoot(outcome(complete: true), inBundle: build.bundleURL)+ #expect(try VPhoneMachineTemplates.freeze(build).record.steps.trimTier == "standard")+ }+}++// MARK: - Socket paths++/// A machine in a template build lives deeper than `sun_path` reaches; its+/// control socket is bound and reached through a short link.+struct UnixSocketLongPathTests {+ @Test func `a socket path longer than sun_path is bound and connected through a link`() throws {+ let fm = FileManager.default+ let root = fm.temporaryDirectory+ .appendingPathComponent(".templates-\(UUID().uuidString)", isDirectory: true)+ .appendingPathComponent(".building-0123456789ab-\(UUID().uuidString)", isDirectory: true)+ .appendingPathComponent("0123456789ab", isDirectory: true)+ try fm.createDirectory(at: root, withIntermediateDirectories: true)+ defer { try? fm.removeItem(at: root.deletingLastPathComponent().deletingLastPathComponent()) }+ let path = root.appendingPathComponent("vphone.sock").path+ #expect(path.utf8CString.count > VPhoneUnixSocket.maximumPathLength)++ let listener = socket(AF_UNIX, SOCK_STREAM, 0)+ #expect(listener >= 0)+ defer { close(listener) }+ let bound = VPhoneUnixSocket.withAddressablePath(path) { short -> Int32 in+ #expect(short.utf8CString.count <= VPhoneUnixSocket.maximumPathLength)+ var address = sockaddr_un()+ address.sun_family = sa_family_t(AF_UNIX)+ withUnsafeMutableBytes(of: &address.sun_path) { buffer in+ for (index, byte) in short.utf8CString.enumerated() {+ buffer[index] = UInt8(bitPattern: byte)+ }+ }+ return withUnsafePointer(to: &address) {+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {+ bind(listener, $0, socklen_t(MemoryLayout<sockaddr_un>.size))+ }+ }+ }+ #expect(bound == 0)+ #expect(listen(listener, 1) == 0)+ // The socket is where the long path says.+ var info = stat()+ #expect(lstat(path, &info) == 0 && info.st_mode & S_IFMT == S_IFSOCK)++ switch VPhoneUnixSocket.connect(to: path) {+ case let .success(fd):+ close(fd)+ case let .failure(error):+ Issue.record("connect failed: \(error)")+ }+ // A short path is used as it is.+ #expect(VPhoneUnixSocket.withAddressablePath("/tmp/x.sock") { $0 } == "/tmp/x.sock")+ }+}++private extension Result {+ var failed: Failure? {+ if case let .failure(error) = self {+ return error+ }+ return nil+ }+}diff --git a/VPhoneKit/VPhoneCoreKitTests/Bundle/TemplateSlimmingRequestTests.swift b/VPhoneKit/VPhoneCoreKitTests/Bundle/TemplateSlimmingRequestTests.swiftnew file mode 100644index 00000000..bed641d6--- /dev/null+++ b/VPhoneKit/VPhoneCoreKitTests/Bundle/TemplateSlimmingRequestTests.swift@@ -0,0 +1,107 @@+import Foundation+import Testing+@testable import VPhoneCoreKit++/// The slimming switches of `vm create` and `vm template setup`, mapped to+/// what a template key promises.+struct TemplateSlimmingRequestTests {+ private typealias Request = VPhoneTemplateSlimmingRequest++ @Test func `no switch asks for a setup boot, the trimmed profile and list C`() throws {+ let slimming = try Request().resolve()+ #expect(slimming.setupBoot)+ #expect(slimming.trimTier == Request.defaultTrimTier)+ #expect(slimming.serviceProfile == "trimmed")+ #expect(slimming.serviceGroups.isEmpty)+ #expect(slimming.removedApps == Request.defaultRemovedApps.sorted())+ #expect(slimming.removedApps.count == 10)+ #expect(slimming == Request.defaultSlimming)+ #expect(Request().isEmpty)+ }++ @Test func `Phone and Camera are never in the default list`() {+ #expect(!Request.defaultRemovedApps.contains("com.apple.mobilephone"))+ #expect(!Request.defaultRemovedApps.contains("com.apple.camera"))+ #expect(Set(Request.defaultRemovedApps).count == Request.defaultRemovedApps.count)+ }++ @Test func `slim off still boots once but slims nothing`() throws {+ let slimming = try Request(slim: false).resolve()+ #expect(slimming == VPhoneMachineTemplateSlimming(trimTier: "none", setupBoot: true, serviceProfile: "none"))+ // Saying the same thing twice is not a contradiction.+ #expect(try Request(slim: false, trimTier: "none", serviceProfile: "none", removeApps: false).resolve() == slimming)+ }++ @Test func `slim off refuses switches that slim`() {+ for request in [+ Request(slim: false, serviceProfile: "trimmed"),+ Request(slim: false, removeApps: true),+ Request(slim: false, keepApps: ["com.apple.news"]),+ Request(slim: false, accountsOff: true),+ Request(slim: false, trimTier: "standard"),+ ] {+ #expect(throws: VPhoneTemplateSlimmingError.self, "\(request)") { try request.resolve() }+ }+ }++ @Test func `parts can be turned off on their own`() throws {+ let noProfile = try Request(serviceProfile: "none").resolve()+ #expect(noProfile.serviceProfile == "none")+ #expect(noProfile.removedApps.count == 10)++ let noApps = try Request(removeApps: false).resolve()+ #expect(noApps.serviceProfile == "trimmed")+ #expect(noApps.removedApps.isEmpty)+ #expect(noApps.setupBoot)+ }++ @Test func `keep-apps subtracts from the default list`() throws {+ let slimming = try Request(keepApps: ["com.apple.findmy", "com.apple.Passbook"]).resolve()+ #expect(slimming.removedApps.count == 8)+ #expect(!slimming.removedApps.contains("com.apple.findmy"))+ #expect(!slimming.removedApps.contains("com.apple.Passbook"))+ #expect(!Request(keepApps: ["com.apple.findmy"]).isEmpty)+ }++ @Test func `keep-apps refuses what is not removed by default`() {+ #expect(throws: VPhoneTemplateSlimmingError.self) {+ try Request(keepApps: ["com.apple.camera"]).resolve()+ }+ #expect(throws: VPhoneTemplateSlimmingError.self) {+ try Request(removeApps: false, keepApps: ["com.apple.news"]).resolve()+ }+ }++ @Test func `accounts-off adds the accounts group and needs the trimmed profile`() throws {+ let slimming = try Request(accountsOff: true).resolve()+ #expect(slimming.serviceGroups == ["accounts"])+ #expect(slimming.serviceProfile == "trimmed")+ #expect(throws: VPhoneTemplateSlimmingError.self) {+ try Request(serviceProfile: "none", accountsOff: true).resolve()+ }+ }++ @Test func `unknown values are refused, all at once`() {+ do {+ _ = try Request(trimTier: "max", serviceProfile: "lean").resolve()+ Issue.record("expected a refusal")+ } catch let error as VPhoneTemplateSlimmingError {+ #expect(error.problems.count == 2)+ } catch {+ Issue.record("\(error)")+ }+ }++ @Test func `every switch that changes the slimming changes the template key`() throws {+ let requests = [+ Request(),+ Request(slim: false),+ Request(serviceProfile: "none"),+ Request(removeApps: false),+ Request(keepApps: ["com.apple.games"]),+ Request(accountsOff: true),+ ]+ let identifiers = try Set(requests.map { try MachineTemplateKeyTests.key(slimming: $0.resolve()).identifier })+ #expect(identifiers.count == requests.count)+ }+}