Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

feat(entry): move the entitlements off the top-level binary onto vphone-vm

Lakr8e4e75c0d9fa
diff --git a/.gitignore b/.gitignore
index 0f7b5907..5938b17b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -322,7 +322,7 @@ __marimo__/
/references/
scripts/vphoned/vphoned
/cfw_input/
-sources/vphone-cli/VPhoneBuildInfo.swift
+sources/VPhoneCore/VPhoneBuildInfo.swift
setup_logs/
/testing_results
/.ida-mcp
diff --git a/Makefile b/Makefile
index 084e6530..22fe60c0 100644
--- a/Makefile
+++ b/Makefile
@@ -30,14 +30,22 @@ truthy = $(filter 1 true yes YES TRUE,$(1))
# ─── Build info ──────────────────────────────────────────────────
GIT_HASH := $(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown")
-BUILD_INFO := sources/vphone-cli/VPhoneBuildInfo.swift
+BUILD_INFO := sources/VPhoneCore/VPhoneBuildInfo.swift
# ─── Paths ────────────────────────────────────────────────────────
SCRIPTS := scripts
+# Three host binaries, and only ONE of them is entitled. vphone-cli is the
+# user-facing entry point and carries nothing, so it always launches; vphone-vm
+# holds the private virtualization keys and is what amfid can refuse;
+# vphone-letmein opens a window when it does. See sources/vphone.entitlements.
BINARY := .build/release/vphone-cli
+VM_BINARY := .build/release/vphone-vm
+LETMEIN_BINARY := .build/release/vphone-letmein
PATCHER_BINARY := .build/debug/vphone-cli
BUNDLE := .build/vphone-cli.app
BUNDLE_BIN := $(BUNDLE)/Contents/MacOS/vphone-cli
+BUNDLE_VM := $(BUNDLE)/Contents/MacOS/vphone-vm
+BUNDLE_LETMEIN := $(BUNDLE)/Contents/MacOS/vphone-letmein
INFO_PLIST := sources/Info.plist
ENTITLEMENTS := sources/vphone.entitlements
VENV := .venv
@@ -94,7 +102,7 @@ help:
@echo " make vm_list List available backups"
@echo " Options: BACKUP_INCLUDE_IPSW=1 Include *_Restore* IPSW directories in the backup"
@echo " FORCE=1 Skip overwrite prompt on restore"
- @echo " make amfidont_allow_vphone Start amfidont for the signed vphone-cli binary"
+ @echo " make letmein Open an AMFI window by hand (vphone-cli does it for you)"
@echo " make boot_host_preflight Diagnose whether host can launch signed PV=3 binary"
@echo " make boot Boot VM (reads from config.plist)"
@echo " make boot_less Boot VM in vphoned patchless compatibility mode"
@@ -231,24 +239,47 @@ $(PATCHER_BINARY): $(SWIFT_SOURCES) Package.swift
$(WRITE_BUILD_INFO)
@set -o pipefail; swift build 2>&1 | tail -5
+# One recipe produces all three host binaries — `swift build` builds every
+# target anyway. Grouped targets (`&:`) would say this more precisely but need
+# GNU Make 4.3, and macOS still ships 3.81, so the other two just depend on
+# this one.
+#
+# Only vphone-vm gets the entitlements. Signing vphone-cli with them too would
+# put us straight back where we started: the entry point itself unable to
+# launch without an AMFI bypass already in place.
$(BINARY): $(SWIFT_SOURCES) Package.swift $(ENTITLEMENTS)
@echo "=== Building vphone-cli ($(GIT_HASH)) ==="
$(WRITE_BUILD_INFO)
@set -o pipefail; swift build -c release 2>&1 | tail -5
@echo ""
- @echo "=== Signing with entitlements ==="
- codesign --force --sign - --entitlements $(ENTITLEMENTS) $@
- @echo " signed OK"
+ @echo "=== Signing ==="
+ @codesign --force --sign - --entitlements $(ENTITLEMENTS) $(VM_BINARY)
+ @codesign --force --sign - $(BINARY)
+ @codesign --force --sign - $(LETMEIN_BINARY)
+ @echo " signed: vphone-vm (entitled), vphone-cli, vphone-letmein"
+ @# An unentitled vphone-vm is worse than a broken one: it launches
+ @# perfectly, which convinces vphone-cli's AMFI probe that nothing is
+ @# wrong, and only fails later trying to create a PV=3 machine. A bare
+ @# `swift build` leaves exactly that state behind.
+ @codesign -d --entitlements - --xml $(VM_BINARY) 2>/dev/null \
+ | grep -q 'com.apple.private.virtualization' \
+ || (echo "Error: $(VM_BINARY) is not entitled after signing." >&2; exit 1)
+
+$(VM_BINARY) $(LETMEIN_BINARY): $(BINARY)
bundle: build $(INFO_PLIST)
@mkdir -p $(BUNDLE)/Contents/MacOS $(BUNDLE)/Contents/Resources
@cp -f $(BINARY) $(BUNDLE_BIN)
+ @cp -f $(VM_BINARY) $(BUNDLE_VM)
+ @cp -f $(LETMEIN_BINARY) $(BUNDLE_LETMEIN)
@cp -f $(INFO_PLIST) $(BUNDLE)/Contents/Info.plist
@cp -f sources/AppIcon.icns $(BUNDLE)/Contents/Resources/AppIcon.icns
@cp -f $(SCRIPTS)/vphoned/signcert.p12 $(BUNDLE)/Contents/Resources/signcert.p12
@cp -f $$(command -v ldid) $(BUNDLE)/Contents/MacOS/ldid
@codesign --force --sign - $(BUNDLE)/Contents/MacOS/ldid
- @codesign --force --sign - --entitlements $(ENTITLEMENTS) $(BUNDLE_BIN)
+ @codesign --force --sign - --entitlements $(ENTITLEMENTS) $(BUNDLE_VM)
+ @codesign --force --sign - $(BUNDLE_BIN)
+ @codesign --force --sign - $(BUNDLE_LETMEIN)
@echo " bundled → $(BUNDLE)"
# Cross-compile + sign vphoned daemon for iOS arm64 (requires ldid)
@@ -269,7 +300,7 @@ vphoned:
# VM management
# ═══════════════════════════════════════════════════════════════════
-.PHONY: vm_new vm_backup vm_restore vm_switch vm_list amfidont_allow_vphone boot_host_preflight boot boot_less boot_dfu boot_binary_check boot_binary_check_less
+.PHONY: vm_new vm_backup vm_restore vm_switch vm_list letmein letmein_off letmein_status boot_host_preflight boot boot_less boot_dfu boot_binary_check boot_binary_check_less
vm_new:
CPU="$(CPU)" MEMORY="$(MEMORY)" \
@@ -306,23 +337,37 @@ vm_list:
fi; \
if [ "$$found" = "0" ]; then echo " (no backups yet — run: make vm_backup NAME=<name>)"; fi
-amfidont_allow_vphone: bundle
- zsh $(SCRIPTS)/start_amfidont_for_vphone.sh
+# Normally unnecessary: vphone-cli opens and closes the window itself around
+# the launch. This is for working on vphone-vm by hand, where paying for one
+# sudo and leaving the window open beats a prompt per run. Close it with
+# `make letmein_off` — while it is open, amfid reports EVERY signature valid.
+letmein: $(LETMEIN_BINARY)
+ sudo "$(CURDIR)/$(LETMEIN_BINARY)" on
+
+letmein_off: $(LETMEIN_BINARY)
+ sudo "$(CURDIR)/$(LETMEIN_BINARY)" off
+
+letmein_status: $(LETMEIN_BINARY)
+ @sudo "$(CURDIR)/$(LETMEIN_BINARY)" status
boot_host_preflight: build
zsh $(SCRIPTS)/boot_host_preflight.sh
+# 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)
@tmp_log="$$(mktemp -t vphone-boot-preflight.XXXXXX)"; \
set +e; \
- "$(CURDIR)/$(BINARY)" --help >"$$tmp_log" 2>&1; \
+ "$(CURDIR)/$(VM_BINARY)" --help >"$$tmp_log" 2>&1; \
rc=$$?; \
set -e; \
if [ $$rc -ne 0 ]; then \
- echo "Error: signed vphone-cli failed to launch (exit $$rc)." >&2; \
+ echo "Error: signed vphone-vm failed to launch (exit $$rc)." >&2; \
echo "Check private virtualization entitlement support and ensure SIP/AMFI are disabled on the host." >&2; \
- echo "Alternatively, start the AMFI bypass helper with 'make amfidont_allow_vphone', then try again." >&2; \
+ echo "vphone-cli opens an AMFI window automatically when it starts a guest; to do it by hand:" >&2; \
+ echo " sudo $(CURDIR)/$(LETMEIN_BINARY) on" >&2; \
if [ -s "$$tmp_log" ]; then \
echo "--- vphone-cli preflight log ---" >&2; \
tail -n 40 "$$tmp_log" >&2; \
diff --git a/Package.swift b/Package.swift
index 786d89d7..b9046ed6 100644
--- a/Package.swift
+++ b/Package.swift
@@ -28,20 +28,27 @@ let package = Package(
),
.target(
name: "VPhoneCore",
+ dependencies: [
+ .product(name: "ArgumentParser", package: "swift-argument-parser"),
+ ],
path: "sources/VPhoneCore",
linkerSettings: [
.linkedFramework("Virtualization"),
]
),
- .executableTarget(
- name: "vphone-cli",
+ // Everything that touches a running guest: the machine, its window and
+ // menus, the vsock channel and the host device bridges. It is a library
+ // so the only executable holding the private virtualization
+ // entitlements can stay as small as an argument parse and an
+ // NSApplication run loop.
+ .target(
+ name: "VPhoneVMKit",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
.product(name: "Dynamic", package: "Dynamic"),
- "FirmwarePatcher",
"VPhoneCore",
],
- path: "sources/vphone-cli",
+ path: "sources/VPhoneVMKit",
linkerSettings: [
.linkedFramework("Virtualization"),
.linkedFramework("AppKit"),
@@ -50,6 +57,38 @@ let package = Package(
.linkedFramework("AVFoundation"),
]
),
+ // The only binary signed with sources/vphone.entitlements.
+ .executableTarget(
+ name: "vphone-vm",
+ dependencies: [
+ .product(name: "ArgumentParser", package: "swift-argument-parser"),
+ "VPhoneCore",
+ "VPhoneVMKit",
+ ],
+ path: "sources/vphone-vm"
+ ),
+ // The user-facing entry point. Note it depends on neither VPhoneVMKit
+ // nor any of the five frameworks above: it never builds a machine, it
+ // starts vphone-vm. Adding a dependency on the kit here would quietly
+ // undo the split, so don't.
+ .executableTarget(
+ name: "vphone-cli",
+ dependencies: [
+ .product(name: "ArgumentParser", package: "swift-argument-parser"),
+ "FirmwarePatcher",
+ "VPhoneCore",
+ ],
+ path: "sources/vphone-cli"
+ ),
+ // Opens a short AMFI window so vphone-vm can be exec'd. Plain C against
+ // the SDK; no third-party anything.
+ .executableTarget(
+ name: "vphone-letmein",
+ path: "sources/vphone-letmein",
+ linkerSettings: [
+ .linkedFramework("Foundation"),
+ ]
+ ),
.testTarget(
name: "FirmwarePatcherTests",
dependencies: ["FirmwarePatcher"],
diff --git a/scripts/boot_host_preflight.sh b/scripts/boot_host_preflight.sh
index 75cb18db..74898331 100755
--- a/scripts/boot_host_preflight.sh
+++ b/scripts/boot_host_preflight.sh
@@ -1,6 +1,6 @@
#!/bin/zsh
# boot_host_preflight.sh — Diagnose whether the host can launch the signed
-# vphone-cli binary required for PV=3 virtualization boot/DFU flows.
+# vphone-vm binary required for PV=3 virtualization boot/DFU flows.
set -euo pipefail
@@ -34,15 +34,18 @@ done
cd "$PROJECT_ROOT"
-# The caller (vphone-cli) passes VPHONE_CLI_BIN = the running binary, so we
-# check THAT — the bundled .app's Contents/MacOS/vphone-cli, not a dev
-# .build/release path that doesn't exist inside the bundle. Falls back to the
-# dev layout for standalone/`make` invocation.
-RELEASE_BIN="${VPHONE_CLI_BIN:-${PROJECT_ROOT}/.build/release/vphone-cli}"
-DEBUG_BIN="${PROJECT_ROOT}/.build/debug/vphone-cli"
+# 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-cli.debug.signed"
+TMP_SIGNED_DEBUG="${TMP_DIR}/vphone-vm.debug.signed"
cleanup() {
rm -rf "$TMP_DIR"
@@ -178,7 +181,9 @@ 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 "a path/CDHash-scoped amfidont bypass may already be active for this repo."
+echo "something is permitting this particular binary and not others."
+echo "Note vphone-letmein is not that something: it is a global switch, so while"
+echo "its window is open BOTH would exit 0."
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)"
@@ -191,7 +196,7 @@ if (( ASSERT_BOOTABLE == 1 )); then
if (( RELEASE_HELP_RC != 0 )); then
(( QUIET == 0 )) && {
echo ""
- echo "Error: signed release vphone-cli is not launchable on this host (exit $RELEASE_HELP_RC)." >&2
+ echo "Error: signed release vphone-vm is not launchable on this host (exit $RELEASE_HELP_RC)." >&2
}
exit "$RELEASE_HELP_RC"
fi
diff --git a/scripts/build.sh b/scripts/build.sh
index f5bfbf72..f4e06072 100755
--- a/scripts/build.sh
+++ b/scripts/build.sh
@@ -16,12 +16,20 @@ SCRIPT_DIR="${0:A:h}"
PROJECT_ROOT="${SCRIPT_DIR:h}"
cd "$PROJECT_ROOT"
+# Three host binaries, and only ONE of them is entitled. vphone-cli is the
+# user-facing entry point and carries nothing, so it always launches; vphone-vm
+# holds the private virtualization keys and is what amfid can refuse;
+# vphone-letmein opens a window when it does.
BINARY=".build/release/vphone-cli"
+VM_BINARY=".build/release/vphone-vm"
+LETMEIN_BINARY=".build/release/vphone-letmein"
BUNDLE=".build/vphone-cli.app"
BUNDLE_BIN="${BUNDLE}/Contents/MacOS/vphone-cli"
+BUNDLE_VM="${BUNDLE}/Contents/MacOS/vphone-vm"
+BUNDLE_LETMEIN="${BUNDLE}/Contents/MacOS/vphone-letmein"
INFO_PLIST="sources/Info.plist"
ENTITLEMENTS="sources/vphone.entitlements"
-BUILD_INFO="sources/vphone-cli/VPhoneBuildInfo.swift"
+BUILD_INFO="sources/VPhoneCore/VPhoneBuildInfo.swift"
GIT_HASH="$(git rev-parse --short HEAD 2>/dev/null || echo unknown)"
BUILD_VPHONED=1
@@ -39,20 +47,44 @@ echo '// Auto-generated — do not edit' > "$BUILD_INFO"
echo "enum VPhoneBuildInfo { static let commitHash = \"${GIT_HASH}\" }" >> "$BUILD_INFO"
swift build -c release
-echo "=== Signing with entitlements ==="
-codesign --force --sign - --entitlements "$ENTITLEMENTS" "$BINARY"
-echo " signed OK → ${BINARY}"
+# Only vphone-vm gets the entitlements. Signing vphone-cli with them too would
+# put us straight back where we started: the entry point itself unable to
+# launch without an AMFI bypass already in place.
+echo "=== Signing ==="
+codesign --force --sign - --entitlements "$ENTITLEMENTS" "$VM_BINARY"
+codesign --force --sign - "$BINARY"
+codesign --force --sign - "$LETMEIN_BINARY"
+echo " signed: vphone-vm (entitled), vphone-cli, vphone-letmein"
+
+# An unentitled vphone-vm is worse than a broken one: it launches perfectly,
+# which convinces vphone-cli's AMFI probe that nothing is wrong, and only fails
+# later when it tries to create a PV=3 machine. A bare `swift build` leaves
+# exactly that state behind. Catch it at the source.
+if ! codesign -d --entitlements - --xml "$VM_BINARY" 2>/dev/null \
+ | grep -q 'com.apple.private.virtualization'; then
+ echo "Error: ${VM_BINARY} is not entitled after signing." >&2
+ echo " It would still launch, and would still fail to create a VM." >&2
+ exit 1
+fi
# --- Bundle (.app used for GUI boot) ---
+# The .app is never opened through Launch Services — every caller runs a binary
+# inside it directly. It exists so the process that becomes an NSApplication
+# has a bundle: icon, LSUIElement, and the location usage strings. That process
+# is vphone-vm, which is why it, and not vphone-cli, is CFBundleExecutable.
echo "=== Bundling ${BUNDLE} ==="
mkdir -p "${BUNDLE}/Contents/MacOS" "${BUNDLE}/Contents/Resources"
cp -f "$BINARY" "$BUNDLE_BIN"
+cp -f "$VM_BINARY" "$BUNDLE_VM"
+cp -f "$LETMEIN_BINARY" "$BUNDLE_LETMEIN"
cp -f "$INFO_PLIST" "${BUNDLE}/Contents/Info.plist"
cp -f "sources/AppIcon.icns" "${BUNDLE}/Contents/Resources/AppIcon.icns"
cp -f "scripts/vphoned/signcert.p12" "${BUNDLE}/Contents/Resources/signcert.p12"
cp -f "$(command -v ldid)" "${BUNDLE}/Contents/MacOS/ldid"
codesign --force --sign - "${BUNDLE}/Contents/MacOS/ldid"
-codesign --force --sign - --entitlements "$ENTITLEMENTS" "$BUNDLE_BIN"
+codesign --force --sign - --entitlements "$ENTITLEMENTS" "$BUNDLE_VM"
+codesign --force --sign - "$BUNDLE_BIN"
+codesign --force --sign - "$BUNDLE_LETMEIN"
echo " bundled → ${BUNDLE}"
# --- vphoned guest daemon (cross-compiled + signed for iOS arm64) ---
@@ -99,24 +131,23 @@ cp -f requirements.txt "${RES}/requirements.txt"
# = the Tested-Environments table fw_prepare.sh reads to label Supported firmwares.
cp -f debs.list "${RES}/debs.list"
cp -f README.md "${RES}/README.md"
-# vphone-amfidont helper (allows this .app through amfid). Kept in Resources —
-# NOT MacOS — so bundle signing doesn't reject it as unsigned nested code; a
-# Homebrew `binary` symlink exposes it on PATH.
-cp -f scripts/vphone-amfidont "${RES}/vphone-amfidont"
-chmod +x "${RES}/vphone-amfidont"
-echo " bundled: scripts/ (patchers+resources), tools/, .tools/bin/{trustcache,insert_dylib}, vphoned.signed, requirements.txt, debs.list, README.md, vphone-amfidont"
+echo " bundled: scripts/ (patchers+resources), tools/, .tools/bin/{trustcache,insert_dylib}, vphoned.signed, requirements.txt, debs.list, README.md"
# Re-sign: codesign seals Contents/Resources at sign time, so the earlier
# bundle-step signature (made before these assets existed) is now stale —
# re-signing here reseals against the final Resources tree.
-echo "=== Re-signing ${BUNDLE_BIN} (resealing Resources) ==="
-codesign --force --sign - --entitlements "$ENTITLEMENTS" "$BUNDLE_BIN"
+echo "=== Re-signing bundled binaries (resealing Resources) ==="
+codesign --force --sign - --entitlements "$ENTITLEMENTS" "$BUNDLE_VM"
+codesign --force --sign - "$BUNDLE_BIN"
+codesign --force --sign - "$BUNDLE_LETMEIN"
echo " resealed OK"
echo ""
echo "=== Build complete ==="
-echo " binary : ${BINARY}"
-echo " bundle : ${BUNDLE}"
-[[ "$BUILD_VPHONED" -eq 1 ]] && echo " vphoned: .build/vphoned.signed"
+echo " vphone-cli : ${BINARY} (no entitlements — always launches)"
+echo " vphone-vm : ${VM_BINARY} (entitled — amfid may refuse it)"
+echo " vphone-letmein : ${LETMEIN_BINARY}"
+echo " bundle : ${BUNDLE}"
+[[ "$BUILD_VPHONED" -eq 1 ]] && echo " vphoned : .build/vphoned.signed"
echo ""
echo "Run: ${BINARY} --help"
diff --git a/scripts/setup_machine.sh b/scripts/setup_machine.sh
index 037e3b39..6f8d2080 100755
--- a/scripts/setup_machine.sh
+++ b/scripts/setup_machine.sh
@@ -246,7 +246,10 @@ stop_process_tree() {
}
kill_stale_vphone_procs() {
- local vphone_bin="${PROJECT_ROOT}/.build/release/vphone-cli"
+ # A stale guest is a vphone-vm, not a vphone-cli: vphone-cli only forwards a
+ # boot and exits when the guest it started does, so it is never the thing
+ # left behind holding a VM.
+ local vphone_bin="${PROJECT_ROOT}/.build/release/vphone-vm"
local -a stale_pids
stale_pids=(${(@f)$(pgrep -f "$vphone_bin" 2>/dev/null || true)})
(( ${#stale_pids[@]} == 0 )) && return
diff --git a/scripts/start_amfidont_for_vphone.sh b/scripts/start_amfidont_for_vphone.sh
deleted file mode 100755
index a811c31f..00000000
--- a/scripts/start_amfidont_for_vphone.sh
+++ /dev/null
@@ -1,25 +0,0 @@
-#!/bin/zsh
-# start_amfidont_for_vphone.sh — Start amfidont for the current vphone build.
-#
-# This is the README "Option 2" host workaround packaged for this repo:
-# - uses the project path so amfidont covers binaries relevant for the project
-# - starts amfidont in daemon mode so signed vphone-cli launches are allowlisted
-# - spoofs signatures to be recognized as apple signed for patchless variant
-
-set -euo pipefail
-
-SCRIPT_DIR="${0:A:h}"
-PROJECT_ROOT="${SCRIPT_DIR:h}"
-
-if ! command -v amfidont &>/dev/null; then
- echo "amfidont not found" >&2
- echo "Install it first: xcrun python3 -m pip install -U amfidont" >&2
- exit 1
-fi
-
-sudo xcrun amfidont daemon \
- --path "$PROJECT_ROOT" \
- --spoof-apple \
- >/dev/null 2>&1
-
-echo "amfidont started"
diff --git a/scripts/vphone-amfidont b/scripts/vphone-amfidont
deleted file mode 100755
index 1873083a..00000000
--- a/scripts/vphone-amfidont
+++ /dev/null
@@ -1,43 +0,0 @@
-#!/bin/zsh
-# vphone-amfidont — allow this vphone-cli.app through amfid via amfidont,
-# started in daemon mode with --spoof-apple. Automates the README "Option B"
-# step. amfidont: https://github.com/zqxwce/amfidont
-set -euo pipefail
-
-# The enclosing .app (this lives at vphone-cli.app/Contents/Resources/vphone-amfidont;
-# `:A` resolves a Homebrew symlink back into the bundle).
-app="${0:A:h:h:h}"
-[[ "${app:e}" == app && -x "$app/Contents/MacOS/vphone-cli" ]] \
- || { print -u2 "Error: run vphone-amfidont from inside vphone-cli.app."; exit 1 }
-
-# Ensure amfidont is installed.
-if ! command -v amfidont >/dev/null; then
- printf "amfidont is not installed. Install it via pip now? [y/N] "
- read -r ans || ans=n
- [[ "$ans" == [yY]* ]] || { print "Cancelled."; exit 1 }
- xcrun python3 -m pip install -U amfidont
- command -v amfidont >/dev/null \
- || { print -u2 "Error: amfidont is installed but not available in this shell. Open a new shell and retry."; exit 1 }
-fi
-# Absolute path: sudo's secure_path won't find a pip-user install by name.
-bin="$(command -v amfidont)"
-
-# Is amfidont already running? Only one can attach to amfid at a time. Check
-# cheaply without root first; its args (and /var/root config) need root, so
-# escalate to a single sudo ONLY when something is actually running.
-raw="$(ps -ax -o pid=,command= | grep '[a]mfidont' | grep -v vphone-amfidont | awk '{print $1}' || true)"
-if [[ -n "${raw//[[:space:]]/}" ]]; then
- pids=(${(f)raw})
- print "amfidont is already running — checking coverage (needs sudo)…"
- info="$(sudo sh -c "ps -o command= -p ${(j:,:)pids} 2>/dev/null; cat /var/root/.amfidont/paths 2>/dev/null" || true)"
- info+=$'\n'"$(cat ~/.amfidont/paths 2>/dev/null || true)"
- # Covered if this .app's path is allowed, or if it's running with --allow-all.
- if print -r -- "$info" | grep -Fq -- "$app" || print -r -- "$info" | grep -Fq -- "--allow-all"; then
- print "amfidont is already running and allows this app — nothing to do."
- exit 0
- fi
- print -u2 "amfidont is already running but does not allow this app. Stop amfidont, then run vphone-amfidont again."
- exit 1
-fi
-
-exec sudo "$bin" daemon --spoof-apple --path "$app"
diff --git a/sources/Info.plist b/sources/Info.plist
index 4d659dd4..1aed738d 100644
--- a/sources/Info.plist
+++ b/sources/Info.plist
@@ -4,8 +4,13 @@
<dict>
<key>CFBundleIdentifier</key>
<string>com.vphone.cli</string>
+ <!-- vphone-vm, not vphone-cli: this bundle exists to give the process that
+ becomes an NSApplication its icon, LSUIElement and the location usage
+ strings below, and that process is vphone-vm. vphone-cli ships in the
+ same Contents/MacOS and is run directly; nothing opens this .app
+ through Launch Services. -->
<key>CFBundleExecutable</key>
- <string>vphone-cli</string>
+ <string>vphone-vm</string>
<key>CFBundleName</key>
<string>vphone-cli</string>
<key>CFBundlePackageType</key>
diff --git a/sources/VPhoneCore/VPhoneBootCLI.swift b/sources/VPhoneCore/VPhoneBootCLI.swift
new file mode 100644
index 00000000..5e902bc0
--- /dev/null
+++ b/sources/VPhoneCore/VPhoneBootCLI.swift
@@ -0,0 +1,143 @@
+import ArgumentParser
+import Foundation
+
+// MARK: - VPhoneVariant
+
+/// Which firmware variant a guest is running.
+///
+/// This used to be nested inside `VPhoneVirtualMachine`, which put it on the
+/// far side of the Virtualization framework. It is a five-case string enum with
+/// no VM in it, and both binaries need it — `vphone-cli` to accept `--variant`,
+/// `vphone-vm` to configure the machine — so it belongs down here. The kit
+/// keeps a `VPhoneVirtualMachine.Variant` typealias so existing call sites read
+/// the same as before.
+public enum VPhoneVariant: String, Sendable, CaseIterable, ExpressibleByArgument {
+ case less
+ case regular
+ case dev
+ case jb
+ case exp
+}
+
+// MARK: - VPhoneBootCLI
+
+/// The options for booting a guest.
+///
+/// Both binaries parse this same declaration. `vphone-vm` runs it: it builds
+/// the machine and becomes the NSApplication. `vphone-cli` only *forwards* it,
+/// re-rendering itself through `bootArguments` and spawning `vphone-vm`.
+///
+/// Keeping one declaration is what makes the two agree about what `--dfu` or
+/// `--variant jb` mean, and it means `vphone-cli boot --help` and
+/// `vphone-vm --help` cannot drift apart.
+///
+/// Note it has no `run()` that boots. `vphone-cli`'s entry point recognises
+/// this command type and spawns instead, so `run()` here would only ever be a
+/// trap for whoever calls it directly.
+public struct VPhoneBootCLI: ParsableCommand {
+ public static let configuration = CommandConfiguration(
+ commandName: "boot",
+ abstract: "Boot a virtual iPhone (PV=3)",
+ discussion: """
+ Creates a Virtualization.framework VM with platform version 3 (vphone)
+ and boots it from a manifest plist that describes all paths and hardware.
+
+ The VM itself runs in the companion `vphone-vm` binary, which is the only
+ one signed with the private virtualization entitlements. `vphone-cli`
+ carries none, so it launches normally and starts `vphone-vm` for you.
+
+ Requires:
+ - macOS 15+ (Sequoia or later)
+ - SIP/AMFI disabled
+
+ Example:
+ vphone-cli --config ./config.plist
+ """
+ )
+
+ @Option(
+ name: .shortAndLong,
+ help: "Path to VM manifest plist (config.plist). Required.",
+ transform: URL.init(fileURLWithPath:)
+ )
+ public var config: URL
+
+ @Flag(name: .shortAndLong, help: "Boot into DFU mode")
+ public var dfu: Bool = false
+
+ @Flag(name: .customLong("headless"), help: "Boot without a VM window or menu bar")
+ public var headless: Bool = false
+
+ @Option(help: "Kernel GDB debug stub port on host (omit for system-assigned port; valid: 6000...65535)")
+ public var kernelDebugPort: Int?
+
+ @Option(help: "Path to signed vphoned binary for guest auto-update")
+ public var vphonedBin: String = ".vphoned.signed"
+
+ @Option(name: [.customShort("V"), .long], help: "Firmware variant to execute.")
+ public var variant: VPhoneVariant = .regular
+
+ @Option(
+ help: "Automatically install the given IPA/TIPA after the guest control channel connects. Unavailable with --dfu.",
+ transform: URL.init(fileURLWithPath:)
+ )
+ public var installIPA: URL?
+
+ @Flag(name: .customLong("no-vphoned"), help: "Exclude vphoned usage (patchless-only).")
+ public var noVphoned: Bool = false
+
+ public init() {}
+
+ /// DFU mode is always headless.
+ public var noGraphics: Bool {
+ dfu || headless
+ }
+
+ public var installPackageURL: URL? {
+ installIPA?.standardizedFileURL
+ }
+
+ public mutating func validate() throws {
+ if dfu, let packageURL = installPackageURL {
+ throw ValidationError(
+ "`--install-ipa` is unavailable with `--dfu` because DFU mode does not start the guest control channel: \(packageURL.path)"
+ )
+ }
+
+ guard let packageURL = installPackageURL else { return }
+
+ guard FileManager.default.fileExists(atPath: packageURL.path) else {
+ throw ValidationError("`--install-ipa` file does not exist: \(packageURL.path)")
+ }
+
+ guard VPhoneInstallPackage.isSupportedFile(packageURL) else {
+ throw ValidationError(
+ "`--install-ipa` only supports .ipa or .tipa packages: \(packageURL.lastPathComponent)"
+ )
+ }
+ }
+
+ // MARK: - Forwarding
+
+ /// This command rendered back into arguments for `vphone-vm`.
+ ///
+ /// Several callers used to hand-build this list — the launch command, and
+ /// four sites in the create orchestrator — each spelling the flags out
+ /// again and each free to forget one. Rendering from the parsed value keeps
+ /// the spelling in the same file as the declaration, so adding an option
+ /// cannot silently fail to reach the guest.
+ ///
+ /// The subcommand name is deliberately omitted: `vphone-vm` *is* the boot
+ /// command, so its arguments start at the first option.
+ public var bootArguments: [String] {
+ var args = ["--config", config.path]
+ if dfu { args.append("--dfu") }
+ if headless { args.append("--headless") }
+ if noVphoned { args.append("--no-vphoned") }
+ if variant != .regular { args += ["--variant", variant.rawValue] }
+ if vphonedBin != ".vphoned.signed" { args += ["--vphoned-bin", vphonedBin] }
+ if let port = kernelDebugPort { args += ["--kernel-debug-port", String(port)] }
+ if let ipa = installIPA { args += ["--install-ipa", ipa.path] }
+ return args
+ }
+}
diff --git a/sources/VPhoneCore/VPhoneGuestLauncher.swift b/sources/VPhoneCore/VPhoneGuestLauncher.swift
new file mode 100644
index 00000000..929c821d
--- /dev/null
+++ b/sources/VPhoneCore/VPhoneGuestLauncher.swift
@@ -0,0 +1,183 @@
+import ArgumentParser
+import Foundation
+
+// MARK: - VPhoneLetMeInPolicy
+
+/// Whether to open an AMFI window before starting the guest.
+public enum VPhoneLetMeInPolicy: String, Sendable, CaseIterable, ExpressibleByArgument {
+ /// Start `vphone-vm` directly; only reach for `vphone-letmein`, and the
+ /// sudo prompt that comes with it, if amfid actually refuses the launch.
+ case auto
+ /// Always go through `vphone-letmein`.
+ case always
+ /// Never. If amfid refuses, the launch fails and says so.
+ case never
+
+ /// The policy for this run.
+ ///
+ /// `VPHONE_LETMEIN` exists because only some commands are worth spending a
+ /// flag on. `vphone vm launch` takes `--let-me-in` explicitly; everything
+ /// else that starts a guest just wants the default, and an environment
+ /// variable covers the rare case without adding an option to every command
+ /// — including to `VPhoneBootCLI`, which `vphone-vm` also parses and where
+ /// such an option would be inert.
+ ///
+ /// An unrecognised value falls back to `.auto` rather than failing: a typo
+ /// in an environment variable should not be able to stop a boot.
+ public static func fromEnvironment(
+ _ env: [String: String] = ProcessInfo.processInfo.environment
+ ) -> VPhoneLetMeInPolicy {
+ env["VPHONE_LETMEIN"].flatMap(VPhoneLetMeInPolicy.init(rawValue:)) ?? .auto
+ }
+}
+
+// MARK: - VPhoneGuestLaunchError
+
+public enum VPhoneGuestLaunchError: Error, CustomStringConvertible {
+ case missingCompanion(name: String, expectedAt: URL)
+ case blockedByAMFI
+ case probeFailed(exitCode: Int32, output: String)
+
+ public var description: String {
+ switch self {
+ case let .missingCompanion(name, url):
+ """
+ \(name) is missing — expected it next to this binary at:
+ \(url.path)
+ The install looks incomplete. Rebuild with `make build`.
+ """
+ case .blockedByAMFI:
+ """
+ amfid refused to launch vphone-vm, and --let-me-in=never forbids \
+ opening a window for it.
+ Re-run with --let-me-in=auto, or open one yourself:
+ sudo vphone-letmein on
+ """
+ case let .probeFailed(code, output):
+ """
+ vphone-vm could not start (exit \(code)). This is not the signature \
+ of an amfid refusal, so no AMFI window was opened.
+ \(output.isEmpty ? "It produced no output." : output)
+ """
+ }
+ }
+}
+
+// MARK: - VPhoneGuestLaunchPlanner
+
+/// Decides, once, how a guest has to be started, then hands out the concrete
+/// command for each boot.
+///
+/// The two binaries are split precisely so this indirection can exist:
+/// `vphone-vm` carries the private virtualization entitlements and therefore
+/// cannot launch unless amfid is willing, while `vphone-cli` carries none and
+/// always launches. That makes `vphone-cli` the natural place to notice the
+/// refusal and open a window just wide enough to get past it.
+///
+/// It is a value rather than a set of static calls because `vm create` boots
+/// the guest four times. Probing amfid — and prompting for sudo — once per
+/// boot would be both wasteful and, for the prompt, rude.
+public struct VPhoneGuestLaunchPlanner: Sendable {
+ /// How long the AMFI window stays open, in seconds.
+ ///
+ /// amfid takes its verdict when the image is exec'd, so this only has to
+ /// cover process start-up and dyld's work, not the guest's lifetime — and
+ /// the window closing does not disturb a guest that is already running.
+ /// Ten seconds is a deliberately loose first guess; it has not yet been
+ /// measured against a real launch on a loaded machine.
+ public static let defaultWindowSeconds = 10
+
+ private let executable: URL
+ private let prefix: [String]
+
+ /// The guest binary itself, whether or not it ends up being launched
+ /// directly. Host preflight checks this, because this is the binary that
+ /// actually has to satisfy amfid.
+ public let guestExecutable: URL
+
+ public init(
+ letMeIn: VPhoneLetMeInPolicy? = nil,
+ windowSeconds: Int = defaultWindowSeconds,
+ announce: Bool = true
+ ) throws {
+ let policy = letMeIn ?? .fromEnvironment()
+
+ let vm = VPhoneResources.siblingExecutable("vphone-vm")
+ guard FileManager.default.isExecutableFile(atPath: vm.path) else {
+ throw VPhoneGuestLaunchError.missingCompanion(name: "vphone-vm", expectedAt: vm)
+ }
+ guestExecutable = vm
+
+ // `never` still probes. Skipping the probe would launch straight into a
+ // SIGKILL and leave the caller with a bare exit 9 and no explanation —
+ // which is the confusing failure this whole path exists to remove.
+ // `never` means "do not open a window", not "do not tell me why".
+ let refused = switch policy {
+ case .always: true // taken as read; don't spend a probe to confirm it
+ case .auto, .never: try Self.amfidRefuses(vm)
+ }
+
+ guard refused else {
+ executable = vm
+ prefix = []
+ return
+ }
+
+ if policy == .never {
+ throw VPhoneGuestLaunchError.blockedByAMFI
+ }
+
+ let letmein = VPhoneResources.siblingExecutable("vphone-letmein")
+ guard FileManager.default.isExecutableFile(atPath: letmein.path) else {
+ throw VPhoneGuestLaunchError.missingCompanion(name: "vphone-letmein", expectedAt: letmein)
+ }
+
+ if announce {
+ print("""
+ [vphone] amfid will not let vphone-vm start on its own.
+ [vphone] Opening an AMFI window for \(windowSeconds)s to get it launched — this needs sudo.
+ [vphone] While that window is open, every signature amfid checks is reported valid.
+ """)
+ }
+
+ executable = URL(fileURLWithPath: "/usr/bin/sudo")
+ prefix = [letmein.path, "exec", "--hold", String(windowSeconds), "--", vm.path]
+ }
+
+ /// The command to spawn for one boot.
+ public func plan(_ arguments: [String]) -> (executable: URL, arguments: [String]) {
+ (executable, prefix + arguments)
+ }
+
+ /// Run a guest to completion and return its exit status.
+ ///
+ /// stdio is inherited so the guest's serial output streams straight to the
+ /// terminal, and the child is placed in the terminal's foreground group so
+ /// that both Ctrl-C and an interactive sudo prompt behave normally.
+ @discardableResult
+ public func run(_ arguments: [String], cwd: URL? = nil) throws -> Int32 {
+ let (exe, args) = plan(arguments)
+ return try VPhoneProcessRunner.runForeground(exe, args, cwd: cwd)
+ }
+
+ // MARK: - Probe
+
+ /// Ask amfid the question cheaply, by running `vphone-vm --help`.
+ ///
+ /// amfid decides at exec, before any of the target's own code runs, so a
+ /// `--help` that never prints is the same refusal the real launch would
+ /// hit — and it costs nothing and touches no VM state. A refused process is
+ /// killed with SIGKILL, which Foundation reports as termination status 9.
+ ///
+ /// Anything else non-zero is somebody else's problem, and is raised rather
+ /// than quietly escalated into a sudo prompt.
+ private static func amfidRefuses(_ vm: URL) throws -> Bool {
+ let probe = try VPhoneProcessRunner.runCapturing(vm, ["--help"])
+ if probe.succeeded { return false }
+ if probe.exitCode == SIGKILL { return true }
+ throw VPhoneGuestLaunchError.probeFailed(
+ exitCode: probe.exitCode,
+ output: (probe.stderr + probe.stdout).trimmingCharacters(in: .whitespacesAndNewlines)
+ )
+ }
+}
diff --git a/sources/vphone-cli/Guest/VPhoneInstallPackage.swift b/sources/VPhoneCore/VPhoneInstallPackage.swift
similarity index 56%
rename from sources/vphone-cli/Guest/VPhoneInstallPackage.swift
rename to sources/VPhoneCore/VPhoneInstallPackage.swift
index 00b2a90f..0a4fbe1b 100644
--- a/sources/vphone-cli/Guest/VPhoneInstallPackage.swift
+++ b/sources/VPhoneCore/VPhoneInstallPackage.swift
@@ -1,13 +1,17 @@
import Foundation
import UniformTypeIdentifiers
-enum VPhoneInstallPackage {
- static let allowedContentTypes: [UTType] = [
+/// What counts as an installable package. This lives in the shared layer
+/// because both sides need the same answer: `vphone-cli` rejects a bad
+/// `--install-ipa` before it launches anything, and `vphone-vm` applies the
+/// same rule to a file dropped on the VM window.
+public enum VPhoneInstallPackage {
+ public static let allowedContentTypes: [UTType] = [
UTType(filenameExtension: "ipa"),
UTType(filenameExtension: "tipa"),
].compactMap(\.self)
- static func isSupportedFile(_ url: URL) -> Bool {
+ public static func isSupportedFile(_ url: URL) -> Bool {
switch url.pathExtension.lowercased() {
case "ipa", "tipa":
true
@@ -16,7 +20,7 @@ enum VPhoneInstallPackage {
}
}
- static func successMessage(for fileName: String, detail: String) -> String {
+ public static func successMessage(for fileName: String, detail: String) -> String {
let trimmedDetail = detail.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmedDetail.isEmpty else {
return "Installed \(fileName)."
diff --git a/sources/VPhoneCore/VPhoneNetworking.swift b/sources/VPhoneCore/VPhoneNetworking.swift
index f604eab4..8df0d15e 100644
--- a/sources/VPhoneCore/VPhoneNetworking.swift
+++ b/sources/VPhoneCore/VPhoneNetworking.swift
@@ -10,6 +10,9 @@ public enum VPhoneNetworkingError: Error, Equatable {
case bridgeInterfaceNotFound(requested: String, available: [String])
/// bridged mode was selected but the host exposes no bridgeable interfaces.
case noBridgeInterfaces
+ /// bridged mode was selected, no interface was named, and this process is
+ /// not the one that can enumerate them.
+ case bridgeInterfaceMustBeNamed
/// `--bridge-interface` was given without selecting bridged mode.
case bridgeInterfaceWithoutBridgedMode
}
@@ -23,6 +26,13 @@ extension VPhoneNetworkingError: CustomStringConvertible, LocalizedError {
"Bridge interface '\(requested)' not found. Available: \(available.isEmpty ? "none" : available.joined(separator: ", "))."
case .noBridgeInterfaces:
"Bridged mode needs a host network interface, but none are available. Use nat instead."
+ case .bridgeInterfaceMustBeNamed:
+ """
+ Bridged mode needs an interface name here. vphone-cli carries no \
+ entitlements, so it cannot list the host's bridgeable interfaces \
+ and cannot pick one for you.
+ Name it explicitly, for example: --bridge-interface en0
+ """
case .bridgeInterfaceWithoutBridgedMode:
"--bridge-interface is only valid with --network bridged."
}
@@ -51,6 +61,21 @@ public enum VPhoneNetworking {
/// - otherwise the first available interface is auto-picked.
public static func resolveBridgeInterface(requested: String?, current: String?) throws -> String {
let available = availableBridgeInterfaces()
+
+ // An empty list is ambiguous: either the host really has nothing
+ // bridgeable, or this process is not entitled to ask. Since vphone-cli
+ // deliberately carries no entitlements, the second case is now the
+ // normal one, and rejecting a perfectly good interface name on the
+ // strength of a list we know is unreliable would break bridged mode
+ // outright. So when we cannot enumerate, we record what we were told
+ // and let vphone-vm — which is entitled — decide at boot, where the
+ // error can name the real problem.
+ guard !available.isEmpty else {
+ if let requested { return requested }
+ if let current { return current }
+ throw VPhoneNetworkingError.bridgeInterfaceMustBeNamed
+ }
+
if let requested {
guard available.contains(requested) else {
throw VPhoneNetworkingError.bridgeInterfaceNotFound(requested: requested, available: available)
@@ -60,10 +85,7 @@ public enum VPhoneNetworking {
if let current, available.contains(current) {
return current
}
- guard let first = available.first else {
- throw VPhoneNetworkingError.noBridgeInterfaces
- }
- return first
+ return available[0] // non-empty, guarded above
}
/// Merge partial edits onto an existing config, validating the result.
diff --git a/sources/VPhoneCore/VPhoneResources.swift b/sources/VPhoneCore/VPhoneResources.swift
index 673b538a..57dfa991 100644
--- a/sources/VPhoneCore/VPhoneResources.swift
+++ b/sources/VPhoneCore/VPhoneResources.swift
@@ -1,3 +1,4 @@
+import Darwin // _NSGetExecutablePath
import Foundation
// MARK: - VPhoneResourcesError
@@ -15,18 +16,48 @@ public struct VPhoneResources: Sendable {
// MARK: - Resolution
- /// The running executable, resolved reliably. `CommandLine.arguments[0]` is
- /// NOT reliable — under a PATH/symlink launch (e.g. a Homebrew symlink) it's
- /// a bare name that `URL(fileURLWithPath:)` resolves against the CWD, so the
- /// binary/base end up under `$HOME`. `Bundle.main.executableURL` is the
- /// kernel-provided executable path, correct regardless of how the process
- /// was invoked; resolve symlinks so a brew symlink lands on the real binary
- /// inside the .app.
+ /// The image this process is actually running, as the kernel recorded it.
+ ///
+ /// Neither obvious alternative works here. `CommandLine.arguments[0]` is a
+ /// bare name under a PATH or symlink launch, which `URL(fileURLWithPath:)`
+ /// then resolves against the CWD and lands under `$HOME`.
+ /// `Bundle.main.executableURL` reads `CFBundleExecutable` out of Info.plist
+ /// — and now that the bundle declares `vphone-vm`, it answers "vphone-vm"
+ /// even when the running binary is `vphone-cli` sitting right beside it in
+ /// the same `Contents/MacOS`. It cannot be used to find ourselves.
+ ///
+ /// `_NSGetExecutablePath` has neither problem: it is the path the kernel
+ /// exec'd, independent of argv and of any plist. Symlinks are resolved so a
+ /// Homebrew symlink lands on the real binary inside the .app.
public static func runningExecutable() -> URL {
+ var size = UInt32(PATH_MAX)
+ var buffer = [CChar](repeating: 0, count: Int(size))
+ if _NSGetExecutablePath(&buffer, &size) == 0 {
+ let bytes = buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }
+ let path = String(decoding: bytes, as: UTF8.self)
+ return URL(fileURLWithPath: path).resolvingSymlinksInPath()
+ }
+ // Only reachable if PATH_MAX was somehow too small for our own path.
if let exe = Bundle.main.executableURL { return exe.resolvingSymlinksInPath() }
return URL(fileURLWithPath: CommandLine.arguments[0]).resolvingSymlinksInPath()
}
+ /// A companion binary shipped beside this one: `vphone-vm`, `vphone-letmein`.
+ ///
+ /// The layout is the same in both places we ever run from — `.build/release`
+ /// during development and `Contents/MacOS` in the bundle — so resolving a
+ /// sibling of the running image covers both without a special case, and
+ /// without ever consulting `PATH`. That last part is the point: a `PATH`
+ /// lookup is what let the old Python probing pick up whatever happened to
+ /// be installed on the machine.
+ ///
+ /// Existence is deliberately not checked here. The caller reports a missing
+ /// companion far better than this function could, because it knows which
+ /// operation is failing and why.
+ public static func siblingExecutable(_ name: String) -> URL {
+ runningExecutable().deletingLastPathComponent().appendingPathComponent(name)
+ }
+
public static func resolve(executablePath: String? = nil) -> VPhoneResources {
let exe = executablePath.map { URL(fileURLWithPath: $0).resolvingSymlinksInPath() }
?? runningExecutable()
diff --git a/sources/vphone-cli/Devices/VPhoneCameraServer.swift b/sources/VPhoneVMKit/Devices/VPhoneCameraServer.swift
similarity index 100%
rename from sources/vphone-cli/Devices/VPhoneCameraServer.swift
rename to sources/VPhoneVMKit/Devices/VPhoneCameraServer.swift
diff --git a/sources/vphone-cli/Devices/VPhoneFrameProducer.swift b/sources/VPhoneVMKit/Devices/VPhoneFrameProducer.swift
similarity index 100%
rename from sources/vphone-cli/Devices/VPhoneFrameProducer.swift
rename to sources/VPhoneVMKit/Devices/VPhoneFrameProducer.swift
diff --git a/sources/vphone-cli/Devices/VPhoneLocationProvider.swift b/sources/VPhoneVMKit/Devices/VPhoneLocationProvider.swift
similarity index 100%
rename from sources/vphone-cli/Devices/VPhoneLocationProvider.swift
rename to sources/VPhoneVMKit/Devices/VPhoneLocationProvider.swift
diff --git a/sources/vphone-cli/Devices/VPhoneScreenRecorder.swift b/sources/VPhoneVMKit/Devices/VPhoneScreenRecorder.swift
similarity index 100%
rename from sources/vphone-cli/Devices/VPhoneScreenRecorder.swift
rename to sources/VPhoneVMKit/Devices/VPhoneScreenRecorder.swift
diff --git a/sources/vphone-cli/Devices/VPhoneTouchIDMonitor.swift b/sources/VPhoneVMKit/Devices/VPhoneTouchIDMonitor.swift
similarity index 100%
rename from sources/vphone-cli/Devices/VPhoneTouchIDMonitor.swift
rename to sources/VPhoneVMKit/Devices/VPhoneTouchIDMonitor.swift
diff --git a/sources/vphone-cli/Guest/VPhoneControl.swift b/sources/VPhoneVMKit/Guest/VPhoneControl.swift
similarity index 100%
rename from sources/vphone-cli/Guest/VPhoneControl.swift
rename to sources/VPhoneVMKit/Guest/VPhoneControl.swift
diff --git a/sources/vphone-cli/Guest/VPhoneControlApps.swift b/sources/VPhoneVMKit/Guest/VPhoneControlApps.swift
similarity index 100%
rename from sources/vphone-cli/Guest/VPhoneControlApps.swift
rename to sources/VPhoneVMKit/Guest/VPhoneControlApps.swift
diff --git a/sources/vphone-cli/Guest/VPhoneControlKeychain.swift b/sources/VPhoneVMKit/Guest/VPhoneControlKeychain.swift
similarity index 100%
rename from sources/vphone-cli/Guest/VPhoneControlKeychain.swift
rename to sources/VPhoneVMKit/Guest/VPhoneControlKeychain.swift
diff --git a/sources/vphone-cli/Guest/VPhoneControlSystem.swift b/sources/VPhoneVMKit/Guest/VPhoneControlSystem.swift
similarity index 100%
rename from sources/vphone-cli/Guest/VPhoneControlSystem.swift
rename to sources/VPhoneVMKit/Guest/VPhoneControlSystem.swift
diff --git a/sources/vphone-cli/Interface/Browsers/VPhoneAppBrowserModel.swift b/sources/VPhoneVMKit/Interface/Browsers/VPhoneAppBrowserModel.swift
similarity index 100%
rename from sources/vphone-cli/Interface/Browsers/VPhoneAppBrowserModel.swift
rename to sources/VPhoneVMKit/Interface/Browsers/VPhoneAppBrowserModel.swift
diff --git a/sources/vphone-cli/Interface/Browsers/VPhoneAppBrowserView.swift b/sources/VPhoneVMKit/Interface/Browsers/VPhoneAppBrowserView.swift
similarity index 100%
rename from sources/vphone-cli/Interface/Browsers/VPhoneAppBrowserView.swift
rename to sources/VPhoneVMKit/Interface/Browsers/VPhoneAppBrowserView.swift
diff --git a/sources/vphone-cli/Interface/Browsers/VPhoneAppWindowController.swift b/sources/VPhoneVMKit/Interface/Browsers/VPhoneAppWindowController.swift
similarity index 100%
rename from sources/vphone-cli/Interface/Browsers/VPhoneAppWindowController.swift
rename to sources/VPhoneVMKit/Interface/Browsers/VPhoneAppWindowController.swift
diff --git a/sources/vphone-cli/Interface/Browsers/VPhoneFileBrowserModel.swift b/sources/VPhoneVMKit/Interface/Browsers/VPhoneFileBrowserModel.swift
similarity index 100%
rename from sources/vphone-cli/Interface/Browsers/VPhoneFileBrowserModel.swift
rename to sources/VPhoneVMKit/Interface/Browsers/VPhoneFileBrowserModel.swift
diff --git a/sources/vphone-cli/Interface/Browsers/VPhoneFileBrowserView.swift b/sources/VPhoneVMKit/Interface/Browsers/VPhoneFileBrowserView.swift
similarity index 100%
rename from sources/vphone-cli/Interface/Browsers/VPhoneFileBrowserView.swift
rename to sources/VPhoneVMKit/Interface/Browsers/VPhoneFileBrowserView.swift
diff --git a/sources/vphone-cli/Interface/Browsers/VPhoneFileWindowController.swift b/sources/VPhoneVMKit/Interface/Browsers/VPhoneFileWindowController.swift
similarity index 100%
rename from sources/vphone-cli/Interface/Browsers/VPhoneFileWindowController.swift
rename to sources/VPhoneVMKit/Interface/Browsers/VPhoneFileWindowController.swift
diff --git a/sources/vphone-cli/Interface/Browsers/VPhoneKeychainBrowserModel.swift b/sources/VPhoneVMKit/Interface/Browsers/VPhoneKeychainBrowserModel.swift
similarity index 100%
rename from sources/vphone-cli/Interface/Browsers/VPhoneKeychainBrowserModel.swift
rename to sources/VPhoneVMKit/Interface/Browsers/VPhoneKeychainBrowserModel.swift
diff --git a/sources/vphone-cli/Interface/Browsers/VPhoneKeychainBrowserView.swift b/sources/VPhoneVMKit/Interface/Browsers/VPhoneKeychainBrowserView.swift
similarity index 100%
rename from sources/vphone-cli/Interface/Browsers/VPhoneKeychainBrowserView.swift
rename to sources/VPhoneVMKit/Interface/Browsers/VPhoneKeychainBrowserView.swift
diff --git a/sources/vphone-cli/Interface/Browsers/VPhoneKeychainItem.swift b/sources/VPhoneVMKit/Interface/Browsers/VPhoneKeychainItem.swift
similarity index 100%
rename from sources/vphone-cli/Interface/Browsers/VPhoneKeychainItem.swift
rename to sources/VPhoneVMKit/Interface/Browsers/VPhoneKeychainItem.swift
diff --git a/sources/vphone-cli/Interface/Browsers/VPhoneKeychainWindowController.swift b/sources/VPhoneVMKit/Interface/Browsers/VPhoneKeychainWindowController.swift
similarity index 100%
rename from sources/vphone-cli/Interface/Browsers/VPhoneKeychainWindowController.swift
rename to sources/VPhoneVMKit/Interface/Browsers/VPhoneKeychainWindowController.swift
diff --git a/sources/vphone-cli/Interface/Browsers/VPhoneQuickLookController.swift b/sources/VPhoneVMKit/Interface/Browsers/VPhoneQuickLookController.swift
similarity index 100%
rename from sources/vphone-cli/Interface/Browsers/VPhoneQuickLookController.swift
rename to sources/VPhoneVMKit/Interface/Browsers/VPhoneQuickLookController.swift
diff --git a/sources/vphone-cli/Interface/Browsers/VPhoneRemoteFile.swift b/sources/VPhoneVMKit/Interface/Browsers/VPhoneRemoteFile.swift
similarity index 100%
rename from sources/vphone-cli/Interface/Browsers/VPhoneRemoteFile.swift
rename to sources/VPhoneVMKit/Interface/Browsers/VPhoneRemoteFile.swift
diff --git a/sources/vphone-cli/Interface/Menu/VPhoneMenuApps.swift b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuApps.swift
similarity index 99%
rename from sources/vphone-cli/Interface/Menu/VPhoneMenuApps.swift
rename to sources/VPhoneVMKit/Interface/Menu/VPhoneMenuApps.swift
index 267d4dff..bad29792 100644
--- a/sources/vphone-cli/Interface/Menu/VPhoneMenuApps.swift
+++ b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuApps.swift
@@ -1,5 +1,6 @@
import AppKit
import Foundation
+import VPhoneCore
// MARK: - Apps Menu
diff --git a/sources/vphone-cli/Interface/Menu/VPhoneMenuBattery.swift b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuBattery.swift
similarity index 100%
rename from sources/vphone-cli/Interface/Menu/VPhoneMenuBattery.swift
rename to sources/VPhoneVMKit/Interface/Menu/VPhoneMenuBattery.swift
diff --git a/sources/vphone-cli/Interface/Menu/VPhoneMenuCamera.swift b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuCamera.swift
similarity index 100%
rename from sources/vphone-cli/Interface/Menu/VPhoneMenuCamera.swift
rename to sources/VPhoneVMKit/Interface/Menu/VPhoneMenuCamera.swift
diff --git a/sources/vphone-cli/Interface/Menu/VPhoneMenuConnect.swift b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuConnect.swift
similarity index 100%
rename from sources/vphone-cli/Interface/Menu/VPhoneMenuConnect.swift
rename to sources/VPhoneVMKit/Interface/Menu/VPhoneMenuConnect.swift
diff --git a/sources/vphone-cli/Interface/Menu/VPhoneMenuController.swift b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuController.swift
similarity index 100%
rename from sources/vphone-cli/Interface/Menu/VPhoneMenuController.swift
rename to sources/VPhoneVMKit/Interface/Menu/VPhoneMenuController.swift
diff --git a/sources/vphone-cli/Interface/Menu/VPhoneMenuKeys.swift b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuKeys.swift
similarity index 100%
rename from sources/vphone-cli/Interface/Menu/VPhoneMenuKeys.swift
rename to sources/VPhoneVMKit/Interface/Menu/VPhoneMenuKeys.swift
diff --git a/sources/vphone-cli/Interface/Menu/VPhoneMenuLocation.swift b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuLocation.swift
similarity index 100%
rename from sources/vphone-cli/Interface/Menu/VPhoneMenuLocation.swift
rename to sources/VPhoneVMKit/Interface/Menu/VPhoneMenuLocation.swift
diff --git a/sources/vphone-cli/Interface/Menu/VPhoneMenuRecord.swift b/sources/VPhoneVMKit/Interface/Menu/VPhoneMenuRecord.swift
similarity index 100%
rename from sources/vphone-cli/Interface/Menu/VPhoneMenuRecord.swift
rename to sources/VPhoneVMKit/Interface/Menu/VPhoneMenuRecord.swift
diff --git a/sources/vphone-cli/Interface/VPhoneKeyHelper.swift b/sources/VPhoneVMKit/Interface/VPhoneKeyHelper.swift
similarity index 100%
rename from sources/vphone-cli/Interface/VPhoneKeyHelper.swift
rename to sources/VPhoneVMKit/Interface/VPhoneKeyHelper.swift
diff --git a/sources/vphone-cli/Interface/VPhoneWindowController.swift b/sources/VPhoneVMKit/Interface/VPhoneWindowController.swift
similarity index 100%
rename from sources/vphone-cli/Interface/VPhoneWindowController.swift
rename to sources/VPhoneVMKit/Interface/VPhoneWindowController.swift
diff --git a/sources/vphone-cli/VM/VPhoneError.swift b/sources/VPhoneVMKit/VM/VPhoneError.swift
similarity index 100%
rename from sources/vphone-cli/VM/VPhoneError.swift
rename to sources/VPhoneVMKit/VM/VPhoneError.swift
diff --git a/sources/vphone-cli/VM/VPhoneHardwareModel.swift b/sources/VPhoneVMKit/VM/VPhoneHardwareModel.swift
similarity index 100%
rename from sources/vphone-cli/VM/VPhoneHardwareModel.swift
rename to sources/VPhoneVMKit/VM/VPhoneHardwareModel.swift
diff --git a/sources/vphone-cli/VM/VPhoneVirtualMachine.swift b/sources/VPhoneVMKit/VM/VPhoneVirtualMachine.swift
similarity index 98%
rename from sources/vphone-cli/VM/VPhoneVirtualMachine.swift
rename to sources/VPhoneVMKit/VM/VPhoneVirtualMachine.swift
index 1f546835..21f6ca3f 100644
--- a/sources/vphone-cli/VM/VPhoneVirtualMachine.swift
+++ b/sources/VPhoneVMKit/VM/VPhoneVirtualMachine.swift
@@ -14,14 +14,12 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {
/// Synthetic battery source for runtime charge/connectivity updates.
private var batterySource: AnyObject?
- public enum Variant: String, Sendable {
- case less
- case regular
- case dev
- case jb
- case exp
- }
-
+ /// Moved to VPhoneCore so vphone-cli can accept `--variant` without linking
+ /// Virtualization. The alias keeps every existing `VPhoneVirtualMachine.Variant`
+ /// spelling working.
+ public typealias Variant = VPhoneVariant
+
+
struct Options {
var configURL: URL
var romURL: URL?
diff --git a/sources/vphone-cli/VM/VPhoneVirtualMachineView.swift b/sources/VPhoneVMKit/VM/VPhoneVirtualMachineView.swift
similarity index 99%
rename from sources/vphone-cli/VM/VPhoneVirtualMachineView.swift
rename to sources/VPhoneVMKit/VM/VPhoneVirtualMachineView.swift
index cd57a02e..32d5be2f 100644
--- a/sources/vphone-cli/VM/VPhoneVirtualMachineView.swift
+++ b/sources/VPhoneVMKit/VM/VPhoneVirtualMachineView.swift
@@ -2,6 +2,7 @@ import AppKit
import Dynamic
import Foundation
import Virtualization
+import VPhoneCore
class VPhoneVirtualMachineView: VZVirtualMachineView {
var keyHelper: VPhoneKeyHelper?
diff --git a/sources/vphone-cli/VPhoneAppDelegate.swift b/sources/VPhoneVMKit/VPhoneAppDelegate.swift
similarity index 99%
rename from sources/vphone-cli/VPhoneAppDelegate.swift
rename to sources/VPhoneVMKit/VPhoneAppDelegate.swift
index 5a1ac348..734448c5 100644
--- a/sources/vphone-cli/VPhoneAppDelegate.swift
+++ b/sources/VPhoneVMKit/VPhoneAppDelegate.swift
@@ -1,6 +1,7 @@
import AppKit
import Foundation
import Virtualization
+import VPhoneCore
class VPhoneAppDelegate: NSObject, NSApplicationDelegate {
private let cli: VPhoneBootCLI
diff --git a/sources/VPhoneVMKit/VPhoneBootCLI+VirtualMachine.swift b/sources/VPhoneVMKit/VPhoneBootCLI+VirtualMachine.swift
new file mode 100644
index 00000000..ac91f77b
--- /dev/null
+++ b/sources/VPhoneVMKit/VPhoneBootCLI+VirtualMachine.swift
@@ -0,0 +1,37 @@
+import Foundation
+import VPhoneCore
+
+// The half of VPhoneBootCLI that needs the Virtualization framework. The
+// options themselves live in VPhoneCore so vphone-cli can parse and forward
+// them without linking any of this.
+extension VPhoneBootCLI {
+ /// Resolve final options by merging manifest values.
+ func resolveOptions() throws -> VPhoneVirtualMachine.Options {
+ let manifest = try VPhoneVirtualMachineManifest.load(from: config)
+ print("[vphone] Loaded VM manifest from \(config.path)")
+
+ let vmDir = config.deletingLastPathComponent()
+
+ return VPhoneVirtualMachine.Options(
+ configURL: config,
+ romURL: manifest.romImages != nil
+ ? manifest.resolve(path: manifest.romImages!.avpBooter, in: vmDir)
+ : nil,
+ nvramURL: manifest.resolve(path: manifest.nvramStorage, in: vmDir),
+ diskURL: manifest.resolve(path: manifest.diskImage, in: vmDir),
+ cpuCount: Int(manifest.cpuCount),
+ memorySize: manifest.memorySize,
+ sepStorageURL: manifest.resolve(path: manifest.sepStorage, in: vmDir),
+ sepRomURL: manifest.romImages != nil
+ ? manifest.resolve(path: manifest.romImages!.avpSEPBooter, in: vmDir)
+ : nil,
+ screenWidth: manifest.screenConfig.width,
+ screenHeight: manifest.screenConfig.height,
+ screenPPI: manifest.screenConfig.pixelsPerInch,
+ screenScale: manifest.screenConfig.scale,
+ kernelDebugPort: kernelDebugPort,
+ variant: variant,
+ noVphoned: noVphoned
+ )
+ }
+}
diff --git a/sources/VPhoneVMKit/VPhoneGuestApp.swift b/sources/VPhoneVMKit/VPhoneGuestApp.swift
new file mode 100644
index 00000000..ad26ec07
--- /dev/null
+++ b/sources/VPhoneVMKit/VPhoneGuestApp.swift
@@ -0,0 +1,24 @@
+import AppKit
+import Foundation
+import VPhoneCore
+
+/// The kit's entry point: turn parsed boot options into a running guest.
+///
+/// This exists so `vphone-vm`'s `main.swift` stays a parse and a call. The
+/// NSApplication wiring is an implementation detail of running a guest, not
+/// something an entry point should be spelling out, and keeping it here means
+/// `VPhoneAppDelegate` does not have to be public — which in turn keeps every
+/// `NSApplicationDelegate` method it implements internal.
+public enum VPhoneGuestApp {
+ /// Run the guest. Returns only when the application terminates.
+ public static func run(_ boot: VPhoneBootCLI) -> Never {
+ let app = NSApplication.shared
+ let delegate = VPhoneAppDelegate(cli: boot)
+ app.delegate = delegate
+ app.run()
+ // NSApplication.run() does not return through here in practice: the
+ // terminate path exits the process. Spelling that out keeps the caller
+ // from having to invent a meaningless return value.
+ exit(0)
+ }
+}
diff --git a/sources/vphone-cli/VPhoneHostControl.swift b/sources/VPhoneVMKit/VPhoneHostControl.swift
similarity index 100%
rename from sources/vphone-cli/VPhoneHostControl.swift
rename to sources/VPhoneVMKit/VPhoneHostControl.swift
diff --git a/sources/vphone-cli/CLI/VPhoneCLI.swift b/sources/vphone-cli/VPhoneCLI.swift
similarity index 64%
rename from sources/vphone-cli/CLI/VPhoneCLI.swift
rename to sources/vphone-cli/VPhoneCLI.swift
index 54b76a16..38190ed1 100644
--- a/sources/vphone-cli/CLI/VPhoneCLI.swift
+++ b/sources/vphone-cli/VPhoneCLI.swift
@@ -15,116 +15,8 @@ struct VPhoneCLI: ParsableCommand {
)
}
-struct VPhoneBootCLI: ParsableCommand {
- static let configuration = CommandConfiguration(
- commandName: "boot",
- abstract: "Boot a virtual iPhone (PV=3)",
- discussion: """
- Creates a Virtualization.framework VM with platform version 3 (vphone)
- and boots it from a manifest plist that describes all paths and hardware.
-
- Requires:
- - macOS 15+ (Sequoia or later)
- - SIP/AMFI disabled
- - Signed with vphone entitlements (done automatically by wrapper script)
-
- Example:
- vphone-cli --config ./config.plist
- """
- )
-
- @Option(
- name: .shortAndLong,
- help: "Path to VM manifest plist (config.plist). Required.",
- transform: URL.init(fileURLWithPath:)
- )
- var config: URL
-
- @Flag(name: .shortAndLong, help: "Boot into DFU mode")
- var dfu: Bool = false
-
- @Flag(name: .customLong("headless"), help: "Boot without a VM window or menu bar")
- var headless: Bool = false
-
- @Option(help: "Kernel GDB debug stub port on host (omit for system-assigned port; valid: 6000...65535)")
- var kernelDebugPort: Int?
-
- @Option(help: "Path to signed vphoned binary for guest auto-update")
- var vphonedBin: String = ".vphoned.signed"
-
- @Option(name: [.customShort("V"), .long], help: "Firmware variant to execute.")
- var variant: PatchFirmwareCLI.VariantOption = .regular
-
- @Option(
- help: "Automatically install the given IPA/TIPA after the guest control channel connects. Unavailable with --dfu.",
- transform: URL.init(fileURLWithPath:)
- )
- var installIPA: URL?
-
- @Flag(name: .customLong("no-vphoned"), help: "Exclude vphoned usage (patchless-only).")
- var noVphoned: Bool = false
-
- /// DFU mode is always headless.
- var noGraphics: Bool {
- dfu || headless
- }
-
- var installPackageURL: URL? {
- installIPA?.standardizedFileURL
- }
-
- mutating func validate() throws {
- if dfu, let packageURL = installPackageURL {
- throw ValidationError(
- "`--install-ipa` is unavailable with `--dfu` because DFU mode does not start the guest control channel: \(packageURL.path)"
- )
- }
-
- guard let packageURL = installPackageURL else { return }
-
- guard FileManager.default.fileExists(atPath: packageURL.path) else {
- throw ValidationError("`--install-ipa` file does not exist: \(packageURL.path)")
- }
-
- guard VPhoneInstallPackage.isSupportedFile(packageURL) else {
- throw ValidationError(
- "`--install-ipa` only supports .ipa or .tipa packages: \(packageURL.lastPathComponent)"
- )
- }
- }
-
- /// Resolve final options by merging manifest values.
- func resolveOptions() throws -> VPhoneVirtualMachine.Options {
- let manifest = try VPhoneVirtualMachineManifest.load(from: config)
- print("[vphone] Loaded VM manifest from \(config.path)")
-
- let vmDir = config.deletingLastPathComponent()
-
- return VPhoneVirtualMachine.Options(
- configURL: config,
- romURL: manifest.romImages != nil
- ? manifest.resolve(path: manifest.romImages!.avpBooter, in: vmDir)
- : nil,
- nvramURL: manifest.resolve(path: manifest.nvramStorage, in: vmDir),
- diskURL: manifest.resolve(path: manifest.diskImage, in: vmDir),
- cpuCount: Int(manifest.cpuCount),
- memorySize: manifest.memorySize,
- sepStorageURL: manifest.resolve(path: manifest.sepStorage, in: vmDir),
- sepRomURL: manifest.romImages != nil
- ? manifest.resolve(path: manifest.romImages!.avpSEPBooter, in: vmDir)
- : nil,
- screenWidth: manifest.screenConfig.width,
- screenHeight: manifest.screenConfig.height,
- screenPPI: manifest.screenConfig.pixelsPerInch,
- screenScale: manifest.screenConfig.scale,
- kernelDebugPort: kernelDebugPort,
- variant: variant.virtualMachineVariant,
- noVphoned: self.noVphoned
- )
- }
-
- mutating func run() throws {}
-}
+// VPhoneBootCLI now lives in VPhoneCore, shared with vphone-vm. This binary
+// only forwards it — see main.swift.
struct PatchFirmwareCLI: ParsableCommand {
enum VariantOption: String, CaseIterable, ExpressibleByArgument {
@@ -144,15 +36,6 @@ struct PatchFirmwareCLI: ParsableCommand {
}
}
- var virtualMachineVariant: VPhoneVirtualMachine.Variant {
- switch self {
- case .less: .less
- case .regular: .regular
- case .dev: .dev
- case .jb: .jb
- case .exp: .exp
- }
- }
}
static let configuration = CommandConfiguration(
diff --git a/sources/vphone-cli/CLI/VPhoneCreateOptions.swift b/sources/vphone-cli/VPhoneCreateOptions.swift
similarity index 100%
rename from sources/vphone-cli/CLI/VPhoneCreateOptions.swift
rename to sources/vphone-cli/VPhoneCreateOptions.swift
diff --git a/sources/vphone-cli/CLI/VPhoneCreateOrchestrator.swift b/sources/vphone-cli/VPhoneCreateOrchestrator.swift
similarity index 95%
rename from sources/vphone-cli/CLI/VPhoneCreateOrchestrator.swift
rename to sources/vphone-cli/VPhoneCreateOrchestrator.swift
index 585752ba..fc00d09c 100644
--- a/sources/vphone-cli/CLI/VPhoneCreateOrchestrator.swift
+++ b/sources/vphone-cli/VPhoneCreateOrchestrator.swift
@@ -94,12 +94,20 @@ extension VPhoneCreateError: LocalizedError {
public struct VPhoneCreateOrchestrator {
private let library: VPhoneLibrary
private let resources: VPhoneResources
- private let selfExecutable: URL
-
- public init(library: VPhoneLibrary, resources: VPhoneResources, selfExecutable: URL) {
+ /// 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
+ /// is needed is taken once, here, rather than probing amfid (and possibly
+ /// prompting for sudo) before each one.
+ private let launcher: VPhoneGuestLaunchPlanner
+
+ public init(
+ library: VPhoneLibrary,
+ resources: VPhoneResources,
+ launcher: VPhoneGuestLaunchPlanner
+ ) {
self.library = library
self.resources = resources
- self.selfExecutable = selfExecutable
+ self.launcher = launcher
}
// MARK: - run
@@ -339,13 +347,9 @@ public struct VPhoneCreateOrchestrator {
print("[*] Starting DFU boot in background...")
// Guest serial is never teed during `vm create` (echo: false); the
// managed process still reads it internally for panic/prompt matching.
- trace("spawn \(selfExecutable.path) --config \(configURL.path) --dfu (guest serial: off)", v)
- let dfu = VPhoneManagedProcess(
- selfExecutable,
- ["--config", configURL.path, "--dfu"],
- cwd: bundleURL,
- echo: false
- )
+ let (dfuExe, dfuArgs) = launcher.plan(["--config", configURL.path, "--dfu"])
+ trace("spawn \(dfuExe.path) \(dfuArgs.joined(separator: " ")) (guest serial: off)", v)
+ let dfu = VPhoneManagedProcess(dfuExe, dfuArgs, cwd: bundleURL, echo: false)
try dfu.start()
defer { dfu.terminate() }
@@ -553,8 +557,9 @@ public struct VPhoneCreateOrchestrator {
print("[*] non-interactive (default): auto-starting first boot")
}
- trace("spawn \(selfExecutable.path) \(args.joined(separator: " ")) (guest serial: off)", v)
- let boot = VPhoneManagedProcess(selfExecutable, args, cwd: bundleURL, echo: false)
+ 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() }
@@ -591,13 +596,9 @@ public struct VPhoneCreateOrchestrator {
private func runBootAnalysis(bundleURL: URL, verbosity v: VPhoneVerbosity) throws {
let configURL = bundleURL.appendingPathComponent("config.plist")
- trace("spawn \(selfExecutable.path) --config \(configURL.path) --headless (guest serial: off)", v)
- let vm = VPhoneManagedProcess(
- selfExecutable,
- ["--config", configURL.path, "--headless"],
- cwd: bundleURL,
- echo: false
- )
+ let (vmExe, vmArgs) = launcher.plan(["--config", configURL.path, "--headless"])
+ trace("spawn \(vmExe.path) \(vmArgs.joined(separator: " ")) (guest serial: off)", v)
+ let vm = VPhoneManagedProcess(vmExe, vmArgs, cwd: bundleURL, echo: false)
try vm.start()
defer { vm.terminate() }
@@ -625,10 +626,10 @@ public struct VPhoneCreateOrchestrator {
private func startVMForeground(bundleURL: URL, verbosity v: VPhoneVerbosity) throws {
let configURL = bundleURL.appendingPathComponent("config.plist")
print("\n=== Start VM ===")
- let args = ["--config", configURL.path, "--variant", "less"]
- trace("spawn \(selfExecutable.path) \(args.joined(separator: " ")) (echo=\(v.showsToolDetail))", v)
+ let (exe, args) = launcher.plan(["--config", configURL.path, "--variant", "less"])
+ trace("spawn \(exe.path) \(args.joined(separator: " ")) (echo=\(v.showsToolDetail))", v)
let code = try VPhoneProcessRunner.runStreaming(
- selfExecutable,
+ exe,
args,
cwd: bundleURL,
echo: v.showsToolDetail
diff --git a/sources/vphone-cli/CLI/VPhoneFWCLI.swift b/sources/vphone-cli/VPhoneFWCLI.swift
similarity index 100%
rename from sources/vphone-cli/CLI/VPhoneFWCLI.swift
rename to sources/vphone-cli/VPhoneFWCLI.swift
diff --git a/sources/vphone-cli/CLI/VPhoneFirmwareSelection.swift b/sources/vphone-cli/VPhoneFirmwareSelection.swift
similarity index 100%
rename from sources/vphone-cli/CLI/VPhoneFirmwareSelection.swift
rename to sources/vphone-cli/VPhoneFirmwareSelection.swift
diff --git a/sources/vphone-cli/CLI/VPhoneProgressBar.swift b/sources/vphone-cli/VPhoneProgressBar.swift
similarity index 100%
rename from sources/vphone-cli/CLI/VPhoneProgressBar.swift
rename to sources/vphone-cli/VPhoneProgressBar.swift
diff --git a/sources/vphone-cli/CLI/VPhoneRestoreCLI.swift b/sources/vphone-cli/VPhoneRestoreCLI.swift
similarity index 100%
rename from sources/vphone-cli/CLI/VPhoneRestoreCLI.swift
rename to sources/vphone-cli/VPhoneRestoreCLI.swift
diff --git a/sources/vphone-cli/CLI/VPhoneSetupCLI.swift b/sources/vphone-cli/VPhoneSetupCLI.swift
similarity index 100%
rename from sources/vphone-cli/CLI/VPhoneSetupCLI.swift
rename to sources/vphone-cli/VPhoneSetupCLI.swift
diff --git a/sources/vphone-cli/CLI/VPhoneVMCLI.swift b/sources/vphone-cli/VPhoneVMCLI.swift
similarity index 100%
rename from sources/vphone-cli/CLI/VPhoneVMCLI.swift
rename to sources/vphone-cli/VPhoneVMCLI.swift
diff --git a/sources/vphone-cli/CLI/VPhoneVMCreateCLI.swift b/sources/vphone-cli/VPhoneVMCreateCLI.swift
similarity index 92%
rename from sources/vphone-cli/CLI/VPhoneVMCreateCLI.swift
rename to sources/vphone-cli/VPhoneVMCreateCLI.swift
index a1d6c617..6133e67a 100644
--- a/sources/vphone-cli/CLI/VPhoneVMCreateCLI.swift
+++ b/sources/vphone-cli/VPhoneVMCreateCLI.swift
@@ -51,13 +51,16 @@ struct VPhoneVMCreateCommand: ParsableCommand {
func run() throws {
let resources = projectRoot.map { VPhoneResources(base: URL(fileURLWithPath: $0)) } ?? .resolve()
- let selfExe = VPhoneResources.runningExecutable()
+ // Resolved up front: a create boots the guest four times, and this is
+ // also where a missing vphone-vm should be reported — before any of the
+ // long-running download and patch work, not after it.
+ let launcher = try VPhoneGuestLaunchPlanner()
// Prompt for any firmware component not supplied on the command line.
let sources = try VPhoneFirmwareSelection.resolve(iphone: iphoneSource, cloudos: cloudosSource)
let orchestrator = VPhoneCreateOrchestrator(
library: lib.library,
resources: resources,
- selfExecutable: selfExe
+ launcher: launcher
)
try orchestrator.run(.init(
name: name,
diff --git a/sources/vphone-cli/CLI/VPhoneVMLaunchCLI.swift b/sources/vphone-cli/VPhoneVMLaunchCLI.swift
similarity index 76%
rename from sources/vphone-cli/CLI/VPhoneVMLaunchCLI.swift
rename to sources/vphone-cli/VPhoneVMLaunchCLI.swift
index 8642f9f6..28f05cc5 100644
--- a/sources/vphone-cli/CLI/VPhoneVMLaunchCLI.swift
+++ b/sources/vphone-cli/VPhoneVMLaunchCLI.swift
@@ -18,6 +18,12 @@ struct VPhoneVMLaunchCommand: ParsableCommand {
var kernelDebugPort: Int?
@Option(name: .shortAndLong, help: "Resource base override (default: inferred from the running binary path)")
var projectRoot: String?
+ @Option(help: """
+ When to open an AMFI window for vphone-vm: auto (only if amfid refuses the \
+ launch), always, or never. Opening one needs sudo and, while open, makes \
+ amfid report every signature as valid.
+ """)
+ var letMeIn: VPhoneLetMeInPolicy = .fromEnvironment()
@Flag(name: .customShort("v"), help: "Increase verbosity: -v tool detail, -vv guest serial, -vvv internal trace")
var verboseCount: Int
@@ -28,18 +34,22 @@ struct VPhoneVMLaunchCommand: ParsableCommand {
let resources = projectRoot.map { VPhoneResources(base: URL(fileURLWithPath: $0)) } ?? .resolve()
let layout = VPhoneLaunchLayout(resources: resources)
- // The running executable is BOTH what we boot from and what preflight
- // should check — a bundled .app is its own boot binary.
- let bootBinary = VPhoneResources.runningExecutable()
- guard FileManager.default.isExecutableFile(atPath: bootBinary.path) else {
- FileHandle.standardError.write(Data(
- "error: \(bootBinary.path) not found — build it first (make build/bundle).\n".utf8))
+ // The guest runs in vphone-vm, not in this process — that is the binary
+ // carrying the virtualization entitlements, so it is also the one
+ // preflight has to check. Checking ourselves would prove nothing: this
+ // binary is unentitled and always launches.
+ let launcher: VPhoneGuestLaunchPlanner
+ do {
+ launcher = try VPhoneGuestLaunchPlanner(letMeIn: letMeIn)
+ } 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 THIS binary
- // (VPHONE_CLI_BIN) so it checks the vphone-cli we're running, not a dev
- // .build/release path that doesn't exist inside the bundled .app.
+ // 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.
var preflightArgs = ["--assert-bootable"]
if variant == "less" { preflightArgs.append("--less") }
var preflightEnv = ProcessInfo.processInfo.environment
@@ -73,25 +83,15 @@ struct VPhoneVMLaunchCommand: ParsableCommand {
if let kernelDebugPort { args += ["--kernel-debug-port", String(kernelDebugPort)] }
if v.tracesInternals {
- print("[trace] spawning: \(bootBinary.path) \(args.joined(separator: " "))")
+ let (exe, spawned) = launcher.plan(args)
+ print("[trace] spawning: \(exe.path) \(spawned.joined(separator: " "))")
}
- let child = Process()
- child.executableURL = bootBinary
- child.arguments = args
- child.currentDirectoryURL = bundle.url
// `vm launch` always streams the guest serial console (inherits our
- // stdio); it is intentionally not gated on verbosity.
- try child.run()
-
- // Forward SIGINT to the child so Ctrl+C stops the VM cleanly.
- let sigint = DispatchSource.makeSignalSource(signal: SIGINT, queue: .main)
- signal(SIGINT, SIG_IGN)
- sigint.setEventHandler { child.interrupt() }
- sigint.resume()
-
- child.waitUntilExit()
- throw ExitCode(child.terminationStatus)
+ // stdio); it is intentionally not gated on verbosity. run() also hands
+ // the terminal to the child, which is what lets Ctrl-C reach the guest
+ // and an interactive sudo prompt reach the user.
+ throw ExitCode(try launcher.run(args, cwd: bundle.url))
}
}
diff --git a/sources/vphone-cli/CLI/VPhoneVMSelection.swift b/sources/vphone-cli/VPhoneVMSelection.swift
similarity index 100%
rename from sources/vphone-cli/CLI/VPhoneVMSelection.swift
rename to sources/vphone-cli/VPhoneVMSelection.swift
diff --git a/sources/vphone-cli/CLI/VPhoneVMTransferCLI.swift b/sources/vphone-cli/VPhoneVMTransferCLI.swift
similarity index 100%
rename from sources/vphone-cli/CLI/VPhoneVMTransferCLI.swift
rename to sources/vphone-cli/VPhoneVMTransferCLI.swift
diff --git a/sources/vphone-cli/main.swift b/sources/vphone-cli/main.swift
index 0b8b7255..e9e6cefb 100644
--- a/sources/vphone-cli/main.swift
+++ b/sources/vphone-cli/main.swift
@@ -1,16 +1,29 @@
-import AppKit
+// vphone-cli — the user-facing entry point.
+//
+// This binary carries no entitlements at all, which is the whole point: it
+// launches normally on any host, so it is always available to explain what is
+// wrong and to arrange whatever the actual work needs. The private
+// virtualization entitlements live on `vphone-vm`, which this starts as a
+// child when a boot is asked for.
+//
+// Booting used to happen right here — the process parsed `boot` and then
+// became the NSApplication itself, which is why the top-level binary had to
+// carry the entitlements and could not start without an AMFI bypass already
+// running.
+
import ArgumentParser
import Foundation
+import VPhoneCore
do {
let command = try VPhoneCLI.parseAsRoot()
switch command {
case let boot as VPhoneBootCLI:
- let app = NSApplication.shared
- let delegate = VPhoneAppDelegate(cli: boot)
- app.delegate = delegate
- app.run()
+ // `boot` is a request for a guest, not work this process does. Hand it
+ // to vphone-vm and report back whatever the guest exits with.
+ let status = try VPhoneGuestLaunchPlanner().run(boot.bootArguments)
+ if status != 0 { throw ExitCode(status) }
default:
var runnable = command
diff --git a/sources/vphone-letmein/main.c b/sources/vphone-letmein/main.c
new file mode 100644
index 00000000..f3e56371
--- /dev/null
+++ b/sources/vphone-letmein/main.c
@@ -0,0 +1,477 @@
+// vphone-letmein — opens a short AMFI window so vphone-vm can launch.
+//
+// Why this exists
+// ---------------------------------------------------------------------------
+// vphone-vm is signed with Apple-private virtualization entitlements (see
+// sources/vphone.entitlements) but only ad-hoc signed, because we are not
+// Apple. amfid rejects that combination, so the kernel kills vphone-vm at exec
+// before a single line of it runs. This tool holds amfid's verdict open for
+// the length of that exec and then puts it back.
+//
+// It is deliberately NOT a daemon. vphone-cli carries no entitlements at all,
+// so it launches normally and can drive this itself:
+//
+// sudo vphone-letmein exec --hold N -- <bundle>/Contents/MacOS/vphone-vm ...
+//
+// The check happens at exec, so N only has to cover the launch; the window
+// closes while the VM keeps running. That is the whole reason the entitlements
+// live on vphone-vm and not on the top-level binary -- it is what makes the
+// window one launch long instead of permanently open.
+//
+// Build: clang and the macOS SDK, nothing else. No pip, no Python, no LLDB,
+// no Xcode.app. Driven by scripts/build.sh; standalone equivalent:
+//
+// clang -arch arm64 -framework Foundation -o vphone-letmein main.c
+// codesign --force --sign - vphone-letmein
+//
+// ---------------------------------------------------------------------------
+// Why this does not use breakpoints
+// ---------------------------------------------------------------------------
+// The obvious implementation drives amfid with a debugger: break on
+// -[AMFIPathValidator_macos validateWithError:], steps out, and overwrites the
+// return register. That needs task_set_exception_ports() and thread_set_state()
+// against amfid — and on macOS 26 amfid carries
+// com.apple.developer.hardened-process, so both calls are gated behind Apple
+// private entitlements:
+//
+// com.apple.private.set-exception-port
+// com.apple.private.thread-set-state
+//
+// Those are exactly the entitlements Xcode's debugserver carries, which is why
+// debugger-based tools have to route through LLDB at all rather than doing it
+// themselves. An ad-hoc signed binary that calls task_set_exception_ports() on
+// amfid is killed on the spot with EXC_GUARD / GUARD_TYPE_MACH_PORT
+// (violation SET_EXCEPTION_BEHAVIOR). Measured, not assumed.
+//
+// task_for_pid(), mach_vm_read(), mach_vm_protect() and mach_vm_write() are NOT
+// gated, so this tool patches amfid's code instead of interrupting it.
+//
+// ---------------------------------------------------------------------------
+// What it patches
+// ---------------------------------------------------------------------------
+// AMFIPathValidator_macos lives in AppleMobileFileIntegrity.framework, i.e. in
+// the dyld shared cache, which is mapped at the same address in every process.
+// So the addresses are resolved here, in this process, with the ObjC runtime —
+// amfid's Mach-O is never parsed and no slide is ever computed.
+//
+// 1. validateWithError: ends in a single epilogue that returns self->_isValid:
+//
+// ldrb w19, [x19, #_isValid] <- rewritten to `mov w19, #1`
+// ...
+// mov x0, x19
+// retab
+//
+// Patching that one load leaves the whole validation running — cdhash,
+// entitlements and the rest of the object are still populated — and only
+// the verdict is forced. Short-circuiting the function entry instead does
+// NOT work: the object stays empty and the kernel still kills the process.
+//
+// 2. isApple is a plain accessor, rewritten to `mov w0, #1; ret`, which is what
+// actually lets Apple-private entitlements through.
+//
+// Both sites are located by scanning for semantic anchors (the epilogue, the
+// register feeding x0, the _isValid ivar offset taken from the live ObjC
+// runtime). No file offset, virtual address or ivar offset is hardcoded.
+//
+// ---------------------------------------------------------------------------
+// Scope, honestly stated
+// ---------------------------------------------------------------------------
+// This is a global switch: while the patch is in place EVERY signature amfid
+// validates is reported valid and Apple-signed. A per-path / per-cdhash
+// allowlist cannot be reproduced without the debugger entitlements above,
+// because there is no way to run a decision per validation -- that requires
+// interrupting amfid, which is exactly what is gated. Do not describe this
+// tool as scoped to a path or a binary; it is not.
+//
+// The compensating control is time, not scope. `exec` holds the patch only for
+// as long as the launch needs it, which is why vphone-cli uses that mode and
+// why `on` exists mainly for debugging.
+//
+// The patch is made through a copy-on-write mapping, so it affects only amfid's
+// private copy and never touches the shared cache on disk. It therefore does
+// not survive a reboot, and `off` restores by writing this process's own
+// (unmodified) bytes back -- there is no state file to lose.
+//
+// Requires: root, and SIP with debugging restrictions disabled
+// (`csrutil enable --without debug`). Same prerequisites the rest of the
+// project already has.
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <signal.h>
+#include <unistd.h>
+#include <errno.h>
+#include <sys/wait.h>
+#include <libproc.h>
+#include <dlfcn.h>
+#include <objc/runtime.h>
+#include <mach/mach.h>
+#include <mach/mach_vm.h>
+
+#define AMFID_PATH "/usr/libexec/amfid"
+#define AMFI_FRAMEWORK \
+ "/System/Library/PrivateFrameworks/AppleMobileFileIntegrity.framework/AppleMobileFileIntegrity"
+#define VALIDATOR_CLASS "AMFIPathValidator_macos"
+
+#define PAGE_SIZE_16K 0x4000ULL
+#define SCAN_INSNS 0x800 // how far into a method body to look for its epilogue
+#define EPILOGUE_WINDOW 24 // instructions before the epilogue that may set up the result
+
+#define INSN_RETAB 0xd65f0fffu
+#define INSN_RET 0xd65f03c0u
+#define INSN_MOV_W0_1 0x52800020u
+
+// LDRB w<t>, [x<n>, #imm12] — unsigned offset, scale 1.
+#define LDRB_BASE(imm12) (0x39400000u | ((uint32_t)(imm12) << 10))
+#define LDRB_MASK 0xFFFFFC00u
+// MOV x0, x<m> is ORR x0, xzr, x<m>.
+#define MOV_X0_FROM(m) (0xAA0003E0u | ((uint32_t)(m) << 16))
+// MOVZ w<d>, #1
+#define MOVZ_W_1(d) (0x52800000u | (1u << 5) | (uint32_t)(d))
+
+// --------------------------------------------------------------------------
+
+typedef struct {
+ const char *name;
+ mach_vm_address_t addr; // address in the shared cache, valid in every process
+ uint32_t want[2]; // what the patched form looks like
+ int words;
+} site_t;
+
+static mach_port_t g_task = MACH_PORT_NULL;
+static site_t g_sites[2];
+static int g_nsites = 0;
+static int g_applied = 0;
+
+static void die(const char *what, kern_return_t kr) {
+ fprintf(stderr, "error: %s: %s\n", what, mach_error_string(kr));
+ exit(1);
+}
+
+static pid_t find_amfid(void) {
+ pid_t pids[8192];
+ int n = proc_listpids(PROC_ALL_PIDS, 0, pids, (int)sizeof(pids)) / (int)sizeof(pid_t);
+ char path[PROC_PIDPATHINFO_MAXSIZE];
+ for (int i = 0; i < n; i++)
+ if (pids[i] > 0 && proc_pidpath(pids[i], path, sizeof(path)) > 0 &&
+ strcmp(path, AMFID_PATH) == 0) return pids[i];
+ return -1;
+}
+
+static Class validator_class(void) {
+ static Class cls = Nil;
+ if (cls) return cls;
+ if (!dlopen(AMFI_FRAMEWORK, RTLD_NOW)) {
+ fprintf(stderr, "error: dlopen AppleMobileFileIntegrity: %s\n", dlerror());
+ exit(1);
+ }
+ cls = objc_getClass(VALIDATOR_CLASS);
+ if (!cls) { fprintf(stderr, "error: class %s not found\n", VALIDATOR_CLASS); exit(1); }
+ return cls;
+}
+
+static mach_vm_address_t imp_of(const char *sel_name) {
+ Method m = class_getInstanceMethod(validator_class(), sel_registerName(sel_name));
+ if (!m) { fprintf(stderr, "error: -[%s %s] not found\n", VALIDATOR_CLASS, sel_name); exit(1); }
+ return (mach_vm_address_t)method_getImplementation(m);
+}
+
+static ptrdiff_t ivar_offset(const char *name) {
+ Ivar iv = class_getInstanceVariable(validator_class(), name);
+ if (!iv) { fprintf(stderr, "error: ivar %s not found on %s\n", name, VALIDATOR_CLASS); exit(1); }
+ return ivar_getOffset(iv);
+}
+
+// --------------------------------------------------------------------------
+// amfid memory
+// --------------------------------------------------------------------------
+
+static void read_amfid(mach_vm_address_t addr, void *buf, size_t len) {
+ mach_vm_size_t got = 0;
+ kern_return_t kr = mach_vm_read_overwrite(g_task, addr, len, (mach_vm_address_t)buf, &got);
+ if (kr != KERN_SUCCESS) die("mach_vm_read_overwrite", kr);
+}
+
+// Writing forces the shared-cache page to be copied into amfid privately, so
+// every other process — including this one — keeps seeing the pristine code.
+static void write_amfid(mach_vm_address_t addr, const uint32_t *words, int n) {
+ mach_vm_address_t page = addr & ~(PAGE_SIZE_16K - 1);
+ mach_vm_size_t span = PAGE_SIZE_16K * 2; // a site may straddle a page boundary
+ kern_return_t kr = mach_vm_protect(g_task, page, span, FALSE,
+ VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY);
+ if (kr != KERN_SUCCESS) die("mach_vm_protect(rw|copy)", kr);
+ kr = mach_vm_write(g_task, addr, (vm_offset_t)words, (mach_msg_type_number_t)(n * 4));
+ if (kr != KERN_SUCCESS) die("mach_vm_write", kr);
+ kr = mach_vm_protect(g_task, page, span, FALSE, VM_PROT_READ | VM_PROT_EXECUTE);
+ if (kr != KERN_SUCCESS) die("mach_vm_protect(rx)", kr);
+}
+
+// --------------------------------------------------------------------------
+// Locating the patch sites
+// --------------------------------------------------------------------------
+
+// Walk validateWithError: to its single epilogue, find which register feeds x0,
+// then find the load of self->_isValid that defines that register.
+static void locate_validate_site(site_t *out) {
+ mach_vm_address_t imp = imp_of("validateWithError:");
+ const uint32_t *code = (const uint32_t *)imp; // pristine, in our own mapping
+ ptrdiff_t off = ivar_offset("_isValid");
+
+ int ret_idx = -1;
+ for (int i = 0; i < SCAN_INSNS; i++)
+ if (code[i] == INSN_RETAB || code[i] == INSN_RET) { ret_idx = i; break; }
+ if (ret_idx < 0) {
+ fprintf(stderr, "error: no epilogue in the first %d instructions of "
+ "validateWithError: — this macOS build is not supported\n", SCAN_INSNS);
+ exit(1);
+ }
+
+ // Which register is returned? Look for `mov x0, x<m>` just before the epilogue.
+ int result_reg = -1;
+ for (int i = ret_idx; i >= 0 && i > ret_idx - EPILOGUE_WINDOW; i--) {
+ for (int m = 0; m < 31; m++)
+ if (code[i] == MOV_X0_FROM(m)) { result_reg = m; break; }
+ if (result_reg >= 0) break;
+ }
+ if (result_reg < 0) {
+ fprintf(stderr, "error: could not find the register feeding x0 before the epilogue\n");
+ exit(1);
+ }
+
+ // And where does that register come from? `ldrb w<result>, [x<n>, #_isValid]`.
+ int idx = -1;
+ for (int i = ret_idx; i >= 0 && i > ret_idx - EPILOGUE_WINDOW; i--) {
+ if ((code[i] & LDRB_MASK) == LDRB_BASE(off) && (int)(code[i] & 0x1F) == result_reg) {
+ idx = i;
+ break;
+ }
+ }
+ if (idx < 0) {
+ fprintf(stderr, "error: the return value is not a load of _isValid (+0x%lx) — "
+ "this macOS build is not supported\n", (long)off);
+ exit(1);
+ }
+
+ out->name = "validateWithError: -> always valid";
+ out->addr = imp + (mach_vm_address_t)idx * 4;
+ out->want[0] = MOVZ_W_1(result_reg);
+ out->words = 1;
+
+ printf(" validateWithError: 0x%llx epilogue +0x%x, returns w%d\n",
+ (unsigned long long)imp, ret_idx * 4, result_reg);
+ printf(" _isValid ivar +0x%lx\n", (long)off);
+ printf(" site 0x%llx %08x (ldrb w%d, [x%d, #0x%lx]) -> %08x (mov w%d, #1)\n",
+ (unsigned long long)out->addr, code[idx], result_reg,
+ (int)((code[idx] >> 5) & 0x1F), (long)off, out->want[0], result_reg);
+}
+
+static void locate_isapple_site(site_t *out) {
+ mach_vm_address_t imp = imp_of("isApple");
+ out->name = "isApple -> always true";
+ out->addr = imp;
+ out->want[0] = INSN_MOV_W0_1;
+ out->want[1] = INSN_RET;
+ out->words = 2;
+ printf(" isApple 0x%llx -> %08x %08x (mov w0, #1; ret)\n",
+ (unsigned long long)imp, out->want[0], out->want[1]);
+}
+
+// --------------------------------------------------------------------------
+// Apply / restore
+// --------------------------------------------------------------------------
+
+// A site counts as patched when amfid's copy matches what we would write.
+static int site_is_patched(const site_t *s) {
+ uint32_t cur[2] = {0, 0};
+ read_amfid(s->addr, cur, (size_t)s->words * 4);
+ for (int i = 0; i < s->words; i++)
+ if (cur[i] != s->want[i]) return 0;
+ return 1;
+}
+
+static void apply_all(void) {
+ for (int i = 0; i < g_nsites; i++) write_amfid(g_sites[i].addr, g_sites[i].want, g_sites[i].words);
+ g_applied = 1;
+}
+
+// The pristine bytes are simply the ones still mapped in this process, since the
+// patch only ever touched amfid's private copy.
+static void restore_all(void) {
+ if (!g_nsites) return;
+ for (int i = 0; i < g_nsites; i++) {
+ const uint32_t *pristine = (const uint32_t *)g_sites[i].addr;
+ write_amfid(g_sites[i].addr, pristine, g_sites[i].words);
+ }
+ g_applied = 0;
+}
+
+// Set once `exec` has forked, so a signal can be passed on before we go.
+static volatile pid_t g_child = 0;
+
+static void restore_on_signal(int sig) {
+ if (g_applied) restore_all();
+ // Forward first, then leave. Without this a Ctrl-C at the terminal takes
+ // down the supervisor and leaves the guest running with no parent, which
+ // looks exactly like a hang.
+ if (g_child > 0) kill(g_child, sig);
+ _exit(128 + sig);
+}
+
+static void restore_at_exit(void) {
+ if (g_applied) restore_all();
+}
+
+static void locate_all(void) {
+ printf("resolving patch sites (shared cache, same addresses in every process):\n");
+ locate_validate_site(&g_sites[0]);
+ locate_isapple_site(&g_sites[1]);
+ g_nsites = 2;
+}
+
+static void attach(void) {
+ if (geteuid() != 0) { fprintf(stderr, "error: must run as root\n"); exit(1); }
+ pid_t pid = find_amfid();
+ if (pid < 0) { fprintf(stderr, "error: amfid is not running\n"); exit(1); }
+ kern_return_t kr = task_for_pid(mach_task_self(), pid, &g_task);
+ if (kr != KERN_SUCCESS) {
+ fprintf(stderr, "error: task_for_pid(%d): %s\n", pid, mach_error_string(kr));
+ fprintf(stderr, " needs root and `csrutil enable --without debug`\n");
+ exit(1);
+ }
+ printf("amfid pid %d\n", pid);
+}
+
+static void usage(const char *argv0) {
+ fprintf(stderr,
+ "usage: sudo %s <command>\n"
+ "\n"
+ " status report whether amfid is currently patched\n"
+ " on patch amfid and exit (stays until `off` or reboot)\n"
+ " off restore amfid\n"
+ " exec [--hold N] [--detach] -- <path>...\n"
+ " patch, run <path>, restore. Without --hold the patch\n"
+ " stays until the command exits. With it, the patch is\n"
+ " removed after N seconds but the command is still\n"
+ " supervised, so its exit status and signals reach you.\n"
+ " --detach (needs --hold) returns as soon as the patch\n"
+ " is removed and leaves the command running.\n"
+ " <path> must be an absolute path: there is no PATH\n"
+ " lookup.\n"
+ "\n"
+ "While patched, EVERY signature amfid checks is reported valid and\n"
+ "Apple-signed -- this is a global switch, not an allowlist. Prefer\n"
+ "`exec`, which keeps the window as short as the launch it is covering.\n",
+ argv0);
+}
+
+int main(int argc, char **argv) {
+ setvbuf(stdout, NULL, _IONBF, 0);
+ if (argc < 2) { usage(argv[0]); return 2; }
+ const char *cmd = argv[1];
+
+ if (!strcmp(cmd, "status")) {
+ attach();
+ locate_all();
+ int n = 0;
+ printf("\n");
+ for (int i = 0; i < g_nsites; i++) {
+ int p = site_is_patched(&g_sites[i]);
+ n += p;
+ printf(" %-36s %s\n", g_sites[i].name, p ? "PATCHED" : "clean");
+ }
+ printf("\namfid is %s\n", n == g_nsites ? "PATCHED (bypass active)"
+ : n == 0 ? "clean (no bypass)"
+ : "PARTIALLY patched — run `off`");
+ return n == g_nsites ? 0 : (n == 0 ? 1 : 2);
+ }
+
+ if (!strcmp(cmd, "on")) {
+ attach();
+ locate_all();
+ apply_all();
+ g_applied = 0; // deliberately persistent: do not restore at exit
+ printf("\namfid patched. Run `%s off` when you are done.\n", argv[0]);
+ return 0;
+ }
+
+ if (!strcmp(cmd, "off")) {
+ attach();
+ locate_all();
+ restore_all();
+ printf("\namfid restored.\n");
+ return 0;
+ }
+
+ if (!strcmp(cmd, "exec")) {
+ int i = 2, hold = -1, detach = 0;
+ while (i < argc) {
+ if (!strcmp(argv[i], "--hold")) {
+ if (i + 1 >= argc) { usage(argv[0]); return 2; }
+ hold = atoi(argv[i + 1]);
+ i += 2;
+ } else if (!strcmp(argv[i], "--detach")) {
+ detach = 1;
+ i += 1;
+ } else {
+ break;
+ }
+ }
+ if (detach && hold < 0) {
+ fprintf(stderr, "error: --detach requires --hold\n");
+ return 2;
+ }
+ if (i < argc && !strcmp(argv[i], "--")) i++;
+ if (i >= argc) { usage(argv[0]); return 2; }
+
+ attach();
+ locate_all();
+ signal(SIGINT, restore_on_signal);
+ signal(SIGTERM, restore_on_signal);
+ signal(SIGHUP, restore_on_signal);
+ atexit(restore_at_exit);
+ apply_all();
+ printf("\n>>> %s\n", argv[i]);
+
+ pid_t child = fork();
+ if (child < 0) { perror("fork"); restore_all(); return 1; }
+ g_child = child;
+ if (child == 0) {
+ // execv, not execvp: a PATH lookup here would resolve the target
+ // through the environment, and the whole point of the launch path
+ // is that vphone-cli hands us a fixed path inside its own bundle.
+ // It is also what the admission rule's source scan looks for.
+ execv(argv[i], &argv[i]);
+ fprintf(stderr, "exec %s: %s\n", argv[i], strerror(errno));
+ _exit(127);
+ }
+
+ int status = 0;
+
+ // The window only has to cover the launch, because amfid's verdict is
+ // taken at exec. So --hold restores early and then goes right back to
+ // supervising: the guest keeps running with a clean amfid, and its exit
+ // status and signals still reach whoever started us. Detaching instead
+ // would close the window just as early but throw that away, which is
+ // why it is opt-in rather than what --hold does by itself.
+ if (hold >= 0) {
+ sleep((unsigned)hold);
+ restore_all();
+ printf("<<< held %ds; amfid restored\n", hold);
+ if (detach) {
+ printf("detached; pid %d keeps running\n", (int)child);
+ return 0;
+ }
+ }
+
+ while (waitpid(child, &status, 0) < 0 && errno == EINTR) {}
+ printf("<<< child exited with status %d\n", WEXITSTATUS(status));
+ if (g_applied) {
+ restore_all();
+ printf("amfid restored.\n");
+ }
+ return WEXITSTATUS(status);
+ }
+
+ usage(argv[0]);
+ return 2;
+}
diff --git a/sources/vphone-vm/main.swift b/sources/vphone-vm/main.swift
new file mode 100644
index 00000000..aa1aa03b
--- /dev/null
+++ b/sources/vphone-vm/main.swift
@@ -0,0 +1,17 @@
+// vphone-vm — the process that actually runs a guest.
+//
+// This is the only binary in the project signed with the private
+// virtualization entitlements (sources/vphone.entitlements), and it is
+// deliberately the smallest thing that can hold them: it parses the boot
+// options, becomes an NSApplication, and hands off to VPhoneAppDelegate.
+// Everything a user types goes through vphone-cli, which carries no
+// entitlements at all and starts this binary for the boot.
+//
+// It takes the boot options directly rather than a `boot` subcommand — this
+// binary has exactly one job, so there is nothing to select between.
+
+import ArgumentParser
+import VPhoneCore
+import VPhoneVMKit
+
+VPhoneGuestApp.run(VPhoneBootCLI.parseOrExit())