Run a virtual iPhone on an Apple Silicon Mac.
Swift
Add data-preserving iOS OTA workflow
Jacky3ef99c1d8a34
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex e5642060..874c6a26 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -1,5 +1,38 @@# Patch Comparison: Regular / Development / Jailbreak / Experimental+> **Experimental full OTA System update (2026-10-20):**+> `system-exp-ota_userland` is off in Standard and the TV presets. For a stopped+> iPhone/iPad guest with a snapshot and prepared target firmware, it replaces+> System from a matching full OTA and reapplies the target Guest patches from+> a fresh receipt state. Data/User volumes and SEPStorage are retained. The same+> private disk clone receives the target kernelcache and TXM payloads under their existing IMG4+> manifest; this reuses the existing declared TXM patches, adding no instruction+> patch or fixed offset. The whole System/kernel/TXM transaction aborts on compatibility+> patch failure. This is host-driven payload installation; Apple's UpdateBrain+> protocol and application migration are not implied. See+> [the implementation and validation record](Restore/data_preserving_full_ota.md).+> **2026-10-21 correction:** full updates also stage, validate and install+> `payloadv2/links.txt`. The 24A446 iPad OTA omits 24,835 duplicate paths from+> its numbered chunks. Missing J410 media resources made audiomxd trap in+> CFRetain(NULL), blocking migration through liveactivitiesd and locationd.+> No new binary patch is used; the installer restores the OTA's own hard links+> through confined parent descriptors and checks the resulting inode.+> Corrected migration and the reference-machine clone subsequently booted with+> retained data. The clone's protected app reopened its existing data offline+> at 4/3/2 GB with service profile none. Separate explicit compatibility steps+> preserved a legacy re-signed app container and synchronized 38 retained Apple+> app programs from the target IPSW; these are not new binary patches.+> **2026-10-21 orchestration:** `fw ota` now captures guest policies, takes one+> disk/SEP/NVRAM checkpoint with separate host configuration/firmware backups,+> prepares a pinned target, verifies real target migration, restores Auto-Lock+> through Settings with effective-policy readback, and reapplies the saved service+> profile. The installer stages target removable-app programs on System;+> `ota.apps.apply` updates matching, already-installed Apple app programs at their+> original container paths and quarantines old serialized placeholders. Legacy+> third-party container signing is a preflight refusal, never an implicit repair.+> This adds no instruction patches. Full application and performance equivalence+> remain outside this result; see the runbook for current verification scope.+> **iPhone19,2 / ARM64E_X1 compatibility (validated 2026-10-17):** the tested> pairing is iPhone 18 Pro 27.0.1 (24A446), V63AP, with cloudOS 26.4> (23E5207q). Cache discovery selects `dyld_shared_cache_arm64e_x1` and itsdiff --git a/Research/Restore/data_preserving_full_ota.md b/Research/Restore/data_preserving_full_ota.mdnew file mode 100644index 00000000..c076d7bf--- /dev/null+++ b/Research/Restore/data_preserving_full_ota.md@@ -0,0 +1,314 @@+# Data-preserving full OTA payload updates++This is an experimental host-driven installation of Apple's full OTA System+payload. It does not implement Apple's `softwareupdated` download, preparation,+UpdateBrain or update-ramdisk protocol. A successful extraction is not evidence+of a successful OS migration or of any third-party app's compatibility.++The development target is iPad16,1, iPadOS 26.6.2 (23G90) to 27.0.1 (24A446),+with the cloudOS 26.4 (23E5207q) kernel/SEP platform retained. A reference+machine with one re-signed third-party app defines the workload. Installation+experiments use a separate, disconnected canary machine and clones of the+reference machine; the reference machine itself is not modified.++## Why a full OTA++The cloudOS erase ramdisk reformats the container even when told to perform an+update; see [the restore experiments](native_restore_architecture.md#an-in-place-restore-cannot-keep-a-guests-data-2026-10-05).+The existing Apple TV OTA reader already streams `payloadv2/payload.NNN` files+through the system AppleArchive framework. These full payloads provide another+way to replace System while retaining the encrypted Data and User volumes.++A delta OTA needs pristine source files and is unsuitable for a CFW System+volume. `fw ota-stage` therefore checks `AssetData/Info.plist` and refuses+prerequisite builds before staging any payload chunks. Device and build are+checked independently against the OTA's BuildManifest and the prepared IPSW.++The 24A446 iPad16,1/iPad16,2 full OTA is 8,589,934,592 bytes. SHA-256:++```text+9256edce7573577df407155909b63441cd1ed5acbccbb114551cd4003c4ccfd7+```++This exact file was downloaded from the Apple CDN and hashed locally. Its+AppleDB record is `osFiles/iPadOS/24x - 27.x/24A446.json`; use the OTA entry+without `prerequisiteBuild`, including its link's `decryptionKey`. The staged+payload consists of 35 numbered chunks and occupies approximately 5.5 GiB.+`AssetData/payloadv2/links.txt` is a separate, required part of this filesystem:+the numbered chunks omit the duplicate paths it describes.++## Installation boundaries++| State | Treatment |+| --- | --- |+| System volume | Replaced from the full OTA, followed by the target CFW patches |+| Encrypted Data and User volumes | Not mounted or written by the host installer |+| SEPStorage and NVRAM | Retained; included with Disk.img in the pre-update snapshot |+| APFS container and volume identities | Retained; no restore, repartition or ASR operation |+| Kernelcache | Target-patched payload installed in the same private clone as System/TXM, keeping the personalized manifest |+| Preboot TXM | Target-patched IM4P placed in its existing personalized IMG4 during the System transaction |+| Preboot device tree | Existing CFW identity/board repairs run against the retained guest identity |+| OpenAVB and OpenSEP | Selected by `fw ota prepare`; old ROMs/configuration are in the host checkpoint; SEPStorage is retained |+| Host restore-info.json | Target userland version recorded after a completed experimental install |++The kernel, System and TXM update are one stopped-machine transaction. No+intermediate kernel-only disk is published. The stopped snapshot and OTA host+checkpoint are the rollback unit. Restoring Disk.img without its corresponding+SEPStorage and NVRAM is not a valid rollback. Normal VM snapshots still exclude+config.plist and patch selection; OTA saves these separately.++## Running the coordinated update++The source must be running, responsive and finished with migration and Setup.+This implementation pins iPhone/iPad iOS 26 to 27.0.1/24A446 and requires the+source cloudOS version/build to remain unchanged. It refuses deltas, mismatched+device/build inputs and protected apps without matching explicit container+entitlements: a protected app's `com.apple.private.security.container-required`+must name the identifier recorded in its existing data container's metadata. It+does not silently re-sign third-party apps.++Install the built bundle with Launchpad and explicitly bind the stopped test+machine to that version. Start it before running the coordinator. The following+is run from the source checkout; variables name the actual machine, installed+bundle and firmware sources you selected. The full OTA and IPSWs accept local+files or HTTPS URLs. The AEA key is the public firmware key.++```zsh+./scripts/ota-upgrade.zsh "$vm" "$bundle_version" \+ "$target_ipsw" "$source_cloudos_ipsw" "$full_ota" "$public_aea_key" \+ "$protected_app_id"+```++Omit the app ID on a fixture that has no such app installed; repeat app IDs to+protect more apps. A protected app must retain its bundle path, data path,+group-container mapping, version and build, and must reach the foreground.+This does not attest the app's own runtime or network behavior.++| Phase | Required state | Effect |+| --- | --- | --- |+| `capture` | Running source | Save source OS, app paths/entitlements, profile/groups/allow and Auto-Lock outside the machine folder |+| `checkpoint` | Stopped | One fresh APFS disk/SEP/NVRAM snapshot plus APFS clones of host config, patch files, ROMs and old firmware inputs |+| `quiesce` | Running source after checkpoint | Re-enable only profile-owned disabled services; refuse externally disabled migration dependencies |+| `prepare` | Stopped | Verify pinned target/cloudOS, cache sources, preserve old host backups, prepare/patch target, stage full OTA and select OpenAVB/OpenSEP |+| `cfw install` | Stopped, existing helper | Replace System/kernel/TXM on one private disk clone; stage target Apple app programs without mounting encrypted Data |+| `complete` | Running target | Require successful migration for 24A446, update retained Apple programs, dismiss post-update Setup, restore effective Auto-Lock/profile, verify protected app launch |+| `rollback` | Stopped | Restore disk/SEP/NVRAM and saved host configuration/firmware; retain recovery material |++The coordinator performs a final stop/start and repeats `complete` after service+overrides have taken effect. It retries migration/Setup/profile convergence for+up to ten minutes. Failures restore the checkpoint; a checkpoint failure starts+the unchanged source again. A failed rollback leaves the recovery material and+prints the action needed. Every VM/privileged action uses Launchpad.++The durable CLI is also available to coordinators. For example:++```zsh+vphone-launchpad-cli exec --bundle "$bundle_version" fw ota status "$vm"+vphone-launchpad-cli vm stop "$vm"+vphone-launchpad-cli exec --bundle "$bundle_version" fw ota rollback "$vm"+vphone-launchpad-cli vm start "$vm" --headless --wait --timeout 600+```++Explicit `--force` is required to roll back a journal already marked completed,+because that discards writes after its checkpoint. The normal recovery unit is+retained at `<library>/.ota-updates/<machine>/`, with one snapshot referenced by+`Update.plist`. Do not overwrite it to restart a failed preparation. Retry that+phase or roll back first. Disk usage includes the shared firmware cache, staged+OTA, target firmware inputs and changed snapshot blocks; these are not RAM.+The installer still requires more than 50 GiB free when installation begins.++## Retained Apple app programs++The full OTA has placeholders for removable Apple apps. Their old programs+survive on encrypted Data, and a 26.x program may fail to load 27.x frameworks.+The installer decrypts and mounts a verified private copy of the target IPSW's+OS image read-only, and copies its `private/var/staged_system_apps` to the new+System volume. Any extraction failure discards the private disk clone.++`ota.apps.status` compares the staged programs with matching registered Apple+apps in UUID bundle containers. `ota.apps.apply {force:true}` copies each target+program beside the existing one and atomically exchanges them. The old program+and `SerializedPlaceholder.ipa` remain under inactive `.ota-24A446-*` names.+The app is re-registered through the dedicated removable-system-app path.+A repeated apply leaves current, registered apps alone, including any+placeholder written after the old one was quarantined.+Independent user-data/group containers and intentionally removed apps remain+untouched; no `_icli`/`_VPhone` ownership marker is fabricated. This API accepts+no caller-selected source/destination paths or list of third-party app IDs.++## Implementation checks (2026-10-21)++The new OTA journal and ordinary snapshot regression suites passed 21 tests.+The coordinator's simulated success, preparation failure with rollback,+checkpoint failure with source restart, and wrong-binding refusal passed.+The host CLI and guest daemon built with their owning Xcode schemes. These+checks cover implementation behavior; integrated canary acceptance is recorded+separately below when run.++The canary run reached 27.0.1 (24A446), completed DataMigrator with+`DMLastMigrationResults.success=true`, and installed 24,835 hard links. It was+rolled back before the network commit because the source Auto-Lock policy was+120 seconds while the target effective policy remained 300 seconds after the+Settings write and cold-boot retries. The target was not committed.++System/TXM installation requires a private APFS clone. Unlike the legacy full+installer's cross-volume fallback, this operation never edits Disk.img in+place. Compatibility patch failures abort before the clone is published. The+existing personalized TXM manifest and restore information remain byte-identical.+The target `trxm` type must match both containers.++The old Guest receipt cannot be reused for the new System contents. Its prior+patch set is reset before applying target patches, including patches common to+26 and 27. Otherwise a cache patch could be incorrectly skipped because it was+already recorded for the erased 26 cache.++All payload chunks are copied into the root installer's private work folder and+validated together before extraction. Validation rejects absolute paths,+traversal, incompatible object types, type changes and a member below a symlink+or another non-directory, including across chunk boundaries. Absolute guest+symlinks themselves are retained. Apple's empty-path root directory entry is+accepted. The root installer repeats the validation after copying the files;+an earlier unprivileged check is not trusted as proof of the later bytes.+The hard-link list is copied and checked with the same chunks before extraction.+Every `=` source must be an archived regular file; every `+` destination must+be new and must not traverse any non-directory. After extraction, `linkat`+operates through confined parent descriptors and the new leaf's inode is checked+against the opened source. A missing list aborts a full update.++## Experimental procedure++The normal commands are dispatched through `vphone-launchpad-cli exec` with the+experimental bundle explicitly selected. The default bundle and other machines+do not change. Prepare the target IPSW and cloudOS sources with `fw prepare`+on a stopped experimental machine, after taking a snapshot. Do not run+`restore`.++The added verb is:++```text+fw ota-stage <vm> --source <local-full-ota> --key <base64-key> --build <target-build>+```++It stages into `OTAUserland/` and writes `Upgrade.plist` only after the archive+passes the full-update, device, build and chunk checks. `--verify-staged` reads+the already staged payload and verifies its filesystem paths without installing+it. Staging refuses to replace an existing OTAUserland folder.++Then run `fw patch` for the target, `cfw update-kernel`, and enable only+`system-exp-ota_userland` on top of the desired preset with `fw set-patches`.+`cfw install --keep-artifacts` performs the experimental System/TXM transaction.+The new patch is off in Standard and both TV presets. A matching staged OTA and+a stopped disk/SEP/NVRAM snapshot are required even if a broader preset selects+the patch. Keeping artifacts allows diagnosis and another offline attempt.++After installation, first prove the target OS boots and can read a marker from+the encrypted Data volume. Then verify cold boots and guest reboots before+testing the real application state. A version shown in Launchpad comes from+host metadata and is not a substitute for `device.info` from the booted guest.++## Evidence and validation++| Evidence | Observation | Consequence |+| --- | --- | --- |+| E-001: `vm list`, `device.info` on the reference machine | iPad16,1, 26.6.2/23G90, cloudOS 26.4, 8 CPUs and 8192 MB, jailbroken | Defines the original system and workload |+| E-002: `apps.info`, `processes.list` | Protected app footprint 228,214,416 B, resident 555,630,592 B | A single running-process sample, not a cold-launch or media peak |+| E-003: CDN metadata and local SHA-256 | Full 24A446 OTA matches the digest above | Pins the exact target asset |+| E-004: OTAArchiveTests | 16 tests passed, including prerequisite rejection and cross-chunk symlink traversal | Offline parser/path validation; no guest compatibility claim |+| E-005: FirmwarePatchSetCatalogTests and CustomFirmwareKernelcacheSwapTests | 27 tests passed; TXM container fixture preserves IM4M and refuses a kernel payload | Offline selection/container validation |+| E-006: `fw ota-stage --verify-staged` on the canary | 35 real payload chunks passed path validation | The real OTA has a supported full filesystem payload |+| E-007: canary | Booted at 26.6.2, wrote a 54-byte Data marker, stopped and saved `pre-ota-26` | Establishes the encrypted-data rollback and migration test |+| E-008: first OTA boot | Guest reported 27.0.1 (24A446), vphoned answered, and the 54-byte Data marker read back exactly; the window stayed at the Apple logo/0 fps | System, SEPStorage and Data unlock worked; UI acceptance failed |+| E-009: `logs.crashes` + `logs.crash` | `com.apple.datamigrator` reported `com.apple.VoiceShortcuts.ShortcutsMigrator (Shortcuts.migrator) - Returned NO from -performMigration: (upgrade) (prev build 23G90)`; `DMLastMigrationResults.success` was false | The first UI regression is a DataMigrator plugin failure during the 23G90 to 24A446 upgrade, not an SEP or Data-volume loss |+| E-010: second OTA boot after forced Cryptex sync | SpringBoard PID 330 was alive and the screen still showed Apple logo/0 fps; marking migration success and respringing did not restore UI | Cryptex replacement was necessary but not sufficient; a real migration fix or skip path remains required |+| E-011: post-service-restore migration stackshot | PreferencesMigrator waited on locationd, which waited through liveactivitiesd on launchd-throttled audiomxd | The dependency chain identifies a media initialization failure below the migration plugin |+| E-012: temporary SIGTRAP tracer on the disconnected canary | audiomxd called CFRetain(NULL) from MediaExperience; CelestialCFCreatePropertyListForModelAndBundleIdentifier returned NULL for J410/CategoriesThatShareVolumes.plist and a valid object for Default | The failure is a missing per-device resource, not low-memory pressure; the reference machine was not instrumented |+| E-013: exact full OTA, rehashed to the digest above | links.txt has 24,835 destinations; J410's missing category/route/volume resources are among them, with archived source files | The first implementation omitted the separate hard-link phase; payload extraction alone is incomplete |+| E-014: corrected ArchiveKit tests and real OTA validation | 94/94 archive tests passed; all 35 actual chunks and 24,835 links passed combined path/source validation | Offline validation of the fix |+| E-015: corrected canary and reference-clone reruns | Real migration returned success=true at 24A446; encrypted Data marker retained; one subsequent setup.skip persisted across cold/guest reboots | The missing-link migration failure is repaired; no synthetic success preference is used as acceptance |+| E-016: runtime comparison on a 27 reference clone | 26's runtime HOME used its legacy signed-identifier container, while 27 used the bundle-ID container; both loaded the app's injected library | A loaded library or visible UI does not show the app reached its existing data; stale state from the source must not be accepted |+| E-017: explicit legacy container entitlement and re-registration | The app reopened its existing data container and wrote fresh state from the current process; UUID and original entitlement values retained | The application needs an explicit container compatibility step; Data was not copied to a different container |+| E-018: reference clone at 4096/3072/2048 MB, service profile none | Existing data reopened from the current process, pressure level 1; 2 GB also passed guest reboot and app reopen | Offline startup is possible at 2 GB; no network or heavy-media claim |+| E-019: retained Apple app bundles on Data | 26.6 Calendar/Music widgets failed with DYLD Symbol missing against 27 frameworks | System-only payload extraction also needs an explicit preinstalled-app compatibility phase |+| E-020: target IPSW staged_system_apps | Replaced 38 already-installed Apple app bundles at their original paths, retaining old copies and all independent data paths; cold boot and Calendar/Music foreground passed, no new crash reports in the bounded follow-up | Validates a clone-only app synchronization experiment; not yet automatic in the installer |+| E-021: final 2 GB complete-app-set sample | The protected app's data check passed; pressure briefly reached level 2 then returned to level 1 with the same app PID and no new jetsam report | 2 GB is an experimental floor, not a demonstrated memory margin |++The temporary trace was removed from the launchd job and the original audiomxd+plist was reloaded after collecting E-012. Diagnostic wrappers and logs were+under `/private/var/tmp`; no shared-cache code was patched. Setup Assistant was+observed changing SetupDone back to false; setup.skip made it true again, but+that does not repair or certify migration. The real rerun starts from the+stopped pre-migration disk/SEP/NVRAM snapshot, before any target migration or+diagnostic preference changes.++The earlier failed boots remain diagnostic history. The corrected rerun actually+completed migration before setup.skip, and retained Setup completion on later+boots. Marking a failed migration successful by hand is not an accepted path.++Path P-001: snapshot the stopped 26 guest (E-007), prepare the target firmware+and full OTA (E-003/E-006), update the kernel and atomically replace System/TXM,+then read `device.info`, real migration results and the Data marker from the+booted 27 guest. After the missing hard links were restored, this passed on the+canary and the reference clone. Retained third-party signing-container policies+and preinstalled Apple app programs require the explicit compatibility steps+below before the app is assessed.++## Retained applications after a major userland change (2026-10-21)++The protected app's executable had an ad hoc CodeDirectory identifier different+from its bundle ID, with no explicit container-required entitlement. The+existing data container's metadata matched that signing identifier. A same-byte+runtime probe used the existing container on 26 but the ordinary bundle-ID+container on 27. Its injected library was loaded in both cases; on 27 it+therefore missed the state it keeps in the existing container. Re-signing a copy+with the exact existing container identifier in+`com.apple.private.security.container-required`, preserving all other+entitlements and the executable UUID, followed by app re-registration, let the+current process reopen the existing data. `fw ota capture` checks this value+against the container's `MCMMetadataIdentifier`. This was done only on the+disconnected clone, with the original binary and snapshot kept. It is not a+generic automatic re-sign policy.++Apple apps stored on Data also retained 26 binaries. Calendar and Music widget+crashes reported missing CalendarLink/MusicKitInternal symbols, rather than+jetsam. The OTA supplied AppPlaceholders but not the complete staged removable+app programs. The matching IPSW's root image contained complete 27 bundles in+`private/var/staged_system_apps`. A clone-only experiment selected the 38 apps+already installed, staged each in its existing bundle container, retained the+old bundle, then replaced the program directory. It neither removed nor+changed the independent user-data container paths. Cold boot and foreground+Calendar/Music passed; bounded post-boot crash reports had no new entries.+The old SerializedPlaceholder.ipa repair path and every individual system-app+feature remain untested. These application steps are not yet part of automatic+`cfw install`; a successful System/TXM transaction alone is insufficient.++Diagnostic launchd stdout persists and appends across boots. Always parse the+last JSON document and require a new heartbeat; when clearing task-owned stdout,+unload the job first so launchd does not retain an unlinked output descriptor.+Allow a slow low-memory diagnostic client to finish instead of cancelling and+restarting it every three seconds. Launchpad also restores bundle environment+libraries on host cold start, so temporary diagnostic library bytes must be+read back before interpreting a probe.++## Memory acceptance++Use the same CPU count, screen geometry, app binary and workload at each memory+size. Keep 8 GB as the migration baseline, then test 4096, 3072 and 2048 MB with+stopped-machine configuration changes. A 7 GiB shared-region address range is+virtual address space; it is not a requirement for 7 GiB of physical RAM.++OpenAVB and OpenSEP already contain the low-memory unbacked-register fixes+documented in [OpenAVB](../Firmware/openavb_boot_rom.md) and+[OpenSEP](../Firmware/opensep_sep_rom.md). Their existing 6144 MB results do not+prove 2–4 GB iPad support.++For every size, record cold-boot time, guest reboots, pressure level, jetsam+events, process restarts, the protected app's footprint and resident memory, and+the slowest operation. Hold the app at one version and verify its image UUID+before comparing sizes. A booted UI or a loaded library does not prove the+app's own network behavior; that needs separate evidence, and no real traffic+should be generated merely to obtain a benchmark.++The claim that 27.0.1's animations use fewer resources remains a performance+hypothesis until paired measurements establish a benefit for this app.+Boot/install memory and foreground media/recovery peaks can set the minimum+even when steady-state process footprints are small.diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.mdindex 2ae74e54..c778f2ac 100644--- a/Research/vphoned_http_api.md+++ b/Research/vphoned_http_api.md@@ -371,7 +371,7 @@ request carries `"force": true`.| Area | Methods || --- | --- || Device | `device.snapshot`, `device.info` (snapshot plus network, screen, rotation, brightness, volume, low power, Developer Mode, agent, `device_name` `{name, own_name}`: the pinned name and the guest's own ComputerName), `device.screen`, `device.network`, `device.ioreg {plane}`, `device.environment`, `device.basebin {archive?}` |-| Display, audio | `display.brightness {value?}`, `display.rotation {orientation?}`, `display.orientation` (`{degrees, source}`: SpringBoard's interface orientation without a screen capture, for polling; `degrees` is null while SpringBoard has no answer; capability `display_orientation`), `display.rotation_lock {locked}`, `display.auto_lock` (`{auto_lock_seconds, never, lock_screen_minimum_seconds}`: Auto-Lock and the Lock Screen timeout vphoned keeps in step with it, see below; capability `display_auto_lock`), `screen.unlock {passcode?, timeout?}` (`{locked, screen_off, was_locked, was_screen_off}`: the display on and the Lock Screen passed, see below; capability `screen_unlock`), `audio.volume {value?, category?}`, `audio.state` |+| Display, audio | `display.brightness {value?}`, `display.rotation {orientation?}`, `display.orientation` (`{degrees, source}`: SpringBoard's interface orientation without a screen capture, for polling; `degrees` is null while SpringBoard has no answer; capability `display_orientation`), `display.rotation_lock {locked}`, `display.auto_lock` (`{auto_lock_seconds, never, lock_screen_minimum_seconds}`), `display.auto_lock.set {seconds}` (writes the mobile UserSettings input through cfprefsd, posts profiled's effective-settings notification, and returns an immediate readback; the caller must verify the effective value), `screen.unlock {passcode?, timeout?}` (`{locked, screen_off, was_locked, was_screen_off}`: the display on and the Lock Screen passed, see below; capability `screen_unlock`), `audio.volume {value?, category?}`, `audio.state` || Input | `input.touch`, `input.hid`, `input.button {name}`, `input.key {name}`, `input.type {text, delay_ms?}`, `input.paste {text}`, `input.tap`, `input.double_tap`, `input.long_press`, `input.swipe`, `input.drag {points}`, `input.touch_sequence {events}` — gesture coordinates are screen points; `input.pointer {x, y, seq?, buttons?}`, `input.scroll {phase, dx?, dy?, x?, y?}` (capabilities `pointer_scroll` and `pointer_buttons`, see below) || UI | `ui.tree` (alias `accessibility.tree`), `ui.element_at`, `ui.tap_element`, `ui.wait`, `ui.wait_gone`, `ui.ocr {languages?, min_confidence?}`, `ui.describe`, `screen.screenshot` || Processes | `processes.list {filter?}`, `processes.kill {pid, signal?}` **force**, `memory.jetsam`, `memory.pressure` (only the three kernel memory sysctls, for polling) |@@ -380,6 +380,7 @@ request carries `"force": true`.| Darwin notifications | `notify.post {name, state?}` (`postDarwinNotification`; `state` is a UInt64, as a number or a decimal string, stored before the post), `notify.state {name}` (`darwinNotificationState`) || Network, security | `network.capture {seconds, interface?, filter?}` (writes a pcap in the guest scratch directory and returns its path), `network.ipv4.get {interface?}`, `network.ipv4.set {interface?, method, address?, subnet_mask?, router?, dns?}`, `network.hostname.get`, `network.hostname.set {local_host_name?}`, `device.name.get`, `device.name.set {name}` (see below), `network.static_names.get`, `network.static_names.set {entries}`, `network.resolve {host, family?, port?, first_only?, timeout_ms?}` (see below), `security.ssl_killswitch` || Apps | `apps.list`, `search`, `refresh`, `launch`, `terminate`, `foreground`, `open_url`, `install`, `info`, `binary`, `data_dir`, `url_schemes`, `handlers`, `registration`, `register`, `network_policy {repair?}`; `apps.uninstall`, `unregister`, `unregister_dir` **force**; `apps.removed_system`, `apps.remove_system {bundle_ids, backup?, respring?}` **force**, `apps.restore_system {bundle_ids?, respring?}` **force** (removable system apps, see below) |+| OTA Apple app programs | `ota.apps.status`, `ota.apps.apply {force:true}` (capability `ota_system_apps`; only matching installed removable Apple apps from the installed 24A446 System payload, no caller-selected paths or third-party app IDs; result `{build, apps, pending}`; preserves user-data/group containers and retains old programs/placeholders; see [the OTA runbook](Restore/data_preserving_full_ota.md#retained-apple-app-programs)) || System | `system.uicache`, `system.system_apps {visible?}`, `system.respring` **force**, `system.reboot {userspace?}` **force**, `system.shutdown` **force**, `developer_mode.status`, `developer_mode.enable`, `power.low_power_mode`, `time.timezone {identifier?, automatic?}`, `time.clock {time?, automatic?}` (see below), `diagnostics.self_test` || Files | `files.list`, `mkdir`, `remove`, `rename`, `read {binary?, limit?}`, `write`, `find`, `copy`, `symlink`, `chmod`, `chown`, `plist`, `plist_set {value \| remove}` || APFS snapshots | `apfs.snapshots {mount?}`, `apfs.snapshot.delete {mount?, name? \| prefix?}` **force** (only `orig-fs.disabled.rn-*`, see below) |diff --git a/VPhoneDaemon/Daemon/GuestAPI+Device.swift b/VPhoneDaemon/Daemon/GuestAPI+Device.swiftindex 77d82bed..a6bb08ef 100644--- a/VPhoneDaemon/Daemon/GuestAPI+Device.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+Device.swift@@ -96,6 +96,11 @@ extension GuestAPI {return try setRotationLock(locked)case "display.auto_lock":return GuestLockScreenIdle.describe()+ case "display.auto_lock.set":+ guard let seconds = (params["seconds"] as? NSNumber)?.intValue else {+ throw GuestAPIError.invalidRequest("seconds must be an integer")+ }+ return try GuestLockScreenIdle.setAutoLockSeconds(seconds)case "screen.unlock":return try GuestScreenUnlock.unlock(passcode: optionalString(params, "passcode"),diff --git a/VPhoneDaemon/Daemon/GuestAPI+SystemApps.swift b/VPhoneDaemon/Daemon/GuestAPI+SystemApps.swiftindex 552b1a11..842c8914 100644--- a/VPhoneDaemon/Daemon/GuestAPI+SystemApps.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+SystemApps.swift@@ -22,6 +22,11 @@ import VphonedNativeextension GuestAPI {static func executeSystemApps(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {switch method {+ case "ota.apps.status":+ return try updateOTASystemApps(apply: false)+ case "ota.apps.apply":+ try requireForce(params, "update retained Apple app programs from the installed OTA")+ return try updateOTASystemApps(apply: true)case "apps.remove_system":guard let ids = try systemAppIDs(params) else {throw GuestAPIError.invalidRequest("bundle_ids must list the apps to remove")@@ -43,6 +48,129 @@ extension GuestAPI {}}+ private static let otaAppsLock = NSLock()++ /// Deliberately separate from apps.install/register: this owns no ordinary+ /// app container. It accepts no caller-selected path or identifier and only+ /// replaces matching Apple apps already registered in UUID containers.+ private static func updateOTASystemApps(apply: Bool) throws -> [String: Any] {+ otaAppsLock.lock()+ defer { otaAppsLock.unlock() }+ let fm = FileManager.default+ let root = "/usr/local/share/vphone-ota"+ let build = "24A446"+ guard let data = fm.contents(atPath: root + "/Upgrade.plist"),+ let metadata = try PropertyListSerialization.propertyList(from: data, format: nil) as? [String: String],+ metadata["Build"] == systemBuildVersion, metadata["Build"] == build else {+ throw GuestAPIError.operationFailed("No matching installed OTA system-app payload.")+ }+ let apps = try listApps()["apps"] as? [[String: Any]] ?? []+ let installed = Dictionary(apps.compactMap { app in (app["bundle_id"] as? String).map { ($0, app) } },+ uniquingKeysWith: { first, _ in first })+ /// A bundle's executable name, refused unless it is one plain component.+ func executableName(_ info: [String: Any]) -> String? {+ guard let name = info["CFBundleExecutable"] as? String,+ !name.isEmpty, !name.contains("/"), name != ".", name != ".." else { return nil }+ return name+ }+ var rows: [[String: Any]] = []+ for name in try fm.contentsOfDirectory(atPath: root + "/apps").sorted() where name.hasSuffix(".app") {+ let source = root + "/apps/" + name+ guard let info = NSDictionary(contentsOfFile: source + "/Info.plist") as? [String: Any],+ let id = info["CFBundleIdentifier"] as? String else {+ throw GuestAPIError.operationFailed("Invalid staged Apple app: \(name)")+ }+ try GuestSystemAppPolicy.validateBundleID(id)+ guard let bundlePath = installed[id]?["bundle_path"] as? String,+ let location = try? GuestSystemAppLocation(bundlePath: bundlePath) else { continue }+ guard location.appDirectoryName == name, try bundleContainerExists(location) else {+ throw GuestAPIError.operationFailed("Staged Apple app does not match its installed container: \(id)")+ }+ try checkBundleIdentifier(location, id)+ guard let executable = executableName(info) else {+ throw GuestAPIError.operationFailed("Invalid staged Apple executable: \(id)")+ }+ guard let liveInfo = NSDictionary(contentsOfFile: location.appPath + "/Info.plist") as? [String: Any],+ let liveExecutable = executableName(liveInfo) else {+ throw GuestAPIError.operationFailed("Invalid installed Apple executable: \(id)")+ }+ // Info.plist first; mapped bytes compare stops at a length or+ // first-byte difference instead of hashing both programs.+ let matches = try NSDictionary(dictionary: liveInfo).isEqual(to: info)+ && Data(contentsOf: URL(fileURLWithPath: source + "/" + executable), options: .mappedIfSafe)+ == Data(contentsOf: URL(fileURLWithPath: location.appPath + "/" + liveExecutable), options: .mappedIfSafe)+ var row: [String: Any] = ["bundle_id": id, "path": location.appPath, "current": matches]+ if apply {+ let stage = location.containerPath + "/.ota-" + build + "-" + name+ if !matches {+ // Copy across System -> Data, keeping every independent+ // user-data/group container at its original path.+ if pathExists(stage) {+ throw GuestAPIError.operationFailed("OTA app staging remains at \(stage); inspect or roll back before retrying.")+ }+ let attributes = try fm.attributesOfItem(atPath: location.appPath)+ guard let owner = attributes[.ownerAccountID] as? NSNumber,+ let group = attributes[.groupOwnerAccountID] as? NSNumber else {+ throw GuestAPIError.operationFailed("Cannot read installed Apple app ownership.")+ }+ if let error = preservingCopy(source, to: stage) {+ throw GuestAPIError.operationFailed("Cannot stage \(id): \(error)")+ }+ // The staged image belongs to root; installed programs+ // keep their original _installd owner. Never follow links.+ let stagedURL = URL(fileURLWithPath: stage)+ let entries = fm.enumerator(at: stagedURL, includingPropertiesForKeys: nil)+ guard lchown(stage, owner.uint32Value, group.uint32Value) == 0 else {+ throw GuestAPIError.operationFailed("Cannot preserve Apple app ownership.")+ }+ while let url = entries?.nextObject() as? URL {+ guard lchown(url.path, owner.uint32Value, group.uint32Value) == 0 else {+ throw GuestAPIError.operationFailed("Cannot preserve ownership of \(url.path)")+ }+ }+ _ = try killApp(id, force: true)+ // Atomic exchange: a crash always leaves a complete .app+ // at the registered path. The old app remains at stage.+ guard renameatx_np(AT_FDCWD, stage, AT_FDCWD, location.appPath, UInt32(RENAME_SWAP)) == 0 else {+ throw GuestAPIError.operationFailed("Cannot publish target Apple app: \(String(cString: strerror(errno)))")+ }+ row["old_program"] = stage+ }+ // A 26.x SerializedPlaceholder can reinstall the old program+ // later. Keep it as an inactive backup in the same container.+ // Once that backup exists, a placeholder written afterwards+ // describes the target program and stays where it is, so a+ // repeated apply is a no-op.+ let placeholder = location.containerPath + "/SerializedPlaceholder.ipa"+ let oldPlaceholder = location.containerPath + "/.ota-" + build + "-SerializedPlaceholder.ipa"+ var changed = !matches+ if pathExists(placeholder), !pathExists(oldPlaceholder) {+ guard rename(placeholder, oldPlaceholder) == 0 else {+ throw GuestAPIError.operationFailed("Could not quarantine the old serialized placeholder for \(id).")+ }+ changed = true+ }+ func registered() throws -> Bool {+ try appRegistration(location.appPath)["registered"] as? Bool == true+ }+ if try changed || !registered() {+ var method: UnsafeMutablePointer<CChar>?+ if let error = vp_ls_register_system_app(location.appPath, location.containerPath, &method) {+ defer { free(error) }+ throw GuestAPIError.operationFailed(String(cString: error))+ }+ free(method)+ guard try registered() else {+ throw GuestAPIError.operationFailed("Updated Apple app is not registered: \(id)")+ }+ }+ row["current"] = true+ }+ rows.append(row)+ }+ return ["build": build, "apps": rows, "pending": rows.filter { $0["current"] as? Bool != true }.count]+ }+/// `bundle_ids` in request order without repeats, or nil when absent.private static func systemAppIDs(_ params: [String: Any]) throws -> [String]? {guard let value = params["bundle_ids"] else { return nil }diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swiftindex 40b2b660..57d707e2 100644--- a/VPhoneDaemon/Daemon/GuestAPI.swift+++ b/VPhoneDaemon/Daemon/GuestAPI.swift@@ -100,6 +100,7 @@ enum GuestAPI {"touch2","hid","apps",+ "ota_system_apps","url","files","clipboard",diff --git a/VPhoneDaemon/Daemon/GuestLockScreenIdle.swift b/VPhoneDaemon/Daemon/GuestLockScreenIdle.swiftindex 05cb81d9..b6244f67 100644--- a/VPhoneDaemon/Daemon/GuestLockScreenIdle.swift+++ b/VPhoneDaemon/Daemon/GuestLockScreenIdle.swift@@ -28,6 +28,7 @@ enum GuestLockScreenIdle {/// then posts `changedNotification`; ManagedConfiguration's own clients/// re-read it on the same signal.private static let settingsPath = "/var/mobile/Library/UserConfigurationProfiles/EffectiveUserSettings.plist"+ private static let userSettingsPath = "/var/mobile/Library/UserConfigurationProfiles/UserSettings.plist"private static let changedNotification = "com.apple.managedconfiguration.effectivesettingschanged"private static let domain = "com.apple.springboard"private static let key = "SBMinimumLockscreenIdleTime"@@ -72,6 +73,27 @@ enum GuestLockScreenIdle {]}+ /// Update the managed UserSettings input through cfprefsd and let profiled+ /// regenerate EffectiveUserSettings. Never edit the effective file itself.+ static func setAutoLockSeconds(_ seconds: Int) throws -> [String: Any] {+ guard seconds >= 0, seconds <= Int(Int32.max) else {+ throw IcliError.failed("Auto-Lock seconds must be between 0 and Int32.max")+ }+ guard let data = FileManager.default.contents(atPath: userSettingsPath),+ let plist = try PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any]+ else { throw IcliError.unavailable("UserSettings.plist is unavailable") }+ var restricted = plist["restrictedValue"] as? [String: Any] ?? [:]+ var setting = restricted["maxInactivity"] as? [String: Any] ?? [:]+ setting["value"] = seconds+ if setting["rangeMinimum"] == nil { setting["rangeMinimum"] = 120 }+ restricted["maxInactivity"] = setting+ _ = try writePreference(domain: userSettingsPath, key: "restrictedValue", value: .plist(restricted), notify: changedNotification)+ apply(reason: "requested Auto-Lock \(seconds)s")+ var result = describe()+ result["requested_auto_lock_seconds"] = seconds+ return result+ }+private static func apply(reason: String) {guard let autoLock = autoLockSeconds() else {NSLog("vphoned: lock screen idle (%@): Auto-Lock is not readable, nothing changed", reason)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swiftindex 992e4d2c..81f901d1 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift@@ -166,17 +166,27 @@ public enum CustomFirmwarePostRestoreDeviceTree {public static func kernelcacheReplacingPayload(prebootIMG4: Data,patchedKernelcache: Data,+ ) throws -> Data? {+ try firmwareReplacingPayload(prebootIMG4: prebootIMG4, patchedComponent: patchedKernelcache, expectedFourcc: "krnl")+ }++ /// A Preboot component keeps its personalized IM4M and restore information;+ /// only the matching, explicitly named payload type may be replaced.+ public static func firmwareReplacingPayload(+ prebootIMG4: Data,+ patchedComponent: Data,+ expectedFourcc: String) throws -> Data? {let container = try Container(prebootIMG4)guard container.isIMG4 else {throw PatcherError.invalidFormat("the Preboot kernelcache is a bare IM4P; expected an IMG4 with a manifest")}- let sourceIM4P = try Container(patchedKernelcache).im4pBytes+ let sourceIM4P = try Container(patchedComponent).im4pByteslet targetFourcc = try IM4P(container.im4pBytes).fourcclet sourceFourcc = try IM4P(sourceIM4P).fourcc- guard targetFourcc == "krnl", sourceFourcc == "krnl" else {+ guard targetFourcc == expectedFourcc, sourceFourcc == expectedFourcc else {throw PatcherError.invalidFormat(- "kernelcache fourcc mismatch: Preboot '\(targetFourcc)', source '\(sourceFourcc)' — expected 'krnl'",+ "firmware fourcc mismatch: Preboot '\(targetFourcc)', source '\(sourceFourcc)' — expected '\(expectedFourcc)'",)}guard container.im4pBytes != sourceIM4P else { return nil }diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swiftindex 42c9aaee..c5cbb79e 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift@@ -40,6 +40,7 @@ public enum FirmwareGuestSystemPatchSet {/// Replaces the restored System volume with an Apple TV 4K userland/// staged from its OTA. Research only: no IPSW exists for that device.public static let tvOTAUserland = "system-tv-exp-ota_userland"+ public static let otaUserland = "system-exp-ota_userland"private static let ios27 = VPhonePatchApplicability(iOSBase: .major(27))@@ -64,6 +65,13 @@ public enum FirmwareGuestSystemPatchSet {name: "Guest System",summary: "Shared-cache policy gates, patched system daemons and the vphone guest payload",patches: [+ VPhonePatchDeclaration(+ identifier: otaUserland,+ title: "Full OTA system update",+ summary: "Experimental: replaces the System volume from a staged full OTA, retaining Data, xART, NVRAM and SEPStorage. Requires a stopped disk/SEP/NVRAM snapshot and a prepared target; installs the target kernelcache and TXM in the same transaction. Use fw ota to verify migration and roll back.",+ target: .guestFile(path: "/"),+ applicability: ios27,+ ),VPhonePatchDeclaration(identifier: tvTPRO,title: "TV TPRO feature detection",diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swiftindex fbf6d95e..408126c8 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift@@ -61,6 +61,7 @@ public enum FirmwarePatchSetCatalog {Set(FirmwareKernelFridaPatchSet.manifest.patches.map(\.identifier)).union(hypervisorConcealmentPatches).union(experimentalIdentityPatches)+ .union([FirmwareGuestSystemPatchSet.otaUserland]).union([FirmwareKernelCustomFirmwarePatchSet.tvTPROPagers, misTrustAuthPatch, FirmwareGuestSystemPatchSet.settingsRootRows, FirmwareGuestSystemPatchSet.settingsSoftwareUpdate, FirmwareGuestSystemPatchSet.tvTPRO, FirmwareGuestSystemPatchSet.tvOTAUserland])/// ProMotion: the 120 Hz timing for the paravirtual display.diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareKernelcacheSwapTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareKernelcacheSwapTests.swiftindex 72dd361a..e33051b5 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareKernelcacheSwapTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareKernelcacheSwapTests.swift@@ -77,6 +77,25 @@ struct CustomFirmwareKernelcacheSwapTests {}}+ @Test+ func `a TXM update keeps its personalized manifest and rejects a wrong component`() throws {+ let manifest = Data(repeating: 7, count: 96)+ let old = try im4p("trxm", [1, 2, 3, 4])+ let new = try im4p("trxm", [5, 6, 7, 8])+ let preboot = img4(im4p: old, manifest: manifest)+ let updated = try #require(try CustomFirmwarePostRestoreDeviceTree.firmwareReplacingPayload(+ prebootIMG4: preboot, patchedComponent: new, expectedFourcc: "trxm"+ ))+ let children = try DERTestEncoder.children(of: updated)+ #expect(children[1] == new)+ #expect(children[2] == DERTestEncoder.element(tag: 0xA0, value: manifest))+ #expect(throws: PatcherError.self) {+ _ = try CustomFirmwarePostRestoreDeviceTree.firmwareReplacingPayload(+ prebootIMG4: preboot, patchedComponent: im4p("krnl", [5]), expectedFourcc: "trxm"+ )+ }+ }+@Testfunc `a bare IM4P target is refused`() throws {let bare = try im4p("krnl", [1, 2, 3, 4])diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex ba10510a..d6df9578 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -180,7 +180,7 @@ struct VPhoneCustomFirmwareInstaller {.map { Set($0.patches) }// The kernel patches the restore or the last `cfw update-kernel` put in// this VM's kernelcache, which decide the shared region size below.- let receiptKernel = receipt?.parts[VPhoneVirtualMachinePatchReceipt.part(for: .firmware(.kernelcache))]+ var receiptKernel = receipt?.parts[VPhoneVirtualMachinePatchReceipt.part(for: .firmware(.kernelcache))].map { Set($0.patches) }let guestTargets = FirmwareGuestPatchResolution.guestTargetIdentifierslet effectiveEnabled = Set(plan?.enabledPatches ?? [])@@ -202,9 +202,32 @@ struct VPhoneCustomFirmwareInstaller {let device = configuredGuestDevice(in: bundleDirectory) ?? guestDevice(of: restore)// Research: an Apple TV 4K userland staged from its OTA, which// `system-tv-exp-ota_userland` puts in place of the restored one.- let otaUserland = device.family == .appleTV && (try? bundleDirectory.isDirectory(VPhoneOTAArchive.userlandDirectoryName)) == true+ let hasOTAUserland = (try? bundleDirectory.isDirectory(VPhoneOTAArchive.userlandDirectoryName)) == true+ let isOTAUpdate = device.family != .appleTV && mode == .full && hasOTAUserland+ && effectiveEnabled.contains(FirmwareGuestSystemPatchSet.otaUserland)+ let otaUserland = (device.family == .appleTV || isOTAUpdate) && hasOTAUserland? try bundleDirectory.directory(VPhoneOTAArchive.userlandDirectoryName): nil+ if isOTAUpdate {+ guard let otaUserland, let restore, let plan else {+ throw ValidationError("A full OTA update needs staged userland and a target firmware plan.")+ }+ try requireOTAUpdate(ota: otaUserland, restore: restore, plan: plan, device: device)+ // System, kernel and TXM are published together on the same private+ // clone. Never require a separately bootable half-updated disk.+ receiptKernel = Set(plan.enabledPatches)+ let snapshots = try bundleDirectory.directory(VPhoneMachineSnapshots.directoryName)+ let saved = try snapshots.entries().contains { name in+ guard (try? snapshots.isDirectory(name)) == true,+ let data = try? snapshots.readData("\(name)/Snapshot.plist"),+ let metadata = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any],+ let files = metadata["Files"] as? [String] else { return false }+ return ["Disk.img", "SEPStorage", "nvram.bin"].allSatisfy {+ files.contains($0) && (try? snapshots.isRegularFile("\(name)/\($0)")) == true+ }+ }+ guard saved else { throw ValidationError("OTA update needs a stopped disk/SEP/NVRAM snapshot.") }+ }if device.family == .appleTV {guard let plan else {throw ValidationError("tvOS installation needs an explicit patch plan. Resolve a TV selection with `fw set-patches` and `fw patch` first.")@@ -240,6 +263,9 @@ struct VPhoneCustomFirmwareInstaller {// and a failed install leaves the original untouched.let image: URLlet cloned = try work.directory.clone(disk, to: "Disk.img")+ if isOTAUpdate, !cloned {+ throw ValidationError("The OTA update needs a private APFS disk clone; the original disk was left untouched.")+ }if device.family == .appleTV {// A paired dyld edit must never fall back to mutating the live disk.// Its errors propagate below, so this clone is committed only after@@ -366,6 +392,17 @@ struct VPhoneCustomFirmwareInstaller {// TV installs deliberately omit vphoned and its launchd backup.let wasInstalled = hasLaunchdBackup || (device.family == .appleTV && receiptGuest != nil)priorGuest = receiptGuest ?? (wasInstalled ? priorFallback : [])+ if isOTAUpdate {+ guard wasInstalled, let otaUserland else {+ throw ValidationError("An OTA update needs an installed guest and staged userland.")+ }+ // All original System bytes disappear. Old receipts and .bak files+ // must not make the new cache skip patches shared with the old OS.+ try replaceOTAUserland(system: systemRoot, ota: otaUserland, work: work)+ guard let restore else { throw ValidationError("OTA target restore tree is missing.") }+ try stageOTASystemApps(restore: restore, system: systemRoot, work: work, owner: callerUID)+ priorGuest = []+ }switch mode {case .kernelUpdate:break // handled by runKernelUpdate, never reached here@@ -385,7 +422,9 @@ struct VPhoneCustomFirmwareInstaller {priorGuest: priorGuest,kernelPatches: receiptKernel,environmentOnly: false,+ strict: isOTAUpdate,)+ if isOTAUpdate { liveGuest.insert(FirmwareGuestSystemPatchSet.otaUserland) }case .environmentOnly:// Evidence a full install ran: nothing to update over otherwise.guard wasInstalled else {@@ -429,6 +468,7 @@ struct VPhoneCustomFirmwareInstaller {includeIdentity: mode == .full,buildVersion: buildVersion,boardDeviceTree: boardDeviceTree,+ otaRestore: isOTAUpdate ? restore : nil,))// Selected patches this guest has nothing for, so the receipt does not// report them as missing forever: the board audio repair on an@@ -459,7 +499,7 @@ struct VPhoneCustomFirmwareInstaller {systemMounted = false_ = try tool("/usr/sbin/diskutil", ["eject", baseDisk], quiet: true)diskAttached = false- if mode == .full {+ if mode == .full, !isOTAUpdate {if cloned {try VPhoneAPFSSnapshot.rename(imageAt: image)} else {@@ -473,6 +513,12 @@ struct VPhoneCustomFirmwareInstaller {try work.directory.setMode("Disk.img", disk.mode & 0o777)try work.directory.rename("Disk.img", to: "Disk.img", in: bundleDirectory)}+ if isOTAUpdate {+ recordKernelcacheReceipt(enabled: effectiveEnabled, in: bundleDirectory,+ owner: invokingUser.map { ($0.uid, $0.gid) })+ recordKernelcacheReceipt(enabled: effectiveEnabled, in: bundleDirectory,+ owner: invokingUser.map { ($0.uid, $0.gid) }, component: .txm)+ }// A serial-only research selection can leave vphoned off. Its host// copy exists only after installVphoned staged it successfully.if try work.directory.isRegularFile("vphoned") {@@ -770,18 +816,19 @@ struct VPhoneCustomFirmwareInstaller {enabled: Set<String>,in bundleDirectory: VPhoneConfinedDirectory,owner: (uid: uid_t, gid: gid_t)?,+ component: VPhoneFirmwareComponent = .kernelcache,) {let kernelPatches = FirmwarePatchSetCatalog.allDeclarations- .filter { $0.target == .firmware(.kernelcache) && enabled.contains($0.identifier) }+ .filter { $0.target == .firmware(component) && enabled.contains($0.identifier) }.map(\.identifier)do {var receipt = (try? bundleDirectory.readData(VPhonePatchPresetStore.receiptFileName)).flatMap { try? VPhoneVirtualMachinePatchReceipt.decode($0) }?? VPhoneVirtualMachinePatchReceipt()receipt.record(- VPhoneFirmwareComponent.kernelcache.rawValue,+ component.rawValue,patches: kernelPatches,- writer: "cfw update-kernel",+ writer: component == .kernelcache ? "cfw update-kernel" : "cfw install (full OTA)",bundleVersion: bundleVersion,)try bundleDirectory.writeFile(@@ -1077,6 +1124,7 @@ struct VPhoneCustomFirmwareInstaller {priorGuest: Set<String>,kernelPatches: Set<String>?,environmentOnly: Bool,+ strict: Bool = false,) throws -> Set<String> {var live = Set<String>()var failures: [String] = []@@ -1169,9 +1217,17 @@ struct VPhoneCustomFirmwareInstaller {live.insert(identifier)}}+ if priorGuest.contains(FirmwareGuestSystemPatchSet.otaUserland) {+ // A checkbox cannot put a previous OS back. Only the stopped+ // disk/SEP/NVRAM snapshot can reverse a completed system update.+ live.insert(FirmwareGuestSystemPatchSet.otaUserland)+ if !on(FirmwareGuestSystemPatchSet.otaUserland) {+ print(" [!] full OTA System update is not reverted by deselection; restore the stopped machine snapshot to roll back")+ }+ }if let restore {- try installCryptexes(restore: restore, system: system, work: work, owner: owner)+ try installCryptexes(restore: restore, system: system, work: work, owner: owner, replaceExisting: strict)}let version = try productVersion(system: system)@@ -1624,6 +1680,9 @@ struct VPhoneCustomFirmwareInstaller {if !failures.isEmpty {print("[!] \(failures.count) guest patch(es) failed and were left in their prior state: \(Set(failures).sorted().joined(separator: ", "))")+ if strict {+ throw ValidationError("OTA compatibility patches failed; the private disk clone was discarded: \(Set(failures).sorted().joined(separator: ", "))")+ }}return live}@@ -1856,13 +1915,14 @@ struct VPhoneCustomFirmwareInstaller {system: VPhoneConfinedDirectory,work: WorkDirectory,owner: uid_t?,+ replaceExisting: Bool = false,) throws {let os = "System/Cryptexes/OS"let app = "System/Cryptexes/App"func populated(_ path: String) -> Bool {(try? system.directory(path).entries().isEmpty) == false}- if !(populated(os) && populated(app)) {+ if replaceExisting || !(populated(os) && populated(app)) {let manifest = work.file("iPhone-BuildManifest.plist")try restore.readData("iPhone-BuildManifest.plist").write(to: manifest)guard case let .cryptex(paths) = try CustomFirmwareDaemons.filesystemLayout(buildManifest: manifest) else {@@ -1932,6 +1992,55 @@ struct VPhoneCustomFirmwareInstaller {)}+ /// Full OTA chunks contain placeholders, not the removable apps retained+ /// on encrypted Data. Stage target programs from the pinned IPSW's OS+ /// image; vphoned reconciles only already-installed Apple apps after boot.+ private func stageOTASystemApps(+ restore: VPhoneConfinedDirectory, system: VPhoneConfinedDirectory,+ work: WorkDirectory, owner: uid_t?+ ) throws {+ guard let manifest = try PropertyListSerialization.propertyList(+ from: restore.readData("iPhone-BuildManifest.plist"), format: nil) as? [String: Any],+ let identities = manifest["BuildIdentities"] as? [[String: Any]] else {+ throw ValidationError("OTA target OS manifest is invalid.")+ }+ let updatePaths = identities.compactMap { identity -> String? in+ guard (identity["Info"] as? [String: Any])?["RestoreBehavior"] as? String == "Update" else { return nil }+ let os = (identity["Manifest"] as? [String: Any])?["OS"] as? [String: Any]+ return (os?["Info"] as? [String: Any])?["Path"] as? String+ }+ let paths = Set(updatePaths)+ guard paths.count == 1, let path = paths.first else {+ throw ValidationError("OTA target has no unique OS image for system-app migration.")+ }+ let image = try stageCryptexImage(path, from: restore, as: "OTA-OS-source.dmg", work: work, owner: owner)+ var plain = image+ if try VPhoneRestoreOperations.isAEAEncrypted(image) {+ plain = work.file("OTA-OS.dmg")+ let key = try vphoneRunBlocking { try await VPhoneAEA.symmetricKey(of: image) }+ try tool("/usr/bin/aea", ["decrypt", "-i", image.path, "-o", plain.path, "-key-value", key], quiet: true)+ }+ let mount = work.file("mnt-ota-apps")+ _ = try work.directory.directory("mnt-ota-apps", create: true, mode: 0o700)+ try attachCryptex(plain, at: mount)+ var attached = true+ defer { if attached { try? detachImage(at: mount) } }+ // Scoped so the volume's directory descriptors close before detach.+ do {+ let root = try work.directory.mountedVolume("mnt-ota-apps")+ let apps = try root.directory("private/var/staged_system_apps")+ guard !(try apps.entries()).isEmpty else { throw ValidationError("Target OS has no staged system apps.") }+ let destination = "usr/local/share/vphone-ota/apps"+ try system.removeItem(destination)+ try system.copyTree(from: apps, to: destination, owner: Self.guestOwner, clearSetID: false)+ try system.writeFile("usr/local/share/vphone-ota/Upgrade.plist",+ contents: system.readData(".vphone-ota-upgrade.plist"), mode: 0o644, owner: Self.guestOwner)+ }+ try detachImage(at: mount)+ attached = false+ print(" [+] OTA target system-app programs staged; encrypted Data was not mounted")+ }+/// Open a manifest-named image inside the restore tree without following/// a link, require a single-link regular file owned by the caller, and/// clone (or, across volumes, copy) that very descriptor into the work@@ -2002,21 +2111,71 @@ struct VPhoneCustomFirmwareInstaller {}}+ /// The staged OTA, the configured device and the patched target firmware+ /// must all name the same 27.x build before System is replaced.+ private func requireOTAUpdate(+ ota: VPhoneConfinedDirectory,+ restore: VPhoneConfinedDirectory,+ plan: VPhoneVirtualMachinePatchPlan,+ device: VPhoneGuestDevice+ ) throws {+ guard let metadata = try PropertyListSerialization.propertyList(from: ota.readData("Upgrade.plist"), format: nil) as? [String: String],+ metadata["Device"] == device.productType,+ metadata["Version"] == plan.iOSBaseVersion,+ metadata["Version"]?.hasPrefix("27.") == true,+ let target = try PropertyListSerialization.propertyList(from: restore.readData("iPhone-BuildManifest.plist"), format: nil) as? [String: Any],+ metadata["Build"] == target["ProductBuildVersion"] as? String else {+ throw ValidationError("The staged OTA, configured device and target IPSW/patch plan disagree. Run fw ota-stage with the matching full OTA.")+ }+ guard try restore.isRegularFile("kernelcache.research.vphone600") else {+ throw ValidationError("The target has no patched kernelcache. Run fw patch before installing the OTA.")+ }+ }++ /// Host-driven full OTA payload installation. The container, Data, User,+ /// xART, SEPStorage, NVRAM and Preboot identity stay with this guest.+ private func replaceOTAUserland(+ system: VPhoneConfinedDirectory,+ ota: VPhoneConfinedDirectory,+ work: WorkDirectory+ ) throws {+ let metadata = try ota.readData("Upgrade.plist")+ // The existing installer treats this as a per-machine preference.+ // Carry it across System replacement; never reuse patched binaries or+ // their backups from the previous OS.+ let misfix = try system.isRegularFile("usr/lib/libmisfix.plist")+ ? try system.readData("usr/lib/libmisfix.plist") : nil+ try replaceTVUserland(system: system, ota: ota, work: work,+ identifier: FirmwareGuestSystemPatchSet.otaUserland)+ guard let expected = try PropertyListSerialization.propertyList(from: metadata, format: nil) as? [String: String],+ let actual = try PropertyListSerialization.propertyList(from: system.readData("System/Library/CoreServices/SystemVersion.plist"), format: nil) as? [String: Any],+ expected["Build"] == actual["ProductBuildVersion"] as? String,+ expected["Version"] == actual["ProductVersion"] as? String else {+ throw ValidationError("The extracted OTA SystemVersion does not match the staged update. The private disk clone was discarded.")+ }+ if let misfix {+ try system.writeFile("usr/lib/libmisfix.plist", contents: misfix, mode: 0o644, owner: Self.guestOwner)+ }+ try system.writeFile(".vphone-ota-upgrade.plist", contents: metadata, mode: 0o644, owner: Self.guestOwner)+ }+/// Research: put an Apple TV 4K userland in place of the restored Apple TV/// HD one. `ota` holds the OTA's raw `payloadv2/payload.NNN` chunks and/// `payload_chunks.txt`; each chunk is an Apple Archive, which `aa` extracts/// as root with the owners, modes, BSD flags and APFS compression the OTA/// records. The chunk list is kept on the volume so an environment update- /// does not extract the same userland again.+ /// does not extract the same userland again. A full iOS OTA update reuses+ /// this extraction under its own `identifier`, adding `links.txt`.private func replaceTVUserland(system: VPhoneConfinedDirectory,ota: VPhoneConfinedDirectory,work: WorkDirectory,+ identifier: String = FirmwareGuestSystemPatchSet.tvOTAUserland,) throws {- let identifier = FirmwareGuestSystemPatchSet.tvOTAUserlandlet marker = ".vphone-ota-userland"let chunkList = try ota.readData(VPhoneOTAArchive.chunkListName)- if try system.isRegularFile(marker), try system.readData(marker) == chunkList {+ if identifier == FirmwareGuestSystemPatchSet.tvOTAUserland,+ try system.isRegularFile(marker), try system.readData(marker) == chunkList {print(" [·] \(identifier): userland already in place")return}@@ -2032,6 +2191,22 @@ struct VPhoneCustomFirmwareInstaller {try work.directory.removeItem(chunk)try ota.copyFile(from: chunk, to: chunk, in: work.directory)}+ let linkList: Data?+ if try ota.isRegularFile(VPhoneOTAArchive.hardLinkListName) {+ try ota.copyFile(from: VPhoneOTAArchive.hardLinkListName,+ to: VPhoneOTAArchive.hardLinkListName, in: work.directory)+ linkList = try work.directory.readData(VPhoneOTAArchive.hardLinkListName)+ } else {+ linkList = nil+ }+ if identifier == FirmwareGuestSystemPatchSet.otaUserland {+ // Root extracts only pinned private copies. Reject traversal and+ // any later member beneath an archive-created symlink first.+ guard let linkList else {+ throw ValidationError("The full OTA has no links.txt. Stage the complete OTA before installing.")+ }+ try VPhoneOTAArchive.validatePayloadPaths(chunks.map { work.file($0) }, hardLinks: linkList)+ }print(" [*] \(identifier): replacing the System volume with \(chunks.count) OTA payload chunks")for entry in try system.entries() {_ = try system.removeItem(entry)@@ -2041,6 +2216,11 @@ struct VPhoneCustomFirmwareInstaller {_ = try tool("/usr/bin/aa", ["extract", "-d", root, "-i", work.file(chunk).path])try work.directory.removeItem(chunk)}+ if let linkList {+ let count = try VPhoneOTAArchive.installHardLinks(linkList, in: system)+ print(" [+] \(identifier): installed \(count) OTA hard links")+ try work.directory.removeItem(VPhoneOTAArchive.hardLinkListName)+ }try system.writeFile(marker, contents: chunkList, mode: 0o644, owner: Self.guestOwner)print(" [+] \(identifier): userland extracted")}@@ -2269,6 +2449,7 @@ struct VPhoneCustomFirmwareInstaller {includeIdentity: Bool,buildVersion: String?,boardDeviceTree: URL?,+ otaRestore: VPhoneConfinedDirectory? = nil,) throws -> Set<String> {var live = Set<String>()// Whether a device-tree patch is enabled. A VM with no plan gets every@@ -2321,7 +2502,7 @@ struct VPhoneCustomFirmwareInstaller {let mayRevertRepair = repairGroup.contains { !enabled($0.id) && priorGuest.contains($0.id) }let wantsBuild = (buildVersion.map { !$0.isEmpty } ?? false) && enabled(buildID)let touchesBuild = wantsBuild || priorGuest.contains(buildID)- guard rewriteIdentity || !repairsOn.isEmpty || mayRevertRepair || touchesBuild else { return live }+ guard otaRestore != nil || rewriteIdentity || !repairsOn.isEmpty || mayRevertRepair || touchesBuild else { return live }guardlet preboot = volumes.first(where: { ($0["Roles"] as? [String])?.contains("Preboot") == true }),@@ -2350,6 +2531,50 @@ struct VPhoneCustomFirmwareInstaller {throw ValidationError("Expected one device tree in the Preboot volume but found \(candidates.count). Restore the VM, then install CFW again.")}+ if let otaRestore {+ /// Swap only the IM4P inside a personalized Preboot IMG4,+ /// keeping its manifest, mode and owner.+ func replacePayload(_ path: String, _ meta: stat, patched: Data, fourcc: String, label: String) throws {+ guard let updated = try CustomFirmwarePostRestoreDeviceTree.firmwareReplacingPayload(+ prebootIMG4: root.readData(path), patchedComponent: patched, expectedFourcc: fourcc+ ) else { return }+ let staged = work.file("\(fourcc).new")+ try updated.write(to: staged)+ try root.replaceFile(path, fromFileAt: staged, mode: meta.st_mode & 0o7777, owner: (meta.st_uid, meta.st_gid))+ print(" [+] OTA Preboot \(label) updated; personalized manifest retained")+ }+ let kernels = try root.entries().compactMap { name -> String? in+ let path = "\(name)/System/Library/Caches/com.apple.kernelcaches/kernelcache"+ return (try? root.isDirectory(name)) == true && (try? root.isRegularFile(path)) == true ? path : nil+ }+ guard kernels.count == 1, let kernelPath = kernels.first,+ let meta = try root.status(kernelPath), meta.st_mode & S_IFMT == S_IFREG else {+ throw ValidationError("OTA guest has no unique regular Preboot kernelcache.")+ }+ try replacePayload(kernelPath, meta, patched: otaRestore.readData("kernelcache.research.vphone600"),+ fourcc: "krnl", label: "kernelcache")+ // iOS 27 needs TXM's pre-check admission in addition to its+ // kernel changes. Keep the original personalized container.+ let component = "Ap,TrustedExecutionMonitor"+ guard let manifest = try PropertyListSerialization.propertyList(from: otaRestore.readData("BuildManifest.plist"), format: nil) as? [String: Any],+ let identities = manifest["BuildIdentities"] as? [[String: Any]] else {+ throw ValidationError("OTA target has no boot manifest.")+ }+ let sources = Set(identities.compactMap { identity -> String? in+ let entry = (identity["Manifest"] as? [String: Any])?[component] as? [String: Any]+ return (entry?["Info"] as? [String: Any])?["Path"] as? String+ })+ guard sources.count == 1, let source = sources.first else {+ throw ValidationError("OTA target has no unique TXM component.")+ }+ let bootFolder = String(deviceTree.prefix { $0 != "/" })+ let path = "\(bootFolder)/usr/standalone/firmware/FUD/\(component).img4"+ guard let meta = try root.status(path), meta.st_mode & S_IFMT == S_IFREG else {+ throw ValidationError("OTA guest has no regular Preboot TXM.")+ }+ try replacePayload(path, meta, patched: otaRestore.readData(source), fourcc: "trxm", label: "TXM")+ }+try buildDeviceTree(deviceTree, in: root, work: work,rewriteIdentity: rewriteIdentity, identity: identity,diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swiftindex b34444b7..f04f9cb0 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift@@ -12,6 +12,9 @@ struct VPhoneFirmwareCommand: ParsableCommand {subcommands: [VPhoneFirmwareCatalogCommand.self,VPhoneFirmwareInspectCommand.self,+ VPhoneFirmwareOTAStageCommand.self,+ VPhoneFirmwareOTAPreflightCommand.self,+ VPhoneFirmwareOTACommand.self,VPhoneFirmwarePrepareCommand.self,VPhoneFirmwarePatchCommand.self,VPhoneFirmwarePatchesCommand.self,diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareOTACommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareOTACommand.swiftnew file mode 100644index 00000000..8bdc5d79--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareOTACommand.swift@@ -0,0 +1,404 @@+import ArgumentParser+import Darwin+import FirmwarePatcher+import Foundation+import VPhoneArchiveKit+import VPhoneCoreKit+import VPhonePatchKit++/// Durable phases for Launchpad and other coordinators. Privilege remains in+/// the existing cfw install helper; this command never obtains root or restores+/// a guest. Starting/stopping is the coordinator's responsibility.+struct VPhoneFirmwareOTACommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "ota",+ abstract: "Checkpoint, prepare, verify or roll back a data-preserving full OTA",+ discussion: """+ Sequence: capture (running), checkpoint (stopped), quiesce (running),+ prepare (stopped), cfw install (stopped, existing root helper), then+ complete (running). rollback requires a stopped machine and restores+ disk/SEP/NVRAM plus host configuration. A journal and one APFS snapshot+ are retained. Memory and network settings are preserved.+ """+ )++ enum Action: String, ExpressibleByArgument {+ case capture, checkpoint, isolate, quiesce, prepare, complete, commit, verify, rollback, status+ }+ @OptionGroup var lib: VPhoneLibraryOption+ @Argument var action: Action+ @Argument var name: String+ @Option(help: "Pinned target build (capture; default 24A446)") var build: String?+ @Option(help: "Pinned target version (capture; default 27.0.1)") var version: String?+ @Option(name: .customLong("app"), help: "Protect this app's bundle, data and group containers (repeatable)")+ var apps: [String] = []+ @Option(help: "Target device IPSW, local path or HTTPS URL (prepare)") var iphoneSource: String?+ @Option(help: "Source-compatible cloudOS IPSW (prepare)") var cloudosSource: String?+ @Option(help: "Full OTA archive, local path or HTTPS URL (prepare)") var source: String?+ @Option(help: "Public AEA symmetric key; not persisted") var key: String?+ @Option(help: "Coordinator operation ID; every phase must match the captured owner") var operationID: String?+ @Flag(help: "Allow rollback of even a completed update, discarding subsequent guest writes") var force = false+ @Flag(help: "Explicitly discard writes after networking resumed; only for manual recovery with --force") var discardOnlineWrites = false++ func run() throws {+ setvbuf(stdout, nil, _IOLBF, 0)+ let bundle = try lib.library.bundle(named: name)+ if let operationID {+ guard !operationID.isEmpty, operationID.count <= 64,+ operationID.unicodeScalars.allSatisfy(CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-_")).contains) else {+ throw ValidationError("Invalid coordinator operation ID.")+ }+ }+ try VPhoneOTAUpdate.withLock(of: bundle) {+ if action != .capture {+ try VPhoneOTAUpdate.requireOperation(operationID, record: VPhoneOTAUpdate.read(of: bundle))+ }+ switch action {+ case .capture: try capture(bundle)+ case .checkpoint: try VPhoneOTAUpdate.checkpoint(of: bundle)+ case .isolate: try VPhoneOTAUpdate.isolateNetwork(of: bundle)+ case .quiesce: try quiesce(bundle)+ case .prepare: try prepare(bundle)+ case .complete: try complete(bundle)+ case .commit: try VPhoneOTAUpdate.commit(of: bundle)+ case .verify: try verifyCommitted(bundle)+ case .rollback:+ if try VPhoneOTAUpdate.read(of: bundle).phase == .completed, !force {+ throw ValidationError("Completed OTA rollback discards later guest writes; pass --force to request it explicitly.")+ }+ guard !discardOnlineWrites || force else { throw ValidationError("--discard-online-writes also requires --force.") }+ try VPhoneOTAUpdate.rollback(of: bundle, discardOnlineWrites: discardOnlineWrites)+ case .status: break+ }+ let record = try VPhoneOTAUpdate.read(of: bundle)+ let result: [String: Any] = [+ "machine": name, "phase": record.phase.rawValue,+ "version": record.targetVersion, "build": record.targetBuild,+ "snapshot": record.snapshot, "journal": VPhoneOTAUpdate.directory(of: bundle).path,+ "operation_id": record.operationID.map { $0 as Any } ?? NSNull(),+ ]+ print(String(decoding: try JSONSerialization.data(withJSONObject: result, options: [.sortedKeys]), as: UTF8.self))+ }+ }++ private func call(_ bundle: VPhoneBundle, _ method: String, _ params: [String: Any] = [:], timeout: Int = 30) throws -> [String: Any] {+ try Self.guestCall(bundle, method, params, timeout: timeout, note: "Its OTA checkpoint is retained.")+ }++ /// One vphoned RPC over the VM process's control socket; `note` ends+ /// every error so the caller can say what state was left behind.+ static func guestCall(_ bundle: VPhoneBundle, _ method: String, _ params: [String: Any] = [:],+ timeout: Int = 30, note: String) throws -> [String: Any] {+ do {+ return try VPhoneHostAutomationProbe.rpc(method, params: params,+ socketPath: bundle.url.appendingPathComponent("vphone.sock").path,+ timeout: timeout)+ } catch let error as VPhoneGuestCallError {+ let outcome = error.kind == .refused ? "Guest refused \(method)" : "Guest did not complete \(method)"+ throw ValidationError("\(outcome): \(error.message). \(note)")+ }+ }++ private func sourceState(_ record: VPhoneOTAUpdate.Record) throws -> [String: Any] {+ guard let state = try JSONSerialization.jsonObject(with: record.source) as? [String: Any] else {+ throw ValidationError("Invalid OTA source state.")+ }+ return state+ }++ /// The only target this path is qualified for; --version/--build default to it.+ static let qualifiedVersion = "27.0.1"+ static let qualifiedBuild = "24A446"++ private func capture(_ bundle: VPhoneBundle) throws {+ let build = build ?? Self.qualifiedBuild+ let version = version ?? Self.qualifiedVersion+ // An engine retry has the same operation ID. Reuse its source record,+ // never recapture a quiesced or partly migrated guest as the source.+ if let operationID, let existing = try? VPhoneOTAUpdate.read(of: bundle),+ existing.operationID == operationID, existing.targetBuild == build,+ existing.targetVersion == version, existing.phase != .rolledBack {+ return+ }+ guard version == Self.qualifiedVersion, build == Self.qualifiedBuild,+ let device = VPhoneGuestDevice.named(bundle.manifest.guestProductType ?? ""),+ device.family == .iPhone || device.family == .iPad else {+ throw ValidationError("This OTA path is qualified only for iPhone/iPad \(Self.qualifiedVersion) (\(Self.qualifiedBuild)).")+ }+ let info = try call(bundle, "device.info")+ guard info["model"] as? String == device.productType,+ (info["ios_version"] as? String)?.hasPrefix("26.") == true else {+ throw ValidationError("Capture needs a responsive configured iPhone/iPad on iOS 26.")+ }+ let setup = try call(bundle, "setup.status")+ let migration = try call(bundle, "settings.get", ["domain": "com.apple.migration"])+ guard Self.sourceFinishedMigration(setup: setup, migration: migration) else {+ throw ValidationError("The source guest has not successfully finished migration and Setup Assistant.")+ }+ let profile = try call(bundle, "services.profile")+ let disabled = try call(bundle, "services.disabled")+ try requireMigrationServices(profile: profile, disabled: disabled)+ let autoLock = try call(bundle, "display.auto_lock")+ guard autoLock["auto_lock_seconds"] as? Int != nil else {+ throw ValidationError("Cannot capture the source Auto-Lock policy.")+ }+ var protected: [[String: Any]] = []+ for id in Set(apps).sorted() {+ let app = try call(bundle, "apps.info", ["bundle_id": id])+ let entitlements = app["entitlements"] as? [String: Any] ?? [:]+ guard app["bundle_id"] as? String == id, let dataPath = app["data_path"] as? String else {+ throw ValidationError("\(id) has no data container to protect.")+ }+ // 27 selects the data container by this entitlement, not by the+ // signing identifier 26 used. It must name the existing container,+ // which for a legacy re-signed app is not its bundle ID.+ let metadata = try call(bundle, "files.plist", ["path": dataPath + "/.com.apple.mobile_container_manager.metadata.plist"])+ let container = (metadata["plist"] as? [String: Any])?["MCMMetadataIdentifier"] as? String+ guard let required = entitlements["com.apple.private.security.container-required"] as? String,+ !required.isEmpty, required == container else {+ throw ValidationError("\(id) lacks a container-required entitlement naming its existing data container (\(container ?? "unknown")). Normalize its signing policy before OTA; no app is silently re-signed.")+ }+ protected.append(app)+ }+ let restore = try JSONSerialization.jsonObject(with: Data(contentsOf: bundle.url.appendingPathComponent("restore-info.json")))+ let state: [String: Any] = ["device": info, "profile": profile, "auto_lock": autoLock,+ "apps": protected, "restore": restore]+ var record = VPhoneOTAUpdate.Record(bundle: bundle, build: build, version: version,+ source: try JSONSerialization.data(withJSONObject: state, options: [.sortedKeys]))+ record.operationID = operationID+ try VPhoneOTAUpdate.capture(record, of: bundle)+ }++ private func quiesce(_ bundle: VPhoneBundle) throws {+ var record = try VPhoneOTAUpdate.read(of: bundle)+ guard record.phase == .checkpointed || record.phase == .quiesced else {+ throw ValidationError("Quiesce needs a completed stopped checkpoint first.")+ }+ guard record.networkIsolated == true, bundle.manifest.networkConfig.mode == .off else {+ throw ValidationError("Stop the source and run fw ota isolate before quiescing it.")+ }+ let source = try sourceState(record)+ let old = source["device"] as? [String: Any] ?? [:]+ let current = try call(bundle, "device.info")+ guard current["ios_version"] as? String == old["ios_version"] as? String else {+ throw ValidationError("The source OS changed since capture.")+ }+ let result = try call(bundle, "services.profile.apply", ["profile": "none", "force": true])+ guard (result["failed"] as? [[String: Any]])?.isEmpty == true else {+ throw ValidationError("Could not re-enable every profile-owned migration dependency; roll back the checkpoint.")+ }+ let profile = try call(bundle, "services.profile")+ try requireMigrationServices(profile: profile, disabled: call(bundle, "services.disabled"))+ record.phase = .quiesced+ try VPhoneOTAUpdate.write(record, of: bundle)+ }++ private func prepare(_ original: VPhoneBundle) throws {+ guard let iphoneSource, let cloudosSource, let source else {+ throw ValidationError("prepare requires --iphone-source, --cloudos-source and --source (full OTA).")+ }+ let record = try VPhoneOTAUpdate.read(of: original)+ if record.phase == .prepared { return }+ guard record.networkIsolated == true, original.manifest.networkConfig.mode == .off else {+ throw ValidationError("OTA preparation requires the saved source network to remain isolated.")+ }+ let state = try sourceState(record)+ let restore = state["restore"] as? [String: Any] ?? [:]+ let cloud = restore["cloudOS"] as? [String: String] ?? [:]+ let resolved = try VPhoneFirmwarePreparer.resolveSources(iPhoneSource: iphoneSource, cloudOSSource: cloudosSource,+ device: original.manifest.guestProductType)+ guard resolved.phone.build == record.targetBuild, resolved.phone.version == record.targetVersion,+ resolved.cloud.build == cloud["build"], resolved.cloud.version == cloud["version"] else {+ throw ValidationError("Target IPSW must match the pinned OTA; cloudOS must remain at the source build.")+ }+ let full = try VPhoneFirmwarePreparer.resolveOTA(source, key: key, device: resolved.device,+ build: record.targetBuild,+ ipswCacheDirectory: VPhoneResources.ipswCacheDirectory(),+ downloadConnections: VPhoneIPSWCache.defaultDownloadConnections)+ try VPhoneOTAUpdate.beginPreparation(of: original)+ let resources = VPhoneResources.resolve()+ // Both ROMs load the existing guest's personalized boot/SEP firmware.+ // Their old bytes and configuration are in the OTA host checkpoint.+ var bundle = try VPhoneBundleOperations.installBootROM(from: resources.base.appendingPathComponent("OpenAVB/OpenAVB.bin"), in: original)+ bundle = try VPhoneBundleOperations.installSEPROM(from: resources.base.appendingPathComponent("OpenSEP/OpenSEP.bin"), in: bundle)+ var selection = VPhonePatchPresetStore.selection(forVM: bundle.url)+ selection.blockedPatches.removeAll { $0 == FirmwareGuestSystemPatchSet.otaUserland }+ selection.allowedPatches = Set(selection.allowedPatches + [FirmwareGuestSystemPatchSet.otaUserland]).sorted()+ try VPhonePatchPresetStore.write(selection, forVM: bundle.url)+ try VPhoneFirmwarePreparer.prepare(iPhoneSource: iphoneSource, cloudOSSource: cloudosSource,+ device: bundle.manifest.guestProductType, bundle: bundle, resources: resources)+ let libraryArguments = lib.libraryRoot.map { ["--library-root", $0] } ?? []+ // ArgumentParser's wrappers, including optional/defaulted properties,+ // are definitions until parsed; a default initializer is not a command.+ let patch = try VPhoneFirmwarePatchCommand.parse([name] + libraryArguments)+ try patch.run()+ var stageArguments = [name, "--build", record.targetBuild, "--source", full.file.path] + libraryArguments+ if let key = full.key { stageArguments += ["--key", key] }+ let stage = try VPhoneFirmwareOTAStageCommand.parse(stageArguments)+ try stage.run()+ var updated = try VPhoneOTAUpdate.read(of: bundle)+ updated.phase = .prepared+ try VPhoneOTAUpdate.write(updated, of: bundle)+ }++ private func complete(_ bundle: VPhoneBundle) throws {+ var record = try VPhoneOTAUpdate.read(of: bundle)+ guard [.prepared, .installed, .completed].contains(record.phase) else {+ throw ValidationError("No prepared OTA to verify.")+ }+ guard record.networkIsolated == true, bundle.manifest.networkConfig.mode == .off else {+ throw ValidationError("Offline verification requires the guest network to remain isolated until commit.")+ }+ let setup = try requireTargetMigration(bundle, record)+ // Never move a completed journal back: rollback of a completed update+ // must keep requiring --force when a repeated complete fails later.+ if record.phase == .prepared {+ record.phase = .installed+ try VPhoneOTAUpdate.write(record, of: bundle)+ }+ let systemApps = try call(bundle, "ota.apps.apply", ["force": true], timeout: 180)+ guard systemApps["pending"] as? Int == 0 else {+ throw ValidationError("Retained Apple app programs have not finished updating.")+ }+ let source = try sourceState(record)+ for app in source["apps"] as? [[String: Any]] ?? [] {+ guard let id = app["bundle_id"] as? String else { throw ValidationError("Invalid protected app record.") }+ try requireUnchanged(bundle, app: app, id: id, fields: ["bundle_path", "data_path", "group_containers", "version", "build"]) {+ "\(id) changed \($0) during OTA; its checkpoint is retained."+ }+ }+ if setup["pending"] as? Bool == true || setup["running"] as? Bool == true {+ _ = try call(bundle, "setup.skip", ["force": true])+ throw ValidationError("Migration succeeded; Setup Assistant was dismissed. Wait for SpringBoard, then retry complete.")+ }+ let oldLock = source["auto_lock"] as? [String: Any] ?? [:]+ guard let seconds = oldLock["auto_lock_seconds"] as? Int else {+ throw ValidationError("Source Auto-Lock was not captured.")+ }+ func autoLockRestored() throws -> Bool {+ try call(bundle, "display.auto_lock")["auto_lock_seconds"] as? Int == seconds+ }+ func requestAutoLock() throws {+ _ = try call(bundle, "display.auto_lock.set", ["seconds": seconds])+ }+ if try !autoLockRestored() {+ if record.autoLockRestorationRequested != true {+ try requestAutoLock()+ record.autoLockRestorationRequested = true+ try VPhoneOTAUpdate.write(record, of: bundle)+ }+ // profiled publishes the effective file asynchronously. The next+ // complete retries its read, never assuming a successful tap was+ // a successful policy change.+ if try !autoLockRestored(), record.autoLockRebootRequested != true {+ _ = try call(bundle, "system.reboot", ["force": true])+ record.autoLockRebootRequested = true+ try VPhoneOTAUpdate.write(record, of: bundle)+ throw ValidationError("Auto-Lock was selected but profiled had not converged; reboot requested. Retry complete after vphoned reconnects.")+ }+ if try !autoLockRestored() {+ try requestAutoLock()+ }+ guard try autoLockRestored() else {+ throw ValidationError("Settings is restoring Auto-Lock; its effective policy has not converged. Retry complete after profiled settles.")+ }+ }+ let profile = source["profile"] as? [String: Any] ?? [:]+ let saved = profile["record"] as? [String: Any] ?? [:]+ let result = try call(bundle, "services.profile.apply", [+ "profile": saved["profile"] ?? "none", "groups": saved["groups"] ?? [], "allow": saved["allow"] ?? [], "force": true,+ ])+ guard (result["failed"] as? [[String: Any]])?.isEmpty == true else {+ throw ValidationError("Migration passed but the saved service profile could not be restored.")+ }+ for app in source["apps"] as? [[String: Any]] ?? [] {+ guard let id = app["bundle_id"] as? String else { continue }+ let launched = try call(bundle, "apps.launch", ["bundle_id": id])+ guard launched["frontmost_verified"] as? Bool == true else {+ throw ValidationError("Protected app \(id) did not reach the foreground after OTA.")+ }+ }+ record.phase = .completed+ try VPhoneOTAUpdate.write(record, of: bundle)+ }++ /// The running target's version and this boot's migration result;+ /// returns setup.status, which complete still needs.+ private func requireTargetMigration(_ bundle: VPhoneBundle, _ record: VPhoneOTAUpdate.Record) throws -> [String: Any] {+ let info = try call(bundle, "device.info")+ let migration = try call(bundle, "settings.get", ["domain": "com.apple.migration"])+ let setup = try call(bundle, "setup.status")+ try VPhoneOTAUpdate.requireMigration(version: record.targetVersion, build: record.targetBuild,+ actualVersion: info["ios_version"] as? String,+ migrationDone: setup["data_migration_done"] as? Bool,+ result: Self.migrationResult(migration))+ return setup+ }++ /// The protected app's current `apps.info` must match its captured+ /// values for every field; `message` names the first that differs.+ private func requireUnchanged(_ bundle: VPhoneBundle, app: [String: Any], id: String, fields: [String],+ message: (String) -> String) throws {+ let current = try call(bundle, "apps.info", ["bundle_id": id])+ for field in fields where !NSDictionary(dictionary: ["v": current[field] ?? NSNull()])+ .isEqual(to: ["v": app[field] ?? NSNull()]) {+ throw ValidationError(message(field))+ }+ }++ static func migrationResult(_ reply: [String: Any]) -> [String: Any]? {+ let values = reply["values"] as? [String: Any]+ return (values?["DMLastMigrationResults"] as? [String: Any])?["value"] as? [String: Any]+ }++ /// The source gate shared by capture and ota-preflight: an unknown+ /// migration result is not success.+ static func sourceFinishedMigration(setup: [String: Any], migration: [String: Any]) -> Bool {+ setup["data_migration_done"] as? Bool == true+ && migrationResult(migration)?["success"] as? Bool == true+ && setup["pending"] as? Bool == false+ }++ private func verifyCommitted(_ bundle: VPhoneBundle) throws {+ let record = try VPhoneOTAUpdate.read(of: bundle)+ guard record.phase == .committed else { throw ValidationError("OTA networking has not been committed.") }+ let original = try VPhoneOTAUpdate.sourceManifest(of: bundle)+ guard bundle.manifest.networkConfig == original.networkConfig,+ bundle.manifest.cpuCount == original.cpuCount, bundle.manifest.memorySize == original.memorySize else {+ throw ValidationError("OTA changed the source network, CPU or memory configuration.")+ }+ _ = try requireTargetMigration(bundle, record)+ let state = try sourceState(record)+ for app in state["apps"] as? [[String: Any]] ?? [] {+ guard let id = app["bundle_id"] as? String else { continue }+ try requireUnchanged(bundle, app: app, id: id, fields: ["bundle_path", "data_path", "group_containers"]) {+ "Committed app \(id) changed \($0); target data was retained."+ }+ guard try call(bundle, "apps.launch", ["bundle_id": id])["frontmost_verified"] as? Bool == true else {+ throw ValidationError("Committed app \(id) could not reach the foreground; target data was retained.")+ }+ }+ }++ /// Services DataMigrator needs that a trimmed source may have disabled.+ static let migrationDependencies = [+ "com.apple.siriactionsd", "com.apple.assistantd", "com.apple.SpringBoard",+ "com.apple.backboardd", "com.apple.runningboardd", "com.apple.mobile.installd",+ "com.apple.lsd", "com.apple.lsd.system", "com.apple.containermanagerd", "com.apple.containermanagerd.system",+ ]++ /// Migration dependencies disabled by an override the service profile+ /// does not own, so neither quiesce nor the profile may re-enable them.+ static func externallyDisabledDependencies(profile: [String: Any], disabled: [String: Any]) -> [String] {+ let owned = Set((profile["record"] as? [String: Any])?["labels"] as? [String] ?? [])+ let overrides = disabled["disabled"] as? [String: Bool] ?? [:]+ return migrationDependencies.filter { overrides[$0] == true && !owned.contains($0) }.sorted()+ }++ private func requireMigrationServices(profile: [String: Any], disabled: [String: Any]) throws {+ let blocked = Self.externallyDisabledDependencies(profile: profile, disabled: disabled)+ guard blocked.isEmpty else {+ throw ValidationError("User-owned service overrides block migration: \(blocked.joined(separator: ", ")). They were left unchanged.")+ }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareOTAPreflightCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareOTAPreflightCommand.swiftnew file mode 100644index 00000000..9a76f57d--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareOTAPreflightCommand.swift@@ -0,0 +1,59 @@+import ArgumentParser+import Foundation+import VPhoneCoreKit++/// Check the running source before stopping it for a full OTA. The encrypted+/// Data volume's launchd overrides cannot be checked by the host installer.+struct VPhoneFirmwareOTAPreflightCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "ota-preflight",+ abstract: "Inspect a running guest's migration state and service dependencies before OTA",+ discussion: """+ Read-only. A trimmed source can retain disabled migration dependencies on+ its Data volume. Save the service profile, take a stopped disk/SEP/NVRAM+ snapshot, and temporarily restore profile-owned services before upgrading.+ User-owned overrides are reported separately and are never changed here.+ Reapply the saved profile only after real migration and UI verification.+ """+ )++ @OptionGroup var lib: VPhoneLibraryOption+ @Argument(help: "Running source VM name") var name: String++ func run() throws {+ let bundle = try lib.library.bundle(named: name)+ func call(_ method: String, _ params: [String: Any] = [:]) throws -> [String: Any] {+ try VPhoneFirmwareOTACommand.guestCall(bundle, method, params, timeout: 15,+ note: "Run ota-preflight while the source is running and responsive.")+ }++ let profile = try call("services.profile")+ let disabled = try call("services.disabled")+ let setup = try call("setup.status")+ let migration = try call("settings.get", ["domain": "com.apple.migration"])+ let lastResult = VPhoneFirmwareOTACommand.migrationResult(migration)+ let record = profile["record"] as? [String: Any] ?? [:]+ let managedDisabled = (profile["disabled"] as? [String] ?? []).sorted()+ let externallyDisabled = VPhoneFirmwareOTACommand.externallyDisabledDependencies(profile: profile, disabled: disabled)+ let migrationDone = setup["data_migration_done"] as? Bool+ // The same gate fw ota capture applies, so a ready report is accepted there.+ let ready = managedDisabled.isEmpty && externallyDisabled.isEmpty+ && VPhoneFirmwareOTACommand.sourceFinishedMigration(setup: setup, migration: migration)+ let report: [String: Any] = [+ "machine": bundle.name,+ "ready_for_ota_experiment": ready,+ "service_profile_record": record,+ "profile_owned_disabled": managedDisabled,+ "externally_disabled_dependencies": externallyDisabled,+ "data_migration_done": migrationDone.map { $0 as Any } ?? NSNull(),+ "last_migration_result": lastResult.map { $0 as Any } ?? NSNull(),+ "notes": [+ "A completed migration with success=false is a failure, even when setup.status says data_migration_done=true.",+ "This check changes no service overrides or migration results and does not attest target-OS compatibility.",+ ],+ ]+ let data = try JSONSerialization.data(withJSONObject: report, options: [.prettyPrinted, .sortedKeys])+ print(String(decoding: data, as: UTF8.self))+ if !ready { throw ExitCode.failure }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareOTAStageCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareOTAStageCommand.swiftnew file mode 100644index 00000000..daa349ad--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareOTAStageCommand.swift@@ -0,0 +1,73 @@+import ArgumentParser+import Foundation+import VPhoneArchiveKit+import VPhoneCoreKit+import VPhoneRestore++/// Stage a full OTA for the opt-in, host-driven System-volume update.+/// This command never runs a restore or writes Disk.img / SEPStorage.+struct VPhoneFirmwareOTAStageCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "ota-stage",+ abstract: "Stage a full OTA for an experimental data-preserving system update",+ discussion: """+ Stop the VM and take a disk/SEP/NVRAM snapshot first. Prepare and patch the+ target firmware, then stage its full OTA here. Allow system-exp-ota_userland+ and run cfw install, which updates System, kernel and TXM together. Never run restore+ on the installed guest: that erases its data. This is an experimental+ offline OTA payload install, not Apple's softwareupdated protocol.+ """+ )++ @OptionGroup var lib: VPhoneLibraryOption+ @Argument(help: "Stopped VM name") var name: String+ @Option(help: "Local full OTA (.aea or decrypted Apple Archive)", transform: URL.init(fileURLWithPath:))+ var source: URL?+ @Option(help: "AEA symmetric key in base64") var key: String?+ @Option(help: "Expected target build, e.g. 24A446") var build: String+ @Flag(help: "Only verify the paths in an already staged payload; do not stage or install it") var verifyStaged = false++ func run() throws {+ let bundle = try lib.library.bundle(named: name)+ try VPhoneBundleActivity.requireStopped(bundle)+ guard let device = VPhoneGuestDevice.named(bundle.manifest.guestProductType ?? ""),+ device.family == .iPad || device.family == .iPhone else {+ throw ValidationError("ota-stage needs a configured iPhone or iPad guest.")+ }+ let fm = FileManager.default+ // The same single iPhone*_Restore tree `restore` and `cfw install` use.+ let tree = try VPhoneRestoreLayout.findRestoreDirectory(in: bundle.url)+ guard let manifest = try PropertyListSerialization.propertyList(+ from: Data(contentsOf: tree.appendingPathComponent("iPhone-BuildManifest.plist")), format: nil+ ) as? [String: Any], manifest["ProductBuildVersion"] as? String == build else {+ throw ValidationError("The prepared target IPSW restore tree does not match --build. Prepare the target before staging the OTA.")+ }+ guard (try VPhoneMachineSnapshots.list(of: bundle)).isEmpty == false else {+ throw ValidationError("Take a stopped VM snapshot first; Disk.img, SEPStorage and NVRAM must roll back together.")+ }+ let userland = bundle.url.appendingPathComponent(VPhoneOTAArchive.userlandDirectoryName)+ if verifyStaged {+ let chunks = try fm.contentsOfDirectory(at: userland, includingPropertiesForKeys: nil)+ .filter { VPhoneOTAArchive.isChunkName($0.lastPathComponent) }.sorted { $0.lastPathComponent < $1.lastPathComponent }+ guard !chunks.isEmpty else { throw ValidationError("No OTA payload is staged.") }+ let links = try Data(contentsOf: userland.appendingPathComponent(VPhoneOTAArchive.hardLinkListName))+ try VPhoneOTAArchive.validatePayloadPaths(chunks, hardLinks: links)+ print("[+] Verified payload paths across \(chunks.count) staged chunks; guest disk untouched.")+ return+ }+ guard let source else { throw ValidationError("--source is required unless --verify-staged is used.") }+ let flash = tree.appendingPathComponent("Firmware/all_flash")+ let staged = try VPhoneOTAArchive.stageUserland(+ from: source, key: key, device: device, build: build,+ deviceTreeDirectory: flash, userlandDirectory: userland,+ requireFullUpdate: true,+ progress: { print("[ota] \($0)") }+ )+ let metadata: [String: String] = [+ "Device": device.productType, "Version": staged.version, "Build": staged.build,+ ]+ try PropertyListSerialization.data(fromPropertyList: metadata, format: .xml, options: 0)+ .write(to: userland.appendingPathComponent("Upgrade.plist"), options: .atomic)+ print("[+] Full OTA staged: \(staged.version) (\(staged.build)), \(staged.chunks.count) payload chunks. Guest disk untouched.")+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Host/VPhoneHostAutomationProbe.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Host/VPhoneHostAutomationProbe.swiftindex 725e64ab..5081ff78 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Host/VPhoneHostAutomationProbe.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Host/VPhoneHostAutomationProbe.swift@@ -10,6 +10,25 @@ enum VPhoneHostAutomationProbe {send(["t": "ping", "screen": false], socketPath: socketPath)?["ok"] as? Bool == true}+ /// One vphoned RPC through the VM process. A refusal from vphoned carries+ /// its error object as `detail`; anything else is a transport failure.+ static func rpc(_ method: String, params: [String: Any], socketPath: String, timeout: Int) throws -> [String: Any] {+ let request: [String: Any] = ["t": "rpc", "method": method, "params": params, "screen": false]+ guard let reply = send(request, socketPath: socketPath, timeout: timeout, 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)+ }+/// One request, one reply line. Nil when the socket is not there or the/// reply is not JSON. `timeout` bounds each read; `maximumReply` the/// reply (an `apps.list` or `processes.list` runs to a few hundred KB).diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swiftindex 5bd5761e..3ca3ffa1 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift@@ -1,6 +1,7 @@import ArgumentParserimport FirmwarePatcherimport Foundation+import VPhoneArchiveKitimport VPhoneCoreKitimport VPhonePatchKitimport VPhoneRestore@@ -344,7 +345,17 @@ struct VPhoneCustomFirmwareInstallCommand: ParsableCommand {private func recordInstall(in bundle: VPhoneBundle) throws {let keepArtifacts = keepArtifactslet record = {- if let info = try? VPhoneRestoreInfo.recordVariant("jb", toBundle: bundle), info.variant != nil {+ let receipt = VPhonePatchPresetStore.receipt(forVM: bundle.url)+ let metadataData = try? Data(contentsOf: bundle.url.appendingPathComponent(VPhoneOTAArchive.userlandDirectoryName)+ .appendingPathComponent("Upgrade.plist"))+ let metadata = metadataData.flatMap { try? PropertyListSerialization.propertyList(from: $0, format: nil) as? [String: String] }+ if receipt?.parts[VPhoneVirtualMachinePatchReceipt.guestPart]?.patches.contains(FirmwareGuestSystemPatchSet.otaUserland) == true,+ let target = VPhoneRestoreInfo.derive(fromBundle: bundle),+ metadata?["Build"] == target.ios.build, metadata?["Version"] == target.ios.version {+ try VPhoneRestoreInfo(ios: target.ios, cloudOS: target.cloudOS, variant: "jb", device: bundle.manifest.guestProductType)+ .write(toBundle: bundle)+ print("[cfw] recorded full OTA userland \(target.ios.version) (\(target.ios.build))")+ } else if let info = try? VPhoneRestoreInfo.recordVariant("jb", toBundle: bundle), info.variant != nil {print("[cfw] recorded variant jb, device \(info.device ?? "?")")}if !keepArtifacts, let removed = try? VPhoneRestoreInfo.removeBuiltFirmware(fromBundle: bundle) {@@ -352,7 +363,7 @@ struct VPhoneCustomFirmwareInstallCommand: ParsableCommand {}}guard geteuid() == 0, let invokingUser = VPhoneInvokingUser.current else {- record()+ try record()return}do {diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneTemplateSetup.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneTemplateSetup.swiftindex 6217b585..6d6ce8c8 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneTemplateSetup.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneTemplateSetup.swift@@ -112,25 +112,7 @@ final class VPhoneTemplateSetupVirtualMachine: VPhoneTemplateSetupMachine {}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)+ try VPhoneHostAutomationProbe.rpc(method, params: params, socketPath: socketPath, timeout: Int(timeout.rounded(.up)))}/// SIGINT makes `vphone-vm` ask the guest to shut down and exit once itdiff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plistindex 52f8f095..d5d58737 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist@@ -87,6 +87,7 @@<string>system-dyld-exp-tv_tpro</string><string>kernel-exp-tv_tpro_pagers</string><string>system-tv-exp-ota_userland</string>+ <string>system-exp-ota_userland</string></array></dict><key>Summary</key>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plistindex d5e25429..75dc76bc 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist@@ -67,6 +67,7 @@<string>Block</string><key>Patches</key><array>+ <string>system-exp-ota_userland</string><string>kernel-exp-frida_thread_set_state_entitlement_flag</string><string>kernel-exp-frida_vm_map_delete_immutable_code</string><string>kernel-exp-hv_vmm</string>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plistindex 00fbb819..1e4ac642 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist@@ -126,6 +126,7 @@<string>system-virtualaudio-cfw-speaker_route_throws</string><string>system-virtualaudio-cfw-volume_mode_precondition</string><string>system-tv-exp-ota_userland</string>+ <string>system-exp-ota_userland</string></array></dict><key>Summary</key>diff --git a/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneOTAArchive.swift b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneOTAArchive.swiftindex 56b52b00..0b2c535e 100644--- a/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneOTAArchive.swift+++ b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneOTAArchive.swift@@ -1,5 +1,6 @@import AppleArchiveimport CryptoKit+import Darwinimport Foundationimport Systemimport VPhoneCoreKit@@ -34,6 +35,7 @@ public enum VPhoneOTAArchive {case unexpectedSize(URL, expected: Int64, actual: Int64)case existingUserland(URL)case noSource(String)+ case deltaUpdate(URL)public var errorDescription: String? {switch self {@@ -63,6 +65,8 @@ public enum VPhoneOTAArchive {"\(folder.path) already exists. Remove it, then prepare the firmware again."case let .noSource(productType):"The firmware catalog has no OTA for \(productType) at this build. Pass the device's full OTA with --ota-source."+ case let .deltaUpdate(file):+ "\(file.lastPathComponent) requires a pristine prerequisite build. A modified vphone system needs a full OTA, without PrerequisiteBuild."}}}@@ -88,6 +92,11 @@ public enum VPhoneOTAArchive {/// `TYP` and `YOP` values are one ASCII letter.private static let regularFile = UInt64(UInt8(ascii: "F"))private static let extractSegment = UInt64(UInt8(ascii: "E"))+ private static let directoryEntry = UInt64(UInt8(ascii: "D"))+ private static let symlinkEntry = UInt64(UInt8(ascii: "L"))+ private static let hardLinkEntry = UInt64(UInt8(ascii: "H"))+ private static let metadataEntry = UInt64(UInt8(ascii: "M"))+ private static let payloadEntryTypes: Set = [regularFile, directoryEntry, symlinkEntry, hardLinkEntry]// MARK: - Key@@ -327,6 +336,7 @@ public enum VPhoneOTAArchive {static let firmwarePrefix = "AssetData/boot/"static let payloadPrefix = "AssetData/payloadv2/"public static let chunkListName = "payload_chunks.txt"+ public static let hardLinkListName = "links.txt"/// The VM folder's copy of the payload, which `cfw install` extracts/// over the restored System volume (`system-tv-exp-ota_userland`).public static let userlandDirectoryName = "OTAUserland"@@ -354,6 +364,7 @@ public enum VPhoneOTAArchive {build: String,deviceTreeDirectory: URL,userlandDirectory: URL,+ requireFullUpdate: Bool = false,progress: ((String) -> Void)? = nil,) throws -> StagedUserland {let fm = FileManager.default@@ -370,8 +381,11 @@ public enum VPhoneOTAArchive {var wroteDeviceTree = falsevar chunks: [String] = []var chunkList: Data?+ var linkList: Data?+ var checkedFullUpdate = falsetry readMembers(ota, key: key, select: { path in+ if requireFullUpdate, path == "AssetData/Info.plist" { return .memory }if path == manifestPath { return .memory }if path == deviceTreeMember {guard identity != nil else { throw Error.missingMember(manifestPath, ota) }@@ -380,17 +394,26 @@ public enum VPhoneOTAArchive {guard path.hasPrefix(payloadPrefix) else { return .skip }let name = String(path.dropFirst(payloadPrefix.count))if name == chunkListName { return .memory }+ if name == hardLinkListName { return .memory }guard isChunkName(name) else { return .skip }guard identity != nil else { throw Error.missingMember(manifestPath, ota) }+ if requireFullUpdate, !checkedFullUpdate {+ throw Error.missingMember("AssetData/Info.plist before the payload", ota)+ }return .file(pending.appendingPathComponent(name))}, received: { path, data in- if path == manifestPath {+ if requireFullUpdate, path == "AssetData/Info.plist" {+ try checkFullUpdateInfo(data ?? Data(), of: ota)+ checkedFullUpdate = true+ } else if path == manifestPath {identity = try checkManifest(data ?? Data(), of: ota, device: device, build: build)progress?("OTA \(identity!.version) (\(identity!.build)) for \(device.productType)")} else if path == deviceTreeMember {wroteDeviceTree = true} else if path == payloadPrefix + chunkListName {chunkList = data+ } else if path == payloadPrefix + hardLinkListName {+ linkList = data} else {let name = String(path.dropFirst(payloadPrefix.count))chunks.append(name)@@ -403,6 +426,15 @@ public enum VPhoneOTAArchive {guard let chunkList else { throw Error.missingMember(payloadPrefix + chunkListName, ota) }chunks.sort()try checkChunks(chunks, list: chunkList, of: ota)+ if requireFullUpdate {+ guard let linkList else { throw Error.missingMember(payloadPrefix + hardLinkListName, ota) }+ try validatePayloadPaths(chunks.map { pending.appendingPathComponent($0) }, hardLinks: linkList)+ }+ if let linkList {+ // A full update already parsed it while validating the payload.+ if !requireFullUpdate { _ = try parseHardLinks(linkList) }+ try linkList.write(to: pending.appendingPathComponent(hardLinkListName))+ }try chunkList.write(to: pending.appendingPathComponent(chunkListName))try fm.moveItem(at: pending, to: userlandDirectory)try VPhoneHostFilePermissions.makeAccessible(at: userlandDirectory)@@ -438,6 +470,165 @@ public enum VPhoneOTAArchive {return !number.isEmpty && number.allSatisfy(\.isASCIIDigit)}+ /// An already modified system cannot satisfy a delta's source hashes.+ /// Reject it before staging any payload, even if its target manifest matches.+ static func checkFullUpdateInfo(_ data: Data, of ota: URL) throws {+ guard let info = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] else {+ throw Error.unreadable(ota, "its AssetData/Info.plist is malformed")+ }+ // OTA asset metadata has used both a flat dictionary and MobileAssetProperties.+ let properties = info["MobileAssetProperties"] as? [String: Any] ?? info+ for key in ["PrerequisiteBuild", "PrerequisiteOSVersion"] {+ if let value = properties[key] {+ if let text = value as? String, text.isEmpty { continue }+ if let list = value as? [String], list.isEmpty { continue }+ throw Error.deltaUpdate(ota)+ }+ }+ }++ /// Before a privileged extraction, inspect every chunk as one filesystem.+ /// Absolute symlink targets are normal in a guest; a member below such a+ /// link is not. No extraction is attempted until all chunks pass.+ public static func validatePayloadPaths(_ chunks: [URL], hardLinks linkList: Data? = nil) throws {+ var nodes: [String: UInt64] = [:]+ var hardLinks: [String: String] = [:]+ func canonical(_ path: String, file: URL) throws -> String {+ var path = path+ while path.hasPrefix("./") { path.removeFirst(2) }+ if path.hasSuffix("/") { path.removeLast() }+ if path.isEmpty || path == "." { return "" }+ guard VPhoneSystemTrim.isSafeRelativePath(path) else {+ throw Error.unreadable(file, "unsafe payload path: \(path)")+ }+ return path+ }+ for chunk in chunks {+ let opened = try openArchive(chunk, key: nil)+ try withExtendedLifetime(opened) {+ defer {+ try? opened.archive.close()+ for stream in opened.streams.reversed() { try? stream.close() }+ }+ while let header = try readHeader(opened.archive, of: chunk) {+ guard case let .uint(_, type)? = header.field(forKey: typKey) else {+ throw Error.unreadable(chunk, "payload entry has no type")+ }+ if type == metadataEntry { continue }+ guard payloadEntryTypes.contains(type),+ case let .string(_, rawPath)? = header.field(forKey: patKey) else {+ throw Error.unreadable(chunk, "payload contains an unsupported filesystem object")+ }+ let path = try canonical(rawPath, file: chunk)+ if path.isEmpty {+ guard type == directoryEntry else {+ throw Error.unreadable(chunk, "payload replaces its extraction root")+ }+ continue+ }+ if let previous = nodes[path], previous != type {+ throw Error.unreadable(chunk, "payload changes the type of \(path)")+ }+ nodes[path] = type+ if type == hardLinkEntry {+ guard case let .string(_, target)? = header.field(forKey: ArchiveHeader.FieldKey("LNK")) else {+ throw Error.unreadable(chunk, "hard link has no target")+ }+ hardLinks[path] = try canonical(target, file: chunk)+ }+ }+ }+ }+ let label = chunks.first ?? URL(fileURLWithPath: "payload")+ if let linkList {+ for link in try parseHardLinks(linkList) {+ guard nodes[link.source] == regularFile, nodes[link.destination] == nil else {+ throw Error.unreadable(label, "hard link \(link.destination) needs an archived regular source and a new destination")+ }+ nodes[link.destination] = hardLinkEntry+ hardLinks[link.destination] = link.source+ }+ }+ // Each ancestor is checked once: one already seen had its whole chain+ // checked when it was first reached.+ var checkedParents = Set<String>()+ for path in nodes.keys {+ var parent = (path as NSString).deletingLastPathComponent+ while !parent.isEmpty, checkedParents.insert(parent).inserted {+ if let type = nodes[parent], type != directoryEntry {+ throw Error.unreadable(label, "payload member \(path) traverses non-directory \(parent)")+ }+ parent = (parent as NSString).deletingLastPathComponent+ }+ }+ for (path, target) in hardLinks where nodes[target] != regularFile {+ throw Error.unreadable(label, "hard link \(path) does not target an archived regular file")+ }+ }++ public struct HardLink: Equatable, Sendable {+ public let source: String+ public let destination: String+ }++ /// Full OTAs store duplicate files outside the numbered archives: '='+ /// selects an archived source and each following '+' names a hard link.+ /// Omitting this list leaves otherwise complete framework bundles broken.+ public static func parseHardLinks(_ data: Data) throws -> [HardLink] {+ let label = URL(fileURLWithPath: hardLinkListName)+ guard data.count <= memoryLimit, let text = String(data: data, encoding: .utf8) else {+ throw Error.unreadable(label, "hard-link list is too large or not UTF-8")+ }+ func path(_ raw: Substring) throws -> String {+ let value = String(raw)+ guard VPhoneSystemTrim.isSafeRelativePath(value) else {+ throw Error.unreadable(label, "unsafe hard-link path: \(value)")+ }+ return value+ }+ var source: String?+ var destinations = Set<String>()+ var links: [HardLink] = []+ for row in text.split(whereSeparator: \.isNewline) {+ switch row.first {+ case "=":+ source = try path(row.dropFirst())+ case "+":+ let destination = try path(row.dropFirst())+ guard let source, source != destination, destinations.insert(destination).inserted else {+ throw Error.unreadable(label, "orphan, self-referencing or duplicate hard link: \(destination)")+ }+ links.append(HardLink(source: source, destination: destination))+ default:+ throw Error.unreadable(label, "unsupported hard-link record")+ }+ }+ return links+ }++ /// Called only on the private stopped-disk clone after validating chunks+ /// together with the list. Both parent walks refuse symlinks and mount+ /// crossings. The inode readback also refuses a changed source leaf.+ @discardableResult+ public static func installHardLinks(_ data: Data, in directory: VPhoneConfinedDirectory) throws -> Int {+ let links = try parseHardLinks(data)+ for link in links {+ // One confined walk per side; the source and the readback use+ // the parents already pinned.+ let from = try directory.parent(of: link.source)+ let to = try directory.parent(of: link.destination)+ let source = try from.directory.openRegularFile(from.leaf)+ guard linkat(from.directory.descriptor, from.leaf, to.directory.descriptor, to.leaf, 0) == 0 else {+ throw VPhoneConfinedDirectoryError.system(link.destination, errno)+ }+ guard try to.directory.refersTo(to.leaf, file: source) else {+ _ = try to.directory.removeItem(to.leaf)+ throw VPhoneConfinedDirectoryError.changedDuringOpen(link.source)+ }+ }+ return links.count+ }+static func checkManifest(_ data: Data,of ota: URL,diff --git a/VPhoneKit/VPhoneArchiveKitTests/OTAArchiveTests.swift b/VPhoneKit/VPhoneArchiveKitTests/OTAArchiveTests.swiftindex 4d3828a1..67c2fbe4 100644--- a/VPhoneKit/VPhoneArchiveKitTests/OTAArchiveTests.swift+++ b/VPhoneKit/VPhoneArchiveKitTests/OTAArchiveTests.swift@@ -28,6 +28,7 @@ struct OTAArchiveTests {private enum Entry {case file(String, Data)case directory(String)+ case symlink(String, String)/// A top-level metadata entry: `yop` and an archive of `entries` in its blob.case segment(Character, [Entry])}@@ -62,6 +63,11 @@ struct OTAArchiveTests {header.append(field("TYP", ascii("D")))header.append(.string(key: ArchiveHeader.FieldKey("PAT"), value: path))blob = nil+ case let .symlink(path, target):+ header.append(field("TYP", ascii("L")))+ header.append(.string(key: ArchiveHeader.FieldKey("PAT"), value: path))+ header.append(.string(key: ArchiveHeader.FieldKey("LNK"), value: target))+ blob = nilcase let .segment(yop, inner):header.append(field("TYP", ascii("M")))header.append(field("YOP", ascii(yop)))@@ -174,6 +180,148 @@ struct OTAArchiveTests {// MARK: - Staging+ @Test func `hard-link lists preserve spaces and reject unsafe or ambiguous records`() throws {+ let links = try VPhoneOTAArchive.parseHardLinks(Data("=System/source file\n+System/copy file\n+System/another\n".utf8))+ #expect(links.count == 2)+ #expect(links[0].source == "System/source file")+ #expect(links[0].destination == "System/copy file")+ for bad in ["+orphan\n", "=/outside\n+target\n", "=source\n+../outside\n",+ "=source\n+source\n", "=source\n+target\n+target\n", "?unsupported\n",+ "=source\n+dir//file\n", "=source\n+dir/./file\n", "=source\n+dir/\u{0}file\n"] {+ #expect(throws: VPhoneOTAArchive.Error.self) {+ try VPhoneOTAArchive.parseHardLinks(Data(bad.utf8))+ }+ }+ }++ @Test func `payload validation checks external hard links against the whole filesystem`() throws {+ let root = try makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let chunk = root.appendingPathComponent("payload.000")+ try encode([.directory("System"), .file("System/source", Data("resource".utf8)),+ .symlink("escape", "/private/tmp")], in: root).write(to: chunk)+ try VPhoneOTAArchive.validatePayloadPaths([chunk], hardLinks: Data("=System/source\n+System/copy\n".utf8))+ for list in ["=missing\n+System/copy\n", "=escape\n+System/copy\n",+ "=System/source\n+escape/outside\n", "=System/source\n+System/source/child\n",+ "=System/source\n+System/copy\n+System/copy/child\n"] {+ #expect(throws: VPhoneOTAArchive.Error.self) {+ try VPhoneOTAArchive.validatePayloadPaths([chunk], hardLinks: Data(list.utf8))+ }+ }+ }++ @Test func `hard-link installation shares the source inode and refuses symlink parents`() throws {+ let root = try makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let directory = try VPhoneConfinedDirectory(root: root.path)+ _ = try directory.directory("System", create: true)+ try directory.writeFile("System/source", contents: Data("resource".utf8), mode: 0o640)+ let list = Data("=System/source\n+System/copy\n".utf8)+ #expect(try VPhoneOTAArchive.installHardLinks(list, in: directory) == 1)+ let source = try directory.openRegularFile("System/source")+ #expect(try directory.refersTo("System/copy", file: source))+ #expect(try directory.readData("System/copy") == Data("resource".utf8))+ #expect(throws: VPhoneConfinedDirectoryError.self) {+ try VPhoneOTAArchive.installHardLinks(list, in: directory)+ }+ try directory.createSymlink(target: "System", at: "alias")+ for bad in ["=alias/source\n+System/other\n", "=System/source\n+alias/other\n"] {+ #expect(throws: VPhoneConfinedDirectoryError.self) {+ try VPhoneOTAArchive.installHardLinks(Data(bad.utf8), in: directory)+ }+ }+ #expect(try directory.exists("System/other") == false)+ }++ @Test func `staging retains the separate hard-link manifest`() throws {+ let root = try makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let links = Data("=System/source\n+System/copy\n".utf8)+ let entries = try otaEntries(manifest: manifest()) + [+ .segment("E", [.file("AssetData/payloadv2/links.txt", links)]),+ ]+ let ota = try makeOTA(in: root, entries)+ _ = try stage(ota, in: root, key: keyText)+ #expect(try Data(contentsOf: root.appendingPathComponent("vm/OTAUserland/links.txt")) == links)+ }++ @Test func `full iPad staging requires and validates the separate hard-link phase`() throws {+ for includeLinks in [false, true] {+ let root = try makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let flash = root.appendingPathComponent("restore/Firmware/all_flash")+ try FileManager.default.createDirectory(at: flash, withIntermediateDirectories: true)+ _ = try vmFolder(root)+ let manifest = try PropertyListSerialization.data(fromPropertyList: [+ "ProductVersion": "27.0.1", "ProductBuildVersion": "24A446",+ "SupportedProductTypes": ["iPad16,1"],+ ], format: .xml, options: 0)+ let info = try PropertyListSerialization.data(fromPropertyList: ["OSVersion": "27.0.1"], format: .xml, options: 0)+ let payload = try encode([.directory("System"), .file("System/source", Data("resource".utf8))], in: root)+ var members: [Entry] = [+ .file("AssetData/Info.plist", info),+ .file("AssetData/boot/BuildManifest.plist", manifest),+ .file("AssetData/boot/Firmware/all_flash/DeviceTree.j410ap.im4p", Data("tree".utf8)),+ .file("AssetData/payloadv2/payload.000", payload),+ .file("AssetData/payloadv2/payload_chunks.txt", Data("0: 1000\n".utf8)),+ ]+ if includeLinks { members.append(.file("AssetData/payloadv2/links.txt", Data("=System/source\n+System/copy\n".utf8))) }+ let ota = try makeOTA(in: root, [.segment("E", members)])+ let device = try #require(VPhoneGuestDevice.named("iPad16,1"))+ let userland = root.appendingPathComponent("vm/OTAUserland")+ if includeLinks {+ let staged = try VPhoneOTAArchive.stageUserland(from: ota, key: keyText, device: device,+ build: "24A446", deviceTreeDirectory: flash, userlandDirectory: userland, requireFullUpdate: true)+ #expect(staged.build == "24A446")+ #expect(FileManager.default.fileExists(atPath: userland.appendingPathComponent("links.txt").path))+ } else {+ #expect(throws: VPhoneOTAArchive.Error.self) {+ try VPhoneOTAArchive.stageUserland(from: ota, key: keyText, device: device,+ build: "24A446", deviceTreeDirectory: flash, userlandDirectory: userland, requireFullUpdate: true)+ }+ #expect(!FileManager.default.fileExists(atPath: userland.path))+ }+ }+ }++ @Test func `full updates reject prerequisite metadata before staging chunks`() throws {+ let root = try makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ for value: Any in ["23G90", ["23G90"], 123] {+ let info = try PropertyListSerialization.data(fromPropertyList: ["PrerequisiteBuild": value], format: .xml, options: 0)+ #expect(throws: VPhoneOTAArchive.Error.self) {+ try VPhoneOTAArchive.checkFullUpdateInfo(info, of: root.appendingPathComponent("delta.aea"))+ }+ }+ let full = try PropertyListSerialization.data(fromPropertyList: ["OSVersion": "27.0.1"], format: .xml, options: 0)+ try VPhoneOTAArchive.checkFullUpdateInfo(full, of: root.appendingPathComponent("full.aea"))+ let nested = try PropertyListSerialization.data(fromPropertyList: ["MobileAssetProperties": ["PrerequisiteBuild": "23G90"]], format: .xml, options: 0)+ #expect(throws: VPhoneOTAArchive.Error.self) {+ try VPhoneOTAArchive.checkFullUpdateInfo(nested, of: root.appendingPathComponent("delta.aea"))+ }+ }++ @Test func `payload validation rejects traversal and cross-chunk symlink descendants`() throws {+ let root = try makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let a = root.appendingPathComponent("payload.000")+ let b = root.appendingPathComponent("payload.001")+ for path in ["../outside", "/outside", "System/../outside", "System//outside"] {+ try encode([.file(path, Data())], in: root).write(to: a)+ #expect(throws: VPhoneOTAArchive.Error.self) {+ try VPhoneOTAArchive.validatePayloadPaths([a])+ }+ }+ try encode([.symlink("escape", "/private/tmp")], in: root).write(to: a)+ try encode([.file("escape/outside", Data())], in: root).write(to: b)+ #expect(throws: VPhoneOTAArchive.Error.self) {+ try VPhoneOTAArchive.validatePayloadPaths([a, b])+ }+ // A guest's absolute links are valid when extraction never follows them.+ try encode([.directory(""), .directory("System"), .file("System/test", Data()), .symlink("var", "/private/var")], in: root).write(to: a)+ try VPhoneOTAArchive.validatePayloadPaths([a])+ }+@Test func `an encrypted OTA stages its device tree, payload chunks and chunk list`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineSnapshots.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineSnapshots.swiftindex 09f1d677..67d0517e 100644--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineSnapshots.swift+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneMachineSnapshots.swift@@ -378,7 +378,7 @@ public enum VPhoneMachineSnapshots {}/// An APFS clone, never a copy. Symbolic links are not followed.- private static func cloneFile(_ source: URL, to destination: URL) throws {+ static func cloneFile(_ source: URL, to destination: URL) throws {guard clonefile(source.path, destination.path, UInt32(CLONE_NOFOLLOW)) == 0 else {let code = errnoif code == ENOTSUP || code == EXDEV {diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneOTAUpdate.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneOTAUpdate.swiftnew file mode 100644index 00000000..7bfe18e9--- /dev/null+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneOTAUpdate.swift@@ -0,0 +1,267 @@+import Darwin+import Foundation++/// OTA adds host configuration to a normal disk/SEP/NVRAM snapshot without+/// changing ordinary snapshot semantics. The journal lives outside the machine+/// folder so guest-side phases can record progress while the VM is running.+public enum VPhoneOTAUpdate {+ public enum Phase: String, Codable, Sendable {+ case captured, checkpointing, checkpointed, quiesced, preparing, prepared+ case installed, completed, committed, rollingBack, rolledBack+ }++ public struct Record: Codable, Sendable {+ public let machinePath: String+ public let snapshot: String+ public let targetBuild: String+ public let targetVersion: String+ public let source: Data+ public var phase: Phase+ public var hostFiles: [String]+ public var artifacts: [String]+ public var autoLockRestorationRequested: Bool?+ public var autoLockRebootRequested: Bool?+ public var operationID: String?+ public var networkIsolated: Bool?++ public init(bundle: VPhoneBundle, build: String, version: String, source: Data) {+ machinePath = bundle.url.resolvingSymlinksInPath().path+ snapshot = "ota-" + UUID().uuidString.lowercased()+ targetBuild = build+ targetVersion = version+ self.source = source+ phase = .captured+ hostFiles = []+ artifacts = []+ }+ }++ public struct Failure: LocalizedError {+ public let errorDescription: String?+ public init(_ message: String) { errorDescription = message }+ }++ private static let hostNames = [+ "config.plist", "PatchSelection.plist", "PatchPlan.plist", ".vphoned.signed",+ "AVPBooter.vresearch1.bin", "AVPSEPBooter.vresearch1.bin", "OpenAVB.bin", "OpenSEP.bin",+ ]++ public static func directory(of bundle: VPhoneBundle) -> URL {+ bundle.url.deletingLastPathComponent()+ .appendingPathComponent(".ota-updates", isDirectory: true).appendingPathComponent(bundle.name, isDirectory: true)+ }++ /// A second coordinator must not prepare or roll back the same machine.+ public static func withLock<T>(of bundle: VPhoneBundle, _ body: () throws -> T) throws -> T {+ let directory = directory(of: bundle)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ // A terminal journal can be archived for a fresh attempt. The lock+ // must stay at a stable path when that directory is renamed.+ let path = directory.deletingLastPathComponent().appendingPathComponent(bundle.name + ".lock").path+ let fd = open(path, O_CREAT | O_RDWR | O_NOFOLLOW, 0o600)+ guard fd >= 0 else { throw Failure("Cannot open OTA lock: \(path)") }+ defer { close(fd) }+ guard flock(fd, LOCK_EX | LOCK_NB) == 0 else { throw Failure("Another OTA command owns \(bundle.name).") }+ defer { flock(fd, LOCK_UN) }+ return try body()+ }++ public static func read(of bundle: VPhoneBundle) throws -> Record {+ let data = try Data(contentsOf: directory(of: bundle).appendingPathComponent("Update.plist"))+ let record = try PropertyListDecoder().decode(Record.self, from: data)+ guard record.machinePath == bundle.url.resolvingSymlinksInPath().path,+ (try? VPhoneMachineSnapshots.requireValidName(record.snapshot)) != nil,+ record.hostFiles.allSatisfy(hostNames.contains),+ record.artifacts.allSatisfy(isArtifactName) else {+ throw Failure("OTA journal does not describe this machine or contains invalid backup paths.")+ }+ return record+ }++ public static func write(_ record: Record, of bundle: VPhoneBundle) throws {+ let encoder = PropertyListEncoder()+ encoder.outputFormat = .xml+ let path = directory(of: bundle).appendingPathComponent("Update.plist")+ try encoder.encode(record).write(to: path, options: .atomic)+ let handle = try FileHandle(forWritingTo: path)+ defer { try? handle.close() }+ try handle.synchronize()+ }++ public static func capture(_ record: Record, of bundle: VPhoneBundle) throws {+ let path = directory(of: bundle).appendingPathComponent("Update.plist")+ if FileManager.default.fileExists(atPath: path.path) {+ let previous = try read(of: bundle)+ guard previous.phase == .rolledBack else {+ throw Failure("This machine already has an OTA journal. Resume or roll it back; do not overwrite its recovery state.")+ }+ let current = directory(of: bundle)+ let archived = current.deletingLastPathComponent().appendingPathComponent(bundle.name + "-" + previous.snapshot)+ try FileManager.default.moveItem(at: current, to: archived)+ try FileManager.default.createDirectory(at: current, withIntermediateDirectories: false)+ }+ try write(record, of: bundle)+ }++ /// Guest version and this boot's migration result must independently+ /// agree. In particular SetupDone or an old successful result is not proof.+ public static func requireMigration(+ version: String, build: String, actualVersion: String?,+ migrationDone: Bool?, result: [String: Any]?+ ) throws {+ guard actualVersion == version, migrationDone == true,+ result?["buildVersion"] as? String == build,+ result?["success"] as? Bool == true else {+ throw Failure("Target build migration has not succeeded. Setup skip cannot satisfy this gate.")+ }+ }++ public static func requireOperation(_ operationID: String?, record: Record) throws {+ if let operationID, record.operationID != operationID {+ throw Failure("The OTA journal belongs to another coordinator operation.")+ }+ }++ public static func isolateNetwork(of bundle: VPhoneBundle) throws {+ try VPhoneBundleActivity.requireStopped(bundle)+ var record = try read(of: bundle)+ guard record.phase == .checkpointed else { throw Failure("Network isolation needs a completed source checkpoint.") }+ let current = try VPhoneBundle.load(at: bundle.url)+ let offline = VPhoneVirtualMachineManifest.NetworkConfig(mode: .off, macAddress: current.manifest.networkConfig.macAddress)+ try current.manifest.updating(networkConfig: offline).write(to: current.configURL)+ record.networkIsolated = true+ try write(record, of: bundle)+ }++ /// Once networking can resume, new guest writes must not be silently+ /// discarded by an automatic rollback. Publish that boundary durably+ /// before restoring the source network policy; repeat safely after a crash.+ public static func commit(of bundle: VPhoneBundle) throws {+ try VPhoneBundleActivity.requireStopped(bundle)+ var record = try read(of: bundle)+ guard record.phase == .completed || record.phase == .committed else {+ throw Failure("OTA can be committed only after offline verification.")+ }+ let source = try sourceManifest(of: bundle)+ let current = try VPhoneBundle.load(at: bundle.url)+ record.phase = .committed+ try write(record, of: bundle)+ try current.manifest.updating(networkConfig: source.networkConfig).write(to: current.configURL)+ }++ public static func sourceManifest(of bundle: VPhoneBundle) throws -> VPhoneVirtualMachineManifest {+ try VPhoneVirtualMachineManifest.load(from: directory(of: bundle).appendingPathComponent("host/config.plist"))+ }++ /// Called before any service or firmware changes. All large backups must+ /// use APFS clones; no full-copy fallback for Disk.img or restore trees.+ public static func checkpoint(of bundle: VPhoneBundle) throws {+ try VPhoneBundleActivity.requireStopped(bundle)+ var record = try read(of: bundle)+ guard record.phase == .captured || record.phase == .checkpointing else {+ if record.phase == .checkpointed { return }+ throw Failure("Cannot checkpoint OTA in phase \(record.phase.rawValue).")+ }+ let fm = FileManager.default+ let backup = directory(of: bundle).appendingPathComponent("host", isDirectory: true)+ if record.phase == .captured {+ record.hostFiles = hostNames.filter { fm.fileExists(atPath: bundle.url.appendingPathComponent($0).path) }+ record.artifacts = try fm.contentsOfDirectory(atPath: bundle.url.path).filter(isArtifactName).sorted()+ record.phase = .checkpointing+ try write(record, of: bundle)+ }+ try fm.createDirectory(at: backup, withIntermediateDirectories: true)+ // Each backup is individually published by rename. A power loss can+ // resume without accepting an incomplete directory as a backup.+ for name in record.hostFiles + record.artifacts {+ let destination = backup.appendingPathComponent(name)+ if !fm.fileExists(atPath: destination.path) {+ try cloneTree(bundle.url.appendingPathComponent(name), to: destination)+ }+ }+ if !(try VPhoneMachineSnapshots.list(of: bundle)).contains(where: { $0.name == record.snapshot }) {+ try VPhoneMachineSnapshots.create(record.snapshot, note: "Before OTA to \(record.targetVersion) (\(record.targetBuild))", of: bundle)+ }+ record.phase = .checkpointed+ try write(record, of: bundle)+ }++ /// Clear only backed-up firmware inputs. Repeatable after an interrupted+ /// preparation. The pre-upgrade host state and snapshot remain intact.+ public static func beginPreparation(of bundle: VPhoneBundle) throws {+ try VPhoneBundleActivity.requireStopped(bundle)+ var record = try read(of: bundle)+ guard record.phase == .quiesced || record.phase == .preparing else {+ throw Failure("OTA preparation needs a checkpoint and quiesced source services.")+ }+ record.phase = .preparing+ try write(record, of: bundle)+ for name in try FileManager.default.contentsOfDirectory(atPath: bundle.url.path).filter(isArtifactName) {+ try FileManager.default.removeItem(at: bundle.url.appendingPathComponent(name))+ }+ }++ /// A failed target remains inspectable. Restore the saved host state and+ /// disk/SEP/NVRAM together, retaining the snapshot and backup for retry.+ public static func rollback(of bundle: VPhoneBundle, discardOnlineWrites: Bool = false) throws {+ try VPhoneBundleActivity.requireStopped(bundle)+ var record = try read(of: bundle)+ if record.phase == .rolledBack { return }+ guard record.phase != .committed || discardOnlineWrites else {+ throw Failure("OTA was committed and the guest may have written new data online. Keep the target data; automatic rollback is refused.")+ }+ guard record.phase != .captured && record.phase != .checkpointing else {+ throw Failure("No completed checkpoint exists; firmware has not been changed.")+ }+ record.phase = .rollingBack+ try write(record, of: bundle)+ let fm = FileManager.default+ let backup = directory(of: bundle).appendingPathComponent("host")+ let failed = directory(of: bundle).appendingPathComponent("failed-" + UUID().uuidString, isDirectory: true)+ try fm.createDirectory(at: failed, withIntermediateDirectories: false)+ // Validate the whole backup before changing any live file.+ for name in record.hostFiles + record.artifacts {+ guard fm.fileExists(atPath: backup.appendingPathComponent(name).path) else {+ throw Failure("OTA host backup is incomplete: \(name)")+ }+ }+ try VPhoneMachineSnapshots.revert(to: record.snapshot, of: bundle)+ let currentArtifacts = try fm.contentsOfDirectory(atPath: bundle.url.path).filter(isArtifactName)+ for name in Set(hostNames + currentArtifacts + record.artifacts).sorted() {+ let live = bundle.url.appendingPathComponent(name)+ if (record.hostFiles + record.artifacts).contains(name) {+ let staged = failed.appendingPathComponent(name)+ try cloneTree(backup.appendingPathComponent(name), to: staged)+ if fm.fileExists(atPath: live.path) {+ // config.plist must always exist, including after a+ // crash: the next CLI needs it to open this machine.+ guard renameatx_np(AT_FDCWD, staged.path, AT_FDCWD, live.path, UInt32(RENAME_SWAP)) == 0 else {+ throw Failure("Cannot publish restored OTA host file \(name): \(String(cString: strerror(errno)))")+ }+ } else {+ try fm.moveItem(at: staged, to: live)+ }+ } else if fm.fileExists(atPath: live.path) {+ try fm.moveItem(at: live, to: failed.appendingPathComponent(name))+ }+ }+ record.phase = .rolledBack+ try write(record, of: bundle)+ }++ private static func isArtifactName(_ name: String) -> Bool {+ VPhoneVirtualMachineManifest.isPlainFileName(name) && !name.hasPrefix(".")+ && (name.contains("Restore") || ["FirmwareOriginals", "OTAUserland"].contains(name))+ }++ private static func cloneTree(_ source: URL, to destination: URL) throws {+ let fm = FileManager.default+ let stage = destination.deletingLastPathComponent().appendingPathComponent(".ota-copy-" + UUID().uuidString)+ defer { try? fm.removeItem(at: stage) }+ // clonefile copies a whole directory tree in one call and keeps the+ // relative links in firmware frameworks as links; NOFOLLOW extends+ // that to a link at the top. Staged, then published by rename.+ try VPhoneMachineSnapshots.cloneFile(source, to: stage)+ try fm.moveItem(at: stage, to: destination)+ }+}diff --git a/VPhoneKit/VPhoneCoreKitTests/Bundle/OTAUpdateTests.swift b/VPhoneKit/VPhoneCoreKitTests/Bundle/OTAUpdateTests.swiftnew file mode 100644index 00000000..35bf68fa--- /dev/null+++ b/VPhoneKit/VPhoneCoreKitTests/Bundle/OTAUpdateTests.swift@@ -0,0 +1,165 @@+import Darwin+import Foundation+import Testing+@testable import VPhoneCoreKit++struct OTAUpdateTests {+ private func fixture() throws -> (URL, VPhoneBundle) {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ let rom = root.appendingPathComponent("rom.bin")+ try Data([0xAA]).write(to: rom)+ let bundle = try VPhoneBundleOperations.create(+ .init(name: "test", cpuCount: 2, memoryMB: 4096, diskSizeGB: 1, romSource: rom, sepromSource: rom),+ in: VPhoneLibrary(root: root))+ for name in ["Disk.img", "SEPStorage", "nvram.bin", "PatchPlan.plist", "PatchSelection.plist"] {+ try Data("old-\(name)".utf8).write(to: bundle.url.appendingPathComponent(name))+ }+ try VPhoneOTAUpdate.withLock(of: bundle) {+ try VPhoneOTAUpdate.capture(.init(bundle: bundle, build: "24A446", version: "27.0.1", source: Data("{}".utf8)), of: bundle)+ }+ return (root, bundle)+ }++ @Test func `OTA rollback restores host selection and config with all three disk state files`() throws {+ let (root, bundle) = try fixture()+ defer { try? FileManager.default.removeItem(at: root) }+ let config = try Data(contentsOf: bundle.configURL)+ let oldTree = bundle.url.appendingPathComponent("old_Restore")+ try FileManager.default.createDirectory(at: oldTree, withIntermediateDirectories: false)+ try Data("original kernel".utf8).write(to: oldTree.appendingPathComponent("kernel"))+ try VPhoneOTAUpdate.checkpoint(of: bundle)+ var record = try VPhoneOTAUpdate.read(of: bundle)+ record.phase = .quiesced+ try VPhoneOTAUpdate.write(record, of: bundle)+ try VPhoneOTAUpdate.beginPreparation(of: bundle)+ #expect(!FileManager.default.fileExists(atPath: oldTree.path))+ for name in ["Disk.img", "SEPStorage", "nvram.bin", "config.plist", "PatchPlan.plist", "PatchSelection.plist", "OpenAVB.bin"] {+ try Data("new".utf8).write(to: bundle.url.appendingPathComponent(name))+ }+ try VPhoneOTAUpdate.rollback(of: bundle)+ #expect(try Data(contentsOf: bundle.configURL) == config)+ for name in ["Disk.img", "SEPStorage", "nvram.bin", "PatchPlan.plist", "PatchSelection.plist"] {+ #expect(try Data(contentsOf: bundle.url.appendingPathComponent(name)) == Data("old-\(name)".utf8))+ }+ #expect(try String(contentsOf: oldTree.appendingPathComponent("kernel"), encoding: .utf8) == "original kernel")+ #expect(!FileManager.default.fileExists(atPath: bundle.url.appendingPathComponent("OpenAVB.bin").path))+ #expect(try VPhoneOTAUpdate.read(of: bundle).phase == .rolledBack)+ try VPhoneOTAUpdate.rollback(of: bundle)+ #expect(try VPhoneMachineSnapshots.list(of: bundle).count == 1)+ }++ @Test func `checkpoint and preparation can resume without making more disk snapshots`() throws {+ let (root, bundle) = try fixture()+ defer { try? FileManager.default.removeItem(at: root) }+ try VPhoneOTAUpdate.checkpoint(of: bundle)+ try VPhoneOTAUpdate.checkpoint(of: bundle)+ var record = try VPhoneOTAUpdate.read(of: bundle)+ record.phase = .quiesced+ try VPhoneOTAUpdate.write(record, of: bundle)+ try VPhoneOTAUpdate.beginPreparation(of: bundle)+ let partial = bundle.url.appendingPathComponent("target_Restore")+ try FileManager.default.createDirectory(at: partial, withIntermediateDirectories: false)+ try VPhoneOTAUpdate.beginPreparation(of: bundle)+ #expect(!FileManager.default.fileExists(atPath: partial.path))+ #expect(try VPhoneMachineSnapshots.list(of: bundle).count == 1)+ }++ @Test func `running guest blocks checkpoint and rollback before touching host files`() throws {+ let (root, bundle) = try fixture()+ defer { try? FileManager.default.removeItem(at: root) }+ try VPhoneOTAUpdate.checkpoint(of: bundle)+ let fd = open(bundle.url.appendingPathComponent("SEPStorage").path, O_RDONLY)+ defer { close(fd) }+ #expect(throws: VPhoneBundleActivityError.self) { try VPhoneOTAUpdate.checkpoint(of: bundle) }+ #expect(throws: VPhoneBundleActivityError.self) { try VPhoneOTAUpdate.rollback(of: bundle) }+ #expect(try VPhoneOTAUpdate.read(of: bundle).phase == .checkpointed)+ }++ @Test func `journal refuses path injection and another machine`() throws {+ let (root, bundle) = try fixture()+ defer { try? FileManager.default.removeItem(at: root) }+ var record = try VPhoneOTAUpdate.read(of: bundle)+ record.artifacts = ["../escape_Restore"]+ try VPhoneOTAUpdate.write(record, of: bundle)+ #expect(throws: VPhoneOTAUpdate.Failure.self) { try VPhoneOTAUpdate.read(of: bundle) }+ record.artifacts = []+ record.hostFiles = ["../config.plist"]+ try VPhoneOTAUpdate.write(record, of: bundle)+ #expect(throws: VPhoneOTAUpdate.Failure.self) { try VPhoneOTAUpdate.read(of: bundle) }+ }++ @Test func `cannot overwrite recovery journal or prepare before a checkpoint`() throws {+ let (root, bundle) = try fixture()+ defer { try? FileManager.default.removeItem(at: root) }+ let record = try VPhoneOTAUpdate.read(of: bundle)+ #expect(throws: VPhoneOTAUpdate.Failure.self) { try VPhoneOTAUpdate.capture(record, of: bundle) }+ #expect(throws: VPhoneOTAUpdate.Failure.self) { try VPhoneOTAUpdate.beginPreparation(of: bundle) }+ #expect(throws: VPhoneOTAUpdate.Failure.self) { try VPhoneOTAUpdate.rollback(of: bundle) }+ }++ @Test func `a new attempt archives a rolled back journal and retains its snapshot`() throws {+ let (root, bundle) = try fixture()+ defer { try? FileManager.default.removeItem(at: root) }+ try VPhoneOTAUpdate.checkpoint(of: bundle)+ let previous = try VPhoneOTAUpdate.read(of: bundle)+ try VPhoneOTAUpdate.rollback(of: bundle)+ let next = VPhoneOTAUpdate.Record(bundle: bundle, build: "24A446", version: "27.0.1", source: Data("{}".utf8))+ try VPhoneOTAUpdate.withLock(of: bundle) { try VPhoneOTAUpdate.capture(next, of: bundle) }+ #expect(try VPhoneOTAUpdate.read(of: bundle).snapshot == next.snapshot)+ let archived = VPhoneOTAUpdate.directory(of: bundle).deletingLastPathComponent()+ .appendingPathComponent(bundle.name + "-" + previous.snapshot + "/Update.plist")+ #expect(FileManager.default.fileExists(atPath: archived.path))+ #expect(try VPhoneMachineSnapshots.list(of: bundle).map(\.name) == [previous.snapshot])+ }++ @Test func `only successful migration for the running target build passes`() throws {+ func verify(_ result: [String: Any]?, done: Bool? = true, version: String? = "27.0.1") throws {+ try VPhoneOTAUpdate.requireMigration(version: "27.0.1", build: "24A446", actualVersion: version,+ migrationDone: done, result: result)+ }+ try verify(["success": true, "buildVersion": "24A446"])+ for result: [String: Any]? in [nil, [:], ["success": true, "buildVersion": "23G90"],+ ["success": false, "buildVersion": "24A446"], ["buildVersion": "24A446"]] {+ #expect(throws: VPhoneOTAUpdate.Failure.self) { try verify(result) }+ }+ #expect(throws: VPhoneOTAUpdate.Failure.self) { try verify(["success": true, "buildVersion": "24A446"], done: false) }+ #expect(throws: VPhoneOTAUpdate.Failure.self) { try verify(["success": true, "buildVersion": "24A446"], version: "26.6.2") }+ }++ @Test func `coordinator must own the recovery journal before using it`() throws {+ let (root, bundle) = try fixture()+ defer { try? FileManager.default.removeItem(at: root) }+ var record = try VPhoneOTAUpdate.read(of: bundle)+ #expect(throws: VPhoneOTAUpdate.Failure.self) { try VPhoneOTAUpdate.requireOperation("operation123", record: record) }+ record.operationID = "operation123"+ try VPhoneOTAUpdate.requireOperation("operation123", record: record)+ #expect(throws: VPhoneOTAUpdate.Failure.self) { try VPhoneOTAUpdate.requireOperation("other456", record: record) }+ try VPhoneOTAUpdate.requireOperation(nil, record: record) // explicit local maintenance+ }++ @Test func `network is isolated until commit which preserves target ROM and source resource settings`() throws {+ let (root, bundle) = try fixture()+ defer { try? FileManager.default.removeItem(at: root) }+ let source = bundle.manifest+ try VPhoneOTAUpdate.checkpoint(of: bundle)+ try VPhoneOTAUpdate.isolateNetwork(of: bundle)+ let offline = try VPhoneBundle.load(at: bundle.url)+ #expect(offline.manifest.networkConfig.mode == .off)+ #expect(offline.manifest.networkConfig.macAddress == source.networkConfig.macAddress)+ var record = try VPhoneOTAUpdate.read(of: bundle)+ #expect(record.networkIsolated == true)+ #expect(throws: VPhoneOTAUpdate.Failure.self) { try VPhoneOTAUpdate.commit(of: offline) }+ record.phase = .completed+ try VPhoneOTAUpdate.write(record, of: offline)+ try VPhoneOTAUpdate.commit(of: offline)+ let committed = try VPhoneBundle.load(at: bundle.url)+ #expect(committed.manifest.networkConfig == source.networkConfig)+ #expect(committed.manifest.cpuCount == source.cpuCount)+ #expect(committed.manifest.memorySize == source.memorySize)+ #expect(try VPhoneOTAUpdate.read(of: bundle).phase == .committed)+ try VPhoneOTAUpdate.commit(of: committed)+ #expect(throws: VPhoneOTAUpdate.Failure.self) { try VPhoneOTAUpdate.rollback(of: committed) }+ #expect(try VPhoneOTAUpdate.read(of: bundle).phase == .committed)+ }+}diff --git a/scripts/ota-upgrade.zsh b/scripts/ota-upgrade.zshnew file mode 100755index 00000000..539effc2--- /dev/null+++ b/scripts/ota-upgrade.zsh@@ -0,0 +1,109 @@+#!/bin/zsh+set -euo pipefail++# Developer coordinator for the durable fw ota phases. Every VM and privileged+# action uses Launchpad, including its fixed cfw install helper verb.+if (( $# < 5 )); then+ print -u2 'usage: ota-upgrade.zsh VM BUNDLE TARGET-IPSW CLOUDOS-IPSW FULL-OTA [AEA-KEY] [APP-ID ...]'+ exit 2+fi+vm=$1+bundle_version=$2+iphone_source=$3+cloudos_source=$4+ota_source=$5+ota_key=${6:-}+protected_apps=("${@:7}")+cli=$(command -v vphone-launchpad-cli)+completed=false+checkpointed=false+stop_requested=false+commit_requested=false++# Keep `phase X || exit $?`: an errexit exit from inside this function does+# not run the EXIT trap in zsh, so recover would never roll back.+phase() { "$cli" exec --bundle "$bundle_version" fw ota "$1" "$vm" "${@:2}"; }+recover() {+ local code=$?+ trap - EXIT INT TERM+ if [[ $completed == true ]]; then+ exit "$code"+ elif [[ $commit_requested == true ]]; then+ "$cli" vm stop "$vm" || true+ print -u2 'OTA reached its network commit boundary. Target data is retained; resume commit/verify without automatically discarding writes made after networking resumed.'+ elif [[ $checkpointed == true ]]; then+ print -u2 'OTA did not complete; restoring its stopped checkpoint.'+ if "$cli" vm stop "$vm" && phase rollback --force; then+ "$cli" vm start "$vm" --headless --wait --timeout 600 || true+ else+ print -u2 'Rollback could not finish. The OTA journal and snapshot are retained; keep the VM stopped and resume recovery.'+ fi+ elif [[ $stop_requested == true ]]; then+ # Checkpointing has not changed the guest. Put the running source back+ # even when a host backup or snapshot failed before it could be recorded.+ "$cli" vm start "$vm" --headless --wait --timeout 600 || true+ fi+ exit "$code"+}+trap recover EXIT+trap 'exit 130' INT+trap 'exit 143' TERM++# Capability and journal checks happen before the source is stopped. The VM+# must already be bound to this installed bundle; cfw install uses that binding.+machines=$("$cli" vm list)+matches=0+for (( index=0; index<10000; index++ )); do+ if ! candidate=$(print -rn -- "$machines" | /usr/bin/plutil -extract "$index.name" raw -o - - 2>/dev/null); then break; fi+ if [[ $candidate != "$vm" ]]; then continue; fi+ (( matches += 1 ))+ bound=$(print -rn -- "$machines" | /usr/bin/plutil -extract "$index.bundle" raw -o - -)+ if [[ $bound != "$bundle_version" ]]; then+ print -u2 "VM $vm is bound to $bound, not requested OTA bundle $bundle_version. Bind it explicitly before upgrading."+ exit 2+ fi+done+if (( matches != 1 )); then+ print -u2 "Expected exactly one VM named $vm in Launchpad; found $matches."+ exit 2+fi+"$cli" exec --bundle "$bundle_version" fw ota --help >/dev/null+capture_args=()+for app in "${protected_apps[@]}"; do capture_args+=(--app "$app"); done+phase capture "${capture_args[@]}" || exit $?+stop_requested=true+"$cli" vm stop "$vm"+phase checkpoint || exit $?+checkpointed=true+phase isolate || exit $?+"$cli" vm start "$vm" --headless --wait --timeout 600+phase quiesce || exit $?+"$cli" vm stop "$vm"+prepare_args=(--iphone-source "$iphone_source" --cloudos-source "$cloudos_source" --source "$ota_source")+if [[ -n $ota_key ]]; then prepare_args+=(--key "$ota_key"); fi+phase prepare "${prepare_args[@]}" || exit $?+"$cli" cfw install "$vm"+"$cli" vm start "$vm" --headless --wait --timeout 600++# vphoned readiness precedes DataMigrator, UI and profiled readiness. A bounded+# retry is allowed to dismiss post-update Setup and await effective Auto-Lock.+for attempt in {1..60}; do+ if phase complete; then+ # Service profile overrides settle at boot. Verify a cold start before+ # returning the upgraded machine to its normal workload.+ "$cli" vm stop "$vm"+ "$cli" vm start "$vm" --headless --wait --timeout 600+ phase complete || exit $?+ "$cli" vm stop "$vm"+ commit_requested=true+ phase commit || exit $?+ "$cli" vm start "$vm" --headless --wait --timeout 600+ phase verify || exit $?+ completed=true+ print -u2 'OTA completed. Its pre-upgrade snapshot and host recovery state are retained.'+ exit 0+ fi+ /bin/sleep 10+done+print -u2 'Target migration or policy verification did not finish within 10 minutes.'+exit 1diff --git a/scripts/tests/fixtures/vphone-launchpad-cli b/scripts/tests/fixtures/vphone-launchpad-clinew file mode 100755index 00000000..bcc186a7--- /dev/null+++ b/scripts/tests/fixtures/vphone-launchpad-cli@@ -0,0 +1,10 @@+#!/bin/zsh+set -euo pipefail+print -r -- "$*" >> "$OTA_TEST_LOG"+if [[ $1 == vm && $2 == list ]]; then+ print -r -- '[{"name":"test","bundle":"test-bundle"}]'+elif [[ $1 == exec && ${6:-} == ${OTA_TEST_FAIL_PHASE:-unused} ]]; then+ exit 1+else+ print -r -- '{"status":0}'+fidiff --git a/scripts/tests/ota-upgrade-tests.zsh b/scripts/tests/ota-upgrade-tests.zshnew file mode 100755index 00000000..07bf7a60--- /dev/null+++ b/scripts/tests/ota-upgrade-tests.zsh@@ -0,0 +1,40 @@+#!/bin/zsh+set -euo pipefail+tests=${0:a:h}+tmp=$(/usr/bin/mktemp -d "${TMPDIR:-/tmp}/ota-driver-tests.XXXXXX")+trap '/bin/rm -rf "$tmp"' EXIT+export PATH="$tests/fixtures:/usr/bin:/bin:/usr/sbin:/sbin"+export OTA_TEST_LOG="$tmp/calls"+driver="$tests/../ota-upgrade.zsh"++/bin/zsh "$driver" test test-bundle phone.ipsw cloud.ipsw full.aea key com.example.app > /dev/null 2>&1+if /usr/bin/grep -q 'fw ota rollback' "$OTA_TEST_LOG"; then exit 1; fi+/usr/bin/grep -q 'cfw install test' "$OTA_TEST_LOG"+/usr/bin/grep -q 'fw ota complete test' "$OTA_TEST_LOG"+/usr/bin/grep -q 'fw ota isolate test' "$OTA_TEST_LOG"+/usr/bin/grep -q 'fw ota commit test' "$OTA_TEST_LOG"+/usr/bin/grep -q 'fw ota verify test' "$OTA_TEST_LOG"++export OTA_TEST_LOG="$tmp/prepare-failure"+export OTA_TEST_FAIL_PHASE=prepare+if /bin/zsh "$driver" test test-bundle phone.ipsw cloud.ipsw full.aea > /dev/null 2>&1; then exit 1; fi+/usr/bin/grep -q 'fw ota rollback test' "$OTA_TEST_LOG"+if /usr/bin/grep -q 'cfw install test' "$OTA_TEST_LOG"; then exit 1; fi++export OTA_TEST_LOG="$tmp/checkpoint-failure"+export OTA_TEST_FAIL_PHASE=checkpoint+if /bin/zsh "$driver" test test-bundle phone.ipsw cloud.ipsw full.aea > /dev/null 2>&1; then exit 1; fi+if /usr/bin/grep -q 'fw ota rollback test' "$OTA_TEST_LOG"; then exit 1; fi+/usr/bin/grep -q 'vm start test' "$OTA_TEST_LOG"++export OTA_TEST_LOG="$tmp/wrong-binding"+unset OTA_TEST_FAIL_PHASE+if /bin/zsh "$driver" test wrong-bundle phone.ipsw cloud.ipsw full.aea > /dev/null 2>&1; then exit 1; fi+if /usr/bin/grep -q 'vm stop' "$OTA_TEST_LOG"; then exit 1; fi++export OTA_TEST_LOG="$tmp/post-commit-failure"+export OTA_TEST_FAIL_PHASE=verify+if /bin/zsh "$driver" test test-bundle phone.ipsw cloud.ipsw full.aea > /dev/null 2>&1; then exit 1; fi+if /usr/bin/grep -q 'fw ota rollback test' "$OTA_TEST_LOG"; then exit 1; fi+if [[ $(/usr/bin/tail -1 "$OTA_TEST_LOG") != 'vm stop test' ]]; then exit 1; fi+print 'OTA driver: success, rollback, checkpoint failure and wrong-binding checks passed'