Run a virtual iPhone on an Apple Silicon Mac.
Swift
Move firmware preparation into native Swift pipeline
Lakr890032501a3e
diff --git a/AGENTS.md b/AGENTS.mdindex 3e3c2548..8bd82fa0 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -28,18 +28,11 @@ For any changes applying new patches, also update research/0_binary_patch_compar- If working on kernel analysis, symbolication lookups, or kernel patch reasoning, read `skills/kernel-analysis-vphone600/SKILL.md` first.- Use this skill as the default procedure for `vphone600` kernel work.-## Firmware Variants+## Firmware Mode-| Variant | Boot Chain | CFW | Make Targets |-| ---------------- | :------------: | :-------: | ---------------------------------- |-| **Regular** | 52 patches | 10 phases | `fw_patch` + `cfw_install` |-| **Development** | 66 patches | 12 phases | `fw_patch_dev` + `cfw_install_dev` |-| **Jailbreak** | 127 patches | 14 phases | `fw_patch_jb` + `cfw_install_jb` |-| **Experimental** | 141 patches | 18 phases | `fw_patch_exp` + `cfw_install_exp` |--> JB finalization (symlinks, Sileo, apt, TrollStore) runs automatically on first boot via `/cores/vphone_jb_setup.sh` LaunchDaemon. Monitor progress: `/var/log/vphone_jb_setup.log`.--> EXP is a JB superset that patches the kernel and DSC to make some Apple services think the device is not a VM, while keeping VM-specific services (graphics passthrough, compute/accel fast paths) working correctly. Other variants are deliberately NOT affected by these changes.+The public CLI exposes only JB: `vphone-cli fw patch` and `vphone-cli cfw install`.+The legacy CFW shell installer still contains first-boot package setup; its+removal is tracked in the integration work. Do not add another public variant.See `research/` for detailed firmware pipeline, component origins, patch breakdowns, and boot flow documentation.@@ -186,7 +179,6 @@ scripts/ # Shell only — the CFW patchers are `vphone-├── check_aux.sh [b] # The self-containment admission gates — `make check-aux`├── setup_tools.sh [b] # Builds insert_dylib, the Mach-O byte-parity test reference├── tail_jb_patch_logs.sh [b] # Tail JB patch log output-├── fw_prepare.sh [d] # Download IPSWs, merge cloudOS into iPhone├── cfw_install.sh [d] # Install CFW (regular)├── cfw_install_dev.sh [d] # Regular + rpcserver daemon├── cfw_install_jb.sh [d] # Regular + jetsam fix + procursusdiff --git a/Makefile b/Makefileindex 6a113bb7..19fc2cd3 100644--- a/Makefile+++ b/Makefile@@ -93,13 +93,8 @@ help:@echo " make boot_dfu Boot VM in DFU mode (reads from config.plist)"@echo ""@echo "Firmware pipeline:"- @echo " make fw_prepare Download IPSWs, extract, merge"- @echo " Options: LIST_FIRMWARES=1 List downloadable iPhone IPSWs for IPHONE_DEVICE and exit"- @echo " IPHONE_DEVICE= Device identifier for firmware lookup (default: iPhone17,3)"- @echo " IPHONE_VERSION= Resolve a downloadable iPhone version to an IPSW URL"- @echo " IPHONE_BUILD= Resolve a downloadable iPhone build to an IPSW URL"- @echo " IPHONE_SOURCE= URL or local path to iPhone IPSW"- @echo " CLOUDOS_SOURCE= URL or local path to cloudOS IPSW"+ @echo " vphone-cli fw prepare <name> --iphone-source IPSW --cloudos-source IPSW"+ @echo " Prepare a VM's restore tree from two IPSWs"@echo " make fw_patch Patch boot chain with the JB Swift pipeline"@echo " Options: FORCE_EXC_GUARD=1 Force the EXC_GUARD Mach-port-guard disable patch even on bases"@echo " that don't strictly need it to boot (e.g. a 3rd-party app's"@@ -350,10 +345,7 @@ boot_dfu: build boot_binary_check# Firmware pipeline# ═══════════════════════════════════════════════════════════════════-.PHONY: fw_prepare fw_patch--fw_prepare:- cd "$(VM_DIR)" && bash "$(CURDIR)/$(SCRIPTS)/fw_prepare.sh"+.PHONY: fw_patchfw_patch: patcher_build"$(CURDIR)/$(PATCHER_BINARY)" patch-firmware --vm-directory "$(VM_DIR_ABS)" \diff --git a/README.md b/README.mdindex 64eb9824..93509a1f 100644--- a/README.md+++ b/README.md@@ -55,7 +55,9 @@ Nothing shipped runs it.One command creates a VM end-to-end (download → patch → DFU restore → CFW install → first boot):```bash-vphone-cli vm create myphone -V jb # -V / --variant+vphone-cli vm create myphone \+ --iphone-source /path/to/iPhone17,3_Restore.ipsw \+ --cloudos-source /path/to/cloudOS.ipswvphone-cli vm launch myphone```@@ -82,15 +84,16 @@ vphone-cli vm delete iphone16```bashvphone-cli vm new myphone # 1. empty bundle-vphone-cli fw prepare myphone --iphone-version 26.1 # 2. download + merge IPSWs-vphone-cli fw patch myphone --variant jb # 3. patch the boot chain+vphone-cli fw prepare myphone --iphone-source /path/to/iPhone17,3_Restore.ipsw \+ --cloudos-source /path/to/cloudOS.ipsw # 2. merge IPSWs+vphone-cli fw patch myphone # 3. patch the JB boot chainvphone-cli vm launch myphone --dfu & # 4. boot into DFU (background)vphone-cli restore myphone --get-shsh # fetch SHSHvphone-cli restore myphone # DFU restorevphone-cli vm stop myphone # stop the DFU boot-vphone-cli cfw install myphone --variant jb # 5. install CFW (host-mount; asks for sudo)+vphone-cli cfw install myphone # 5. install CFW (host-mount; asks for sudo)vphone-cli vm launch myphone # 6. first boot```@@ -101,24 +104,15 @@ libirecovery and idevicerestore directly — no external restore tool, no setupstep before the first one works. Add `--offline` to restore from a `.shsh`already saved beside the VM instead of asking Apple for a fresh one.-## Firmware Variants+## Firmware Mode-Five patch variants with increasing security bypass — pass one to `--variant`:--| Variant | Boot Chain | CFW | Notes |-| ------------ | ----------- | --------- | ----------------------------------------------------------------- |-| `less` | 4 patches | 2 phases | Patchless — keeps iOS mitigations enabled |-| `regular` | 42 patches | 10 phases | AMFI/SSV/Img4/TXM bypass |-| `dev` | 53 patches | 12 phases | + TXM entitlement/debug bypass |-| `jb` | 113 patches | 14 phases | + full jailbreak (Sileo, TrollStore auto-install on first boot) |-| `exp` | 141 patches | 18 phases | JB superset + anti-VM-detection research patches |+The CLI exposes one firmware mode: JB. There is no `--variant` choice.See [`research/0_binary_patch_comparison.md`](./research/0_binary_patch_comparison.md) for the per-component breakdown.## Running & Connecting- **SSH (jailbreak):** `ssh -p 22222 mobile@<vm-ip>` (password `alpine`)-- **SSH (regular/dev):** `ssh -p 22222 root@<vm-ip>`- **VNC:** `vnc://<vm-ip>:5901`## Locations@@ -130,7 +124,7 @@ Everything vphone-cli creates lives under `~/.vphone/` — kept outside the repo| `~/.vphone/` | The per-user data root — override the entire location with `$VPHONE_ROOT`. || `~/.vphone/VMs/` | VM bundles — one directory per VM. This is the library; override with `$VPHONE_LIBRARY_ROOT`. || `~/.vphone/ipsws/`| Downloaded iPhone + cloudOS IPSWs, cached and reused across VMs. |-| `~/.vphone/tools/`| Cached APFS seal-volume artifacts (`apfs_sealvolume_<version>`) fetched during `fw prepare`. |+| `~/.vphone/tools/`| Cached APFS seal-volume artifacts used by firmware patching. || `~/.vphone/debs/` | Cached `.deb` packages the `jb`/`exp` CFW install lays into the guest (Sileo, apt, …). |Precedence: the per-item override `$VPHONE_LIBRARY_ROOT` wins over `$VPHONE_ROOT`, which wins over the `~/.vphone` default. The `ipsws/`, `tools/`, and `debs/` caches always sit directly under whichever root is active.@@ -243,7 +237,7 @@ always launches, so its cdhash is not the one you want.**System apps won't install** — during iOS setup, don't pick Japan or the EU as your region (extra regulatory checks the VM can't satisfy); pick e.g. United States.-**App crashes on launch with `EXC_GUARD` / `GUARD_TYPE_MACH_PORT`** — re-patch with `vphone-cli fw patch <name> --variant <v> --force-exc-guard`, then re-restore/install ([#291](https://github.com/Lakr233/vphone-cli/issues/291)). Always on for iOS 18 bases.+**App crashes on launch with `EXC_GUARD` / `GUARD_TYPE_MACH_PORT`** — re-patch with `vphone-cli fw patch <name> --force-exc-guard`, then re-restore/install ([#291](https://github.com/Lakr233/vphone-cli/issues/291)). Always on for iOS 18 bases.**Install a `.ipa`/`.tipa`** — use the running VM's Install menu (drag-drop or file picker).@@ -257,4 +251,4 @@ always launches, so its cdhash is not the one you want.## Acknowledgements-- [wh1te4ever/super-tart-vphone-writeup](https://github.com/wh1te4ever/super-tart-vphone-writeup)\ No newline at end of file+- [wh1te4ever/super-tart-vphone-writeup](https://github.com/wh1te4ever/super-tart-vphone-writeup)diff --git a/research/firmware_manifest_and_origins.md b/research/firmware_manifest_and_origins.mdindex d2286b57..2bace0cd 100644--- a/research/firmware_manifest_and_origins.md+++ b/research/firmware_manifest_and_origins.md@@ -12,8 +12,8 @@ runtime components use the **vphone600** variant because its DeviceTree sets MKB(allows boot without system keybag), its SEP firmware matches the vphone600 device tree,and `hardware target` reports as `vphone600ap` for proper iPhone emulation.-`fw_prepare.sh` downloads both IPSWs, merges cloudOS firmware into the iPhone-restore directory, then `fw_manifest.py` generates the hybrid BuildManifest.+`vphone-cli fw prepare` resolves both IPSWs, merges cloudOS firmware into the+iPhone restore directory, then generates the hybrid BuildManifest in Swift.---diff --git a/scripts/build.sh b/scripts/build.shindex 6bc54fa4..7cb7623f 100755--- a/scripts/build.sh+++ b/scripts/build.sh@@ -174,7 +174,7 @@ zsh scripts/dist_manifest.sh | rsync -a --files-from=- scripts/ "${RES}/scripts/[[ -d .build/guest ]] && cp -R .build/guest "${RES}/guest"[[ -f .build/vphoned.signed ]] && cp -f .build/vphoned.signed "${RES}/vphoned.signed" || true# debs.list = extra-deb manifest (fetch_debs.sh reads $base/debs.list); README.md-# = the Tested-Environments table fw_prepare.sh reads to label Supported firmwares.+# = the Tested-Environments table `vphone-cli fw prepare` reads for firmware status.cp -f debs.list "${RES}/debs.list"cp -f README.md "${RES}/README.md"echo " bundled: scripts/ (dist tier), guest/ (5 iOS binaries), vphoned.signed,"diff --git a/scripts/fw_prepare.sh b/scripts/fw_prepare.shdeleted file mode 100755index 5b0f2cdc..00000000--- a/scripts/fw_prepare.sh+++ /dev/null@@ -1,498 +0,0 @@-#!/bin/bash-# vphone-tier: dist-# fw_prepare.sh — Download/copy, merge, and generate hybrid restore firmware.-# Combines cloudOS boot chain with iPhone OS images for vresearch101.-#-# Accepts:-# - direct iPhone IPSW URLs or local file paths-# - version/build selectors for the target device-# - listing of all downloadable IPSWs for the target device-# - The "VARIANT" environment variable to download apfs_sealvolume for the patchless mode-#-# Listing and selection are resolved through the `ipsw` CLI already used-# elsewhere in this repo, so the script can work with the full downloadable-# restore history instead of only Apple's current PMV asset set.-set -euo pipefail-SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"--DEFAULT_IPHONE_DEVICE="iPhone17,3"-DEFAULT_IPHONE_SOURCE="https://updates.cdn-apple.com/2025FallFCS/fullrestores/089-13864/668EFC0E-5911-454C-96C6-E1063CB80042/iPhone17,3_26.1_23B85_Restore.ipsw"-DEFAULT_CLOUDOS_SOURCE="https://updates.cdn-apple.com/private-cloud-compute/399b664dd623358c3de118ffc114e42dcd51c9309e751d43bc949b98f4e31349"-README_PATH="${SCRIPT_DIR}/../README.md"--usage() {- cat <<EOF-Usage:- $(basename "$0") [iphone_source_or_selector] [cloudos_source]- $(basename "$0") --list [--device iPhone17,3]- $(basename "$0") --version 26.3.1 [--device iPhone17,3] [--cloudos-source URL_OR_PATH]- $(basename "$0") --build 23D9133 [--device iPhone17,3] [--cloudos-source URL_OR_PATH]--Examples:- $(basename "$0") --list- $(basename "$0") 26.3.1- $(basename "$0") --build 23D9133- $(basename "$0") /path/to/iPhone17,3_26.1_23B85_Restore.ipsw--Environment variables:- LIST_FIRMWARES Set to 1 to list downloadable IPSWs and exit- IPHONE_DEVICE Device identifier for IPSW lookup (default: ${DEFAULT_IPHONE_DEVICE})- IPHONE_VERSION iOS version shorthand to resolve to a downloadable IPSW URL- IPHONE_BUILD Build shorthand to resolve to a downloadable IPSW URL- IPHONE_SOURCE Direct iPhone IPSW URL or local path- CLOUDOS_SOURCE Direct cloudOS IPSW URL or local path- IPSW_DIR Directory used to cache downloaded/copied IPSWs-EOF-}--die() {- echo "ERROR: $*" >&2- exit 1-}--is_local() {- [[ "$1" != http://* && "$1" != https://* ]]-}--looks_like_source() {- local value="$1"- [[ "$value" == http://* || "$value" == https://* || "$value" == *.ipsw || "$value" == */* || -f "$value" ]]-}--looks_like_build() {- [[ "$1" =~ ^[0-9]{2}[A-Z][0-9A-Z]+$ ]]-}--# Locate one of this project's own binaries (vphone-cli, vphone-archive).-# Same resolution order as scripts/cfw_install_host.sh and cfw-kit/run.sh:-# VPHONE_CLI_BIN when a vphone-cli subcommand invoked us — the wanted binary is-# its sibling — otherwise a dev tree or the .app, where scripts/ sits in-# Contents/Resources and the binaries are one level up in MacOS. Deliberately-# not `command -v`: these have to be the binaries we built, not another copy-# that happens to be on PATH. Prints the path; returns non-zero when it finds-# nothing, so the caller can `die` with something a user can act on.-resolve_vphone_binary() {- local name="$1" proj_root candidate- proj_root="$(cd "$SCRIPT_DIR/.." && pwd)"- if [[ -n "${VPHONE_CLI_BIN:-}" ]]; then- candidate="$(dirname "$VPHONE_CLI_BIN")/$name"- [[ -x "$candidate" ]] && { printf '%s\n' "$candidate"; return 0; }- fi- for candidate in "$proj_root/.build/release/$name" "$(dirname "$proj_root")/MacOS/$name"; do- [[ -x "$candidate" ]] && { printf '%s\n' "$candidate"; return 0; }- done- return 1-}--# Only ever used to name a cache file, so a short hash is enough.-#-# One absolute path, no fallback ladder. There used to be three branches —-# `shasum`, then `sha256sum`, then Python — and every one of them was a PATH-# lookup that could pick up something other than the system tool. /usr/bin/shasum-# ships with macOS; sha256sum does not, and never resolved here.-source_hash_suffix() {- printf '%s' "$1" | /usr/bin/shasum -a 256 | /usr/bin/awk '{print substr($1, 1, 12)}'-}--derive_cache_ipsw_name() {- local src="$1" fallback_stem="$2"- local base stem suffix- base="${src##*/}"- base="${base%%\?*}"- base="${base%%\#*}"-- if [[ "$base" == *.ipsw ]]; then- printf '%s\n' "$base"- return- fi-- stem="${base%.*}"- [[ -n "$stem" ]] || stem="$fallback_stem"- stem="$(printf '%s' "$stem" | tr -cs '[:alnum:]_.-' '_')"- [[ -n "$stem" ]] || stem="$fallback_stem"- if [[ ${#stem} -gt 48 ]]; then- stem="${stem:0:48}"- fi-- suffix="$(source_hash_suffix "$src")"- printf '%s-%s.ipsw\n' "$stem" "$suffix"-}--# `ipsw download ipsw --device D --urls` was here. `vphone-cli fw urls` prints-# the same lines from AppleDB's catalogue and ships in the bundle.-downloadable_ipsw_urls() {- local cli- cli="$(firmware_matrix_cli)"- "$cli" fw urls --device "$1"-}--supports_color() {- [[ -z "${NO_COLOR:-}" ]] && { [[ -t 1 ]] || [[ "${CLICOLOR_FORCE:-0}" == "1" ]]; }-}--style_status() {- local status="$1"- if ! supports_color; then- printf '%s' "$status"- return- fi- case "$status" in- Supported)- printf '\033[32m%s\033[0m' "$status"- ;;- "Not Tested")- printf '\033[33m%s\033[0m' "$status"- ;;- Unsupported)- printf '\033[31m%s\033[0m' "$status"- ;;- *)- printf '%s' "$status"- ;;- esac-}--# The firmware support matrix — the README's "Tested Environments" table joined-# against what Apple still serves — lives in VPhoneCore/VPhoneFirmwareMatrix.swift-# now. The shell keeps the half it is good at: running `ipsw` and handing the-# output over in DOWNLOADABLE_IPSW_URLS, the same variable the Python read, so-# the contract between the two halves did not change.-#-# Colour is decided per stream inside the callee, from NO_COLOR, CLICOLOR_FORCE-# and isatty: `fw list` styles stdout, `fw resolve` styles stderr (its stdout is-# the $( ) capture below). That only stays right because the binary inherits-# this script's descriptors — do not add a pipe or a tee.-firmware_matrix_cli() {- resolve_vphone_binary vphone-cli \- || die "cannot find vphone-cli for the firmware matrix — run 'make build'"-}--list_firmwares() {- local device="$1" readme_path="$2" cli downloadable_urls- # Separate from `local`, which would swallow the substitution's status.- cli="$(firmware_matrix_cli)"- downloadable_urls="$(downloadable_ipsw_urls "$device")"- DOWNLOADABLE_IPSW_URLS="$downloadable_urls" \- "$cli" fw list --device "$device" --readme "$readme_path"-}--resolve_selector_from_downloads() {- local device="$1" version="$2" build="$3" readme_path="$4" cli downloadable_urls- cli="$(firmware_matrix_cli)"- downloadable_urls="$(downloadable_ipsw_urls "$device")"- DOWNLOADABLE_IPSW_URLS="$downloadable_urls" \- "$cli" fw resolve --device "$device" --version "$version" \- --build "$build" --readme "$readme_path"-}--# /usr/bin/curl, and nothing else.-#-# This used to try aria2c first, then curl, then wget, and die if it found-# none — three PATH lookups, two of which are Homebrew packages, in a script-# that ships inside the .app. A user without them got a slower download; a user-# with a different aria2c on PATH got whatever that did. curl is part of macOS-# and resumes with -C -, which is the only thing aria2c was here for that-# mattered. An IPSW is one 11 GB file from Apple's CDN; the parallelism was-# never the bottleneck.-download_file() {- local src="$1" out="$2" rc=0- /usr/bin/curl --fail --location --progress-bar -C - -o "$out" "$src" || rc=$?- # 33 = HTTP range error — typically means the file is already fully there.- [[ $rc -eq 33 ]] && return 0- return $rc-}--fetch() {- local src="$1" out="$2"- if [[ -f "$out" ]]; then- if is_local "$src"; then- echo "==> Skipping: '$out' already exists."- return- fi- # File exists — could be partial (interrupted) or complete.- # Attempt to resume; curl -C - is a no-op on a fully-downloaded file.- local local_size- local_size=$(wc -c < "$out" | tr -d ' ')- echo "==> Found existing ${out##*/} (${local_size} bytes), resuming ..."- local rc=0- download_file "$src" "$out" || rc=$?- if [[ $rc -eq 0 ]]; then- return- fi- # curl exit 22 = HTTP error; with -C - on a complete file the server- # returns 416 which --fail maps to exit 22. Verify via content-length.- if [[ $rc -eq 22 ]]; then- local remote_size- remote_size=$(curl -sI --location "$src" | awk 'tolower($1)=="content-length:"{v=$2} END{print v}' | tr -d '\r')- if [[ -n "$remote_size" && "$local_size" -ge "$remote_size" ]]; then- echo "==> Already fully downloaded (${local_size} bytes)."- return- fi- fi- echo "==> Resume failed; retrying full download ..."- rm -f "$out"- fi- if is_local "$src"; then- [[ -f "$src" ]] || die "Local IPSW not found: $src"- echo "==> Copying ${src##*/} ..."- cp "$src" "$out"- else- echo "==> Downloading ${out##*/} ..."- if ! download_file "$src" "$out"; then- # Keep partial file on disk so the next run can resume- die "Failed to download '$src'"- fi- fi-}--extract() {- local zip="$1" cache="$2" out="$3" archive_bin- if [[ -d "$cache" && -n "$(ls -A "$cache" 2>/dev/null)" ]]; then- echo "==> Cached: ${cache##*/}"- else- rm -rf "$cache"- echo "==> Extracting ${zip##*/} ..."- mkdir -p "$cache"- # vphone-archive instead of unzip: libarchive in-process, measured at- # 0.75s against unzip's 4.97s on a real 1.2 GB IPSW, with identical- # output — 88 files, 10 dirs, every content digest and mode matching.- # The extractor's host preset applies the umask and never restores- # setuid, which is what `unzip` did here, and the cache directory is- # freshly removed above so there is nothing to overwrite (`unzip -o`).- archive_bin="$(resolve_vphone_binary vphone-archive)" \- || die "vphone-archive not found — run 'make build'"- "$archive_bin" extract -f "$zip" -C "$cache"- chmod -R u+w "$cache"- fi- rm -rf "$out"- echo "==> Cloning ${cache##*/} → ${out##*/} ..."- # -c makes this an APFS clone, which is what the line above already claims- # it is. Without it a full second copy of the extracted IPSW is written —- # ~11.5 GB for an iPhone restore — on top of the .ipsw and the cache, and- # the patchers then rewrite only a handful of files out of it. Cloning is- # copy-on-write, so the bytes are shared until something changes them.- # Falls back to copyfile(2) where the target cannot be cloned, so this is- # safe off APFS too.- cp -Rc "$cache" "$out"-}--# apfs_sealvolume is what seals a rebuilt system volume, and it is not in an-# iPhone restore image — only in the macOS one of the same marketing version.-#-# This was forty lines of shell around six `ipsw` invocations: resolve a macOS-# build from AppleDB, range-fetch BuildManifest.plist out of an 18 GB remote-# zip, read the ramdisk path out of it, range-fetch that, unwrap the IM4P, mount-# it, copy one file. `vphone-cli fw seal-tool` does all of it — the remote zip-# reader, the IM4P unwrapper and the AppleDB client are all in the binary now —-# and this function is left only to work out which version to ask for and where-# to put it.-download_apfs_sealvolume() {- local src="$1" base ios_version PROJECT_DIR TOOLS_PREFIX cli-- base="$(basename "$src")"- ios_version="$(/usr/bin/awk -F_ 'NF >= 2 { print $2 }' <<<"$base")"-- if [[ -z "$ios_version" ]]; then- echo "Error: could not determine iOS version from filename: $base" >&2- return 1- fi-- PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"- TOOLS_PREFIX="${VPHONE_SEAL_DIR:-$PROJECT_DIR/.tools}"- cli="$(firmware_matrix_cli)"- "$cli" fw seal-tool --version "$ios_version" --output "$TOOLS_PREFIX"-}--LIST_FIRMWARES="${LIST_FIRMWARES:-0}"-IPHONE_DEVICE="${IPHONE_DEVICE:-$DEFAULT_IPHONE_DEVICE}"-IPHONE_VERSION="${IPHONE_VERSION:-}"-IPHONE_BUILD="${IPHONE_BUILD:-}"-IPHONE_SOURCE="${IPHONE_SOURCE:-}"-CLOUDOS_SOURCE="${CLOUDOS_SOURCE:-}"-IPSW_DIR="${IPSW_DIR:-${SCRIPT_DIR}/../ipsws}"--POSITIONAL=()-while [[ $# -gt 0 ]]; do- case "$1" in- --list)- LIST_FIRMWARES=1- shift- ;;- --device)- [[ $# -ge 2 ]] || die "--device requires a value"- IPHONE_DEVICE="$2"- shift 2- ;;- --version)- [[ $# -ge 2 ]] || die "--version requires a value"- IPHONE_VERSION="$2"- shift 2- ;;- --build)- [[ $# -ge 2 ]] || die "--build requires a value"- IPHONE_BUILD="$2"- shift 2- ;;- --iphone-source)- [[ $# -ge 2 ]] || die "--iphone-source requires a value"- IPHONE_SOURCE="$2"- shift 2- ;;- --cloudos-source)- [[ $# -ge 2 ]] || die "--cloudos-source requires a value"- CLOUDOS_SOURCE="$2"- shift 2- ;;- -h|--help)- usage- exit 0- ;;- --)- shift- while [[ $# -gt 0 ]]; do- POSITIONAL+=("$1")- shift- done- ;;- -*)- die "Unknown option: $1"- ;;- *)- POSITIONAL+=("$1")- shift- ;;- esac-done--if [[ ${#POSITIONAL[@]} -gt 2 ]]; then- die "Too many positional arguments"-fi--if [[ -z "$IPHONE_SOURCE" && -z "$IPHONE_VERSION" && -z "$IPHONE_BUILD" && ${#POSITIONAL[@]} -ge 1 ]]; then- if looks_like_source "${POSITIONAL[0]}"; then- IPHONE_SOURCE="${POSITIONAL[0]}"- elif looks_like_build "${POSITIONAL[0]}"; then- IPHONE_BUILD="${POSITIONAL[0]}"- else- IPHONE_VERSION="${POSITIONAL[0]}"- fi-fi--if [[ -z "$CLOUDOS_SOURCE" && ${#POSITIONAL[@]} -ge 2 ]]; then- CLOUDOS_SOURCE="${POSITIONAL[1]}"-fi--if [[ "$LIST_FIRMWARES" == "1" ]]; then- list_firmwares "$IPHONE_DEVICE" "$README_PATH"- exit 0-fi--if [[ -n "$IPHONE_SOURCE" && ( -n "$IPHONE_VERSION" || -n "$IPHONE_BUILD" ) ]]; then- die "Use either IPHONE_SOURCE or version/build selection, not both"-fi--if [[ -n "$IPHONE_VERSION" || -n "$IPHONE_BUILD" ]]; then- selection="$(resolve_selector_from_downloads "$IPHONE_DEVICE" "$IPHONE_VERSION" "$IPHONE_BUILD" "$README_PATH")" || {- status=$?- [[ $status -eq 2 ]] && exit 2- exit "$status"- }- IFS=$'\t' read -r selected_version selected_build selected_url selected_status <<<"$selection"- IPHONE_SOURCE="$selected_url"- echo "==> Selected downloadable firmware:"- echo " Device: $IPHONE_DEVICE"- echo " Version: $selected_version"- echo " Build: $selected_build"- echo " URL: $selected_url"- echo " Status: $(style_status "$selected_status")"-fi--IPHONE_SOURCE="${IPHONE_SOURCE:-$DEFAULT_IPHONE_SOURCE}"-CLOUDOS_SOURCE="${CLOUDOS_SOURCE:-$DEFAULT_CLOUDOS_SOURCE}"--mkdir -p "$IPSW_DIR"--IPHONE_IPSW="${IPHONE_SOURCE##*/}"-IPHONE_DIR="${IPHONE_IPSW%.ipsw}"-CLOUDOS_IPSW="$(derive_cache_ipsw_name "$CLOUDOS_SOURCE" "pcc-base")"-CLOUDOS_DIR="${CLOUDOS_IPSW%.ipsw}"-IPHONE_IPSW_PATH="${IPSW_DIR}/${IPHONE_IPSW}"-CLOUDOS_IPSW_PATH="${IPSW_DIR}/${CLOUDOS_IPSW}"--echo "=== prepare_firmware ==="-echo " Device: $IPHONE_DEVICE"-echo " iPhone: $IPHONE_SOURCE"-echo " CloudOS: $CLOUDOS_SOURCE"-echo " IPSWs: $IPSW_DIR"-echo " Output: $(pwd)/$IPHONE_DIR/"-echo ""--fetch "$IPHONE_SOURCE" "$IPHONE_IPSW_PATH"-fetch "$CLOUDOS_SOURCE" "$CLOUDOS_IPSW_PATH"--VARIANT="${VARIANT:-}"-if [[ "$VARIANT" == "less" ]]; then- download_apfs_sealvolume "$IPHONE_SOURCE"-else- echo "==> Downloading apfs sealvolume (skipped — patchless variant only)"-fi--IPHONE_CACHE="${IPSW_DIR}/${IPHONE_DIR}"-CLOUDOS_CACHE="${IPSW_DIR}/${CLOUDOS_DIR}"--extract "$IPHONE_IPSW_PATH" "$IPHONE_CACHE" "$IPHONE_DIR"-extract "$CLOUDOS_IPSW_PATH" "$CLOUDOS_CACHE" "$CLOUDOS_DIR"--# Keep exactly one active restore tree in the working directory so fw_patch-# cannot accidentally pick a stale older firmware directory.-cleanup_old_restore_dirs() {- local keep="$1"- local found=0- shopt -s nullglob- for dir in *Restore*; do- [[ -d "$dir" ]] || continue- [[ "$dir" == "$keep" ]] && continue- if [[ $found -eq 0 ]]; then- echo "==> Removing stale restore directories ..."- found=1- fi- echo " rm -rf $dir"- rm -rf "$dir"- done- shopt -u nullglob-}-cleanup_old_restore_dirs "$IPHONE_DIR"--echo "==> Importing cloudOS firmware components ..."--cp "${CLOUDOS_DIR}"/kernelcache.* "$IPHONE_DIR"/--for sub in agx all_flash ane dfu pmp; do- cp "${CLOUDOS_DIR}/Firmware/${sub}"/* "$IPHONE_DIR/Firmware/${sub}"/-done--cp "${CLOUDOS_DIR}"/Firmware/*.im4p "$IPHONE_DIR/Firmware"/--cp -n "${CLOUDOS_DIR}"/*.dmg "$IPHONE_DIR"/ 2>/dev/null || true-cp -n "${CLOUDOS_DIR}"/Firmware/*.dmg.trustcache "$IPHONE_DIR/Firmware"/ 2>/dev/null || true--cp "$IPHONE_DIR/BuildManifest.plist" "$IPHONE_DIR/iPhone-BuildManifest.plist"--echo "==> Generating hybrid plists ..."-VPHONE_CLI="$(resolve_vphone_binary vphone-cli)" \- || die "cannot find vphone-cli to generate the hybrid plists — run 'make build'"-"$VPHONE_CLI" fw manifest "$IPHONE_DIR" "$CLOUDOS_DIR"--echo "==> Cleaning up ..."-rm -rf "$CLOUDOS_DIR"--# Drop the extracted base-IPSW caches (kept .ipsw re-extracts). VPHONE_KEEP_ARTIFACTS opts out.-if [[ -z "${VPHONE_KEEP_ARTIFACTS:-}" ]]; then- hybrid="$(cd "$IPHONE_DIR" && pwd -P)"- for cache in "$IPHONE_CACHE" "$CLOUDOS_CACHE"; do- [[ -d "$cache" && "$(cd "$cache" && pwd -P)" != "$hybrid" ]] && rm -rf "$cache"- done-fi--echo "==> Done. Restore directory ready: $IPHONE_DIR/"-echo " Run 'make fw_patch' to patch boot-chain components."diff --git a/sources/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift b/sources/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swiftindex 0e6d229d..64e00f0d 100644--- a/sources/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift+++ b/sources/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift@@ -28,7 +28,7 @@ extension FirmwarePipeline {.sorted(by: compareRestoreDirectories)guard let restoreDir = contents.first else {- throw PatcherError.fileNotFound("Restore directory in \(vmDirectory.path). Run make fw_prepare first.")+ throw PatcherError.fileNotFound("Restore directory in \(vmDirectory.path). Run vphone-cli fw prepare first.")}return restoreDir}diff --git a/sources/VPhoneArchive/VPhoneIPSWCache.swift b/sources/VPhoneArchive/VPhoneIPSWCache.swiftnew file mode 100644index 00000000..06e7093b--- /dev/null+++ b/sources/VPhoneArchive/VPhoneIPSWCache.swift@@ -0,0 +1,104 @@+import CryptoKit+import Foundation++/// Resolves a local IPSW or downloads one into a reusable, validated cache.+/// Source archives are never rewritten. Remote downloads become visible only+/// after their BuildManifest can be read and their transfer size checks out.+public enum VPhoneIPSWCache {+ public struct Archive: Sendable {+ public let file: URL+ public let version: String+ public let build: String+ }++ public enum Error: Swift.Error, LocalizedError {+ case unsupportedSource(String)+ case missingFile(URL)+ case invalidManifest(URL)+ case unexpectedHTTP(URL, Int)+ case incompleteDownload(URL, expected: Int64, actual: Int64)++ public var errorDescription: String? {+ switch self {+ case let .unsupportedSource(source): "Unsupported IPSW source: \(source)"+ case let .missingFile(file): "IPSW does not exist: \(file.path)"+ case let .invalidManifest(file): "IPSW has no readable BuildManifest.plist: \(file.path)"+ case let .unexpectedHTTP(url, status): "IPSW download returned HTTP \(status): \(url)"+ case let .incompleteDownload(url, expected, actual):+ "IPSW download from \(url) is incomplete: \(actual) of \(expected) bytes"+ }+ }+ }++ public static func resolve(+ _ source: String,+ in cacheDirectory: URL,+ session: URLSession = .shared+ ) async throws -> Archive {+ guard let url = URL(string: source), let scheme = url.scheme?.lowercased() else {+ return try inspect(URL(fileURLWithPath: source))+ }+ if scheme == "file" { return try inspect(url) }+ guard scheme == "http" || scheme == "https" else {+ throw Error.unsupportedSource(source)+ }++ let fm = FileManager.default+ try fm.createDirectory(at: cacheDirectory, withIntermediateDirectories: true)+ let cache = cacheDirectory.appendingPathComponent(cacheName(for: url))+ if fm.fileExists(atPath: cache.path) {+ if let valid = try? inspect(cache) { return valid }+ try fm.removeItem(at: cache)+ }++ var request = URLRequest(url: url)+ request.timeoutInterval = 3 * 60 * 60+ let (downloaded, response) = try await session.download(for: request)+ defer { try? fm.removeItem(at: downloaded) }+ guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {+ throw Error.unexpectedHTTP(url, (response as? HTTPURLResponse)?.statusCode ?? 0)+ }+ let size = try Int64(fm.attributesOfItem(atPath: downloaded.path)[.size] as? UInt64 ?? 0)+ if response.expectedContentLength > 0, size != response.expectedContentLength {+ throw Error.incompleteDownload(+ url, expected: response.expectedContentLength, actual: size+ )+ }++ let pending = cacheDirectory.appendingPathComponent(".\(cache.lastPathComponent).\(UUID().uuidString).partial")+ defer { try? fm.removeItem(at: pending) }+ try fm.moveItem(at: downloaded, to: pending)+ let metadata = try inspect(pending)+ try fm.moveItem(at: pending, to: cache)+ return Archive(file: cache, version: metadata.version, build: metadata.build)+ }++ public static func inspect(_ file: URL) throws -> Archive {+ guard FileManager.default.fileExists(atPath: file.path) else {+ throw Error.missingFile(file)+ }+ guard let data = try? VPhoneArchiveReader.readMember("BuildManifest.plist", from: file),+ let plist = try? PropertyListSerialization.propertyList(from: data, format: nil)+ as? [String: Any],+ let version = plist["ProductVersion"] as? String, !version.isEmpty,+ let build = plist["ProductBuildVersion"] as? String, !build.isEmpty+ else {+ throw Error.invalidManifest(file)+ }+ return Archive(file: file, version: version, build: build)+ }++ static func cacheName(for url: URL) -> String {+ let base = url.lastPathComponent+ let stem = base.lowercased().hasSuffix(".ipsw") ? String(base.dropLast(5)) : base+ let safe = String(stem.prefix(48).unicodeScalars.map { scalar in+ let value = scalar.value+ return (value >= 48 && value <= 57) || (value >= 65 && value <= 90)+ || (value >= 97 && value <= 122) || value == 45 || value == 46 || value == 95+ ? Character(scalar) : "_"+ })+ let digest = SHA256.hash(data: Data(url.absoluteString.utf8))+ let suffix = digest.prefix(6).map { String(format: "%02x", $0) }.joined()+ return "\(safe.isEmpty ? "firmware" : safe)-\(suffix).ipsw"+ }+}diff --git a/sources/VPhoneCore/VPhoneFirmwarePicker.swift b/sources/VPhoneCore/VPhoneFirmwarePicker.swiftindex c2a9a346..2523935b 100644--- a/sources/VPhoneCore/VPhoneFirmwarePicker.swift+++ b/sources/VPhoneCore/VPhoneFirmwarePicker.swift@@ -16,8 +16,8 @@ public enum VPhoneFirmwarePickerError: Error, CustomStringConvertible, Equatable// MARK: - VPhoneFirmwareSources-/// The resolved `fw prepare` sources — a URL or local path per component, or-/// nil to let `fw_prepare.sh` fall back to its built-in default.+/// The resolved `fw prepare` sources — a URL or local path per component.+/// A non-interactive caller rejects missing sources before preparation starts.public struct VPhoneFirmwareSources: Sendable, Equatable {public let iphoneSource: String?public let cloudosSource: String?@@ -32,7 +32,7 @@ public struct VPhoneFirmwareSources: Sendable, Equatable {public enum VPhoneFirmwarePicker {/// Resolve the iPhone/cloudOS sources for `vm create`, prompting only for/// what's missing. Both given → passthrough. Non-interactive → passthrough- /// (fw_prepare defaults fill any gap). Neither given → pick a full pairing.+ /// so the caller can report which source is missing. Neither given → pick a full pairing./// One given → prompt for just the other. Prompts show friendly names; the/// result carries URLs. I/O is injected so the logic is unit-testable.public static func resolve(diff --git a/sources/VPhoneCore/VPhoneResources.swift b/sources/VPhoneCore/VPhoneResources.swiftindex b2733357..f1ea53de 100644--- a/sources/VPhoneCore/VPhoneResources.swift+++ b/sources/VPhoneCore/VPhoneResources.swift@@ -93,7 +93,6 @@ public struct VPhoneResources: Sendable {public var scriptsDir: URL { base.appendingPathComponent("scripts") }public var resourceArchivesDir: URL { scriptsDir.appendingPathComponent("resources") }- public var fwPrepareScript: URL { scriptsDir.appendingPathComponent("fw_prepare.sh") }public var cfwInstallHostScript: URL { scriptsDir.appendingPathComponent("cfw_install_host.sh") }public var preflightScript: URL { scriptsDir.appendingPathComponent("boot_host_preflight.sh") }public var signcert: URL { scriptsDir.appendingPathComponent("vphoned/signcert.p12") }diff --git a/sources/vphone-cli/VPhoneCreateOrchestrator.swift b/sources/vphone-cli/VPhoneCreateOrchestrator.swiftindex 88744818..b962adb1 100644--- a/sources/vphone-cli/VPhoneCreateOrchestrator.swift+++ b/sources/vphone-cli/VPhoneCreateOrchestrator.swift@@ -1,3 +1,4 @@+import ArgumentParserimport FirmwarePatcherimport Foundationimport VPhoneCore@@ -10,7 +11,6 @@ import VPhoneRestore/// `wait_for_recovery` / `wait_for_first_boot_prompt_auto` / `run_boot_analysis`.private enum VPhoneCreateError: Error, CustomStringConvertible {case nestedVirtualization- case fwPrepareFailed(Int32)case identityTimedOut(URL)case invalidUDID(String)case invalidECID(String)@@ -30,8 +30,6 @@ private enum VPhoneCreateError: Error, CustomStringConvertible {switch self {case .nestedVirtualization:"Guest boot is unavailable inside a VM. Run vm create on a macOS 15 or later host that is not itself a VM."- case let .fwPrepareFailed(code):- "Firmware preparation failed (exit code \(code))."case let .identityTimedOut(path):"Device identity file not found: \(path.path). Run vm create again to regenerate it."case let .invalidUDID(v):@@ -244,31 +242,14 @@ public struct VPhoneCreateOrchestrator {// MARK: - fw prepare / fw patchprivate func runFWPrepare(options: Options, bundleURL: URL) throws {- let v = options.verbosity- try FileManager.default.createDirectory(at: resources.ipswCacheDir, withIntermediateDirectories: true)- try FileManager.default.createDirectory(at: resources.sealVolumeCacheDir, withIntermediateDirectories: true)-- var env = ProcessInfo.processInfo.environment- if let iphoneSource = options.iphoneSource { env["IPHONE_SOURCE"] = iphoneSource }- if let cloudosSource = options.cloudosSource { env["CLOUDOS_SOURCE"] = cloudosSource }- // No VPHONE_PYTHON: fw_prepare.sh no longer runs any Python.- env["IPSW_DIR"] = resources.ipswCacheDir.path- env["VPHONE_SEAL_DIR"] = resources.sealVolumeCacheDir.path- if options.keepArtifacts { env["VPHONE_KEEP_ARTIFACTS"] = "1" }-- trace(- "spawn /bin/bash \(resources.fwPrepareScript.path) (env keys: IPSW_DIR, VPHONE_SEAL_DIR)",- v- )- // Always streamed — silence during a multi-GB download reads as a hang.- let code = try VPhoneProcessRunner.runStreaming(- URL(fileURLWithPath: "/bin/bash"),- [resources.fwPrepareScript.path],- cwd: bundleURL,- env: env,- echo: true+ guard let phone = options.iphoneSource, let cloud = options.cloudosSource else {+ throw ValidationError("Specify both iPhone and cloudOS IPSW sources when running without a terminal.")+ }+ let bundle = try VPhoneBundle.load(at: bundleURL)+ try VPhoneFirmwarePreparer.prepare(+ iPhoneSource: phone, cloudOSSource: cloud,+ bundle: bundle, cacheDirectory: resources.ipswCacheDir)- guard code == 0 else { throw VPhoneCreateError.fwPrepareFailed(code) }print("[+] Firmware prepared (iPhone + cloudOS merged into bundle).")}diff --git a/sources/vphone-cli/VPhoneFWCLI.swift b/sources/vphone-cli/VPhoneFWCLI.swiftindex 2389dc30..497a2d3e 100644--- a/sources/vphone-cli/VPhoneFWCLI.swift+++ b/sources/vphone-cli/VPhoneFWCLI.swift@@ -24,9 +24,7 @@ struct VPhoneFWCommand: ParsableCommand {// MARK: - firmware support matrix-/// Replaces the two Python heredocs that used to live inside-/// `scripts/fw_prepare.sh`. Both read the `DOWNLOADABLE_IPSW_URLS` the shell-/// already sets, so only the language changed; the shell still runs `ipsw`.+/// Lists the available firmware using the URLs supplied by AppleDB.////// Neither writes through `print`: `list` styles stdout and `resolve` styles/// stderr, and colour is only right if each descriptor is asked separately.@@ -54,8 +52,7 @@ struct VPhoneFWResolveCommand: ParsableCommand {commandName: "resolve",abstract: "Resolve a version/build selector to a downloadable IPSW URL",discussion: """- Prints version<TAB>build<TAB>url<TAB>status on stdout, which fw_prepare.sh- reads back with `IFS=$'\\t' read -r`.+ Prints version<TAB>build<TAB>url<TAB>status on stdout.Exits 2 — not 1 — when a bare version matches more than one build, so acaller can tell "pick a build" from "there is no such firmware". An empty@@ -82,8 +79,7 @@ struct VPhoneFWResolveCommand: ParsableCommand {// MARK: - manifest-/// Replaces `scripts/fw_manifest.py`, called from `fw_prepare.sh` once both-/// IPSWs are extracted and merged.+/// Generates the hybrid manifest after both IPSWs are extracted and merged.struct VPhoneFWManifestCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "manifest",@@ -94,7 +90,7 @@ struct VPhoneFWManifestCommand: ParsableCommand {OS images into a single DFU erase-install build identity.Both files are written into <iphone-dir>, replacing what is there.- fw_prepare.sh keeps the original as iPhone-BuildManifest.plist first.+ `fw prepare` keeps the original as iPhone-BuildManifest.plist first.""")@@ -170,37 +166,51 @@ struct VPhoneFWPrepareCommand: ParsableCommand {var verboseCount: Intfunc run() throws {- let v = max(VPhoneVerbosity.info, VPhoneVerbosity(count: verboseCount))- let name = try VPhoneVMSelection.resolveExisting(name, in: lib.library)- let bundle = try lib.library.bundle(named: name)let resources = projectRoot.map { VPhoneResources(base: URL(fileURLWithPath: $0)) } ?? .resolve()+ let readme = resources.base.appendingPathComponent("README.md").path+ let needsCatalog = list || iphoneVersion != nil || iphoneBuild != nil+ let urls = if needsCatalog {+ try vphoneRunBlocking {+ try await VPhoneFirmwareIndex.restoreURLs(forDevice: "iPhone17,3")+ }.joined(separator: "\n")+ } else { "" }++ if list {+ let code = VPhoneFirmwareMatrixCommandLine.list(+ device: "iPhone17,3", readmePath: readme, downloadURLs: urls+ )+ if code != 0 { throw ExitCode(code) }+ return+ }- var env = ProcessInfo.processInfo.environment- if let iphoneSource { env["IPHONE_SOURCE"] = iphoneSource }- if let cloudosSource { env["CLOUDOS_SOURCE"] = cloudosSource }- if let iphoneVersion { env["IPHONE_VERSION"] = iphoneVersion }- if let iphoneBuild { env["IPHONE_BUILD"] = iphoneBuild }- if list { env["LIST_FIRMWARES"] = "1" }-- // Redirect the two things a read-only bundle can't provide (IPSW cache,- // extracted apfs_sealvolume) to the writable user cache. No Python:- // fw_prepare.sh's last heredocs moved into `fw list` / `fw resolve`.- try FileManager.default.createDirectory(at: resources.ipswCacheDir, withIntermediateDirectories: true)- try FileManager.default.createDirectory(at: resources.sealVolumeCacheDir, withIntermediateDirectories: true)- env["IPSW_DIR"] = resources.ipswCacheDir.path- env["VPHONE_SEAL_DIR"] = resources.sealVolumeCacheDir.path+ var source = iphoneSource+ if iphoneVersion != nil || iphoneBuild != nil {+ guard source == nil else {+ throw ValidationError("Use either --iphone-source or --iphone-version/--iphone-build.")+ }+ let selection = VPhoneFirmwareMatrix.selection(+ device: "iPhone17,3", version: iphoneVersion ?? "", build: iphoneBuild ?? "",+ readme: try? String(contentsOfFile: readme, encoding: .utf8),+ downloadURLs: urls,+ style: .forStream(FileHandle.standardError.fileDescriptor)+ )+ switch selection {+ case let .selected(release, _): source = release.url+ case let .ambiguous(message), let .unmatched(message):+ throw ValidationError(message.trimmingCharacters(in: .whitespacesAndNewlines))+ }+ }- if v.tracesInternals {- print("[trace] spawning: /bin/bash \(resources.fwPrepareScript.path) (env keys: IPSW_DIR, VPHONE_SEAL_DIR)")+ let selected = try VPhoneFirmwareSelection.resolve(iphone: source, cloudos: cloudosSource)+ guard let phone = selected.iphoneSource, let cloud = selected.cloudosSource else {+ throw ValidationError("Specify both --iphone-source and --cloudos-source when running without a terminal.")}- let code = try VPhoneProcessRunner.runStreaming(- URL(fileURLWithPath: "/bin/bash"),- [resources.fwPrepareScript.path],- cwd: bundle.url,- env: env,- echo: v.showsToolDetail+ let name = try VPhoneVMSelection.resolveExisting(name, in: lib.library)+ let bundle = try lib.library.bundle(named: name)+ try VPhoneFirmwarePreparer.prepare(+ iPhoneSource: phone, cloudOSSource: cloud,+ bundle: bundle, cacheDirectory: resources.ipswCacheDir)- throw ExitCode(code)}}diff --git a/sources/vphone-cli/VPhoneFirmwarePreparer.swift b/sources/vphone-cli/VPhoneFirmwarePreparer.swiftnew file mode 100644index 00000000..7f0fc28f--- /dev/null+++ b/sources/vphone-cli/VPhoneFirmwarePreparer.swift@@ -0,0 +1,154 @@+import Darwin+import FirmwarePatcher+import Foundation+import VPhoneArchive+import VPhoneCore++/// Builds one restore tree from two IPSWs without a shell or a second full+/// copy of either source archive. All extraction and merging happens in one+/// disposable directory inside the VM; only a complete tree is moved into+/// place for the patch/restore steps to see.+enum VPhoneFirmwarePreparer {+ enum Error: Swift.Error, LocalizedError {+ case existingRestore(URL)+ case missingComponent(URL)+ case sourceNameMismatch(URL, version: String, build: String)++ var errorDescription: String? {+ switch self {+ case let .existingRestore(path):+ "Firmware preparation would replace an existing restore tree: \(path.path)"+ case let .missingComponent(path):+ "Firmware component is missing: \(path.path)"+ case let .sourceNameMismatch(path, version, build):+ "IPSW name and BuildManifest disagree (\(version)/\(build)): \(path.path)"+ }+ }+ }++ static func prepare(+ iPhoneSource: String,+ cloudOSSource: String,+ bundle: VPhoneBundle,+ cacheDirectory: URL+ ) throws {+ let fm = FileManager.default+ let existing = try fm.contentsOfDirectory(+ at: bundle.url, includingPropertiesForKeys: [.isDirectoryKey]+ )+ for candidate in existing where candidate.lastPathComponent.contains("Restore") {+ if try candidate.resourceValues(forKeys: [.isDirectoryKey]).isDirectory == true {+ throw Error.existingRestore(candidate)+ }+ }++ print("[*] Resolving iPhone IPSW...")+ let phone = try vphoneRunBlocking {+ try await VPhoneIPSWCache.resolve(iPhoneSource, in: cacheDirectory)+ }+ print("[*] Resolving cloudOS IPSW...")+ let cloud = try vphoneRunBlocking {+ try await VPhoneIPSWCache.resolve(cloudOSSource, in: cacheDirectory)+ }+ try checkIPhoneName(iPhoneSource, archive: phone)+ print("[+] iPhone \(phone.version) (\(phone.build)); cloudOS \(cloud.version) (\(cloud.build))")++ let name = "iPhone17,3_\(phone.version)_\(phone.build)_Restore"+ let destination = bundle.url.appendingPathComponent(name)+ let staging = bundle.url.appendingPathComponent(".firmware-prepare-\(UUID().uuidString)")+ let phoneTree = staging.appendingPathComponent(name)+ let cloudTree = staging.appendingPathComponent("cloudOS")+ try fm.createDirectory(at: phoneTree, withIntermediateDirectories: true)+ try fm.createDirectory(at: cloudTree, withIntermediateDirectories: true)+ defer { try? fm.removeItem(at: staging) }++ print("[*] Extracting iPhone IPSW...")+ try VPhoneArchiveExtractor.extract(phone.file, into: phoneTree, options: .intoHostDirectory)+ print("[*] Extracting cloudOS IPSW...")+ try VPhoneArchiveExtractor.extract(cloud.file, into: cloudTree, options: .intoHostDirectory)++ try makeUserWritable(phoneTree)+ try mergeCloudOS(from: cloudTree, into: phoneTree)+ let originalManifest = phoneTree.appendingPathComponent("BuildManifest.plist")+ try clone(originalManifest, to: phoneTree.appendingPathComponent("iPhone-BuildManifest.plist"))+ try FirmwareManifest.generate(iPhoneDir: phoneTree, cloudOSDir: cloudTree, verbose: true)++ // The destination did not exist at entry and the staging directory is+ // on the same volume. One rename exposes the complete restore tree.+ guard !fm.fileExists(atPath: destination.path) else { throw Error.existingRestore(destination) }+ try fm.moveItem(at: phoneTree, to: destination)+ print("[+] Restore tree ready: \(destination.path)")+ }++ private static func checkIPhoneName(_ source: String, archive: VPhoneIPSWCache.Archive) throws {+ let basename = URL(string: source)?.lastPathComponent+ ?? URL(fileURLWithPath: source).lastPathComponent+ let pattern = #"^iPhone17,3_([^_]+)_([^_]+)_Restore\.ipsw$"#+ guard let range = basename.range(of: pattern, options: .regularExpression) else { return }+ let components = basename[range].split(separator: "_")+ guard components.count == 4 else { return }+ if String(components[1]) != archive.version || String(components[2]) != archive.build {+ throw Error.sourceNameMismatch(archive.file, version: archive.version, build: archive.build)+ }+ }++ private static func mergeCloudOS(from cloud: URL, into phone: URL) throws {+ let fm = FileManager.default+ try copyMatching(from: cloud, into: phone) { $0.hasPrefix("kernelcache.") }+ for subdirectory in ["agx", "all_flash", "ane", "dfu", "pmp"] {+ let source = cloud.appending(path: "Firmware/\(subdirectory)")+ let destination = phone.appending(path: "Firmware/\(subdirectory)")+ guard fm.fileExists(atPath: source.path) else { throw Error.missingComponent(source) }+ try fm.createDirectory(at: destination, withIntermediateDirectories: true)+ try copyMatching(from: source, into: destination) { _ in true }+ }+ let cloudFirmware = cloud.appendingPathComponent("Firmware")+ let phoneFirmware = phone.appendingPathComponent("Firmware")+ try copyMatching(from: cloudFirmware, into: phoneFirmware) { $0.hasSuffix(".im4p") }+ try copyMatching(from: cloud, into: phone, overwrite: false) { $0.hasSuffix(".dmg") }+ try copyMatching(from: cloudFirmware, into: phoneFirmware, overwrite: false) {+ $0.hasSuffix(".dmg.trustcache")+ }+ }++ private static func copyMatching(+ from source: URL,+ into destination: URL,+ overwrite: Bool = true,+ where predicate: (String) -> Bool+ ) throws {+ let fm = FileManager.default+ guard fm.fileExists(atPath: source.path) else { throw Error.missingComponent(source) }+ let names = try fm.contentsOfDirectory(atPath: source.path).filter(predicate)+ for name in names {+ let to = destination.appendingPathComponent(name)+ if !overwrite, fm.fileExists(atPath: to.path) { continue }+ try clone(source.appendingPathComponent(name), to: to)+ }+ }++ private static func clone(_ source: URL, to destination: URL) throws {+ let fm = FileManager.default+ guard fm.fileExists(atPath: source.path) else { throw Error.missingComponent(source) }+ if fm.fileExists(atPath: destination.path) { try fm.removeItem(at: destination) }+ if clonefile(source.path, destination.path, 0) == 0 { return }+ if fm.fileExists(atPath: destination.path) { try fm.removeItem(at: destination) }+ try fm.copyItem(at: source, to: destination)+ }++ private static func makeUserWritable(_ directory: URL) throws {+ let fm = FileManager.default+ guard let entries = fm.enumerator(+ at: directory, includingPropertiesForKeys: [.isSymbolicLinkKey]+ ) else { return }+ for case let file as URL in entries {+ let values = try file.resourceValues(forKeys: [.isSymbolicLinkKey])+ if values.isSymbolicLink == true { continue }+ let attributes = try fm.attributesOfItem(atPath: file.path)+ let mode = (attributes[.posixPermissions] as? NSNumber)?.uint16Value ?? 0o644+ try fm.setAttributes(+ [.posixPermissions: NSNumber(value: mode | 0o200)], ofItemAtPath: file.path+ )+ }+ }+}diff --git a/sources/vphone-cli/VPhoneFirmwareSelection.swift b/sources/vphone-cli/VPhoneFirmwareSelection.swiftindex 9f807e19..4612d2fe 100644--- a/sources/vphone-cli/VPhoneFirmwareSelection.swift+++ b/sources/vphone-cli/VPhoneFirmwareSelection.swift@@ -7,7 +7,7 @@ enum VPhoneFirmwareSelection {/// Resolve `vm create`'s iPhone/cloudOS sources, prompting on a TTY for/// whichever component the user didn't pass. Non-interactive or fully- /// specified → returns the inputs unchanged (fw_prepare defaults fill gaps).+ /// specified → returns the inputs unchanged for caller validation.static func resolve(iphone: String?, cloudos: String?) throws -> VPhoneFirmwareSources {try VPhoneFirmwarePicker.resolve(iphone: iphone,diff --git a/sources/vphone-cli/VPhoneVMCreateCLI.swift b/sources/vphone-cli/VPhoneVMCreateCLI.swiftindex 2463df9b..521fcb98 100644--- a/sources/vphone-cli/VPhoneVMCreateCLI.swift+++ b/sources/vphone-cli/VPhoneVMCreateCLI.swift@@ -51,6 +51,9 @@ struct VPhoneVMCreateCommand: ParsableCommand {let launcher = try VPhoneGuestLaunchPlanner()// Prompt for any firmware component not supplied on the command line.let sources = try VPhoneFirmwareSelection.resolve(iphone: iphoneSource, cloudos: cloudosSource)+ guard sources.iphoneSource != nil, sources.cloudosSource != nil else {+ throw ValidationError("Specify both --iphone-source and --cloudos-source when running without a terminal.")+ }let orchestrator = VPhoneCreateOrchestrator(library: lib.library,resources: resources,diff --git a/tests/VPhoneArchiveTests/IPSWCacheTests.swift b/tests/VPhoneArchiveTests/IPSWCacheTests.swiftnew file mode 100644index 00000000..fae176f5--- /dev/null+++ b/tests/VPhoneArchiveTests/IPSWCacheTests.swift@@ -0,0 +1,108 @@+import Foundation+import Testing+@testable import VPhoneArchive++private final class IPSWStubProtocol: URLProtocol {+ nonisolated(unsafe) static var payload = Data()+ nonisolated(unsafe) static var status = 200++ override class func canInit(with request: URLRequest) -> Bool { true }+ override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }++ override func startLoading() {+ let response = HTTPURLResponse(+ url: request.url!, statusCode: Self.status, httpVersion: "HTTP/1.1",+ headerFields: ["Content-Length": String(Self.payload.count)]+ )!+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)+ client?.urlProtocol(self, didLoad: Self.payload)+ client?.urlProtocolDidFinishLoading(self)+ }++ override func stopLoading() {}+}++@Suite("IPSW cache", .serialized)+struct IPSWCacheTests {+ private func fixture(in root: URL) throws -> URL {+ let files = root.appendingPathComponent("files")+ try FileManager.default.createDirectory(at: files, withIntermediateDirectories: true)+ let manifest: [String: Any] = [+ "ProductVersion": "26.6.2", "ProductBuildVersion": "23G90",+ ]+ let data = try PropertyListSerialization.data(+ fromPropertyList: manifest, format: .xml, options: 0+ )+ try data.write(to: files.appendingPathComponent("BuildManifest.plist"))+ let archive = root.appendingPathComponent("input.ipsw")+ try VPhoneArchiveWriter.create(archive: archive, from: files)+ return archive+ }++ @Test func localSourceReadsManifestWithoutCopying() async throws {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let source = try fixture(in: root)+ let result = try await VPhoneIPSWCache.resolve(+ source.path, in: root.appendingPathComponent("cache")+ )+ #expect(result.file == source)+ #expect(result.version == "26.6.2")+ #expect(result.build == "23G90")+ #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent("cache").path))+ }++ @Test func downloadReplacesInvalidCacheOnlyAfterValidation() async throws {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let source = try fixture(in: root)+ IPSWStubProtocol.payload = try Data(contentsOf: source)+ IPSWStubProtocol.status = 200+ let configuration = URLSessionConfiguration.ephemeral+ configuration.protocolClasses = [IPSWStubProtocol.self]+ let session = URLSession(configuration: configuration)+ defer { session.invalidateAndCancel() }++ let url = URL(string: "https://example.invalid/input.ipsw")!+ let cacheDir = root.appendingPathComponent("cache")+ try FileManager.default.createDirectory(at: cacheDir, withIntermediateDirectories: true)+ let cached = cacheDir.appendingPathComponent(VPhoneIPSWCache.cacheName(for: url))+ try Data("damaged".utf8).write(to: cached)++ let result = try await VPhoneIPSWCache.resolve(+ url.absoluteString, in: cacheDir, session: session+ )+ #expect(result.file == cached)+ #expect(result.build == "23G90")+ #expect(try Data(contentsOf: cached) == Data(contentsOf: source))++ IPSWStubProtocol.status = 503+ let reused = try await VPhoneIPSWCache.resolve(+ url.absoluteString, in: cacheDir, session: session+ )+ #expect(reused.file == cached)+ }++ @Test func failedDownloadLeavesNoReusableCache() async throws {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }+ IPSWStubProtocol.payload = Data("server unavailable".utf8)+ IPSWStubProtocol.status = 503+ let configuration = URLSessionConfiguration.ephemeral+ configuration.protocolClasses = [IPSWStubProtocol.self]+ let session = URLSession(configuration: configuration)+ defer { session.invalidateAndCancel() }++ let url = URL(string: "https://example.invalid/input.ipsw")!+ let cacheDir = root.appendingPathComponent("cache")+ await #expect(throws: VPhoneIPSWCache.Error.self) {+ try await VPhoneIPSWCache.resolve(url.absoluteString, in: cacheDir, session: session)+ }+ #expect(!FileManager.default.fileExists(+ atPath: cacheDir.appendingPathComponent(VPhoneIPSWCache.cacheName(for: url)).path+ ))+ }+}diff --git a/tests/VPhoneCoreTests/ResourcesTests.swift b/tests/VPhoneCoreTests/ResourcesTests.swiftindex d1ab144c..9df21dbc 100644--- a/tests/VPhoneCoreTests/ResourcesTests.swift+++ b/tests/VPhoneCoreTests/ResourcesTests.swift@@ -18,7 +18,6 @@ struct ResourcesTests {let exe = "/Applications/vphone-cli.app/Contents/MacOS/vphone-cli"let r = VPhoneResources.resolve(executablePath: exe)#expect(r.base.path == "/Applications/vphone-cli.app/Contents/Resources")- #expect(r.fwPrepareScript.path == "/Applications/vphone-cli.app/Contents/Resources/scripts/fw_prepare.sh")#expect(r.cfwInstallHostScript.path== "/Applications/vphone-cli.app/Contents/Resources/scripts/cfw_install_host.sh")}@@ -72,7 +71,7 @@ struct ResourcesTests {let base = URL(fileURLWithPath: "/x")let r = VPhoneResources(base: base)let rooted = [- r.scriptsDir, r.resourceArchivesDir, r.fwPrepareScript,+ r.scriptsDir, r.resourceArchivesDir,r.cfwInstallHostScript, r.preflightScript, r.signcert, r.vphoned,]for url in rooted {