Run a virtual iPhone on an Apple Silicon Mac.
Swift
Replace runtime install scripts with native JB workflow
Lakrf4a60c434f2d
diff --git a/AGENTS.md b/AGENTS.mdindex 3579478a..cf2d752a 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -62,6 +62,8 @@ sources/│ ├── VPhoneVMTransferCLI.swift # VM transfer│ ├── VPhoneCreateOptions.swift # Create-flow option set│ ├── VPhoneCreateOrchestrator.swift # Native `vm create` pipeline driver+│ ├── VPhoneCFWInstaller.swift # Native host-mount JB install+│ ├── VPhoneHostPreflight.swift # Native host launch check│ ├── VPhoneFirmwareSelection.swift # Interactive firmware picker│ ├── VPhoneVMSelection.swift # Interactive VM picker│ └── VPhoneProgressBar.swift # Terminal progress rendering@@ -172,19 +174,13 @@ sources/├── VPhoneTouchIDMonitor.swift # BiometricKit delegate sink└── VPhoneScreenRecorder.swift # VM screen recording to file-scripts/ # Shell only — the CFW patchers are `vphone-cli cfw <verb>` now,-│ # and there is no Python here at all. Every .sh declares its-│ # tier on line 2; `[d]` = dist (ships), `[b]` = build, `[g]` = guest-├── dist_manifest.sh [b] # What ships. The allowlist build.sh and `make bundle` stage from+scripts/ # Build scripts and payloads only; no runtime shell+├── build.sh [b] # Compile, sign and bundle+├── dist_manifest.sh [b] # Payload allowlist staged by build.sh├── guest_binaries.mk [b] # Cross-compiles vphoned (needs the iPhoneOS SDK)├── 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-├── cfw_install.sh [d] # Base system patches and vphoned-├── cfw_install_jb.sh [d] # JB system patches; no package bootstrap-├── cfw_install_host.sh [d] # Host-mount CFW driver (attaches Disk.img, VM off; re-execs sudo)-├── boot_host_preflight.sh [d] # Why the host cannot launch vphone-vm-├── payloads/ [d] # Small GPU driver archive; no bootstrap payloads+├── payloads/ # Small GPU driver archive; no bootstrap payloads├── vphoned/ # Guest daemon source; only its plist and entitlements ship├── tweakloader/ vpregister/ vcamcaptured/ camfix/ # Unshipped experimental sources└── repos/ # Toolchain source (git submodule: insert_dylib)diff --git a/Makefile b/Makefileindex f4e170a5..e547b56e 100644--- a/Makefile+++ b/Makefile@@ -300,13 +300,13 @@ amfi_off:@sudo "$(CURDIR)/$(AMFI_BINARY)" offboot_host_preflight: build- zsh $(SCRIPTS)/boot_host_preflight.sh+ "$(CURDIR)/$(BINARY)" host preflight# Checks the ENTITLED binary, because that is the one amfid can refuse.# Running `vphone-cli --help` here would prove nothing: it carries no# entitlements and launches on any host.define BOOT_BINARY_CHECK- @zsh $(SCRIPTS)/boot_host_preflight.sh $(1)+ @"$(CURDIR)/$(BINARY)" host preflight --quiet@tmp_log="$$(mktemp -t vphone-boot-preflight.XXXXXX)"; \set +e; \"$(CURDIR)/$(VM_BINARY)" --help >"$$tmp_log" 2>&1; \@@ -394,41 +394,9 @@ restore: build$(if $(RESTORE_UDID),--udid $(RESTORE_UDID),) \--ecid "$$ECID"-# The `ipsw fw aea` loop below stays: decrypting the AEA images is not part of-# what moved in-process. `vphone-cli restore --offline` then picks the same-# first-sorted .shsh this recipe checks for, and its own AEA pass finds nothing-# left to do after the loop has run.+# The native restore command validates the SHSH and decrypts AEA images itself.restore_offline: build@$(call _resolve_ecid); \- SHSH=$$(ls "$(VM_DIR_ABS)/"*.shsh 2>/dev/null | head -1); \- if [ -z "$$SHSH" ]; then \- echo "[-] No .shsh file in $(VM_DIR)/ — run 'make restore_get_shsh' first"; \- exit 1; \- fi; \- RESTORE_SRC=$$(echo "$(VM_DIR_ABS)/iPhone"*_Restore); \- if [ ! -d "$$RESTORE_SRC" ]; then \- echo "[-] No iPhone*_Restore directory in $(VM_DIR)/"; \- exit 1; \- fi; \- echo "[+] Decrypting AEA images in place…"; \- for aea in "$$RESTORE_SRC"/*.dmg.aea; do \- [ -f "$$aea" ] || continue; \- [ "$$(xxd -l 4 -p "$$aea")" = "41454131" ] || continue; \- base=$$(basename "$$aea"); \- if ! ipsw fw aea -o "$$RESTORE_SRC" "$$aea"; then \- echo "[-] Could not decrypt $$base with ipsw — restore stopped."; \- exit 1; \- fi; \- if ! mv -f "$$RESTORE_SRC/$${base%.aea}" "$$aea"; then \- echo "[-] Could not replace $$base with its decrypted image — restore stopped."; \- exit 1; \- fi; \- if [ "$$(xxd -l 4 -p "$$aea")" = "41454131" ]; then \- echo "[-] $$base is still encrypted after decryption — restore stopped."; \- exit 1; \- fi; \- done; \- echo "[+] Restoring offline with SHSH: $$(basename $$SHSH)"; \"$(CURDIR)/$(BINARY)" restore $(RESTORE_VM_ARGS) --offline \$(if $(RESTORE_UDID),--udid $(RESTORE_UDID),) \--ecid "$$ECID"@@ -439,5 +407,5 @@ restore_offline: build.PHONY: cfw_install-cfw_install:- $(if $(call truthy,$(FRIDA)),VPHONE_FRIDA=1) zsh "$(CURDIR)/$(SCRIPTS)/cfw_install_host.sh" "$(VM_DIR_ABS)"+cfw_install: build+ "$(CURDIR)/$(BINARY)" cfw install $(RESTORE_VM_ARGS) --project-root "$(CURDIR)"diff --git a/README.md b/README.mdindex ca706df7..3080cc46 100644--- a/README.md+++ b/README.md@@ -58,6 +58,10 @@ vphone-cli vm create myphone \vphone-cli vm launch myphone```+The single supported firmware mode is JB. Creation installs vphoned and the+required system patches, then checks that vphoned connects. It does not install+a package manager, SSH server, or user bootstrap.+## Commands`vphone-cli vm create` runs the whole pipeline; the individual steps below let you drive it manually or re-run one stage.diff --git a/research/0_binary_patch_comparison.md b/research/0_binary_patch_comparison.mdindex 5b554c39..7d740f62 100644--- a/research/0_binary_patch_comparison.md+++ b/research/0_binary_patch_comparison.md@@ -3,7 +3,7 @@> **Current product scope (September 2026):** the tables below preserve the> historical patch comparison. The public runtime now exposes only JB. Guest> package managers, Procursus, BaseBin hooks, and first-boot package setup are-> outside this repository. The JB install retains the base system patches,+> outside this repository. The native Swift JB install retains the base system patches,> launchd jetsam guard, debugserver entitlement edit, iOS 27 Campo entitlement> edit, GPU driver, and mandatory vphoned. Old variant rows are research history,> not available install modes.diff --git a/scripts/boot_host_preflight.sh b/scripts/boot_host_preflight.shdeleted file mode 100755index 2274c8d9..00000000--- a/scripts/boot_host_preflight.sh+++ /dev/null@@ -1,206 +0,0 @@-#!/bin/zsh-# vphone-tier: dist-# boot_host_preflight.sh — Diagnose whether the host can launch the signed-# vphone-vm binary required for PV=3 virtualization boot/DFU flows.--set -euo pipefail--SCRIPT_DIR="${0:A:h}"-PROJECT_ROOT="${SCRIPT_DIR:h}"--ASSERT_BOOTABLE=0-QUIET=0--while [[ $# -gt 0 ]]; do- case "$1" in- --assert-bootable)- ASSERT_BOOTABLE=1- shift- ;;- --quiet)- QUIET=1- shift- ;;- --less)- # Accepted for `make boot_binary_check_less` (Makefile), which passes it- # alongside --assert-bootable; this script's checks do not differ.- shift- ;;- *)- echo "Unknown option: $1" >&2- exit 2- ;;- esac-done--cd "$PROJECT_ROOT"--# What we check is vphone-vm, not vphone-cli. vphone-cli carries no-# entitlements and launches on any host, so asking whether it runs proves-# nothing; vphone-vm holds the private virtualization keys and is the binary-# amfid can refuse. The caller passes VPHONE_CLI_BIN pointing at it — the-# bundled .app's Contents/MacOS/vphone-vm, not a dev .build/release path that-# does not exist inside the bundle. The fallback is the dev layout, for-# standalone and `make` invocation.-RELEASE_BIN="${VPHONE_CLI_BIN:-${PROJECT_ROOT}/.build/release/vphone-vm}"-DEBUG_BIN="${PROJECT_ROOT}/.build/debug/vphone-vm"-ENTITLEMENTS="${PROJECT_ROOT}/sources/vphone.entitlements"-TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/vphone-preflight.XXXXXX")"-TMP_SIGNED_DEBUG="${TMP_DIR}/vphone-vm.debug.signed"--cleanup() {- rm -rf "$TMP_DIR"-}-trap cleanup EXIT--print_section() {- (( QUIET == 0 )) || return 0- echo ""- echo "=== $1 ==="-}--run_capture() {- local label="$1"- shift-- local log_file="${TMP_DIR}/${label}.log"- local rc=0- "$@" >"$log_file" 2>&1 || rc=$?-- (( QUIET == 0 )) && echo "[${label}] exit=${rc}"- if (( QUIET == 0 )) && [[ -s "$log_file" ]]; then- sed -n '1,40p' "$log_file"- fi- return "$rc"-}--MODEL_NAME="$(system_profiler SPHardwareDataType 2>/dev/null | awk -F': ' '/Model Name/ {print $2; exit}')"-HV_VMM_PRESENT="$(sysctl -n kern.hv_vmm_present 2>/dev/null || true)"-SIP_STATUS="$(csrutil status)"-RESEARCH_GUEST_STATUS="$(- # First pass with EOF stdin — captures the menu without blocking- _out=$(csrutil allow-research-guests status </dev/null 2>/dev/null || true)- if ! echo "$_out" | grep -q "Pick a macOS installation"; then- # Single install or already got a direct answer- echo "$_out"- else- # Multiple installs: try to auto-select "Macintosh HD"- _num=$(echo "$_out" | awk '/Macintosh HD/ { match($0, /[0-9]+/); if (RSTART > 0) { print substr($0, RSTART, RLENGTH); exit } }')- if [[ -n "$_num" ]]; then- _result=$(printf '%s\n' "$_num" | csrutil allow-research-guests status 2>/dev/null \- | grep -o 'Allow Research Guests status:.*' || true)- if [[ -n "$_result" ]]; then- echo "(auto-selected: Macintosh HD) $_result"- exit 0- fi- fi- # No Macintosh HD found, or auto-select failed — prompt interactively- # only when a controlling TTY exists. Non-interactive runs should degrade- # cleanly instead of failing on /dev/tty access under set -e.- if { : >/dev/tty; } 2>/dev/null; then- printf '%s\n' "$_out" >/dev/tty- printf 'Pick a macOS installation: ' >/dev/tty- read _choice </dev/tty- if [[ -n "$_choice" ]]; then- printf '%s\n' "$_choice" | csrutil allow-research-guests status 2>/dev/null \- | grep -o 'Allow Research Guests status:.*' || echo 'unavailable'- else- echo 'unavailable'- fi- else- echo 'unavailable (multiple installs; no interactive tty)'- fi- fi-)"-CURRENT_BOOT_ARGS="$(sysctl -n kern.bootargs 2>/dev/null || true)"-NEXT_BOOT_ARGS="$({ nvram boot-args 2>/dev/null || true; } | sed 's/^boot-args[[:space:]]*//')"-ASSESSMENT_STATUS="$(spctl --status 2>/dev/null || true)"--print_section "Host"-sw_vers-echo "model: $MODEL_NAME"-echo "kern.hv_vmm_present: $HV_VMM_PRESENT"-echo "SIP: $SIP_STATUS"-echo "allow-research-guests: $RESEARCH_GUEST_STATUS"-echo "current kern.bootargs: $CURRENT_BOOT_ARGS"-echo "next-boot nvram boot-args: $NEXT_BOOT_ARGS"-echo "assessment: $ASSESSMENT_STATUS"--if (( ASSERT_BOOTABLE == 1 )); then- if [[ "$HV_VMM_PRESENT" == "1" ]] || [[ "$MODEL_NAME" == "Apple Virtual Machine 1" ]]; then- (( QUIET == 0 )) && {- echo ""- echo "Error: nested Apple VM host detected; Virtualization.framework guest boot is unavailable here." >&2- }- exit 3- fi-fi--print_section "Entitlements"-if [[ -f "$RELEASE_BIN" ]]; then- codesign -d --entitlements :- "$RELEASE_BIN" 2>/dev/null || true-else- echo "missing release binary: $RELEASE_BIN"-fi--print_section "Policy"-if [[ -f "$RELEASE_BIN" ]]; then- spctl --assess --type execute --verbose=4 "$RELEASE_BIN" 2>&1 || true-fi--print_section "Unsigned Debug Binary"-if [[ ! -f "$DEBUG_BIN" ]]; then- echo "(skipped — debug binary not built; run 'make patcher_build' to include)"-else- set +e- run_capture "debug_help" "$DEBUG_BIN" --help- set -e-fi--print_section "Signed Release Binary"-if [[ ! -f "$RELEASE_BIN" ]]; then- echo "missing release binary: $RELEASE_BIN"- exit 1-fi-set +e-run_capture "release_help" "$RELEASE_BIN" --help-RELEASE_HELP_RC=$?-set -e--print_section "Signed Debug Control"-if [[ ! -f "$DEBUG_BIN" ]]; then- echo "(skipped — debug binary not built)"-else- cp "$DEBUG_BIN" "$TMP_SIGNED_DEBUG"- codesign --force --sign - --entitlements "$ENTITLEMENTS" "$TMP_SIGNED_DEBUG" >/dev/null- set +e- run_capture "signed_debug_help" "$TMP_SIGNED_DEBUG" --help- set -e-fi--print_section "Result"-echo "If unsigned debug runs but either signed binary exits 137 / signal 9,"-echo "the host is not currently permitting the required private virtualization entitlements."-echo "If the signed release binary exits 0 but the signed debug control still exits 137,"-echo "something is permitting this particular binary and not others — and with an"-echo "allowlist, which is what 'make amfi_allow' installs, that is the EXPECTED result,"-echo "not a contradiction: it allows only the binaries it was given, and the debug"-echo "control above is a fresh copy in a temp directory with its own CDHash."-echo "'make amfi_allow' covers this build; it needs root and is not run for you."-echo "Typical requirements for this project are:"-echo " 1. macOS 15+ with PV=3 support"-echo " 2. Host hardware must expose Virtualization.framework VM support (not a nested VM without virtualization availability)"-echo " 3. SIP disabled"-echo " 4. allow-research-guests enabled in Recovery OS"-echo " 5. AMFI / execution policy state that permits the private entitlements"-echo " 6. Gatekeeper / assessment configured so the signed binary is launchable"--if (( ASSERT_BOOTABLE == 1 )); then- if (( RELEASE_HELP_RC != 0 )); then- (( QUIET == 0 )) && {- echo ""- echo "Error: signed release vphone-vm is not launchable on this host (exit $RELEASE_HELP_RC)." >&2- }- exit "$RELEASE_HELP_RC"- fi-fidiff --git a/scripts/cfw_install.sh b/scripts/cfw_install.shdeleted file mode 100755index 9c418f2a..00000000--- a/scripts/cfw_install.sh+++ /dev/null@@ -1,545 +0,0 @@-#!/bin/zsh-# vphone-tier: dist-# cfw_install.sh — Install base CFW modifications on vphone.-#-# Installs Cryptexes, patches required system binaries, and installs vphoned.-#-# Files are placed directly on the VM's Disk.img volumes, which cfw_install_host.sh-# attaches and mounts on the host; the VM must be off.-#-# Safe to run multiple times — always patches from original .bak files,-# keeps decrypted Cryptex DMGs cached, handles already-mounted filesystems.-#-# Prerequisites:-# - VM restored (make restore) and powered off-# - /usr/bin/aea (macOS 12+) — the only external program this script runs-# - vphone-cli built (make build) — every CFW patcher, the signer, the-# archive reader and the prebuilt guest binaries come with it-# - the bundled GPU driver payload and prebuilt vphoned present-#-# Usage: make cfw_install-set -euo pipefail--# ── Restore caller's PATH — Nix /etc/zshenv resets PATH on zsh startup ─-[[ -n "${_VPHONE_PATH:-}" ]] && export PATH="$_VPHONE_PATH"--VM_DIR="${1:-.}"-SCRIPT_DIR="${0:a:h}"--# Resolve absolute paths-VM_DIR="$(cd "$VM_DIR" && pwd)"--# ── vphone-cli resolver — every CFW patcher this script calls lives in it ─-# Same order as scripts/cfw_install_host.sh and cfw-kit/run.sh: VPHONE_CLI_BIN-# when a vphone-cli subcommand invoked us, otherwise a dev tree or the .app,-# where scripts/ sits in Contents/Resources and the binaries are one level up-# in MacOS. Never `command -v` — the binary has to be the one we built beside-# these scripts, not whatever else is on PATH.-# Resolved up front, before anything is mounted or written: a missing binary-# should stop the run here, not halfway through with volumes attached.-VPHONE_CLI="${VPHONE_CLI_BIN:-}"-if [[ -z "$VPHONE_CLI" ]]; then- for candidate in "${SCRIPT_DIR:h}/.build/release/vphone-cli" "${SCRIPT_DIR:h:h}/MacOS/vphone-cli"; do- [[ -x "$candidate" ]] && { VPHONE_CLI="$candidate"; break }- done-fi-[[ -x "$VPHONE_CLI" ]] || {- echo "[-] cannot find vphone-cli (the CFW patchers live in it) — run 'make build'" >&2- exit 1-}--# vphone-archive and vphone-cli are always installed side by side — in-# .build/release during development and in Contents/MacOS in the .app — so a-# sibling of the binary we just resolved is the whole lookup. It replaces the-# GNU tar and zstd this script used to reach for on PATH.-VPHONE_ARCHIVE="${VPHONE_CLI:h}/vphone-archive"-[[ -x "$VPHONE_ARCHIVE" ]] || {- echo "[-] cannot find vphone-archive beside $VPHONE_CLI — run 'make build'" >&2- exit 1-}--# The vphoned binary this install puts in the guest is cross-compiled at-# BUILD time (scripts/guest_binaries.mk) and shipped, because compiling them-# here would make Xcode and the iPhoneOS SDK a requirement for running a VM.-# Contents/Resources/guest in the .app, .build/guest in a dev tree.-GUEST_BIN=""-for candidate in "${SCRIPT_DIR:h}/guest" "${SCRIPT_DIR:h}/.build/guest"; do- [[ -d "$candidate" ]] && { GUEST_BIN="$candidate"; break }-done--# ── Configuration ───────────────────────────────────────────────-TEMP_DIR="$VM_DIR/.cfw_temp"--# ── Helpers ─────────────────────────────────────────────────────-die() {- echo "[-] $*" >&2- exit 1-}--# ldid is gone from this script. `vphone-cli sign` writes the same bytes — the-# same CodeDirectory, the same synthesised designated requirement, no CMS and-# no ad-hoc flag — out of the system frameworks, and it ships inside the .app.-# ldid did not: it links Homebrew's libcrypto.3 and libplist-2.0.4, so a .app-# carrying it worked on the machine that built it and nowhere else.-#-# The three shapes this file ever called it in map one to one:-# ldid -S -M [-I<id>] f -> guest_sign f [id]-# ldid -S<ent> -M [-I] f -> guest_sign_ent f ent [id]-# ldid -e f -> guest_entitlements f-guest_sign() {- local file="$1" bundle_id="${2:-}"- local args=(--merge)- [[ -n "$bundle_id" ]] && args+=(--identifier "$bundle_id")- "$VPHONE_CLI" sign "${args[@]}" "$file"-}--# Like guest_sign but re-applies an entitlements plist (for binaries whose-# entitlements must survive the re-sign, e.g. diskimagesiod's embedded sandbox-# profile + private DA/apfs entitlements).-guest_sign_ent() {- local file="$1" ent="$2" bundle_id="${3:-}"- local args=(--entitlements "$ent" --merge)- [[ -n "$bundle_id" ]] && args+=(--identifier "$bundle_id")- "$VPHONE_CLI" sign "${args[@]}" "$file"-}--# `ldid -e`: the embedded entitlements of every slice, byte for byte and with-# nothing in between, because the output is redirected into a plist and fed-# straight back to guest_sign_ent.-guest_entitlements() {- "$VPHONE_CLI" dump-entitlements "$1"-}--# `tar` in every shape this script used it. The compressor is detected from the-# file, so --zstd is not passed and cannot be passed wrongly; --warning= has no-# counterpart because nothing warns.-guest_untar() { # guest_untar <archive> <dest> [extra flags…]- local archive="$1" dest="$2"; shift 2- "$VPHONE_ARCHIVE" extract -f "$archive" -C "$dest" "$@"-}--host_hdiutil() {- local rc- # SUDO_PASSWORD flow exports SUDO_ASKPASS: go straight to sudo -A so- # hdiutil never runs unprivileged first (which triggers an auth prompt).- [[ -n "${SUDO_ASKPASS:-}" ]] && { sudo -A hdiutil "$@"; return; }-- hdiutil "$@" && return 0- rc=$?-- if sudo -n true 2>/dev/null; then- sudo hdiutil "$@"- return- fi-- return "$rc"-}--# Detach a DMG mountpoint if currently mounted, ignore errors-safe_detach() {- local mnt="$1"- if mount | grep -Fq " on $mnt "; then- host_hdiutil detach -force "$mnt" 2>/dev/null || true- fi-}--assert_mount_under_vm() {- local mnt="$1" label="${2:-mountpoint}"- local abs_vm abs_mnt-- abs_vm="$(cd "$VM_DIR" && pwd -P)"- abs_mnt="$(cd "$mnt" && pwd -P)"- case "$abs_mnt/" in- "$abs_vm/"*) ;;- *) die "Unsafe ${label}: ${abs_mnt} (must be inside ${abs_vm})" ;;- esac-}--# ── Find restore directory ─────────────────────────────────────-find_restore_dir() {- for dir in "$VM_DIR"/iPhone*_Restore; do- [[ -f "$dir/BuildManifest.plist" ]] && echo "$dir" && return- done- die "No restore directory found in $VM_DIR"-}--# ── Check prerequisites ────────────────────────────────────────-# What used to be here was `command -v ipsw` and `command -v aea`. The first is-# gone: the one thing this script asked ipsw for was the SystemOS AEA key, and-# `vphone-cli fw aea-key` derives it from the archive's own auth data. The-# second stays, because /usr/bin/aea is part of macOS — but it is called by-# absolute path now, so there is nothing left to look up.-require_firmware_tools() {- [[ -x /usr/bin/aea ]] || die "/usr/bin/aea missing (it ships with macOS 12+)"- [[ -n "$GUEST_BIN" ]] || die "no prebuilt guest binaries — run 'make build'"- echo "[*] Patchers: $VPHONE_CLI cfw"-}--# ── Cleanup trap (unmount DMGs on error) ───────────────────────-cleanup_on_exit() {- safe_detach "$TEMP_DIR/mnt_sysos" 2>/dev/null || true- safe_detach "$TEMP_DIR/mnt_appos" 2>/dev/null || true-}-trap cleanup_on_exit EXIT--# The VM's Disk.img is attached on the host by cfw_install_host.sh; its APFS-# volumes are mounted here and every file is placed with plain cp/chmod/etc.-# (the VM is off — nothing runs "on the device").-: "${CFW_HOST_CONTAINER:?CFW_HOST_CONTAINER unset — run via cfw_install_host.sh}"-HOST_MNT="${CFW_HOST_MNT:-/private/tmp/cfwhost}"-MNT1="$HOST_MNT/mnt1" # disk1s1 (System / rootfs)-MNT3="$HOST_MNT/mnt3" # disk1s3-mkdir -p "$HOST_MNT"--# Mount an APFS volume of the attached image container at a host mount point.-mount_vol() { # mount_vol <slice, e.g. s1> <mountpoint> [opts]- local dev="/dev/${CFW_HOST_CONTAINER}$1" mnt="$2" opts="${3:-rw}"- /bin/mkdir -p "$mnt"- /sbin/mount | /usr/bin/grep -q " on $mnt " && return 0- /sbin/mount_apfs -o "$opts" "$dev" "$mnt" 2>/dev/null || true- /sbin/mount | /usr/bin/grep -q " on $mnt " || die "mount failed: $dev -> $mnt"-}--# ════════════════════════════════════════════════════════════════-# Main-# ════════════════════════════════════════════════════════════════-echo "[*] cfw_install.sh — Installing CFW on vphone..."--require_firmware_tools--RESTORE_DIR=$(find_restore_dir)-echo "[+] Restore directory: $RESTORE_DIR"--mkdir -p "$TEMP_DIR"--# ── Parse Cryptex paths from BuildManifest ─────────────────────-echo ""-echo "[*] Parsing iPhone BuildManifest for Cryptex paths..."-CRYPTEX_PATHS=$("$VPHONE_CLI" cfw cryptex-paths "$RESTORE_DIR/iPhone-BuildManifest.plist")-CRYPTEX_SYSOS=$(echo "$CRYPTEX_PATHS" | head -1)-CRYPTEX_APPOS=$(echo "$CRYPTEX_PATHS" | tail -1)-echo " SystemOS: $CRYPTEX_SYSOS"-echo " AppOS: $CRYPTEX_APPOS"--# ═══════════ 1/7 INSTALL CRYPTEX ══════════════════════════════-echo ""-echo "[1/7] Installing Cryptex (SystemOS + AppOS)..."--# Mount the image's System volume first to check existing state-echo " Mounting rootfs rw..."-mount_vol s1 "$MNT1"--# Check if Cryptexes already exist on the volume (skip the slow copy if so).-# ls only runs when the dir exists, so its failure can't trip set -e/pipefail-# (on a fresh install these dirs don't exist yet → counts stay 0).-CRYPTEX_OS_COUNT=0-CRYPTEX_APP_COUNT=0-[[ -d "$MNT1/System/Cryptexes/OS" ]] && CRYPTEX_OS_COUNT=$(/bin/ls "$MNT1/System/Cryptexes/OS/" | /usr/bin/wc -l | tr -d ' ')-[[ -d "$MNT1/System/Cryptexes/App" ]] && CRYPTEX_APP_COUNT=$(/bin/ls "$MNT1/System/Cryptexes/App/" | /usr/bin/wc -l | tr -d ' ')--if [[ "${CRYPTEX_OS_COUNT:-0}" -gt 0 && "${CRYPTEX_APP_COUNT:-0}" -gt 0 ]]; then- echo " [*] Cryptexes already installed (OS=${CRYPTEX_OS_COUNT} entries, App=${CRYPTEX_APP_COUNT} entries), skipping"-- # Still ensure dyld symlinks exist- /bin/ln -sf ../../../System/Cryptexes/OS/System/Library/Caches/com.apple.dyld \- $MNT1/System/Library/Caches/com.apple.dyld- /bin/ln -sf ../../../../System/Cryptexes/OS/System/DriverKit/System/Library/dyld \- $MNT1/System/DriverKit/System/Library/dyld-- echo " [+] Cryptex skipped (already present)"-else- SYSOS_DMG="$TEMP_DIR/CryptexSystemOS.dmg"- APPOS_DMG="$TEMP_DIR/CryptexAppOS.dmg"- MNT_SYSOS="$TEMP_DIR/mnt_sysos"- MNT_APPOS="$TEMP_DIR/mnt_appos"-- # Decrypt SystemOS AEA (cached — skip if already decrypted)- if [[ ! -f "$SYSOS_DMG" ]]; then- echo " Extracting AEA key..."- AEA_KEY=$("$VPHONE_CLI" fw aea-key "$RESTORE_DIR/$CRYPTEX_SYSOS")- echo " key: $AEA_KEY"- echo " Decrypting SystemOS..."- /usr/bin/aea decrypt -i "$RESTORE_DIR/$CRYPTEX_SYSOS" -o "$SYSOS_DMG" -key-value "$AEA_KEY"- else- echo " Using cached SystemOS DMG"- fi-- # Copy AppOS (unencrypted, cached)- if [[ ! -f "$APPOS_DMG" ]]; then- cp "$RESTORE_DIR/$CRYPTEX_APPOS" "$APPOS_DMG"- else- echo " Using cached AppOS DMG"- fi-- # Detach any leftover mounts from previous runs- safe_detach "$MNT_SYSOS"- safe_detach "$MNT_APPOS"- mkdir -p "$MNT_SYSOS" "$MNT_APPOS"- assert_mount_under_vm "$MNT_SYSOS" "SystemOS mountpoint"- assert_mount_under_vm "$MNT_APPOS" "AppOS mountpoint"-- echo " Mounting SystemOS..."- host_hdiutil attach -mountpoint "$MNT_SYSOS" "$SYSOS_DMG" -nobrowse -owners off \- || die "Failed to mount SystemOS DMG. Run 'sudo -v' in a terminal and retry if hdiutil needs administrator privileges."- echo " Mounting AppOS..."- host_hdiutil attach -mountpoint "$MNT_APPOS" "$APPOS_DMG" -nobrowse -owners off \- || die "Failed to mount AppOS DMG. Run 'sudo -v' in a terminal and retry if hdiutil needs administrator privileges."-- /bin/rm -rf $MNT1/System/Cryptexes/App $MNT1/System/Cryptexes/OS- /bin/mkdir -p $MNT1/System/Cryptexes/App $MNT1/System/Cryptexes/OS- /bin/chmod 0755 $MNT1/System/Cryptexes/App $MNT1/System/Cryptexes/OS-- # Copy Cryptex files onto the volume- echo " Copying Cryptexes..."- cp -R "$MNT_SYSOS/." "$MNT1/System/Cryptexes/OS"- cp -R "$MNT_APPOS/." "$MNT1/System/Cryptexes/App"-- # Create dyld symlinks (ln -sf is idempotent)- echo " Creating dyld symlinks..."- /bin/ln -sf ../../../System/Cryptexes/OS/System/Library/Caches/com.apple.dyld \- $MNT1/System/Library/Caches/com.apple.dyld- /bin/ln -sf ../../../../System/Cryptexes/OS/System/DriverKit/System/Library/dyld \- $MNT1/System/DriverKit/System/Library/dyld-- # Unmount Cryptex DMGs- echo " Unmounting Cryptex DMGs..."- safe_detach "$MNT_SYSOS"- safe_detach "$MNT_APPOS"-- echo " [+] Cryptex installed"-fi--# Some userland versions send an IOMobileFramebuffer SwapEnd state whose size-# differs from what the PCC vphone600 userclient expects (an exact-# checkStructureInputSize check), so SwapEnd returns kIOReturnBadArgument and-# the host VZ display stays black (guest still renders; visible over VNC).-#-# The accepted size is a property of the BASE KERNEL, not the userland:-# - 26.1 base: userclient expects 0x560-# - 26.4 base (xnu-12377, current): userclient expects 0x588-# Reliably reading it from the kernelcache needs the IOMFB userclient dispatch-# table (a blind shape-scan is ambiguous — 8 candidates), so until that dynamic-# detection lands we key the target off the userland version as a proxy for the-# validated base pairing:-# - 27.x runs on the 26.4 base -> 0x588-# - 26.0/26.0.1 and 18.x validated on 26.1 base -> 0x560-# Known userland-sent sizes: 18.x -> 0x514, 26.0/26.0.1 -> 0x548, 27.0 -> 0x6e0.-# Patch only that immediate in the installed DSC; the patcher is semantic +-# idempotent (rewrites the SwapEnd size to the target, no-op if already there).-# NOTE: iOS 27 is NOT handled by the size-truncation path — its swap struct-# (0x6e0) has a new layout, and more fundamentally 27 defaults the paravirt-# display's present to IOMFB's `_virt_*` callback path, which never enters the-# userclient at all (method 5 is never called), so no size change would help.-# iOS 27 instead gets `patch-iomfb-force-kern` below, which retargets IOMFB's-# public Swap* trampolines to their `_kern_*` (method-5) siblings — the path the-# 26.4 paravirt GPU scans out to the host — paired with the KernelJBPatchIomfbSwap-# kernel patches that make the userclient accept 27's native 0x6e0 struct.-IOS_VERSION=$(/usr/bin/plutil -extract ProductVersion raw -o - "$MNT1/System/Library/CoreServices/SystemVersion.plist" 2>/dev/null || true)-DSC_DIR="$MNT1/System/Cryptexes/OS/System/Library/Caches/com.apple.dyld"-case "$IOS_VERSION" in- 26.0*|18.*)- echo " [*] Patching IOMobileFramebuffer SwapEnd payload size (iOS $IOS_VERSION -> 0x560)..."- [[ -d "$DSC_DIR" ]] || die "dyld cache dir missing: $DSC_DIR"- "$VPHONE_CLI" cfw patch-iomfb-swapend "$DSC_DIR" --target-size 0x560- ;;- 27.*)- echo " [*] Forcing IOMobileFramebuffer present onto the kern (method-5) path (iOS $IOS_VERSION)..."- [[ -d "$DSC_DIR" ]] || die "dyld cache dir missing: $DSC_DIR"- "$VPHONE_CLI" cfw patch-iomfb-force-kern "$DSC_DIR"- ;;-esac--# iOS-27-only DSC patches (hard-gated — a 26.x/18.x base applies neither).-# - maxSlide: iOS 27's dyld shared cache nearly fills the vphone600 26.x kernel's-# fixed 6 GiB shared region. The kernel reserves the cache's mapped span PLUS the-# cache-header maxSlide (512 MiB); iOS 27.0 (~5.95 GiB span + 512 MiB) overflows-# 0x180000000, so _shared_region_map_and_slide returns ENOMEM, dyld cannot map-# libSystem, and launchd (pid 1) panics at boot. Zero maxSlide so the cache maps-# at slide 0. (The patcher also self-gates on the actual span, but older userlands-# fit with full slide and never need it — so it is not run there at all.)-# - lsd embedded-registration gate: opens lsd's containerized-registration path so-# registerApplicationDictionary is a no-op stub on 27. The gate remains-# part of the maximal JB patch set even though app bootstrap is external.-# - xpc LWCR self-check: iOS 27's libxpc brk-aborts when its Lightweight Code-# Requirement matcher returns the contradictory (matched=0, error_code=MATCH) pair-# that our JB code-signing environment produces. That crash-loops every daemon which-# pins an entitlement peer-requirement (intelligencetasksd/searchpartyd/transparencyd/-# bluetoothd/...). Absent on 26.x/18.x libxpc (self-gating patcher no-ops there).-# FORCE_DSC_MAXSLIDE=1 (default 0): opt in to zeroing maxSlide on non-27 bases,-# whose caches fit and would otherwise self-gate to a no-op (--force bypasses that).-FORCE_DSC_MAXSLIDE="${FORCE_DSC_MAXSLIDE:-0}"-case "$IOS_VERSION" in- 27.*)- if [[ -d "$DSC_DIR" ]]; then- echo " [*] Checking dyld cache maxSlide vs kernel shared region..."- "$VPHONE_CLI" cfw patch-dsc-maxslide "$DSC_DIR"- echo " [*] Patching lsd embedded-registration gate (iOS 27 app registration)..."- "$VPHONE_CLI" cfw patch-lsd-embedded-reg "$DSC_DIR"- echo " [*] Patching libxpc LWCR self-check (iOS 27 daemon crash-loop)..."- "$VPHONE_CLI" cfw patch-xpc-lwcr "$DSC_DIR"- echo " [*] Patching os_lockdown_mode_enabled (missing MAC sysctl -> launchd abort)..."- "$VPHONE_CLI" cfw patch-lockdown-mode "$DSC_DIR"- fi- ;;- *)- if [[ "$FORCE_DSC_MAXSLIDE" == "1" && -d "$DSC_DIR" ]]; then- echo " [*] Forcing dyld cache maxSlide=0 (opt-in FORCE_DSC_MAXSLIDE=1; base iOS ${IOS_VERSION:-unknown})..."- "$VPHONE_CLI" cfw patch-dsc-maxslide "$DSC_DIR" --force- fi- ;;-esac--# ═══════════ 2/7 PATCH SEPUTIL ════════════════════════════════-echo ""-echo "[2/7] Patching seputil..."--# Always patch from .bak (original unpatched binary)-if ! [[ -e "$MNT1/usr/libexec/seputil.bak" ]]; then- echo " Creating backup..."- /bin/cp $MNT1/usr/libexec/seputil $MNT1/usr/libexec/seputil.bak-fi--cp "$MNT1/usr/libexec/seputil.bak" "$TEMP_DIR/seputil"-"$VPHONE_CLI" cfw patch-seputil "$TEMP_DIR/seputil"-guest_sign "$TEMP_DIR/seputil" "com.apple.seputil"-cp -R "$TEMP_DIR/seputil" "$MNT1/usr/libexec/seputil"-/bin/chmod 0755 $MNT1/usr/libexec/seputil--# ── DDI (/System/Developer) auto-mount — diskimagesiod (iOS 27 only) ──-# Force -[DIDiskArb isMountCompleteWithExpectedCount:diskTracker:] → YES so-# MobileStorageMounter proceeds to mount the iOS-27 personalized DDI (its-# waitForDAMount otherwise hangs forever on the 26.4 vphone600 hybrid: only some-# IOMedia appear to diskimagesiod's DA session + DA never auto-mounts). Pairs-# with the DiskImages2 ABI + sandbox mac_policy_ops[124] JB kernel patches.-# Entitlements (embedded sandbox profile + private DA/apfs) preserved on re-sign.-# Gated to 27.*: on a version-matched userland the native waitForDAMount completes-# correctly, and forcing the wait to return early could race the real mount — so-# it is NOT applied there (uses the same $IOS_VERSION as the DSC patches above).-case "$IOS_VERSION" in- 27.*)- echo " Patching diskimagesiod (DDI auto-mount, iOS $IOS_VERSION)..."- if ! [[ -e "$MNT1/usr/libexec/diskimagesiod.bak" ]]; then- /bin/cp "$MNT1/usr/libexec/diskimagesiod" "$MNT1/usr/libexec/diskimagesiod.bak"- fi- guest_entitlements "$MNT1/usr/libexec/diskimagesiod.bak" > "$TEMP_DIR/diskimagesiod.ent.plist"- cp "$MNT1/usr/libexec/diskimagesiod.bak" "$TEMP_DIR/diskimagesiod"- "$VPHONE_CLI" cfw patch-diskimagesiod "$TEMP_DIR/diskimagesiod"- guest_sign_ent "$TEMP_DIR/diskimagesiod" "$TEMP_DIR/diskimagesiod.ent.plist" "com.apple.diskimagesiod"- cp -R "$TEMP_DIR/diskimagesiod" "$MNT1/usr/libexec/diskimagesiod"- /bin/chmod 0755 "$MNT1/usr/libexec/diskimagesiod"- ;;-esac--# Rename gigalocker (mv to same name is fine on re-run)-echo " Renaming gigalocker..."-mount_vol s3 "$MNT3"-mv "$MNT3"/*.gl(N) "$MNT3/AA.gl" 2>/dev/null || true--echo " [+] seputil patched"--# ═══════════ 3/7 INSTALL GPU DRIVER ══════════════════════════-echo ""-echo "[3/7] Installing AppleParavirtGPUMetalIOGPUFamily..."--guest_untar "$SCRIPT_DIR/payloads/AppleParavirtGPUMetalIOGPUFamily.tar" "$MNT1" \- --preserve-permissions --no-overwrite-dir--BUNDLE="$MNT1/System/Library/Extensions/AppleParavirtGPUMetalIOGPUFamily.bundle"-# Clean macOS resource fork files (._* files from tar xattrs)-find $BUNDLE -name '._*' -delete 2>/dev/null || true-/usr/sbin/chown -R 0:0 $BUNDLE-/bin/chmod 0755 $BUNDLE-/bin/chmod 0755 $BUNDLE/libAppleParavirtCompilerPluginIOGPUFamily.dylib-/bin/chmod 0755 $BUNDLE/AppleParavirtGPUMetalIOGPUFamily-/bin/chmod 0755 $BUNDLE/_CodeSignature-/bin/chmod 0644 $BUNDLE/_CodeSignature/CodeResources-/bin/chmod 0644 $BUNDLE/Info.plist-echo " [+] GPU driver installed"--# ═══════════ 5/7 PATCH LAUNCHD_CACHE_LOADER ══════════════════-echo ""-echo "[5/7] Patching launchd_cache_loader..."--# Always patch from .bak (original unpatched binary)-if ! [[ -e "$MNT1/usr/libexec/launchd_cache_loader.bak" ]]; then- echo " Creating backup..."- /bin/cp $MNT1/usr/libexec/launchd_cache_loader $MNT1/usr/libexec/launchd_cache_loader.bak-fi--cp "$MNT1/usr/libexec/launchd_cache_loader.bak" "$TEMP_DIR/launchd_cache_loader"-"$VPHONE_CLI" cfw patch-launchd-cache-loader "$TEMP_DIR/launchd_cache_loader"-guest_sign "$TEMP_DIR/launchd_cache_loader" "com.apple.launchd_cache_loader"-cp -R "$TEMP_DIR/launchd_cache_loader" "$MNT1/usr/libexec/launchd_cache_loader"-/bin/chmod 0755 $MNT1/usr/libexec/launchd_cache_loader--echo " [+] launchd_cache_loader patched"--# ═══════════ 6/7 PATCH MOBILEACTIVATIOND ═════════════════════-echo ""-echo "[6/7] Patching mobileactivationd..."--# Always patch from .bak (original unpatched binary)-if ! [[ -e "$MNT1/usr/libexec/mobileactivationd.bak" ]]; then- echo " Creating backup..."- /bin/cp $MNT1/usr/libexec/mobileactivationd $MNT1/usr/libexec/mobileactivationd.bak-fi--cp "$MNT1/usr/libexec/mobileactivationd.bak" "$TEMP_DIR/mobileactivationd"-"$VPHONE_CLI" cfw patch-mobileactivationd "$TEMP_DIR/mobileactivationd"-guest_sign "$TEMP_DIR/mobileactivationd"-cp -R "$TEMP_DIR/mobileactivationd" "$MNT1/usr/libexec/mobileactivationd"-/bin/chmod 0755 $MNT1/usr/libexec/mobileactivationd--echo " [+] mobileactivationd patched"--# ═══════════ 7/7 LAUNCHDAEMONS + LAUNCHD.PLIST ══════════════-echo ""-echo "[7/7] Installing LaunchDaemons..."--# Install vphoned (vsock HID injector daemon).-#-# It used to be cross-compiled right here, out of .m sources shipped inside the-# .app, whenever they looked newer than the binary — which made Xcode and the-# iPhoneOS SDK a requirement for installing CFW onto a VM. It is built at build-# time now (scripts/guest_binaries.mk) and shipped compiled.-VPHONED_SRC="$SCRIPT_DIR/vphoned"-VPHONED_BIN="$GUEST_BIN/vphoned"-[[ -f "$VPHONED_BIN" ]] || die "missing prebuilt vphoned at $VPHONED_BIN — run 'make build'"-cp "$VPHONED_BIN" "$TEMP_DIR/vphoned"-guest_sign_ent "$TEMP_DIR/vphoned" "$VPHONED_SRC/entitlements.plist"-cp -R "$TEMP_DIR/vphoned" "$MNT1/usr/bin/vphoned"-/bin/chmod 0755 $MNT1/usr/bin/vphoned-# Keep a copy of the signed binary for host-side auto-update-cp "$TEMP_DIR/vphoned" "$VM_DIR/.vphoned.signed"-echo " [+] vphoned installed (signed copy at .vphoned.signed)"--cp -R "$VPHONED_SRC/vphoned.plist" "$MNT1/System/Library/LaunchDaemons/"-/bin/chmod 0644 $MNT1/System/Library/LaunchDaemons/vphoned.plist--# Always patch launchd.plist from .bak (original)-echo " Patching launchd.plist..."-if ! [[ -e "$MNT1/System/Library/xpc/launchd.plist.bak" ]]; then- echo " Creating backup..."- /bin/cp $MNT1/System/Library/xpc/launchd.plist $MNT1/System/Library/xpc/launchd.plist.bak-fi--cp "$MNT1/System/Library/xpc/launchd.plist.bak" "$TEMP_DIR/launchd.plist"-"$VPHONE_CLI" cfw inject-daemon "$TEMP_DIR/launchd.plist" \- "$VPHONED_SRC/vphoned.plist" --name vphoned-cp -R "$TEMP_DIR/launchd.plist" "$MNT1/System/Library/xpc/launchd.plist"-/bin/chmod 0644 $MNT1/System/Library/xpc/launchd.plist--echo " [+] LaunchDaemons installed"--# ═══════════ CLEANUP ═════════════════════════════════════════-echo ""-echo "[*] Unmounting image volumes..."-/sbin/umount $MNT1 2>/dev/null || true-/sbin/umount $MNT3 2>/dev/null || true--echo "[*] Cleaning up temp..."-rm -rf "$TEMP_DIR"--echo ""-echo "[+] CFW installation complete!"-echo " Boot to apply changes."diff --git a/scripts/cfw_install_host.sh b/scripts/cfw_install_host.shdeleted file mode 100755index f6e084e6..00000000--- a/scripts/cfw_install_host.sh+++ /dev/null@@ -1,110 +0,0 @@-#!/bin/zsh-# vphone-tier: dist-# cfw_install_host.sh — CFW install by host-mounting the VM's Disk.img.-#-# Attaches the VM's Disk.img on the host and hands the container to the JB-# installer, which mounts the APFS volumes and places every-# CFW file directly. Then flips the boot snapshot offline-# (`vphone-cli cfw flip-snapshot`) so the VM boots the live volume.-#-# Prereqs: VM restored (make restore) and powered off, and a built vphone-cli-# (make build), which is where every CFW patcher, the signer and the archive-# reader live. There is no host toolchain to install: this used to need gnu-tar,-# ipsw, ldid and zstd from Homebrew plus Xcode for the guest binaries, and now-# needs nothing outside macOS. SIP disabled (project baseline); NO-# authenticated-root/ARV change needed.-#-# Usage: cfw_install_host.sh [vm_dir]-# Runs as root (mount_apfs/chown/cp to owners-honored mounts); re-execs under-# sudo automatically (honors SUDO_ASKPASS for non-interactive use).-set -euo pipefail-SCRIPT_DIR="${0:a:h}"-PROJ="${SCRIPT_DIR:h}"--VM_DIR="${1:-$PROJ/vm}"-[[ $# -le 1 ]] || { echo "[-] expected one VM directory" >&2; exit 1; }--# Re-exec as root; owners-honored mounts + chown/cp require it.-if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then- exec sudo ${SUDO_ASKPASS:+-A} -E /bin/zsh "$0" "$VM_DIR"-fi-unset SUDO_ASKPASS # already root: host_hdiutil/pre-step use plain sudo/hdiutil--VM_DIR="${VM_DIR:a}"-IMG="$VM_DIR/Disk.img"-[[ -f "$IMG" ]] || { echo "[-] no Disk.img at $IMG" >&2; exit 1; }--# System directories only.-#-# This used to prepend "$PROJ/.tools/bin:/opt/homebrew/bin", because the-# installers needed gnu-tar, ipsw, ldid and zstd from Homebrew. None of them is-# reached for any more: signing is `vphone-cli sign`, archives are-# `vphone-archive`, the AEA key is `vphone-cli fw aea-key`, and the guest-# binaries are cross-compiled at build time instead of by xcrun here. Putting-# Homebrew back on this PATH would let a dependency return without anything-# failing, which is exactly how the last one survived so long.-#-# No python entry either, at either end: the installers call `vphone-cli cfw-# <verb>` for every patch, and as of P2.4 there is no interpreter on this-# machine's behalf to find.-P="/usr/bin:/bin:/usr/sbin:/sbin"-export PATH="$P"--if /usr/sbin/lsof "$IMG" >/dev/null 2>&1; then- echo "[-] $IMG is in use — stop the VM first." >&2; exit 1-fi--echo "[*] host-mode JB CFW install: vm=$VM_DIR"-AO=$(hdiutil attach -nomount -imagekey diskimage-class=CRawDiskImage "$IMG" 2>/dev/null)-BASEDISK=$(awk 'NR == 1 { print $1; exit }' <<< "$AO")-CONT=$(diskutil info -plist "${BASEDISK}s1" | /usr/bin/plutil -extract APFSContainerReference raw -o - - 2>/dev/null || true)-SYS=$(diskutil apfs list "$CONT" 2>/dev/null | awk '/APFS Volume Disk \(Role\):/{for(i=1;i<=NF;i++) if($i ~ /^disk[0-9]+s[0-9]+$/) dev=$i} /Name:.*System \(Case-sensitive\)/{print dev; exit}')-[[ -n "$CONT" && -n "$SYS" ]] || { echo "[-] System volume not found in $IMG" >&2; hdiutil detach "$BASEDISK" 2>/dev/null; exit 1; }-echo "[*] attached: container=$CONT system=$SYS"--cleanup() {- for m in /private/tmp/cfwhost/mnt1 /private/tmp/cfwhost/mnt3 /private/tmp/cfwhost/mnt5; do- umount "$m" 2>/dev/null || true- done- hdiutil detach "$BASEDISK" 2>/dev/null || diskutil eject "$BASEDISK" 2>/dev/null || true-}-trap cleanup EXIT--echo "[*] running cfw_install_jb.sh (files placed on host mounts)..."-# via env: an expansion-produced ${VAR:+NAME=val} isn't parsed as a shell assignment.-( cd "$VM_DIR" && env CFW_HOST_CONTAINER="$CONT" _VPHONE_PATH="$P" \- ${SPOOF_BUILD:+SPOOF_BUILD="$SPOOF_BUILD"} \- ${FORCE_DSC_MAXSLIDE:+FORCE_DSC_MAXSLIDE="$FORCE_DSC_MAXSLIDE"} \- ${VPHONE_FRIDA:+VPHONE_FRIDA="$VPHONE_FRIDA"} \- zsh "$SCRIPT_DIR/cfw_install_jb.sh" . )--cleanup-trap - EXIT--echo "[*] flipping boot snapshot offline (com.apple.os.update -> live volume)..."-# VPHONE_CLI_BIN is set by `vphone-cli cfw install`; the fallbacks cover being-# run by hand from a dev tree or from inside the .app, where scripts/ sits in-# Contents/Resources and the binaries are one level up in MacOS.-VPHONE_CLI="${VPHONE_CLI_BIN:-}"-if [[ -z "$VPHONE_CLI" ]]; then- for candidate in "$PROJ/.build/release/vphone-cli" "${PROJ:h}/MacOS/vphone-cli"; do- [[ -x "$candidate" ]] && { VPHONE_CLI="$candidate"; break }- done-fi-[[ -x "$VPHONE_CLI" ]] || { echo "[-] cannot find vphone-cli to flip the snapshot" >&2; exit 1; }-"$VPHONE_CLI" cfw flip-snapshot "$IMG"--# The whole install ran as root (owners-honored mounts / chown / cp). Hand the-# host-side artifacts it created (vm/.vphoned.signed and vm/.cfw_temp) back to the invoking user, so the subsequent user-run-# steps (make boot / setup_machine first boot, which rewrite-# vm/.vphoned.signed) don't hit "Permission denied".-#-# scripts/vphoned/vphoned used to need the same treatment, because the install-# compiled it in place as root. It is built at build time now, by the user, and-# nothing here writes to the source tree.-if [[ -n "${SUDO_USER:-}" ]]; then- chown -R "$SUDO_USER" "$VM_DIR" 2>/dev/null || true- echo "[*] restored ownership of host-side artifacts to $SUDO_USER"-fi--echo "[+] host-mode CFW install complete. Boot with: make boot"diff --git a/scripts/cfw_install_jb.sh b/scripts/cfw_install_jb.shdeleted file mode 100755index 015d9593..00000000--- a/scripts/cfw_install_jb.sh+++ /dev/null@@ -1,86 +0,0 @@-#!/bin/zsh-# vphone-tier: dist-# Install the JB-specific system patches after the base CFW and vphoned.-# User package managers, bootstrap payloads, and first-boot installers are out-# of scope: the guest is left empty except for the required daemon.-set -euo pipefail--[[ -n "${_VPHONE_PATH:-}" ]] && export PATH="$_VPHONE_PATH"-SCRIPT_DIR="${0:a:h}"-VM_DIR="${1:-.}"-VM_DIR="$(cd "$VM_DIR" && pwd -P)"--VPHONE_CLI="${VPHONE_CLI_BIN:-}"-if [[ -z "$VPHONE_CLI" ]]; then- for candidate in "${SCRIPT_DIR:h}/.build/release/vphone-cli" "${SCRIPT_DIR:h:h}/MacOS/vphone-cli"; do- [[ -x "$candidate" ]] && { VPHONE_CLI="$candidate"; break }- done-fi-[[ -x "$VPHONE_CLI" ]] || { echo "[-] vphone-cli is missing — run make build" >&2; exit 1; }--echo "[*] Installing JB CFW and vphoned..."-zsh "$SCRIPT_DIR/cfw_install.sh" "$VM_DIR"--: "${CFW_HOST_CONTAINER:?CFW_HOST_CONTAINER unset — run via cfw_install_host.sh}"-HOST_MNT="${CFW_HOST_MNT:-/private/tmp/cfwhost}"-MNT1="$HOST_MNT/mnt1"-TEMP_DIR="$VM_DIR/.cfw_temp"-/bin/mkdir -p "$MNT1" "$TEMP_DIR"-cleanup() {- /sbin/umount "$MNT1" 2>/dev/null || true- /bin/rm -rf "$TEMP_DIR"-}-trap cleanup EXIT--if ! /sbin/mount | /usr/bin/grep -q " on $MNT1 "; then- /sbin/mount_apfs -o rw "/dev/${CFW_HOST_CONTAINER}s1" "$MNT1"-fi--echo "[*] Patching launchd jetsam guard..."-LAUNCHD="$MNT1/sbin/launchd"-[[ -f "$LAUNCHD.bak" ]] || /bin/cp "$LAUNCHD" "$LAUNCHD.bak"-/bin/cp "$LAUNCHD.bak" "$TEMP_DIR/launchd"-"$VPHONE_CLI" dump-entitlements "$TEMP_DIR/launchd" > "$TEMP_DIR/launchd.entitlements" 2>/dev/null || true-"$VPHONE_CLI" cfw patch-launchd-jetsam "$TEMP_DIR/launchd"-if [[ -s "$TEMP_DIR/launchd.entitlements" ]]; then- "$VPHONE_CLI" sign --entitlements "$TEMP_DIR/launchd.entitlements" --merge "$TEMP_DIR/launchd"-else- "$VPHONE_CLI" sign --merge "$TEMP_DIR/launchd"-fi-/bin/cp "$TEMP_DIR/launchd" "$LAUNCHD"-/bin/chmod 0755 "$LAUNCHD"--echo "[*] Patching debugserver entitlements..."-DEBUGSERVER="$MNT1/usr/libexec/debugserver"-if [[ -f "$DEBUGSERVER" ]]; then- /bin/cp "$DEBUGSERVER" "$TEMP_DIR/debugserver"- "$VPHONE_CLI" dump-entitlements "$TEMP_DIR/debugserver" > "$TEMP_DIR/debugserver.entitlements"- /usr/bin/plutil -remove seatbelt-profiles "$TEMP_DIR/debugserver.entitlements" 2>/dev/null || true- /usr/bin/plutil -insert task_for_pid-allow -bool YES "$TEMP_DIR/debugserver.entitlements"- "$VPHONE_CLI" sign --entitlements "$TEMP_DIR/debugserver.entitlements" --merge "$TEMP_DIR/debugserver"- /bin/cp "$TEMP_DIR/debugserver" "$DEBUGSERVER"- /bin/chmod 0755 "$DEBUGSERVER"-else- echo "[!] debugserver is absent; entitlement patch skipped" >&2-fi--IOS_VERSION=$(/usr/bin/plutil -extract ProductVersion raw -o - \- "$MNT1/System/Library/CoreServices/SystemVersion.plist" 2>/dev/null || true)-if [[ "$IOS_VERSION" == 27.* ]]; then- CAMPO="$MNT1/Applications/Campo.app/Campo"- if [[ -f "$CAMPO" ]]; then- echo "[*] Patching Campo entitlements for iOS $IOS_VERSION..."- /bin/cp "$CAMPO" "$TEMP_DIR/Campo"- "$VPHONE_CLI" dump-entitlements "$TEMP_DIR/Campo" > "$TEMP_DIR/Campo.entitlements" 2>/dev/null || true- if [[ -s "$TEMP_DIR/Campo.entitlements" ]]; then- "$VPHONE_CLI" cfw patch-campo-entitlements "$TEMP_DIR/Campo.entitlements"- "$VPHONE_CLI" sign --entitlements "$TEMP_DIR/Campo.entitlements" "$TEMP_DIR/Campo"- /bin/cp "$TEMP_DIR/Campo" "$CAMPO"- /bin/chmod 0755 "$CAMPO"- else- echo "[!] Campo has no readable entitlements; patch skipped" >&2- fi- fi-fi--echo "[+] JB system patches installed; no bootstrap payload staged."diff --git a/scripts/check_aux.sh b/scripts/check_aux.shindex 64fbde40..379742e5 100755--- a/scripts/check_aux.sh+++ b/scripts/check_aux.sh@@ -515,7 +515,7 @@ check_smoke() {# host's own AMFI bypass allows this copy — and the copy under test is a# relocated one, with a path no allowlist was told about. Its exit code would# say something about the host, not about self-containment.- [[ -x "$vm" ]] && note "gate 3: vphone-vm skipped (amfid gates it; see boot_host_preflight.sh)"+ [[ -x "$vm" ]] && note "gate 3: relocated vphone-vm skipped (host AMFI policy may gate it; run vphone-cli host preflight on the installed build)"rm -rf "$tmp"}diff --git a/scripts/tail_jb_patch_logs.sh b/scripts/tail_jb_patch_logs.shdeleted file mode 100755index 080ccbe2..00000000--- a/scripts/tail_jb_patch_logs.sh+++ /dev/null@@ -1,64 +0,0 @@-#!/bin/zsh-# vphone-tier: build-# tail_jb_patch_logs.sh — follow the guest's first-boot JB setup log.-set -euo pipefail-unsetopt BG_NICE 2>/dev/null || true--TARGET_DIR="${1:-}"-TAIL_LINES="${2:-20}"-SCAN_INTERVAL="${SCAN_INTERVAL:-1}"--if [[ -z "$TARGET_DIR" ]]; then- echo "Usage: $0 <log_dir> [tail_lines]" >&2- exit 1-fi--if [[ ! -d "$TARGET_DIR" ]]; then- echo "Error: log directory not found: $TARGET_DIR" >&2- echo "Usage: $0 <log_dir> [tail_lines]" >&2- exit 1-fi--typeset -A seen_files-typeset -a tail_pids--cleanup() {- local pid- for pid in "${tail_pids[@]-}"; do- kill "$pid" 2>/dev/null || true- done-}-trap cleanup EXIT INT TERM--start_tail_for_file() {- local file="$1"- local label="${file:t}"-- [[ -n "${seen_files[$file]-}" ]] && return 0- seen_files["$file"]=1-- echo "[watch] $file"- (- tail -n "$TAIL_LINES" -F -- "$file" 2>&1 \- | awk -v p="$label" '{ print "[" p "] " $0; fflush(); }'- ) &- tail_pids+=("$!")-}--discover_files() {- local file- for file in "$TARGET_DIR"/**/*(.N); do- start_tail_for_file "$file"- done-}--echo "Following logs in: $TARGET_DIR"-echo "Tail lines per file: $TAIL_LINES"-echo "Scan interval: ${SCAN_INTERVAL}s"--discover_files--while true; do- sleep "$SCAN_INTERVAL"- discover_files-donediff --git a/sources/VPhoneCore/VPhoneAPFSSnapshot.swift b/sources/VPhoneCore/VPhoneAPFSSnapshot.swiftindex a0ad38a6..7f8d2378 100644--- a/sources/VPhoneCore/VPhoneAPFSSnapshot.swift+++ b/sources/VPhoneCore/VPhoneAPFSSnapshot.swift@@ -6,6 +6,7 @@ public enum VPhoneAPFSSnapshotError: Error, CustomStringConvertible {case prefixLengthMismatch(given: Int, required: Int)case cannotOpen(URL, errno: Int32)case cannotMap(URL, errno: Int32)+ case cannotAccess(URL, operation: String, errno: Int32)public var description: String {switch self {@@ -15,6 +16,8 @@ public enum VPhoneAPFSSnapshotError: Error, CustomStringConvertible {"Could not open \(url.path): \(String(cString: strerror(err)))"case let .cannotMap(url, err):"Could not map \(url.path): \(String(cString: strerror(err)))"+ case let .cannotAccess(url, operation, err):+ "Could not \(operation) \(url.path): \(String(cString: strerror(err)))"}}}@@ -198,16 +201,27 @@ public enum VPhoneAPFSSnapshot {}let length = Int(stats.st_size)- let protection = dryRun ? PROT_READ : (PROT_READ | PROT_WRITE)- guard let base = mmap(nil, length, protection, MAP_SHARED, fd, 0),- base != MAP_FAILED- else {- throw VPhoneAPFSSnapshotError.cannotMap(url, errno: errno)+ // A Disk.img is commonly 64 GiB. Mapping and touching all of it at+ // once can fill host RAM, even though the file is sparse. Each window+ // starts on a page and APFS block boundary, so scan() still sees each+ // complete metadata block and returns the same records.+ let windowSize = 64 * 1024 * 1024+ var blocks: [(blockOffset: Int, offsetsInBlock: [Int])] = []+ var snapshotName: String?+ for offset in stride(from: 0, to: length, by: windowSize) {+ let count = min(windowSize, length - offset)+ guard let base = mmap(nil, count, PROT_READ, MAP_PRIVATE, fd, off_t(offset)),+ base != MAP_FAILED else {+ throw VPhoneAPFSSnapshotError.cannotMap(url, errno: errno)+ }+ let part = scan(UnsafeRawBufferPointer(start: base, count: count))+ if snapshotName == nil { snapshotName = part.snapshotName }+ blocks.append(contentsOf: part.blocks.map {+ (blockOffset: offset + $0.blockOffset, offsetsInBlock: $0.offsetsInBlock)+ })+ _ = munmap(base, count)}- defer { munmap(base, length) }-- let image = UnsafeRawBufferPointer(start: base, count: length)- let report = scan(image)+ let report = Report(snapshotName: snapshotName, blocks: blocks)guard !report.isEmpty else {log("No com.apple.os.update-* root snapshot found. The snapshot may already be renamed.")@@ -224,27 +238,37 @@ public enum VPhoneAPFSSnapshot {return report}- let writable = UnsafeMutableRawBufferPointer(start: base, count: length)for (blockOffset, offsets) in report.blocks {- for within in offsets {- let at = blockOffset + within- for (k, byte) in newPrefixBytes.enumerated() {- writable[at + k] = byte+ var block = Data(count: blockSize)+ let readCount = block.withUnsafeMutableBytes {+ pread(fd, $0.baseAddress, blockSize, off_t(blockOffset))+ }+ guard readCount == blockSize else {+ throw VPhoneAPFSSnapshotError.cannotAccess(url, operation: "read", errno: errno)+ }+ block.withUnsafeMutableBytes { raw in+ for within in offsets {+ for (k, byte) in newPrefixBytes.enumerated() {+ raw[within + k] = byte+ }+ }+ let sum = checksum(UnsafeRawBufferPointer(raw))+ var littleEndian = sum.littleEndian+ withUnsafeBytes(of: &littleEndian) { bytes in+ for (k, byte) in bytes.enumerated() { raw[k] = byte }}}- // Recompute over the block as it now stands, then stamp it in.- let block = UnsafeRawBufferPointer(- rebasing: image[blockOffset..<blockOffset + blockSize]- )- var sum = checksum(block)- withUnsafeBytes(of: &sum) { bytes in- for (k, byte) in bytes.enumerated() { writable[blockOffset + k] = byte }+ let written = block.withUnsafeBytes {+ pwrite(fd, $0.baseAddress, blockSize, off_t(blockOffset))+ }+ guard written == blockSize else {+ throw VPhoneAPFSSnapshotError.cannotAccess(url, operation: "write", errno: errno)}log("Block 0x\(String(blockOffset, radix: 16)): renamed \(offsets.count) record(s) and fixed the checksum.")}- guard msync(base, length, MS_SYNC) == 0 else {- throw VPhoneAPFSSnapshotError.cannotMap(url, errno: errno)+ guard fsync(fd) == 0 else {+ throw VPhoneAPFSSnapshotError.cannotAccess(url, operation: "sync", errno: errno)}log("Done. Root snapshot renamed to \(newPrefix)*. The VM will boot the live volume.")return reportdiff --git a/sources/VPhoneCore/VPhoneBootPatterns.swift b/sources/VPhoneCore/VPhoneBootPatterns.swiftindex f62ed711..b41f2258 100644--- a/sources/VPhoneCore/VPhoneBootPatterns.swift+++ b/sources/VPhoneCore/VPhoneBootPatterns.swift@@ -2,48 +2,16 @@ import Foundation// MARK: - VPhoneBootPatterns-/// Boot-log regex patterns and device-identity normalization, ported VERBATIM-/// from `scripts/setup_machine.sh` so the native `vm create` orchestrator-/// (`VPhoneCreateOrchestrator`, executable target) matches the proven shell-/// choreography exactly. Lives in VPhoneCore (rather than alongside the-/// orchestrator) purely so `VPhoneCoreTests` can unit-test these pure,-/// device-independent pieces — the orchestrator itself needs `FirmwarePatcher`-/// and can't live in VPhoneCore without creating a package dependency cycle-/// (FirmwarePatcher already depends on VPhoneCore).+/// Boot-log matching and device-identity normalization used by `vm create`.public enum VPhoneBootPatterns {- /// `BOOT_BASH_PROMPT_REGEX` (setup_machine.sh:39) — the iosbinpack bash- /// prompt, or a ramdisk/root shell prompt.- public static let promptRegex = #"bash-[0-9]+(\.[0-9]+)+#|:/[^ ]* root#"#-- /// `BOOT_PANIC_REGEX` (setup_machine.sh:40).+ /// Kernel panic marker in the guest serial log.public static let panicRegex = #"(^|[^p])(panic|kernel panic|panic\.apple\.com|stackshot succeeded)"#- /// `monitor_boot_log_until` (setup_machine.sh:363-388) checks panic and- /// prompt with DIFFERENT case sensitivity — `grep -Eiq "$BOOT_PANIC_REGEX"`- /// (case-insensitive) vs. `grep -Eq "$BOOT_BASH_PROMPT_REGEX"` (case-- /// sensitive). A single `NSRegularExpression` has one global case-folding- /// setting, so the panic half is wrapped in an ICU scoped inline modifier- /// (`(?i:...)`) to fold ONLY that half, leaving the prompt half exactly as- /// case-sensitive as the shell's plain `grep -E`.- public static let panicOrPromptRegex = "(?i:\(panicRegex))|\(promptRegex)"-- /// `send_first_boot_commands` (setup_machine.sh:344-361) — verbatim order,- /// including the exact PATH string (setup_machine.sh:348).- public static let firstBootCommands: [String] = [- "export PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/bin/X11:/usr/games:/iosbinpack64/usr/local/sbin:/iosbinpack64/usr/local/bin:/iosbinpack64/usr/sbin:/iosbinpack64/usr/bin:/iosbinpack64/sbin:/iosbinpack64/bin'",- "cp /iosbinpack64/etc/profile /var/profile",- "cp /iosbinpack64/etc/motd /var/motd",- "mkdir -p /var/dropbear",- "dropbearkey -t rsa -f /var/dropbear/dropbear_rsa_host_key",- "dropbearkey -t ecdsa -f /var/dropbear/dropbear_ecdsa_host_key",- "shutdown -h now",- ]+ /// A connected guest daemon is the first-boot success marker. The old+ /// iosbinpack shell prompt no longer exists in the JB-only guest.+ public static let panicOrVphonedRegex = "(?i:\(panicRegex))|\\[control\\] connected to vphoned v[0-9]+"- /// Port of `normalize_ecid` (setup_machine.sh:80-86): strip one leading- /// `0x` and one leading `0X` (matching the shell's two sequential `#0x`/- /// `#0X` strips), require 1-16 ASCII hex digits, uppercase, and left-pad- /// with zeros to 16 characters. `nil` for anything that isn't valid hex —- /// the shell's `return 1` from the `[[ =~ ]]` guard.+ /// Accept 1-16 ASCII hex digits, with an optional 0x prefix.public static func normalizeECID(_ raw: String) -> String? {var value = rawif value.hasPrefix("0x") { value.removeFirst(2) }diff --git a/sources/VPhoneCore/VPhoneGuestLauncher.swift b/sources/VPhoneCore/VPhoneGuestLauncher.swiftindex def3390d..3ed7ae82 100644--- a/sources/VPhoneCore/VPhoneGuestLauncher.swift+++ b/sources/VPhoneCore/VPhoneGuestLauncher.swift@@ -20,54 +20,19 @@ public enum VPhoneGuestLaunchError: Error, CustomStringConvertible {"""case let .blockedByAMFI(guest, cdHash):- // Both quoted: a VM bundle can sit under a path with spaces, and- // these lines are meant to be pasted, not retyped. The cdhash- // falls back to the command that prints it, so the advice stays- // complete even on a binary this could not read.- let directory = guest.deletingLastPathComponent().path- let cdHashArgument = cdHash.map { "--cdhash \($0)" }- ?? ("--cdhash \"$(codesign -dv --verbose=4 '\(guest.path)'"- + " 2>&1 | sed -n 's/^CDHash=//p' | head -1)\"")+ let helper = guest.deletingLastPathComponent()+ .appendingPathComponent("vphone-amfi-allow")return """amfid refused to launch vphone-vm, so no guest could start.- vphone-vm is the only binary here that carries the private- virtualization entitlements, so it is the only one amfid can- refuse — vphone-cli itself is unentitled and always starts.- Two ways past it; pick one.+ Binary: \(guest.path)+ CDHash: \(cdHash ?? "unavailable")- 1. Allow this one binary, with amfidont.+ Allow this build's signed VM binary with the bundled helper:+ sudo '\(helper.path)' allow '\(guest.path)'- amfidont is not part of vphone-cli: you install it and you- keep it running, and vphone-cli neither installs, starts nor- supervises it. Install it once with Apple's python3 —- Homebrew's refuses under PEP 668 — which also means Xcode- has to be present:-- xcrun python3 -m pip install --user amfidont-- It lands in ~/Library/Python/3.9/bin, which is usually not- on PATH. Leave it running in another terminal, then boot- again:-- sudo amfidont daemon --path '\(directory)' \\- \(cdHashArgument) --spoof-apple --verbose-- It is an allowlist, not a switch: only the path and cdhash- named above are affected, and every other signature amfid- checks is judged exactly as it would be without it. It- drives amfid through LLDB, so it sets breakpoints in the- CPU's debug registers instead of writing amfid's pages —- which is why it works even where- `sysctl vm.cs_system_enforcement` reads 1.-- 2. Relax AMFI for the whole machine, and run nothing extra.-- Set the amfi_get_out_of_my_way=1 boot-arg with SIP off.- With AMFI relaxed vphone-vm launches on its own, and no- daemon is involved at all.-- Both are written up under "SIP/AMFI Relaxation" in README.md.+ The allowlist is specific to this signature, so repeat after a+ rebuild. See "SIP/AMFI Relaxation" in README.md for host settings."""case let .probeFailed(code, output):diff --git a/sources/VPhoneCore/VPhoneLaunchLayout.swift b/sources/VPhoneCore/VPhoneLaunchLayout.swiftindex f4359b28..05e45db3 100644--- a/sources/VPhoneCore/VPhoneLaunchLayout.swift+++ b/sources/VPhoneCore/VPhoneLaunchLayout.swift@@ -8,7 +8,6 @@ public struct VPhoneLaunchLayout: Sendable {public init(resources: VPhoneResources) { self.resources = resources }public init(projectRoot: URL) { self.init(resources: VPhoneResources(base: projectRoot)) }- public var preflightScript: URL { resources.preflightScript }public var vphoned: URL { resources.vphoned }/// Copy the built vphoned into the bundle if present and different.diff --git a/sources/VPhoneCore/VPhoneManagedProcess.swift b/sources/VPhoneCore/VPhoneManagedProcess.swiftindex 3733864f..25838cb2 100644--- a/sources/VPhoneCore/VPhoneManagedProcess.swift+++ b/sources/VPhoneCore/VPhoneManagedProcess.swift@@ -10,9 +10,8 @@ public enum VPhoneMatchResult: Equatable, Sendable {// MARK: - VPhoneManagedProcess-/// A long-lived child process with stdin driving and stdout/stderr-/// regex-waiting — the primitive for DFU background boot, first-boot-/// command injection, and boot log analysis.+/// A long-lived child process with stdin and stdout/stderr regex-waiting,+/// used for DFU background boot and first-boot log checks.public final class VPhoneManagedProcess: @unchecked Sendable {/// Thread-safe accumulator for the combined stdout+stderr bytes, plus an/// EOF flag so `waitForOutput` can tell "no more output is coming" apartdiff --git a/sources/VPhoneCore/VPhoneResources.swift b/sources/VPhoneCore/VPhoneResources.swiftindex 5e9659ec..5b56886d 100644--- a/sources/VPhoneCore/VPhoneResources.swift+++ b/sources/VPhoneCore/VPhoneResources.swift@@ -95,8 +95,6 @@ public struct VPhoneResources: Sendable {public var gpuDriverArchive: URL {scriptsDir.appendingPathComponent("payloads/AppleParavirtGPUMetalIOGPUFamily.tar")}- public var cfwInstallHostScript: URL { scriptsDir.appendingPathComponent("cfw_install_host.sh") }- public var preflightScript: URL { scriptsDir.appendingPathComponent("boot_host_preflight.sh") }public var vphoned: URL {let bundled = base.appendingPathComponent("vphoned.signed")diff --git a/sources/VPhoneCore/VPhoneRestoreOps.swift b/sources/VPhoneCore/VPhoneRestoreOps.swiftindex 5165cbff..3f50aee9 100644--- a/sources/VPhoneCore/VPhoneRestoreOps.swift+++ b/sources/VPhoneCore/VPhoneRestoreOps.swift@@ -1,3 +1,4 @@+import Darwinimport Foundationpublic enum VPhoneRestoreError: Error, Equatable {@@ -67,26 +68,29 @@ public enum VPhoneRestoreOps {return head == Data([0x41, 0x45, 0x41, 0x31])}- /// Decrypt every AEA1-encrypted `*.dmg.aea` in `dir` in place (via `ipsw fw aea`),- /// keeping the `.aea` filename with decrypted content (matches make restore_offline).+ /// Decrypt every AEA1-encrypted `*.dmg.aea` with macOS's aea tool, keeping+ /// the `.aea` filename expected by the offline restore manifest.public static func decryptAEAImages(inRestoreDir dir: URL) throws {let fm = FileManager.defaultlet entries = (try? fm.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)) ?? []for aea in entries where aea.lastPathComponent.hasSuffix(".dmg.aea") {guard try isAEAEncrypted(aea) else { continue }+ let decrypted = dir.appendingPathComponent(".\(aea.lastPathComponent).decrypted-\(UUID().uuidString)")+ defer { try? fm.removeItem(at: decrypted) }+ let key = try vphoneRunBlocking { try await VPhoneAEA.symmetricKey(of: aea) }let code = try VPhoneProcessRunner.runStreaming(- URL(fileURLWithPath: "/usr/bin/env"),- ["ipsw", "fw", "aea", "-o", dir.path, aea.path])+ URL(fileURLWithPath: "/usr/bin/aea"),+ ["decrypt", "-i", aea.path, "-o", decrypted.path, "-key-value", key])guard code == 0 else { throw VPhoneRestoreError.aeaDecryptFailed(aea.lastPathComponent) }- // ipsw wrote <dir>/<name minus .aea>; move it onto the .aea filename.- // Confirm the decrypted output exists BEFORE removing the original (mv -f semantics).- let decrypted = dir.appendingPathComponent(aea.deletingPathExtension().lastPathComponent)guard fm.fileExists(atPath: decrypted.path) else {throw VPhoneRestoreError.aeaDecryptFailed(aea.lastPathComponent)}- if fm.fileExists(atPath: aea.path) { try fm.removeItem(at: aea) }- try fm.moveItem(at: decrypted, to: aea)- if try isAEAEncrypted(aea) { throw VPhoneRestoreError.aeaStillEncrypted(aea.lastPathComponent) }+ guard try !isAEAEncrypted(decrypted) else {+ throw VPhoneRestoreError.aeaStillEncrypted(aea.lastPathComponent)+ }+ guard rename(decrypted.path, aea.path) == 0 else {+ throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno))+ }}}}diff --git a/sources/VPhoneVMKit/VPhoneHostControl.swift b/sources/VPhoneVMKit/VPhoneHostControl.swiftindex acdbf836..a6b1ba73 100644--- a/sources/VPhoneVMKit/VPhoneHostControl.swift+++ b/sources/VPhoneVMKit/VPhoneHostControl.swift@@ -18,6 +18,7 @@ import ImageIO/// {"t":"swipe","x1":645,"y1":2600,"x2":645,"y2":1400,"ms":300} → swipe/// {"t":"key","name":"home"} → hardware key (home/power/volup/voldown)/// {"t":"type","text":"Hello"} → set guest clipboard+/// {"t":"ping"} → vphoned request/response////// All commands except "screenshot" wait briefly then capture a compact screen/// image returned as `"image":"<base64>"` in the response. Pass `"screen":false`@@ -199,6 +200,25 @@ class VPhoneHostControl {let screenDelay = json["delay"] as? Int ?? 500switch type {+ case "ping":+ let semaphore = DispatchSemaphore(value: 0)+ let result = ResultBox()+ Task { @MainActor in+ defer { semaphore.signal() }+ guard let controller, let control = controller.control, control.isConnected else {+ result.error = "guest not connected"+ return+ }+ do {+ try await control.sendPing()+ result.ok = true+ } catch {+ result.error = "\(error)"+ }+ }+ semaphore.wait()+ writeResponse(fd, ok: result.ok, error: result.error)+case "screenshot":let outputPath = json["path"] as? Stringlet semaphore = DispatchSemaphore(value: 0)diff --git a/sources/vphone-cli/VPhoneCFWInstaller.swift b/sources/vphone-cli/VPhoneCFWInstaller.swiftnew file mode 100644index 00000000..86d0cd02--- /dev/null+++ b/sources/vphone-cli/VPhoneCFWInstaller.swift@@ -0,0 +1,360 @@+import ArgumentParser+import Darwin+import FirmwarePatcher+import Foundation+import VPhoneArchive+import VPhoneCore+import VPhoneSign++/// Host-side JB system installation. The VM must be off: all writes go to its+/// mounted Disk.img, while the source IPSWs and any other VM stay untouched.+struct VPhoneCFWInstaller {+ let bundle: URL+ let resources: VPhoneResources+ let forceDSCMaxSlide: Bool++ private var executable: URL { VPhoneResources.runningExecutable() }+ private var fm: FileManager { .default }++ static func elevate(+ bundle: URL,+ resources: VPhoneResources,+ forceDSCMaxSlide: Bool,+ rootPopup: Bool,+ environment: [String: String] = [:],+ verbose: Bool = true+ ) throws -> Int32 {+ let exe = VPhoneResources.runningExecutable()+ var args = ["cfw", "install-root", bundle.path, "--resources", resources.base.path]+ if forceDSCMaxSlide { args.append("--force-dsc-maxslide") }+ if geteuid() == 0 {+ try VPhoneCFWInstaller(bundle: bundle, resources: resources,+ forceDSCMaxSlide: forceDSCMaxSlide).run()+ return 0+ }+ if rootPopup {+ var env = environment+ env["SUDO_USER"] = NSUserName()+ env["SUDO_UID"] = String(getuid())+ return try VPhoneProcessRunner.runWithAdminPrivileges(+ exe, args, env: env, echo: verbose+ )+ }+ var env = ProcessInfo.processInfo.environment+ env.merge(environment) { _, new in new }+ args.insert(contentsOf: ["-E", exe.path], at: 0)+ if env["SUDO_ASKPASS"] != nil { args.insert("-A", at: 0) }+ return try VPhoneProcessRunner.runForeground(+ URL(fileURLWithPath: "/usr/bin/sudo"), args, env: env, echo: verbose+ )+ }++ func run() throws {+ guard geteuid() == 0 else { throw ValidationError("CFW install requires administrator privileges") }+ let diskImage = bundle.appendingPathComponent("Disk.img")+ guard fm.fileExists(atPath: diskImage.path) else {+ throw ValidationError("Disk.img is missing: \(diskImage.path)")+ }+ let busy = try VPhoneProcessRunner.runCapturing(+ URL(fileURLWithPath: "/usr/sbin/lsof"), [diskImage.path]+ )+ guard busy.stdout.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {+ throw ValidationError("VM disk is in use; stop the VM before installing CFW")+ }+ let capacity = try bundle.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])+ .volumeAvailableCapacityForImportantUsage ?? 0+ guard capacity > 100 * 1024 * 1024 * 1024 else {+ throw ValidationError("Less than 100 GiB available; CFW install stopped before mounting")+ }++ let attached = try tool("/usr/bin/hdiutil", [+ "attach", "-nomount", "-imagekey", "diskimage-class=CRawDiskImage", diskImage.path+ ])+ guard let baseDisk = attached.split(whereSeparator: \.isNewline).first?+ .split(whereSeparator: \.isWhitespace).first.map(String.init),+ baseDisk.hasPrefix("/dev/disk") else {+ throw ValidationError("hdiutil attached no disk device")+ }+ defer { _ = try? tool("/usr/bin/hdiutil", ["detach", baseDisk], quiet: true) }++ let info = try tool("/usr/sbin/diskutil", ["info", "-plist", "\(baseDisk)s1"], quiet: true)+ guard let plist = try PropertyListSerialization.propertyList(+ from: Data(info.utf8), format: nil) as? [String: Any],+ let container = plist["APFSContainerReference"] as? String,+ container.hasPrefix("disk") else {+ throw ValidationError("Could not resolve the APFS container for \(baseDisk)")+ }+ let work = bundle.appendingPathComponent(".cfw-native-\(UUID().uuidString)")+ let system = work.appendingPathComponent("system")+ let data = work.appendingPathComponent("data")+ try fm.createDirectory(at: system, withIntermediateDirectories: true)+ try fm.createDirectory(at: data, withIntermediateDirectories: true)+ defer {+ _ = try? tool("/sbin/umount", [data.path], quiet: true)+ _ = try? tool("/sbin/umount", [system.path], quiet: true)+ try? fm.removeItem(at: work)+ }+ try tool("/sbin/mount_apfs", ["-o", "rw", "/dev/\(container)s1", system.path])+ try tool("/sbin/mount_apfs", ["-o", "rw", "/dev/\(container)s3", data.path])+ print("[*] JB system install: \(bundle.lastPathComponent)")+ try installMounted(system: system, data: data, work: work)+ _ = try tool("/sbin/umount", [data.path])+ _ = try tool("/sbin/umount", [system.path])+ _ = try tool("/usr/bin/hdiutil", ["detach", baseDisk], quiet: true)+ try fm.removeItem(at: work)+ try VPhoneAPFSSnapshot.rename(imageAt: diskImage)+ if let uid = ProcessInfo.processInfo.environment["SUDO_UID"].flatMap(UInt32.init) {+ let signed = bundle.appendingPathComponent(".vphoned.signed")+ if fm.fileExists(atPath: signed.path) { _ = chown(signed.path, uid, gid_t.max) }+ }+ print("[+] JB system install complete; vphoned is installed, no package bootstrap was staged")+ }++ private func installMounted(system: URL, data: URL, work: URL) throws {+ guard let restore = try fm.contentsOfDirectory(at: bundle, includingPropertiesForKeys: [.isDirectoryKey])+ .first(where: { $0.lastPathComponent.contains("Restore") &&+ fm.fileExists(atPath: $0.appendingPathComponent("iPhone-BuildManifest.plist").path) }) else {+ throw ValidationError("No prepared iPhone restore tree exists in \(bundle.path)")+ }+ try installCryptexes(restore: restore, system: system, work: work)+ let version = try productVersion(system: system)+ let dsc = system.appendingPathComponent("System/Cryptexes/OS/System/Library/Caches/com.apple.dyld")+ if version.hasPrefix("27.") {+ try patch("patch-iomfb-force-kern", [dsc.path])+ try patch("patch-dsc-maxslide", [dsc.path])+ try patch("patch-lsd-embedded-reg", [dsc.path])+ try patch("patch-xpc-lwcr", [dsc.path])+ try patch("patch-lockdown-mode", [dsc.path])+ } else if version.hasPrefix("26.0") || version.hasPrefix("18.") {+ try patch("patch-iomfb-swapend", [dsc.path, "--target-size", "0x560"])+ } else if forceDSCMaxSlide {+ try patch("patch-dsc-maxslide", [dsc.path, "--force"])+ }+ try patchMachO(system: system, work: work,+ path: "usr/libexec/seputil", verb: "patch-seputil", identifier: "com.apple.seputil")+ if version.hasPrefix("27.") {+ try patchMachO(system: system, work: work,+ path: "usr/libexec/diskimagesiod", verb: "patch-diskimagesiod", preserveEntitlements: true)+ }+ try renameGigalocker(data: data)+ try VPhoneArchiveExtractor.extract(resources.gpuDriverArchive, into: system,+ options: .ontoGuestVolume)+ let gpu = system.appendingPathComponent(+ "System/Library/Extensions/AppleParavirtGPUMetalIOGPUFamily.bundle")+ try tool("/usr/sbin/chown", ["-R", "0:0", gpu.path])+ for file in [gpu, gpu.appendingPathComponent("AppleParavirtGPUMetalIOGPUFamily"),+ gpu.appendingPathComponent("libAppleParavirtCompilerPluginIOGPUFamily.dylib"),+ gpu.appendingPathComponent("_CodeSignature")] {+ try fm.setAttributes([.posixPermissions: NSNumber(value: 0o755)], ofItemAtPath: file.path)+ }+ for file in [gpu.appendingPathComponent("Info.plist"),+ gpu.appendingPathComponent("_CodeSignature/CodeResources")] {+ try fm.setAttributes([.posixPermissions: NSNumber(value: 0o644)], ofItemAtPath: file.path)+ }+ try patchMachO(system: system, work: work,+ path: "usr/libexec/launchd_cache_loader", verb: "patch-launchd-cache-loader",+ identifier: "com.apple.launchd_cache_loader")+ try patchMachO(system: system, work: work,+ path: "usr/libexec/mobileactivationd", verb: "patch-mobileactivationd")+ try installVphoned(system: system, work: work)+ try patchMachO(system: system, work: work,+ path: "sbin/launchd", verb: "patch-launchd-jetsam", preserveEntitlements: true)+ try patchDebugserver(system: system, work: work)+ if version.hasPrefix("27.") { try patchCampo(system: system, work: work) }+ }++ private func installCryptexes(restore: URL, system: URL, work: URL) throws {+ let os = system.appendingPathComponent("System/Cryptexes/OS")+ let app = system.appendingPathComponent("System/Cryptexes/App")+ if !((try? fm.contentsOfDirectory(atPath: os.path))?.isEmpty == false &&+ (try? fm.contentsOfDirectory(atPath: app.path))?.isEmpty == false) {+ let paths = try CFWDaemons.cryptexPaths(+ buildManifest: restore.appendingPathComponent("iPhone-BuildManifest.plist"))+ let encrypted = restore.appendingPathComponent(paths.systemOS)+ let plain = work.appendingPathComponent("SystemOS.dmg")+ let key = try vphoneRunBlocking { try await VPhoneAEA.symmetricKey(of: encrypted) }+ try tool("/usr/bin/aea", ["decrypt", "-i", encrypted.path,+ "-o", plain.path, "-key-value", key], quiet: true)+ let osMount = work.appendingPathComponent("mnt-os")+ let appMount = work.appendingPathComponent("mnt-app")+ try fm.createDirectory(at: osMount, withIntermediateDirectories: true)+ try fm.createDirectory(at: appMount, withIntermediateDirectories: true)+ try tool("/usr/bin/hdiutil", ["attach", "-mountpoint", osMount.path,+ plain.path, "-nobrowse", "-owners", "off"], quiet: true)+ defer { _ = try? tool("/usr/bin/hdiutil", ["detach", "-force", osMount.path], quiet: true) }+ try tool("/usr/bin/hdiutil", ["attach", "-mountpoint", appMount.path,+ restore.appendingPathComponent(paths.appOS).path, "-nobrowse", "-owners", "off"], quiet: true)+ defer { _ = try? tool("/usr/bin/hdiutil", ["detach", "-force", appMount.path], quiet: true) }+ for (source, destination) in [(osMount, os), (appMount, app)] {+ // The restored rootfs has dangling Cryptex symlinks. fileExists+ // follows those links and reports false until Preboot is populated.+ if fm.fileExists(atPath: destination.path) ||+ (try? fm.destinationOfSymbolicLink(atPath: destination.path)) != nil {+ try fm.removeItem(at: destination)+ }+ try fm.createDirectory(at: destination, withIntermediateDirectories: true)+ try tool("/bin/cp", ["-R", source.appendingPathComponent(".").path, destination.path])+ }+ }+ try symlink("../../../System/Cryptexes/OS/System/Library/Caches/com.apple.dyld",+ at: system.appendingPathComponent("System/Library/Caches/com.apple.dyld"))+ try symlink("../../../../System/Cryptexes/OS/System/DriverKit/System/Library/dyld",+ at: system.appendingPathComponent("System/DriverKit/System/Library/dyld"))+ }++ private func installVphoned(system: URL, work: URL) throws {+ let vphoned = try VPhoneGuestBinaries.resolve("vphoned")+ let staged = work.appendingPathComponent("vphoned")+ try fm.copyItem(at: vphoned, to: staged)+ let entitlementsURL = resources.scriptsDir.appendingPathComponent("vphoned/entitlements.plist")+ let entitlements = try Data(contentsOf: entitlementsURL, options: .mappedIfSafe)+ try VPhoneSigner.sign(fileAt: staged,+ options: .init(entitlements: entitlements, mergesExisting: true))+ try replace(staged, at: system.appendingPathComponent("usr/bin/vphoned"), mode: 0o755)+ let signed = bundle.appendingPathComponent(".vphoned.signed")+ if fm.fileExists(atPath: signed.path) { try fm.removeItem(at: signed) }+ try fm.copyItem(at: staged, to: signed)+ let daemon = resources.scriptsDir.appendingPathComponent("vphoned/vphoned.plist")+ try replace(daemon, at: system.appendingPathComponent(+ "System/Library/LaunchDaemons/vphoned.plist"), mode: 0o644)+ let launchd = system.appendingPathComponent("System/Library/xpc/launchd.plist")+ let backup = launchd.appendingPathExtension("bak")+ if !fm.fileExists(atPath: backup.path) { try fm.copyItem(at: launchd, to: backup) }+ let temp = work.appendingPathComponent("launchd.plist")+ try fm.copyItem(at: backup, to: temp)+ try CFWDaemons.injectDaemon(into: temp, name: "vphoned", from: daemon)+ try replace(temp, at: launchd, mode: 0o644)+ }++ private func patchMachO(system: URL, work: URL, path: String, verb: String,+ identifier: String? = nil, preserveEntitlements: Bool = false) throws {+ let target = system.appendingPathComponent(path)+ let backup = target.appendingPathExtension("bak")+ if !fm.fileExists(atPath: backup.path) { try fm.copyItem(at: target, to: backup) }+ let staged = work.appendingPathComponent(target.lastPathComponent)+ if fm.fileExists(atPath: staged.path) { try fm.removeItem(at: staged) }+ try fm.copyItem(at: backup, to: staged)+ let entitlements = preserveEntitlements+ ? try VPhoneSigner.entitlements(ofFileAt: backup).first(where: { !$0.isEmpty })+ : nil+ try patch(verb, [staged.path])+ try VPhoneSigner.sign(fileAt: staged,+ options: .init(identifier: identifier, entitlements: entitlements, mergesExisting: true))+ try replace(staged, at: target, mode: 0o755)+ }++ private func patchDebugserver(system: URL, work: URL) throws {+ let target = system.appendingPathComponent("usr/libexec/debugserver")+ guard fm.fileExists(atPath: target.path) else {+ print("[!] debugserver absent; entitlement patch skipped")+ return+ }+ guard let source = try VPhoneSigner.entitlements(ofFileAt: target)+ .first(where: { !$0.isEmpty }),+ var plist = try PropertyListSerialization.propertyList(+ from: source, format: nil) as? [String: Any] else {+ print("[!] debugserver has no readable entitlements; patch skipped")+ return+ }+ plist.removeValue(forKey: "seatbelt-profiles")+ plist["task_for_pid-allow"] = true+ let data = try PropertyListSerialization.data(fromPropertyList: plist,+ format: .xml, options: 0)+ let staged = work.appendingPathComponent("debugserver")+ try fm.copyItem(at: target, to: staged)+ try VPhoneSigner.sign(fileAt: staged,+ options: .init(entitlements: data, mergesExisting: true))+ try replace(staged, at: target, mode: 0o755)+ }++ private func patchCampo(system: URL, work: URL) throws {+ let target = system.appendingPathComponent("Applications/Campo.app/Campo")+ guard fm.fileExists(atPath: target.path) else {+ print("[!] Campo absent; entitlement patch skipped")+ return+ }+ guard let source = try VPhoneSigner.entitlements(ofFileAt: target)+ .first(where: { !$0.isEmpty }) else {+ print("[!] Campo has no readable entitlements; patch skipped")+ return+ }+ let ent = work.appendingPathComponent("Campo.entitlements")+ try source.write(to: ent)+ try patch("patch-campo-entitlements", [ent.path])+ let staged = work.appendingPathComponent("Campo")+ try fm.copyItem(at: target, to: staged)+ try VPhoneSigner.sign(fileAt: staged,+ options: .init(entitlements: try Data(contentsOf: ent, options: .mappedIfSafe), mergesExisting: true))+ try replace(staged, at: target, mode: 0o755)+ }++ private func renameGigalocker(data: URL) throws {+ let files = try fm.contentsOfDirectory(at: data, includingPropertiesForKeys: nil)+ for source in files where source.pathExtension == "gl" {+ let destination = data.appendingPathComponent("AA.gl")+ if source == destination { continue }+ if fm.fileExists(atPath: destination.path) { try fm.removeItem(at: destination) }+ try fm.moveItem(at: source, to: destination)+ }+ }++ private func productVersion(system: URL) throws -> String {+ let plist = system.appendingPathComponent(+ "System/Library/CoreServices/SystemVersion.plist")+ guard let value = try PropertyListSerialization.propertyList(+ from: Data(contentsOf: plist, options: .mappedIfSafe), format: nil) as? [String: Any],+ let version = value["ProductVersion"] as? String else {+ throw ValidationError("SystemVersion.plist has no ProductVersion")+ }+ return version+ }++ private func symlink(_ destination: String, at path: URL) throws {+ if fm.fileExists(atPath: path.path) || (try? path.resourceValues(forKeys: [.isSymbolicLinkKey]))?.isSymbolicLink == true {+ try fm.removeItem(at: path)+ }+ try fm.createSymbolicLink(atPath: path.path, withDestinationPath: destination)+ }++ private func replace(_ source: URL, at destination: URL, mode: Int) throws {+ try tool("/bin/cp", ["-f", source.path, destination.path], quiet: true)+ try fm.setAttributes([.posixPermissions: NSNumber(value: mode)], ofItemAtPath: destination.path)+ }++ @discardableResult+ private func patch(_ verb: String, _ arguments: [String]) throws -> String {+ try tool(executable.path, ["cfw", verb] + arguments)+ }++ @discardableResult+ private func tool(_ path: String, _ arguments: [String], quiet: Bool = false) throws -> String {+ let result = try VPhoneProcessRunner.runCapturing(URL(fileURLWithPath: path), arguments)+ if !quiet {+ if !result.stdout.isEmpty { print(result.stdout, terminator: "") }+ if !result.stderr.isEmpty { fputs(result.stderr, stderr) }+ }+ guard result.succeeded else {+ throw ValidationError("\(URL(fileURLWithPath: path).lastPathComponent) failed (\(result.exitCode)): \(result.stderr)")+ }+ return result.stdout+ }+}++struct VPhoneCFWInstallRootCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "install-root", abstract: "Internal privileged JB disk install",+ shouldDisplay: false+ )++ @Argument(help: "VM bundle path") var bundle: String+ @Option(help: "Resource base") var resources: String+ @Flag(name: .customLong("force-dsc-maxslide")) var forceDSCMaxSlide = false++ func run() throws {+ try VPhoneCFWInstaller(+ bundle: URL(fileURLWithPath: bundle),+ resources: VPhoneResources(base: URL(fileURLWithPath: resources)),+ forceDSCMaxSlide: forceDSCMaxSlide+ ).run()+ }+}diff --git a/sources/vphone-cli/VPhoneCLI.swift b/sources/vphone-cli/VPhoneCLI.swiftindex 41d7dc32..38d03426 100644--- a/sources/vphone-cli/VPhoneCLI.swift+++ b/sources/vphone-cli/VPhoneCLI.swift@@ -11,6 +11,7 @@ struct VPhoneCLI: ParsableCommand {VPhoneBootCLI.self, PatchFirmwareCLI.self, PatchComponentCLI.self, VPhoneVMCommand.self,VPhoneFWCommand.self, VPhoneRestoreCommand.self, VPhoneRecoveryProbeCommand.self,VPhoneCFWCommand.self,+ VPhoneHostCommand.self,VPhoneSignCommand.self, VPhoneDumpEntitlementsCommand.self,],defaultSubcommand: VPhoneBootCLI.selfdiff --git a/sources/vphone-cli/VPhoneCreateOptions.swift b/sources/vphone-cli/VPhoneCreateOptions.swiftindex 81a8b524..5ff555d6 100644--- a/sources/vphone-cli/VPhoneCreateOptions.swift+++ b/sources/vphone-cli/VPhoneCreateOptions.swift@@ -11,7 +11,6 @@ extension VPhoneCreateOrchestrator {public var forceDSCMaxSlide: Boolpublic var enableFrida: Boolpublic var rootPopup: Bool- public var interactive: Boolpublic var cpuCount: UIntpublic var memoryMB: UInt64public var diskSizeGB: UInt64@@ -26,7 +25,6 @@ extension VPhoneCreateOrchestrator {forceDSCMaxSlide: Bool = false,enableFrida: Bool = false,rootPopup: Bool = false,- interactive: Bool = false,cpuCount: UInt = 8,memoryMB: UInt64 = 8192,diskSizeGB: UInt64 = 64,@@ -40,7 +38,6 @@ extension VPhoneCreateOrchestrator {self.forceDSCMaxSlide = forceDSCMaxSlideself.enableFrida = enableFridaself.rootPopup = rootPopup- self.interactive = interactiveself.cpuCount = cpuCountself.memoryMB = memoryMBself.diskSizeGB = diskSizeGBdiff --git a/sources/vphone-cli/VPhoneCreateOrchestrator.swift b/sources/vphone-cli/VPhoneCreateOrchestrator.swiftindex 2a5c8b88..89252317 100644--- a/sources/vphone-cli/VPhoneCreateOrchestrator.swift+++ b/sources/vphone-cli/VPhoneCreateOrchestrator.swift@@ -6,9 +6,7 @@ import VPhoneRestore// MARK: - VPhoneCreateError-/// Failure points across the native `vm create` pipeline — the `die()` call-/// sites of `scripts/setup_machine.sh`'s `main()` / `load_device_identity` /-/// `wait_for_recovery` / `wait_for_first_boot_prompt_auto` / `run_boot_analysis`.+/// Failure points across the native `vm create` pipeline.private enum VPhoneCreateError: Error, CustomStringConvertible {case nestedVirtualizationcase identityTimedOut(URL)@@ -20,8 +18,6 @@ private enum VPhoneCreateError: Error, CustomStringConvertible {case restoreUpdateFailed(String)case cfwInstallFailed(Int32)case sudoPasswordRequired- case firstBootPanic- case firstBootExitedBeforePrompt(Int32)case bootAnalysisPaniccase bootAnalysisExited(Int32)case bootAnalysisTimeout@@ -52,16 +48,12 @@ private enum VPhoneCreateError: Error, CustomStringConvertible {case .sudoPasswordRequired:"Custom firmware installation requires root, but no sudo password is available. "+ "Pass --sudo-password, or run vm create in an interactive terminal."- case .firstBootPanic:- "First boot panicked before the setup commands could run."- case let .firstBootExitedBeforePrompt(code):- "First boot exited before the setup commands could run (exit code \(code))."case .bootAnalysisPanic:"Boot analysis failed: the guest panicked."case let .bootAnalysisExited(code):- "Boot analysis ended before the guest finished booting (exit code \(code))."+ "Boot check ended before vphoned connected (exit code \(code))."case .bootAnalysisTimeout:- "Boot analysis timed out."+ "Boot check timed out waiting for vphoned."}}}@@ -72,9 +64,8 @@ extension VPhoneCreateError: LocalizedError {// MARK: - VPhoneCreateOrchestrator-/// Native port of `scripts/setup_machine.sh`'s `main()` — runs the full-/// `vm create` pipeline (prepare → patch → restore → CFW → first boot → boot-/// analysis) with no `make`/`setup_machine.sh` shell-out.+/// Native `vm create` pipeline: prepare, patch, restore, install JB system+/// files, and verify that the guest daemon connects on first boot.////// Lives in the EXECUTABLE target rather than VPhoneCore because it composes/// `FirmwarePatcher.FirmwarePipeline`, and `FirmwarePatcher` already depends on@@ -86,8 +77,8 @@ extension VPhoneCreateError: LocalizedError {public struct VPhoneCreateOrchestrator {private let library: VPhoneLibraryprivate let resources: VPhoneResources- /// How to start the guest. A create boots it four times — DFU, first boot,- /// boot analysis, foreground — so the decision about whether an AMFI window+ /// How to start the guest. A create boots in DFU and once for verification,+ /// so the decision about whether an AMFI window/// is needed is taken once, here, rather than probing amfid (and possibly/// prompting for sudo) before each one.private let launcher: VPhoneGuestLaunchPlanner@@ -137,9 +128,12 @@ public struct VPhoneCreateOrchestrator {print("[!] --sudo-password failed validation; will still try at CFW-install time")}} else if !options.rootPopup && isatty(FileHandle.standardInput.fileDescriptor) == 0 {- // No password, no popup, no terminal for sudo to prompt on — fail- // before the long download/restore, not at the eventual sudo prompt.- throw VPhoneCreateError.sudoPasswordRequired+ // A preconfigured passwordless sudo is valid in a non-interactive+ // session. Probe it now so a failure happens before the restore.+ let sudo = try? VPhoneProcessRunner.runCapturing(+ URL(fileURLWithPath: "/usr/bin/sudo"), ["-n", "/usr/bin/true"]+ )+ if sudo?.succeeded != true { throw VPhoneCreateError.sudoPasswordRequired }}print("\n=== vm new ===")@@ -175,14 +169,10 @@ public struct VPhoneCreateOrchestrator {print("[+] Removed built firmware \(removed)/ to save space (--keep-artifacts to keep)")}- print("\n=== First boot ===")- try runFirstBoot(options: options, bundleURL: bundleURL)-- print("\n=== Done ===")- print("Setup completed.")-- print("\n=== Boot analysis ===")+ print("\n=== First boot check ===")try runBootAnalysis(bundleURL: bundleURL, verbosity: v)+ print("\n=== Done ===")+ print("JB VM created; vphoned connected. Guest user environment is untouched.")}// MARK: - trace@@ -429,65 +419,14 @@ public struct VPhoneCreateOrchestrator {private func runCFWInstall(options: Options, bundleURL: URL, sudoEnvExtras: [String: String]) throws {let v = options.verbosity- try FileManager.default.createDirectory(at: resources.ipswCacheDir, withIntermediateDirectories: true)- try FileManager.default.createDirectory(at: resources.sealVolumeCacheDir, withIntermediateDirectories: true)- // No VPHONE_PYTHON: the CFW installers and cfw-kit run `vphone-cli cfw- // <verb>` now, so nothing under this script reads a python. Asking for- // one here would only force a venv bootstrap nobody uses.- var scriptEnv: [String: String] = [- // What replaced it. The script re-execs under sudo, so it cannot- // work out where we live from its own path in the bundled case —- // same reason `cfw install` passes it (VPhoneRestoreCLI). Without- // it the script falls back to guessing, which works in a dev tree- // and in the .app but is a guess either way.- "VPHONE_CLI_BIN": VPhoneResources.runningExecutable().path,- "IPSW_DIR": resources.ipswCacheDir.path,- "VPHONE_SEAL_DIR": resources.sealVolumeCacheDir.path,- ]- if options.forceDSCMaxSlide { scriptEnv["FORCE_DSC_MAXSLIDE"] = "1" }- if options.enableFrida { scriptEnv["VPHONE_FRIDA"] = "1" }-- let args = [resources.cfwInstallHostScript.path, bundleURL.path]// --sudo-password (askpass) wins over --root-popup.let usePopup = options.rootPopup && sudoEnvExtras["SUDO_ASKPASS"] == nil- let code: Int32- if usePopup {- // Forward SUDO_USER (sudo would set it) so the script's chown-back runs.- scriptEnv["SUDO_USER"] = NSUserName()- trace("osascript admin-privileges /bin/zsh \(args.joined(separator: " "))", v)- code = try VPhoneProcessRunner.runWithAdminPrivileges(- URL(fileURLWithPath: "/bin/zsh"),- args,- env: scriptEnv,- echo: v.showsToolDetail- )- } else {- var env = ProcessInfo.processInfo.environment- for (key, value) in scriptEnv { env[key] = value }- for (key, value) in sudoEnvExtras { env[key] = value }- let envKeys = (["VPHONE_CLI_BIN", "IPSW_DIR", "VPHONE_SEAL_DIR"] + sudoEnvExtras.keys.sorted())- .joined(separator: ", ")- trace("spawn /bin/zsh \(args.joined(separator: " ")) (env keys: \(envKeys))", v)- // With an askpass credential sudo is non-interactive → honor verbosity.- // Without one, sudo must prompt on the terminal → run as a foreground- // job so its process group owns the tty (see runForeground).- if sudoEnvExtras["SUDO_ASKPASS"] != nil {- code = try VPhoneProcessRunner.runStreaming(- URL(fileURLWithPath: "/bin/zsh"),- args,- env: env,- echo: v.showsToolDetail- )- } else {- print("[*] CFW install needs root — sudo will prompt for your macOS password.")- code = try VPhoneProcessRunner.runForeground(- URL(fileURLWithPath: "/bin/zsh"),- args,- env: env,- echo: v.showsToolDetail- )- }- }+ trace("native JB CFW install for \(bundleURL.path)", v)+ let code = try VPhoneCFWInstaller.elevate(+ bundle: bundleURL, resources: resources,+ forceDSCMaxSlide: options.forceDSCMaxSlide,+ rootPopup: usePopup, environment: sudoEnvExtras+ )guard code == 0 else { throw VPhoneCreateError.cfwInstallFailed(code) }print("[+] JB CFW installed.")if let bundle = try? VPhoneBundle.load(at: bundleURL),@@ -496,58 +435,7 @@ public struct VPhoneCreateOrchestrator {}}- // MARK: - first boot-- private func runFirstBoot(options: Options, bundleURL: URL) throws {- let v = options.verbosity- let configURL = bundleURL.appendingPathComponent("config.plist")- var args = ["--config", configURL.path]- // --interactive keeps the window: it is the operator's only boot-progress cue.- if !options.interactive { args.append("--headless") }-- if options.interactive {- print("[*] press Enter to start VM, after the VM has finished booting, press Enter again to finish last stage")- _ = readLine()- } else {- print("[*] non-interactive (default): auto-starting first boot")- }-- let (bootExe, bootArgs) = launcher.plan(args)- trace("spawn \(bootExe.path) \(bootArgs.joined(separator: " ")) (guest serial: off)", v)- let boot = VPhoneManagedProcess(bootExe, bootArgs, cwd: bundleURL, echo: false)- try boot.start()- defer { boot.terminate() }-- if options.interactive {- print("[*] Press Enter once the VM is fully booted")- _ = readLine()- } else {- let outcome = boot.waitForOutput(matching: VPhoneBootPatterns.panicOrPromptRegex, timeout: 60)- trace("first-boot managed-process outcome: \(outcome)", v)- switch outcome {- case .matched:- if case .matched = boot.waitForOutput(matching: "(?i:\(VPhoneBootPatterns.panicRegex))", timeout: 0) {- print("[-] Panic detected while waiting for first-boot shell prompt.")- throw VPhoneCreateError.firstBootPanic- }- print("[+] First-boot shell prompt detected")- case let .exited(code):- print("[-] make boot exited before first-boot command injection.")- throw VPhoneCreateError.firstBootExitedBeforePrompt(code)- case .timedOut:- print("[!] Shell prompt not detected within 60s; fallback to timed continue.")- }- }-- for cmd in VPhoneBootPatterns.firstBootCommands {- boot.send(cmd)- }-- print("[*] Commands sent. Waiting for VM shutdown...")- _ = boot.waitUntilExit()- }-- // MARK: - boot analysis+ // MARK: - first boot checkprivate func runBootAnalysis(bundleURL: URL, verbosity v: VPhoneVerbosity) throws {let configURL = bundleURL.appendingPathComponent("config.plist")@@ -557,15 +445,15 @@ public struct VPhoneCreateOrchestrator {try vm.start()defer { vm.terminate() }- let outcome = vm.waitForOutput(matching: VPhoneBootPatterns.panicOrPromptRegex, timeout: 300)- trace("boot-analysis managed-process outcome: \(outcome)", v)+ let outcome = vm.waitForOutput(matching: VPhoneBootPatterns.panicOrVphonedRegex, timeout: 300)+ trace("first-boot managed-process outcome: \(outcome)", v)switch outcome {case .matched:if case .matched = vm.waitForOutput(matching: "(?i:\(VPhoneBootPatterns.panicRegex))", timeout: 0) {print("[-] Boot analysis: panic detected, stopping VM.")throw VPhoneCreateError.bootAnalysisPanic}- print("[+] Boot analysis: bash prompt detected, boot success.")+ print("[+] First boot: vphoned connected.")case let .exited(code):print("[-] Boot analysis: VM process exited before success marker.")throw VPhoneCreateError.bootAnalysisExited(code)diff --git a/sources/vphone-cli/VPhoneHostPreflight.swift b/sources/vphone-cli/VPhoneHostPreflight.swiftnew file mode 100644index 00000000..8a28bbb0--- /dev/null+++ b/sources/vphone-cli/VPhoneHostPreflight.swift@@ -0,0 +1,39 @@+import ArgumentParser+import Foundation+import VPhoneCore++/// The launch gate shared by direct boot and VM-library boot. It checks the+/// entitled companion itself, so an unentitled CLI starting successfully does+/// not give a false positive.+enum VPhoneHostPreflight {+ static func check() throws -> VPhoneGuestLaunchPlanner {+ let probe = try VPhoneProcessRunner.runCapturing(+ URL(fileURLWithPath: "/usr/sbin/sysctl"), ["-n", "kern.hv_vmm_present"]+ )+ if probe.succeeded,+ probe.stdout.trimmingCharacters(in: .whitespacesAndNewlines) == "1" {+ throw ValidationError("Nested virtualization is unavailable for this VM")+ }+ return try VPhoneGuestLaunchPlanner()+ }+}++struct VPhoneHostCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "host", subcommands: [VPhoneHostPreflightCommand.self]+ )+}++struct VPhoneHostPreflightCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "preflight",+ abstract: "Check whether the entitled VM binary can launch on this host"+ )++ @Flag(help: "Suppress the success message") var quiet = false++ func run() throws {+ _ = try VPhoneHostPreflight.check()+ if !quiet { print("Host preflight passed: vphone-vm can launch") }+ }+}diff --git a/sources/vphone-cli/VPhoneRestoreCLI.swift b/sources/vphone-cli/VPhoneRestoreCLI.swiftindex e05a65e2..192a912f 100644--- a/sources/vphone-cli/VPhoneRestoreCLI.swift+++ b/sources/vphone-cli/VPhoneRestoreCLI.swift@@ -129,10 +129,8 @@ struct VPhoneRestoreCommand: ParsableCommand {/// The Python bridge's `recovery-probe`, under the same name.///-/// It exists for `scripts/setup_machine.sh`, which polls for a DFU endpoint-/// from the shell and has nothing but an exit code to go on — `vm create` does-/// the same waiting in process (`VPhoneCreateOrchestrator.waitForRecovery`) and-/// does not go through here.+/// A standalone DFU probe. `vm create` does the same waiting in process+/// (`VPhoneCreateOrchestrator.waitForRecovery`).struct VPhoneRecoveryProbeCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "recovery-probe",@@ -164,6 +162,7 @@ struct VPhoneCFWCommand: ParsableCommand {abstract: "Custom-firmware install (host-mount; VM must be off; re-execs sudo)",subcommands: [VPhoneCFWInstallCommand.self,+ VPhoneCFWInstallRootCommand.self,VPhoneCFWFlipSnapshotCommand.self,// The per-step patchers the installers used to reach through// scripts/patchers/cfw.py for — see VPhoneCFWPatchCLI.swift.@@ -248,46 +247,11 @@ struct VPhoneCFWInstallCommand: ParsableCommand {let bundle = try lib.library.bundle(named: name)let resources = projectRoot.map { VPhoneResources(base: URL(fileURLWithPath: $0)) } ?? .resolve()- // Env the bundled scripts read: rides along via `sudo -E` by default;- // --root-popup forwards it inline (do shell script's bare env).- try FileManager.default.createDirectory(at: resources.ipswCacheDir, withIntermediateDirectories: true)- try FileManager.default.createDirectory(at: resources.sealVolumeCacheDir, withIntermediateDirectories: true)- var scriptEnv: [String: String] = [- // The script re-execs under sudo, so it cannot work out where we- // live from its own path in the bundled case. Tell it.- "VPHONE_CLI_BIN": VPhoneResources.runningExecutable().path,- // No VPHONE_PYTHON: the installers call `vphone-cli cfw <verb>` for- // every patch, and cfw_install_host.sh stopped reading it when the- // last Python patcher was deleted.- "IPSW_DIR": resources.ipswCacheDir.path,- "VPHONE_SEAL_DIR": resources.sealVolumeCacheDir.path,- ]- if forceDSCMaxSlide { scriptEnv["FORCE_DSC_MAXSLIDE"] = "1" }-- let args = [resources.cfwInstallHostScript.path, bundle.url.path]- let code: Int32- if rootPopup {- // Forward SUDO_USER (sudo would set it) so the script's chown-back runs.- scriptEnv["SUDO_USER"] = NSUserName()- code = try VPhoneProcessRunner.runWithAdminPrivileges(- URL(fileURLWithPath: "/bin/zsh"),- args,- env: scriptEnv,- echo: v.showsToolDetail- )- } else {- var env = ProcessInfo.processInfo.environment- for (key, value) in scriptEnv { env[key] = value }- if v.tracesInternals {- print("[trace] spawning: /bin/zsh \(args.joined(separator: " ")) (env keys: VPHONE_CLI_BIN, IPSW_DIR, VPHONE_SEAL_DIR)")- }- code = try VPhoneProcessRunner.runStreaming(- URL(fileURLWithPath: "/bin/zsh"),- args,- env: env,- echo: v.showsToolDetail- )- }+ let code = try VPhoneCFWInstaller.elevate(+ bundle: bundle.url, resources: resources,+ forceDSCMaxSlide: forceDSCMaxSlide, rootPopup: rootPopup,+ verbose: v.showsToolDetail+ )if code == 0 {if let info = try? VPhoneRestoreInfo.recordVariant("jb", toBundle: bundle), info.variant != nil {print("[cfw] recorded variant jb, device \(info.device ?? "?")")diff --git a/sources/vphone-cli/VPhoneVMCreateCLI.swift b/sources/vphone-cli/VPhoneVMCreateCLI.swiftindex 521fcb98..accb4c30 100644--- a/sources/vphone-cli/VPhoneVMCreateCLI.swift+++ b/sources/vphone-cli/VPhoneVMCreateCLI.swift@@ -24,7 +24,7 @@ struct VPhoneVMCreateCommand: ParsableCommand {var forceDSCMaxSlide = false@Flag(name: .customLong("frida"),- help: "Opt in to Frida Stalker support: install re.frida.server (latest GitHub release) + jb/exp kernel relaxations"+ help: "Opt in to Frida Stalker kernel relaxations")var frida = false@Flag(@@ -32,10 +32,9 @@ struct VPhoneVMCreateCommand: ParsableCommand {help: "Elevate the CFW host-mount via macOS's native authentication dialog (osascript) instead of a sudo prompt")var rootPopup = false- @Flag(help: "Prompt at first-boot stages instead of running non-interactively") var interactive = false@Flag(name: .customLong("keep-artifacts"),- help: "Keep intermediate build artifacts (built restore firmware, extracted base-IPSW caches, extracted CFW input dirs) instead of removing them after use. Source archives (.ipsw / .tar.zst) are always kept."+ help: "Keep the prepared restore tree after installation. Source IPSWs are always kept.")var keepArtifacts = false@Option(name: .shortAndLong, help: "Resource base override (default: inferred from the running binary path)")@@ -67,7 +66,6 @@ struct VPhoneVMCreateCommand: ParsableCommand {forceDSCMaxSlide: forceDSCMaxSlide,enableFrida: frida,rootPopup: rootPopup,- interactive: interactive,diskSizeGB: diskSize,verbosity: VPhoneVerbosity(count: verboseCount),keepArtifacts: keepArtifactsdiff --git a/sources/vphone-cli/VPhoneVMLaunchCLI.swift b/sources/vphone-cli/VPhoneVMLaunchCLI.swiftindex c8ea1b88..f9961e0c 100644--- a/sources/vphone-cli/VPhoneVMLaunchCLI.swift+++ b/sources/vphone-cli/VPhoneVMLaunchCLI.swift@@ -32,31 +32,11 @@ struct VPhoneVMLaunchCommand: ParsableCommand {// binary is unentitled and always launches.let launcher: VPhoneGuestLaunchPlannerdo {- launcher = try VPhoneGuestLaunchPlanner()+ launcher = try VPhoneHostPreflight.check()} catch {FileHandle.standardError.write(Data("error: \(error)\n".utf8))throw ExitCode(1)}- let bootBinary = launcher.guestExecutable-- // Host preflight — same gate make boot applies. Point it at the guest- // binary (VPHONE_CLI_BIN) so it checks what actually has to launch, not- // a dev .build/release path that doesn't exist inside the bundled .app.- let preflightArgs = ["--assert-bootable"]- var preflightEnv = ProcessInfo.processInfo.environment- preflightEnv["VPHONE_CLI_BIN"] = bootBinary.path- let pre = try VPhoneProcessRunner.runCapturing(- URL(fileURLWithPath: "/bin/zsh"),- [layout.preflightScript.path] + preflightArgs,- cwd: resources.base,- env: preflightEnv- )- if !pre.stdout.isEmpty { print(pre.stdout, terminator: "") }- guard pre.succeeded else {- FileHandle.standardError.write(Data(pre.stderr.utf8))- throw ExitCode(pre.exitCode == 0 ? 1 : pre.exitCode)- }-if !dfu {_ = try layout.stageVphoned(into: bundle)}diff --git a/tests/VPhoneCoreTests/APFSSnapshotTests.swift b/tests/VPhoneCoreTests/APFSSnapshotTests.swiftindex 7fcafb58..df146f8b 100644--- a/tests/VPhoneCoreTests/APFSSnapshotTests.swift+++ b/tests/VPhoneCoreTests/APFSSnapshotTests.swift@@ -148,6 +148,33 @@ struct APFSSnapshotTests {#expect(stored == computed)}+ @Test("renames snapshot records on both sides of a 64 MiB scan window")+ func renameAcrossWindows() throws {+ let name = Self.snapshotName(hash: Self.validHash)+ let first = Self.makeValidBlock(payload: name, at: 100)+ let second = Self.makeValidBlock(payload: name, at: 200)+ let url = try Self.write(first)+ defer { try? FileManager.default.removeItem(at: url) }+ let handle = try FileHandle(forWritingTo: url)+ try handle.seek(toOffset: 64 * 1024 * 1024)+ try handle.write(contentsOf: Data(second))+ try handle.close()++ let report = try VPhoneAPFSSnapshot.rename(imageAt: url, log: { _ in })+ #expect(report.blocks.map(\.blockOffset) == [0, 64 * 1024 * 1024])+ let check = try FileHandle(forReadingFrom: url)+ defer { try? check.close() }+ let firstAfter = try #require(try check.read(upToCount: VPhoneAPFSSnapshot.blockSize))+ try check.seek(toOffset: 64 * 1024 * 1024)+ let secondAfter = try #require(try check.read(upToCount: VPhoneAPFSSnapshot.blockSize))+ for (block, offset) in [(firstAfter, 100), (secondAfter, 200)] {+ #expect(String(decoding: block[offset..<offset + 20], as: UTF8.self)+ == VPhoneAPFSSnapshot.defaultNewPrefix)+ #expect(block.withUnsafeBytes { VPhoneAPFSSnapshot.checksum($0) }+ == block.withUnsafeBytes { $0.loadUnaligned(as: UInt64.self) })+ }+ }+@Test("rename is idempotent: a second pass finds nothing")func renameIsIdempotent() throws {let name = Self.snapshotName(hash: Self.validHash)diff --git a/tests/VPhoneCoreTests/CreateOrchestratorTests.swift b/tests/VPhoneCoreTests/CreateOrchestratorTests.swiftindex 0ec7e2bc..c72d6ecf 100644--- a/tests/VPhoneCoreTests/CreateOrchestratorTests.swift+++ b/tests/VPhoneCoreTests/CreateOrchestratorTests.swift@@ -4,29 +4,16 @@ import Testing// Tests for `VPhoneBootPatterns` — the pure, device-independent pieces of the// native `vm create` pipeline (`VPhoneCreateOrchestrator`, executable target).-// The orchestrator's live stages (DFU/restore/CFW/first-boot/boot-analysis)+// The orchestrator's live stages (DFU/restore/CFW/boot check)// need a real device and are NOT exercised here; see the Task 2 report.struct CreateOrchestratorTests {- // MARK: - promptRegex / panicRegex (verbatim ports of setup_machine.sh's- // BOOT_BASH_PROMPT_REGEX / BOOT_PANIC_REGEX)+ // MARK: - first-boot log markersprivate func matches(_ pattern: String, _ line: String) throws -> Bool {let re = try NSRegularExpression(pattern: pattern)return re.firstMatch(in: line, range: NSRange(line.startIndex..., in: line)) != nil}- @Test func promptRegexMatchesIosbinpackBashPrompt() throws {- #expect(try matches(VPhoneBootPatterns.promptRegex, "bash-3.2#"))- }-- @Test func promptRegexMatchesRamdiskRootPrompt() throws {- #expect(try matches(VPhoneBootPatterns.promptRegex, ":/ root#"))- }-- @Test func promptRegexDoesNotMatchOrdinaryLogLine() throws {- #expect(try !matches(VPhoneBootPatterns.promptRegex, "vphoned: connected, awaiting handshake"))- }-@Test func panicRegexMatchesKernelPanicLine() throws {#expect(try matches(VPhoneBootPatterns.panicRegex, "panic(cpu 0 caller 0xfffffff01234): test panic"))}@@ -39,16 +26,14 @@ struct CreateOrchestratorTests {#expect(try !matches(VPhoneBootPatterns.panicRegex, "vphoned: connected, awaiting handshake"))}- // MARK: - panicOrPromptRegex (mixed case-sensitivity, per- // monitor_boot_log_until's `grep -Ei` panic vs. `grep -E` prompt)-- @Test func panicOrPromptRegexMatchesPanicCaseInsensitively() throws {- #expect(try matches(VPhoneBootPatterns.panicOrPromptRegex, "PANIC(cpu 0 caller 0x0): uppercase panic"))+ @Test func bootCheckMatchesPanicCaseInsensitively() throws {+ #expect(try matches(VPhoneBootPatterns.panicOrVphonedRegex, "PANIC(cpu 0 caller 0x0): uppercase panic"))}- @Test func panicOrPromptRegexKeepsPromptCaseSensitive() throws {- #expect(try matches(VPhoneBootPatterns.panicOrPromptRegex, "bash-3.2#"))- #expect(try !matches(VPhoneBootPatterns.panicOrPromptRegex, "BASH-3.2#"))+ @Test func bootCheckRequiresVphonedConnectionInsteadOfShellPrompt() throws {+ #expect(try matches(VPhoneBootPatterns.panicOrVphonedRegex,+ "[control] connected to vphoned v1 (192.168.64.2) iOS 26.6.2"))+ #expect(try !matches(VPhoneBootPatterns.panicOrVphonedRegex, "bash-3.2#"))}// MARK: - normalizeECID (port of setup_machine.sh's normalize_ecid)@@ -82,17 +67,4 @@ struct CreateOrchestratorTests {// `sysctl -n kern.hv_vmm_present`. The nested-host check reads the int// through `sysctlbyname` now, so the parse — and its tests — are gone.- // MARK: - firstBootCommands (setup_machine.sh:344-361)-- @Test func firstBootCommandsMatchSetupMachineVerbatim() {- #expect(VPhoneBootPatterns.firstBootCommands == [- "export PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/bin/X11:/usr/games:/iosbinpack64/usr/local/sbin:/iosbinpack64/usr/local/bin:/iosbinpack64/usr/sbin:/iosbinpack64/usr/bin:/iosbinpack64/sbin:/iosbinpack64/bin'",- "cp /iosbinpack64/etc/profile /var/profile",- "cp /iosbinpack64/etc/motd /var/motd",- "mkdir -p /var/dropbear",- "dropbearkey -t rsa -f /var/dropbear/dropbear_rsa_host_key",- "dropbearkey -t ecdsa -f /var/dropbear/dropbear_ecdsa_host_key",- "shutdown -h now",- ])- }}diff --git a/tests/VPhoneCoreTests/LaunchLayoutTests.swift b/tests/VPhoneCoreTests/LaunchLayoutTests.swiftindex b7fe8aad..06d88fb4 100644--- a/tests/VPhoneCoreTests/LaunchLayoutTests.swift+++ b/tests/VPhoneCoreTests/LaunchLayoutTests.swift@@ -3,11 +3,6 @@ import Foundationimport Testingstruct LaunchLayoutTests {- @Test func resolvesArtifactPaths() {- let layout = VPhoneLaunchLayout(projectRoot: URL(fileURLWithPath: "/proj"))- #expect(layout.preflightScript.path == "/proj/scripts/boot_host_preflight.sh")- }-@Test func delegatesToResources() {let resources = VPhoneResources(base: URL(fileURLWithPath: "/proj"))let layout = VPhoneLaunchLayout(resources: resources)diff --git a/tests/VPhoneCoreTests/ResourcesTests.swift b/tests/VPhoneCoreTests/ResourcesTests.swiftindex 3223e62f..bcc4e580 100644--- a/tests/VPhoneCoreTests/ResourcesTests.swift+++ b/tests/VPhoneCoreTests/ResourcesTests.swift@@ -18,8 +18,8 @@ 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.cfwInstallHostScript.path- == "/Applications/vphone-cli.app/Contents/Resources/scripts/cfw_install_host.sh")+ #expect(r.gpuDriverArchive.path+ == "/Applications/vphone-cli.app/Contents/Resources/scripts/payloads/AppleParavirtGPUMetalIOGPUFamily.tar")}@Test func devLayoutWalksUpToProjectRoot() throws {@@ -71,7 +71,7 @@ struct ResourcesTests {let r = VPhoneResources(base: base)let rooted = [r.scriptsDir, r.gpuDriverArchive,- r.cfwInstallHostScript, r.preflightScript, r.vphoned,+ r.vphoned,]for url in rooted {#expect(url.path.hasPrefix("/x/"), "\(url.path) escapes the resource base")