Run a virtual iPhone on an Apple Silicon Mac.
Swift
Load the camera hooks without a bootstrap and add the environment update
Lakr233fc57dca56bc6
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex 1ece40c3..d1287e7f 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -27,6 +27,20 @@> second run. The Preboot DT rewrite succeeded on a copy and was likewise> unchanged on a second run. The original VM disk was not modified or booted.+> **Camera hooks and environment update (2026-09-25; not yet verified in a+> guest):** `cfw install` also places `libvcamcaptured.dylib` and+> `libcamfix.dylib` in `/usr/lib`. SystemHook treats+> `/usr/libexec/cameracaptured` as an injection target and loads+> `/usr/lib/libvcamcaptured.dylib` there, and loads `/usr/lib/libcamfix.dylib`+> into app processes that already have AVFoundation loaded. Neither needs+> ElleKit or a bootstrap: both hooks install their own Objective-C method+> replacements. A missing library is skipped silently; other load failures are+> logged to `vphone-systemhook.log`. A running guest receives changed copies of+> all four `/usr/lib` libraries through the vphoned environment update+> (`Research/vphoned_http_api.md`). Validation: `processes.list` shows+> `cameracaptured`, `vphone-systemhook.log` records `camera-hook=... result=loaded`+> for its PID, and `vcamcaptured.log` shows the hook installing its source.+> **Current launchd hook (2026-09-25; isolated VM verification):**> `cfw install` now places `launchdhook-vphone.dylib` and a diagnostic> `SystemHook-vphone.dylib` in `/usr/lib`, links `/vh` to the launchd hook,diff --git a/Research/Guest/virtual_camera_transport.md b/Research/Guest/virtual_camera_transport.mdindex 84dfbc8e..e8cc5d8e 100644--- a/Research/Guest/virtual_camera_transport.md+++ b/Research/Guest/virtual_camera_transport.md@@ -30,7 +30,10 @@ installation-layout detection. A system log fallback retains diagnostics whenfile logging fails.At the 2026-09-24 transport test, the camera hook dylibs were not installed or-loaded. An initial check of fixed application directories also missed+loaded. Since 2026-09-25, `cfw install` and the vphoned environment update+place both hooks in `/usr/lib`, and SystemHook loads them without a bootstrap;+see the camera hook note in `Research/0_binary_patch_comparison.md`. The+remainder of this section describes the earlier state. An initial check of fixed application directories also missedCamera.app, but a later app registration query found`com.apple.camera` in an application container under`/private/var/containers/Bundle/Application`. The guest component archivediff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.mdindex 20235c5a..040384eb 100644--- a/Research/vphoned_http_api.md+++ b/Research/vphoned_http_api.md@@ -213,6 +213,7 @@ request carries `"force": true`.| Keychain | `keychain.list {class?}`, `add`, `delete`, `get`, `update`, `database` || Packages (read-only) | `packages.list`, `status`, `info {path}`, `compare`, `tweaks`, `repos` || Bootstrap | `bootstrap.install {layout}`, `bootstrap.status`, `bootstrap.inspect`, `bootstrap.uninstall {jbroot, force}`, `bootstrap.firmware` (see above) |+| Environment | `environment.status` (SHA-256 of each vphone library in `/usr/lib`, or null when absent, plus the staging directory), `environment.install {libraries: [{name, sha256}]}` (see below) |`processes.list` joins icli's kernel process list with `proc_pid_rusage`footprint, resident size and CPU time (`VPhoneDaemon/Native/vphoned_process.m`),@@ -221,11 +222,27 @@ Account passwords, boot logo rendering and package installation, removal andrepository changes are deliberately not exposed. `/v1/health` lists the newareas in `capabilities` (`device_info`, `display`, `audio`, `input_gestures`,`ui_inspection`, `processes`, `services`, `logs`, `network_capture`,-`app_details`, `system_control`, `file_tools`, `packages`) so a host can hide+`app_details`, `system_control`, `file_tools`, `packages`, `environment_update`) so a host can hidepanels an older agent cannot serve. icli failures reach the caller withicli's own error `code` (`failed`, `unavailable`, `device_locked`, …) andmessage.+The environment update keeps `launchdhook-vphone.dylib`,+`SystemHook-vphone.dylib`, `libvcamcaptured.dylib` and `libcamfix.dylib` in+`/usr/lib` in step with the host bundle. After each connection the VM+process compares the guest's hashes with `Contents/Resources/guest-resources`,+uploads the libraries that differ to the staging directory+(`/var/root/Library/Caches/vphone-environment`) and calls+`environment.install`. vphoned accepts only those four names and checks each+SHA-256. When `/` is mounted read-only it runs `/sbin/mount -u -w /`, copies+each library beside its destination, renames it into place with mode 0755+and owner root, and runs `/sbin/mount -u -r /` again; jailbreak detection+reads a writable root as a rootful layout. It stops a running+`cameracaptured` when a camera hook or SystemHook changed, so the next+camera client loads the new hook. The result lists `installed`,+`restarted_pids` and `reboot_required`, which is true when the launchd hook+changed: launchd keeps the copy it mapped at boot.+## Connection failure behaviorA dropped HTTP or WebSocket connection closes only that request channel. Thediff --git a/VPhoneDaemon/Daemon/GuestAPI+Environment.swift b/VPhoneDaemon/Daemon/GuestAPI+Environment.swiftnew file mode 100644index 00000000..81dc7a25--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestAPI+Environment.swift@@ -0,0 +1,130 @@+import Darwin+import Foundation+import IcliSystem++// MARK: - vphone Environment++/// The environment update keeps the libraries cfw install placed in /usr/lib+/// in step with the host bundle. The host uploads each changed library to+/// the staging directory, then asks for the set to be installed.+extension GuestAPI {+ /// Must match `VPhoneGuestEnvironment.libraries` on the host.+ static let environmentLibraries = [+ "launchdhook-vphone.dylib",+ "SystemHook-vphone.dylib",+ "libvcamcaptured.dylib",+ "libcamfix.dylib",+ ]+ static let environmentStaging = "/var/root/Library/Caches/vphone-environment"++ static func executeEnvironment(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {+ switch method {+ case "environment.status":+ let libraries = environmentLibraries.map { name -> [String: Any] in+ let data = try? Data(contentsOf: URL(fileURLWithPath: "/usr/lib/" + name), options: .mappedIfSafe)+ return ["name": name, "sha256": data.map(sha256Hex) ?? NSNull()]+ }+ return ["libraries": libraries, "staging": environmentStaging]+ case "environment.install":+ return try installEnvironment(params)+ default:+ return nil+ }+ }++ private static func installEnvironment(_ params: [String: Any]) throws -> [String: Any] {+ guard let requested = params["libraries"] as? [[String: Any]], !requested.isEmpty else {+ throw GuestAPIError.invalidRequest("libraries must list the uploaded libraries")+ }+ var names: [String] = []+ for entry in requested {+ let name = try string(entry, "name")+ guard environmentLibraries.contains(name) else {+ throw GuestAPIError.invalidRequest("\(name) is not part of the vphone environment")+ }+ let staged = URL(fileURLWithPath: environmentStaging + "/" + name)+ guard let data = try? Data(contentsOf: staged, options: .mappedIfSafe) else {+ throw GuestAPIError.invalidRequest("Upload \(name) to \(environmentStaging) first")+ }+ guard sha256Hex(data) == (try string(entry, "sha256")) else {+ throw GuestAPIError.invalidRequest("\(name) does not match its SHA-256")+ }+ names.append(name)+ }++ try withWritableRoot {+ for name in names {+ try installLibrary(from: environmentStaging + "/" + name, to: "/usr/lib/" + name)+ }+ }+ for name in names {+ unlink(environmentStaging + "/" + name)+ }++ // SystemHook loads the camera daemon hook when cameracaptured starts.+ // launchd starts it again for the next camera client.+ var restarted: [Int] = []+ if names.contains("libvcamcaptured.dylib") || names.contains("SystemHook-vphone.dylib") {+ restarted = stopProcesses(named: "cameracaptured")+ }+ return [+ "installed": names,+ "restarted_pids": restarted,+ // launchd loaded its hook at boot and keeps the old copy mapped.+ "reboot_required": names.contains("launchdhook-vphone.dylib"),+ ]+ }++ /// Runs `body` with `/` writable, then makes a read-only root read-only+ /// again. Jailbreak detection reads a writable root as a rootful layout.+ private static func withWritableRoot(_ body: () throws -> Void) throws {+ var root = statfs()+ guard statfs("/", &root) == 0 else {+ throw GuestAPIError.operationFailed("statfs(/): \(String(cString: strerror(errno)))")+ }+ guard root.f_flags & UInt32(MNT_RDONLY) != 0 else {+ return try body()+ }+ try remountRoot("-w")+ let result = Result { try body() }+ try remountRoot("-r")+ try result.get()+ }++ /// `mode` is `-w` for read-write or `-r` for read-only.+ private static func remountRoot(_ mode: String) throws {+ let arguments = ["/sbin/mount", "-u", mode, "/"]+ var argv = arguments.map { strdup($0) } + [nil]+ defer { argv.forEach { free($0) } }+ var pid: pid_t = 0+ let spawned = posix_spawn(&pid, arguments[0], nil, nil, &argv, environ)+ guard spawned == 0 else {+ throw GuestAPIError.operationFailed("mount -u \(mode) /: \(String(cString: strerror(spawned)))")+ }+ var status: Int32 = 0+ guard waitpid(pid, &status, 0) == pid, status == 0 else {+ throw GuestAPIError.operationFailed("mount -u \(mode) / exited with status \(status)")+ }+ }++ /// Copies onto the system volume first, so the rename that replaces the+ /// library is atomic. Running processes keep the copy they mapped.+ private static func installLibrary(from source: String, to destination: String) throws {+ let temporary = destination + ".vphoned-" + UUID().uuidString+ try FileManager.default.copyItem(atPath: source, toPath: temporary)+ guard chown(temporary, 0, 0) == 0, chmod(temporary, 0o755) == 0, rename(temporary, destination) == 0 else {+ let reason = String(cString: strerror(errno))+ unlink(temporary)+ throw GuestAPIError.operationFailed("Could not install \(destination): \(reason)")+ }+ }++ private static func stopProcesses(named name: String) -> [Int] {+ let rows = (try? listProcesses(filter: name))?["processes"] as? [[String: Any]] ?? []+ return rows.compactMap { row in+ guard row["name"] as? String == name, let pid = row["pid"] as? Int, kill(pid_t(pid), SIGTERM) == 0+ else { return nil }+ return pid+ }+ }+}diff --git a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift b/VPhoneDaemon/Daemon/GuestAPI+Extended.swiftindex 650f9cc5..4e963a8c 100644--- a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+Extended.swift@@ -13,6 +13,7 @@ extension GuestAPI {executeLog,executeAppDetail,executeFileTool,+ executeEnvironment,]for area in areas {if let result = try area(method, params) {diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swiftindex e2369586..21b217ce 100644--- a/VPhoneDaemon/Daemon/GuestAPI.swift+++ b/VPhoneDaemon/Daemon/GuestAPI.swift@@ -36,7 +36,7 @@ enum GuestAPI {return sha256Hex(data)}()- private static func sha256Hex(_ data: Data) -> String {+ static func sha256Hex(_ data: Data) -> String {SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()}@@ -80,6 +80,7 @@ enum GuestAPI {"system_control","file_tools","packages",+ "environment_update",],]}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex 1527f72f..4c0f57bb 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -254,7 +254,7 @@ struct VPhoneCustomFirmwareInstaller {)try patchWatchdog(system: system, work: work)try installVphoned(system: system, work: work)- try installLaunchHook(system: system)+ try installEnvironment(system: system)try patchMachO(system: system,work: work,@@ -382,8 +382,10 @@ struct VPhoneCustomFirmwareInstaller {try replace(temp, at: launchd, mode: 0o644)}- private func installLaunchHook(system: URL) throws {- for name in ["launchdhook-vphone.dylib", "SystemHook-vphone.dylib"] {+ // The launchd hook, SystemHook and the camera hooks. SystemHook loads the+ // camera hooks from /usr/lib without a bootstrap or tweak loader.+ private func installEnvironment(system: URL) throws {+ for name in VPhoneGuestEnvironment.libraries {let source = try VPhoneGuestBinaries.resolve(name)try replace(source, at: system.appendingPathComponent("usr/lib/\(name)"), mode: 0o755)}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swiftindex 841c764e..7d9a971b 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift@@ -116,6 +116,9 @@ final class VPhoneGuestControl {isConnected = trueprint("[control] connected to vphoned HTTP API (iOS \(guestIOSVersion ?? "?"))")onConnect?(guestCapabilities)+ if capabilities.contains("environment_update") {+ Task { await syncEnvironment() }+ }}} catch {if !isConnected {diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlEnvironment.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlEnvironment.swiftnew file mode 100644index 00000000..2e53b4de--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlEnvironment.swift@@ -0,0 +1,72 @@+import CryptoKit+import Foundation+import VPhoneCoreKit++// MARK: - vphone Environment++/// Keeps the guest's /usr/lib hooks in step with this bundle, the way the+/// probe keeps vphoned in step: compare hashes, upload what differs, install.+extension VPhoneGuestControl {+ struct EnvironmentUpdate {+ let installed: [String]+ let rebootRequired: Bool+ }++ /// Uploads each bundled library whose hash differs from the guest's copy,+ /// then installs them together. An up-to-date guest installs nothing.+ func updateEnvironment() async throws -> EnvironmentUpdate {+ guard guestCapabilities.contains("environment_update") else {+ throw ControlError.unsupportedCapability("environment_update")+ }+ let status = try await call("environment.status")+ guard let staging = status["staging"] as? String,+ let rows = status["libraries"] as? [[String: Any]]+ else {+ throw ControlError.protocolError("missing environment status")+ }+ let guestHashes = Dictionary(+ rows.compactMap { row -> (String, String)? in+ guard let name = row["name"] as? String, let hash = row["sha256"] as? String else { return nil }+ return (name, hash)+ },+ uniquingKeysWith: { first, _ in first },+ )+ typealias Library = (name: String, data: Data, hash: String)+ let changed = try VPhoneGuestEnvironment.libraries.compactMap { name -> Library? in+ let data = try Data(contentsOf: VPhoneGuestBinaries.resolve(name), options: .mappedIfSafe)+ let hash = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()+ return guestHashes[name] == hash ? nil : (name, data, hash)+ }+ guard !changed.isEmpty else {+ return EnvironmentUpdate(installed: [], rebootRequired: false)+ }++ try await createDirectory(path: staging)+ for library in changed {+ try await uploadFile(path: staging + "/" + library.name, data: library.data)+ }+ let result = try await call(+ "environment.install",+ params: ["libraries": changed.map { ["name": $0.name, "sha256": $0.hash] }],+ )+ return EnvironmentUpdate(+ installed: result["installed"] as? [String] ?? [],+ rebootRequired: result["reboot_required"] as? Bool ?? false,+ )+ }++ /// Runs once per connection. A failure is logged and leaves the guest's+ /// current libraries in place.+ func syncEnvironment() async {+ do {+ let update = try await updateEnvironment()+ guard !update.installed.isEmpty else { return }+ print("[environment] installed \(update.installed.joined(separator: ", "))")+ if update.rebootRequired {+ print("[environment] restart the guest to load the new launchd hook")+ }+ } catch {+ print("[environment] update failed: \(error)")+ }+ }+}diff --git a/VPhoneGuestComponents/README.md b/VPhoneGuestComponents/README.mdindex 00968e1a..24478476 100644--- a/VPhoneGuestComponents/README.md+++ b/VPhoneGuestComponents/README.md@@ -14,7 +14,11 @@ tweak filter plists, and the GPU provenance note:| PCC GPU driver | `gpu/README.md` (source and extraction flow; no Apple binary) |The archive is a local build artifact, not a VM bootstrap. `cfw install` places-both hooks in `/usr/lib`. After a bootstrap installs ElleKit, the launchd hook+the launchd hook, SystemHook and both camera hooks in `/usr/lib`, and the+vphoned environment update replaces changed copies in a running guest. SystemHook+loads `libvcamcaptured.dylib` into `/usr/libexec/cameracaptured` and+`libcamfix.dylib` into apps that have AVFoundation loaded; neither camera hook+needs ElleKit or a bootstrap. After a bootstrap installs ElleKit, the launchd hookinserts SystemHook into `xpcproxy`, bootstrap executables, and apps starteddirectly by launchd. Inside `xpcproxy`, SystemHook carries itself into thefinal executable through `posix_spawnp`. Injected App and bootstrap processesdiff --git a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.cindex 3529fd13..14f4d5fc 100644--- a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c+++ b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c@@ -29,11 +29,19 @@ static int vpIsAppPath(const char *path) {return path && path[0] == '/' && strstr(path, ".app/") != NULL;}+// The camera daemon hook serves every camera client, so the daemon is a+// target even though it is neither an app nor a bootstrap executable.+static int vpIsCameraDaemon(const char *path) {+ static const char suffix[] = "/usr/libexec/cameracaptured";+ size_t length = path ? strlen(path) : 0;+ return length >= sizeof(suffix) - 1 && strcmp(path + length - (sizeof(suffix) - 1), suffix) == 0;+}+static int vpIsInjectionTarget(const char *path) {if (!path)return 0;const char *root = getenv("VPHONE_JB_ROOT");- return vpIsBootstrapPath(path, root) || vpIsAppPath(path) ||+ return vpIsBootstrapPath(path, root) || vpIsAppPath(path) || vpIsCameraDaemon(path) ||(vpInBootstrap && path[0] != '/');}@@ -127,6 +135,35 @@ static int vpExecve(const char *path, char *const argv[], char *const envp[]) {return status;}+// cfw install and the environment update place the camera hooks in /usr/lib.+// They need no tweak loader: each installs its own Objective-C hooks.+#define VP_CAMERA_DAEMON_HOOK "/usr/lib/libvcamcaptured.dylib"+#define VP_CAMERA_APP_HOOK "/usr/lib/libcamfix.dylib"+#define VP_AVFOUNDATION "/System/Library/Frameworks/AVFoundation.framework/AVFoundation"++// A missing library is expected and stays quiet; anything else is logged.+static void vpLoadLibrary(const char *kind, const char *library) {+ if (access(library, R_OK) != 0) {+ int accessError = errno;+ if (accessError == ENOENT)+ return;+ int fd = vpOpenLog("vphone-systemhook.log");+ if (fd >= 0) {+ dprintf(fd, "pid=%d %s=%s access_errno=%d\n", getpid(), kind, library, accessError);+ close(fd);+ }+ return;+ }+ void *loaded = dlopen(library, RTLD_NOW | RTLD_LOCAL);+ int fd = vpOpenLog("vphone-systemhook.log");+ if (fd >= 0) {+ const char *error = loaded ? NULL : dlerror();+ dprintf(fd, "pid=%d %s=%s result=%s\n", getpid(), kind, library,+ loaded ? "loaded" : error ? error : "unknown error");+ close(fd);+ }+}+// xpcproxy needs this bridge because launchd only spawns the proxy, not its target.__attribute__((constructor)) static void vpLogProcess(void) {char path[PATH_MAX];@@ -152,34 +189,22 @@ __attribute__((constructor)) static void vpLogProcess(void) {if (strcmp(name, "vphoned") == 0 || strcmp(name, "logd") == 0 ||strcmp(name, "notifyd") == 0 || strcmp(name, "usermanagerd") == 0)return;+ if (vpIsCameraDaemon(path)) {+ vpLoadLibrary("camera-hook", VP_CAMERA_DAEMON_HOOK);+ return;+ }+ if (!vpInBootstrap && !vpIsAppPath(path))+ return;+ if (vpIsAppPath(path) && dlopen(VP_AVFOUNDATION, RTLD_LAZY | RTLD_NOLOAD))+ vpLoadLibrary("camera-hook", VP_CAMERA_APP_HOOK);const char *root = getenv("VPHONE_JB_ROOT");if (!root || !*root)root = "/var/jb";- if (!vpInBootstrap && !vpIsAppPath(path))- return;char loader[PATH_MAX];int used = snprintf(loader, sizeof(loader), "%s/usr/lib/TweakLoader.dylib", root);if (used <= 0 || (size_t)used >= sizeof(loader))return;- if (access(loader, R_OK) != 0) {- int accessError = errno;- if (accessError != ENOENT) {- fd = vpOpenLog("vphone-systemhook.log");- if (fd >= 0) {- dprintf(fd, "pid=%d tweakloader=%s access_errno=%d\n", getpid(), loader, accessError);- close(fd);- }- }- return;- }- void *loaded = dlopen(loader, RTLD_NOW | RTLD_LOCAL);- fd = vpOpenLog("vphone-systemhook.log");- if (fd >= 0) {- const char *error = loaded ? NULL : dlerror();- dprintf(fd, "pid=%d tweakloader=%s result=%s\n", getpid(), loader,- loaded ? "loaded" : error ? error : "unknown error");- close(fd);- }+ vpLoadLibrary("tweakloader", loader);}int vphone_systemhook_version(void) { return 1; }diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swiftnew file mode 100644index 00000000..bb7d9044--- /dev/null+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift@@ -0,0 +1,15 @@+import Foundation++// MARK: - VPhoneGuestEnvironment++/// The libraries vphone keeps in the guest's /usr/lib. cfw install places them+/// on the system volume, and the environment update replaces changed ones in a+/// running guest. vphoned keeps the same list in `GuestAPI+Environment.swift`.+public enum VPhoneGuestEnvironment {+ public static let libraries = [+ "launchdhook-vphone.dylib",+ "SystemHook-vphone.dylib",+ "libvcamcaptured.dylib",+ "libcamfix.dylib",+ ]+}