Run a virtual iPhone on an Apple Silicon Mac.
Swift
test dylib injection without insert_dylib submodule
Lakre3ad481bddc3
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 985c897a..00fa32fe 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -17,7 +17,6 @@ jobs:steps:- name: Checkoutuses: actions/checkout@v4- with:- name: Toolchain versionsrun: |diff --git a/.gitmodules b/.gitmodulesdeleted file mode 100644index 31b9b0b9..00000000--- a/.gitmodules+++ /dev/null@@ -1,3 +0,0 @@-[submodule "scripts/repos/insert_dylib"]- path = Scripts/Repos/InsertDylib- url = https://github.com/tyilo/insert_dylib.gitdiff --git a/AGENTS.md b/AGENTS.mdindex 5085554d..051a8f5a 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -12,7 +12,7 @@ Virtual iPhone boot tool using Apple's Virtualization.framework with PCC researc- **Restore:** `vphone-cli restore`, in process. Vendored libirecovery + idevicerestore (`Sources/MobileRecoveryCore`, `Sources/MobileRestoreCore`) over the `AppleMobileDeviceLibrary` xcframeworks. No interpreter, no environment to provision, no setup step. See `research/restore/p2_restore_off_python.md`.- **Platform:** macOS 15+ (Sequoia). `vphone-vm` needs amfid to accept its private entitlements: either SIP off with `amfi_get_out_of_my_way=1`, or SIP on (`--without debug`) plus an allowlist bypass the user runs. Both are in `docs/guides/host-setup.md`; neither is installed by this project.- **Language:** Swift 6.0 (SwiftPM), private APIs via [Dynamic](https://github.com/mhdhejazi/Dynamic). This package's own manifest is `swift-tools-version:6.0`, but the **toolchain floor is Swift 6.2**: `libcapstone-spm` declares 6.2 so that it can reach `CSetting.disableWarning` instead of `.unsafeFlags`, which is what lets it be depended on by version at all.-- **Dependencies:** Host and guest SwiftPM packages resolve dependencies by URL and version; `Package.resolved` pins the full graphs. The only git submodule is `Scripts/Repos/InsertDylib`, a build-time test reference. **No Python anywhere, and no Homebrew package at runtime** — see Tiers below.+- **Dependencies:** Host and guest SwiftPM packages resolve dependencies by URL and version; `Package.resolved` pins the full graphs. There are no git submodules. **No Python anywhere, and no Homebrew package at runtime** — see Tiers below.- **Tiers.** Three environments run code here and the rules differ. **build** (the machine that builds the `.app`) may use Xcode, `xcrun`, clang, swift, git and Homebrew. **dist** (the shipped `.app`, on a clean macOS) may use `/usr/lib`, `/System` and the bundle — nothing else, no `PATH` lookup. **guest** (inside the VM) is out of host self-containment scope. Every script declares its tier on **line 2** (`# vphone-tier: dist`); `Scripts/dist_manifest.sh` reads those and is what `Scripts/build.sh` stages from, so a script that declares nothing ships nowhere. `Scripts/check_aux.sh` runs the admission gates. The dist tier's registered-exception list is **empty** and a release requires it to stay that way.## Workflow Rules@@ -182,9 +182,7 @@ Scripts/ # Build scripts and payloads only; no runtime├── build.sh [b] # Compile, sign and bundle├── dist_manifest.sh [b] # Payload allowlist staged by build.sh├── check_aux.sh [b] # The self-containment admission gates-├── setup_tools.sh [b] # Builds insert_dylib, the Mach-O byte-parity test reference-├── VPhoned/ # Guest SwiftNIO/IcliKit package plus native installer/keychain/camera code-└── Repos/ # Toolchain source (git submodule: InsertDylib)+└── VPhoned/ # Guest SwiftNIO/IcliKit package plus native installer/keychain/camera codeSiblings/ # Guest component sources/provenance; separate package├── CamFix/ VCamCaptured/ # Camera hooks and filter plistsdiff --git a/Package.swift b/Package.swiftindex d8312183..c72635a6 100644--- a/Package.swift+++ b/Package.swift@@ -298,6 +298,7 @@ let package = Package(name: "FirmwarePatcherTests",dependencies: ["FirmwarePatcher"],path: "Tests/FirmwarePatcherTests",+ exclude: ["Fixtures"],),.testTarget(name: "VPhoneCoreTests",diff --git a/README.md b/README.mdindex 6c69069e..6fe0c8ed 100644--- a/README.md+++ b/README.md@@ -41,7 +41,7 @@ A distributed `.app` uses macOS system tools and its own bundled binaries; it doBuilding from source needs Xcode, including its iPhoneOS SDK for vphoned:```sh-git clone --recurse-submodules https://github.com/Lakr233/vphone-cli.git+git clone https://github.com/Lakr233/vphone-cli.gitcd vphone-clizsh Scripts/build.sh.build/release/vphone-cli --helpdiff --git a/Scripts/Repos/InsertDylib b/Scripts/Repos/InsertDylibdeleted file mode 160000index eb727816..00000000--- a/Scripts/Repos/InsertDylib+++ /dev/null@@ -1 +0,0 @@-Subproject commit eb7278162af8fcc372e7f2946a2dee6a386b17d8diff --git a/Scripts/build.sh b/Scripts/build.shindex 81111365..346d420d 100755--- a/Scripts/build.sh+++ b/Scripts/build.sh@@ -203,8 +203,8 @@ rm -rf "${RES}/scripts" "${RES}/guest" "${RES}/tools" "${RES}/.tools" \mkdir -p "${RES}/scripts"# An ALLOWLIST, from each script's own `# vphone-tier:` line. This used to be a# list of exclusions, which meant anything new shipped by default — and so the-# .app carried build.sh, check_aux.sh and setup_tools.sh, the last of which runs-# `brew install`. See Scripts/dist_manifest.sh for the three tiers.+# .app carried build.sh, check_aux.sh and the old setup_tools.sh, which once+# ran `brew install`. See Scripts/dist_manifest.sh for the three tiers.zsh Scripts/dist_manifest.sh | sed '/^vphoned\//d' | rsync -a --files-from=- Scripts/ "${RES}/scripts/"mkdir -p "${RES}/scripts/vphoned"cp -f Scripts/VPhoned/vphoned.plist Scripts/VPhoned/entitlements.plist "${RES}/scripts/vphoned/"diff --git a/Scripts/check_aux.sh b/Scripts/check_aux.shindex 79d7c6a6..0053b648 100755--- a/Scripts/check_aux.sh+++ b/Scripts/check_aux.sh@@ -80,7 +80,7 @@ typeset -a DIST_REMAINING=(# script execs one.typeset -a BUILD_ALLOWED=(brew xcrun xcodebuild clang swift git rsync- ldid gtar zstd ipsw aria2c wget sshpass trustcache insert_dylib+ ldid gtar zstd ipsw aria2c wget sshpass trustcache)# python3 must never appear on any of these lists. The restore backend was its@@ -231,7 +231,7 @@ check_closure() {# ---------------------------------------------------------------------------# The bundler used to work from a list of EXCLUSIONS, so anything new shipped by# default. That is how the .app came to carry build.sh, check_aux.sh and-# setup_tools.sh alongside the scripts it actually+# build-tier scripts alongside the scripts they actually# needs. It is an allowlist now, and this gate is what keeps it honest: a# build-tier script inside the bundle is a hard failure, because everything in# that tier is allowed to assume a toolchain the dist tier does not have.diff --git a/Scripts/dist_manifest.sh b/Scripts/dist_manifest.shindex a98bd6a3..67d925b0 100755--- a/Scripts/dist_manifest.sh+++ b/Scripts/dist_manifest.sh@@ -18,8 +18,8 @@# build.sh maps the VPhoned plist source files back to the shipped vphoned/ path.# It is an ALLOWLIST derived from those declarations,# which is the point: the bundler used to work from a list of exclusions, so-# anything new shipped by default and the build-only `setup_tools.sh`,-# `build.sh` and `check_aux.sh` all ended up inside the .app. An+# anything new shipped by default and the build-only `build.sh` and+# `check_aux.sh` ended up inside the .app. An# undeclared script now ships nowhere, and says so.## Usage: dist_manifest.sh # the payload, for rsync --files-from@@ -59,7 +59,6 @@ done# vphone-cli itself opens it by name; the greppable proof is in the comment.## What is deliberately ABSENT is as important:-# Repos/ toolchain submodules — build tier, sources only# ../Siblings/ guest sources and GPU provenance; not copied into the# shipped app (GPU extraction runs in native fw prepare)# VPhoned/*.m *.h Vendor/ same, and it is the bulk of Scripts/diff --git a/Scripts/setup_tools.sh b/Scripts/setup_tools.shdeleted file mode 100755index 46da2022..00000000--- a/Scripts/setup_tools.sh+++ /dev/null@@ -1,67 +0,0 @@-#!/bin/zsh-# vphone-tier: build-# setup_tools.sh — the one development tool that is not in this repository.-#-# There is nothing to install any more. This script used to run `brew install`-# for six packages and build two tools from submodules; all of it is gone except-# insert_dylib, which no shipped code runs and which exists only so a test has-# something independent to compare against.-#-# aria2 wget download fallbacks in fw_prepare.sh -> curl, which is macOS-# gnu-tar zstd -> vphone-archive-# ldid-procursus -> `vphone-cli sign`-# openssl@3 only ever linked into the trustcache build below-# sshpass installed for years and invoked by nothing in this repo-# trustcache built, bundled into the .app, and invoked by nothing. The-# trust cache is generated by cryptexctl out of-# /System/Library/SecurityResearch. It was also the last file-# in the bundle linking /opt/homebrew's libcrypto.3.-#-# So: no Homebrew, no interpreter, no environment. `Scripts/build.sh` builds the app.-#-# Run: zsh Scripts/setup_tools.sh before the optional byte-parity test.--set -euo pipefail--SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"-PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"-TOOLS_PREFIX="${TOOLS_PREFIX:-$PROJECT_DIR/.tools}"-REPOS_DIR="$SCRIPT_DIR/Repos"--ensure_repo_submodule() {- local rel_path="$1"- local abs_path="$PROJECT_DIR/$rel_path"-- if [[ ! -e "$abs_path/.git" ]]; then- git -C "$PROJECT_DIR" submodule update --init --recursive "$rel_path"- fi-}--# ── insert_dylib (test reference only) ─────────────────────────-#-# Nothing in the product runs this: `CustomFirmwareInjectDylib` injects the weak load-# command in-process, and the last caller that shelled out was-# scripts/patchers/cfw.py. It is still built because it is the independent-# reference the `CustomFirmwareInjectDylibTests` "matches insert dylib" test compares the Swift injector-# against, byte for byte — that test skips silently when it is missing, which-# is the worst possible way to lose the check.-#-# It is one .c file and one system framework, so this needs clang and nothing-# else. There is no `brew install` left in this script.--echo "insert_dylib (byte-parity reference for CustomFirmwareInjectDylibTests)"--INSERT_DYLIB_BIN="$TOOLS_PREFIX/bin/insert_dylib"-if [[ -x "$INSERT_DYLIB_BIN" ]]; then- echo " Already built: $INSERT_DYLIB_BIN"-else- INSERT_DYLIB_DIR="$REPOS_DIR/InsertDylib"- ensure_repo_submodule "Scripts/Repos/InsertDylib"- echo " Building insert_dylib..."- mkdir -p "$TOOLS_PREFIX/bin"- clang -o "$INSERT_DYLIB_BIN" "$INSERT_DYLIB_DIR/insert_dylib/main.c" -framework Security -O2- echo " Installed: $INSERT_DYLIB_BIN"-fi--echo ""-echo "All tools installed."diff --git a/Sources/FirmwarePatcher/CustomFirmware/CustomFirmwareInjectDylib.swift b/Sources/FirmwarePatcher/CustomFirmware/CustomFirmwareInjectDylib.swiftindex bbfa8e86..714e7098 100644--- a/Sources/FirmwarePatcher/CustomFirmware/CustomFirmwareInjectDylib.swift+++ b/Sources/FirmwarePatcher/CustomFirmware/CustomFirmwareInjectDylib.swift@@ -1,15 +1,13 @@// CustomFirmwareInjectDylib.swift — LC_LOAD_DYLIB / LC_LOAD_WEAK_DYLIB insertion.//-// Replaces the `insert_dylib` binary built from `Scripts/Repos/InsertDylib`,-// whose only caller is the launchdhook injection in `cfw_install_jb.sh` and-// `cfw_install_exp.sh`:+// Replaces the former `insert_dylib` subprocess used for launchdhook injection://// cfw.py inject-dylib "$TEMP_DIR/launchd" "/b"// -> insert_dylib --weak --inplace --all-yes /b <launchd>//-// This is a deliberate behaviour-for-behaviour port, because byte equality with-// the C tool is the only independent check available for it. Two things differ-// on purpose, both in the safe direction, both marked below:+// A host-side test injects a real Objective-C swizzle dylib into a small+// executable and verifies the changed output. Two things differ from the+// former C tool on purpose, both marked below://// 1. `insert_dylib --all-yes` answers "y" to "It doesn't seem like there is// enough empty space. Continue anyway?" and then writes the load commanddiff --git a/Tests/FirmwarePatcherTests/CustomFirmwareMachOTests.swift b/Tests/FirmwarePatcherTests/CustomFirmwareMachOTests.swiftindex b8347ab2..54a28255 100644--- a/Tests/FirmwarePatcherTests/CustomFirmwareMachOTests.swift+++ b/Tests/FirmwarePatcherTests/CustomFirmwareMachOTests.swift@@ -1,18 +1,16 @@// CustomFirmwareMachOTests.swift — Mach-O load-command insertion and code-signature re-attestation.//-// Both modules replace something outside this code, so both are tested against-// it rather than against expectations written down by hand:+// The modules are checked against independent effects://-// * `CustomFirmwareInjectDylib` against `.tools/bin/insert_dylib`, byte for byte, while-// that submodule build is still in the tree.+// * `CustomFirmwareInjectDylib` loads a real Objective-C swizzle dylib into+// a small executable, changing its observed output.// * `CustomFirmwareMachOCodeSignature` against `scripts/patchers/cfw_macho_codesign.py`,// byte for byte. That Python is gone, so what it wrote is frozen in// ``MachOCodeSignGolden`` below — over the real 24A435 `seputil` rather// than a local build product, because a golden is only worth what its// input is reproducible.//-// Those two comparisons are the migration plan's stated gate (P1.1). Everything-// that can be asserted without a reference is asserted unconditionally, first+// Everything that can be asserted without a reference is asserted, first// among them the short tail slot, which is the known regression in independent// re-signing.//@@ -90,16 +88,10 @@ enum MachOFixture {instead of failing"""- static let insertDylib = repositoryRoot.appending(path: ".tools/bin/insert_dylib")-static func exists(_ url: URL) -> Bool {FileManager.default.fileExists(atPath: url.path)}- static var hasInsertDylib: Bool {- exists(insertDylib)- }-static var hasCodesign: Bool {exists(URL(filePath: "/usr/bin/codesign"))}@@ -550,24 +542,54 @@ struct CustomFirmwareInjectDylibTests {}}- /// The migration gate for this half: identical output to the C tool it- /// replaces, on the exact command line the CFW scripts use.- @Test(.enabled(if: MachOFixture.runs && MachOFixture.hasInsertDylib, MachOFixture.missing))- func `matches insert dylib`() throws {- let swiftFile = try MachOFixture.scratchCopy("swift")- let referenceFile = swiftFile.deletingLastPathComponent().appending(path: "reference")- try FileManager.default.copyItem(at: MachOFixture.signedBinary(), to: referenceFile)-- try CustomFirmwareInjectDylib.inject(dylibPath: "/b", into: swiftFile)- let reference = try MachOFixture.run(- MachOFixture.insertDylib,- ["--weak", "--inplace", "--all-yes", "/b", referenceFile.path],- )- try #require(reference.status == 0, "insert_dylib failed: \(reference.output)")-- #expect(- try Data(contentsOf: swiftFile) == Data(contentsOf: referenceFile),- "Swift injection must match insert_dylib byte for byte",+ /// Compile both checked-in sources, then prove that the inserted load+ /// command actually makes dyld run the swizzle before main().+ @Test func `injected Objective-C swizzle changes hello world output`() throws {+ let fixtures = MachOFixture.repositoryRoot+ .appending(path: "Tests/FirmwarePatcherTests/Fixtures/DylibInjection")+ let directory = FileManager.default.temporaryDirectory+ .appending(path: "DylibInjection-\(UUID().uuidString)")+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: directory) }++ let executable = directory.appending(path: "hello")+ let dylib = directory.appending(path: "swizzle.dylib")+ let clang = URL(filePath: "/usr/bin/clang")++ let buildExecutable = try MachOFixture.run(clang, [+ "-fobjc-arc", "-framework", "Foundation", "-Wl,-headerpad,0x4000",+ fixtures.appending(path: "hello.m").path, "-o", executable.path,+ ])+ try #require(buildExecutable.status == 0, "hello fixture: \(buildExecutable.output)")+ let buildDylib = try MachOFixture.run(clang, [+ "-dynamiclib", "-fobjc-arc", "-framework", "Foundation",+ fixtures.appending(path: "swizzle.m").path, "-o", dylib.path,+ ])+ try #require(buildDylib.status == 0, "swizzle fixture: \(buildDylib.output)")++ let before = try MachOFixture.run(executable, [])+ try #require(before.status == 0, "plain hello failed: \(before.output)")+ #expect(before.output == "hello world\n")++ let injections = try CustomFirmwareInjectDylib.inject(+ dylibPath: dylib.path,+ into: executable,+ weak: true,+ policy: .strip,)+ let injection = try #require(injections.first)+ #expect(injections.count == 1)+ #expect(injection.isWeak)+ #expect(MachOFixture.dylibLoadCommands(in: try Data(contentsOf: executable)).contains {+ $0.command == 0x8000_0018 && $0.path == dylib.path+ })++ let sign = try MachOFixture.run(URL(filePath: "/usr/bin/codesign"), [+ "--force", "--sign", "-", "--timestamp=none", executable.path,+ ])+ try #require(sign.status == 0, "signing injected hello: \(sign.output)")+ let after = try MachOFixture.run(executable, [])+ try #require(after.status == 0, "injected hello failed: \(after.output)")+ #expect(after.output == "world hello\n")}}diff --git a/Tests/FirmwarePatcherTests/Fixtures/DylibInjection/hello.m b/Tests/FirmwarePatcherTests/Fixtures/DylibInjection/hello.mnew file mode 100644index 00000000..1ad9afca--- /dev/null+++ b/Tests/FirmwarePatcherTests/Fixtures/DylibInjection/hello.m@@ -0,0 +1,18 @@+#import <Foundation/Foundation.h>++@interface Greeting : NSObject+- (NSString *)message;+@end++@implementation Greeting+- (NSString *)message {+ return @"hello world";+}+@end++int main(void) {+ @autoreleasepool {+ puts([[[Greeting new] message] UTF8String]);+ }+ return 0;+}diff --git a/Tests/FirmwarePatcherTests/Fixtures/DylibInjection/swizzle.m b/Tests/FirmwarePatcherTests/Fixtures/DylibInjection/swizzle.mnew file mode 100644index 00000000..6221b864--- /dev/null+++ b/Tests/FirmwarePatcherTests/Fixtures/DylibInjection/swizzle.m@@ -0,0 +1,22 @@+#import <Foundation/Foundation.h>+#import <objc/runtime.h>++@interface WorldHelloSwizzle : NSObject+- (NSString *)worldHelloMessage;+@end++@implementation WorldHelloSwizzle++ (void)load {+ Class greeting = objc_getClass("Greeting");+ Method original = class_getInstanceMethod(greeting, @selector(message));+ Method replacement = class_getInstanceMethod(self, @selector(worldHelloMessage));+ if (original == NULL || replacement == NULL) {+ abort();+ }+ method_exchangeImplementations(original, replacement);+}++- (NSString *)worldHelloMessage {+ return @"world hello";+}+@enddiff --git a/docs/README_ja.md b/docs/README_ja.mdindex 0254d1bf..75efe667 100644--- a/docs/README_ja.md+++ b/docs/README_ja.md@@ -29,7 +29,7 @@ cloudOS 26.4(`23E5207q`)との組み合わせで、iPhone17,3 の iOS 26.6.2配布 `.app` の実行に Homebrew、Python、Xcode や別の実行環境は不要です。ソースからのビルドには、vphoned をコンパイルするための iPhoneOS SDK を含む Xcode が必要です。```sh-git clone --recurse-submodules https://github.com/Lakr233/vphone-cli.git+git clone https://github.com/Lakr233/vphone-cli.gitcd vphone-clizsh Scripts/build.sh.build/release/vphone-cli host preflightdiff --git a/docs/README_ko.md b/docs/README_ko.mdindex 29c94ced..d94bee41 100644--- a/docs/README_ko.md+++ b/docs/README_ko.md@@ -29,7 +29,7 @@ cloudOS 26.4(`23E5207q`)와 함께 iPhone17,3 iOS 26.6.2(`23G90`), 27.0(`24A435`배포된 `.app` 실행에는 Homebrew, Python, Xcode나 별도의 런타임 환경이 필요하지 않습니다. 소스 빌드에는 vphoned용 iPhoneOS SDK가 포함된 Xcode가 필요합니다.```sh-git clone --recurse-submodules https://github.com/Lakr233/vphone-cli.git+git clone https://github.com/Lakr233/vphone-cli.gitcd vphone-clizsh Scripts/build.sh.build/release/vphone-cli host preflightdiff --git a/docs/README_zh.md b/docs/README_zh.mdindex ebfe76bd..16a85d10 100644--- a/docs/README_zh.md+++ b/docs/README_zh.md@@ -29,7 +29,7 @@ vphone-cli vm launch myphone成品 `.app` 运行时不需要 Homebrew、Python 或 Xcode,也不需要额外安装运行环境。从源码构建则需要 Xcode 的 iPhoneOS SDK,以编译 vphoned:```sh-git clone --recurse-submodules https://github.com/Lakr233/vphone-cli.git+git clone https://github.com/Lakr233/vphone-cli.gitcd vphone-clizsh Scripts/build.sh.build/release/vphone-cli host preflightdiff --git a/research/0_binary_patch_comparison.md b/research/0_binary_patch_comparison.mdindex 27f621c6..cc45e744 100644--- a/research/0_binary_patch_comparison.md+++ b/research/0_binary_patch_comparison.md@@ -416,12 +416,13 @@ and neither changing a byte:* The three idempotence divergences in the section above stand: the Swiftrecognises its own output where the Python double-applies or exits 1.-**Not removed:** `Scripts/Repos/InsertDylib`. Nothing in the product runs it —-`CFWInjectDylib` does the injection in process — but-`CFWMachOTests.matchesInsertDylib` still runs the real binary as an independent-byte-parity reference, gated on its presence. Deleting the submodule would turn-that check into a silent skip rather than a failure. CI no longer initialises it;-`setup_tools.sh` still builds it, relabelled as a test reference.+**Final submodule removed:** `Scripts/Repos/InsertDylib` was retained only for+a byte-parity test after `CustomFirmwareInjectDylib` took over the injection.+That test is replaced with two checked-in Objective-C source fixtures: a+`hello world` executable and a swizzle dylib. The test compiles them, checks the+plain output, injects the dylib with the Swift patcher, re-signs the executable,+and checks that it prints `world hello`. This exercises the actual dyld load+and swizzle without an external test reference or an optional skip.**P1 dropped `capstone`, `keystone-engine` and `pyimg4` from the dependencylist; P2 then deleted the list.** `requirements.txt`, `scripts/setup_venv.sh`,