Run a virtual iPhone on an Apple Silicon Mac.
Swift
Repair vphone guest controls, camera transport, and IcliKit integration
Lakr0394ee6a0fa1
diff --git a/AGENTS.md b/AGENTS.mdindex 73481547..53b342db 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -46,7 +46,7 @@ See `Research/` for detailed firmware pipeline, component origins, patch breakdo- `VPhoneExecutable/VPhoneCommand/VPhoneRestore`: native restore code and tests.- `VPhoneExecutable/VPhoneEscalator`: the AMFI allowlist program, built for arm64e. It is not a general privilege service.- `VPhoneKit`: shared core, archive, and external access kits with their tests.-- `VPhoneDaemon`: guest `vphoned`, native code including `vpregister`, and daemon configuration.+- `VPhoneDaemon`: guest `vphoned`, native operations, and daemon configuration.- `VPhoneGuestComponents`: guest dylibs built by Makefile from the bundle build phase.The `VPhone` scheme puts all shipped Mach-O files in `VPhone.bundle/Contents/MacOS`. Guest configuration is in `Contents/Resources`. Xcode targets have `CODE_SIGNING_ALLOWED=NO`; the bundle build phase signs each binary ad hoc with only its own entitlements, then seals the outer bundle. `VPhoneVirtualization.entitlements` belongs to `vphone-vm`; `VPhoneDaemon.entitlements` belongs to `vphoned`. The bundle and CLI have no private entitlements.diff --git a/Documents/Guides/bundle-integration.md b/Documents/Guides/bundle-integration.mdindex 33251cc6..f1b86bf1 100644--- a/Documents/Guides/bundle-integration.md+++ b/Documents/Guides/bundle-integration.md@@ -12,7 +12,7 @@ executables and resources, not a macOS app or a dynamically loaded plug-in.| `Contents/MacOS/vphone-vm` | VM and window process; private virtualization entitlements || `Contents/MacOS/VPhoneEscalator` | AMFI allowlist tool for the current VM cdhash || `Contents/MacOS/vphoned.signed` | Guest daemon payload with its own entitlements |-| `Contents/MacOS/vpregister` and guest dylibs | Guest installation payloads |+| Guest dylibs in `Contents/MacOS` | Guest installation payloads || `Contents/Resources` | Guest configuration and nonexecutable resources |All executable payloads use ad hoc code signatures. Only the required childdiff --git a/Research/Guest/virtual_camera_transport.md b/Research/Guest/virtual_camera_transport.mdnew file mode 100644index 00000000..84dfbc8e--- /dev/null+++ b/Research/Guest/virtual_camera_transport.md@@ -0,0 +1,66 @@+# Virtual camera transport and capture hooks++## Runtime boundary++The host camera server sends BGRA frames over VSOCK port 1338. `vphoned`+receives them, writes a sequence guarded shared memory frame, and posts+`com.vphone.vcam.frame`. The optional `libvcamcaptured` hook reads that frame+and supplies it to camera clients. The host's **Camera server: connected**+status confirms the VSOCK connection only. It does not confirm that a camera+app or the capture hook is installed, loaded, or showing a preview.++The shared protocol and runtime paths are in+`VPhoneGuestComponents/VCamCaptured/VCamFrameProtocol.h`. All camera runtime+files live in `/var/mobile/Media/SimulatedCamera`: the shared frame+`vphone-vcam-frame.shm`, daemon log `vphone-vcam.log`, hook logs+`vcamcaptured.log` and `camfix.log`, and synthetic photo diagnostic+`vphone-synth-photo.bgra`. `vphoned` waits for the mobile home to be ready,+creates the directory with the mobile account as owner, and then opens the+shared file and binds port 1338. If setup fails during early boot, the+listener retries.++## Failure observed before the media path change++On 2026-09-24, the old daemon required a shared file and log under a directory+that this VM did not have. Shared memory initialization failed before the+VSOCK listener started. Its diagnostic went to the same nonexistent directory.+The host repeatedly logged POSIX error 54, `Connection reset by peer`. The+camera transport now uses the mobile media directory directly, without+installation-layout detection. A system log fallback retains diagnostics when+file 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+Camera.app, but a later app registration query found+`com.apple.camera` in an application container under+`/private/var/containers/Bundle/Application`. The guest component archive+builds the camera hooks but does not install them; see+`VPhoneGuestComponents/README.md`. Camera.app preview and still/video capture+were therefore unverified.++## Transport acceptance on the media directory++On 2026-09-24, the integrated VM exposed `127.0.0.1:8765` for its guest API.+`/var/mobile/Media/SimulatedCamera/vphone-vcam.log` showed+`listening on vsock 1338`, `client connected`, and published frame counts.+The host Camera menu showed **Camera server: connected**. Shared memory was+read back through `GET /v1/files/content` with its `path` query set to+`/var/mobile/Media/SimulatedCamera/vphone-vcam-frame.shm`.++| Source and action | Shared memory observation |+| --- | --- |+| Test Pattern, streaming | Two samples were 8,388,672 bytes each. Frame index increased from 305 to 469 and the file hash changed. The header described 1280×720 BGRA, 5,120 bytes per row, and 3,686,400 pixel bytes. |+| Stop Streaming | Frame index remained 622 and the complete shared file hash stayed identical across two samples. |+| Video File, streaming | A generated 320×180 MOV was selected in the host menu. Frame index increased from 750 to 888 and the pixel payload hash changed. |+| Source: Off | Frame index remained 1,628 and the complete file hash stayed identical across two samples. The host menu returned to **Start Streaming**. |++This verifies the host-to-guest transport and shared frame publication,+including source selection and stopping. A full camera acceptance test still+needs a supported hook loading path: verify the hook is loaded, open+Camera.app's preview, compare visible frames against Test Pattern and Video+File, then test still and video capture separately. After the relocated path+passed its guest test, the stale+`/var/mobile/Library/vphone-vcam-frame.shm` and+`/var/mobile/Library/vphone-vcam.log` files from the earlier build were+removed through the guest API. A subsequent directory listing contained+neither file.diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.mdindex ad437732..da62a57c 100644--- a/Research/vphoned_http_api.md+++ b/Research/vphoned_http_api.md@@ -16,14 +16,14 @@ The SwiftPM `VPhoneAPIKit` product is an unentitled HTTP/WebSocket client forexposes `VPhoneAPIProxy` to an app that owns a `VZVirtioSocketDevice`. Thecommand-line executable remains unentitled and still launches `vphone-vm`.-The guest build also includes the pinned `icli` executable, signed with-icli's entitlements and installed at `/usr/bin/icli` alongside vphoned.-`POST /v1/icli/execute` and the WebSocket method `icli.execute` accept-`{"argv":["device","info"]}`. The guest passes that array to icli directly,-captures its JSON output, and returns `exit_code`, `output`, and `stderr`.-This exposes icli's complete command tree, including newly added subcommands,-without duplicating each command in vphoned. `stdin` or `stdin_base64` supports-commands that read standard input. The process has a 120 second deadline.+The guest links IcliKit directly. App registration refresh is available through+`POST /v1/apps/refresh` or the WebSocket method `apps.refresh`. An optional+`directory` selects a bundle directory; omitted, it uses the bootstrap's+`/Applications`. IcliKit verifies registrations by reading them back.+`screen.screenshot` uses IcliKit's native screen capture and returns a base64+JPEG with `mime_type`, `width`, and `height`; the current VM produces 1290×2796.+The host's Save/Copy Screenshot menu decodes this guest image. It omits the+notch and cutout drawn by the host VM window.## HTTP and WebSocket contract@@ -35,6 +35,17 @@ directory then renames it after all chunks have been written. JSON bodieshave a 1 MiB limit. Binary transfers stream without loading the entire fileinto memory.+`apps.launch` returns a PID and `frontmost_verified`. On the iOS 26 research VM,+IcliKit can keep reporting SpringBoardEducation after an app reaches the screen.+The guest checks RunningBoard's live focal assertion in that case and accepts+it only when one app owns it. iOS 26.6.2 uses `SuspendableRole-UIFocal`; older+systems may use `Workspace-ForegroundFocal`. The Home screen's widget renderer+can hold `UIFocal`, so it is excluded as an app candidate. `apps.foreground`+also reports `verified` and `source`. If no unique focal app can be confirmed,+a newly started process is reported with `frontmost_verified=false` and a+warning. A failed start or an already running app without foreground+confirmation remains an error.+Upload accepts an optional octal `mode` query parameter (default `644`) andcreates missing parent directories. Download follows file symlinks, matchingthe previous file browser behavior.@@ -52,13 +63,16 @@ correlate them by `id`. The socket also sendsreceive pong frames. JSON WebSocket frames are limited to 1 MiB afterfragment reassembly.-SwiftNIO handles parsing, upgrade, masking, and backpressure. IcliKit 0.6.1+SwiftNIO handles parsing, upgrade, masking, and backpressure. IcliKit 0.6.3owns general device operations. Each HTTP or WebSocket request runs independentlyon a concurrent worker queue, so a stalled system service does not block HID,file browsing, or unrelated requests. The host serializes the input events itsends so touch and key sequences retain their order. State polling uses its own-worker queue. The vphone-specific IPA signing and all-app-keychain view remain in native Objective-C modules. The VM GUI uses HTTP over+worker queue. The vphone-specific IPA signing remains in native Objective-C.+Keychain listings combine IcliKit's accessible Security.framework attributes+with its protected database metadata. They return no value data, and possible+duplicates remain visible because the two sources have no stable join key.+The VM GUI uses HTTP overVSOCK 1339 directly; host TCP forwarding is opt-in. The former length-prefixedVSOCK 1337 protocol and duplicate ObjC command handlers have been removed.The 1338 virtual camera stream remains. At startup, the host compares the@@ -92,7 +106,7 @@ import VPhoneAPIKitlet client = VPhoneAPIClient(baseURL: URL(string: "http://127.0.0.1:8765")!)let device = try await client.call("device.snapshot")-let icli = try await client.runIcli(["device", "info"])+let apps = try await client.call("apps.refresh")let socket = try client.openWebSocket()try await socket.send("input.touch", params: ["phase": .string("down"), "x": .number(0.5), "y": .number(0.5),diff --git a/Scripts/check_aux.sh b/Scripts/check_aux.shindex 6d4ad2ff..eda9dc19 100755--- a/Scripts/check_aux.sh+++ b/Scripts/check_aux.sh@@ -20,7 +20,7 @@ file_copy_spawns="$(/usr/bin/find "$root/VPhoneExecutable" "$root/VPhoneKit" \[[ -d "$bundle" ]] || { print -u2 "Missing Xcode bundle: $bundle"; exit 1; }for name in vphone-vm vphone-cli VPhoneEscalator vphoned vphoned.signed \- vpregister libswiftCompatibilitySpan.vphone.dylib libcamfix.dylib libvcamcaptured.dylib \+ libswiftCompatibilitySpan.vphone.dylib libcamfix.dylib libvcamcaptured.dylib \launchdhook-vphone.dylib SystemHook-vphone.dylib \libAppleParavirtCompilerPluginIOGPUFamily.dylib; do[[ -f "$macos/$name" ]] || { print -u2 "Missing binary: Contents/MacOS/$name"; exit 1; }@@ -34,7 +34,7 @@ for name in vphone-vm vphone-cli VPhoneEscalator vphoned vphoned.signed \}done-for name in vphone-app VPhoneAMFIAllow vphone-archive icli vphone-ask-for-permission; do+for name in vphone-app VPhoneAMFIAllow vphone-archive icli vpregister vphone-ask-for-permission; do[[ ! -e "$macos/$name" ]] || { print -u2 "Obsolete binary: $name"; exit 1; }done@@ -85,7 +85,7 @@ daemon_entitlements="$(/usr/bin/codesign -d --entitlements - --xml "$macos/vphonprint -u2 "vphoned has the wrong entitlements"exit 1}-for name in vphone-cli vpregister VPhoneEscalator; do+for name in vphone-cli VPhoneEscalator; doprocess_entitlements="$(/usr/bin/codesign -d --entitlements - --xml "$macos/$name" 2>/dev/null || true)"[[ "$process_entitlements" != *'com.apple.private.virtualization'* &&"$process_entitlements" != *'com.apple.CommCenter.fine-grained'* ]] || {diff --git a/VPhone.xcworkspace/xcshareddata/swiftpm/Package.resolved b/VPhone.xcworkspace/xcshareddata/swiftpm/Package.resolvedindex 7ecc72f2..2782239b 100644--- a/VPhone.xcworkspace/xcshareddata/swiftpm/Package.resolved+++ b/VPhone.xcworkspace/xcshareddata/swiftpm/Package.resolved@@ -1,5 +1,5 @@{- "originHash" : "1de27e729fcb6338110f5bcd0bee0f3630087d45462f3e4d5e75e9be0ff1add0",+ "originHash" : "f64f0141522e4fc1ff1b3bb6ad935f5a786d14cb195f34f75733bb0b4c35ac72","pins" : [{"identity" : "applemobiledevicelibrary",@@ -24,8 +24,8 @@"kind" : "remoteSourceControl","location" : "https://github.com/owngoal-dev/icli.git","state" : {- "revision" : "c3407df5f160919b5eb7d2fefb5a5c21351314fb",- "version" : "0.6.1"+ "revision" : "ee01bde8ceeb4c90779427674185e353bf8e022d",+ "version" : "0.6.3"}},{@@ -123,8 +123,8 @@"kind" : "remoteSourceControl","location" : "https://github.com/apple/swift-collections.git","state" : {- "revision" : "a66de878e87ef5a3d5d390e0f6d9002aa5541a43",- "version" : "1.7.0"+ "revision" : "a0cb0954ecb21e4e31b0070e6ed5674e8556685a",+ "version" : "1.6.0"}},{diff --git a/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements b/VPhoneDaemon/Configuration/VPhoneDaemon.entitlementsindex bee6eb6f..5162245a 100644--- a/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements+++ b/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements@@ -13,8 +13,14 @@</array><key>com.apple.locationd.preauthorized</key><true/>+ <key>com.apple.locationd.effective_bundle</key>+ <true/><key>com.apple.locationd.simulation</key><true/>+ <key>com.apple.lsapplicationworkspace.rebuildappdatabases</key>+ <true/>+ <key>com.apple.powerd.lowpowermode.allow</key>+ <true/><key>com.apple.Pasteboard.background-access</key><true/><key>com.apple.Pasteboard.originating-bundle-id-query</key>@@ -69,6 +75,12 @@<true/><key>com.apple.private.amfi.developer-mode-control</key><true/>+ <key>com.apple.private.coreservices.can-register-install-results</key>+ <true/>+ <key>com.apple.private.coreservices.canmaplsdatabase</key>+ <true/>+ <key>com.apple.private.coreservices.lsaw</key>+ <true/><key>com.apple.private.hid.client.event-dispatch</key><true/><key>com.apple.private.hid.client.event-filter</key>@@ -81,6 +93,8 @@<true/><key>com.apple.private.kernel.jetsam</key><true/>+ <key>com.apple.private.installcoordinationd.daemon</key>+ <true/><key>com.apple.private.memorystatus</key><true/><key>com.apple.private.persona-mgmt</key>diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swiftindex 9e7a33ee..3586729b 100644--- a/VPhoneDaemon/Daemon/GuestAPI.swift+++ b/VPhoneDaemon/Daemon/GuestAPI.swift@@ -2,6 +2,8 @@ import CryptoKitimport Darwinimport Foundationimport IcliKit+import IcliSystem+import UIKitimport VphonedNativeenum GuestAPIError: Error, CustomStringConvertible {@@ -18,8 +20,8 @@ enum GuestAPIError: Error, CustomStringConvertible {}/// The API boundary is deliberately small: named operations and JSON values.-/// IcliKit owns general device work; only vphone-specific installation and-/// keychain enumeration cross into the older daemon code.+/// IcliKit owns general device work, including Keychain metadata. Only+/// vphone-specific installation crosses into the native daemon code.enum GuestAPI {// Each request executes independently. A synchronous system service such// as powerd may wait during boot; it must not hold up HID or file requests.@@ -58,6 +60,7 @@ enum GuestAPI {"keychain","ipa_install","camera",+ "screenshot",],]}@@ -68,9 +71,11 @@ enum GuestAPI {return try collectDeviceSnapshot()case "device.screen":return screenInfo()+ case "screen.screenshot":+ return try takeScreenshot(base64: true, nativeResolution: true)case "apps.list":let filter = params["filter"] as? String ?? "all"- let apps = try searchApps("")["apps"] as? [[String: Any]] ?? []+ let apps = try listApps()["apps"] as? [[String: Any]] ?? []let running = try runningApps()["apps"] as? [[String: Any]] ?? []let pids = Dictionary(uniqueKeysWithValues: running.compactMap { app -> (String, Int)? inguard let id = app["bundle_id"] as? String, let pid = app["pid"] as? Int else { return nil }@@ -78,11 +83,16 @@ enum GuestAPI {})return ["apps": apps.compactMap { app -> [String: Any]? invar info = app- let id = app["bundle_id"] as? String ?? ""+ guard let id = app["bundle_id"] as? String, !id.isEmpty else { return nil }let pid = pids[id] ?? 0let path = app["bundle_path"] as? String ?? ""- let type = app["type"] as? String- ?? (path.hasPrefix("/System/") || id.hasPrefix("com.apple.") ? "system" : "user")+ let type: String+ if let registeredType = (app["type"] as? String)?.lowercased(),+ registeredType == "system" || registeredType == "user" {+ type = registeredType+ } else {+ type = path.hasPrefix("/System/") || id.hasPrefix("com.apple.") ? "system" : "user"+ }if filter == "running" && pid == 0 {return nil}@@ -101,19 +111,41 @@ enum GuestAPI {}]case "apps.search":return try searchApps(string(params, "query"))+ case "apps.refresh":+ return try refreshApps(directory: params["directory"] as? String)case "apps.launch":let id = try string(params, "bundle_id")if let url = params["url"] as? String {_ = try openAppURL(url, bundleID: id)} else {- _ = try launchApp(id)+ let before = try runningApps()["apps"] as? [[String: Any]] ?? []+ let wasRunning = before.contains { $0["bundle_id"] as? String == id }+ do {+ _ = try launchApp(id)+ } catch IcliError.failed(let message) where message == "app did not become frontmost: \(id)" {+ let after = try runningApps()["apps"] as? [[String: Any]] ?? []+ guard let pid = after.first(where: { $0["bundle_id"] as? String == id })?["pid"] as? Int+ else { throw IcliError.failed(message) }+ if GuestForeground.current()["bundle_id"] as? String == id {+ return ["pid": pid, "frontmost_verified": true]+ }+ guard !wasRunning else { throw IcliError.failed(message) }+ return [+ "pid": pid,+ "frontmost_verified": false,+ "warning": "App process started, but foreground state could not be confirmed",+ ]+ }}let running = try? runningApps()["apps"] as? [[String: Any]]- return ["pid": running?.first(where: { $0["bundle_id"] as? String == id })?["pid"] ?? 0]+ return [+ "pid": running?.first(where: { $0["bundle_id"] as? String == id })?["pid"] ?? 0,+ "frontmost_verified": params["url"] == nil,+ ]case "apps.terminate":return try killApp(string(params, "bundle_id"), force: true)case "apps.foreground":- let front = frontmostApp()+ let front = GuestForeground.current()let id = front["bundle_id"] as? String ?? ""let apps = try searchApps(id)["apps"] as? [[String: Any]] ?? []let running = try runningApps()["apps"] as? [[String: Any]] ?? []@@ -121,6 +153,8 @@ enum GuestAPI {"bundle_id": id,"name": apps.first?["name"] ?? "","pid": running.first(where: { $0["bundle_id"] as? String == id })?["pid"] ?? 0,+ "verified": front["verified"] ?? false,+ "source": front["source"] ?? "",]case "apps.open_url":return try openAppURL(string(params, "url"), bundleID: params["bundle_id"] as? String)@@ -164,13 +198,37 @@ enum GuestAPI {return try enableDeveloperMode()case "power.low_power_mode":if let enabled = params["enabled"] as? Bool {- return try setLowPowerMode(enabled)+ let before = try lowPowerMode()["enabled"] as? Bool ?? false+ switch vp_low_power_mode_set_async(enabled) {+ case -1:+ throw GuestAPIError.operationFailed("powerd's asynchronous Low Power Mode API is unavailable")+ case -2:+ throw GuestAPIError.operationFailed("powerd did not answer the Low Power Mode request within 3 seconds")+ case -3:+ throw GuestAPIError.operationFailed("powerd rejected the Low Power Mode request")+ default:+ break+ }+ let deadline = Date().addingTimeInterval(2)+ while Date() < deadline {+ if try lowPowerMode()["enabled"] as? Bool == enabled {+ return ["enabled": enabled, "changed": before != enabled, "method": "powerd"]+ }+ Thread.sleep(forTimeInterval: 0.05)+ }+ throw GuestAPIError.operationFailed("powerd replied but did not apply Low Power Mode")}return try lowPowerMode()case "clipboard.get":return try clipboardInfo()case "clipboard.set":return try setClipboard(string(params, "text"))+ case "clipboard.clear":+ guard let pasteboard = UIPasteboard(name: .general, create: false) else {+ throw GuestAPIError.operationFailed("The system clipboard is unavailable")+ }+ pasteboard.items = []+ return try clipboardInfo()case "files.list":return try fileList(string(params, "path"))case "files.mkdir":@@ -198,17 +256,23 @@ enum GuestAPI {key: string(params, "key"),value: PreferenceValue(text: text, type: type),)+ case "settings.delete":+ return try deletePreference(domain: string(params, "domain"), key: string(params, "key"))case "accessibility.tree":throw GuestAPIError.operationFailed("The accessibility tree is not available on this guest yet.")case "keychain.list":- return try native(["t": "keychain_list", "class": params["class"] as? String ?? ""])+ return try GuestKeychain.list(className: params["class"] as? String)case "keychain.add":- return try native([- "t": "keychain_add",- "account": string(params, "account"),- "service": string(params, "service"),- "password": string(params, "password"),- ])+ return try GuestKeychain.add(+ account: string(params, "account"),+ service: string(params, "service"),+ password: string(params, "password")+ )+ case "keychain.delete":+ return try GuestKeychain.delete(+ account: string(params, "account"),+ service: string(params, "service")+ )case "agent.apply_update":let expected = try string(params, "sha256")let cache = "/var/root/Library/Caches/vphoned"@@ -258,6 +322,11 @@ enum GuestAPI {var enriched = entryenriched["type"] = isLink ? "link" : kind == mode_t(S_IFDIR) ? "dir" : "file"enriched["link_target_dir"] = targetsDirectory+ if kind == mode_t(S_IFDIR) || targetsDirectory,+ let canonicalPath = fullPath.withCString({ realpath($0, nil) }) {+ enriched["resolved_path"] = String(cString: canonicalPath)+ free(canonicalPath)+ }enriched["size"] = metadata.st_sizeenriched["perm"] = String(metadata.st_mode & 0o777, radix: 8)enriched["mtime"] = Double(metadata.st_mtimespec.tv_sec)@@ -281,6 +350,8 @@ enum GuestAPI {}private static func number(_ params: [String: Any], _ key: String, default fallback: Double = .nan) -> Double {- (params[key] as? NSNumber)?.doubleValue ?? fallback+ if let value = params[key] as? NSNumber { return value.doubleValue }+ if let value = params[key] as? String, let number = Double(value) { return number }+ return fallback}}diff --git a/VPhoneDaemon/Daemon/GuestEventPublisher.swift b/VPhoneDaemon/Daemon/GuestEventPublisher.swiftindex 8bd23bb2..1b0ae4fb 100644--- a/VPhoneDaemon/Daemon/GuestEventPublisher.swift+++ b/VPhoneDaemon/Daemon/GuestEventPublisher.swift@@ -24,7 +24,7 @@ final class GuestEventPublisher: @unchecked Sendable {}let state: [String: Any] = ["screen": screenInfo(),- "frontmost_app": frontmostApp(),+ "frontmost_app": GuestForeground.current(),"low_power_mode": (try? lowPowerMode()) ?? [:],]guard let data = try? JSONSerialization.data(withJSONObject: state, options: [.sortedKeys]),diff --git a/VPhoneDaemon/Daemon/GuestForeground.swift b/VPhoneDaemon/Daemon/GuestForeground.swiftnew file mode 100644index 00000000..653507a0--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestForeground.swift@@ -0,0 +1,22 @@+import Darwin+import Foundation+import IcliKit+import VphonedNative++enum GuestForeground {+ static func current() -> [String: Any] {+ let reported = frontmostApp()["bundle_id"] as? String ?? "com.apple.springboard"+ let isSpringBoard = reported == "com.apple.springboard" || reported == "com.apple.springboardeducation"+ guard isSpringBoard else {+ return ["bundle_id": reported, "verified": true, "source": "springboard"]+ }++ let screen = screenInfo()+ guard screen["locked"] as? Bool != true, screen["screen_off"] as? Bool != true,+ let focal = vp_runningboard_focal_bundle_id() else {+ return ["bundle_id": reported, "verified": false, "source": "springboard"]+ }+ defer { free(focal) }+ return ["bundle_id": String(cString: focal), "verified": true, "source": "runningboard"]+ }+}diff --git a/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift b/VPhoneDaemon/Daemon/GuestHyperTextHandler.swiftindex 5579e3b9..341c8eb2 100644--- a/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift+++ b/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift@@ -163,6 +163,7 @@ final class GuestHyperTextHandler: ChannelInboundHandler, RemovableChannelHandlecase (.GET, "/v1/device"): "device.snapshot"case (.GET, "/v1/device/screen"): "device.screen"case (.GET, "/v1/apps"): "apps.list"+ case (.POST, "/v1/apps/refresh"): "apps.refresh"case (.POST, "/v1/apps/launch"): "apps.launch"case (.POST, "/v1/apps/terminate"): "apps.terminate"case (.GET, "/v1/apps/foreground"): "apps.foreground"@@ -177,14 +178,17 @@ final class GuestHyperTextHandler: ChannelInboundHandler, RemovableChannelHandlecase (.POST, "/v1/developer-mode/enable"): "developer_mode.enable"case (.GET, "/v1/low-power-mode"), (.PUT, "/v1/low-power-mode"): "power.low_power_mode"case (.GET, "/v1/clipboard"), (.PUT, "/v1/clipboard"): verb == .GET ? "clipboard.get" : "clipboard.set"+ case (.DELETE, "/v1/clipboard"): "clipboard.clear"case (.GET, "/v1/files"): "files.list"case (.POST, "/v1/files/mkdir"): "files.mkdir"case (.POST, "/v1/files/remove"): "files.remove"case (.POST, "/v1/files/rename"): "files.rename"case (.POST, "/v1/settings/get"): "settings.get"case (.POST, "/v1/settings/set"): "settings.set"+ case (.POST, "/v1/settings/delete"): "settings.delete"case (.GET, "/v1/keychain"): "keychain.list"case (.POST, "/v1/keychain"): "keychain.add"+ case (.DELETE, "/v1/keychain"): "keychain.delete"default: throw GuestAPIError.invalidRequest("No route for \(verb) \(path)")}}diff --git a/VPhoneDaemon/Daemon/GuestKeychain.swift b/VPhoneDaemon/Daemon/GuestKeychain.swiftnew file mode 100644index 00000000..612ca496--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestKeychain.swift@@ -0,0 +1,104 @@+import Foundation+import IcliKit++/// Keep the existing vphoned response shape while IcliKit owns both Keychain+/// queries. Neither listing asks Security.framework for item data.+enum GuestKeychain {+ static func list(className: String?) throws -> [String: Any] {+ let requested = try libraryClass(className)+ var items: [[String: Any]] = []+ var diagnostics: [String] = []+ var succeeded = false++ do {+ let result = try listKeychain(+ className: requested,+ service: nil,+ account: nil,+ server: nil,+ group: nil,+ includeData: false+ )+ let rows = result["items"] as? [[String: Any]] ?? []+ items += rows.map(adaptItem)+ diagnostics.append("Security: \(rows.count) accessible items")+ succeeded = true+ } catch {+ diagnostics.append("Security: \(error)")+ }++ if requested != "identity" {+ do {+ let result = try listKeychainDatabaseMetadata(className: requested)+ let rows = result["items"] as? [[String: Any]] ?? []+ items += rows.map(adaptItem)+ diagnostics.append("Database: \(rows.count) protected metadata rows")+ succeeded = true+ } catch {+ diagnostics.append("Database: \(error)")+ }+ }++ guard succeeded else {+ throw GuestAPIError.operationFailed(diagnostics.joined(separator: "; "))+ }+ if items.contains(where: { $0["source"] as? String == "security" }) {+ diagnostics.append("Accessible attributes may also appear as protected database rows")+ }+ return ["items": items, "count": items.count, "diag": diagnostics]+ }++ static func add(account: String, service: String, password: String) throws -> [String: Any] {+ // IcliKit returns item data on add; only status crosses the VM boundary.+ _ = try addKeychain(+ className: "generic_password",+ service: service,+ account: account,+ server: nil,+ label: "\(service) (\(account))",+ group: nil,+ data: password+ )+ return ["ok": true, "status": 0]+ }++ static func delete(account: String, service: String) throws -> [String: Any] {+ let result = try deleteKeychain(+ className: "generic_password",+ service: service,+ account: account,+ server: nil,+ group: nil+ )+ return ["ok": true, "removed": result["deleted"] as? Bool ?? false]+ }++ private static func libraryClass(_ className: String?) throws -> String? {+ switch className ?? "" {+ case "": nil+ case "genp", "generic_password", "generic": "generic_password"+ case "inet", "internet_password", "internet": "internet_password"+ case "cert", "certificate": "certificate"+ case "keys", "key": "key"+ case "idnt", "identity": "identity"+ default: throw GuestAPIError.invalidRequest("Unknown keychain class")+ }+ }++ private static func adaptItem(_ item: [String: Any]) -> [String: Any] {+ var adapted = item+ switch item["class"] as? String {+ case "generic_password": adapted["class"] = "genp"+ case "internet_password": adapted["class"] = "inet"+ case "certificate": adapted["class"] = "cert"+ case "key": adapted["class"] = "keys"+ case "identity": adapted["class"] = "idnt"+ default: break+ }+ if let group = item["group"] { adapted["accessGroup"] = group }+ if let rowID = item["rowid"] { adapted["_rowid"] = rowID }+ adapted["valueEncoding"] = "protected"+ adapted.removeValue(forKey: "data")+ return adapted+ }+}diff --git a/VPhoneDaemon/Daemon/GuestSigner.swift b/VPhoneDaemon/Daemon/GuestSigner.swiftnew file mode 100644index 00000000..29b6b36a--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestSigner.swift@@ -0,0 +1,41 @@+import Darwin+import Foundation+import VPhoneSign++/// The native IPA installer prepares each executable's guest entitlements.+/// Sign them with the same bundled signer used by the host CLI, without a+/// package-manager supplied ldid executable inside the VM.+@_cdecl("vp_guest_sign_binary")+func vpGuestSignBinary(+ _ path: UnsafePointer<CChar>?,+ _ entitlementsPath: UnsafePointer<CChar>?,+ _ certificatePath: UnsafePointer<CChar>?+) -> UnsafeMutablePointer<CChar>? {+ guard let path else { return strdup("Missing executable path") }++ do {+ var options = VPhoneSignOptions()+ if let entitlementsPath {+ options.entitlements = try Data(+ contentsOf: URL(fileURLWithPath: String(cString: entitlementsPath)),+ options: .mappedIfSafe+ )+ } else {+ options.mergesExisting = true+ }+ if let certificatePath {+ options.mergesExisting = true+ options.identity = try VPhoneSignIdentity(+ pkcs12: Data(+ contentsOf: URL(fileURLWithPath: String(cString: certificatePath)),+ options: .mappedIfSafe+ ),+ password: ""+ )+ }+ try VPhoneSigner.sign(fileAt: URL(fileURLWithPath: String(cString: path)), options: options)+ return nil+ } catch {+ return strdup(String(describing: error))+ }+}diff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.hindex f455524a..4ace90d1 100644--- a/VPhoneDaemon/Native/Include/VphonedNative.h+++ b/VPhoneDaemon/Native/Include/VphonedNative.h@@ -6,3 +6,7 @@ NSDictionary *vp_native_api_command(NSDictionary *message);void vp_native_bootstrap_cached_binary(void);void vp_native_confirm_cached_binary(void);void vp_vcam_start(void);+/// Returns 0 on acceptance, -1 when unavailable, -2 on timeout, or -3 on rejection.+int vp_low_power_mode_set_async(bool enabled);+/// A malloc-owned bundle ID only when one live app has RunningBoard's focal assertion.+char *vp_runningboard_focal_bundle_id(void);diff --git a/VPhoneDaemon/Native/vphoned_foreground.m b/VPhoneDaemon/Native/vphoned_foreground.mnew file mode 100644index 00000000..0a244e64--- /dev/null+++ b/VPhoneDaemon/Native/vphoned_foreground.m@@ -0,0 +1,67 @@+#import "Include/VphonedNative.h"+#import <dlfcn.h>+#import <objc/message.h>+#import <sys/sysctl.h>++char *vp_runningboard_focal_bundle_id(void) {+ @autoreleasepool {+ dlopen("/System/Library/PrivateFrameworks/RunningBoardServices.framework/RunningBoardServices", RTLD_NOW);+ Class identifierClass = NSClassFromString(@"RBSProcessIdentifier");+ Class handleClass = NSClassFromString(@"RBSProcessHandle");+ SEL identifierSelector = NSSelectorFromString(@"identifierWithPid:");+ SEL handleSelector = NSSelectorFromString(@"handleForIdentifier:error:");+ if (![identifierClass respondsToSelector:identifierSelector] || ![handleClass respondsToSelector:handleSelector])+ return NULL;+ void *libproc = dlopen("/usr/lib/libproc.dylib", RTLD_NOW);+ int (*pidPath)(int, void *, uint32_t) = libproc ? dlsym(libproc, "proc_pidpath") : NULL;+ if (!pidPath) {+ if (libproc) dlclose(libproc);+ return NULL;+ }++ int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};+ size_t length = 0;+ if (sysctl(mib, 3, NULL, &length, NULL, 0) != 0) {+ dlclose(libproc);+ return NULL;+ }+ length += 64 * sizeof(struct kinfo_proc);+ struct kinfo_proc *processes = calloc(1, length);+ if (!processes || sysctl(mib, 3, processes, &length, NULL, 0) != 0) {+ free(processes);+ dlclose(libproc);+ return NULL;+ }++ NSMutableSet<NSString *> *focalIDs = [NSMutableSet set];+ for (size_t i = 0; i < length / sizeof(struct kinfo_proc) && focalIDs.count < 2; i++) {+ pid_t pid = processes[i].kp_proc.p_pid;+ char path[4096] = {0};+ if (pid <= 0 || pidPath(pid, path, sizeof(path)) <= 0 || !strstr(path, ".app/"))+ continue;+ @try {+ id identifier = ((id (*)(id, SEL, int))objc_msgSend)(identifierClass, identifierSelector, pid);+ id handle = ((id (*)(id, SEL, id, NSError **))objc_msgSend)(handleClass, handleSelector,+ identifier, NULL);+ NSString *bundleID = [[handle valueForKey:@"identity"] valueForKey:@"embeddedApplicationIdentifier"];+ if (![bundleID isKindOfClass:NSString.class] || !bundleID.length) continue;+ // The Home screen's widget renderer can own UIFocal without being the frontmost app.+ if ([bundleID hasPrefix:@"com.apple.chrono.WidgetRenderer"]) continue;+ for (id assertion in [[handle valueForKey:@"currentState"] valueForKey:@"assertions"]) {+ NSString *domain = [assertion valueForKey:@"domain"];+ if ([domain isKindOfClass:NSString.class] &&+ ([domain containsString:@"Workspace-ForegroundFocal"] ||+ [domain containsString:@"com.apple.frontboard:SuspendableRole-UIFocal"])) {+ [focalIDs addObject:bundleID];+ break;+ }+ }+ } @catch (NSException *exception) {+ (void)exception;+ }+ }+ free(processes);+ dlclose(libproc);+ return focalIDs.count == 1 ? strdup(focalIDs.anyObject.UTF8String) : NULL;+ }+}diff --git a/VPhoneDaemon/Native/vphoned_install.m b/VPhoneDaemon/Native/vphoned_install.mindex 8369031a..109e80c3 100644--- a/VPhoneDaemon/Native/vphoned_install.m+++ b/VPhoneDaemon/Native/vphoned_install.m@@ -4,12 +4,9 @@#import <Security/Security.h>#include <dlfcn.h>#include <errno.h>-#include <fcntl.h>#include <mach-o/fat.h>#include <mach-o/loader.h>-#include <spawn.h>#include <sys/stat.h>-#include <sys/wait.h>#include <unistd.h>#import "vphoned_response.h"@@ -59,6 +56,10 @@ extern CFStringRef kSecCodeInfoEntitlementsDict;static NSString *const VPManagedMarker = @"_VPhone";+// Implemented in GuestSigner.swift using the shared VPhoneSign target.+// A non-null result is a malloc-owned error message.+extern char *vp_guest_sign_binary(const char *path, const char *entitlementsPath, const char *certificatePath);+static void vp_load_private_frameworks(void) {static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{@@ -152,82 +153,6 @@ static void vp_fix_permissions_of_app_bundle(NSString *appBundlePath) {}}-static NSString *vp_read_all_from_fd(int fd) {- NSMutableData *data = [NSMutableData data];- uint8_t buf[4096];- ssize_t n = 0;- while ((n = read(fd, buf, sizeof(buf))) > 0) {- [data appendBytes:buf length:(NSUInteger)n];- }- if (data.length == 0) return @"";- NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];- return string ?: @"";-}--static int vp_run_process_with_output(NSString *path, NSArray<NSString *> *args, NSString **output) {- NSUInteger argc = args.count + 2;- char **argv = calloc(argc, sizeof(char *));- if (!argv) return ENOMEM;-- argv[0] = strdup(path.fileSystemRepresentation);- for (NSUInteger i = 0; i < args.count; i++) {- argv[i + 1] = strdup(args[i].fileSystemRepresentation);- }- argv[argc - 1] = NULL;-- int pipeFds[2] = {-1, -1};- if (pipe(pipeFds) != 0) {- for (NSUInteger i = 0; i < argc - 1; i++) free(argv[i]);- free(argv);- return errno;- }-- posix_spawn_file_actions_t actions;- posix_spawn_file_actions_init(&actions);- posix_spawn_file_actions_adddup2(&actions, pipeFds[1], STDOUT_FILENO);- posix_spawn_file_actions_adddup2(&actions, pipeFds[1], STDERR_FILENO);- posix_spawn_file_actions_addclose(&actions, pipeFds[0]);-- pid_t pid = 0;- int spawnError = posix_spawn(&pid, path.fileSystemRepresentation, &actions, NULL, argv, NULL);-- posix_spawn_file_actions_destroy(&actions);- close(pipeFds[1]);-- NSString *captured = vp_read_all_from_fd(pipeFds[0]);- close(pipeFds[0]);-- int status = 0;- if (spawnError == 0 && waitpid(pid, &status, 0) < 0) {- spawnError = errno;- }-- for (NSUInteger i = 0; i < argc - 1; i++) free(argv[i]);- free(argv);-- if (output) *output = captured;-- if (spawnError != 0) return spawnError;- if (WIFEXITED(status)) return WEXITSTATUS(status);- if (WIFSIGNALED(status)) return 128 + WTERMSIG(status);- return -1;-}--static NSString *vp_find_ldid_path(void) {- NSFileManager *fm = [NSFileManager defaultManager];- for (NSString *path in @[- @"/var/jb/usr/bin/ldid",- @"/iosbinpack64/usr/bin/ldid",- @"/usr/bin/ldid",- ]) {- if ([fm isExecutableFileAtPath:path]) {- return path;- }- }- return nil;-}--static SecStaticCodeRef vp_get_static_code_ref(NSString *binaryPath) {if (binaryPath.length == 0) return NULL;@@ -274,16 +199,9 @@ static int vp_sign_binary(NSString *filePath,NSDictionary *entitlements,NSString *certPath,- NSString *ldidPath,NSString **errorOutput) {- if (ldidPath.length == 0) {- if (errorOutput) *errorOutput = @"The code-signing tool (ldid) is missing on the guest.";- return ENOENT;- }-NSString *entitlementsPath = nil;- NSMutableArray<NSString *> *args = [NSMutableArray array];NSData *entitlementsXML = entitlements ? [NSPropertyListSerializationdataWithPropertyList:entitlementsformat:NSPropertyListXMLFormat_v1_0@@ -292,29 +210,27 @@ static int vp_sign_binary(if (entitlementsXML) {entitlementsPath = [[NSTemporaryDirectory() stringByAppendingPathComponent:[NSUUID UUID].UUIDString]stringByAppendingPathExtension:@"plist"];- [entitlementsXML writeToFile:entitlementsPath atomically:NO];- [args addObject:[@"-S" stringByAppendingString:entitlementsPath]];- } else {- [args addObject:@"-S"];- }-- if (certPath.length > 0) {- [args addObject:@"-M"];- [args addObject:[@"-K" stringByAppendingString:certPath]];+ if (![entitlementsXML writeToFile:entitlementsPath atomically:YES]) {+ if (errorOutput) *errorOutput = @"Could not prepare app entitlements.";+ return EIO;+ }}- [args addObject:filePath];-- NSString *output = @"";- int ret = vp_run_process_with_output(ldidPath, args, &output);+ char *error = vp_guest_sign_binary(+ filePath.fileSystemRepresentation,+ entitlementsPath.fileSystemRepresentation,+ certPath.length > 0 ? certPath.fileSystemRepresentation : NULL+ );if (entitlementsPath) {[[NSFileManager defaultManager] removeItemAtPath:entitlementsPath error:nil];}- if (errorOutput) *errorOutput = output;- return ret;+ if (!error) return 0;+ if (errorOutput) *errorOutput = [NSString stringWithUTF8String:error] ?: @"Could not sign app executable.";+ free(error);+ return EINVAL;}-static int vp_sign_app(NSString *appPath, NSString *certPath, NSString *ldidPath, NSString **errorOutput) {+static int vp_sign_app(NSString *appPath, NSString *certPath, NSString **errorOutput) {if (!vp_info_dictionary_for_app_path(appPath)) {if (errorOutput) *errorOutput = @"The app package is incomplete and cannot be signed.";return 172;@@ -326,6 +242,7 @@ static int vp_sign_app(NSString *appPath, NSString *certPath, NSString *ldidPathreturn 174;}+ NSMutableSet<NSString *> *signedExecutables = [NSMutableSet set];NSURL *fileURL = nil;NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager]enumeratorAtURL:[NSURL fileURLWithPath:appPath]@@ -391,18 +308,29 @@ static int vp_sign_app(NSString *appPath, NSString *certPath, NSString *ldidPathentitlementsToUse[@"jb.pmap_cs_custom_trust"] = @"PMAP_CS_APP_STORE";NSString *signOutput = @"";- int ret = vp_sign_binary(bundleMainExecutablePath, entitlementsToUse, certPath, ldidPath, &signOutput);+ int ret = vp_sign_binary(bundleMainExecutablePath, entitlementsToUse, certPath, &signOutput);if (ret != 0) {if (errorOutput) *errorOutput = signOutput;return 173;}+ [signedExecutables addObject:bundleMainExecutablePath];}- NSString *recursiveOutput = @"";- int recursiveRet = vp_sign_binary(appPath, nil, certPath, ldidPath, &recursiveOutput);- if (recursiveRet != 0) {- if (errorOutput) *errorOutput = recursiveOutput;- return 173;+ // Sign code without an Info.plist executable declaration, such as dylibs.+ // The declared executables above already carry their guest entitlements.+ enumerator = [[NSFileManager defaultManager]+ enumeratorAtURL:[NSURL fileURLWithPath:appPath]+ includingPropertiesForKeys:nil+ options:0+ errorHandler:nil];+ while ((fileURL = [enumerator nextObject])) {+ NSString *filePath = fileURL.path;+ if ([signedExecutables containsObject:filePath] || !vp_is_macho_file(filePath)) continue;+ NSString *signOutput = @"";+ if (vp_sign_binary(filePath, nil, certPath, &signOutput) != 0) {+ if (errorOutput) *errorOutput = signOutput;+ return 173;+ }}return 0;}@@ -648,11 +576,29 @@ static BOOL vp_mark_container_as_managed(NSString *containerPath) {return [@"" writeToFile:markerPath atomically:YES encoding:NSUTF8StringEncoding error:nil];}+static void vp_rollback_app_install(+ NSString *newPath,+ NSString *oldPath,+ NSString *backupPath,+ NSString *markerPath,+ BOOL markerExisted,+ BOOL newMoved,+ BOOL oldMoved,+ BOOL restoreRegistration,+ BOOL forceSystem+) {+ NSFileManager *fm = [NSFileManager defaultManager];+ if (newMoved) [fm removeItemAtPath:newPath error:nil];+ if (oldMoved && [fm moveItemAtPath:backupPath toPath:oldPath error:nil] && restoreRegistration) {+ vp_register_path(oldPath, NO, forceSystem);+ }+ if (!markerExisted) [fm removeItemAtPath:markerPath error:nil];+}+static int vp_install_app_from_package(NSString *appPackagePath,BOOL forceSystem,NSString *certPath,- NSString *ldidPath,NSString **detailOutput) {NSString *appPayloadPath = [appPackagePath stringByAppendingPathComponent:@"Payload"];@@ -674,7 +620,7 @@ static int vp_install_app_from_package(}NSString *signOutput = @"";- int signRet = vp_sign_app(appBundleToInstallPath, certPath, ldidPath, &signOutput);+ int signRet = vp_sign_app(appBundleToInstallPath, certPath, &signOutput);if (signRet != 0) {if (detailOutput) *detailOutput = signOutput;return signRet;@@ -691,6 +637,7 @@ static int vp_install_app_from_package(createIfNecessary:NOexisted:nilerror:nil];+ NSString *oldAppPath = nil;if (appContainer) {NSURL *bundleContainerURL = appContainer.url;NSURL *appBundleURL = vp_find_app_url_in_bundle_url(bundleContainerURL);@@ -698,9 +645,7 @@ static int vp_install_app_from_package(if (detailOutput) *detailOutput = @"An app with the same bundle identifier is already installed. Remove it and try again.";return 171;}- if (appBundleURL.path.length > 0) {- [[NSFileManager defaultManager] removeItemAtURL:appBundleURL error:nil];- }+ oldAppPath = appBundleURL.path;} else {NSError *mcmError = nil;appContainer = [appContainerClass@@ -714,35 +659,54 @@ static int vp_install_app_from_package(}}+ NSFileManager *fm = [NSFileManager defaultManager];+ NSString *containerPath = appContainer.url.path;NSString *newAppBundlePath =- [appContainer.url.path stringByAppendingPathComponent:appBundleToInstallPath.lastPathComponent];+ [containerPath stringByAppendingPathComponent:appBundleToInstallPath.lastPathComponent];+ NSString *stagedPath = [containerPath stringByAppendingPathComponent:+ [@".vphone-install-" stringByAppendingString:[NSUUID UUID].UUIDString]];+ NSString *backupPath = oldAppPath.length > 0 ? [containerPath stringByAppendingPathComponent:+ [@".vphone-backup-" stringByAppendingString:[NSUUID UUID].UUIDString]] : nil;+ NSString *markerPath = [containerPath stringByAppendingPathComponent:VPManagedMarker];+ BOOL markerExisted = [fm fileExistsAtPath:markerPath];NSError *copyError = nil;- if (![[NSFileManager defaultManager] copyItemAtPath:appBundleToInstallPath- toPath:newAppBundlePath- error:©Error]) {+ if (![fm copyItemAtPath:appBundleToInstallPath toPath:stagedPath error:©Error]) {+ [fm removeItemAtPath:stagedPath error:nil];if (detailOutput) *detailOutput = copyError.localizedDescription ?: @"Unable to copy the app onto the guest.";return 178;}- if (!vp_mark_container_as_managed(appContainer.url.path)) {- if (detailOutput) *detailOutput = @"The app was installed but could not be marked as managed.";- return 177;+ if (oldAppPath.length > 0 && ![fm moveItemAtPath:oldAppPath toPath:backupPath error:©Error]) {+ [fm removeItemAtPath:stagedPath error:nil];+ if (detailOutput) *detailOutput = copyError.localizedDescription ?: @"Unable to back up the existing app.";+ return 178;}-- NSURL *updatedAppURL = vp_find_app_url_in_bundle_url(appContainer.url);- if (updatedAppURL.path.length == 0) {- if (detailOutput) *detailOutput = @"The app was installed but could not be located afterwards.";+ BOOL oldMoved = oldAppPath.length > 0;+ if (![fm moveItemAtPath:stagedPath toPath:newAppBundlePath error:©Error]) {+ [fm removeItemAtPath:stagedPath error:nil];+ vp_rollback_app_install(newAppBundlePath, oldAppPath, backupPath, markerPath,+ markerExisted, NO, oldMoved, NO, forceSystem);+ if (detailOutput) *detailOutput = copyError.localizedDescription ?: @"Unable to place the app onto the guest.";return 178;}- vp_fix_permissions_of_app_bundle(updatedAppURL.path);- if (!vp_register_path(updatedAppURL.path, NO, forceSystem)) {+ vp_fix_permissions_of_app_bundle(newAppBundlePath);+ if (!vp_mark_container_as_managed(containerPath)) {+ vp_rollback_app_install(newAppBundlePath, oldAppPath, backupPath, markerPath,+ markerExisted, YES, oldMoved, NO, forceSystem);+ if (detailOutput) *detailOutput = @"The app was copied but could not be marked as managed.";+ return 177;+ }+ if (!vp_register_path(newAppBundlePath, NO, forceSystem)) {+ vp_rollback_app_install(newAppBundlePath, oldAppPath, backupPath, markerPath,+ markerExisted, YES, oldMoved, YES, forceSystem);if (detailOutput) *detailOutput = @"The app was copied but could not be registered with the system.";return 181;}+ if (oldMoved) [fm removeItemAtPath:backupPath error:nil];if (detailOutput) {- *detailOutput = [NSString stringWithFormat:@"%@ (%@)", updatedAppURL.lastPathComponent, appId];+ *detailOutput = [NSString stringWithFormat:@"%@ (%@)", newAppBundlePath.lastPathComponent, appId];}return 0;}@@ -773,7 +737,6 @@ NSDictionary *vp_handle_custom_install(NSDictionary *msg) {NSString *ipaPath = msg[@"path"];NSString *registration = msg[@"registration"];NSString *certPath = msg[@"cert_path"];- NSString *ldidPath = vp_find_ldid_path();BOOL forceSystem = [registration isEqualToString:@"System"];if (ipaPath.length == 0) {@@ -796,11 +759,6 @@ NSDictionary *vp_handle_custom_install(NSDictionary *msg) {response[@"msg"] = @"This guest cannot install apps. The built-in installer is not supported here.";return response;}- if (ldidPath.length == 0) {- NSMutableDictionary *response = vp_make_response(@"err", reqId);- response[@"msg"] = @"The code-signing tool (ldid) is missing on the guest. Install it and try again.";- return response;- }if (certPath.length > 0 && ![[NSFileManager defaultManager] fileExistsAtPath:certPath]) {certPath = nil;}@@ -820,7 +778,7 @@ NSDictionary *vp_handle_custom_install(NSDictionary *msg) {int extractRet = vp_extract_package_to_directory(ipaPath, tmpPackagePath, &detail);int installRet = 0;if (extractRet == 0) {- installRet = vp_install_app_from_package(tmpPackagePath, forceSystem, certPath, ldidPath, &detail);+ installRet = vp_install_app_from_package(tmpPackagePath, forceSystem, certPath, &detail);}[[NSFileManager defaultManager] removeItemAtPath:tmpPackagePath error:nil];diff --git a/VPhoneDaemon/Native/vphoned_keychain.h b/VPhoneDaemon/Native/vphoned_keychain.hdeleted file mode 100644index 35c8da0d..00000000--- a/VPhoneDaemon/Native/vphoned_keychain.h+++ /dev/null@@ -1,12 +0,0 @@-/*- * vphoned_keychain — Remote keychain enumeration over vsock.- *- * Handles keychain_list: queries SecItemCopyMatching for all keychain- * classes and returns attributes as JSON.- */--#pragma once-#import <Foundation/Foundation.h>--/// Handle a keychain command. Returns a response dict.-NSDictionary *vp_handle_keychain_command(NSDictionary *msg);diff --git a/VPhoneDaemon/Native/vphoned_keychain.m b/VPhoneDaemon/Native/vphoned_keychain.mdeleted file mode 100644index 8541e56e..00000000--- a/VPhoneDaemon/Native/vphoned_keychain.m+++ /dev/null@@ -1,207 +0,0 @@-/*- * vphoned_keychain — Remote keychain enumeration over vsock.- *- * Uses both SecItemCopyMatching (for items we're entitled to) and direct- * sqlite3 access to /var/Keychains/keychain-2.db (for everything else).- * The sqlite approach bypasses access-group entitlement checks entirely.- */--#import "vphoned_keychain.h"-#import "vphoned_response.h"-#import <Security/Security.h>-#import <sqlite3.h>--// MARK: - SQLite-based keychain reader--static NSString *KEYCHAIN_DB_PATH = @"/var/Keychains/keychain-2.db";--/// Read a text column, returning @"" if NULL.-static NSString *col_text(sqlite3_stmt *stmt, int col) {- const unsigned char *val = sqlite3_column_text(stmt, col);- if (!val) return @"";- return [NSString stringWithUTF8String:(const char *)val];-}--/// Query one table from the keychain DB via sqlite3.-static NSArray *query_db_table(sqlite3 *db, NSString *table, NSString *className, NSMutableArray *diag) {- // Columns available in genp/inet tables:- // rowid, acct, svce, agrp, labl, data, cdat, mdat, desc, icmt, type, crtr, pdmn- // inet also has: srvr, ptcl, port, path- NSString *sql;- BOOL isInet = [table isEqualToString:@"inet"];- BOOL hasAccountColumns = !([table isEqualToString:@"cert"] || [table isEqualToString:@"keys"]);-- if (isInet) {- sql = [NSString stringWithFormat:- @"SELECT rowid, acct, svce, agrp, labl, data, cdat, mdat, pdmn, srvr, ptcl, port, path FROM %@", table];- } else if (!hasAccountColumns) {- sql = [NSString stringWithFormat:- @"SELECT rowid, agrp, labl, data, cdat, mdat, pdmn FROM %@", table];- } else {- sql = [NSString stringWithFormat:- @"SELECT rowid, acct, svce, agrp, labl, data, cdat, mdat, pdmn FROM %@", table];- }-- sqlite3_stmt *stmt = NULL;- int rc = sqlite3_prepare_v2(db, sql.UTF8String, -1, &stmt, NULL);- if (rc != SQLITE_OK) {- [diag addObject:[NSString stringWithFormat:@"%@: sqlite error %d", className, rc]];- return @[];- }-- NSMutableArray *output = [NSMutableArray array];- while (sqlite3_step(stmt) == SQLITE_ROW) {- NSMutableDictionary *entry = [NSMutableDictionary dictionary];- entry[@"class"] = className;-- int col = 0;- int rowid = sqlite3_column_int(stmt, col++);-- if (hasAccountColumns) {- entry[@"account"] = col_text(stmt, col++);- entry[@"service"] = col_text(stmt, col++);- }- entry[@"accessGroup"] = col_text(stmt, col++);- entry[@"label"] = col_text(stmt, col++);-- // Value data- const void *blob = sqlite3_column_blob(stmt, col);- int blobSize = sqlite3_column_bytes(stmt, col);- if (blob && blobSize > 0) {- NSData *data = [NSData dataWithBytes:blob length:blobSize];- NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];- if (str) {- entry[@"value"] = str;- entry[@"valueEncoding"] = @"utf8";- } else {- entry[@"value"] = [data base64EncodedStringWithOptions:0];- entry[@"valueEncoding"] = @"base64";- }- entry[@"valueSize"] = @(blobSize);- }- col++;-- // Dates (stored as text in sqlite, e.g. "2025-01-15 12:34:56")- NSString *cdat = col_text(stmt, col++);- NSString *mdat = col_text(stmt, col++);- if (cdat.length > 0) entry[@"createdStr"] = cdat;- if (mdat.length > 0) entry[@"modifiedStr"] = mdat;-- // Protection class (pdmn)- NSString *pdmn = col_text(stmt, col++);- if (pdmn.length > 0) entry[@"protection"] = pdmn;-- // inet-specific fields- if (isInet) {- NSString *server = col_text(stmt, col++);- if (server.length > 0) entry[@"server"] = server;- NSString *protocol = col_text(stmt, col++);- if (protocol.length > 0) entry[@"protocol"] = protocol;- int port = sqlite3_column_int(stmt, col++);- if (port > 0) entry[@"port"] = @(port);- NSString *path = col_text(stmt, col++);- if (path.length > 0) entry[@"path"] = path;- }-- // Use rowid for unique ID generation- entry[@"_rowid"] = @(rowid);- [output addObject:entry];- }-- sqlite3_finalize(stmt);-- NSUInteger count = output.count;- if (count > 0) {- [diag addObject:[NSString stringWithFormat:@"%@: %lu rows", className, (unsigned long)count]];- } else {- [diag addObject:[NSString stringWithFormat:@"%@: empty", className]];- }- return output;-}--/// Read all keychain items directly from the sqlite database.-static NSArray *query_keychain_db(NSString *filterClass, NSMutableArray *diag) {- sqlite3 *db = NULL;- int rc = sqlite3_open_v2(KEYCHAIN_DB_PATH.UTF8String, &db, SQLITE_OPEN_READONLY, NULL);- if (rc != SQLITE_OK) {- [diag addObject:[NSString stringWithFormat:@"db open failed: %d", rc]];- NSLog(@"vphoned: sqlite3_open(%@) failed: %d", KEYCHAIN_DB_PATH, rc);- return @[];- }-- [diag addObject:[NSString stringWithFormat:@"opened %@", KEYCHAIN_DB_PATH]];-- NSMutableArray *allItems = [NSMutableArray array];-- NSArray<NSString *> *tables = @[ @"genp", @"inet", @"cert", @"keys" ];-- for (NSString *table in tables) {- if (filterClass && ![filterClass isEqualToString:table]) continue;- [allItems addObjectsFromArray:query_db_table(db, table, table, diag)];- }-- sqlite3_close(db);- return allItems;-}--// MARK: - Command Handler--NSDictionary *vp_handle_keychain_command(NSDictionary *msg) {- id reqId = msg[@"id"];- NSString *type = msg[@"t"];-- // Add a test keychain item (for debugging)- if ([type isEqualToString:@"keychain_add"]) {- NSString *account = msg[@"account"] ?: @"vphone-test";- NSString *service = msg[@"service"] ?: @"vphone";- NSString *password = msg[@"password"] ?: @"testpass123";-- NSDictionary *deleteQuery = @{- (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,- (__bridge id)kSecAttrAccount: account,- (__bridge id)kSecAttrService: service,- };- SecItemDelete((__bridge CFDictionaryRef)deleteQuery);-- NSDictionary *attrs = @{- (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,- (__bridge id)kSecAttrAccount: account,- (__bridge id)kSecAttrService: service,- (__bridge id)kSecAttrLabel: [NSString stringWithFormat:@"%@ (%@)", service, account],- (__bridge id)kSecValueData: [password dataUsingEncoding:NSUTF8StringEncoding],- };-- OSStatus status = SecItemAdd((__bridge CFDictionaryRef)attrs, NULL);- NSLog(@"vphoned: keychain_add: account=%@ service=%@ status=%d", account, service, (int)status);-- NSMutableDictionary *resp = vp_make_response(@"keychain_add", reqId);- resp[@"status"] = @(status);- resp[@"ok"] = @(status == errSecSuccess);- if (status != errSecSuccess) {- resp[@"msg"] = [NSString stringWithFormat:@"Unable to add the keychain item (status %d).", (int)status];- }- return resp;- }-- if ([type isEqualToString:@"keychain_list"]) {- NSString *filterClass = msg[@"class"];- NSMutableArray *diag = [NSMutableArray array];-- // Primary: read directly from sqlite DB (bypasses entitlement checks)- NSArray *dbItems = query_keychain_db(filterClass, diag);-- NSLog(@"vphoned: keychain_list: %lu items (sqlite), diag: %@",- (unsigned long)dbItems.count,- diag);-- NSMutableDictionary *resp = vp_make_response(@"keychain_list", reqId);- resp[@"items"] = dbItems;- resp[@"count"] = @(dbItems.count);- resp[@"diag"] = diag;- return resp;- }-- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = [NSString stringWithFormat:@"unknown keychain command: %@", type];- return r;-}diff --git a/VPhoneDaemon/Native/vphoned_native.m b/VPhoneDaemon/Native/vphoned_native.mindex 0317ef3e..5339fec8 100644--- a/VPhoneDaemon/Native/vphoned_native.m+++ b/VPhoneDaemon/Native/vphoned_native.m@@ -1,7 +1,8 @@#import "Include/VphonedNative.h"#import "vphoned_install.h"-#import "vphoned_keychain.h"#import <CommonCrypto/CommonDigest.h>+#import <dlfcn.h>+#import <objc/message.h>#include <mach-o/dyld.h>#include <unistd.h>@@ -9,11 +10,40 @@ static const char *cache = "/var/root/Library/Caches/vphoned";static const char *marker = "/var/root/Library/Caches/vphoned.api-v2";static const char *pending = "/var/root/Library/Caches/vphoned.api-v2.pending";+int vp_low_power_mode_set_async(bool enabled) {+ dlopen("/System/Library/PrivateFrameworks/LowPowerMode.framework/LowPowerMode", RTLD_NOW);+ Class cls = NSClassFromString(@"_PMLowPowerMode");+ SEL shared = NSSelectorFromString(@"sharedInstance");+ SEL set = NSSelectorFromString(@"setPowerMode:fromSource:withCompletion:");+ if (![cls respondsToSelector:shared]) return -1;+ id service = ((id (*)(Class, SEL))objc_msgSend)(cls, shared);+ if (![service respondsToSelector:set]) return -1;++ dispatch_semaphore_t done = dispatch_semaphore_create(0);+ __block BOOL accepted = NO;+ __block NSError *failure = nil;+ NSLog(@"vphoned: low power mode async request enabled=%d", enabled);+ // The iOS 26 synchronous selector waits for a powerd XPC reply without a+ // deadline. Its completion variant uses an asynchronous remote proxy.+ void (^completion)(BOOL, NSError *) = ^(BOOL applied, NSError *error) {+ accepted = applied;+ failure = error;+ NSLog(@"vphoned: low power mode async reply applied=%d error_domain=%@ error_code=%ld error_info=%@",+ applied, error.domain, (long)error.code, error.userInfo);+ dispatch_semaphore_signal(done);+ };+ ((void (*)(id, SEL, long, NSString *, id))objc_msgSend)(service, set,+ enabled ? 1 : 0, @"ControlCenter", completion);+ if (dispatch_semaphore_wait(done, dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC)) != 0) {+ NSLog(@"vphoned: low power mode async request timed out after 3 seconds");+ return -2;+ }+ return accepted && !failure ? 0 : -3;+}+NSDictionary *vp_native_api_command(NSDictionary *message) {NSString *type = message[@"t"];if ([type isEqualToString:@"ipa_install"]) return vp_handle_custom_install(message);- if ([type isEqualToString:@"keychain_list"] || [type isEqualToString:@"keychain_add"])- return vp_handle_keychain_command(message);return @{@"t": @"err", @"msg": @"Unknown native operation"};}diff --git a/VPhoneDaemon/Native/vphoned_vcam.h b/VPhoneDaemon/Native/vphoned_vcam.hindex bc12da24..aa3c5510 100644--- a/VPhoneDaemon/Native/vphoned_vcam.h+++ b/VPhoneDaemon/Native/vphoned_vcam.h@@ -12,47 +12,15 @@#define VPHONED_VCAM_H#import <Foundation/Foundation.h>+#include "../../VPhoneGuestComponents/VCamCaptured/VCamFrameProtocol.h"#ifdef __cplusplusextern "C" {#endif-/*- * Path of the shared frame file (read by libvcamcaptured).- * Lives under /var/jb so cameracaptured's sandbox allows reads.- */-#ifndef VPHONED_VCAM_SHM_PATH-#define VPHONED_VCAM_SHM_PATH \- "/var/jb/var/mobile/Library/vphone-vcam-frame.shm"-#endif#ifndef VPHONED_VCAM_VSOCK_PORT#define VPHONED_VCAM_VSOCK_PORT 1338#endif-#ifndef VPHONED_VCAM_NOTIFY_NAME-#define VPHONED_VCAM_NOTIFY_NAME "com.vphone.vcam.frame"-#endif--/* Shared-memory layout. seq increments by 2 per frame; odd values mean- * a write is in progress. Readers re-check seq after copying to detect- * mid-write tearing. */-typedef struct __attribute__((packed)) {- uint64_t seq;- uint32_t width;- uint32_t height;- uint32_t bytes_per_row;- uint32_t pixel_format; /* 4cc */- uint32_t _reserved;- uint64_t timestamp_ns;- uint64_t frame_index;- uint32_t pixels_length;- uint32_t _pad;- /* pixels start at offset 64; capacity = total mmap size - 64. */-} vphoned_vcam_shm_header_t;--#define VPHONED_VCAM_SHM_HEADER_SIZE 64-#define VPHONED_VCAM_SHM_MAX_PIXELS (8 * 1024 * 1024) /* 8 MiB */-#define VPHONED_VCAM_SHM_TOTAL_SIZE \- (VPHONED_VCAM_SHM_HEADER_SIZE + VPHONED_VCAM_SHM_MAX_PIXELS)/* Starts the listener on a background thread. Idempotent. */void vp_vcam_start(void);diff --git a/VPhoneDaemon/Native/vphoned_vcam.m b/VPhoneDaemon/Native/vphoned_vcam.mindex df9dd01a..3b685914 100644--- a/VPhoneDaemon/Native/vphoned_vcam.m+++ b/VPhoneDaemon/Native/vphoned_vcam.m@@ -18,6 +18,8 @@#include <fcntl.h>#include <notify.h>#include <pthread.h>+#include <pwd.h>+#include <stdarg.h>#include <stdatomic.h>#include <stdint.h>#include <stdio.h>@@ -27,52 +29,75 @@#include <sys/socket.h>#include <sys/stat.h>#include <sys/types.h>+#include <sys/vsock.h>#include <unistd.h>-#ifndef AF_VSOCK-#define AF_VSOCK 40-#endif-#ifndef VMADDR_CID_ANY-#define VMADDR_CID_ANY 0xFFFFFFFFu-#endif--struct vp_sockaddr_vm {- __uint8_t svm_len;- sa_family_t svm_family;- __uint16_t svm_reserved1;- __uint32_t svm_port;- __uint32_t svm_cid;-};-static pthread_once_t s_start_once = PTHREAD_ONCE_INIT;static uint8_t *s_shm_base = NULL;static int s_notify_token = -1;-#define VVC_LOG_PATH "/var/jb/var/mobile/Library/vphone-vcam.log"-__attribute__((format(printf, 1, 2)))static void vvc_logf(const char *fmt, ...) {- FILE *fp = fopen(VVC_LOG_PATH, "a");- if (!fp) return;+ FILE *fp = fopen(VPHONE_VCAM_DAEMON_LOG_PATH, "a");va_list ap;va_start(ap, fmt);- vfprintf(fp, fmt, ap);+ if (!fp) {+ char message[1024];+ vsnprintf(message, sizeof(message), fmt, ap);+ NSLog(@"%s", message);+ } else {+ vfprintf(fp, fmt, ap);+ fputc('\n', fp);+ fclose(fp);+ }va_end(ap);- fputc('\n', fp);- fclose(fp);}static int open_shm(void) {+ /* Wait for mobile's home before creating its media directory. */+ struct passwd *mobile_user = getpwnam("mobile");+ struct stat mobile_home;+ if (!mobile_user || stat("/var/mobile", &mobile_home) < 0 ||+ !S_ISDIR(mobile_home.st_mode) || mobile_home.st_uid != mobile_user->pw_uid) {+ vvc_logf("vphoned_vcam: mobile home is not ready");+ return -1;+ }+ NSString *directory = [NSString stringWithUTF8String:VPHONE_VCAM_DIRECTORY];+ NSError *error = nil;+ if (![[NSFileManager defaultManager] createDirectoryAtPath:directory+ withIntermediateDirectories:YES+ attributes:@{NSFilePosixPermissions: @0755}+ error:&error]) {+ vvc_logf("vphoned_vcam: create(%s) failed: %s", directory.UTF8String,+ error.localizedDescription.UTF8String);+ return -1;+ }+ int directory_fd = open(VPHONE_VCAM_DIRECTORY, O_RDONLY | O_DIRECTORY | O_NOFOLLOW);+ if (directory_fd < 0) {+ vvc_logf("vphoned_vcam: open directory failed: %s", strerror(errno));+ return -1;+ }+ if (fchown(directory_fd, mobile_user->pw_uid, mobile_user->pw_gid) < 0) {+ vvc_logf("vphoned_vcam: chown directory failed: %s", strerror(errno));+ close(directory_fd);+ return -1;+ }+ if (fchmod(directory_fd, 0755) < 0) {+ vvc_logf("vphoned_vcam: chmod directory failed: %s", strerror(errno));+ close(directory_fd);+ return -1;+ }+ close(directory_fd);/* Truncate to total size each fresh open so a stale half-written file* from a previous boot doesn't confuse readers. */- int fd = open(VPHONED_VCAM_SHM_PATH, O_RDWR | O_CREAT, 0644);+ int fd = open(VPHONE_VCAM_SHM_PATH, O_RDWR | O_CREAT, 0644);if (fd < 0) {vvc_logf("vphoned_vcam: open(%s) failed: %s",- VPHONED_VCAM_SHM_PATH,+ VPHONE_VCAM_SHM_PATH,strerror(errno));return -1;}- if (ftruncate(fd, VPHONED_VCAM_SHM_TOTAL_SIZE) < 0) {+ if (ftruncate(fd, VPHONE_VCAM_SHM_TOTAL_SIZE) < 0) {vvc_logf("vphoned_vcam: ftruncate failed: %s", strerror(errno));close(fd);return -1;@@ -81,7 +106,7 @@ static int open_shm(void) {fchmod(fd, 0644);void *base = mmap(NULL,- VPHONED_VCAM_SHM_TOTAL_SIZE,+ VPHONE_VCAM_SHM_TOTAL_SIZE,PROT_READ | PROT_WRITE,MAP_SHARED,fd,@@ -92,7 +117,7 @@ static int open_shm(void) {return -1;}/* Zero the header on first init so seq starts at 0. */- memset(base, 0, VPHONED_VCAM_SHM_HEADER_SIZE);+ memset(base, 0, VPHONE_VCAM_SHM_HEADER_SIZE);s_shm_base = (uint8_t *)base;return 0;}@@ -118,12 +143,12 @@ static void publish_frame(uint32_t w,const uint8_t *pixels,size_t pixel_len) {if (!s_shm_base) return;- if (pixel_len > VPHONED_VCAM_SHM_MAX_PIXELS) {+ if (pixel_len > VPHONE_VCAM_SHM_MAX_PIXELS) {vvc_logf("vphoned_vcam: frame too large: %zu", pixel_len);return;}- vphoned_vcam_shm_header_t *hdr = (vphoned_vcam_shm_header_t *)s_shm_base;- uint8_t *dst = s_shm_base + VPHONED_VCAM_SHM_HEADER_SIZE;+ vphone_vcam_shm_header_t *hdr = (vphone_vcam_shm_header_t *)s_shm_base;+ uint8_t *dst = s_shm_base + VPHONE_VCAM_SHM_HEADER_SIZE;uint64_t prev_seq = atomic_load_explicit((_Atomic uint64_t *)&hdr->seq, memory_order_acquire);@@ -150,7 +175,7 @@ static void publish_frame(uint32_t w,memory_order_release);if (s_notify_token >= 0) {- notify_post(VPHONED_VCAM_NOTIFY_NAME);+ notify_post(VPHONE_VCAM_NOTIFY_NAME);}}@@ -161,8 +186,8 @@ static void handle_client(int fd) {uint32_t total_len = 0, header_len = 0;if (read_full(fd, &total_len, 4) <= 0) break;if (read_full(fd, &header_len, 4) <= 0) break;- if (total_len < 4 || header_len + 4 > total_len ||- total_len > VPHONED_VCAM_SHM_MAX_PIXELS + 4096) {+ if (total_len < 4 || header_len > total_len - 4 ||+ total_len > VPHONE_VCAM_SHM_MAX_PIXELS + 4096) {vvc_logf("vphoned_vcam: framing error total=%u header=%u",total_len,header_len);@@ -225,10 +250,10 @@ static void handle_client(int fd) {}static void *listener_thread(__unused void *unused) {- if (open_shm() < 0) return NULL;+ while (open_shm() < 0) sleep(3);/* Register the notify name so notify_post() actually delivers. */- if (notify_register_check(VPHONED_VCAM_NOTIFY_NAME,+ if (notify_register_check(VPHONE_VCAM_NOTIFY_NAME,&s_notify_token) != NOTIFY_STATUS_OK) {s_notify_token = -1;}@@ -241,7 +266,7 @@ static void *listener_thread(__unused void *unused) {int one = 1;setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));- struct vp_sockaddr_vm addr = {+ struct sockaddr_vm addr = {.svm_len = sizeof(addr),.svm_family = AF_VSOCK,.svm_port = VPHONED_VCAM_VSOCK_PORT,@@ -261,7 +286,7 @@ static void *listener_thread(__unused void *unused) {}vvc_logf("vphoned_vcam: listening on vsock %d, shm=%s",VPHONED_VCAM_VSOCK_PORT,- VPHONED_VCAM_SHM_PATH);+ VPHONE_VCAM_SHM_PATH);for (;;) {int fd = accept(srv, NULL, NULL);diff --git a/VPhoneDaemon/Native/vpregister.m b/VPhoneDaemon/Native/vpregister.mdeleted file mode 100644index 617c6ad6..00000000--- a/VPhoneDaemon/Native/vpregister.m+++ /dev/null@@ -1,78 +0,0 @@-// vpregister — register JB app bundles on iOS 27 via the containerized-// LaunchServices API (the modern replacement for the deprecated, gutted-// -[LSApplicationWorkspace registerApplicationDictionary:] that uicache -a-// uses). Requires the lsd clientIsEntitledForEmbeddedRegistrationOperations-// gate patch (cfw_patch_lsd_embedded_reg). Usage: vpregister [app.app ...]-// (no args = scan /var/jb/Applications/*.app).-#import <Foundation/Foundation.h>-#import <dlfcn.h>-#import <objc/message.h>-@interface LSApplicationWorkspace : NSObject-+ (instancetype)defaultWorkspace;-- (BOOL)registerContainerizedApplicationWithInfoDictionaries:(NSArray *)infos- operationUUID:(NSUUID *)uuid- requestContext:(id)context- saveObserver:(id)observer- registrationError:(NSError **)error;-@end-static BOOL register_app(LSApplicationWorkspace *ws, NSString *path) {- NSDictionary *info =- [NSDictionary dictionaryWithContentsOfFile:[path stringByAppendingPathComponent:@"Info.plist"]];- NSString *bundleID = info[@"CFBundleIdentifier"];- if (bundleID.length == 0) return NO;- NSDictionary *dictToRegister = @{- @"Path" : path,- @"CFBundleIdentifier" : bundleID,- @"CodeInfoIdentifier" : bundleID,- @"ApplicationType" : @"System",- @"CompatibilityState" : @0,- @"SignerIdentity" : @"Apple iPhone OS Application Signing",- @"SignerOrganization" : @"Apple Inc.",- @"IsAdHocSigned" : @YES,- @"SignatureVersion" : @132352,- @"IsDeletable" : @YES,- };- NSError *err = nil;- // The containerized API returns NO even when registration succeeds, so a nil- // registrationError is the success signal (same rule as vphoned_install.m's- // containerized path).- [ws registerContainerizedApplicationWithInfoDictionaries:@[dictToRegister]- operationUUID:[NSUUID UUID]- requestContext:nil- saveObserver:nil- registrationError:&err];- if (err) fprintf(stderr, " Unable to register: %s\n", err.description.UTF8String);- return err == nil;-}-int main(int argc, char **argv) {- @autoreleasepool {- dlopen("/System/Library/Frameworks/CoreServices.framework/CoreServices", RTLD_NOW);- Class workspaceClass = NSClassFromString(@"LSApplicationWorkspace");- if (!workspaceClass) {- fprintf(stderr, "LaunchServices workspace is unavailable\n");- return 1;- }- LSApplicationWorkspace *ws = ((id (*)(id, SEL))objc_msgSend)(- workspaceClass,- @selector(defaultWorkspace));- if (!ws) {- fprintf(stderr, "LaunchServices workspace could not be opened\n");- return 1;- }- NSMutableArray *paths = [NSMutableArray array];- for (int i = 1; i < argc; i++) [paths addObject:@(argv[i])];- if (paths.count == 0) {- NSString *dir = @"/var/jb/Applications";- for (NSString *bundleName in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dir error:nil])- if ([bundleName hasSuffix:@".app"]) [paths addObject:[dir stringByAppendingPathComponent:bundleName]];- }- int fail = 0;- for (NSString *appPath in paths) {- BOOL registered = register_app(ws, appPath);- printf("%-10s %s\n", registered ? "Registered" : "Failed", appPath.UTF8String);- if (!registered) fail++;- }- printf("Registered %d, failed %d\n", (int)paths.count - fail, fail);- return fail ? 1 : 0;- }-}diff --git a/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.pbxproj b/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.pbxprojindex 97021953..d006f3f2 100644--- a/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.pbxproj+++ b/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.pbxproj@@ -14,6 +14,7 @@C10000000000000000000015 /* NIOPosix in Frameworks */ = {isa = PBXBuildFile; productRef = C10000000000000000000064 /* NIOPosix */; };C10000000000000000000016 /* NIOWebSocket in Frameworks */ = {isa = PBXBuildFile; productRef = C10000000000000000000065 /* NIOWebSocket */; };C10000000000000000000017 /* LibArchive in Frameworks */ = {isa = PBXBuildFile; productRef = C10000000000000000000066 /* LibArchive */; };+ C10000000000000000000018 /* IcliSystem in Frameworks */ = {isa = PBXBuildFile; productRef = C10000000000000000000068 /* IcliSystem */; };/* End PBXBuildFile section *//* Begin PBXContainerItemProxy section */@@ -29,32 +30,10 @@/* Begin PBXFileReference section */C10000000000000000000001 /* libVphonedNative.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libVphonedNative.a; sourceTree = BUILT_PRODUCTS_DIR; };C10000000000000000000002 /* vphoned */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = vphoned; sourceTree = BUILT_PRODUCTS_DIR; };- C10000000000000000000003 /* vpregister */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = vpregister; sourceTree = BUILT_PRODUCTS_DIR; };/* End PBXFileReference section */-/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */- C10000000000000000000035 /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {- isa = PBXFileSystemSynchronizedBuildFileExceptionSet;- membershipExceptions = (- vpregister.m,- );- target = C10000000000000000000081 /* VphonedNative */;- };- C10000000000000000000036 /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {- isa = PBXFileSystemSynchronizedBuildFileExceptionSet;- membershipExceptions = (- unarchive.m,- vphoned_install.m,- vphoned_keychain.m,- vphoned_native.m,- vphoned_vcam.m,- );- target = C10000000000000000000083 /* vpregister */;- };-/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */-/* Begin PBXFileSystemSynchronizedRootGroup section */- C10000000000000000000031 /* Native */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (C10000000000000000000035 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, C10000000000000000000036 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = Native; sourceTree = "<group>"; };+ C10000000000000000000031 /* Native */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = Native; sourceTree = "<group>"; };C10000000000000000000032 /* Daemon */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = Daemon; sourceTree = "<group>"; };C10000000000000000000033 /* Configuration */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = Configuration; sourceTree = "<group>"; };/* End PBXFileSystemSynchronizedRootGroup section */@@ -78,13 +57,7 @@C10000000000000000000015 /* NIOPosix in Frameworks */,C10000000000000000000016 /* NIOWebSocket in Frameworks */,C10000000000000000000017 /* LibArchive in Frameworks */,- );- runOnlyForDeploymentPostprocessing = 0;- };- C10000000000000000000043 /* Frameworks */ = {- isa = PBXFrameworksBuildPhase;- buildActionMask = 2147483647;- files = (+ C10000000000000000000018 /* IcliSystem in Frameworks */,);runOnlyForDeploymentPostprocessing = 0;};@@ -106,7 +79,6 @@children = (C10000000000000000000001 /* libVphonedNative.a */,C10000000000000000000002 /* vphoned */,- C10000000000000000000003 /* vpregister */,);name = Products;sourceTree = "<group>";@@ -137,6 +109,7 @@isa = PBXNativeTarget;buildConfigurationList = C10000000000000000000092 /* Build configuration list for PBXNativeTarget "vphoned" */;buildPhases = (+ C100000000000000000000A4 /* Build Guest Signer */,C100000000000000000000A2 /* Sources */,C10000000000000000000042 /* Frameworks */,);@@ -156,30 +129,12 @@C10000000000000000000064 /* NIOPosix */,C10000000000000000000065 /* NIOWebSocket */,C10000000000000000000066 /* LibArchive */,+ C10000000000000000000068 /* IcliSystem */,);productName = vphoned;productReference = C10000000000000000000002 /* vphoned */;productType = "com.apple.product-type.tool";};- C10000000000000000000083 /* vpregister */ = {- isa = PBXNativeTarget;- buildConfigurationList = C10000000000000000000094 /* Build configuration list for PBXNativeTarget "vpregister" */;- buildPhases = (- C100000000000000000000A3 /* Sources */,- C10000000000000000000043 /* Frameworks */,- );- buildRules = (- );- dependencies = (- );- fileSystemSynchronizedGroups = (- C10000000000000000000031 /* Native */,- );- name = vpregister;- productName = vpregister;- productReference = C10000000000000000000003 /* vpregister */;- productType = "com.apple.product-type.tool";- };/* End PBXNativeTarget section *//* Begin PBXProject section */@@ -208,27 +163,37 @@targets = (C10000000000000000000081 /* VphonedNative */,C10000000000000000000082 /* vphoned */,- C10000000000000000000083 /* vpregister */,);};/* End PBXProject section */-/* Begin PBXSourcesBuildPhase section */- C100000000000000000000A1 /* Sources */ = {- isa = PBXSourcesBuildPhase;+/* Begin PBXShellScriptBuildPhase section */+ C100000000000000000000A4 /* Build Guest Signer */ = {+ isa = PBXShellScriptBuildPhase;+ alwaysOutOfDate = 1;buildActionMask = 2147483647;files = ();+ inputPaths = (+ );+ name = "Build Guest Signer";+ outputPaths = (+ );runOnlyForDeploymentPostprocessing = 0;+ shellPath = /bin/zsh;+ shellScript = "set -euo pipefail\nroot=\"$(cd \"$SRCROOT/..\" && pwd)\"\n/usr/bin/env -i HOME=\"$HOME\" TMPDIR=\"${TMPDIR:-/tmp}\" PATH=\"/usr/bin:/bin:/usr/sbin:/sbin\" /usr/bin/xcodebuild -project \"$root/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj\" -scheme VPhoneSign -configuration \"$CONFIGURATION\" -destination 'generic/platform=iOS' -derivedDataPath \"$root/.build/XcodeSignGuest-$CONFIGURATION\" CODE_SIGNING_ALLOWED=NO build\n";};- C100000000000000000000A2 /* Sources */ = {+/* End PBXShellScriptBuildPhase section */++/* Begin PBXSourcesBuildPhase section */+ C100000000000000000000A1 /* Sources */ = {isa = PBXSourcesBuildPhase;buildActionMask = 2147483647;files = ();runOnlyForDeploymentPostprocessing = 0;};- C100000000000000000000A3 /* Sources */ = {+ C100000000000000000000A2 /* Sources */ = {isa = PBXSourcesBuildPhase;buildActionMask = 2147483647;files = (@@ -299,8 +264,11 @@DEFINES_MODULE = YES;HEADER_SEARCH_PATHS = "$(PROJECT_DIR)/Native/Include";IPHONEOS_DEPLOYMENT_TARGET = 15.0;+ LIBRARY_SEARCH_PATHS = "$(SRCROOT)/../.build/XcodeSignGuest-$(CONFIGURATION)/Build/Products/$(CONFIGURATION)-iphoneos";+ OTHER_LDFLAGS = "-lVPhoneSign";PRODUCT_NAME = "$(TARGET_NAME)";SDKROOT = iphoneos;+ SWIFT_INCLUDE_PATHS = "$(SRCROOT)/../.build/XcodeSignGuest-$(CONFIGURATION)/Build/Products/$(CONFIGURATION)-iphoneos";SWIFT_STRICT_CONCURRENCY = complete;SWIFT_VERSION = 6.0;};@@ -313,8 +281,11 @@DEFINES_MODULE = YES;HEADER_SEARCH_PATHS = "$(PROJECT_DIR)/Native/Include";IPHONEOS_DEPLOYMENT_TARGET = 15.0;+ LIBRARY_SEARCH_PATHS = "$(SRCROOT)/../.build/XcodeSignGuest-$(CONFIGURATION)/Build/Products/$(CONFIGURATION)-iphoneos";+ OTHER_LDFLAGS = "-lVPhoneSign";PRODUCT_NAME = "$(TARGET_NAME)";SDKROOT = iphoneos;+ SWIFT_INCLUDE_PATHS = "$(SRCROOT)/../.build/XcodeSignGuest-$(CONFIGURATION)/Build/Products/$(CONFIGURATION)-iphoneos";SWIFT_STRICT_CONCURRENCY = complete;SWIFT_VERSION = 6.0;};@@ -342,28 +313,6 @@};name = Release;};- C100000000000000000000B7 /* Debug */ = {- isa = XCBuildConfiguration;- buildSettings = {- ARCHS = arm64e;- CLANG_ENABLE_OBJC_ARC = YES;- IPHONEOS_DEPLOYMENT_TARGET = 15.0;- PRODUCT_NAME = vpregister;- SDKROOT = iphoneos;- };- name = Debug;- };- C100000000000000000000B8 /* Release */ = {- isa = XCBuildConfiguration;- buildSettings = {- ARCHS = arm64e;- CLANG_ENABLE_OBJC_ARC = YES;- IPHONEOS_DEPLOYMENT_TARGET = 15.0;- PRODUCT_NAME = vpregister;- SDKROOT = iphoneos;- };- name = Release;- };/* End XCBuildConfiguration section *//* Begin XCConfigurationList section */@@ -394,15 +343,6 @@defaultConfigurationIsVisible = 0;defaultConfigurationName = Release;};- C10000000000000000000094 /* Build configuration list for PBXNativeTarget "vpregister" */ = {- isa = XCConfigurationList;- buildConfigurations = (- C100000000000000000000B7 /* Debug */,- C100000000000000000000B8 /* Release */,- );- defaultConfigurationIsVisible = 0;- defaultConfigurationName = Release;- };/* End XCConfigurationList section *//* Begin XCRemoteSwiftPackageReference section */@@ -411,7 +351,7 @@repositoryURL = "https://github.com/owngoal-dev/icli.git";requirement = {kind = exactVersion;- version = 0.6.1;+ version = 0.6.3;};};C10000000000000000000072 /* XCRemoteSwiftPackageReference "swift-nio" */ = {@@ -471,6 +411,11 @@package = C10000000000000000000073 /* XCRemoteSwiftPackageReference "libarchive.xcframework" */;productName = LibArchive;};+ C10000000000000000000068 /* IcliSystem */ = {+ isa = XCSwiftPackageProductDependency;+ package = C10000000000000000000071 /* XCRemoteSwiftPackageReference "icli" */;+ productName = IcliSystem;+ };/* End XCSwiftPackageProductDependency section */};rootObject = C100000000000000000000F0 /* Project object */;diff --git a/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolvedindex 6f89829c..d79a07dd 100644--- a/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved+++ b/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved@@ -1,13 +1,13 @@{- "originHash" : "c5727c1f3616a5e260c03cfb3f864a169a2b87fa2d8eed64ef143ee8be072b09",+ "originHash" : "00413e50535a5795694962f3fb733b172429718565c2a71af5da825f070189a2","pins" : [{"identity" : "icli","kind" : "remoteSourceControl","location" : "https://github.com/owngoal-dev/icli.git","state" : {- "revision" : "c3407df5f160919b5eb7d2fefb5a5c21351314fb",- "version" : "0.6.1"+ "revision" : "ee01bde8ceeb4c90779427674185e353bf8e022d",+ "version" : "0.6.3"}},{diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj/project.pbxproj b/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj/project.pbxprojindex bbac75b3..aaeb104c 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj/project.pbxproj+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj/project.pbxproj@@ -465,10 +465,12 @@CODE_SIGNING_ALLOWED = NO;DEFINES_MODULE = YES;ENABLE_TESTABILITY = YES;+ IPHONEOS_DEPLOYMENT_TARGET = 15.0;MACOSX_DEPLOYMENT_TARGET = 15.0;PRODUCT_NAME = VPhoneSign;- SDKROOT = macosx;+ SDKROOT = auto;SKIP_INSTALL = YES;+ SUPPORTED_PLATFORMS = "macosx iphoneos";SWIFT_STRICT_CONCURRENCY = complete;SWIFT_VERSION = 6.0;};@@ -481,10 +483,12 @@ARCHS = arm64;CODE_SIGNING_ALLOWED = NO;DEFINES_MODULE = YES;+ IPHONEOS_DEPLOYMENT_TARGET = 15.0;MACOSX_DEPLOYMENT_TARGET = 15.0;PRODUCT_NAME = VPhoneSign;- SDKROOT = macosx;+ SDKROOT = auto;SKIP_INSTALL = YES;+ SUPPORTED_PLATFORMS = "macosx iphoneos";SWIFT_STRICT_CONCURRENCY = complete;SWIFT_VERSION = 6.0;};diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.shindex 085c9a33..354aca68 100755--- a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh+++ b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh@@ -30,11 +30,6 @@ build_project -project "$root/VPhoneDaemon/VPhoneDaemon.xcodeproj" \-destination 'generic/platform=iOS' \-derivedDataPath "$root/.build/XcodeDaemon" CODE_SIGNING_ALLOWED=NO build-build_project -project "$root/VPhoneDaemon/VPhoneDaemon.xcodeproj" \- -scheme vpregister -configuration "$configuration" \- -destination 'generic/platform=iOS' \- -derivedDataPath "$root/.build/XcodeDaemon" CODE_SIGNING_ALLOWED=NO build-build_project -project "$root/VPhoneExecutable/VPhoneEscalator/VPhoneEscalator.xcodeproj" \-scheme VPhoneEscalator -configuration "$configuration" \-destination 'platform=macOS,arch=arm64e' \@@ -60,7 +55,6 @@ fi/bin/cp "$command_products/vphone-cli" "$macos/vphone-cli"/bin/cp "$daemon_products/vphoned" "$macos/vphoned"/bin/cp "$daemon_products/vphoned" "$macos/vphoned.signed"-/bin/cp "$daemon_products/vpregister" "$macos/vpregister"/bin/cp "$amfi_products/VPhoneEscalator" "$macos/VPhoneEscalator"/bin/cp "$guest_products/camfix/libcamfix.dylib" "$macos/libcamfix.dylib"/bin/cp "$guest_products/vcamcaptured/libvcamcaptured.dylib" "$macos/libvcamcaptured.dylib"@@ -85,7 +79,6 @@ compatibility_library="$(/usr/bin/xcrun swift-stdlib-tool --print \/usr/bin/codesign --force --sign - "$macos/vphone-cli"/usr/bin/codesign --force --sign - --entitlements "$root/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements" "$macos/vphoned"/usr/bin/codesign --force --sign - --entitlements "$root/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements" "$macos/vphoned.signed"-/usr/bin/codesign --force --sign - "$macos/vpregister"/usr/bin/codesign --force --sign - "$macos/VPhoneEscalator"/usr/bin/codesign --force --sign - "$macos/libswiftCompatibilitySpan.vphone.dylib"/usr/bin/codesign --force --sign - --entitlements "$root/VPhoneExecutable/VPhoneVirtualization/Resources/VPhoneVirtualization.entitlements" "$macos/vphone-vm"diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swiftindex fb135a52..2e96a876 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift@@ -34,6 +34,8 @@ final class VPhoneGuestControl {private weak var device: VZVirtioSocketDevice?private var monitor: Task<Void, Never>?private var orderedInput: Task<Void, Never>?+ private var orderedLocation: Task<Void, Never>?+ private var locationGeneration: UInt64 = 0private(set) var isConnected = falseprivate(set) var guestCapabilities: [String] = []private(set) var guestIPAddress: String?@@ -65,6 +67,8 @@ final class VPhoneGuestControl {monitor = nilorderedInput?.cancel()orderedInput = nil+ orderedLocation?.cancel()+ orderedLocation = nildevice = nilsetDisconnected()}@@ -167,6 +171,18 @@ final class VPhoneGuestControl {return value?["binary_hash"] as? String ?? "unknown"}+ func screenshotJPEG() async throws -> Data {+ let result = try await call("screen.screenshot")+ guard result["mime_type"] as? String == "image/jpeg",+ let encoded = result["data"] as? String,+ let data = Data(base64Encoded: encoded),+ data.starts(with: [0xFF, 0xD8])+ else {+ throw ControlError.protocolError("invalid guest screenshot")+ }+ return data+ }+/// Retains the UI-facing request shape while all transport and guest/// operations use the versioned HTTP API.func sendRequest(_ request: [String: Any]) async throws -> ([String: Any], Data?) {@@ -198,6 +214,7 @@ final class VPhoneGuestControl {case "app_foreground": method = "apps.foreground"case "keychain_list": method = "keychain.list"case "keychain_add": method = "keychain.add"+ case "keychain_delete": method = "keychain.delete"case "open_url": method = "apps.open_url"case "settings_get": method = "settings.get"case "settings_set": method = "settings.set"@@ -308,18 +325,30 @@ final class VPhoneGuestControl {speed: Double,course: Double,) {- Task {- do { _ = try await call("location.set", params: [- "latitude": latitude, "longitude": longitude, "altitude": altitude,- "horizontal_accuracy": horizontalAccuracy, "vertical_accuracy": verticalAccuracy,- "speed": speed, "course": course,- ]) } catch { print("[control] location: \(error)") }- }+ var params: [String: Any] = [+ "latitude": latitude, "longitude": longitude, "altitude": altitude,+ "horizontal_accuracy": horizontalAccuracy, "vertical_accuracy": verticalAccuracy,+ ]+ // CoreLocation uses negative values for unavailable speed and course.+ // IcliKit expects those fields to be absent in that case.+ if speed >= 0 { params["speed"] = speed }+ if course >= 0 { params["course"] = course }+ enqueueLocation("location.set", params: params)}func sendLocationStop() {- Task { do { _ = try await call("location.clear") }- catch { print("[control] location clear: \(error)") }+ enqueueLocation("location.clear")+ }++ private func enqueueLocation(_ method: String, params: [String: Any] = [:]) {+ locationGeneration &+= 1+ let generation = locationGeneration+ let previous = orderedLocation+ orderedLocation = Task {+ await previous?.value+ guard !Task.isCancelled, generation == locationGeneration else { return }+ do { _ = try await call(method, params: params) }+ catch { print("[control] \(method): \(error)") }}}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlApps.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlApps.swiftindex d3b5e1d2..d6bd9fe2 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlApps.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlApps.swift@@ -31,25 +31,35 @@ extension VPhoneGuestControl {}}- func appLaunch(bundleId: String, url: String? = nil) async throws -> Int {+ func appLaunch(bundleId: String, url: String? = nil) async throws -> (+ pid: Int, frontmostVerified: Bool, warning: String?+ ) {var req: [String: Any] = ["t": "app_launch", "bundle_id": bundleId]if let url {req["url"] = url}let (resp, _) = try await sendRequest(req)- return resp["pid"] as? Int ?? 0+ return (+ pid: resp["pid"] as? Int ?? 0,+ frontmostVerified: resp["frontmost_verified"] as? Bool ?? false,+ warning: resp["warning"] as? String,+ )}func appTerminate(bundleId: String) async throws {_ = try await sendRequest(["t": "app_terminate", "bundle_id": bundleId])}- func appForeground() async throws -> (bundleId: String, name: String, pid: Int) {+ func appForeground() async throws -> (+ bundleId: String, name: String, pid: Int, verified: Bool, source: String+ ) {let (resp, _) = try await sendRequest(["t": "app_foreground"])return (bundleId: resp["bundle_id"] as? String ?? "",name: resp["name"] as? String ?? "",pid: resp["pid"] as? Int ?? 0,+ verified: resp["verified"] as? Bool ?? false,+ source: resp["source"] as? String ?? "",)}}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlKeychain.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlKeychain.swiftindex 107a0e39..98b7cf1f 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlKeychain.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlKeychain.swift@@ -33,4 +33,14 @@ extension VPhoneGuestControl {throw ControlError.protocolError("keychain_add: \(msg)")}}++ func deleteKeychainItem(account: String, service: String) async throws -> Bool {+ let (resp, _) = try await sendRequest([+ "t": "keychain_delete", "account": account, "service": service,+ ])+ guard resp["ok"] as? Bool == true else {+ throw ControlError.guestError(resp["msg"] as? String ?? "Unable to delete the keychain item")+ }+ return resp["removed"] as? Bool ?? false+ }}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/HostDevices/VPhoneCameraServer.swift b/VPhoneExecutable/VPhoneVirtualization/UI/HostDevices/VPhoneCameraServer.swiftindex 89a044e3..aabc9c49 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/HostDevices/VPhoneCameraServer.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/HostDevices/VPhoneCameraServer.swift@@ -6,8 +6,8 @@ import Virtualization////// Opens a vsock connection to the guest on port 1338 (separate from the/// vphoned control channel on 1337) and pushes raw BGRA frames at a fixed-/// rate. The guest counterpart (a libvcamcaptured-attached receiver inside-/// cameracaptured) ferries those frames into the AVF capture pipeline.+/// rate. vphoned receives frames on that port and publishes shared memory;+/// the optional libvcamcaptured hook consumes it inside cameracaptured.////// Wire format (one frame, length-prefixed):/// uint32 LE total_payload_lengthdiff --git a/VPhoneExecutable/VPhoneVirtualization/UI/HostDevices/VPhoneScreenRecorder.swift b/VPhoneExecutable/VPhoneVirtualization/UI/HostDevices/VPhoneScreenRecorder.swiftindex 20179d76..b0c632ca 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/HostDevices/VPhoneScreenRecorder.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/HostDevices/VPhoneScreenRecorder.swift@@ -122,47 +122,36 @@ class VPhoneScreenRecorder {return url}- func copyScreenshotToPasteboard(view: NSView) async throws {- let cgImage = try await captureStillImage(from: view)-- let data = NSMutableData()- guard let dest = CGImageDestinationCreateWithData(data, "public.jpeg" as CFString, 1, nil) else {- throw CaptureError.clipboardWriteFailed- }- CGImageDestinationAddImage(dest, cgImage, nil)- guard CGImageDestinationFinalize(dest) else {- throw CaptureError.clipboardWriteFailed- }-+ func copyScreenshotToPasteboard(jpegData: Data) throws {let pasteboard = NSPasteboard.generalpasteboard.clearContents()- pasteboard.setData(data as Data, forType: .init("public.jpeg"))-- print("[record] screenshot copied to clipboard")+ guard pasteboard.setData(jpegData, forType: .init("public.jpeg")) else {+ throw CaptureError.clipboardWriteFailed+ }+ print("[record] guest screenshot copied to clipboard")}- func saveScreenshot(view: NSView) async throws -> URL {- try await saveScreenshot(view: view, to: screenshotOutputURL())+ func saveScreenshot(jpegData: Data) throws -> URL {+ let url = screenshotOutputURL()+ return try saveScreenshot(jpegData: jpegData, to: url)}- func saveScreenshot(view: NSView, to url: URL) async throws -> URL {- let cgImage = try await captureStillImage(from: view)- let utType = url.pathExtension.lowercased() == "png" ? "public.png" : "public.jpeg"-- guard let dest = CGImageDestinationCreateWithURL(- url as CFURL,- utType as CFString,- 1,- nil,- ) else {- throw CaptureError.encodingFailed- }- CGImageDestinationAddImage(dest, cgImage, nil)- guard CGImageDestinationFinalize(dest) else {+ func saveScreenshot(jpegData: Data, to url: URL) throws -> URL {+ do {+ if url.pathExtension.lowercased() == "png" {+ guard let source = CGImageSourceCreateWithData(jpegData as CFData, nil),+ let image = CGImageSourceCreateImageAtIndex(source, 0, nil),+ let destination = CGImageDestinationCreateWithURL(url as CFURL, "public.png" as CFString, 1, nil)+ else { throw CaptureError.encodingFailed }+ CGImageDestinationAddImage(destination, image, nil)+ guard CGImageDestinationFinalize(destination) else { throw CaptureError.encodingFailed }+ } else {+ try jpegData.write(to: url, options: .atomic)+ }+ } catch {throw CaptureError.encodingFailed}-- print("[record] screenshot saved - \(url.path)")+ print("[record] guest screenshot saved - \(url.path)")return url}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileBrowserModel.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileBrowserModel.swiftindex ff74cc74..9dadc22e 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileBrowserModel.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileBrowserModel.swift@@ -28,6 +28,7 @@ class VPhoneFileBrowserModel {/// Navigation stacksprivate var pathHistory: [String] = []private var forwardHistory: [String] = []+ private var refreshGeneration = 0init(control: VPhoneGuestControl, quickLookController: VPhoneQuickLookController) {self.control = control@@ -73,6 +74,7 @@ class VPhoneFileBrowserModel {pathHistory.append(currentPath)forwardHistory.removeAll()currentPath = path+ refreshGeneration += 1selection.removeAll()Task { await refresh() }}@@ -81,6 +83,7 @@ class VPhoneFileBrowserModel {guard let prev = pathHistory.popLast() else { return }forwardHistory.append(currentPath)currentPath = prev+ refreshGeneration += 1selection.removeAll()Task { await refresh() }}@@ -89,6 +92,7 @@ class VPhoneFileBrowserModel {guard let next = forwardHistory.popLast() else { return }pathHistory.append(currentPath)currentPath = next+ refreshGeneration += 1selection.removeAll()Task { await refresh() }}@@ -144,12 +148,18 @@ class VPhoneFileBrowserModel {// MARK: - Refreshfunc refresh() async {+ refreshGeneration += 1+ let generation = refreshGeneration+ let path = currentPathisLoading = trueerror = nildo {- let entries = try await control.listFiles(path: currentPath)- files = entries.compactMap { VPhoneRemoteFile(dir: currentPath, entry: $0) }+ let entries = try await control.listFiles(path: path)+ guard generation == refreshGeneration, path == currentPath else { return }+ files = entries.compactMap { VPhoneRemoteFile(dir: path, entry: $0) }+ selection.formIntersection(Set(files.map(\.id)))} catch {+ guard generation == refreshGeneration, path == currentPath else { return }self.error = "\(error)"files = []}@@ -161,8 +171,8 @@ class VPhoneFileBrowserModel {func downloadSelected(to directory: URL) async {let selected = files.filter { selection.contains($0.id) }for file in selected {- if file.isDirectory {- await downloadDirectory(remotePath: file.path, name: file.name, to: directory)+ if file.isDirectoryLike {+ await downloadDirectory(file, to: directory, ancestors: [])} else {await downloadFile(remotePath: file.path, name: file.name, size: file.size, to: directory)}@@ -188,8 +198,22 @@ class VPhoneFileBrowserModel {}}- private func downloadDirectory(remotePath: String, name: String, to localParent: URL) async {- let localDir = localParent.appendingPathComponent(name)+ private func downloadDirectory(+ _ file: VPhoneRemoteFile,+ to localParent: URL,+ ancestors: Set<String>,+ ) async {+ guard !file.isSymbolicLink || file.resolvedPath != nil else {+ error = "Download requires an updated guest agent to follow \(file.path)."+ return+ }+ let resolvedPath = file.resolvedPath ?? file.path+ guard !ancestors.contains(resolvedPath) else {+ error = "Directory link creates a cycle at \(file.path)."+ return+ }+ let ancestors = ancestors.union([resolvedPath])+ let localDir = localParent.appendingPathComponent(file.name)do {try FileManager.default.createDirectory(at: localDir, withIntermediateDirectories: true)} catch {@@ -199,16 +223,16 @@ class VPhoneFileBrowserModel {let entries: [[String: Any]]do {- entries = try await control.listFiles(path: remotePath)+ entries = try await control.listFiles(path: file.path)} catch {self.error = "List directory failed: \(error)"return}- let children = entries.compactMap { VPhoneRemoteFile(dir: remotePath, entry: $0) }+ let children = entries.compactMap { VPhoneRemoteFile(dir: file.path, entry: $0) }for child in children {- if child.isDirectory {- await downloadDirectory(remotePath: child.path, name: child.name, to: localDir)+ if child.isDirectoryLike {+ await downloadDirectory(child, to: localDir, ancestors: ancestors)} else {await downloadFile(remotePath: child.path,@@ -255,6 +279,10 @@ class VPhoneFileBrowserModel {}func createNewFolder(name: String) async {+ guard !files.contains(where: { $0.name == name }) else {+ error = "An item named \(name) already exists."+ return+ }let path = (currentPath as NSString).appendingPathComponent(name)do {try await control.createDirectory(path: path)@@ -279,6 +307,11 @@ class VPhoneFileBrowserModel {}func renameFile(_ file: VPhoneRemoteFile, to newName: String) async {+ guard newName != file.name else { return }+ guard !files.contains(where: { $0.dir == file.dir && $0.name == newName }) else {+ error = "An item named \(newName) already exists."+ return+ }let newPath = (file.dir as NSString).appendingPathComponent(newName)do {try await control.renameFile(from: file.path, to: newPath)diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileBrowserView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileBrowserView.swiftindex ff4a6cb3..1c24ce1b 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileBrowserView.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileBrowserView.swift@@ -7,6 +7,8 @@ struct VPhoneFileBrowserView: View {@State private var showNewFolder = false@State private var newFolderName = ""+ @State private var fileToRename: VPhoneRemoteFile?+ @State private var renameName = ""private let controlBarHeight: CGFloat = 24@@ -47,6 +49,9 @@ struct VPhoneFileBrowserView: View {.sheet(isPresented: $showNewFolder) {newFolderSheet}+ .sheet(item: $fileToRename) { file in+ renameSheet(for: file)+ }}// MARK: - Table@@ -86,8 +91,12 @@ struct VPhoneFileBrowserView: View {.width(min: 80, ideal: 140, max: .infinity)} rows: {ForEach(model.filteredFiles) { file in- TableRow(file)- .draggable(FileDragItem(file: file, control: model.control))+ if file.isDirectoryLike {+ TableRow(file)+ } else {+ TableRow(file)+ .draggable(FileDragItem(file: file, control: model.control))+ }}}.contextMenu(forSelectionType: VPhoneRemoteFile.ID.self) { ids in@@ -244,6 +253,12 @@ struct VPhoneFileBrowserView: View {model.selection = idsdownloadAction()}+ if ids.count == 1, let file = model.files.first(where: { ids.contains($0.id) }) {+ Button("Rename…") {+ renameName = file.name+ fileToRename = file+ }+ }Button("Delete") {model.selection = idsTask { await model.deleteSelected() }@@ -275,7 +290,28 @@ struct VPhoneFileBrowserView: View {Spacer()Button("Create") { createFolder() }.keyboardShortcut(.defaultAction)- .disabled(newFolderName.trimmingCharacters(in: .whitespaces).isEmpty)+ .disabled(!validName(newFolderName))+ }+ }+ .padding(20)+ .frame(width: 300)+ }++ // MARK: - Rename Sheet++ func renameSheet(for file: VPhoneRemoteFile) -> some View {+ VStack(spacing: 16) {+ Text("Rename").font(.headline)+ TextField("Name", text: $renameName)+ .textFieldStyle(.roundedBorder)+ .onSubmit { rename(file) }+ HStack {+ Button("Cancel") { fileToRename = nil }+ .keyboardShortcut(.cancelAction)+ Spacer()+ Button("Rename") { rename(file) }+ .keyboardShortcut(.defaultAction)+ .disabled(!validName(renameName) || renameName.trimmingCharacters(in: .whitespaces) == file.name)}}.padding(20)@@ -312,11 +348,24 @@ struct VPhoneFileBrowserView: View {func createFolder() {let name = newFolderName.trimmingCharacters(in: .whitespaces)- guard !name.isEmpty else { return }+ guard validName(name) else { return }showNewFolder = falseTask { await model.createNewFolder(name: name) }}+ func rename(_ file: VPhoneRemoteFile) {+ let name = renameName.trimmingCharacters(in: .whitespaces)+ guard validName(name), name != file.name else { return }+ fileToRename = nil+ Task { await model.renameFile(file, to: name) }+ }++ func validName(_ name: String) -> Bool {+ let trimmed = name.trimmingCharacters(in: .whitespaces)+ return !trimmed.isEmpty && trimmed != "." && trimmed != ".."+ && !trimmed.contains("/") && !trimmed.contains("\0")+ }+func dropFiles(_ providers: [NSItemProvider]) -> Bool {let validProviders = providers.filter { $0.canLoadObject(ofClass: URL.self) }guard !validProviders.isEmpty else { return false }diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneRemoteFile.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneRemoteFile.swiftindex 00c520a4..75532a5a 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneRemoteFile.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneRemoteFile.swift@@ -8,6 +8,7 @@ struct VPhoneRemoteFile: Identifiable, Hashable {let permissions: Stringlet modified: Datelet symlinkTargetsDirectory: Bool+ let resolvedPath: String?var id: String {path@@ -94,6 +95,7 @@ extension VPhoneRemoteFile {self.name = nameself.type = typesymlinkTargetsDirectory = entry["link_target_dir"] as? Bool ?? false+ resolvedPath = entry["resolved_path"] as? Stringsize = (entry["size"] as? NSNumber)?.uint64Value ?? 0permissions = entry["perm"] as? String ?? "---"modified = Date(timeIntervalSince1970: (entry["mtime"] as? Double) ?? 0)diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainBrowserModel.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainBrowserModel.swiftindex 6a4c0cad..7a816414 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainBrowserModel.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainBrowserModel.swift@@ -61,7 +61,6 @@ class VPhoneKeychainBrowserModel {("Internet", "inet"),("Certificates", "cert"),("Keys", "keys"),- ("Identities", "idnt"),]// MARK: - Actions@@ -77,6 +76,16 @@ class VPhoneKeychainBrowserModel {}}+ func removeTestItem() async {+ do {+ _ = try await control.deleteKeychainItem(account: "vphone-test", service: "vphone")+ await refresh()+ } catch {+ self.error = "Unable to remove the test keychain item. Try again."+ print("[keychain] remove failed: \(error)")+ }+ }+// MARK: - Refreshfunc refresh() async {diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainBrowserView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainBrowserView.swiftindex 26894215..0e603406 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainBrowserView.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainBrowserView.swift@@ -61,14 +61,14 @@ struct VPhoneKeychainBrowserView: View {.width(min: 60, ideal: 80, max: 100)TableColumn("Account", value: \.account) { item in- Text(item.account.isEmpty ? "-" : item.account)+ Text(item.account.isEmpty ? (item.protectedMetadata ? "Protected" : "-") : item.account).lineLimit(1).help(item.account)}.width(min: 80, ideal: 150, max: .infinity)TableColumn("Service", value: \.service) { item in- Text(item.service.isEmpty ? "-" : item.service)+ Text(item.service.isEmpty ? (item.protectedMetadata ? "Protected" : "-") : item.service).lineLimit(1).help(item.service)}@@ -229,6 +229,14 @@ struct VPhoneKeychainBrowserView: View {}.help("Add a test keychain item (debug)")}+ ToolbarItem {+ Button {+ Task { await model.removeTestItem() }+ } label: {+ Label("Remove Test", systemImage: "minus.circle")+ }+ .help("Remove the test keychain item")+ }ToolbarItem {Button {copySelected()diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainItem.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainItem.swiftindex 7e9c5461..51d1b301 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainItem.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Keychain/VPhoneKeychainItem.swift@@ -12,6 +12,7 @@ struct VPhoneKeychainItem: Identifiable, Hashable {let value: Stringlet valueEncoding: Stringlet valueSize: Int+ let protectedMetadata: Boollet created: Date?let modified: Date?@@ -38,6 +39,9 @@ struct VPhoneKeychainItem: Identifiable, Hashable {}var displayValue: String {+ if valueEncoding == "protected" {+ return "Protected"+ }if value.isEmpty {return "-"}@@ -60,6 +64,9 @@ struct VPhoneKeychainItem: Identifiable, Hashable {if !server.isEmpty {return server}+ if protectedMetadata {+ return "(protected)"+ }return "(unnamed)"}@@ -116,6 +123,7 @@ extension VPhoneKeychainItem {value = entry["value"] as? String ?? ""valueEncoding = entry["valueEncoding"] as? String ?? ""valueSize = (entry["valueSize"] as? NSNumber)?.intValue ?? 0+ protectedMetadata = (entry["protectedMetadata"] as? NSNumber)?.boolValue ?? falseif let ts = entry["created"] as? Double {created = Date(timeIntervalSince1970: ts)@@ -137,7 +145,11 @@ extension VPhoneKeychainItem {modified = nil}- let rowid = (entry["_rowid"] as? NSNumber)?.intValue ?? index- id = "\(cls)-\(rowid)"+ if entry["source"] as? String == "security" {+ id = "\(cls)-security-\(index)"+ } else {+ let rowid = (entry["_rowid"] as? NSNumber)?.intValue ?? index+ id = "\(cls)-database-\(rowid)"+ }}}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuBattery.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuBattery.swiftindex 37f6acc4..3a452718 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuBattery.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuBattery.swift@@ -62,31 +62,16 @@ extension VPhoneMenuController {}@objc func setBatteryLevel(_ sender: NSMenuItem) {- guard let menu = sender.menu else { return }- for mi in menu.items {- if mi.isSeparatorItem {- break- }- mi.state = mi === sender ? .on : .off- }+ batteryLevelMenuItems.forEach { $0.state = $0 === sender ? .on : .off }let charge = Double(sender.tag)- let connectivity = currentBatteryConnectivity(in: menu)+ let connectivity = currentBatteryConnectivity()vm?.setBattery(charge: charge, connectivity: connectivity)print("[battery] set \(sender.tag)%, connectivity=\(connectivity)")}@objc func setBatteryConnectivity(_ sender: NSMenuItem) {- guard let menu = sender.menu else { return }- var pastSeparator = false- for mi in menu.items {- if mi.isSeparatorItem {- pastSeparator = true; continue- }- if pastSeparator {- mi.state = mi === sender ? .on : .off- }- }- let charge = currentBatteryCharge(in: menu)+ batteryConnectivityMenuItems.forEach { $0.state = $0 === sender ? .on : .off }+ let charge = currentBatteryCharge()vm?.setBattery(charge: charge, connectivity: sender.tag)print("[battery] set \(Int(charge))%, connectivity=\(sender.tag)")}@@ -218,28 +203,11 @@ extension VPhoneMenuController {// MARK: - Helpers- private func currentBatteryCharge(in menu: NSMenu) -> Double {- for mi in menu.items {- if mi.isSeparatorItem {- break- }- if mi.state == .on {- return Double(mi.tag)- }- }- return 100.0+ private func currentBatteryCharge() -> Double {+ Double(batteryLevelMenuItems.first(where: { $0.state == .on })?.tag ?? 100)}- private func currentBatteryConnectivity(in menu: NSMenu) -> Int {- var pastSeparator = false- for mi in menu.items {- if mi.isSeparatorItem {- pastSeparator = true; continue- }- if pastSeparator, mi.state == .on {- return mi.tag- }- }- return 1+ private func currentBatteryConnectivity() -> Int {+ batteryConnectivityMenuItems.first(where: { $0.state == .on })?.tag ?? 1}}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuConnect.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuConnect.swiftindex 3f86cb85..34c985ae 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuConnect.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuConnect.swift@@ -331,7 +331,7 @@ extension VPhoneMenuController {let lbl3 = NSTextField(labelWithString: "Type:")lbl3.frame = NSRect(x: 20, y: 98, width: 380, height: 18)let typeField = NSTextField(frame: NSRect(x: 20, y: 72, width: 380, height: 22))- typeField.placeholderString = "boolean | string | integer | float"+ typeField.placeholderString = "bool | string | int | float"let lbl4 = NSTextField(labelWithString: "Value:")lbl4.frame = NSRect(x: 20, y: 48, width: 380, height: 18)@@ -369,21 +369,43 @@ extension VPhoneMenuController {guard response == .OK else { return }let domain = domainField.stringValuelet key = keyField.stringValue- let type = typeField.stringValue+ let type = typeField.stringValue.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()let rawValue = valueField.stringValueguard !domain.isEmpty, !key.isEmpty else { return }- let value: Any =- switch type.lowercased() {- case "boolean", "bool":- rawValue.lowercased() == "true" || rawValue == "1"- case "integer", "int":- Int(rawValue) ?? 0- case "float", "double":- Double(rawValue) ?? 0.0+ let value: Any+ let valueType: String+ switch type {+ case "", "string":+ value = rawValue+ valueType = "string"+ case "boolean", "bool":+ switch rawValue.lowercased() {+ case "true", "yes", "1": value = true+ case "false", "no", "0": value = falsedefault:- rawValue+ showAlert(title: "Write Setting", message: "Enter true or false for a boolean value.", style: .warning)+ return}+ valueType = "bool"+ case "integer", "int":+ guard let number = Int64(rawValue) else {+ showAlert(title: "Write Setting", message: "Enter a valid integer.", style: .warning)+ return+ }+ value = number+ valueType = "int"+ case "float", "double":+ guard let number = Double(rawValue), number.isFinite else {+ showAlert(title: "Write Setting", message: "Enter a finite number.", style: .warning)+ return+ }+ value = number+ valueType = "float"+ default:+ showAlert(title: "Write Setting", message: "Type must be string, bool, int, or float.", style: .warning)+ return+ }Task {do {@@ -391,7 +413,7 @@ extension VPhoneMenuController {domain: domain,key: key,value: value,- type: type.isEmpty ? nil : type,+ type: valueType,)showAlert(title: "Write Setting",diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuLocation.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuLocation.swiftindex 96ac84bd..b0401ef1 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuLocation.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuLocation.swift@@ -141,6 +141,7 @@ extension VPhoneMenuController {@objc func stopLocationReplay(_: NSMenuItem) {locationProvider?.stopReplay()+ control.sendLocationStop()refreshLocationReplayState(available: locationMenuItem?.isEnabled ?? false)}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuRecord.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuRecord.swiftindex 0c5d7328..e3c2a81f 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuRecord.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuRecord.swift@@ -45,10 +45,10 @@ extension VPhoneMenuController {@objc func copyScreenshotToClipboard() {guard let recorder = screenRecorder else { return }- guard let view = activeCaptureView() else {+ guard control.isConnected else {showAlert(title: "Screenshot",- message: "No VM window is open. Start a VM, then try again.",+ message: "The guest is not connected. Start a VM, then try again.",style: .warning,)return@@ -56,7 +56,8 @@ extension VPhoneMenuController {Task { @MainActor indo {- try await recorder.copyScreenshotToPasteboard(view: view)+ let image = try await control.screenshotJPEG()+ try recorder.copyScreenshotToPasteboard(jpegData: image)showAlert(title: "Screenshot", message: "Copied to clipboard.", style: .informational)} catch {showAlert(title: "Screenshot", message: "Unable to copy the screenshot. Try again.", style: .warning)@@ -66,10 +67,10 @@ extension VPhoneMenuController {@objc func saveScreenshotToFile() {guard let recorder = screenRecorder else { return }- guard let view = activeCaptureView() else {+ guard control.isConnected else {showAlert(title: "Screenshot",- message: "No VM window is open. Start a VM, then try again.",+ message: "The guest is not connected. Start a VM, then try again.",style: .warning,)return@@ -77,7 +78,8 @@ extension VPhoneMenuController {Task { @MainActor indo {- let url = try await recorder.saveScreenshot(view: view)+ let image = try await control.screenshotJPEG()+ let url = try recorder.saveScreenshot(jpegData: image)showAlert(title: "Screenshot", message: "Saved to \(url.path)", style: .informational)} catch {showAlert(title: "Screenshot", message: "Unable to save the screenshot. Try again.", style: .warning)diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swiftindex e664cde4..6d024213 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swift@@ -241,6 +241,7 @@ class VPhoneHostAutomationServer {defer { semaphore.signal() }guard let controller,let recorder = controller.screenRecorder,+ let control = controller.control,let view = controller.captureView,view.window != nilelse {@@ -248,10 +249,13 @@ class VPhoneHostAutomationServer {return}do {- if let outputPath {- let url = try await recorder.saveScreenshot(view: view, to: URL(fileURLWithPath: outputPath))- result.path = url.path+ let image = try await control.screenshotJPEG()+ let url = if let outputPath {+ try recorder.saveScreenshot(jpegData: image, to: URL(fileURLWithPath: outputPath))+ } else {+ try recorder.saveScreenshot(jpegData: image)}+ result.path = url.path// Always include compact image for screenshot commandresult.imageBase64 = await controller.captureCompactScreenshot()result.ok = truediff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swiftindex c0533c21..fe0608bc 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift@@ -156,6 +156,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {mc?.updateCameraConnectionState(connected: connected)}}+ mc.updateCameraConnectionState(connected: camServer.isConnected)}let recorder = VPhoneScreenRecorder()mc.screenRecorder = recorderdiff --git a/VPhoneGuestComponents/CamFix/libcamfix.m b/VPhoneGuestComponents/CamFix/libcamfix.mindex c405d6b6..c2f2d6ed 100644--- a/VPhoneGuestComponents/CamFix/libcamfix.m+++ b/VPhoneGuestComponents/CamFix/libcamfix.m@@ -1,5 +1,5 @@/*- * libcamfix — substrate-injected into Camera.app (com.apple.camera).+ * libcamfix — optional injection hook for Camera.app (com.apple.camera).** Our virtual camera has no daemon-side still or preview pipeline behind it,* so AVFoundation's own paths crash, throw, or render black. The hooks@@ -13,7 +13,7 @@** 2. -[AVCapturePhotoOutput capturePhotoWithSettings:delegate:]: when the* photo output is bound to our virtual camera, read- * /var/jb/var/mobile/Library/vphone-vcam-frame.shm and fire the modern+ * the vphoned shared frame file and fire the modern* didFinishProcessingPhoto:error: delegate with an AVCapturePhoto built* from that frame; JPEG encoding happens client-side via ImageIO. The* deprecated CMSampleBuffer delegate is the fallback, taken only for a@@ -39,7 +39,7 @@* 7. CAMStillImageCaptureRequest stubs for the accessors Camera.app's* capture engine reads off a request.*- * All logging goes to /tmp/camfix.log, written by cfxlog.+ * Diagnostics go to the shared camera media directory, written by cfxlog.*/#import <AVFoundation/AVFoundation.h>@@ -56,33 +56,20 @@#include <mach-o/dyld.h>#include <mach-o/loader.h>#include <string.h>+#include "../VCamCaptured/VCamFrameProtocol.h"-#define LOG_PATH "/tmp/camfix.log"-#define SHM_PATH "/var/jb/var/mobile/Library/vphone-vcam-frame.shm"#define VCAM_UID @"vphone:vcam:0"-#define CFX_SHM_HEADER_SIZE 64-typedef struct __attribute__((packed)) {- uint64_t seq;- uint32_t width;- uint32_t height;- uint32_t bytes_per_row;- uint32_t pixel_format;- uint32_t _reserved;- uint64_t timestamp_ns;- uint64_t frame_index;- uint32_t pixels_length;- uint32_t _pad;-} cfx_shm_header_t;-static void cfxlog(NSString *fmt, ...) {va_list ap; va_start(ap, fmt);NSString *line = [[NSString alloc] initWithFormat:fmt arguments:ap];va_end(ap);- FILE *fp = fopen(LOG_PATH, "a");+ FILE *fp = fopen(VPHONE_VCAM_APP_LOG_PATH, "a");if (fp) {fprintf(fp, "[camfix:%d] %s\n", getpid(), line.UTF8String ?: "?");fclose(fp);+ } else {+ NSLog(@"camfix: %@", line);}}@@ -94,9 +81,9 @@ static size_t cfx_shm_size = 0;static BOOL cfx_shm_open(void) {if (cfx_shm_base) return YES;- cfx_shm_fd = open(SHM_PATH, O_RDONLY);+ cfx_shm_fd = open(VPHONE_VCAM_SHM_PATH, O_RDONLY);if (cfx_shm_fd < 0) {- cfxlog(@"shm open failed: %s (errno=%d)", SHM_PATH, errno);+ cfxlog(@"shm open failed: %s (errno=%d)", VPHONE_VCAM_SHM_PATH, errno);return NO;}struct stat st;@@ -109,24 +96,24 @@ static BOOL cfx_shm_open(void) {close(cfx_shm_fd); cfx_shm_fd = -1; return NO;}cfx_shm_base = (const uint8_t *)p;- cfxlog(@"shm mapped %s size=%zu", SHM_PATH, cfx_shm_size);+ cfxlog(@"shm mapped %s size=%zu", VPHONE_VCAM_SHM_PATH, cfx_shm_size);return YES;}// One owner for "map the frame and check it is usable": opens the shm,// rejects a zeroed header, and rejects a pixel plane that runs past the// mapping. On success returns the header — the pixels start-// CFX_SHM_HEADER_SIZE bytes after cfx_shm_base — and writes the pixel-plane+// VPHONE_VCAM_SHM_HEADER_SIZE bytes after cfx_shm_base — and writes the pixel-plane// length to *outLen. Returns NULL when the frame cannot be read.-static const cfx_shm_header_t *cfx_shm_frame(size_t *outLen) {+static const vphone_vcam_shm_header_t *cfx_shm_frame(size_t *outLen) {if (!cfx_shm_open()) return NULL;- const cfx_shm_header_t *hdr = (const cfx_shm_header_t *)cfx_shm_base;+ const vphone_vcam_shm_header_t *hdr = (const vphone_vcam_shm_header_t *)cfx_shm_base;if (!hdr->width || !hdr->height || !hdr->bytes_per_row) {cfxlog(@"shm header zeros");return NULL;}size_t len = (size_t)hdr->bytes_per_row * hdr->height;- if ((size_t)CFX_SHM_HEADER_SIZE + len > cfx_shm_size) {+ if ((size_t)VPHONE_VCAM_SHM_HEADER_SIZE + len > cfx_shm_size) {cfxlog(@"shm: pixel range exceeds mapping");return NULL;}@@ -146,12 +133,12 @@ static void cfx_cg_release_data(void *info, const void *data, size_t size) {static CMSampleBufferRef cfx_build_cmsb(void) {size_t len = 0;- const cfx_shm_header_t *hdr = cfx_shm_frame(&len);+ const vphone_vcam_shm_header_t *hdr = cfx_shm_frame(&len);if (!hdr) return NULL;uint32_t w = hdr->width, h = hdr->height, bpr = hdr->bytes_per_row;void *pixels = malloc(len);if (!pixels) return NULL;- memcpy(pixels, cfx_shm_base + CFX_SHM_HEADER_SIZE, len);+ memcpy(pixels, cfx_shm_base + VPHONE_VCAM_SHM_HEADER_SIZE, len);CVPixelBufferRef pb = NULL;CVReturn cvr = CVPixelBufferCreateWithBytes(@@ -727,13 +714,13 @@ static BOOL cfx_output_is_for_vcam(id self) {static NSData *cfx_build_jpeg_from_shm(void) {size_t len = 0;- const cfx_shm_header_t *hdr = cfx_shm_frame(&len);+ const vphone_vcam_shm_header_t *hdr = cfx_shm_frame(&len);if (!hdr) return nil;uint32_t w = hdr->width, h = hdr->height, bpr = hdr->bytes_per_row;void *copy = malloc(len);if (!copy) return nil;- memcpy(copy, cfx_shm_base + CFX_SHM_HEADER_SIZE, len);+ memcpy(copy, cfx_shm_base + VPHONE_VCAM_SHM_HEADER_SIZE, len);CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();CGDataProviderRef dp = CGDataProviderCreateWithData(@@ -774,12 +761,12 @@ static NSData *cfx_build_jpeg_from_shm(void) {static CGImageRef cfx_build_cgimage_from_shm(void) CF_RETURNS_RETAINED {size_t len = 0;- const cfx_shm_header_t *hdr = cfx_shm_frame(&len);+ const vphone_vcam_shm_header_t *hdr = cfx_shm_frame(&len);if (!hdr) return NULL;uint32_t w = hdr->width, h = hdr->height, bpr = hdr->bytes_per_row;void *copy = malloc(len);if (!copy) return NULL;- memcpy(copy, cfx_shm_base + CFX_SHM_HEADER_SIZE, len);+ memcpy(copy, cfx_shm_base + VPHONE_VCAM_SHM_HEADER_SIZE, len);CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();CGDataProviderRef dp = CGDataProviderCreateWithData(NULL,@@ -805,7 +792,7 @@ static CGImageRef cfx_build_cgimage_from_shm(void) CF_RETURNS_RETAINED {static IOSurfaceRef cfx_build_iosurface_from_shm(uint32_t *outW, uint32_t *outH) CF_RETURNS_RETAINED {size_t len = 0;- const cfx_shm_header_t *hdr = cfx_shm_frame(&len);+ const vphone_vcam_shm_header_t *hdr = cfx_shm_frame(&len);if (!hdr) return NULL;uint32_t w = hdr->width, h = hdr->height, bpr = hdr->bytes_per_row;NSDictionary *props = @{@@ -820,7 +807,7 @@ static IOSurfaceRef cfx_build_iosurface_from_shm(uint32_t *outW, uint32_t *outH)if (!surf) return NULL;IOSurfaceLock(surf, 0, NULL);void *base = IOSurfaceGetBaseAddress(surf);- if (base) memcpy(base, cfx_shm_base + CFX_SHM_HEADER_SIZE, len);+ if (base) memcpy(base, cfx_shm_base + VPHONE_VCAM_SHM_HEADER_SIZE, len);IOSurfaceUnlock(surf, 0, NULL);if (outW) *outW = w;if (outH) *outH = h;diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefileindex 8043727c..62c42d7d 100644--- a/VPhoneGuestComponents/Makefile+++ b/VPhoneGuestComponents/Makefile@@ -10,6 +10,17 @@ COMMON_FLAGS := $(GUEST_C_FLAGS) -fobjc-arcCAMFIX := $(STAGE)/camfix/libcamfix.dylibVCAMCAPTURED := $(STAGE)/vcamcaptured/libvcamcaptured.dylib+VCAMCAPTURED_SOURCES := VCamCaptured/libvcamcaptured.m \+ VCamCaptured/VCamImageResolution.inc \+ VCamCaptured/VCamSourceInstallation.inc \+ VCamCaptured/VCamCaptureObservation.inc \+ VCamCaptured/VCamSyntheticDevice.inc \+ VCamCaptured/VCamSyntheticStreams.inc \+ VCamCaptured/VCamViewfinderHooks.inc \+ VCamCaptured/VCamSessionHooks.inc \+ VCamCaptured/VCamStillSink.inc \+ VCamCaptured/VCamFrameReceiver.inc \+ VCamCaptured/VCamFrameProtocol.hLAUNCHHOOK := $(STAGE)/launchhook/launchdhook-vphone.dylibSYSTEMHOOK := $(STAGE)/systemhook/SystemHook-vphone.dylibGPU_PLUGIN := $(STAGE)/gpu/libAppleParavirtCompilerPluginIOGPUFamily.dylib@@ -31,18 +42,18 @@ package: all$(STAGE)/camfix $(STAGE)/vcamcaptured $(STAGE)/launchhook $(STAGE)/systemhook $(STAGE)/gpu:@mkdir -p $@-$(CAMFIX): CamFix/libcamfix.m | $(STAGE)/camfix+$(CAMFIX): CamFix/libcamfix.m VCamCaptured/VCamFrameProtocol.h | $(STAGE)/camfix$(CLANG) $(COMMON_FLAGS) -dynamiclib \- -install_name /var/jb/usr/lib/libcamfix.dylib \+ -install_name @rpath/libcamfix.dylib \-o $@ $< \-framework Foundation -framework AVFoundation -framework ImageIO \-framework IOSurface -framework CoreMedia -framework CoreVideo \-framework CoreGraphics -framework QuartzCore@codesign --force --sign - $@-$(VCAMCAPTURED): VCamCaptured/libvcamcaptured.m | $(STAGE)/vcamcaptured+$(VCAMCAPTURED): $(VCAMCAPTURED_SOURCES) | $(STAGE)/vcamcaptured$(CLANG) $(COMMON_FLAGS) -dynamiclib \- -install_name /var/jb/usr/lib/libvcamcaptured.dylib \+ -install_name @rpath/libvcamcaptured.dylib \-o $@ $< \-framework Foundation -framework CoreMedia -framework CoreVideo@codesign --force --sign - $@diff --git a/VPhoneGuestComponents/README.md b/VPhoneGuestComponents/README.mdindex 8aef56be..975e6959 100644--- a/VPhoneGuestComponents/README.md+++ b/VPhoneGuestComponents/README.md@@ -10,7 +10,6 @@ tweak filter plists, and the GPU provenance note:| Camera daemon hook | `vcamcaptured/libvcamcaptured.dylib`, `vcamcaptured/libvcamcaptured.plist` || Launchd hook | `launchhook/launchdhook-vphone.dylib` || Reserved process hook | `systemhook/SystemHook-vphone.dylib` |-| iOS 27 app registrar | `vpregister/vpregister` || PCC GPU driver | `gpu/README.md` (source and extraction flow; no Apple binary) |The archive is a local build artifact, not a VM bootstrap. The launchd hook is@@ -20,3 +19,6 @@ ElleKit's own `TweakLoader.dylib` in the selected bootstrap. The required GPU buinstead extracted from the selected PCC firmware by `vphone-cli fw prepare`and copied into the VM during JB installation. No Apple GPU binary is storedin this directory, the archive, or the shipped app.++See `Research/Guest/virtual_camera_transport.md` for the camera transport+validation and the hook installation prerequisites.diff --git a/VPhoneGuestComponents/VCamCaptured/VCamCaptureObservation.inc b/VPhoneGuestComponents/VCamCaptured/VCamCaptureObservation.incnew file mode 100644index 00000000..02af02f4--- /dev/null+++ b/VPhoneGuestComponents/VCamCaptured/VCamCaptureObservation.inc@@ -0,0 +1,315 @@+// MARK: - frame-sender endpoint observation+//+// AVF capture clients (Camera.app, AVCaptureSession-using apps) tell the+// daemon "I want frames from camera X" by publishing a FrameSenderEndpoint+// — XPC handler `_captureSourceServer_handlePublishFrameSenderEndpointMessage`+// in CMCapture forwards each publish into the daemon-side class+// `CMCaptureFrameSenderEndpointsServerSideSingleton` via the+// `+addEndpoint:endpointUniqueID:endpointType:endpointPID:endpointProxyPID:+// endpointAuditToken:endpointProxyAuditToken:endpointCameraUniqueID:`+// class method. Each endpoint carries the requesting client's audit token+// and the camera unique-ID they want frames for. Our synth's unique-ID is+// "vphone:vcam:0", so any endpoint whose cameraUniqueID matches that string+// is a client expecting frames from us.+//+// We swizzle the class method below to log every registration. Once we+// see Camera.app (or rpcserver_ios) publishing an endpoint for our synth,+// we know the next sub-stage is to build a `-[CMCaptureFrameSenderService+// sendFrame:]` call path that pushes CMSampleBuffers built from our shm+// `vcc_latest_frame` into each registered endpoint.+//+// This hook is observation-only; it does not deliver frames yet.++static IMP vcc_add_endpoint_orig_imp = NULL;++typedef BOOL (*VccAddEndpointFn)(id,+ SEL,+ id /*endpoint*/,+ id /*endpointUniqueID*/,+ int /*endpointType*/,+ int /*endpointPID*/,+ int /*endpointProxyPID*/,+ audit_token_t * /*auditToken*/,+ audit_token_t * /*proxyAuditToken*/,+ id /*endpointCameraUniqueID*/);++static BOOL vcc_add_endpoint_hook(id self,+ SEL _cmd,+ id endpoint,+ id endpointUniqueID,+ int endpointType,+ int endpointPID,+ int endpointProxyPID,+ audit_token_t *auditToken,+ audit_token_t *proxyAuditToken,+ id endpointCameraUniqueID) {+ vcc_log(@" +addEndpoint cameraID=%@ pid=%d type=%d endpointUniqueID=%@",+ endpointCameraUniqueID, endpointPID, endpointType, endpointUniqueID);+ if (!vcc_add_endpoint_orig_imp) return NO;+ VccAddEndpointFn orig = (VccAddEndpointFn)vcc_add_endpoint_orig_imp;+ BOOL ok = orig(self, _cmd, endpoint, endpointUniqueID, endpointType,+ endpointPID, endpointProxyPID, auditToken,+ proxyAuditToken, endpointCameraUniqueID);+ vcc_log(@" +addEndpoint orig returned %d", ok);+ return ok;+}++static void vcc_install_endpoint_hook(void) {+ Class cls = NSClassFromString(+ @"CMCaptureFrameSenderEndpointsServerSideSingleton");+ if (!cls) {+ vcc_log(@" endpoint hook: class missing");+ return;+ }+ SEL sel = NSSelectorFromString(+ @"addEndpoint:endpointUniqueID:endpointType:endpointPID:"+ @"endpointProxyPID:endpointAuditToken:endpointProxyAuditToken:"+ @"endpointCameraUniqueID:");+ Method m = class_getClassMethod(cls, sel);+ if (!m) {+ vcc_log(@" endpoint hook: class_getClassMethod returned NULL");+ return;+ }+ vcc_add_endpoint_orig_imp = method_setImplementation(m, (IMP)vcc_add_endpoint_hook);+ vcc_log(@" endpoint hook installed (orig=%p)",+ vcc_add_endpoint_orig_imp);+}++// MARK: - sink-node diagnostic dump+//+// Enumerate the BWImageQueueSinkNode + BWRemoteQueueSinkNode method tables+// at runtime so we can identify the actual init / setup / render selectors+// the session pipeline invokes. The static class-dump on the DSC binary+// returns garbled selptr references — at runtime the selector table is+// resolved, so this dump is reliable. Result lands in the vcamcaptured.log+// file; we use it to pick the right hook target for stage G.++static void vcc_dump_class(const char *name) {+ Class cls = NSClassFromString(@(name));+ if (!cls) {+ vcc_log(@" class %s NOT FOUND", name);+ return;+ }+ Class super = class_getSuperclass(cls);+ vcc_log(@" class %s @ %p (super=%s)", name, cls,+ super ? class_getName(super) : "<root>");++ unsigned int count = 0;+ Method *list = class_copyMethodList(cls, &count);+ vcc_log(@" -- instance methods (%u) --", count);+ for (unsigned i = 0; i < count; i++) {+ Method m = list[i];+ SEL s = method_getName(m);+ IMP imp = method_getImplementation(m);+ const char *types = method_getTypeEncoding(m);+ vcc_log(@" -[%s %@] imp=%p types=%s", name,+ NSStringFromSelector(s), (void *)imp,+ types ? types : "?");+ }+ free(list);++ Class meta = object_getClass((id)cls);+ count = 0;+ Method *clist = class_copyMethodList(meta, &count);+ vcc_log(@" -- class methods (%u) --", count);+ for (unsigned i = 0; i < count; i++) {+ Method m = clist[i];+ SEL s = method_getName(m);+ IMP imp = method_getImplementation(m);+ vcc_log(@" +[%s %@] imp=%p", name,+ NSStringFromSelector(s), (void *)imp);+ }+ free(clist);+}++static void vcc_dump_sink_node_methods(void) {+ vcc_log(@"---- sink-node method dump ----");+ vcc_dump_class("BWSinkNode");+ vcc_dump_class("BWImageQueueSinkNode");+ vcc_dump_class("BWRemoteQueueSinkNode");+ vcc_dump_class("BWFigCaptureSession");+ vcc_dump_class("BWFigCaptureDeviceVendor");+ vcc_dump_class("FigCaptureSourceBacking");+ vcc_dump_class("FigCaptureVideoSourceBacking");+ vcc_dump_class("FigCameraViewfinderStream");+ vcc_dump_class("FigCameraViewfinderSessionLocal");+ vcc_dump_class("FigCameraViewfinderLocal");+ vcc_dump_class("BWPreviewTimeMachineSinkNode");+ // Photo-path classes for capturePhoto debugging+ vcc_dump_class("BWStillImageCaptureCoordinator");+ vcc_dump_class("BWStillImageSampleBufferSinkNode");+ vcc_dump_class("BWStillImageProcessorController");+ vcc_dump_class("BWFigCaptureStillImageRequest");+ vcc_dump_class("FigCaptureCameraSourcePipeline");+ vcc_dump_class("FigCaptureSourcePipeline");+ vcc_log(@"---- end sink-node method dump ----");+}++// MARK: - sink observation hooks+//+// Stage G observation pass: swizzle the two sink classes' init + render+// methods. Goals:+// 1) Confirm whether sinks are instantiated when an AVF client opens our+// synth source (i.e. is the pipeline starved at the SOURCE end or at the+// configuration end?).+// 2) See whether ANY renderSampleBuffer:forInput: calls fire — if they do,+// we know the pipeline runs and we just need to substitute the+// sample-buffer contents.++static unsigned long vcc_render_call_count = 0;+static unsigned long vcc_iqsn_init_count = 0;+static unsigned long vcc_rqsn_init_count = 0;++static IMP vcc_iqsn_init_orig = NULL;+static IMP vcc_rqsn_init_orig = NULL;+static IMP vcc_iqsn_render_orig = NULL;+static IMP vcc_rqsn_render_orig = NULL;++typedef id (*VccIqsnInitFn)(+ id self,+ SEL _cmd,+ BOOL hfrSupport,+ BOOL ispJitterCompensationEnabled,+ audit_token_t auditToken,+ id sinkID);++typedef id (*VccRqsnInitFn)(+ id self,+ SEL _cmd,+ uint32_t mediaType,+ audit_token_t auditToken,+ id sinkID,+ id cameraInfoByPortType);++typedef void (*VccRenderFn)(+ id self,+ SEL _cmd,+ CMSampleBufferRef cmsb,+ id input);++static id vcc_iqsn_init_hook(+ id self,+ SEL _cmd,+ BOOL hfrSupport,+ BOOL ispJitterCompensationEnabled,+ audit_token_t auditToken,+ id sinkID) {+ VccIqsnInitFn orig = (VccIqsnInitFn)vcc_iqsn_init_orig;+ id ret = orig(self, _cmd, hfrSupport, ispJitterCompensationEnabled,+ auditToken, sinkID);+ vcc_iqsn_init_count++;+ vcc_log(@" [IQSN init] -> %p sinkID=%@ count=%lu",+ ret, sinkID, vcc_iqsn_init_count);+ return ret;+}++static id vcc_rqsn_init_hook(+ id self,+ SEL _cmd,+ uint32_t mediaType,+ audit_token_t auditToken,+ id sinkID,+ id cameraInfoByPortType) {+ VccRqsnInitFn orig = (VccRqsnInitFn)vcc_rqsn_init_orig;+ id ret = orig(self, _cmd, mediaType, auditToken, sinkID,+ cameraInfoByPortType);+ vcc_rqsn_init_count++;+ vcc_log(@" [RQSN init] -> %p mediaType=0x%x sinkID=%@ count=%lu",+ ret, mediaType, sinkID, vcc_rqsn_init_count);+ return ret;+}++static void vcc_iqsn_render_hook(+ id self,+ SEL _cmd,+ CMSampleBufferRef cmsb,+ id input) {+ vcc_render_call_count++;+ if (vcc_render_call_count <= 5 || (vcc_render_call_count & 63) == 1) {+ vcc_log(@" [IQSN render] self=%p cmsb=%p input=%p inputCls=%@ #%lu",+ self, cmsb, input, NSStringFromClass([input class]),+ vcc_render_call_count);+ }+ VccRenderFn orig = (VccRenderFn)vcc_iqsn_render_orig;+ orig(self, _cmd, cmsb, input);+}++static void vcc_rqsn_render_hook(+ id self,+ SEL _cmd,+ CMSampleBufferRef cmsb,+ id input) {+ vcc_render_call_count++;+ if (vcc_render_call_count <= 5 || (vcc_render_call_count & 63) == 1) {+ vcc_log(@" [RQSN render] self=%p cmsb=%p input=%p inputCls=%@ #%lu",+ self, cmsb, input, NSStringFromClass([input class]),+ vcc_render_call_count);+ }+ VccRenderFn orig = (VccRenderFn)vcc_rqsn_render_orig;+ orig(self, _cmd, cmsb, input);+}++static void vcc_swizzle_method(Class cls, SEL sel, IMP newImp, IMP *outOrig) {+ Method m = class_getInstanceMethod(cls, sel);+ if (!m) {+ vcc_log(@" swizzle: -[%s %@] missing", class_getName(cls),+ NSStringFromSelector(sel));+ return;+ }+ *outOrig = method_setImplementation(m, newImp);+ vcc_log(@" swizzled -[%s %@] (orig imp=%p)", class_getName(cls),+ NSStringFromSelector(sel), *outOrig);+}++// Extra observation: hook -[BWFigCaptureDeviceVendor copyDeviceWithID:forClient:informClientWhenDeviceAvailableAgain:error:]+// to see when an AVF client asks for our device. If this fires, we know the+// session is at least requesting a device for our synth. If it doesn't fire,+// the client never even reached the device-vendor stage (gated upstream).++static IMP vcc_copy_device_orig = NULL;++// Type encoding observed on iOS 26.5 cameracaptured:+// @40@0:8@16i24B28^i32+// => id (*)(id self, SEL _cmd, NSString *deviceID, int clientPID,+// BOOL informClient, int *err)+// The earlier disabled stub mis-typed clientPID as `id`, causing ARC to+// emit objc_retain on an integer register and crash inside the hook+// prologue.++typedef id (*VccCopyDeviceFn)(id self,+ SEL _cmd,+ NSString *deviceID,+ int clientPID,+ BOOL informClient,+ int *err);++static Class vcc_synth_device_class = Nil;++// Forward decls.+static void vcc_init_synth_device_class(void);+__attribute__((ns_returns_retained))+static id vcc_make_synth_device(NSString *deviceID);++static id vcc_copy_device_hook(id self,+ SEL _cmd,+ NSString *deviceID,+ int clientPID,+ BOOL informClient,+ int *err) {+ vcc_log(@" [copyDeviceWithID] deviceID=%@ clientPID=%d inform=%d",+ deviceID, clientPID, informClient);++ if ([deviceID isEqualToString:kVccSynthDeviceID]) {+ id synth = vcc_make_synth_device(deviceID);+ if (err) *err = 0;+ vcc_log(@" [copyDeviceWithID] -> synth %p (class=%s err=0)",+ synth, object_getClassName(synth));+ return synth;+ }++ VccCopyDeviceFn orig = (VccCopyDeviceFn)vcc_copy_device_orig;+ id ret = orig(self, _cmd, deviceID, clientPID, informClient, err);+ int errval = err ? *err : 0;+ vcc_log(@" [copyDeviceWithID] returned %p (err=%d)", ret, errval);+ return ret;+}diff --git a/VPhoneGuestComponents/VCamCaptured/VCamFrameProtocol.h b/VPhoneGuestComponents/VCamCaptured/VCamFrameProtocol.hnew file mode 100644index 00000000..072b58c4--- /dev/null+++ b/VPhoneGuestComponents/VCamCaptured/VCamFrameProtocol.h@@ -0,0 +1,37 @@+#ifndef VPHONE_VCAM_FRAME_PROTOCOL_H+#define VPHONE_VCAM_FRAME_PROTOCOL_H++#include <stdint.h>+#include <stddef.h>++// All guest camera runtime data lives in the mobile media area, regardless+// of how the VM was installed.+#define VPHONE_VCAM_DIRECTORY "/var/mobile/Media/SimulatedCamera"+#define VPHONE_VCAM_SHM_PATH VPHONE_VCAM_DIRECTORY "/vphone-vcam-frame.shm"+#define VPHONE_VCAM_DAEMON_LOG_PATH VPHONE_VCAM_DIRECTORY "/vphone-vcam.log"+#define VPHONE_VCAM_CAPTURE_LOG_PATH VPHONE_VCAM_DIRECTORY "/vcamcaptured.log"+#define VPHONE_VCAM_APP_LOG_PATH VPHONE_VCAM_DIRECTORY "/camfix.log"+#define VPHONE_VCAM_SYNTH_PHOTO_PATH VPHONE_VCAM_DIRECTORY "/vphone-synth-photo.bgra"+#define VPHONE_VCAM_NOTIFY_NAME "com.vphone.vcam.frame"+#define VPHONE_VCAM_SHM_HEADER_SIZE 64+#define VPHONE_VCAM_SHM_MAX_PIXELS (8 * 1024 * 1024)+#define VPHONE_VCAM_SHM_TOTAL_SIZE (VPHONE_VCAM_SHM_HEADER_SIZE + VPHONE_VCAM_SHM_MAX_PIXELS)++typedef struct __attribute__((packed)) {+ uint64_t seq __attribute__((aligned(8)));+ uint32_t width;+ uint32_t height;+ uint32_t bytes_per_row;+ uint32_t pixel_format;+ uint32_t _reserved;+ uint64_t timestamp_ns;+ uint64_t frame_index;+ uint32_t pixels_length;+ uint32_t _pad;+} vphone_vcam_shm_header_t;++_Static_assert(offsetof(vphone_vcam_shm_header_t, timestamp_ns) == 28, "camera frame timestamp offset");+_Static_assert(offsetof(vphone_vcam_shm_header_t, pixels_length) == 44, "camera frame length offset");+_Static_assert(sizeof(vphone_vcam_shm_header_t) <= VPHONE_VCAM_SHM_HEADER_SIZE, "camera frame header capacity");++#endifdiff --git a/VPhoneGuestComponents/VCamCaptured/VCamFrameReceiver.inc b/VPhoneGuestComponents/VCamCaptured/VCamFrameReceiver.incnew file mode 100644index 00000000..b29ea7e6--- /dev/null+++ b/VPhoneGuestComponents/VCamCaptured/VCamFrameReceiver.inc@@ -0,0 +1,121 @@+// MARK: - shared-frame reader++// The latest frame copied out of the vphoned-published shm. Mutated only+// from the reader callback thread; readers (AVF stream production, next+// stage) take the lock for the brief duration of a copy.+// (struct vcc_latest_frame_s is forward-declared above as vcc_latest_frame_t+// for use by the viewfinder injection code.)++vcc_latest_frame_t vcc_latest_frame = {+ .lock = PTHREAD_MUTEX_INITIALIZER,+};++static const uint8_t *vcc_shm_base = NULL;+static uint64_t vcc_last_seq_seen = 0;+static uint64_t vcc_frames_received = 0;+static uint8_t *vcc_staging_pixels = NULL;+static size_t vcc_staging_capacity = 0;++static int vcc_shm_map(void) {+ int fd = open(VPHONE_VCAM_SHM_PATH, O_RDONLY);+ if (fd < 0) {+ vcc_log(@" shm open(%s) failed: %s", VPHONE_VCAM_SHM_PATH, strerror(errno));+ return -1;+ }+ struct stat st;+ if (fstat(fd, &st) < 0 || st.st_size < (off_t)VPHONE_VCAM_SHM_TOTAL_SIZE) {+ vcc_log(@" shm fstat failed or undersized");+ close(fd);+ return -1;+ }+ void *base = mmap(NULL, VPHONE_VCAM_SHM_TOTAL_SIZE, PROT_READ,+ MAP_SHARED, fd, 0);+ close(fd);+ if (base == MAP_FAILED) {+ vcc_log(@" shm mmap failed: %s", strerror(errno));+ return -1;+ }+ vcc_shm_base = (const uint8_t *)base;+ vcc_log(@" shm mapped %s -> %p", VPHONE_VCAM_SHM_PATH, vcc_shm_base);+ return 0;+}++// Read the latest frame with seq-stability discipline. Returns 1 on a+// fresh frame, 0 if seq hasn't advanced since last call or a read tore.+static int vcc_shm_read_latest(void) {+ if (!vcc_shm_base && vcc_shm_map() < 0) return 0;+ const vphone_vcam_shm_header_t *hdr = (const vphone_vcam_shm_header_t *)vcc_shm_base;++ uint64_t seq_a = atomic_load_explicit(+ (const _Atomic uint64_t *)&hdr->seq, memory_order_acquire);+ if (seq_a == vcc_last_seq_seen) return 0;+ if (seq_a & 1ull) return 0; // writer in progress++ uint32_t w = hdr->width;+ uint32_t h = hdr->height;+ uint32_t bpr = hdr->bytes_per_row;+ uint32_t fmt = hdr->pixel_format;+ uint64_t idx = hdr->frame_index;+ uint32_t pix_len = hdr->pixels_length;++ if (pix_len == 0 || pix_len > VPHONE_VCAM_SHM_MAX_PIXELS) return 0;+ if (w == 0 || h == 0 || bpr == 0 || pix_len < (size_t)bpr * h) return 0;++ if (vcc_staging_capacity < pix_len) {+ uint8_t *larger = (uint8_t *)realloc(vcc_staging_pixels, pix_len);+ if (!larger) return 0;+ vcc_staging_pixels = larger;+ vcc_staging_capacity = pix_len;+ }+ memcpy(vcc_staging_pixels, vcc_shm_base + VPHONE_VCAM_SHM_HEADER_SIZE, pix_len);++ // Re-check seq after copy. If it advanced past our snapshot+1 we may+ // have torn — but the writer always sets even seq AFTER pixel write,+ // so seeing the same even seq means our copy was clean.+ uint64_t seq_b = atomic_load_explicit(+ (const _Atomic uint64_t *)&hdr->seq, memory_order_acquire);+ if (seq_b != seq_a) return 0;++ pthread_mutex_lock(&vcc_latest_frame.lock);+ uint8_t *old_pixels = vcc_latest_frame.pixels;+ size_t old_capacity = vcc_latest_frame.pixels_capacity;+ vcc_latest_frame.pixels = vcc_staging_pixels;+ vcc_latest_frame.pixels_capacity = vcc_staging_capacity;+ vcc_latest_frame.pixels_length = pix_len;+ vcc_latest_frame.width = w;+ vcc_latest_frame.height = h;+ vcc_latest_frame.bytes_per_row = bpr;+ vcc_staging_pixels = old_pixels;+ vcc_staging_capacity = old_capacity;+ pthread_mutex_unlock(&vcc_latest_frame.lock);++ vcc_last_seq_seen = seq_a;+ vcc_frames_received++;+ if ((vcc_frames_received & 29) == 1) {+ vcc_log(@" shm frame #%llu (idx=%llu) w=%u h=%u bpr=%u fmt=0x%08x",+ (unsigned long long)vcc_frames_received,+ (unsigned long long)idx, w, h, bpr, fmt);+ }+ return 1;+}++static void vcc_start_frame_receiver(void) {+ // Subscribe before mapping: cameracaptured may start before vphoned has+ // created the file. The first frame notification retries the map.+ int token = -1;+ dispatch_queue_t q = dispatch_queue_create("com.vphone.vcam.frames", DISPATCH_QUEUE_SERIAL);+ uint32_t status = notify_register_dispatch(+ VPHONE_VCAM_NOTIFY_NAME, &token, q,+ ^(__unused int t) {+ @autoreleasepool {+ (void)vcc_shm_read_latest();+ }+ });+ if (status != NOTIFY_STATUS_OK) {+ vcc_log(@" notify_register_dispatch(%s) failed: %u",+ VPHONE_VCAM_NOTIFY_NAME, status);+ return;+ }+ vcc_log(@" subscribed to %s (token=%d)", VPHONE_VCAM_NOTIFY_NAME, token);+ dispatch_async(q, ^{ @autoreleasepool { (void)vcc_shm_read_latest(); } });+}diff --git a/VPhoneGuestComponents/VCamCaptured/VCamImageResolution.inc b/VPhoneGuestComponents/VCamCaptured/VCamImageResolution.incnew file mode 100644index 00000000..f6ee442c--- /dev/null+++ b/VPhoneGuestComponents/VCamCaptured/VCamImageResolution.inc@@ -0,0 +1,589 @@+// MARK: - runtime image resolution++#define VCC_MAX_DATA_RANGES 8++typedef struct {+ uintptr_t start;+ uintptr_t end;+} vcc_range_t;++typedef struct {+ const struct mach_header_64 *mh;+ intptr_t slide;+ const uint32_t *text;+ size_t text_words; // count of 4-byte instructions+ vcc_range_t data_ranges[VCC_MAX_DATA_RANGES];+ unsigned data_range_count;+ // LC_SYMTAB pointers (may be 0 on DSC dylibs that strip private symbols+ // from the per-image symtab; callers must handle gracefully).+ const struct nlist_64 *symtab;+ const char *strtab;+ uint32_t nsyms;+} vcc_image_t;++static int vcc_image_resolve(vcc_image_t *out, const char *anchor_sym) {+ memset(out, 0, sizeof(*out));+ void *anchor = dlsym(RTLD_DEFAULT, anchor_sym);+ if (!anchor) return -1;+ void *stripped = ptrauth_strip(anchor, ptrauth_key_function_pointer);+ Dl_info info;+ if (!dladdr(stripped, &info) || !info.dli_fbase) return -2;+ const struct mach_header_64 *mh =+ (const struct mach_header_64 *)info.dli_fbase;+ if (mh->magic != MH_MAGIC_64) return -3;+ out->mh = mh;++ uint32_t cnt = _dyld_image_count();+ for (uint32_t i = 0; i < cnt; i++) {+ if (_dyld_get_image_header(i) == (const struct mach_header *)mh) {+ out->slide = _dyld_get_image_vmaddr_slide(i);+ break;+ }+ }++ unsigned long sz = 0;+ uint8_t *text =+ getsectiondata((struct mach_header_64 *)mh, "__TEXT", "__text", &sz);+ if (!text || sz < 8) return -4;+ out->text = (const uint32_t *)text;+ out->text_words = sz / 4;++ // Capture bounds of every writable segment so the structural scan can+ // reject candidate targets that don't fall within a data segment.+ // Also stash the LC_SYMTAB pointers for later private-symbol lookups.+ const struct load_command *lc = (const struct load_command *)(mh + 1);+ const struct segment_command_64 *linkedit = NULL;+ const struct symtab_command *symtab_cmd = NULL;+ for (uint32_t i = 0; i < mh->ncmds; i++) {+ if (lc->cmd == LC_SEGMENT_64) {+ const struct segment_command_64 *seg =+ (const struct segment_command_64 *)lc;+ if (strcmp(seg->segname, "__LINKEDIT") == 0) {+ linkedit = seg;+ }+ // Skip __TEXT, __LINKEDIT — only consider writable/data segments.+ // segname comparisons are sufficient; __PAGEZERO has vmaddr 0 anyway.+ if (strcmp(seg->segname, "__TEXT") != 0 &&+ strcmp(seg->segname, "__LINKEDIT") != 0 &&+ strcmp(seg->segname, "__PAGEZERO") != 0 &&+ seg->vmsize > 0 &&+ out->data_range_count < VCC_MAX_DATA_RANGES) {+ uintptr_t start = (uintptr_t)seg->vmaddr + out->slide;+ out->data_ranges[out->data_range_count++] = (vcc_range_t){+ start, start + (uintptr_t)seg->vmsize};+ }+ } else if (lc->cmd == LC_SYMTAB) {+ symtab_cmd = (const struct symtab_command *)lc;+ }+ lc = (const struct load_command *)((const char *)lc + lc->cmdsize);+ }+ if (out->data_range_count == 0) return -5;++ // LC_SYMTAB pointers — file-offsets in the symtab_cmd are relative to the+ // DSC file layout; runtime addresses are recovered via the __LINKEDIT+ // segment's (vmaddr+slide) - fileoff base.+ if (symtab_cmd && linkedit && linkedit->fileoff <= symtab_cmd->symoff) {+ uintptr_t linkedit_base = (uintptr_t)linkedit->vmaddr + out->slide -+ (uintptr_t)linkedit->fileoff;+ out->symtab = (const struct nlist_64 *)(linkedit_base ++ (uintptr_t)symtab_cmd->symoff);+ out->strtab = (const char *)(linkedit_base + (uintptr_t)symtab_cmd->stroff);+ out->nsyms = symtab_cmd->nsyms;+ }+ return 0;+}++// Walk CMCapture's LC_SYMTAB for `name`. Returns slid VMA on match, or 0.+// On DSC dylibs the per-image symtab may be stripped of private symbols, in+// which case this returns 0 even for symbols that exist statically.+static uintptr_t vcc_lookup_lc_symtab(const vcc_image_t *img,+ const char *name) {+ if (!img->symtab || !img->strtab || img->nsyms == 0) return 0;+ for (uint32_t i = 0; i < img->nsyms; i++) {+ if (img->symtab[i].n_un.n_strx == 0) continue;+ const char *nm = img->strtab + img->symtab[i].n_un.n_strx;+ if (strcmp(nm, name) == 0) {+ uintptr_t val = (uintptr_t)img->symtab[i].n_value;+ if (val == 0) continue;+ return val + img->slide;+ }+ }+ return 0;+}++// Decode ARM64 BL imm26 -> absolute branch target.+static uintptr_t vcc_bl_target(uintptr_t bl_pc, uint32_t bl) {+ int64_t imm = (int64_t)(bl & 0x03FFFFFFu) << 6; // place 26 bits in top+ imm >>= 4; // shift right 4 (sign-ext + *4)+ return bl_pc + (uintptr_t)imm;+}++// Scan __text for the per-source ownership filter inside+// _captureSourceServer_handleCopySourcesMessage. The compiler emits:+//+// bl <objc_msgSend$boolValue> ; w0 = [prewarmingEnabledRet boolValue]+// mov x25, x0 ; 0xAA0003F9+// ldr x2, [sp, #<imm>] ; F9400000 | (imm12<<10) | (31<<5) | 2+// ; — copy of bundleID outparam; offset+// ; is compiler-chosen, so mask it off+// mov x0, x22 ; 0xAA1603E0 — clientSI string+// bl <objc_msgSend$isEqualToString:>; w0 = [clientSI isEqualToString:bundleID]+// cbz w0, SKIP ; (insn & 0xFF00001F) == 0x34000000 → patch+// cbz w25, SKIP ; (insn & 0xFF00001F) == 0x34000019 → patch+//+// Both cbz branch targets are identical (same SKIP label). We patch both+// to NOP so every source survives the per-client ownership + prewarming-+// enabled filter and reaches the response serializer.+static uintptr_t vcc_find_per_source_filter(const vcc_image_t *img) {+ if (!img->text || img->text_words < 6) return 0;+ for (size_t i = 0; i + 5 < img->text_words; i++) {+ if (img->text[i] != 0xAA0003F9u) continue; // mov x25, x0+ // ldr x2, [sp, #?] — any sp-relative 64-bit load into x2. The stack+ // offset is a compiler-chosen frame slot and shifts between builds.+ if ((img->text[i + 1] & 0xFFC003FFu) != 0xF94003E2u) continue;+ if (img->text[i + 2] != 0xAA1603E0u) continue; // mov x0, x22+ if ((img->text[i + 3] & 0xFC000000u) != 0x94000000u) // BL (don't care)+ continue;+ if ((img->text[i + 4] & 0xFF00001Fu) != 0x34000000u) // cbz w0, ?+ continue;+ if ((img->text[i + 5] & 0xFF00001Fu) != 0x34000019u) // cbz w25, ?+ continue;+ // Verify both cbz branch to the same target (same SKIP block).+ // CBZ encoding: bits 23..5 = imm19 (19-bit signed instruction offset).+ // Byte offset = sign_extend(imm19) * 4.+ int32_t imm0 = (int32_t)((img->text[i + 4] >> 5) & 0x7FFFFu);+ int32_t imm1 = (int32_t)((img->text[i + 5] >> 5) & 0x7FFFFu);+ if (imm0 & 0x40000) imm0 |= 0xFFF80000;+ if (imm1 & 0x40000) imm1 |= 0xFFF80000;+ uintptr_t tgt0 = (uintptr_t)&img->text[i + 4] + (intptr_t)imm0 * 4;+ uintptr_t tgt1 = (uintptr_t)&img->text[i + 5] + (intptr_t)imm1 * 4;+ if (tgt0 != tgt1) continue;+ return (uintptr_t)&img->text[i + 4];+ }+ return 0;+}++// Patch two consecutive instructions starting at `pc` to NOP. iOS __TEXT+// is W^X-enforced + TXM-validated. Try in order:+// (a) vm_protect with VM_PROT_COPY: kernel COWs the page into an anon+// mapping and grants RW. Standard iOS-hooker recipe (libhooker etc).+// (b) vm_allocate scratch + memcpy + vm_remap(OVERWRITE|FIXED) overlay.+// Either way, scratch_writable -> patch -> set RX -> icache flush.+static int vcc_patch_two_nops(uintptr_t pc) {+ uintptr_t page_size = (uintptr_t)getpagesize();+ uintptr_t page_start = pc & ~(page_size - 1);+ uintptr_t end = pc + 8;+ uintptr_t page_end =+ ((end + page_size - 1) & ~(page_size - 1));+ vm_size_t span = (vm_size_t)(page_end - page_start);+ mach_port_t self_task = mach_task_self();++ // (a) vm_protect with VM_PROT_COPY (= 0x10) to force COW.+ kern_return_t kr = vm_protect(+ self_task,+ (vm_address_t)page_start,+ span,+ FALSE,+ VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY);+ if (kr == KERN_SUCCESS) {+ uint32_t nop = 0xD503201Fu;+ ((uint32_t *)pc)[0] = nop;+ ((uint32_t *)pc)[1] = nop;+ kr = vm_protect(+ self_task,+ (vm_address_t)page_start,+ span,+ FALSE,+ VM_PROT_READ | VM_PROT_EXECUTE);+ if (kr == KERN_SUCCESS) {+ sys_icache_invalidate((void *)pc, 8);+ vcc_log(@" vm_protect+COPY patch OK @ 0x%lx",+ (unsigned long)pc);+ return 1;+ }+ vcc_log(@" vm_protect restore RX failed: %d (page=0x%lx)",+ kr,+ (unsigned long)page_start);+ // Continue to try (b).+ } else {+ vcc_log(@" vm_protect+COPY failed: %d", kr);+ }++ // (b) Scratch allocation + vm_remap with FIXED|OVERWRITE.+ vm_address_t scratch = 0;+ kr = vm_allocate(self_task, &scratch, span, VM_FLAGS_ANYWHERE);+ if (kr != KERN_SUCCESS) {+ vcc_log(@" vm_allocate failed: %d", kr);+ return 0;+ }+ memcpy((void *)scratch, (const void *)page_start, span);+ uint32_t nop = 0xD503201Fu;+ uintptr_t scratch_pc = scratch + (pc - page_start);+ ((uint32_t *)scratch_pc)[0] = nop;+ ((uint32_t *)scratch_pc)[1] = nop;+ kr = vm_protect(+ self_task,+ scratch,+ span,+ FALSE,+ VM_PROT_READ | VM_PROT_EXECUTE);+ if (kr != KERN_SUCCESS) {+ vcc_log(@" vm_protect RX scratch failed: %d", kr);+ vm_deallocate(self_task, scratch, span);+ return 0;+ }+ vm_address_t target = (vm_address_t)page_start;+ vm_prot_t cur_prot = 0, max_prot = 0;+ kr = vm_remap(+ self_task,+ &target,+ span,+ 0,+ VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE,+ self_task,+ scratch,+ FALSE,+ &cur_prot,+ &max_prot,+ VM_INHERIT_NONE);+ if (kr != KERN_SUCCESS) {+ vcc_log(@" vm_remap FIXED|OVERWRITE failed: %d (cur=0x%x max=0x%x)",+ kr,+ cur_prot,+ max_prot);+ vm_deallocate(self_task, scratch, span);+ return 0;+ }+ sys_icache_invalidate((void *)pc, 8);+ vcc_log(@" vm_remap OK: page=0x%lx span=%zu (cur=0x%x max=0x%x)",+ (unsigned long)page_start,+ (size_t)span,+ cur_prot,+ max_prot);+ return 1;+}++// Patch a single 32-bit ARM64 instruction word at `pc` to `new_word`.+// Uses the same vm_protect(VM_PROT_COPY) → write → vm_protect(RX) →+// icache flush dance as vcc_patch_two_nops. Verifies the original word+// matches `expected_word` before writing so an iOS version skew doesn't+// silently corrupt the wrong code. Returns 1 on success.+static int vcc_patch_word(uintptr_t pc,+ uint32_t expected_word,+ uint32_t new_word) {+ uint32_t cur = ((const uint32_t *)pc)[0];+ if (cur != expected_word) {+ vcc_log(@" patch_word @ 0x%lx: expected 0x%08x, found 0x%08x — skip",+ (unsigned long)pc,+ expected_word,+ cur);+ return 0;+ }+ uintptr_t page_size = (uintptr_t)getpagesize();+ uintptr_t page_start = pc & ~(page_size - 1);+ uintptr_t end = pc + 4;+ uintptr_t page_end = ((end + page_size - 1) & ~(page_size - 1));+ vm_size_t span = (vm_size_t)(page_end - page_start);+ mach_port_t self_task = mach_task_self();++ kern_return_t kr = vm_protect(+ self_task,+ (vm_address_t)page_start,+ span,+ FALSE,+ VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY);+ if (kr != KERN_SUCCESS) {+ vcc_log(@" patch_word vm_protect+COPY failed: %d", kr);+ return 0;+ }+ ((uint32_t *)pc)[0] = new_word;+ kr = vm_protect(+ self_task,+ (vm_address_t)page_start,+ span,+ FALSE,+ VM_PROT_READ | VM_PROT_EXECUTE);+ if (kr != KERN_SUCCESS) {+ vcc_log(@" patch_word restore RX failed: %d", kr);+ return 0;+ }+ sys_icache_invalidate((void *)pc, 4);+ vcc_log(@" patch_word OK @ 0x%lx: 0x%08x -> 0x%08x",+ (unsigned long)pc,+ expected_word,+ new_word);+ return 1;+}++// Scan the image's __text for every occurrence of `needle` and rewrite+// each to `replacement` via vcc_patch_word. Replaces hardcoded image+// VMAs for patches whose addresses we don't know per-build but whose+// instruction encoding is a stable fingerprint (e.g. `mov w20, #-12783`+// MOVN encodings used for error-prep). Returns the count patched.+static unsigned vcc_scan_and_patch(const vcc_image_t *img,+ uint32_t needle,+ uint32_t replacement,+ const char *what) {+ if (!img->text || !img->text_words) return 0;+ unsigned hits = 0;+ for (size_t i = 0; i < img->text_words; i++) {+ if (img->text[i] != needle) continue;+ uintptr_t pc = (uintptr_t)&img->text[i];+ if (vcc_patch_word(pc, needle, replacement)) hits++;+ }+ vcc_log(@" scan_and_patch %s (0x%08x -> 0x%08x): %u hit(s)",+ what ? what : "?",+ needle,+ replacement,+ hits);+ return hits;+}++// Scan __text for the daemon's client-allowlist filter sequence:+// bl <FigCaptureCopyClientCodeSigningIdentifier> ; X+// bl <objc_autorelease_stub> ; (don't care about target)+// mov x22, x0 ; 0xAA0003F6+// bl <FigCaptureGetSupportedPrewarmingBundleIds> ; Y+// cbz x22, ... ; (insn & 0xFF00001F) == 0xB4000016+// mov x2, x22 ; 0xAA1603E2+// bl <objc_msgSend$containsObject:> ; (don't care)+// cbz w0, ... ; (insn & 0xFF00001F) == 0x34000000+//+// On a hit, writes the absolute (slid) target of the 1st and 4th BL into+// `*si_fn_out` and `*prewarm_fn_out`. Returns the PC of the first BL.+static uintptr_t vcc_find_filter_chain(const vcc_image_t *img,+ uintptr_t *si_fn_out,+ uintptr_t *prewarm_fn_out) {+ if (!img->text || img->text_words < 8) return 0;+ *si_fn_out = 0;+ *prewarm_fn_out = 0;++ for (size_t i = 0; i + 7 < img->text_words; i++) {+ uint32_t bl1 = img->text[i];+ if ((bl1 & 0xFC000000u) != 0x94000000u) continue; // BL++ uint32_t bl2 = img->text[i + 1];+ if ((bl2 & 0xFC000000u) != 0x94000000u) continue; // BL++ uint32_t mov_x22 = img->text[i + 2];+ if (mov_x22 != 0xAA0003F6u) continue; // mov x22, x0++ uint32_t bl3 = img->text[i + 3];+ if ((bl3 & 0xFC000000u) != 0x94000000u) continue; // BL++ uint32_t cbz_x22 = img->text[i + 4];+ if ((cbz_x22 & 0xFF00001Fu) != 0xB4000016u) continue; // cbz x22, ...++ uint32_t mov_x2 = img->text[i + 5];+ if (mov_x2 != 0xAA1603E2u) continue; // mov x2, x22++ uint32_t bl4 = img->text[i + 6];+ if ((bl4 & 0xFC000000u) != 0x94000000u) continue; // BL++ uint32_t cbz_w0 = img->text[i + 7];+ if ((cbz_w0 & 0xFF00001Fu) != 0x34000000u) continue; // cbz w0, ...++ uintptr_t bl1_pc = (uintptr_t)&img->text[i];+ uintptr_t bl3_pc = (uintptr_t)&img->text[i + 3];+ *si_fn_out = vcc_bl_target(bl1_pc, bl1);+ *prewarm_fn_out = vcc_bl_target(bl3_pc, bl3);+ return bl1_pc;+ }+ return 0;+}++static int vcc_addr_in_data(const vcc_image_t *img, uintptr_t addr) {+ for (unsigned i = 0; i < img->data_range_count; i++) {+ if (addr >= img->data_ranges[i].start &&+ addr < img->data_ranges[i].end) return 1;+ }+ return 0;+}++// Decode ARM64 ADRP immediate from the instruction word.+// Returns the absolute page-aligned target of `adrp Xn, <page>`.+static uintptr_t vcc_adrp_target(uintptr_t adrp_pc, uint32_t adrp) {+ int64_t immlo = (adrp >> 29) & 0x3;+ int64_t immhi = (adrp >> 5) & 0x7ffff;+ int64_t imm = (immhi << 2) | immlo;+ if (imm & (1LL << 20)) imm |= ~((1LL << 21) - 1);+ return (adrp_pc & ~(uintptr_t)0xfffULL) + (uintptr_t)(imm << 12);+}++// Find a global by scanning __text for `adrp Xn, page; ldr Xm, [Xn, #offset]`.+// Tallies hits per resolved target address; accepts only candidates that+// fall inside one of CMCapture's writable data segments. Returns the+// most-hit candidate, or 0 if no candidate qualifies / there is a tie.+//+// `offset` is the byte offset within the page (must be a multiple of 8).+static uintptr_t vcc_find_data_xref(const vcc_image_t *img, unsigned offset) {+ if (!img->text || !img->text_words) return 0;+ if ((offset & 7) || offset > 0x7FF8) return 0;+ uint32_t scaled_imm = (offset / 8) & 0xfff;++ enum { MAX_CANDS = 16 };+ struct { uintptr_t addr; unsigned hits; } cands[MAX_CANDS];+ unsigned n_cands = 0;++ for (size_t i = 1; i < img->text_words; i++) {+ uint32_t ldr = img->text[i];+ // 64-bit LDR (immediate, unsigned offset): bits 31..22 = 1111100101+ if ((ldr & 0xFFC00000u) != 0xF9400000u) continue;+ if (((ldr >> 10) & 0xfff) != scaled_imm) continue;+ uint32_t rn = (ldr >> 5) & 0x1f;+ uint32_t adrp = img->text[i - 1];+ // ADRP: bits 31..24 fixed = 1xx10000 (mask 0x9F000000 == 0x90000000)+ if ((adrp & 0x9F000000u) != 0x90000000u) continue;+ if ((adrp & 0x1f) != rn) continue;+ uintptr_t adrp_pc = (uintptr_t)&img->text[i - 1];+ uintptr_t target = vcc_adrp_target(adrp_pc, adrp) + offset;+ if (!vcc_addr_in_data(img, target)) continue;++ unsigned k;+ for (k = 0; k < n_cands; k++) {+ if (cands[k].addr == target) { cands[k].hits++; break; }+ }+ if (k == n_cands && n_cands < MAX_CANDS) {+ cands[n_cands].addr = target;+ cands[n_cands].hits = 1;+ n_cands++;+ }+ }++ unsigned best = 0, best_hits = 0;+ int tie = 0;+ for (unsigned i = 0; i < n_cands; i++) {+ if (cands[i].hits > best_hits) {+ best_hits = cands[i].hits;+ best = i;+ tie = 0;+ } else if (cands[i].hits == best_hits) {+ tie = 1;+ }+ }+ if (best_hits == 0) {+ vcc_log(@" xref scan #%u: no in-data candidates", offset);+ return 0;+ }+ if (tie) {+ vcc_log(@" xref scan #%u: %u candidates tied at %u hits — refusing to pick",+ offset,+ n_cands,+ best_hits);+ return 0;+ }+ vcc_log(@" xref scan #%u: %u candidates, winner 0x%lx with %u hits",+ offset,+ n_cands,+ (unsigned long)cands[best].addr,+ best_hits);+ return cands[best].addr;+}++// arm64e ISA class-pointer mask, per libobjc's objc-private.h:+// `#define ISA_MASK 0x00007ffffffffff8ULL`. Bits 0-2 are isa flags+// (has_assoc / has_cxx_dtor / is_indexed), bits 3-46 are the class+// pointer (44 bits), bits 47-63 are PAC + magic-signature bits.+#define VCC_ISA_CLASS_MASK 0x00007FFFFFFFFFF8ULL++// Returns YES if the value stored at `slot_addr` is a pointer to a+// heap-allocated CFArray instance. Uses malloc_zone_from_ptr to+// confirm the candidate pointer was returned by malloc (safe for any+// 64-bit value; never dereferences) before reading its isa. CFArray+// instances are always heap allocations from the default malloc zone,+// so a non-heap value can't be _sSourceList.+static BOOL vcc_slot_value_is_cfarray(uintptr_t slot_addr) {+ if (!slot_addr) return NO;+ // The slot addresses read here are always in CMCapture's __DATA /+ // __DATA_CONST segments (filtered upstream by vcc_addr_in_data) so the read+ // itself is safe — those pages are mapped read-something into the process.+ uintptr_t val_ptr = *(uintptr_t *)slot_addr;+ if (!val_ptr) return NO;+ if (val_ptr < 0x100000000ULL || val_ptr > 0x800000000000ULL) return NO;+ // malloc_zone_from_ptr returns NULL for non-malloc pointers — this+ // is the safe pre-deref guard. CFArray instances are always heap-+ // allocated, so any candidate whose slot value isn't heap-owned is+ // definitionally not _sSourceList.+ malloc_zone_t *zone = malloc_zone_from_ptr((const void *)val_ptr);+ if (!zone) return NO;+ // Now safe to dereference: the value is a confirmed heap allocation.+ uintptr_t isa = *(uintptr_t *)val_ptr;+ uintptr_t isa_class = isa & VCC_ISA_CLASS_MASK;+ if (!isa_class) return NO;+ static const char *array_classes[] = {+ "__NSCFArray", "__NSArrayM", "__NSArrayI", "__NSArray0",+ "__NSSingleObjectArrayI", "NSArray", "NSMutableArray",+ "NSCFArray", NULL,+ };+ for (unsigned i = 0; array_classes[i]; i++) {+ Class c = objc_getClass(array_classes[i]);+ if (!c) continue;+ uintptr_t c_class = ((uintptr_t)c) & VCC_ISA_CLASS_MASK;+ if (isa_class == c_class) return YES;+ }+ return NO;+}++// Walk a function's body and collect every (BL <X> ; adrp + str x0,+// [Xn, #imm]) pair into `out_addrs`, returning the count. Useful for+// extracting the data-global init sequence of a static-init block —+// each pair represents one "store the result of a function call into+// a static global" site. The init block for CMCapture's source-list+// statics emits one such pair per global it initializes; the first+// one is `_sSourceList`.+static unsigned vcc_collect_call_then_store_globals(+ uintptr_t func,+ unsigned maxInsns,+ unsigned lookahead,+ uintptr_t *out_addrs,+ unsigned cap) {+ if (!func || !out_addrs || !cap) return 0;+ func = (uintptr_t)ptrauth_strip((void *)func, ptrauth_key_function_pointer);+ uint32_t *ip = (uint32_t *)func;+ unsigned n = 0;+ for (unsigned i = 0; i < maxInsns && n < cap; i++) {+ uint32_t insn = ip[i];+ if ((insn & 0xFC000000u) != 0x94000000u) continue; // BL+ for (unsigned j = 1; j <= lookahead && i + j + 1 < maxInsns; j++) {+ uint32_t adrp = ip[i + j];+ if ((adrp & 0x9F000000u) != 0x90000000u) continue;+ uint32_t rd_adrp = adrp & 0x1Fu;+ uint32_t str = ip[i + j + 1];+ if ((str & 0xFFC00000u) != 0xF9000000u) continue;+ uint32_t rt = str & 0x1Fu;+ uint32_t rn = (str >> 5) & 0x1Fu;+ uint32_t off = ((str >> 10) & 0xFFFu) * 8;+ if (rt != 0) continue;+ if (rn != rd_adrp) continue;+ uintptr_t adrp_pc = (uintptr_t)&ip[i + j];+ uintptr_t target = vcc_adrp_target(adrp_pc, adrp) + off;+ // Dedup+ BOOL dup = NO;+ for (unsigned k = 0; k < n; k++) {+ if (out_addrs[k] == target) { dup = YES; break; }+ }+ if (!dup) out_addrs[n++] = target;+ break;+ }+ }+ return n;+}++// Resolve a CFString constant by symbol name.+static CFStringRef vcc_cfconst(const char *symname) {+ void **slot = dlsym(RTLD_DEFAULT, symname);+ if (!slot) {+ vcc_log(@" dlsym FAIL: %s", symname);+ return NULL;+ }+ return (CFStringRef)*slot;+}++// Resolve a function symbol by name. On arm64e dlsym returns a PAC-signed+// pointer signed with key IA + discriminator 0 (the standard C ABI signing+// schema) — callable directly as a C function pointer. Returns NULL on miss.+static void *vcc_dlsym_fn(const char *name) {+ void *p = dlsym(RTLD_DEFAULT, name);+ if (!p) vcc_log(@" dlsym FAIL: %s", name);+ return p;+}diff --git a/VPhoneGuestComponents/VCamCaptured/VCamSessionHooks.inc b/VPhoneGuestComponents/VCamCaptured/VCamSessionHooks.incnew file mode 100644index 00000000..315c2ff1--- /dev/null+++ b/VPhoneGuestComponents/VCamCaptured/VCamSessionHooks.inc@@ -0,0 +1,486 @@+// MARK: - BWStillImageSampleBufferSinkNode observation + injection+//+// AVCapturePhotoOutput attaches a sampleBufferAvailableHandler block to the+// still-image sink node; the upstream graph normally drives the node by+// calling -renderSampleBuffer:forInput:, which routes the buffer through+// the node's internal logic and ultimately invokes the handler. Our synth+// has no upstream graph that produces frames, so the handler never fires.+//+// First pass: observe. Hook -setSampleBufferAvailableHandler: and+// -initWithInputMediaType:sinkID: to capture the node + the handler+// block per session, so we can later push a CMSampleBuffer ourselves.++static NSMutableArray *vcc_still_sinks = nil; // strong refs to nodes+static IMP vcc_still_set_handler_orig = NULL;+static IMP vcc_still_init_orig = NULL;+static IMP vcc_still_render_orig = NULL;++typedef id (*VccStillInitFn)(id self, SEL _cmd, id mediaType, id sinkID);+typedef void (*VccStillSetHandlerFn)(id self, SEL _cmd, id handler);+typedef void (*VccStillRenderFn)(id self, SEL _cmd, CMSampleBufferRef sb, id input);++static id vcc_still_init_hook(id self, SEL _cmd, id mediaType, id sinkID) {+ VccStillInitFn orig = (VccStillInitFn)vcc_still_init_orig;+ id ret = orig(self, _cmd, mediaType, sinkID);+ vcc_log(@" [StillSink init] self=%p mediaType=%@ sinkID=%@",+ ret, mediaType, sinkID);+ if (ret) {+ if (!vcc_still_sinks) vcc_still_sinks = [NSMutableArray new];+ [vcc_still_sinks addObject:ret];+ }+ return ret;+}++static void vcc_still_set_handler_hook(id self, SEL _cmd, id handler) {+ vcc_log(@" [StillSink setSampleBufferAvailableHandler:] self=%p handler=%p",+ self, handler);+ VccStillSetHandlerFn orig = (VccStillSetHandlerFn)vcc_still_set_handler_orig;+ orig(self, _cmd, handler);+}++static void vcc_still_render_hook(id self,+ SEL _cmd,+ CMSampleBufferRef sb,+ id input) {+ vcc_log(@" [StillSink renderSampleBuffer:forInput:] self=%p sb=%p input=%@",+ self, sb, input);+ VccStillRenderFn orig = (VccStillRenderFn)vcc_still_render_orig;+ orig(self, _cmd, sb, input);+}++static void vcc_install_still_sink_observation(void) {+ Class cls = NSClassFromString(@"BWStillImageSampleBufferSinkNode");+ if (!cls) {+ vcc_log(@" still-sink obs: class missing");+ return;+ }+ SEL initSel = NSSelectorFromString(@"initWithInputMediaType:sinkID:");+ SEL setHSel = @selector(setSampleBufferAvailableHandler:);+ SEL renderSel = @selector(renderSampleBuffer:forInput:);+ vcc_swizzle_method(cls, initSel,+ (IMP)vcc_still_init_hook, &vcc_still_init_orig);+ vcc_swizzle_method(cls, setHSel,+ (IMP)vcc_still_set_handler_hook,+ &vcc_still_set_handler_orig);+ vcc_swizzle_method(cls, renderSel,+ (IMP)vcc_still_render_hook, &vcc_still_render_orig);+}++// MARK: - BWFigCaptureSession graph callback observation+//+// AVCaptureSession.startRunning → cameracaptured graph build → start → these+// delegate callbacks fire on BWFigCaptureSession. If start fails (error != 0),+// the daemon reports failure back over XPC and client.isRunning stays NO.+// Hook these to see exactly where in the graph startup the failure occurs.++static IMP vcc_sess_didFinishStarting_orig = NULL;+static IMP vcc_sess_didStartSourceNode_orig = NULL;+static IMP vcc_sess_didPrepare_orig = NULL;++typedef void (*VccSessDidFinishStartingFn)(id self, SEL _cmd, id graph, int error);+typedef void (*VccSessDidStartSourceFn)(id self, SEL _cmd, id graph, id node, int error);+typedef void (*VccSessDidPrepareFn)(id self, SEL _cmd, id graph);++static void vcc_sess_didFinishStarting_hook(id self,+ SEL _cmd,+ id graph,+ int error) {+ vcc_log(@" [Sess graph:didFinishStartingWithError:] self=%p graph=%p err=%d",+ self, graph, error);+ VccSessDidFinishStartingFn orig =+ (VccSessDidFinishStartingFn)vcc_sess_didFinishStarting_orig;+ orig(self, _cmd, graph, error);+}++static void vcc_sess_didStartSourceNode_hook(id self,+ SEL _cmd,+ id graph,+ id node,+ int error) {+ vcc_log(@" [Sess graph:didStartSourceNode:error:] self=%p graph=%p node=%@ err=%d",+ self, graph, node, error);+ VccSessDidStartSourceFn orig =+ (VccSessDidStartSourceFn)vcc_sess_didStartSourceNode_orig;+ orig(self, _cmd, graph, node, error);+}++static void vcc_sess_didPrepare_hook(id self, SEL _cmd, id graph) {+ vcc_log(@" [Sess graphDidPrepareNodes:] self=%p graph=%p", self, graph);+ VccSessDidPrepareFn orig =+ (VccSessDidPrepareFn)vcc_sess_didPrepare_orig;+ orig(self, _cmd, graph);+}++static void vcc_install_session_graph_observation(void) {+ Class cls = NSClassFromString(@"BWFigCaptureSession");+ if (!cls) {+ vcc_log(@" session-graph obs: class missing");+ return;+ }+ vcc_swizzle_method(cls,+ @selector(graph:didFinishStartingWithError:),+ (IMP)vcc_sess_didFinishStarting_hook,+ &vcc_sess_didFinishStarting_orig);+ vcc_swizzle_method(cls,+ @selector(graph:didStartSourceNode:error:),+ (IMP)vcc_sess_didStartSourceNode_hook,+ &vcc_sess_didStartSourceNode_orig);+ vcc_swizzle_method(cls,+ @selector(graphDidPrepareNodes:),+ (IMP)vcc_sess_didPrepare_hook,+ &vcc_sess_didPrepare_orig);+}++// MARK: - BWFigCaptureSession init capture + pipelines extraction+//+// To splice our manual sink into a real session, we need a handle to its+// FigCaptureSessionPipelines instance. Hook the session's init and, post-orig,+// reach into the _pipelines ivar via KVC. Store globally so the next-stage+// injector has a live reference.++static IMP vcc_sess_initWithFigSess_orig = NULL;+typedef id (*VccSessInitWithFigSessFn)(id self, SEL _cmd, void *figSess);++static id vcc_captured_bw_session = nil; // strong ref to the BWFigCaptureSession+static id vcc_captured_pipelines = nil; // its _pipelines ivar value++__attribute__((ns_returns_retained))+static id vcc_sess_initWithFigSess_hook(id self, SEL _cmd, void *figSess) {+ VccSessInitWithFigSessFn orig =+ (VccSessInitWithFigSessFn)vcc_sess_initWithFigSess_orig;+ id ret = orig(self, _cmd, figSess);+ if (ret) {+ vcc_captured_bw_session = ret;+ @try {+ vcc_captured_pipelines = [ret valueForKey:@"pipelines"];+ } @catch (NSException *e) {+ @try {+ vcc_captured_pipelines = [ret valueForKey:@"_pipelines"];+ } @catch (NSException *e2) {+ vcc_captured_pipelines = nil;+ }+ }+ vcc_log(@" [BWFigCaptureSession init] -> self=%p figSess=%p _pipelines=%p (class=%@)",+ ret, figSess, vcc_captured_pipelines,+ NSStringFromClass([vcc_captured_pipelines class]));+ }+ return ret;+}++static void vcc_install_session_init_capture(void) {+ Class cls = NSClassFromString(@"BWFigCaptureSession");+ if (!cls) {+ vcc_log(@" session-init capture: class missing");+ return;+ }+ vcc_swizzle_method(cls,+ @selector(initWithFigCaptureSession:),+ (IMP)vcc_sess_initWithFigSess_hook,+ &vcc_sess_initWithFigSess_orig);+}++// MARK: - BWFigCaptureSession stillImageCoordinator observation+//+// AVCapturePhotoOutput.capturePhoto → daemon-side BWStillImageCaptureCoordinator+// queues a request and fires these delegate callbacks on BWFigCaptureSession.+// If willBegin… fires but didCapture… doesn't, the photo pipeline received+// the request but couldn't satisfy it (typically because no sample buffer+// arrived for it to wrap into a photo).++static IMP vcc_sess_willBeginPhoto_orig = NULL;+static IMP vcc_sess_willBeginPhotoForSettings_orig = NULL;+static IMP vcc_sess_willPreparePhoto_orig = NULL;+static IMP vcc_sess_willCapturePhoto_orig = NULL;+static IMP vcc_sess_didCapturePhoto_orig = NULL;++typedef void (*VccSessWillBeginPhotoFn)(id self, SEL _cmd, id coord, long settingsID);+typedef void (*VccSessSettingsFn)(id self, SEL _cmd, id coord, id settings);+typedef void (*VccSessWillPrepareFn)(id self, SEL _cmd, id coord, id settings, BOOL clientInitiated);+typedef void (*VccSessWillCaptureFn)(id self, SEL _cmd, id coord, id settings, int err);++static void vcc_sess_willBeginPhoto_hook(id self,+ SEL _cmd,+ id coord,+ long settingsID) {+ vcc_log(@" [Sess stillImageCoordinator:willBeginCaptureBeforeResolvingSettingsForID:] coord=%p id=%ld",+ coord, settingsID);+ VccSessWillBeginPhotoFn orig =+ (VccSessWillBeginPhotoFn)vcc_sess_willBeginPhoto_orig;+ orig(self, _cmd, coord, settingsID);+}++static void vcc_sess_willBeginPhotoForSettings_hook(id self,+ SEL _cmd,+ id coord,+ id settings) {+ vcc_log(@" [Sess stillImageCoordinator:willBeginCaptureForSettings:] coord=%p settings=%@",+ coord, settings);+ VccSessSettingsFn orig =+ (VccSessSettingsFn)vcc_sess_willBeginPhotoForSettings_orig;+ orig(self, _cmd, coord, settings);+}++static void vcc_sess_willPreparePhoto_hook(id self,+ SEL _cmd,+ id coord,+ id settings,+ BOOL clientInitiated) {+ vcc_log(@" [Sess stillImageCoordinator:willPrepareStillImageCaptureWithSettings:clientInitiated:] coord=%p settings=%@ ci=%d",+ coord, settings, clientInitiated);+ VccSessWillPrepareFn orig =+ (VccSessWillPrepareFn)vcc_sess_willPreparePhoto_orig;+ orig(self, _cmd, coord, settings, clientInitiated);+}++static void vcc_sess_willCapturePhoto_hook(id self,+ SEL _cmd,+ id coord,+ id settings,+ int err) {+ vcc_log(@" [Sess stillImageCoordinator:willCapturePhotoForSettings:error:] coord=%p settings=%@ err=%d",+ coord, settings, err);+ VccSessWillCaptureFn orig =+ (VccSessWillCaptureFn)vcc_sess_willCapturePhoto_orig;+ orig(self, _cmd, coord, settings, err);+}++static void vcc_sess_didCapturePhoto_hook(id self,+ SEL _cmd,+ id coord,+ id settings) {+ vcc_log(@" [Sess stillImageCoordinator:didCapturePhotoForSettings:] coord=%p settings=%@",+ coord, settings);+ VccSessSettingsFn orig =+ (VccSessSettingsFn)vcc_sess_didCapturePhoto_orig;+ orig(self, _cmd, coord, settings);+}++static void vcc_install_still_coordinator_observation(void) {+ Class cls = NSClassFromString(@"BWFigCaptureSession");+ if (!cls) {+ vcc_log(@" still-coord obs: BWFigCaptureSession missing");+ return;+ }+ vcc_swizzle_method(cls,+ @selector(stillImageCoordinator:willBeginCaptureBeforeResolvingSettingsForID:),+ (IMP)vcc_sess_willBeginPhoto_hook,+ &vcc_sess_willBeginPhoto_orig);+ vcc_swizzle_method(cls,+ @selector(stillImageCoordinator:willBeginCaptureForSettings:),+ (IMP)vcc_sess_willBeginPhotoForSettings_hook,+ &vcc_sess_willBeginPhotoForSettings_orig);+ vcc_swizzle_method(cls,+ @selector(stillImageCoordinator:willPrepareStillImageCaptureWithSettings:clientInitiated:),+ (IMP)vcc_sess_willPreparePhoto_hook,+ &vcc_sess_willPreparePhoto_orig);+ vcc_swizzle_method(cls,+ @selector(stillImageCoordinator:willCapturePhotoForSettings:error:),+ (IMP)vcc_sess_willCapturePhoto_hook,+ &vcc_sess_willCapturePhoto_orig);+ vcc_swizzle_method(cls,+ @selector(stillImageCoordinator:didCapturePhotoForSettings:),+ (IMP)vcc_sess_didCapturePhoto_hook,+ &vcc_sess_didCapturePhoto_orig);+}++// MARK: - BWStillImageCoordinatorNode existence detector+//+// If our synth session never instantiates BWStillImageCoordinatorNode, the+// capturePhoto request has nowhere to land. Swizzle its known internal+// method (-_enqueueRequestWithSettings:serviceRequestsIfNecessary:) so we+// detect whether the coordinator exists and ever sees a capture request.++static IMP vcc_still_coord_enqueue_orig = NULL;+typedef void (*VccStillCoordEnqueueFn)(id self, SEL _cmd, id settings, BOOL serviceIfNecessary);++static void vcc_still_coord_enqueue_hook(id self,+ SEL _cmd,+ id settings,+ BOOL serviceIfNecessary) {+ vcc_log(@" [StillCoord enqueueRequest] self=%p settings=%@ service=%d",+ self, settings, serviceIfNecessary);+ VccStillCoordEnqueueFn orig =+ (VccStillCoordEnqueueFn)vcc_still_coord_enqueue_orig;+ orig(self, _cmd, settings, serviceIfNecessary);+}++static void vcc_install_still_coord_node_observation(void) {+ Class cls = NSClassFromString(@"BWStillImageCoordinatorNode");+ if (!cls) {+ vcc_log(@" still-coord-node obs: class missing");+ return;+ }+ vcc_swizzle_method(cls,+ @selector(_enqueueRequestWithSettings:serviceRequestsIfNecessary:),+ (IMP)vcc_still_coord_enqueue_hook,+ &vcc_still_coord_enqueue_orig);+}++// MARK: - FigCaptureStillImageSinkPipeline init detector+//+// Per CMCapture symbols, the still pipeline is constructed via:+// -[FigCaptureStillImageSinkPipeline initWithConfiguration:captureDevice:+// sourceOutputsByPortType:captureStatusDelegate:inferenceScheduler:+// graph:name:]+// Hook this to see if it's called for our synth session, and what its+// arguments look like. If it's never called, the daemon's graph-build code+// decides upstream that no still pipeline is needed (probably based on a+// source attribute). If it's called and returns nil, we can inspect the+// arguments to figure out which is missing.++static IMP vcc_still_pipe_init_orig = NULL;+typedef id (*VccStillPipeInitFn)(id self,+ SEL _cmd,+ id config,+ id device,+ id outputsByPortType,+ id captureStatusDelegate,+ id inferenceScheduler,+ id graph,+ id name);++__attribute__((ns_returns_retained))+static id vcc_still_pipe_init_hook(id self,+ SEL _cmd,+ id config,+ id device,+ id outputsByPortType,+ id captureStatusDelegate,+ id inferenceScheduler,+ id graph,+ id name) {+ vcc_log(@" [StillPipe init] self=%p config=%@ device=%@ outputs.count=%lu name=%@",+ self, config, device,+ (unsigned long)([outputsByPortType respondsToSelector:@selector(count)]+ ? [outputsByPortType count] : 0),+ name);+ VccStillPipeInitFn orig = (VccStillPipeInitFn)vcc_still_pipe_init_orig;+ id ret = orig(self, _cmd, config, device, outputsByPortType,+ captureStatusDelegate, inferenceScheduler, graph, name);+ vcc_log(@" [StillPipe init] -> %p", ret);+ return ret;+}++static void vcc_install_still_pipeline_observation(void) {+ Class cls = NSClassFromString(@"FigCaptureStillImageSinkPipeline");+ if (!cls) {+ vcc_log(@" still-pipe obs: class missing");+ return;+ }+ SEL sel = NSSelectorFromString(+ @"initWithConfiguration:captureDevice:sourceOutputsByPortType:"+ @"captureStatusDelegate:inferenceScheduler:graph:name:");+ vcc_swizzle_method(cls, sel, (IMP)vcc_still_pipe_init_hook,+ &vcc_still_pipe_init_orig);+}++// MARK: - FigCaptureSessionPipelines.addStillImageSinkPipelineSessionStorage+//+// Per CMCapture symbols, this is the daemon-side method that registers a+// still-image sink pipeline with the session. If captureSession_buildGraph-+// WithConfiguration's still-pipeline branch ever runs for our synth source,+// this method gets called. If it's never called for our test, the upstream+// gate (parsed still-image sink configurations array empty?) is what we+// need to address.++static IMP vcc_pipelines_addStill_orig = NULL;+typedef void (*VccPipelinesAddStillFn)(id self, SEL _cmd, id storage);++static void vcc_pipelines_addStill_hook(id self, SEL _cmd, id storage) {+ vcc_log(@" [Pipelines addStillImageSinkPipelineSessionStorage:] self=%p storage=%@",+ self, storage);+ VccPipelinesAddStillFn orig =+ (VccPipelinesAddStillFn)vcc_pipelines_addStill_orig;+ orig(self, _cmd, storage);+}++static void vcc_install_pipelines_addStill_observation(void) {+ Class cls = NSClassFromString(@"FigCaptureSessionPipelines");+ if (!cls) {+ vcc_log(@" pipelines obs: class missing");+ return;+ }+ vcc_swizzle_method(cls,+ @selector(addStillImageSinkPipelineSessionStorage:),+ (IMP)vcc_pipelines_addStill_hook,+ &vcc_pipelines_addStill_orig);+}++// MARK: - graph-build error suppressors+//+// captureSession_buildGraphWithConfiguration's per-source iteration bails+// to OSStatus -12783 along three known paths on our synth source:+//+// (1) -[FigCaptureCameraSourcePipeline requiresMasterClock] returns YES,+// and the post-iteration check (OR of all pipelines' returns) bails+// on a virtual source that has no real ISP/HW clock.+// (2) _cs_addObjectToStreamsAttributes returns -12783 when an inherited+// ivar slot is NULL (called from _FigVideoCaptureSourcesActivate-+// AndCreateDevices during session activation).+// (3) -[BWFigVideoCaptureStream initWithCaptureStream:…] sets *errOut+// = -12783 in its validation-failure path.+//+// (1) is neutralized by rewriting the function's prologue to `mov w0, #0; ret`.+// The function's address is resolved from CMCapture's LC_SYMTAB by name —+// no hardcoded VMA.+//+// (2)+(3) are neutralized by scanning CMCapture's __text for the specific+// MOVN encodings the compiler used to prepare -12783 in w20 / w8, and+// rewriting each to `MOVZ w?, #0`. -12783 is a capture-specific OSStatus+// emitted only by the daemon; over-application is benign because the+// daemon's only consumer in the VM is our synth.++static void vcc_install_csp_requires_master_clock_hook(void) {+ vcc_image_t img;+ if (vcc_image_resolve(&img, "FigCaptureSourceServerStart") != 0) {+ vcc_log(@" graph-build patches: image resolve failed");+ return;+ }++ // (1) Resolve -[FigCaptureCameraSourcePipeline requiresMasterClock] via+ // LC_SYMTAB. The function is called via direct C dispatch (not in the+ // objc method table on observed builds, so swizzling won't work), so+ // we rewrite its prologue in place. The PAC-signed address from the+ // symtab is stripped before the write.+ static const char *const kReqMCSyms[] = {+ "_-[FigCaptureCameraSourcePipeline requiresMasterClock]",+ "-[FigCaptureCameraSourcePipeline requiresMasterClock]",+ NULL,+ };+ uintptr_t reqMC = 0;+ for (unsigned i = 0; kReqMCSyms[i]; i++) {+ reqMC = vcc_lookup_lc_symtab(&img, kReqMCSyms[i]);+ if (reqMC) {+ vcc_log(@" requiresMasterClock @ 0x%lx (sym=%s)",+ (unsigned long)reqMC, kReqMCSyms[i]);+ break;+ }+ }+ if (reqMC) {+ uintptr_t target = (uintptr_t)ptrauth_strip(+ (void *)reqMC, ptrauth_key_function_pointer);+ uint32_t insn0 = ((const uint32_t *)target)[0];+ uint32_t insn1 = ((const uint32_t *)target)[1];+ // Sanity anchor: the second prologue insn should be pacibsp on every+ // arm64e build that signs return addresses. Refuse the patch if it+ // isn't — we'd rather skip than rewrite an unrelated function.+ if (insn1 != 0xD503237Fu) {+ vcc_log(@" requiresMasterClock @ 0x%lx: insn1=0x%08x != pacibsp; skip",+ (unsigned long)target, insn1);+ } else {+ int ok1 = vcc_patch_word(target, insn0, 0x52800000u); // mov w0, #0+ int ok2 = vcc_patch_word(target + 4, insn1, 0xd65f03c0u); // ret+ vcc_log(@" requiresMasterClock prologue patch @ 0x%lx: %d/%d",+ (unsigned long)target, ok1, ok2);+ }+ } else {+ vcc_log(@" requiresMasterClock symbol not in LC_SYMTAB; patch skipped");+ }++ // (2) `mov w20, #-12783` (MOVN encoding 0x12863dd4) -> `mov w20, #0`.+ vcc_scan_and_patch(&img, 0x12863dd4u, 0x52800014u,+ "mov w20, #-12783 -> #0");+ // (3) `mov w8, #-12783` (MOVN encoding 0x12863dc8) -> `mov w8, #0`.+ vcc_scan_and_patch(&img, 0x12863dc8u, 0x52800008u,+ "mov w8, #-12783 -> #0");+}diff --git a/VPhoneGuestComponents/VCamCaptured/VCamSourceInstallation.inc b/VPhoneGuestComponents/VCamCaptured/VCamSourceInstallation.incnew file mode 100644index 00000000..4656030d--- /dev/null+++ b/VPhoneGuestComponents/VCamCaptured/VCamSourceInstallation.inc@@ -0,0 +1,624 @@+// MARK: - synthetic source construction++// Published as the synthetic source's CaptureDeviceID attribute, and matched+// against by the -[BWFigCaptureDeviceVendor copyDeviceWithID:…] hook. One+// declaration: the two must stay identical or the device lookup stops matching.+static NSString *const kVccSynthDeviceID = @"vphone:vcam:device:0";++static id vcc_build_backing(void) {+ Class backingClass = NSClassFromString(@"FigCaptureSourceBacking");+ if (!backingClass) {+ vcc_log(@" FigCaptureSourceBacking class missing");+ return nil;+ }+ CFStringRef k_uid = vcc_cfconst("kFigCaptureSourceAttributeKey_UniqueID");+ CFStringRef k_dt = vcc_cfconst("kFigCaptureSourceAttributeKey_DeviceType");+ CFStringRef k_ln = vcc_cfconst("kFigCaptureSourceAttributeKey_LocalizedName");+ CFStringRef k_mid = vcc_cfconst("kFigCaptureSourceAttributeKey_ModelID");+ CFStringRef k_pos = vcc_cfconst("kFigCaptureSourceAttributeKey_Position");+ CFStringRef k_st = vcc_cfconst("kFigCaptureSourceAttributeKey_SourceType");+ CFStringRef k_cdid = vcc_cfconst("kFigCaptureSourceAttributeKey_CaptureDeviceID");+ if (!k_uid || !k_dt) {+ vcc_log(@" required attr keys missing");+ return nil;+ }++ NSMutableDictionary *attrs = [NSMutableDictionary dictionary];+ attrs[(__bridge NSString *)k_uid] = @"vphone:vcam:0";+ // DeviceType: empirical sweep+ // - 1 (BuiltInWideAngleCamera): Camera.app routes to the real ISP /+ // hardware path and fails immediately because no hardware backs+ // us — viewfinder stream pool isn't even spun up.+ // - 2: Camera.app's Photo/Video tabs use the generic / soft path+ // and at least start the FigCameraViewfinderStream init pool+ // (~2000/sec) before stalling at openWithDestination:. This is+ // where we have a chance to inject a destination.+ // Keep 2 until the inject-destination shape is figured out.+ attrs[(__bridge NSString *)k_dt] = @(2);+ if (k_ln) attrs[(__bridge NSString *)k_ln] = @"vphone Virtual Camera";+ if (k_mid) attrs[(__bridge NSString *)k_mid] = @"vphone-vcam-1";+ if (k_pos) attrs[(__bridge NSString *)k_pos] = @(1);+ // sourceType MUST be 1 (video) for the daemon's media-type filter to+ // include this source in a vide-typed FigCaptureSourceRemoteCopyCaptureSources+ // request. Without it, attrs[SourceType] = nil → intValue = 0 → fails+ // the tbnz w8 gate in handleCopySourcesMessage.+ if (k_st) attrs[(__bridge NSString *)k_st] = @(1);+ // captureSession_buildGraphWithConfiguration (CMCapture vmaddr 0x1ae2b1910)+ // iterates the source list and calls+ // _FigCaptureSourceGetAttribute(source, kFigCaptureSourceAttributeKey_CaptureDeviceID)+ // then -[NSMutableArray addObject:] with the result. If the key is missing+ // the call returns nil and the array throws NSInvalidArgumentException+ // ("object cannot be nil") inside -[__NSArrayM insertObject:atIndex:] —+ // which kills cameracaptured as soon as any AVCaptureSession references+ // our synth.+ //+ // The value must be a string, NOT a number. -[BWFigCaptureDeviceVendor+ // _createDevice:reason:clientPID:figCaptureDevice:] sends isEqualToString:+ // to it; an NSNumber raises "unrecognized selector". Use a unique opaque+ // string outside whatever pattern Apple uses for hardware cameras.+ if (k_cdid) attrs[(__bridge NSString *)k_cdid] = kVccSynthDeviceID;++ // After hooking _FigCaptureSourceGetAttribute via lldb we observed+ // Camera.app's graph builder also queries these 5 boolean / scheme keys+ // against our synth. Provide explicit values so the builder doesn't bail+ // on a nil capability check. Verified order observed via lldb:+ // SmartCameraSupported, StillImageNoiseReductionAndFusionScheme,+ // MidFrameSynchronizationNotSupported, TimeOfFlightAssistedAutoFocusSupported,+ // StructuredLightAssistedAutoFocusSupported+ // Resolve the canonical CFString constant by symbol name when possible (some+ // are defined in a private framework not in the dyld exports trie, so we fall+ // back to the plain string after the Fig naming convention:+ // kFigSupportedFormat_VideoMinFrameRate → "VideoMinFrameRate").+ NSString *(^figKeyN)(const char *) = ^NSString *(const char *symname) {+ void **slot = dlsym(RTLD_DEFAULT, symname);+ if (slot && *slot) return (__bridge NSString *)(CFStringRef)(*slot);+ const char *cs = symname;+ const char *u = strrchr(cs, '_');+ if (u) cs = u + 1;+ return [NSString stringWithUTF8String:cs];+ };+ attrs[figKeyN("kFigCaptureSourceAttributeKey_SmartCameraSupported")] = @NO;+ attrs[figKeyN("kFigCaptureSourceAttributeKey_StillImageNoiseReductionAndFusionScheme")] = @(0);+ attrs[figKeyN("kFigCaptureSourceAttributeKey_MidFrameSynchronizationNotSupported")] = @NO;+ attrs[figKeyN("kFigCaptureSourceAttributeKey_TimeOfFlightAssistedAutoFocusSupported")] = @NO;+ attrs[figKeyN("kFigCaptureSourceAttributeKey_StructuredLightAssistedAutoFocusSupported")] = @NO;++ // Construct a FigCaptureSourceVideoFormat via its private init taking a+ // stream format dictionary. Required keys recovered by reversing+ // `-[FigCaptureSourceFormat formatDescription]` + `-format` + `-dimensions`:+ // "Name" (NSString) -- required by base init's cbz guard+ // "Width" (NSNumber) -- becomes dimensions.width+ // "Height" (NSNumber) -- becomes dimensions.height+ // "PixelFormatType" (NSNumber) -- 4cc fed to CMVideoFormatDescriptionCreate+ // All other keys read by the subclass init fall through to default+ // (0/nil) values via objectForKeyedSubscript: chains.+ NSArray *formats = @[];+ Class fmtClass = NSClassFromString(@"FigCaptureSourceVideoFormat");+ if (fmtClass) {+ // Publish TWO formats: one BGRA, one 420v at the same 1280x720+ // dimensions. Clients that filter on BGRA (e.g. Loupe / Magnifier)+ // see one; clients that pick the canonical ISP pixel format (AVF's+ // _preferredFormatForPreset: matcher for AVCaptureSessionPresetHigh)+ // pick the 420v one. Same preset list + frame-rate range on both.+ NSDictionary *commonKeys = @{+ @"DefaultActiveFormat" : @NO, // overridden on the active one+ figKeyN("kFigSupportedFormat_VideoMinFrameRate") : @(1),+ figKeyN("kFigSupportedFormat_VideoMaxFrameRate") : @(60),+ // -[FigCaptureSourceVideoFormat maxZoomFactor] takes a fast path that+ // returns 1.0 for raw bayer formats; for BGRA (our case) it falls to+ // a fancy path that reads stabilizationTypeOverrideForCinematic / -ForStandard+ // and consults a dimension-table when either equals 3. Setting this+ // key to 3 makes the table apply (returns 16.0 for 1280-wide formats),+ // which keeps -[AVCaptureFigVideoDevice setVideoZoomFactor:] from+ // throwing "out-of-range [1, activeFormat.videoMaxZoomFactor]" when+ // Camera.app sets a default zoom > 1.0.+ @"VideoStabilizationTypeOverrideForStandard" : @(3),+ // Without AVCaptureSessionPresets, -[AVCaptureDevice+ // supportsAVCaptureSessionPreset:] returns NO for every preset+ // (canAddInput=False everywhere except InputPriority). Camera.app+ // uses High/Photo — list them all so common AVF clients pass.+ @"AVCaptureSessionPresets" : @[+ @"AVCaptureSessionPresetHigh",+ @"AVCaptureSessionPreset1280x720",+ @"AVCaptureSessionPreset640x480",+ @"AVCaptureSessionPresetMedium",+ @"AVCaptureSessionPresetLow",+ @"AVCaptureSessionPresetPhoto",+ @"AVCaptureSessionPreset352x288",+ ],+ };+ NSMutableDictionary *bgra_fmt = [@{+ @"Name" : @"vphone-vcam-720p-bgra",+ @"Width" : @1280,+ @"Height" : @720,+ @"PixelFormatType" : @(0x42475241u), // 'BGRA'+ } mutableCopy];+ [bgra_fmt addEntriesFromDictionary:commonKeys];++ NSMutableDictionary *y420v_fmt = [@{+ @"Name" : @"vphone-vcam-720p-420v",+ @"Width" : @1280,+ @"Height" : @720,+ @"PixelFormatType" : @(0x34323076u), // '420v'+ } mutableCopy];+ [y420v_fmt addEntriesFromDictionary:commonKeys];+ // Mark 420v as default — it's what AVF's preset matcher prefers when+ // picking _setActiveFormat: under standard presets.+ y420v_fmt[@"DefaultActiveFormat"] = @YES;++ SEL fmtInitSel = NSSelectorFromString(+ @"initWithFigCaptureStreamFormatDictionary:");+ NSMutableArray *formatObjs = [NSMutableArray array];+ for (NSDictionary *fmtDict in @[ bgra_fmt, y420v_fmt ]) {+ id fmtAlloc = ((id (*)(Class, SEL))objc_msgSend)(fmtClass,+ @selector(alloc));+ id fmtObj = nil;+ if (fmtAlloc) {+ fmtObj = ((id (*)(id, SEL, id))objc_msgSend)(+ fmtAlloc,+ fmtInitSel,+ fmtDict);+ }+ vcc_log(@" FigCaptureSourceVideoFormat (%@) = %p",+ fmtDict[@"Name"],+ fmtObj);+ if (fmtObj) [formatObjs addObject:fmtObj];+ }+ formats = formatObjs;+ } else {+ vcc_log(@" FigCaptureSourceVideoFormat class missing");+ }++ SEL initSel = NSSelectorFromString(+ @"initWithMediaType:attributes:cachedProperties:formats:"+ @"missingFormatNames:synchronizedStreamUniqueIDs:"+ @"unsynchronizedStreamUniqueIDs:");+ id alloced = ((id (*)(Class, SEL))objc_msgSend)(backingClass,+ @selector(alloc));+ if (!alloced) return nil;+ uint32_t mediaTypeVideo = 0x76696465; // 'vide'+ id backing = ((id (*)(id, SEL, uint32_t, id, id, id, id, id, id))objc_msgSend)(+ alloced,+ initSel,+ mediaTypeVideo,+ attrs,+ [NSMutableDictionary dictionary],+ formats,+ @[],+ @[],+ @[]);+ vcc_log(@" backing = %p (attrs.count=%lu formats.count=%lu)",+ backing,+ (unsigned long)attrs.count,+ (unsigned long)formats.count);+ return backing;+}++// FigCaptureSourceCreateFromBacking signature (5 args):+// (CFAllocatorRef allocator, FigCaptureSourceBacking *backing,+// audit_token_t *token, int unused_x3, FigCaptureSource **outSource)+typedef int (*VCC_CreateFn)(CFAllocatorRef, id, void *, int, void **);++static void *vcc_create_synthetic_source(VCC_CreateFn create_fn, id backing) {+ audit_token_t self_token;+ mach_msg_type_number_t count = TASK_AUDIT_TOKEN_COUNT;+ kern_return_t kr = task_info(mach_task_self(), TASK_AUDIT_TOKEN,+ (task_info_t)&self_token, &count);+ if (kr != KERN_SUCCESS) {+ vcc_log(@" task_info(TASK_AUDIT_TOKEN) failed: %d", kr);+ return NULL;+ }++ void *outSource = NULL;+ int ret = create_fn(kCFAllocatorDefault, backing, &self_token, 0, &outSource);+ vcc_log(@" CreateFromBacking ret=0x%x outSource=%p", (unsigned)ret,+ outSource);+ return outSource;+}++// Walk the synthetic's PAC-signed vtable to call CopyProperty (vtable[6]) for+// confirmation of the contract methods. This is purely diagnostic; uses only+// dlsym-resolvable anchors (CMBaseObjectGetVTable) and standard PAC builtins.+static void vcc_probe_contract(void *source) {+ void *(*CMBaseObjectGetVTable)(void *) =+ (void *(*)(void *))vcc_dlsym_fn("CMBaseObjectGetVTable");+ if (!CMBaseObjectGetVTable) return;+ void *V = CMBaseObjectGetVTable(source);+ vcc_log(@" CMBaseObjectGetVTable(synth) = %p", V);+ if (!V) return;++ // Auth the vtable pointer (data key A, address-blended discriminator).+ void **vtable_slot = (void **)((char *)V + 8);+ void *real_vtable_signed = *vtable_slot;+ uintptr_t vt_disc =+ __builtin_ptrauth_blend_discriminator(vtable_slot, 47377);+ void *real_vtable = __builtin_ptrauth_auth(real_vtable_signed,+ ptrauth_key_asda, vt_disc);+ vcc_log(@" real_vtable @ %p", real_vtable);++ // Auth method6 (instruction key A) then resign for the C ABI call.+ void **method6_slot = (void **)((char *)real_vtable + 48);+ void *method6_signed = *method6_slot;+ uintptr_t m6_disc =+ __builtin_ptrauth_blend_discriminator(method6_slot, 38693);+ void *method6 = __builtin_ptrauth_auth_and_resign(+ method6_signed, ptrauth_key_asia, m6_disc,+ ptrauth_key_function_pointer, 0);+ vcc_log(@" CopyProperty (vtable[6]) @ %p", method6);++ typedef int (*VCC_CopyPropFn)(void *src, CFStringRef key,+ CFAllocatorRef alloc, CFTypeRef *out);+ VCC_CopyPropFn copyProp = (VCC_CopyPropFn)method6;++ CFStringRef k_attrs = vcc_cfconst(+ "kFigCaptureSourceProperty_AttributesDictionary");+ CFStringRef k_fmts = vcc_cfconst("kFigCaptureSourceProperty_Formats");++ CFTypeRef outAttrs = NULL;+ int e1 = copyProp(source, k_attrs, kCFAllocatorDefault, &outAttrs);+ vcc_log(@" CopyProperty(AttributesDictionary) ret=%d out=%p (%@)",+ e1, outAttrs, outAttrs);+ if (outAttrs) CFRelease(outAttrs);++ CFTypeRef outFmts = NULL;+ int e2 = copyProp(source, k_fmts, kCFAllocatorDefault, &outFmts);+ vcc_log(@" CopyProperty(Formats) ret=%d out=%p (count=%ld)",+ e2, outFmts,+ outFmts && CFGetTypeID(outFmts) == CFArrayGetTypeID()+ ? CFArrayGetCount(outFmts) : -1);+ if (outFmts) CFRelease(outFmts);+}++// MARK: - _sSourceList manipulation++static void vcc_install_synthetic(void) {+ vcc_image_t img;+ int rc = vcc_image_resolve(&img, "FigCaptureSourceServerStart");+ if (rc != 0) {+ vcc_log(@" image resolve failed rc=%d", rc);+ return;+ }+ vcc_log(@" CMCapture mh=%p slide=0x%lx text=%p words=%zu nsyms=%u",+ img.mh, (unsigned long)img.slide, img.text, img.text_words,+ img.nsyms);++ // DSC strips per-image LC_SYMTAB names to "<redacted>" — symtab walking+ // by name doesn't work. Recover the two private function addresses via+ // a structural pattern scan of __text for the daemon's filter chain.+ uintptr_t si_fn_addr = 0, prewarm_fn_addr = 0;+ uintptr_t hit_pc =+ vcc_find_filter_chain(&img, &si_fn_addr, &prewarm_fn_addr);+ vcc_log(@" filter-chain scan: pc=0x%lx si_fn=0x%lx prewarm_fn=0x%lx",+ (unsigned long)hit_pc, (unsigned long)si_fn_addr,+ (unsigned long)prewarm_fn_addr);++ // Patch the per-source ownership/prewarming filter that runs inside the+ // iteration loop of handleCopySourcesMessage. Without these patches,+ // every source is rejected unless its ClientBundleIdentifier property+ // matches the requesting client's signing-id AND PrewarmingEnabled is+ // YES — which is never true for our synthetic source nor for the daemon+ // bring-up source against a non-Camera.app client.+ uintptr_t per_source_pc = vcc_find_per_source_filter(&img);+ if (per_source_pc) {+ int ok = vcc_patch_two_nops(per_source_pc);+ vcc_log(@" per-source NOP patch %s @ 0x%lx",+ ok ? "OK" : "FAILED", (unsigned long)per_source_pc);+ } else {+ vcc_log(@" per-source filter not located — daemon will skip our source");+ }++ if (prewarm_fn_addr) {+ typedef CFTypeRef (*PrewarmFn)(void);+ PrewarmFn pf = (PrewarmFn)ptrauth_sign_unauthenticated(+ (void *)prewarm_fn_addr, ptrauth_key_function_pointer, 0);+ CFTypeRef setv = pf();+ vcc_log(@" prewarming allowlist set = %p (%@)",+ setv, (__bridge id)setv);++ // Patch the daemon's prewarming-bundle allowlist so EVERY XPC client+ // passes the `[set containsObject:clientSI]` gate in+ // _captureSourceServer_handleCopySourcesMessage. We don't mutate the+ // set's contents — we object_setClass it to a dynamically-built+ // subclass whose -containsObject: implementation always returns YES.+ // This is __DATA-clean (no __TEXT writes, no TXM concerns) and+ // limited to this single singleton instance.+ if (setv) {+ id theSet = (__bridge id)setv;+ Class origCls = object_getClass(theSet);+ Class allowCls = objc_allocateClassPair(+ origCls, "vcc_AlwaysAllowSet", 0);+ if (allowCls) {+ IMP yesImp = imp_implementationWithBlock(+ ^BOOL(__unused id self_, __unused id obj) { return YES; });+ Method orig = class_getInstanceMethod(origCls,+ @selector(containsObject:));+ const char *types = orig ? method_getTypeEncoding(orig) : "B@:@";+ class_addMethod(allowCls, @selector(containsObject:), yesImp, types);+ objc_registerClassPair(allowCls);+ object_setClass(theSet, allowCls);+ vcc_log(@" swizzled set's class -> vcc_AlwaysAllowSet (orig=%s)",+ class_getName(origCls));+ } else {+ vcc_log(@" objc_allocateClassPair returned nil (already registered?)");+ }+ }+ }+++ // Force daemon's source-server init so `_sSourceList` is allocated.+ void *start_fn = vcc_dlsym_fn("FigCaptureSourceServerStart");+ if (start_fn) {+ ((void (*)(void))start_fn)();+ vcc_log(@" called FigCaptureSourceServerStart()");+ }++ // Resolve _sSourceList structurally:+ //+ // LC_SYMTAB → __captureSourceServer_initializeStatics_block_invoke+ // (the dispatch_once init body — static text symbol, retained+ // in the on-device DSC nlist even when static *data* symbols+ // like `_sSourceList` itself are stripped)+ // → BL CFArrayCreateMutable inside the block body+ // → adrp+str x0, [Xn, #imm] ← stores into _sSourceList+ //+ // Every link is a structural ARM64 pattern, so the chain is stable+ // across iOS revisions. The static-init function naming convention+ // (`<class>_initializeStatics_block_invoke`) has been used by Apple+ // since the iOS 14 era and persists through 26.x.+ uintptr_t fnCFArrayCreate = (uintptr_t)dlsym(RTLD_DEFAULT,+ "CFArrayCreateMutable");+ // The on-device nlist exports static text symbols with leading+ // underscores. Block-invoke names take one extra underscore vs the+ // outer C symbol — try the canonical first, plus a triple-_ variant+ // some clangs emit.+ static const char *kInitBlockNames[] = {+ "__captureSourceServer_initializeStatics_block_invoke",+ "___captureSourceServer_initializeStatics_block_invoke",+ NULL,+ };+ uintptr_t blockInvoke = 0;+ for (unsigned i = 0; kInitBlockNames[i]; i++) {+ blockInvoke = vcc_lookup_lc_symtab(&img, kInitBlockNames[i]);+ if (blockInvoke) {+ vcc_log(@" init-statics block-invoke (%s) @ 0x%lx",+ kInitBlockNames[i], (unsigned long)blockInvoke);+ break;+ }+ }+ // If the symbol is stripped on-device (typical for the DSC), walk+ // the structural chain rooted at FigCaptureSourceServerStart to+ // find the dispatch_once block-invoke. The chain is:+ //+ // FigCaptureSourceServerStart (exported, addr known)+ // `cmn x?, #0x1 ; b.ne <wrapper>` (onceToken check)+ // wrapper (`.cold.1`, static; addr from b.ne)+ // `bl <cold.1>` (we land here from b.ne; target IS cold.1)+ // cold.1 (5–6 instructions, static)+ // `adrp x0,...; add x0, x0, ...` (onceToken pointer)+ // `adrp x1,...; add x1, x1, ...` (block-constant pointer)+ // `bl <dispatch_once stub>`+ // block constant (struct __Block_literal in __DATA_CONST)+ // +0x10 = invoke pointer (PAC-signed; raw bytes are the function+ // address before signature stripping)+ if (!blockInvoke) {+ uintptr_t fnFigStart = (uintptr_t)dlsym(RTLD_DEFAULT,+ "FigCaptureSourceServerStart");+ if (fnFigStart) {+ fnFigStart = (uintptr_t)ptrauth_strip((void *)fnFigStart,+ ptrauth_key_function_pointer);+ uint32_t *ip = (uint32_t *)fnFigStart;+ uintptr_t coldWrapper = 0;+ // Step 1: find `cmn x?, #0x1; b.ne <target>` and decode target.+ // CMN (immediate) 64-bit, no shift:+ // 1011 0001 00ii iiii iiii iinn nnn1 1111+ // mask 0xFFC0001F, match 0xB100001F.+ // B.NE: 0101 0100 iiii iiii iiii iiii iii0 0001+ // mask 0xFF00001F, match 0x54000001.+ for (unsigned i = 0; i < 256 && !coldWrapper; i++) {+ uint32_t cmn = ip[i];+ if ((cmn & 0xFFC0001Fu) != 0xB100001Fu) continue;+ // imm12 in bits[21:10]+ uint32_t imm = (cmn >> 10) & 0xFFFu;+ if (imm != 1) continue;+ if (i + 1 >= 256) continue;+ uint32_t bne = ip[i + 1];+ if ((bne & 0xFF00001Fu) != 0x54000001u) continue;+ int32_t imm19 = (int32_t)((bne & 0x00FFFFE0u) << 8) >> 11;+ coldWrapper = (uintptr_t)&ip[i + 1] + (intptr_t)imm19;+ }+ if (!coldWrapper) {+ vcc_log(@" cmn+b.ne onceToken-check pattern not found in "+ @"FigCaptureSourceServerStart");+ } else {+ vcc_log(@" cold-wrapper site @ 0x%lx", (unsigned long)coldWrapper);+ // Step 2: cold wrapper starts with `bl <cold.1>`. Decode.+ uint32_t bl = *(uint32_t *)coldWrapper;+ uintptr_t cold1 = 0;+ if ((bl & 0xFC000000u) == 0x94000000u) {+ int32_t imm26 = (int32_t)((bl & 0x03FFFFFFu) << 6) >> 4;+ cold1 = coldWrapper + (intptr_t)imm26;+ vcc_log(@" cold.1 @ 0x%lx", (unsigned long)cold1);+ }+ // Step 3: walk cold.1 looking for the LAST `adrp x1,...; add x1,+ // x1, #imm` pair BEFORE the dispatch_once `bl`. That's the block+ // constant. cold.1 is typically only 5–6 instructions long.+ if (cold1) {+ uint32_t *cip = (uint32_t *)cold1;+ uintptr_t blockConst = 0;+ for (unsigned i = 0; i < 16; i++) {+ uint32_t add = cip[i];+ if ((add & 0xFF800000u) != 0x91000000u) continue;+ if ((add & 0x1Fu) != 1) continue; // ADD x1, ...+ if (((add >> 5) & 0x1Fu) != 1) continue;+ uint32_t add_imm = (add >> 10) & 0xFFFu;+ // Walk back for matching adrp x1+ for (unsigned k = 1; k <= 4 && k <= i; k++) {+ uint32_t adrp = cip[i - k];+ if ((adrp & 0x9F000000u) != 0x90000000u) continue;+ if ((adrp & 0x1Fu) != 1) continue;+ uintptr_t adrp_pc = (uintptr_t)&cip[i - k];+ blockConst = vcc_adrp_target(adrp_pc, adrp) + add_imm;+ break;+ }+ if (blockConst) break;+ }+ if (!blockConst) {+ vcc_log(@" block-constant adrp+add not found in cold.1");+ } else {+ vcc_log(@" block constant @ 0x%lx", (unsigned long)blockConst);+ // Step 4: read invoke pointer at offset 0x10 within the+ // block constant. PAC-strip and assign as block-invoke.+ uintptr_t rawInvoke = *(uintptr_t *)(blockConst + 0x10);+ blockInvoke = (uintptr_t)ptrauth_strip(+ (void *)rawInvoke, ptrauth_key_function_pointer);+ vcc_log(@" init block-invoke (via cold.1 chain) @ 0x%lx",+ (unsigned long)blockInvoke);+ }+ }+ }+ }+ }+ uintptr_t sSourceListAddr = 0;+ if (blockInvoke) {+ uintptr_t globals[8] = {0};+ unsigned ng = vcc_collect_call_then_store_globals(blockInvoke,+ /*maxInsns*/512,+ /*lookahead*/12,+ globals, 8);+ for (unsigned i = 0; i < ng; i++) {+ vcc_log(@" init-statics global #%u: 0x%lx",+ i, (unsigned long)globals[i]);+ }+ // The init block initializes both `_sSourceListLock` (lock+ // handle) and `_sSourceList` (CFArray) in order. Walk the+ // discovered globals and pick the first one whose slot value+ // is actually a CFArray — that's the source list. The lock+ // entry has a void* mutex handle which malloc_zone validates+ // but isa fails the CFArray-class check.+ uintptr_t symLookup = vcc_lookup_lc_symtab(&img, "_sSourceList");+ if (symLookup) {+ vcc_log(@" _sSourceList also in LC_SYMTAB at 0x%lx — using",+ (unsigned long)symLookup);+ sSourceListAddr = symLookup;+ } else {+ for (unsigned i = 0; i < ng; i++) {+ if (vcc_slot_value_is_cfarray(globals[i])) {+ uintptr_t val = 0;+ if (globals[i]) val = *(uintptr_t *)globals[i];+ vcc_log(@" _sSourceList chosen (init-store #%u, CFArray @ 0x%lx) at 0x%lx",+ i, (unsigned long)val, (unsigned long)globals[i]);+ sSourceListAddr = globals[i];+ break;+ }+ }+ if (!sSourceListAddr) {+ vcc_log(@" no init-store global slot held a CFArray; falling "+ @"back to first init-store");+ if (ng > 0) sSourceListAddr = globals[0];+ }+ }+ } else {+ vcc_log(@" init-statics block-invoke lookup failed");+ }+ if (!sSourceListAddr) {+ vcc_log(@" data global resolve failed: _sSourceList not located");+ return;+ }++ // For the lock, the call-anchor approach requires knowing which+ // mutex-create function the daemon uses (FigSimpleMutexCreate / Init+ // / etc. — name varies across iOS). Skip locking entirely: our+ // dispatch_after fires after FigCaptureSourceServerStart's+ // dispatch_once block has finished, and we're the only writer to+ // _sSourceList during this init window.+ CFMutableArrayRef *sSourceListSlot =+ (CFMutableArrayRef *)sSourceListAddr;+ vcc_log(@" lock acquisition skipped (single-threaded init window)");+ vcc_log(@" _sSourceList slot @ %p (list=%p)", sSourceListSlot,+ *sSourceListSlot);++ // Resolve FigCaptureSourceCreateFromBacking. Marked `external` in+ // CMCapture's symtab — should be in the dyld exports trie.+ void *create_p = vcc_dlsym_fn("FigCaptureSourceCreateFromBacking");+ if (!create_p) {+ vcc_log(@" abort: FigCaptureSourceCreateFromBacking not dlsym-resolvable");+ return;+ }+ VCC_CreateFn create_fn = (VCC_CreateFn)create_p;++ id backing = vcc_build_backing();+ if (!backing) return;+ void *source = vcc_create_synthetic_source(create_fn, backing);+ if (!source) {+ vcc_log(@" create returned NULL — abort");+ return;+ }++ vcc_probe_contract(source);++ // Dump ALL existing sources' AttributesDictionary so we can mirror what+ // the daemon's stock (bring-up / hardware) sources use for keys like+ // DeviceType, SmartCameraSupported, Streams, Ports, etc.+ {+ CFMutableArrayRef listSnap = *sSourceListSlot;+ CFIndex cnt = listSnap ? CFArrayGetCount(listSnap) : 0;+ vcc_log(@" --- existing sources (count=%ld) ---", (long)cnt);+ void *(*CMBaseObjectGetVTable)(void *) =+ (void *(*)(void *))vcc_dlsym_fn("CMBaseObjectGetVTable");+ for (CFIndex i = 0; i < cnt; i++) {+ void *s = (void *)CFArrayGetValueAtIndex(listSnap, i);+ vcc_log(@" source[%ld] = %p", (long)i, s);+ if (!CMBaseObjectGetVTable) continue;+ void *V = CMBaseObjectGetVTable(s);+ if (!V) continue;+ void **vtable_slot = (void **)((char *)V + 8);+ void *real_vtable_signed = *vtable_slot;+ uintptr_t vt_disc =+ __builtin_ptrauth_blend_discriminator(vtable_slot, 47377);+ void *real_vtable = __builtin_ptrauth_auth(real_vtable_signed,+ ptrauth_key_asda, vt_disc);+ if (!real_vtable) continue;+ void **method6_slot = (void **)((char *)real_vtable + 48);+ void *method6_signed = *method6_slot;+ uintptr_t m6_disc =+ __builtin_ptrauth_blend_discriminator(method6_slot, 38693);+ void *method6 = __builtin_ptrauth_auth_and_resign(+ method6_signed, ptrauth_key_asia, m6_disc,+ ptrauth_key_function_pointer, 0);+ typedef int (*CP)(void *, CFStringRef, CFAllocatorRef, CFTypeRef *);+ CP copyProp = (CP)method6;+ CFStringRef k_attrs = vcc_cfconst(+ "kFigCaptureSourceProperty_AttributesDictionary");+ CFTypeRef out = NULL;+ int e = copyProp(s, k_attrs, kCFAllocatorDefault, &out);+ vcc_log(@" attrs ret=%d -> %@", e, (__bridge id)out);+ if (out) CFRelease(out);+ }+ }++ CFMutableArrayRef list = *sSourceListSlot;+ if (!list) {+ vcc_log(@" _sSourceList is NULL (server init not yet allocated it) — abort");+ return;+ }+ CFIndex preCount = CFArrayGetCount(list);+ CFArrayAppendValue(list, source);+ CFIndex postCount = CFArrayGetCount(list);+ vcc_log(@" appended source — list %ld -> %ld", (long)preCount,+ (long)postCount);++ CFStringRef notifNameCF = vcc_cfconst(+ "kFigCaptureSourceNotification_SourceInfoArrayChanged");+ if (notifNameCF) {+ char buf[256];+ if (CFStringGetCString(notifNameCF, buf, sizeof(buf),+ kCFStringEncodingUTF8)) {+ uint32_t status = notify_post(buf);+ vcc_log(@" notify_post(%s) -> %u", buf, status);+ } else {+ vcc_log(@" CFStringGetCString failed for notif name");+ }+ } else {+ vcc_log(@" notif name CFString constant missing");+ }+}diff --git a/VPhoneGuestComponents/VCamCaptured/VCamStillSink.inc b/VPhoneGuestComponents/VCamCaptured/VCamStillSink.incnew file mode 100644index 00000000..a436cdef--- /dev/null+++ b/VPhoneGuestComponents/VCamCaptured/VCamStillSink.inc@@ -0,0 +1,249 @@+// MARK: - Sink node injection — manually-constructed BWStillImageSampleBufferSinkNode+//+// The daemon's session graph for our synth source builds without a still-image+// pipeline → no BWStillImageSampleBufferSinkNode exists → capturePhoto can't+// find a sink to deliver to → -11803 "Cannot Record".+//+// Manually construct a BWStillImageSampleBufferSinkNode at install time.+// Observation pass: prove the class accepts initialization in our daemon+// context. Next iteration adds the wiring path so capturePhoto sees this+// sink and delivers our shm frame through it.++static id vcc_synth_still_sink = nil;++static void vcc_construct_still_sink(void) {+ Class cls = NSClassFromString(@"BWStillImageSampleBufferSinkNode");+ if (!cls) {+ vcc_log(@" manual still-sink: class missing");+ return;+ }+ // Per ipsw symaddr the simpler init is -[BWStillImageSampleBufferSinkNode+ // initWithSinkID:] at static 0x1ae333e20. The full init takes inputMediaType+ // + sinkID. Try the simpler one first.+ SEL sinkIdInit = NSSelectorFromString(@"initWithSinkID:");+ id sinkID = @(0xCAFEBABEull); // synthetic sinkID, unique to us+ id alloced = ((id (*)(Class, SEL))objc_msgSend)(cls, @selector(alloc));+ if (!alloced) {+ vcc_log(@" manual still-sink: alloc returned nil");+ return;+ }+ if (![alloced respondsToSelector:sinkIdInit]) {+ vcc_log(@" manual still-sink: doesn't respond to %@",+ NSStringFromSelector(sinkIdInit));+ // Don't init — leak the alloced bytes (cheaper than crashing)+ return;+ }+ @try {+ vcc_synth_still_sink =+ ((id (*)(id, SEL, id))objc_msgSend)(alloced, sinkIdInit, sinkID);+ } @catch (NSException *e) {+ vcc_log(@" manual still-sink: init exception: %@", e);+ return;+ }+ vcc_log(@" manual still-sink: created %p (class=%@)",+ vcc_synth_still_sink,+ NSStringFromClass([vcc_synth_still_sink class]));+ if (!vcc_synth_still_sink) return;++ // Probe properties to make sure we got a usable instance.+ @try {+ SEL hdlrGet = @selector(sampleBufferAvailableHandler);+ if ([vcc_synth_still_sink respondsToSelector:hdlrGet]) {+ id existing =+ ((id (*)(id, SEL))objc_msgSend)(vcc_synth_still_sink, hdlrGet);+ vcc_log(@" manual still-sink: initial sampleBufferAvailableHandler=%p",+ existing);+ } else {+ vcc_log(@" manual still-sink: no -sampleBufferAvailableHandler");+ }+ } @catch (NSException *e) {+ vcc_log(@" manual still-sink: probe exception: %@", e);+ }++ // Synthesize a sampleBufferAvailableHandler block and set it on our sink.+ //+ // Per disasm of -[BWStillImageSampleBufferSinkNode renderSampleBuffer:forInput:]+ // at static 0x1ae577428, the block invoke at 0x1ae57758c-590 takes:+ // x0 = block (auto)+ // x1 = CMSampleBufferRef sampleBuffer+ // x2 = BOOL flag (always 0 at this site)+ // x3 = [x21 requestedSettings] (presumably the AVCapturePhotoSettings)+ //+ // We don't yet have a real XPC reply path; this handler is currently a+ // logging probe that lets us verify our manually-installed handler does+ // fire when we drive -renderSampleBuffer:forInput: ourselves.+ SEL setHandlerSel = @selector(setSampleBufferAvailableHandler:);+ if ([vcc_synth_still_sink respondsToSelector:setHandlerSel]) {+ void (^block)(CMSampleBufferRef, BOOL, id) =+ ^(CMSampleBufferRef sbuf, BOOL flag, id requestedSettings) {+ vcc_log(@" [SyntheticHandler] sbuf=%p flag=%d settings=%@",+ sbuf, flag, requestedSettings);+ // Extract the image data and write to disk as proof of pipeline integrity.+ if (!sbuf) return;+ CVImageBufferRef pb = CMSampleBufferGetImageBuffer(sbuf);+ if (!pb) {+ vcc_log(@" [SyntheticHandler] no image buffer");+ return;+ }+ CVPixelBufferLockBaseAddress(pb, kCVPixelBufferLock_ReadOnly);+ size_t w = CVPixelBufferGetWidth(pb);+ size_t h = CVPixelBufferGetHeight(pb);+ size_t bpr = CVPixelBufferGetBytesPerRow(pb);+ OSType fmt = CVPixelBufferGetPixelFormatType(pb);+ vcc_log(@" [SyntheticHandler] pb=%p w=%zu h=%zu bpr=%zu fmt=0x%x",+ pb, w, h, bpr, (unsigned)fmt);+ // Write the raw BGRA bytes beside the shared camera frame for verification.+ const char *out_path = VPHONE_VCAM_SYNTH_PHOTO_PATH;+ uint8_t *base = (uint8_t *)CVPixelBufferGetBaseAddress(pb);+ if (base) {+ int fd = open(out_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);+ if (fd >= 0) {+ for (size_t y = 0; y < h; y++) {+ (void)write(fd, base + y * bpr, w * 4);+ }+ close(fd);+ vcc_log(@" [SyntheticHandler] wrote %s (%zu bytes)",+ out_path, w * h * 4);+ } else {+ vcc_log(@" [SyntheticHandler] open(%s) failed: %d", out_path, errno);+ }+ }+ CVPixelBufferUnlockBaseAddress(pb, kCVPixelBufferLock_ReadOnly);+ };+ @try {+ ((void (*)(id, SEL, id))objc_msgSend)(vcc_synth_still_sink,+ setHandlerSel, block);+ vcc_log(@" manual still-sink: installed synthetic handler block");+ } @catch (NSException *e) {+ vcc_log(@" manual still-sink: setHandler exception: %@", e);+ }+ // Verify the handler was stored+ @try {+ id stored = ((id (*)(id, SEL))objc_msgSend)(+ vcc_synth_still_sink, @selector(sampleBufferAvailableHandler));+ vcc_log(@" manual still-sink: post-set sampleBufferAvailableHandler=%p",+ stored);+ } @catch (NSException *e) {+ vcc_log(@" manual still-sink: getHandler exception: %@", e);+ }+ } else {+ vcc_log(@" manual still-sink: doesn't respond to setSampleBufferAvailableHandler:");+ }+}++// Trigger-the-handler probe: call -renderSampleBuffer:forInput: on our+// synth sink directly with a synthetic CMSampleBuffer built from+// vcc_latest_frame. If our manually-installed handler fires, we have+// proven the synthetic-handler approach works at the API level.+static void vcc_drive_still_sink_once(void) {+ if (!vcc_synth_still_sink) return;+ CMSampleBufferRef sbuf = vcc_build_cmsb_from_shm();+ if (!sbuf) {+ vcc_log(@" still-drive: no shm frame yet");+ return;+ }+ SEL renderSel = @selector(renderSampleBuffer:forInput:);+ if (![vcc_synth_still_sink respondsToSelector:renderSel]) {+ vcc_log(@" still-drive: sink doesn't respond to renderSampleBuffer:forInput:");+ CFRelease(sbuf);+ return;+ }+ vcc_log(@" still-drive: calling renderSampleBuffer: on sink %p with sbuf=%p",+ vcc_synth_still_sink, sbuf);+ @try {+ ((void (*)(id, SEL, CMSampleBufferRef, id))objc_msgSend)(+ vcc_synth_still_sink, renderSel, sbuf, nil);+ vcc_log(@" still-drive: render call returned");+ } @catch (NSException *e) {+ vcc_log(@" still-drive: render exception: %@", e);+ }+ CFRelease(sbuf);+}++// MARK: - FigCaptureSessionParsedConfiguration observation+//+// This is the daemon-side parser that converts the XPC session config into+// the structured configuration the graph builder uses. After init,+// _parsedStillImageSinkConfigurations is populated; if empty, no still+// pipeline will be built.++static IMP vcc_parsed_cfg_init_orig = NULL;+typedef id (*VccParsedCfgInitFn)(id self,+ SEL _cmd,+ id sessionCfg,+ BOOL clientSetsUserInitiated,+ id restrictions);++__attribute__((ns_returns_retained))+static id vcc_parsed_cfg_init_hook(id self,+ SEL _cmd,+ id sessionCfg,+ BOOL clientSetsUserInitiated,+ id restrictions) {+ VccParsedCfgInitFn orig = (VccParsedCfgInitFn)vcc_parsed_cfg_init_orig;+ id ret = orig(self, _cmd, sessionCfg, clientSetsUserInitiated, restrictions);+ if (ret) {+ id stillCfgs = nil;+ @try {+ stillCfgs = [ret valueForKey:@"parsedStillImageSinkConfigurations"];+ } @catch (NSException *e) {+ stillCfgs = nil;+ }+ id cameraCfgs = nil;+ @try {+ cameraCfgs = [ret valueForKey:@"parsedCameraSourceConfigurations"];+ } @catch (NSException *e) {+ cameraCfgs = nil;+ }+ vcc_log(@" [ParsedCfg init] -> %p stillCfgs.count=%lu cameraCfgs.count=%lu",+ ret,+ (unsigned long)(stillCfgs && [stillCfgs respondsToSelector:@selector(count)]+ ? [stillCfgs count] : 0),+ (unsigned long)(cameraCfgs && [cameraCfgs respondsToSelector:@selector(count)]+ ? [cameraCfgs count] : 0));+ if (cameraCfgs && [cameraCfgs respondsToSelector:@selector(count)]+ && [cameraCfgs count] > 0) {+ vcc_log(@" [ParsedCfg] cameraCfgs[0] class=%@",+ NSStringFromClass([[cameraCfgs firstObject] class]));+ }+ if (stillCfgs && [stillCfgs respondsToSelector:@selector(count)]+ && [stillCfgs count] > 0) {+ id stillCfg = [stillCfgs firstObject];+ vcc_log(@" [ParsedCfg] stillCfgs[0] class=%@ desc=%@",+ NSStringFromClass([stillCfg class]), stillCfg);+ // Dump the still cfg's properties — what does it tell the graph builder?+ id connConfigs = nil, primaryConnConfig = nil, movieCfg = nil, pointCfg = nil;+ @try { connConfigs = [stillCfg valueForKey:@"stillImageConnectionConfigurations"]; } @catch (NSException *e) {}+ @try {+ primaryConnConfig = [stillCfg valueForKey:@"primaryStillImageConnectionConfiguration"];+ } @catch (NSException *e) {}+ @try { movieCfg = [stillCfg valueForKey:@"movieFileVideoConnectionConfiguration"]; } @catch (NSException *e) {}+ @try { pointCfg = [stillCfg valueForKey:@"pointCloudDataConnectionConfiguration"]; } @catch (NSException *e) {}+ vcc_log(@" [ParsedCfg] stillCfgs[0].connCfgs=%@",+ connConfigs ?: @"(nil)");+ vcc_log(@" [ParsedCfg] stillCfgs[0].primary=%@", primaryConnConfig ?: @"(nil)");+ // Also dump the camera source config to see what source it's bound to+ id cameraCfg = [cameraCfgs firstObject];+ id sourceID = nil, deviceType = nil, captureDeviceID = nil;+ @try { sourceID = [cameraCfg valueForKey:@"sourceID"]; } @catch (NSException *e) {}+ @try { deviceType = [cameraCfg valueForKey:@"sourceDeviceType"]; } @catch (NSException *e) {}+ @try { captureDeviceID = [cameraCfg valueForKey:@"captureDeviceID"]; } @catch (NSException *e) {}+ vcc_log(@" [ParsedCfg] cameraCfg sourceID=%@ deviceType=%@ captureDeviceID=%@",+ sourceID ?: @"(nil)", deviceType ?: @"(nil)",+ captureDeviceID ?: @"(nil)");+ }+ }+ return ret;+}++static void vcc_install_parsed_cfg_observation(void) {+ Class cls = NSClassFromString(@"FigCaptureSessionParsedConfiguration");+ if (!cls) {+ vcc_log(@" parsed-cfg obs: class missing");+ return;+ }+ SEL sel = NSSelectorFromString(+ @"initWithSessionConfiguration:clientSetsUserInitiatedCaptureRequestTime:restrictions:");+ vcc_swizzle_method(cls, sel, (IMP)vcc_parsed_cfg_init_hook,+ &vcc_parsed_cfg_init_orig);+}diff --git a/VPhoneGuestComponents/VCamCaptured/VCamSyntheticDevice.inc b/VPhoneGuestComponents/VCamCaptured/VCamSyntheticDevice.incnew file mode 100644index 00000000..833c8b94--- /dev/null+++ b/VPhoneGuestComponents/VCamCaptured/VCamSyntheticDevice.inc@@ -0,0 +1,178 @@+// MARK: - synthetic FigCaptureDevice subclass+//+// Subclass `BWFigCaptureDevice` at runtime via objc_allocateClassPair, then+// instantiate via +alloc. We write the deviceID NSString directly into the+// inherited ivar slot. Ivar offsets are resolved at synth-class init time+// via the ObjC runtime (class_getInstanceVariable + ivar_getOffset) so+// the layout follows whatever Apple ships, not a hardcoded 26.5 value.+//+// To prevent the crash in+// `-[BWFigCaptureDevice _copyProperty:requireSupported:error:]` (where the+// inherited body would deref the NULL figCaptureDevice via+// CMBaseObjectGetVTable), we OVERRIDE the public ObjC wrappers+// (-copyProperty:error:, -getProperty:error:, -copyPropertyIfSupported:error:)+// in our subclass so they never call _copyProperty:. Each override returns+// canned values for known properties and sets *err=-12787 ("property not+// supported") for everything else.++// Resolved at synth-class init. -1 until populated; vcc_init_synth_device_class+// refuses to register the synth class if resolution fails so we never write+// to a stale offset.+static ptrdiff_t kBWFigCaptureDevice_deviceID_Offset = -1;++// Resolve an instance-variable offset by name on `cls`, trying each+// candidate in `names` (NULL-terminated) until one matches. Returns -1+// if none match. Logs the outcome so a future iOS rename surfaces in+// the install log instead of silently writing to a wrong slot.+static ptrdiff_t vcc_resolve_ivar(Class cls,+ const char *what,+ const char *const *names) {+ if (!cls) {+ vcc_log(@" ivar %s: class missing", what ? what : "?");+ return -1;+ }+ for (unsigned i = 0; names[i]; i++) {+ Ivar iv = class_getInstanceVariable(cls, names[i]);+ if (iv) {+ ptrdiff_t off = ivar_getOffset(iv);+ vcc_log(@" ivar %s -> %s @ +0x%lx", what ? what : "?",+ names[i], (long)off);+ return off;+ }+ }+ vcc_log(@" ivar %s: no candidate matched on %s", what ? what : "?",+ class_getName(cls));+ return -1;+}++// Cached CF constant — resolved lazily from CMCaptureCore / CMCaptureDevice.+static CFStringRef vcc_cf_kClock = NULL;++static void vcc_load_synth_cfconsts(void) {+ if (!vcc_cf_kClock) vcc_cf_kClock = vcc_cfconst("kFigCaptureDeviceProperty_Clock");+}++// Returns a CMClockRef (CoreMedia host time clock). Lifetime tied to the+// process — we never release it.+static CFTypeRef vcc_get_host_clock(void) {+ static CFTypeRef cached = NULL;+ if (cached) return cached;+ typedef CFTypeRef (*GetHostClockFn)(void);+ GetHostClockFn fn = (GetHostClockFn)dlsym(RTLD_DEFAULT, "CMClockGetHostTimeClock");+ if (!fn) {+ vcc_log(@" synth-dev: CMClockGetHostTimeClock missing");+ return NULL;+ }+ cached = fn();+ if (cached) CFRetain(cached); // keep it alive+ return cached;+}++// copyProperty: follows the +1 "copy" convention — return must be retained.+__attribute__((ns_returns_retained))+static id vcc_synth_copy_property(id self, SEL _cmd, id property, int *err) {+ NSString *propStr = [property description];+ if (vcc_cf_kClock &&+ [(__bridge id)vcc_cf_kClock isEqual:property]) {+ CFTypeRef clk = vcc_get_host_clock();+ if (err) *err = clk ? 0 : -12787;+ vcc_log(@" [SynthDev copyProperty:Clock] -> %p", clk);+ if (!clk) return nil;+ CFRetain(clk);+ return (__bridge_transfer id)clk; // +1 retained, ns_returns_retained+ }+ if (err) *err = -12787;+ vcc_log(@" [SynthDev copyProperty:%@] -> nil (err=-12787)", propStr);+ return nil;+}++__attribute__((ns_returns_retained))+static id vcc_synth_copy_property_if_supported(id self,+ SEL _cmd,+ id property,+ int *err) {+ NSString *propStr = [property description];+ if (err) *err = 0;+ vcc_log(@" [SynthDev copyPropertyIfSupported:%@] -> nil", propStr);+ return nil;+}++static int vcc_synth_get_property(id self, SEL _cmd, id property, int *err) {+ NSString *propStr = [property description];+ if (err) *err = -12787;+ vcc_log(@" [SynthDev getProperty:%@] -> 0 (err=-12787)", propStr);+ return 0;+}++static id vcc_synth_supported_properties(id self, SEL _cmd) {+ // BWFigVideoCaptureDevice expects an NSDictionary here — it queries the+ // returned object via -objectForKeyedSubscript: for property keys (e.g.+ // kFigCaptureDeviceProperty_SupportedSynchronizedStreamsGroups). Returning+ // an NSSet would crash on that selector.+ vcc_log(@" [SynthDev supportedProperties] -> empty dict");+ return [NSDictionary dictionary];+}++static id vcc_synth_unique_id(id self, SEL _cmd) {+ void **slot = (void **)((char *)(__bridge void *)self+ + kBWFigCaptureDevice_deviceID_Offset);+ id idVal = (__bridge id)(*slot);+ return idVal;+}++static void vcc_synth_dealloc(id self, SEL _cmd) {+ void **slot = (void **)((char *)(__bridge void *)self+ + kBWFigCaptureDevice_deviceID_Offset);+ if (*slot) {+ CFRelease((CFTypeRef)*slot);+ *slot = NULL;+ }+ // Skip parent's -dealloc and finish destruction ourselves. ARC marks+ // objc_destructInstance as unavailable, so resolve via dlsym.+ static void *(*destruct)(id) = NULL;+ if (!destruct) destruct = dlsym(RTLD_DEFAULT, "objc_destructInstance");+ if (destruct) destruct(self);+ free((__bridge void *)self);+}++static void vcc_init_synth_device_class(void) {+ if (vcc_synth_device_class) return;+ Class parent = NSClassFromString(@"BWFigCaptureDevice");+ if (!parent) {+ vcc_log(@" synth-dev: BWFigCaptureDevice class missing");+ return;+ }+ static const char *const kDeviceIDNames[] = {+ "_deviceID", "deviceID", NULL,+ };+ kBWFigCaptureDevice_deviceID_Offset = vcc_resolve_ivar(+ parent, "BWFigCaptureDevice.deviceID", kDeviceIDNames);+ if (kBWFigCaptureDevice_deviceID_Offset < 0) {+ vcc_log(@" synth-dev: required ivar not found — registration aborted");+ return;+ }+ vcc_load_synth_cfconsts();++ Class cls = objc_allocateClassPair(parent, "VccSynthDevice", 0);+ if (!cls) {+ vcc_log(@" synth-dev: objc_allocateClassPair failed");+ return;+ }++ class_addMethod(cls, @selector(copyProperty:error:),+ (IMP)vcc_synth_copy_property, "@@:@^i");+ class_addMethod(cls, @selector(copyPropertyIfSupported:error:),+ (IMP)vcc_synth_copy_property_if_supported, "@@:@^i");+ class_addMethod(cls, @selector(getProperty:error:),+ (IMP)vcc_synth_get_property, "i@:@^i");+ class_addMethod(cls, @selector(supportedProperties),+ (IMP)vcc_synth_supported_properties, "@@:");+ class_addMethod(cls, @selector(uniqueID),+ (IMP)vcc_synth_unique_id, "@@:");+ class_addMethod(cls, NSSelectorFromString(@"dealloc"),+ (IMP)vcc_synth_dealloc, "v@:");++ objc_registerClassPair(cls);+ vcc_synth_device_class = cls;+ vcc_log(@" registered VccSynthDevice : BWFigCaptureDevice (cls=%p)", cls);+}diff --git a/VPhoneGuestComponents/VCamCaptured/VCamSyntheticStreams.inc b/VPhoneGuestComponents/VCamCaptured/VCamSyntheticStreams.incnew file mode 100644index 00000000..e09b0923--- /dev/null+++ b/VPhoneGuestComponents/VCamCaptured/VCamSyntheticStreams.inc@@ -0,0 +1,372 @@+// MARK: - synthetic FigCaptureStream subclass+//+// Subclass BWFigCaptureStream. Ivar offsets are resolved at synth-class+// init time via the ObjC runtime so the layout follows whatever Apple+// ships. Historical disasm of -[BWFigCaptureStream initWith…] and the+// trivial ivar accessors gave us the slot semantics:+//+// figCaptureStream : C handle, leave NULL+// portType : NSString+// uniqueID : NSString+// isSpecialDeviceID : BOOL (we don't touch it)+// property cache : NSDictionary — DO NOT write a non-dict here.+// Earlier iteration put a deviceID string in the slot; the+// inherited -_copyProperty: calls [cache+// objectForKeyedSubscript:key] unconditionally, and the+// unrecognized-selector crashed cameracaptured. Leave NULL+// so the lookup short-circuits to nil.+// streaming : BOOL — set to 1 so -streaming returns YES.++static Class vcc_synth_stream_class = Nil;+// Resolved at synth-class init. portType/uniqueID are required (-1 -> abort+// class registration); streaming is optional (-1 -> skip the YES poke).+static ptrdiff_t kBWFigCaptureStream_portType_Offset = -1;+static ptrdiff_t kBWFigCaptureStream_uniqueID_Offset = -1;+static ptrdiff_t kBWFigCaptureStream_streaming_Offset = -1;++static CFStringRef vcc_cf_kSupportedFormatsArray = NULL;++__attribute__((ns_returns_retained))+static id vcc_synth_stream_copy_property(id self,+ SEL _cmd,+ id property,+ int *err) {+ if (!vcc_cf_kSupportedFormatsArray) {+ vcc_cf_kSupportedFormatsArray =+ vcc_cfconst("kFigCaptureStreamProperty_SupportedFormatsArray");+ }+ if (vcc_cf_kSupportedFormatsArray &&+ [(__bridge id)vcc_cf_kSupportedFormatsArray isEqual:property]) {+ if (err) *err = 0;+ // Empirically: empty SupportedFormatsArray returns +1-retained per+ // ns_returns_retained convention. Non-empty arrays (objects or dicts)+ // trip a daemon-side validation that we don't satisfy → isRunning=0.+ // The AVCaptureDevice.formats list is populated separately via+ // -[FigCaptureSourceBacking initWith…formats:…], so the AVF client+ // still sees both formats and selects activeFormat.+ vcc_log(@" [SynthStream copyProperty:SupportedFormatsArray] -> empty array");+ return [[NSArray alloc] init];+ }+ if (err) *err = -12787;+ vcc_log(@" [SynthStream copyProperty:%@] -> nil (err=-12787)",+ [property description]);+ return nil;+}++__attribute__((ns_returns_retained))+static id vcc_synth_stream_copy_property_if_supported(id self,+ SEL _cmd,+ id property,+ int *err) {+ if (err) *err = 0;+ vcc_log(@" [SynthStream copyPropertyIfSupported:%@] -> nil",+ [property description]);+ return nil;+}++static int vcc_synth_stream_get_property(id self,+ SEL _cmd,+ id property,+ int *err) {+ NSString *propStr = [property description];+ // The daemon's session-start path queries PixelSize on the stream and+ // treats err=-12787 as fatal — propagates up to AVCaptureSessionRuntimeError+ // and stops the session. Return 0 with err=0 (supported, zero value) so+ // the check passes. Same defensive default for any other property we+ // haven't otherwise explicitly handled.+ if (err) *err = 0;+ vcc_log(@" [SynthStream getProperty:%@] -> 0 err=0", propStr);+ return 0;+}++static int vcc_synth_stream_get_property_if_supported(id self,+ SEL _cmd,+ id property,+ int *err) {+ if (err) *err = 0;+ vcc_log(@" [SynthStream getPropertyIfSupported:%@] -> 0 err=0",+ [property description]);+ return 0;+}++// Catches the private _copyProperty:requireSupported:error: path. Same+// effective result as -copyProperty:error: (canned values for known+// keys, -12787 otherwise) — just a 3rd BOOL arg.+static id vcc_synth_stream_underscore_copy_property(id self,+ SEL _cmd,+ id property,+ BOOL requireSupported,+ int *err) {+ return vcc_synth_stream_copy_property(self, @selector(copyProperty:error:),+ property, err);+}++static id vcc_synth_stream_supported_properties(id self, SEL _cmd) {+ return [NSDictionary dictionary];+}++static int vcc_synth_stream_set_property(id self,+ SEL _cmd,+ id property,+ id value) {+ vcc_log(@" [SynthStream setProperty:%@] (ignored)", [property description]);+ return 0;+}++static void vcc_synth_stream_dealloc(id self, SEL _cmd) {+ void *p = (__bridge void *)self;+ void **portTypeSlot = (void **)((char *)p + kBWFigCaptureStream_portType_Offset);+ void **uniqueIDSlot = (void **)((char *)p + kBWFigCaptureStream_uniqueID_Offset);+ if (*portTypeSlot) { CFRelease(*portTypeSlot); *portTypeSlot = NULL; }+ if (*uniqueIDSlot) { CFRelease(*uniqueIDSlot); *uniqueIDSlot = NULL; }+ // Skip parent's -dealloc (would touch many uninitialized ivars). Manually+ // destruct + free the storage. ARC blocks direct objc_destructInstance,+ // so resolve via dlsym.+ static void *(*destruct)(id) = NULL;+ if (!destruct) destruct = dlsym(RTLD_DEFAULT, "objc_destructInstance");+ if (destruct) destruct(self);+ free((__bridge void *)self);+}++static void vcc_init_synth_stream_class(void) {+ if (vcc_synth_stream_class) return;+ Class parent = NSClassFromString(@"BWFigCaptureStream");+ if (!parent) {+ vcc_log(@" synth-stream: BWFigCaptureStream class missing");+ return;+ }+ static const char *const kPortTypeNames[] = {"_portType", "portType", NULL};+ static const char *const kUniqueIDNames[] = {"_uniqueID", "uniqueID", NULL};+ static const char *const kStreamingNames[] = {+ "_streaming", "streaming", "_isStreaming", "isStreaming", NULL,+ };+ kBWFigCaptureStream_portType_Offset = vcc_resolve_ivar(+ parent, "BWFigCaptureStream.portType", kPortTypeNames);+ kBWFigCaptureStream_uniqueID_Offset = vcc_resolve_ivar(+ parent, "BWFigCaptureStream.uniqueID", kUniqueIDNames);+ kBWFigCaptureStream_streaming_Offset = vcc_resolve_ivar(+ parent, "BWFigCaptureStream.streaming", kStreamingNames);+ if (kBWFigCaptureStream_portType_Offset < 0 ||+ kBWFigCaptureStream_uniqueID_Offset < 0) {+ vcc_log(@" synth-stream: required ivar(s) not found — registration aborted");+ return;+ }+ Class cls = objc_allocateClassPair(parent, "VccSynthStream", 0);+ if (!cls) {+ vcc_log(@" synth-stream: objc_allocateClassPair failed");+ return;+ }+ class_addMethod(cls, @selector(copyProperty:error:),+ (IMP)vcc_synth_stream_copy_property, "@@:@^i");+ class_addMethod(cls, @selector(copyPropertyIfSupported:error:),+ (IMP)vcc_synth_stream_copy_property_if_supported, "@@:@^i");+ class_addMethod(cls, @selector(getProperty:error:),+ (IMP)vcc_synth_stream_get_property, "i@:@^i");+ class_addMethod(cls, @selector(getPropertyIfSupported:error:),+ (IMP)vcc_synth_stream_get_property_if_supported, "i@:@^i");+ // Also override the underlying _copyProperty:requireSupported:error:+ // so any inherited call path that bypasses the public wrappers (e.g.+ // -getPropertyIfSupported: in older code paths) still lands here+ // instead of crashing on the NULL figCaptureStream vtable deref.+ class_addMethod(cls,+ NSSelectorFromString(@"_copyProperty:requireSupported:error:"),+ (IMP)vcc_synth_stream_underscore_copy_property, "@@:@B^i");+ class_addMethod(cls, @selector(supportedProperties),+ (IMP)vcc_synth_stream_supported_properties, "@@:");+ class_addMethod(cls, @selector(setProperty:value:),+ (IMP)vcc_synth_stream_set_property, "i@:@@");+ class_addMethod(cls, NSSelectorFromString(@"dealloc"),+ (IMP)vcc_synth_stream_dealloc, "v@:");+ objc_registerClassPair(cls);+ vcc_synth_stream_class = cls;+ vcc_log(@" registered VccSynthStream : BWFigCaptureStream (cls=%p)", cls);+}++// Strong references to every manufactured synth stream, so they can't be+// released early by autorelease churn or refcount bugs in our dealloc.+// Memory grows by one stream per session start; acceptable for diagnosis.+static NSMutableArray *vcc_synth_streams_strong_refs = nil;++__attribute__((ns_returns_retained))+static id vcc_make_synth_stream(NSString *uniqueID,+ NSString *deviceID,+ NSString *portType) {+ if (!vcc_synth_stream_class) vcc_init_synth_stream_class();+ if (!vcc_synth_stream_class) return nil;+ // Use +alloc via runtime — ARC-safe (class_createInstance is+ // OBJC_ARC_UNAVAILABLE and the retain-count semantics don't match what+ // ARC expects). Function attributed ns_returns_retained so callers+ // treat the +1 from alloc correctly without autorelease.+ id s = ((id (*)(Class, SEL))objc_msgSend)(vcc_synth_stream_class,+ @selector(alloc));+ if (!s) return nil;++ void *p = (__bridge void *)s;+ *(void **)((char *)p + kBWFigCaptureStream_portType_Offset) =+ (void *)CFBridgingRetain([portType copy]);+ *(void **)((char *)p + kBWFigCaptureStream_uniqueID_Offset) =+ (void *)CFBridgingRetain([uniqueID copy]);+ // property-cache NSDictionary ivar intentionally left NULL — the+ // parent class unconditionally sends -objectForKeyedSubscript: to it,+ // and an earlier iteration that stored deviceID there crashed with+ // unrecognized-selector. The deviceID isn't read off the stream by+ // inherited code anyway (only a per-stream BOOL comparison result is).+ (void)deviceID;+ // streaming BOOL — set to 1 so -streaming returns YES. Optional:+ // skip if the ivar isn't present on this build.+ if (kBWFigCaptureStream_streaming_Offset >= 0) {+ *(uint8_t *)((char *)p + kBWFigCaptureStream_streaming_Offset) = 1;+ }++ // Pin so dealloc never runs — diagnostic to isolate the autorelease-+ // pool-drain crash. Each session start leaks one stream.+ if (!vcc_synth_streams_strong_refs) {+ vcc_synth_streams_strong_refs = [NSMutableArray new];+ }+ [vcc_synth_streams_strong_refs addObject:s];++ vcc_log(@" synth-stream: %p uid=%@ port=%@ devID=%@",+ s, uniqueID, portType, deviceID);+ return s;+}++// MARK: - hook BWFigCaptureDeviceVendor copyStreamsWithUniqueIDs:forDevice:+//+// When forDevice is our synth, manufacture one VccSynthStream per requested+// uniqueID so that the vendor's identity-matching inner loop in+// `-_copyStreamsForAttributes:` produces a result array whose count matches+// the input attributes count.++static IMP vcc_copy_streams_orig = NULL;+typedef id (*VccCopyStreamsFn)(id self,+ SEL _cmd,+ NSArray *uniqueIDs,+ id forDevice,+ int priority,+ int *err);++static id vcc_copy_streams_hook(id self,+ SEL _cmd,+ NSArray *uniqueIDs,+ id forDevice,+ int priority,+ int *err) {+ if (forDevice && object_getClass(forDevice) == vcc_synth_device_class) {+ vcc_log(@" [copyStreamsWithUniqueIDs forDevice:synth] ids=%@", uniqueIDs);+ NSMutableArray *out = [NSMutableArray array];+ void *p = (__bridge void *)forDevice;+ NSString *devID = (__bridge NSString *)(*(void **)((char *)p + kBWFigCaptureDevice_deviceID_Offset));+ for (NSString *uid in uniqueIDs) {+ id s = vcc_make_synth_stream(uid, devID, @"Back");+ if (s) [out addObject:s];+ }+ if (err) *err = 0;+ vcc_log(@" [copyStreamsWithUniqueIDs] -> %lu streams",+ (unsigned long)out.count);+ return out;+ }+ VccCopyStreamsFn orig = (VccCopyStreamsFn)vcc_copy_streams_orig;+ return orig(self, _cmd, uniqueIDs, forDevice, priority, err);+}++static void vcc_install_copy_streams_hook(void) {+ Class cls = NSClassFromString(@"BWFigCaptureDeviceVendor");+ if (!cls) return;+ SEL sel = NSSelectorFromString(+ @"copyStreamsWithUniqueIDs:forDevice:deviceClientPriority:error:");+ vcc_swizzle_method(cls, sel, (IMP)vcc_copy_streams_hook, &vcc_copy_streams_orig);+}++static IMP vcc_copy_streams_from_orig = NULL;+typedef id (*VccCopyStreamsFromFn)(id self,+ SEL _cmd,+ id fromDevice,+ NSArray *positions,+ NSArray *deviceTypes,+ int prio,+ BOOL allowsLoss,+ int *err);++static id vcc_copy_streams_from_hook(id self,+ SEL _cmd,+ id fromDevice,+ NSArray *positions,+ NSArray *deviceTypes,+ int prio,+ BOOL allowsLoss,+ int *err) {+ if (fromDevice && object_getClass(fromDevice) == vcc_synth_device_class) {+ vcc_log(@" [copyStreamsFromDevice:synth positions=%@ deviceTypes=%@]",+ positions, deviceTypes);+ NSMutableArray *out = [NSMutableArray array];+ void *p = (__bridge void *)fromDevice;+ NSString *devID = (__bridge NSString *)(*(void **)((char *)p + kBWFigCaptureDevice_deviceID_Offset));+ NSUInteger count = positions.count;+ for (NSUInteger i = 0; i < count; i++) {+ NSString *uid = [NSString stringWithFormat:@"%@:stream:%lu",+ devID, (unsigned long)i];+ id s = vcc_make_synth_stream(uid, devID, @"Back");+ if (s) [out addObject:s];+ }+ if (err) *err = 0;+ vcc_log(@" [copyStreamsFromDevice] -> %lu streams",+ (unsigned long)out.count);+ return out;+ }+ VccCopyStreamsFromFn orig = (VccCopyStreamsFromFn)vcc_copy_streams_from_orig;+ return orig(self, _cmd, fromDevice, positions, deviceTypes,+ prio, allowsLoss, err);+}++static void vcc_install_copy_streams_from_hook(void) {+ Class cls = NSClassFromString(@"BWFigCaptureDeviceVendor");+ if (!cls) return;+ SEL sel = NSSelectorFromString(+ @"copyStreamsFromDevice:positions:deviceTypes:deviceClientPriority:allowsStreamControlLoss:error:");+ vcc_swizzle_method(cls, sel, (IMP)vcc_copy_streams_from_hook,+ &vcc_copy_streams_from_orig);+}++__attribute__((ns_returns_retained))+static id vcc_make_synth_device(NSString *deviceID) {+ if (!vcc_synth_device_class) vcc_init_synth_device_class();+ if (!vcc_synth_device_class) return nil;++ // Use +alloc via runtime — ARC-safe. Function attributed+ // ns_returns_retained so ARC treats the alloc'd +1 correctly.+ id d = ((id (*)(Class, SEL))objc_msgSend)(vcc_synth_device_class,+ @selector(alloc));+ if (!d) {+ vcc_log(@" synth-dev: class_createInstance failed");+ return nil;+ }+ // Write deviceID at the runtime-resolved ivar offset via+ // CFBridgingRetain so our -dealloc override CFRelease's it.+ NSString *idCopy = [deviceID copy];+ void *slotBase = (__bridge void *)d;+ void **slot = (void **)((char *)slotBase + kBWFigCaptureDevice_deviceID_Offset);+ *slot = (void *)CFBridgingRetain(idCopy);++ // Pin so dealloc never runs — diagnostic to isolate the autorelease+ // pool drain crash. Each session start leaks one synth device.+ static NSMutableArray *vcc_synth_devs_strong_refs = nil;+ if (!vcc_synth_devs_strong_refs) {+ vcc_synth_devs_strong_refs = [NSMutableArray new];+ }+ [vcc_synth_devs_strong_refs addObject:d];++ vcc_log(@" synth-dev: %p deviceID=%@ (slot@+0x%lx=%p)",+ d, idCopy, (long)kBWFigCaptureDevice_deviceID_Offset, *slot);+ return d;+}++static void vcc_install_device_vendor_hook(void) {+ Class cls = NSClassFromString(@"BWFigCaptureDeviceVendor");+ if (!cls) {+ vcc_log(@" device-vendor hook: class missing");+ return;+ }+ SEL sel = NSSelectorFromString(+ @"copyDeviceWithID:forClient:informClientWhenDeviceAvailableAgain:error:");+ vcc_swizzle_method(cls, sel, (IMP)vcc_copy_device_hook, &vcc_copy_device_orig);+}diff --git a/VPhoneGuestComponents/VCamCaptured/VCamViewfinderHooks.inc b/VPhoneGuestComponents/VCamCaptured/VCamViewfinderHooks.incnew file mode 100644index 00000000..0892cba5--- /dev/null+++ b/VPhoneGuestComponents/VCamCaptured/VCamViewfinderHooks.inc@@ -0,0 +1,213 @@+// MARK: - viewfinder stream injection+//+// Camera.app's preview path goes through FigCameraViewfinderStream, NOT+// BWImageQueueSinkNode. The stream exposes -enqueueVideoSampleBuffer: which+// the daemon's normal frame producer calls to deliver each frame to the+// client (Camera.app's AVCaptureVideoPreviewLayer). For our synth source —+// which has no real producer — we hook -[FigCameraViewfinderStream init],+// capture each instance, and drive enqueueVideoSampleBuffer: ourselves on+// a 30 Hz timer, wrapping vcc_latest_frame pixels in a fresh CMSampleBuffer.++// Forward declaration — full definition is later in the file under the+// "shared-frame reader" section.+typedef struct vcc_latest_frame_s {+ pthread_mutex_t lock;+ uint32_t width;+ uint32_t height;+ uint32_t bytes_per_row;+ uint8_t *pixels;+ size_t pixels_capacity;+ size_t pixels_length;+} vcc_latest_frame_t;+extern vcc_latest_frame_t vcc_latest_frame;++// CVPixelBuffer release callback for the malloc'd pixel buffer. Has to be+// a real C function (block isn't compatible with the callback signature).+static void vcc_cv_release_bytes(void *refcon, const void *baseAddress) {+ (void)refcon;+ free((void *)baseAddress);+}++static IMP vcc_vfs_init_orig = NULL;+static IMP vcc_vfs_open_orig = NULL;+static IMP vcc_vfs_close_orig = NULL;+static NSMutableArray *vcc_vf_streams = nil; // strong refs+static dispatch_source_t vcc_vf_timer = NULL;+static dispatch_queue_t vcc_vf_q = NULL;+static uint64_t vcc_vf_pts_ns = 0;+static uint64_t vcc_vf_enqueue_count = 0;+static uint64_t vcc_vf_enqueue_success = 0;++typedef id (*VccVfsInitFn)(id self, SEL _cmd);+typedef void (*VccVfsOpenFn)(id self, SEL _cmd, id dest);+typedef void (*VccVfsCloseFn)(id self, SEL _cmd);++static _Atomic uint64_t vcc_vfs_init_count = 0;++static id vcc_vfs_init_hook(id self, SEL _cmd) {+ VccVfsInitFn orig = (VccVfsInitFn)vcc_vfs_init_orig;+ id ret = orig(self, _cmd);+ // Throttled — Camera.app spins ~2000 inits/sec without ever opening+ // (session config silently incomplete). Log every 1024th to keep the log+ // file usable.+ uint64_t n = atomic_fetch_add(&vcc_vfs_init_count, 1) + 1;+ if ((n & 0x3ff) == 1) {+ vcc_log(@" [VFS init] -> %p (total=%llu)",+ ret, (unsigned long long)n);+ }+ return ret;+}++static void vcc_vfs_open_hook(id self, SEL _cmd, id dest) {+ vcc_log(@" [VFS open] self=%p dest=%@", self, dest);+ VccVfsOpenFn orig = (VccVfsOpenFn)vcc_vfs_open_orig;+ orig(self, _cmd, dest);+ if (!vcc_vf_streams) vcc_vf_streams = [NSMutableArray array];+ [vcc_vf_streams addObject:self];+ vcc_log(@" [VFS open] captured stream %p (total=%lu)",+ self, (unsigned long)vcc_vf_streams.count);+}++static void vcc_vfs_close_hook(id self, SEL _cmd) {+ vcc_log(@" [VFS close] self=%p", self);+ if (vcc_vf_streams) [vcc_vf_streams removeObject:self];+ VccVfsCloseFn orig = (VccVfsCloseFn)vcc_vfs_close_orig;+ orig(self, _cmd);+}++// Build a CMSampleBuffer wrapping the latest shm frame. Caller must+// CFRelease the result.+static CMSampleBufferRef vcc_build_cmsb_from_shm(void) {+ pthread_mutex_lock(&vcc_latest_frame.lock);+ uint32_t w = vcc_latest_frame.width;+ uint32_t h = vcc_latest_frame.height;+ uint32_t bpr = vcc_latest_frame.bytes_per_row;+ size_t len = vcc_latest_frame.pixels_length;+ if (!len || !w || !h || !bpr) {+ pthread_mutex_unlock(&vcc_latest_frame.lock);+ return NULL;+ }+ void *pixels = malloc(len);+ if (!pixels) {+ pthread_mutex_unlock(&vcc_latest_frame.lock);+ return NULL;+ }+ memcpy(pixels, vcc_latest_frame.pixels, len);+ pthread_mutex_unlock(&vcc_latest_frame.lock);++ CVPixelBufferRef pb = NULL;+ CVReturn cvr = CVPixelBufferCreateWithBytes(+ kCFAllocatorDefault, w, h, kCVPixelFormatType_32BGRA,+ pixels, bpr, vcc_cv_release_bytes, NULL, NULL, &pb);+ if (cvr != kCVReturnSuccess || !pb) {+ free(pixels);+ return NULL;+ }++ CMVideoFormatDescriptionRef desc = NULL;+ OSStatus s = CMVideoFormatDescriptionCreateForImageBuffer(+ kCFAllocatorDefault, pb, &desc);+ if (s != noErr || !desc) {+ CVPixelBufferRelease(pb);+ return NULL;+ }++ // Monotonic PTS at 30 fps. The viewfinder's internal jitter buffer+ // discards frames whose PTS doesn't advance, so we increment per call.+ vcc_vf_pts_ns += 33333333ull; // 1/30s in nanoseconds+ CMSampleTimingInfo timing = {+ .duration = CMTimeMake(1, 30),+ .presentationTimeStamp = CMTimeMake((int64_t)vcc_vf_pts_ns, 1000000000),+ .decodeTimeStamp = kCMTimeInvalid,+ };++ CMSampleBufferRef cmsb = NULL;+ s = CMSampleBufferCreateForImageBuffer(+ kCFAllocatorDefault, pb, true, NULL, NULL, desc, &timing, &cmsb);+ CFRelease(desc);+ CVPixelBufferRelease(pb);+ if (s != noErr || !cmsb) return NULL;+ return cmsb;+}++static void vcc_vf_drive_once(void) {+ if (!vcc_vf_streams || vcc_vf_streams.count == 0) return;+ CMSampleBufferRef cmsb = vcc_build_cmsb_from_shm();+ if (!cmsb) return;+ SEL sel = NSSelectorFromString(@"enqueueVideoSampleBuffer:");+ for (id stream in [vcc_vf_streams copy]) {+ int ret = ((int (*)(id, SEL, CMSampleBufferRef))objc_msgSend)(+ stream, sel, cmsb);+ vcc_vf_enqueue_count++;+ if (ret == 0) vcc_vf_enqueue_success++;+ if ((vcc_vf_enqueue_count & 29) == 1) {+ vcc_log(@" [VFS drive] enqueue ret=%d (count=%llu ok=%llu)",+ ret,+ (unsigned long long)vcc_vf_enqueue_count,+ (unsigned long long)vcc_vf_enqueue_success);+ }+ }+ CFRelease(cmsb);+}++static void vcc_install_viewfinder_hooks(void) {+ Class cls = NSClassFromString(@"FigCameraViewfinderStream");+ if (!cls) {+ vcc_log(@" VF hook: class missing");+ return;+ }+ SEL init_sel = NSSelectorFromString(@"init");+ SEL open_sel = NSSelectorFromString(@"openWithDestination:");+ SEL close_sel = NSSelectorFromString(@"close");+ Method m;+ if ((m = class_getInstanceMethod(cls, init_sel))) {+ vcc_vfs_init_orig = method_setImplementation(m, (IMP)vcc_vfs_init_hook);+ }+ if ((m = class_getInstanceMethod(cls, open_sel))) {+ vcc_vfs_open_orig = method_setImplementation(m, (IMP)vcc_vfs_open_hook);+ }+ if ((m = class_getInstanceMethod(cls, close_sel))) {+ vcc_vfs_close_orig = method_setImplementation(m, (IMP)vcc_vfs_close_hook);+ }+ vcc_log(@" swizzled FigCameraViewfinderStream init/open/close");++ // Drive at 30 Hz. Frames are enqueued only when at least one stream is+ // open AND a fresh shm frame exists (covered by build_cmsb_from_shm).+ vcc_vf_q = dispatch_queue_create("com.vphone.vcam.vfdrive",+ DISPATCH_QUEUE_SERIAL);+ vcc_vf_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,+ vcc_vf_q);+ dispatch_source_set_timer(vcc_vf_timer,+ dispatch_time(DISPATCH_TIME_NOW, 0),+ 33333333ull, 2000000ull);+ dispatch_source_set_event_handler(vcc_vf_timer, ^{+ @autoreleasepool { vcc_vf_drive_once(); }+ });+ dispatch_resume(vcc_vf_timer);+ vcc_log(@" viewfinder drive timer armed (30 Hz)");+}++static void vcc_install_sink_observation(void) {+ Class iqsn = NSClassFromString(@"BWImageQueueSinkNode");+ Class rqsn = NSClassFromString(@"BWRemoteQueueSinkNode");+ if (!iqsn || !rqsn) {+ vcc_log(@" sink obs: classes missing iqsn=%p rqsn=%p", iqsn, rqsn);+ return;+ }++ SEL iqsnInit = NSSelectorFromString(+ @"initWithHFRSupport:ispJitterCompensationEnabled:"+ @"clientAuditToken:sinkID:");+ SEL rqsnInit = NSSelectorFromString(+ @"initWithMediaType:clientAuditToken:sinkID:cameraInfoByPortType:");+ SEL renderSel = @selector(renderSampleBuffer:forInput:);++ vcc_swizzle_method(iqsn, iqsnInit, (IMP)vcc_iqsn_init_hook,+ &vcc_iqsn_init_orig);+ vcc_swizzle_method(rqsn, rqsnInit, (IMP)vcc_rqsn_init_hook,+ &vcc_rqsn_init_orig);+ vcc_swizzle_method(iqsn, renderSel, (IMP)vcc_iqsn_render_hook,+ &vcc_iqsn_render_orig);+ vcc_swizzle_method(rqsn, renderSel, (IMP)vcc_rqsn_render_hook,+ &vcc_rqsn_render_orig);+}diff --git a/VPhoneGuestComponents/VCamCaptured/libvcamcaptured.m b/VPhoneGuestComponents/VCamCaptured/libvcamcaptured.mindex 945bb994..9671878c 100644--- a/VPhoneGuestComponents/VCamCaptured/libvcamcaptured.m+++ b/VPhoneGuestComponents/VCamCaptured/libvcamcaptured.m@@ -1,8 +1,8 @@/** libvcamcaptured — synthetic camera source injection in cameracaptured.*- * Loaded into `/usr/libexec/cameracaptured` via the systemhook ->- * TweakLoader chain (TweakLoader.m's `kVPhoneAllowedDaemonPaths`).+ * Optional hook for `/usr/libexec/cameracaptured`. Building the guest+ * component does not install or inject it; a process loader is required.** Strategy (iOS 26.x):* 1. AVF clients query `+[AVCaptureDevice devicesWithMediaType:]`.@@ -61,6 +61,7 @@#include <sys/stat.h>#include <sys/types.h>#include <unistd.h>+#include "VCamFrameProtocol.h"// MARK: - shared frame layout (matches vphoned_vcam.h)//@@ -70,32 +71,8 @@// file read-only, subscribe to the notification, and copy out the latest// frame on each fire.-#define VCC_SHM_PATH \- "/var/jb/var/mobile/Library/vphone-vcam-frame.shm"-#define VCC_NOTIFY_NAME "com.vphone.vcam.frame"-#define VCC_SHM_HEADER_SIZE 64-#define VCC_SHM_MAX_PIXELS (8 * 1024 * 1024)-#define VCC_SHM_TOTAL_SIZE \- (VCC_SHM_HEADER_SIZE + VCC_SHM_MAX_PIXELS)--typedef struct __attribute__((packed)) {- uint64_t seq;- uint32_t width;- uint32_t height;- uint32_t bytes_per_row;- uint32_t pixel_format;- uint32_t _reserved;- uint64_t timestamp_ns;- uint64_t frame_index;- uint32_t pixels_length;- uint32_t _pad;-} vcc_shm_header_t;-// MARK: - sentinel logging-static NSString *const kSentinelPath =- @"/var/jb/var/mobile/Library/vcamcaptured.log";-static void vcc_log(NSString *fmt, ...) {va_list args;va_start(args, fmt);@@ -109,10 +86,7 @@ static void vcc_log(NSString *fmt, ...) {msg];NSData *data = [line dataUsingEncoding:NSUTF8StringEncoding];if (!data.length) return;- int fd = open(- kSentinelPath.fileSystemRepresentation,- O_WRONLY | O_CREAT | O_APPEND,- 0644);+ int fd = open(VPHONE_VCAM_CAPTURE_LOG_PATH, O_WRONLY | O_CREAT | O_APPEND, 0644);if (fd >= 0) {(void)write(fd, data.bytes, data.length);close(fd);@@ -120,3160 +94,19 @@ static void vcc_log(NSString *fmt, ...) {NSLog(@"vcamcaptured: %@", msg);}-// MARK: - runtime image resolution--#define VCC_MAX_DATA_RANGES 8--typedef struct {- uintptr_t start;- uintptr_t end;-} vcc_range_t;--typedef struct {- const struct mach_header_64 *mh;- intptr_t slide;- const uint32_t *text;- size_t text_words; // count of 4-byte instructions- vcc_range_t data_ranges[VCC_MAX_DATA_RANGES];- unsigned data_range_count;- // LC_SYMTAB pointers (may be 0 on DSC dylibs that strip private symbols- // from the per-image symtab; callers must handle gracefully).- const struct nlist_64 *symtab;- const char *strtab;- uint32_t nsyms;-} vcc_image_t;--static int vcc_image_resolve(vcc_image_t *out, const char *anchor_sym) {- memset(out, 0, sizeof(*out));- void *anchor = dlsym(RTLD_DEFAULT, anchor_sym);- if (!anchor) return -1;- void *stripped = ptrauth_strip(anchor, ptrauth_key_function_pointer);- Dl_info info;- if (!dladdr(stripped, &info) || !info.dli_fbase) return -2;- const struct mach_header_64 *mh =- (const struct mach_header_64 *)info.dli_fbase;- if (mh->magic != MH_MAGIC_64) return -3;- out->mh = mh;-- uint32_t cnt = _dyld_image_count();- for (uint32_t i = 0; i < cnt; i++) {- if (_dyld_get_image_header(i) == (const struct mach_header *)mh) {- out->slide = _dyld_get_image_vmaddr_slide(i);- break;- }- }-- unsigned long sz = 0;- uint8_t *text =- getsectiondata((struct mach_header_64 *)mh, "__TEXT", "__text", &sz);- if (!text || sz < 8) return -4;- out->text = (const uint32_t *)text;- out->text_words = sz / 4;-- // Capture bounds of every writable segment so the structural scan can- // reject candidate targets that don't fall within a data segment.- // Also stash the LC_SYMTAB pointers for later private-symbol lookups.- const struct load_command *lc = (const struct load_command *)(mh + 1);- const struct segment_command_64 *linkedit = NULL;- const struct symtab_command *symtab_cmd = NULL;- for (uint32_t i = 0; i < mh->ncmds; i++) {- if (lc->cmd == LC_SEGMENT_64) {- const struct segment_command_64 *seg =- (const struct segment_command_64 *)lc;- if (strcmp(seg->segname, "__LINKEDIT") == 0) {- linkedit = seg;- }- // Skip __TEXT, __LINKEDIT — only consider writable/data segments.- // segname comparisons are sufficient; __PAGEZERO has vmaddr 0 anyway.- if (strcmp(seg->segname, "__TEXT") != 0 &&- strcmp(seg->segname, "__LINKEDIT") != 0 &&- strcmp(seg->segname, "__PAGEZERO") != 0 &&- seg->vmsize > 0 &&- out->data_range_count < VCC_MAX_DATA_RANGES) {- uintptr_t start = (uintptr_t)seg->vmaddr + out->slide;- out->data_ranges[out->data_range_count++] = (vcc_range_t){- start, start + (uintptr_t)seg->vmsize};- }- } else if (lc->cmd == LC_SYMTAB) {- symtab_cmd = (const struct symtab_command *)lc;- }- lc = (const struct load_command *)((const char *)lc + lc->cmdsize);- }- if (out->data_range_count == 0) return -5;-- // LC_SYMTAB pointers — file-offsets in the symtab_cmd are relative to the- // DSC file layout; runtime addresses are recovered via the __LINKEDIT- // segment's (vmaddr+slide) - fileoff base.- if (symtab_cmd && linkedit && linkedit->fileoff <= symtab_cmd->symoff) {- uintptr_t linkedit_base = (uintptr_t)linkedit->vmaddr + out->slide -- (uintptr_t)linkedit->fileoff;- out->symtab = (const struct nlist_64 *)(linkedit_base +- (uintptr_t)symtab_cmd->symoff);- out->strtab = (const char *)(linkedit_base + (uintptr_t)symtab_cmd->stroff);- out->nsyms = symtab_cmd->nsyms;- }- return 0;-}--// Walk CMCapture's LC_SYMTAB for `name`. Returns slid VMA on match, or 0.-// On DSC dylibs the per-image symtab may be stripped of private symbols, in-// which case this returns 0 even for symbols that exist statically.-static uintptr_t vcc_lookup_lc_symtab(const vcc_image_t *img,- const char *name) {- if (!img->symtab || !img->strtab || img->nsyms == 0) return 0;- for (uint32_t i = 0; i < img->nsyms; i++) {- if (img->symtab[i].n_un.n_strx == 0) continue;- const char *nm = img->strtab + img->symtab[i].n_un.n_strx;- if (strcmp(nm, name) == 0) {- uintptr_t val = (uintptr_t)img->symtab[i].n_value;- if (val == 0) continue;- return val + img->slide;- }- }- return 0;-}--// Decode ARM64 BL imm26 -> absolute branch target.-static uintptr_t vcc_bl_target(uintptr_t bl_pc, uint32_t bl) {- int64_t imm = (int64_t)(bl & 0x03FFFFFFu) << 6; // place 26 bits in top- imm >>= 4; // shift right 4 (sign-ext + *4)- return bl_pc + (uintptr_t)imm;-}--// Scan __text for the per-source ownership filter inside-// _captureSourceServer_handleCopySourcesMessage. The compiler emits:-//-// bl <objc_msgSend$boolValue> ; w0 = [prewarmingEnabledRet boolValue]-// mov x25, x0 ; 0xAA0003F9-// ldr x2, [sp, #<imm>] ; F9400000 | (imm12<<10) | (31<<5) | 2-// ; — copy of bundleID outparam; offset-// ; is compiler-chosen, so mask it off-// mov x0, x22 ; 0xAA1603E0 — clientSI string-// bl <objc_msgSend$isEqualToString:>; w0 = [clientSI isEqualToString:bundleID]-// cbz w0, SKIP ; (insn & 0xFF00001F) == 0x34000000 → patch-// cbz w25, SKIP ; (insn & 0xFF00001F) == 0x34000019 → patch-//-// Both cbz branch targets are identical (same SKIP label). We patch both-// to NOP so every source survives the per-client ownership + prewarming--// enabled filter and reaches the response serializer.-static uintptr_t vcc_find_per_source_filter(const vcc_image_t *img) {- if (!img->text || img->text_words < 6) return 0;- for (size_t i = 0; i + 5 < img->text_words; i++) {- if (img->text[i] != 0xAA0003F9u) continue; // mov x25, x0- // ldr x2, [sp, #?] — any sp-relative 64-bit load into x2. The stack- // offset is a compiler-chosen frame slot and shifts between builds.- if ((img->text[i + 1] & 0xFFC003FFu) != 0xF94003E2u) continue;- if (img->text[i + 2] != 0xAA1603E0u) continue; // mov x0, x22- if ((img->text[i + 3] & 0xFC000000u) != 0x94000000u) // BL (don't care)- continue;- if ((img->text[i + 4] & 0xFF00001Fu) != 0x34000000u) // cbz w0, ?- continue;- if ((img->text[i + 5] & 0xFF00001Fu) != 0x34000019u) // cbz w25, ?- continue;- // Verify both cbz branch to the same target (same SKIP block).- // CBZ encoding: bits 23..5 = imm19 (19-bit signed instruction offset).- // Byte offset = sign_extend(imm19) * 4.- int32_t imm0 = (int32_t)((img->text[i + 4] >> 5) & 0x7FFFFu);- int32_t imm1 = (int32_t)((img->text[i + 5] >> 5) & 0x7FFFFu);- if (imm0 & 0x40000) imm0 |= 0xFFF80000;- if (imm1 & 0x40000) imm1 |= 0xFFF80000;- uintptr_t tgt0 = (uintptr_t)&img->text[i + 4] + (intptr_t)imm0 * 4;- uintptr_t tgt1 = (uintptr_t)&img->text[i + 5] + (intptr_t)imm1 * 4;- if (tgt0 != tgt1) continue;- return (uintptr_t)&img->text[i + 4];- }- return 0;-}--// Patch two consecutive instructions starting at `pc` to NOP. iOS __TEXT-// is W^X-enforced + TXM-validated. Try in order:-// (a) vm_protect with VM_PROT_COPY: kernel COWs the page into an anon-// mapping and grants RW. Standard iOS-hooker recipe (libhooker etc).-// (b) vm_allocate scratch + memcpy + vm_remap(OVERWRITE|FIXED) overlay.-// Either way, scratch_writable -> patch -> set RX -> icache flush.-static int vcc_patch_two_nops(uintptr_t pc) {- uintptr_t page_size = (uintptr_t)getpagesize();- uintptr_t page_start = pc & ~(page_size - 1);- uintptr_t end = pc + 8;- uintptr_t page_end =- ((end + page_size - 1) & ~(page_size - 1));- vm_size_t span = (vm_size_t)(page_end - page_start);- mach_port_t self_task = mach_task_self();-- // (a) vm_protect with VM_PROT_COPY (= 0x10) to force COW.- kern_return_t kr = vm_protect(- self_task,- (vm_address_t)page_start,- span,- FALSE,- VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY);- if (kr == KERN_SUCCESS) {- uint32_t nop = 0xD503201Fu;- ((uint32_t *)pc)[0] = nop;- ((uint32_t *)pc)[1] = nop;- kr = vm_protect(- self_task,- (vm_address_t)page_start,- span,- FALSE,- VM_PROT_READ | VM_PROT_EXECUTE);- if (kr == KERN_SUCCESS) {- sys_icache_invalidate((void *)pc, 8);- vcc_log(@" vm_protect+COPY patch OK @ 0x%lx",- (unsigned long)pc);- return 1;- }- vcc_log(@" vm_protect restore RX failed: %d (page=0x%lx)",- kr,- (unsigned long)page_start);- // Continue to try (b).- } else {- vcc_log(@" vm_protect+COPY failed: %d", kr);- }-- // (b) Scratch allocation + vm_remap with FIXED|OVERWRITE.- vm_address_t scratch = 0;- kr = vm_allocate(self_task, &scratch, span, VM_FLAGS_ANYWHERE);- if (kr != KERN_SUCCESS) {- vcc_log(@" vm_allocate failed: %d", kr);- return 0;- }- memcpy((void *)scratch, (const void *)page_start, span);- uint32_t nop = 0xD503201Fu;- uintptr_t scratch_pc = scratch + (pc - page_start);- ((uint32_t *)scratch_pc)[0] = nop;- ((uint32_t *)scratch_pc)[1] = nop;- kr = vm_protect(- self_task,- scratch,- span,- FALSE,- VM_PROT_READ | VM_PROT_EXECUTE);- if (kr != KERN_SUCCESS) {- vcc_log(@" vm_protect RX scratch failed: %d", kr);- vm_deallocate(self_task, scratch, span);- return 0;- }- vm_address_t target = (vm_address_t)page_start;- vm_prot_t cur_prot = 0, max_prot = 0;- kr = vm_remap(- self_task,- &target,- span,- 0,- VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE,- self_task,- scratch,- FALSE,- &cur_prot,- &max_prot,- VM_INHERIT_NONE);- if (kr != KERN_SUCCESS) {- vcc_log(@" vm_remap FIXED|OVERWRITE failed: %d (cur=0x%x max=0x%x)",- kr,- cur_prot,- max_prot);- vm_deallocate(self_task, scratch, span);- return 0;- }- sys_icache_invalidate((void *)pc, 8);- vcc_log(@" vm_remap OK: page=0x%lx span=%zu (cur=0x%x max=0x%x)",- (unsigned long)page_start,- (size_t)span,- cur_prot,- max_prot);- return 1;-}--// Patch a single 32-bit ARM64 instruction word at `pc` to `new_word`.-// Uses the same vm_protect(VM_PROT_COPY) → write → vm_protect(RX) →-// icache flush dance as vcc_patch_two_nops. Verifies the original word-// matches `expected_word` before writing so an iOS version skew doesn't-// silently corrupt the wrong code. Returns 1 on success.-static int vcc_patch_word(uintptr_t pc,- uint32_t expected_word,- uint32_t new_word) {- uint32_t cur = ((const uint32_t *)pc)[0];- if (cur != expected_word) {- vcc_log(@" patch_word @ 0x%lx: expected 0x%08x, found 0x%08x — skip",- (unsigned long)pc,- expected_word,- cur);- return 0;- }- uintptr_t page_size = (uintptr_t)getpagesize();- uintptr_t page_start = pc & ~(page_size - 1);- uintptr_t end = pc + 4;- uintptr_t page_end = ((end + page_size - 1) & ~(page_size - 1));- vm_size_t span = (vm_size_t)(page_end - page_start);- mach_port_t self_task = mach_task_self();-- kern_return_t kr = vm_protect(- self_task,- (vm_address_t)page_start,- span,- FALSE,- VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY);- if (kr != KERN_SUCCESS) {- vcc_log(@" patch_word vm_protect+COPY failed: %d", kr);- return 0;- }- ((uint32_t *)pc)[0] = new_word;- kr = vm_protect(- self_task,- (vm_address_t)page_start,- span,- FALSE,- VM_PROT_READ | VM_PROT_EXECUTE);- if (kr != KERN_SUCCESS) {- vcc_log(@" patch_word restore RX failed: %d", kr);- return 0;- }- sys_icache_invalidate((void *)pc, 4);- vcc_log(@" patch_word OK @ 0x%lx: 0x%08x -> 0x%08x",- (unsigned long)pc,- expected_word,- new_word);- return 1;-}--// Scan the image's __text for every occurrence of `needle` and rewrite-// each to `replacement` via vcc_patch_word. Replaces hardcoded image-// VMAs for patches whose addresses we don't know per-build but whose-// instruction encoding is a stable fingerprint (e.g. `mov w20, #-12783`-// MOVN encodings used for error-prep). Returns the count patched.-static unsigned vcc_scan_and_patch(const vcc_image_t *img,- uint32_t needle,- uint32_t replacement,- const char *what) {- if (!img->text || !img->text_words) return 0;- unsigned hits = 0;- for (size_t i = 0; i < img->text_words; i++) {- if (img->text[i] != needle) continue;- uintptr_t pc = (uintptr_t)&img->text[i];- if (vcc_patch_word(pc, needle, replacement)) hits++;- }- vcc_log(@" scan_and_patch %s (0x%08x -> 0x%08x): %u hit(s)",- what ? what : "?",- needle,- replacement,- hits);- return hits;-}--// Scan __text for the daemon's client-allowlist filter sequence:-// bl <FigCaptureCopyClientCodeSigningIdentifier> ; X-// bl <objc_autorelease_stub> ; (don't care about target)-// mov x22, x0 ; 0xAA0003F6-// bl <FigCaptureGetSupportedPrewarmingBundleIds> ; Y-// cbz x22, ... ; (insn & 0xFF00001F) == 0xB4000016-// mov x2, x22 ; 0xAA1603E2-// bl <objc_msgSend$containsObject:> ; (don't care)-// cbz w0, ... ; (insn & 0xFF00001F) == 0x34000000-//-// On a hit, writes the absolute (slid) target of the 1st and 4th BL into-// `*si_fn_out` and `*prewarm_fn_out`. Returns the PC of the first BL.-static uintptr_t vcc_find_filter_chain(const vcc_image_t *img,- uintptr_t *si_fn_out,- uintptr_t *prewarm_fn_out) {- if (!img->text || img->text_words < 8) return 0;- *si_fn_out = 0;- *prewarm_fn_out = 0;-- for (size_t i = 0; i + 7 < img->text_words; i++) {- uint32_t bl1 = img->text[i];- if ((bl1 & 0xFC000000u) != 0x94000000u) continue; // BL-- uint32_t bl2 = img->text[i + 1];- if ((bl2 & 0xFC000000u) != 0x94000000u) continue; // BL-- uint32_t mov_x22 = img->text[i + 2];- if (mov_x22 != 0xAA0003F6u) continue; // mov x22, x0-- uint32_t bl3 = img->text[i + 3];- if ((bl3 & 0xFC000000u) != 0x94000000u) continue; // BL-- uint32_t cbz_x22 = img->text[i + 4];- if ((cbz_x22 & 0xFF00001Fu) != 0xB4000016u) continue; // cbz x22, ...-- uint32_t mov_x2 = img->text[i + 5];- if (mov_x2 != 0xAA1603E2u) continue; // mov x2, x22-- uint32_t bl4 = img->text[i + 6];- if ((bl4 & 0xFC000000u) != 0x94000000u) continue; // BL-- uint32_t cbz_w0 = img->text[i + 7];- if ((cbz_w0 & 0xFF00001Fu) != 0x34000000u) continue; // cbz w0, ...-- uintptr_t bl1_pc = (uintptr_t)&img->text[i];- uintptr_t bl3_pc = (uintptr_t)&img->text[i + 3];- *si_fn_out = vcc_bl_target(bl1_pc, bl1);- *prewarm_fn_out = vcc_bl_target(bl3_pc, bl3);- return bl1_pc;- }- return 0;-}--static int vcc_addr_in_data(const vcc_image_t *img, uintptr_t addr) {- for (unsigned i = 0; i < img->data_range_count; i++) {- if (addr >= img->data_ranges[i].start &&- addr < img->data_ranges[i].end) return 1;- }- return 0;-}--// Decode ARM64 ADRP immediate from the instruction word.-// Returns the absolute page-aligned target of `adrp Xn, <page>`.-static uintptr_t vcc_adrp_target(uintptr_t adrp_pc, uint32_t adrp) {- int64_t immlo = (adrp >> 29) & 0x3;- int64_t immhi = (adrp >> 5) & 0x7ffff;- int64_t imm = (immhi << 2) | immlo;- if (imm & (1LL << 20)) imm |= ~((1LL << 21) - 1);- return (adrp_pc & ~(uintptr_t)0xfffULL) + (uintptr_t)(imm << 12);-}--// Find a global by scanning __text for `adrp Xn, page; ldr Xm, [Xn, #offset]`.-// Tallies hits per resolved target address; accepts only candidates that-// fall inside one of CMCapture's writable data segments. Returns the-// most-hit candidate, or 0 if no candidate qualifies / there is a tie.-//-// `offset` is the byte offset within the page (must be a multiple of 8).-static uintptr_t vcc_find_data_xref(const vcc_image_t *img, unsigned offset) {- if (!img->text || !img->text_words) return 0;- if ((offset & 7) || offset > 0x7FF8) return 0;- uint32_t scaled_imm = (offset / 8) & 0xfff;-- enum { MAX_CANDS = 16 };- struct { uintptr_t addr; unsigned hits; } cands[MAX_CANDS];- unsigned n_cands = 0;-- for (size_t i = 1; i < img->text_words; i++) {- uint32_t ldr = img->text[i];- // 64-bit LDR (immediate, unsigned offset): bits 31..22 = 1111100101- if ((ldr & 0xFFC00000u) != 0xF9400000u) continue;- if (((ldr >> 10) & 0xfff) != scaled_imm) continue;- uint32_t rn = (ldr >> 5) & 0x1f;- uint32_t adrp = img->text[i - 1];- // ADRP: bits 31..24 fixed = 1xx10000 (mask 0x9F000000 == 0x90000000)- if ((adrp & 0x9F000000u) != 0x90000000u) continue;- if ((adrp & 0x1f) != rn) continue;- uintptr_t adrp_pc = (uintptr_t)&img->text[i - 1];- uintptr_t target = vcc_adrp_target(adrp_pc, adrp) + offset;- if (!vcc_addr_in_data(img, target)) continue;-- unsigned k;- for (k = 0; k < n_cands; k++) {- if (cands[k].addr == target) { cands[k].hits++; break; }- }- if (k == n_cands && n_cands < MAX_CANDS) {- cands[n_cands].addr = target;- cands[n_cands].hits = 1;- n_cands++;- }- }-- unsigned best = 0, best_hits = 0;- int tie = 0;- for (unsigned i = 0; i < n_cands; i++) {- if (cands[i].hits > best_hits) {- best_hits = cands[i].hits;- best = i;- tie = 0;- } else if (cands[i].hits == best_hits) {- tie = 1;- }- }- if (best_hits == 0) {- vcc_log(@" xref scan #%u: no in-data candidates", offset);- return 0;- }- if (tie) {- vcc_log(@" xref scan #%u: %u candidates tied at %u hits — refusing to pick",- offset,- n_cands,- best_hits);- return 0;- }- vcc_log(@" xref scan #%u: %u candidates, winner 0x%lx with %u hits",- offset,- n_cands,- (unsigned long)cands[best].addr,- best_hits);- return cands[best].addr;-}--// arm64e ISA class-pointer mask, per libobjc's objc-private.h:-// `#define ISA_MASK 0x00007ffffffffff8ULL`. Bits 0-2 are isa flags-// (has_assoc / has_cxx_dtor / is_indexed), bits 3-46 are the class-// pointer (44 bits), bits 47-63 are PAC + magic-signature bits.-#define VCC_ISA_CLASS_MASK 0x00007FFFFFFFFFF8ULL--// Returns YES if the value stored at `slot_addr` is a pointer to a-// heap-allocated CFArray instance. Uses malloc_zone_from_ptr to-// confirm the candidate pointer was returned by malloc (safe for any-// 64-bit value; never dereferences) before reading its isa. CFArray-// instances are always heap allocations from the default malloc zone,-// so a non-heap value can't be _sSourceList.-static BOOL vcc_slot_value_is_cfarray(uintptr_t slot_addr) {- if (!slot_addr) return NO;- // The slot addresses read here are always in CMCapture's __DATA /- // __DATA_CONST segments (filtered upstream by vcc_addr_in_data) so the read- // itself is safe — those pages are mapped read-something into the process.- uintptr_t val_ptr = *(uintptr_t *)slot_addr;- if (!val_ptr) return NO;- if (val_ptr < 0x100000000ULL || val_ptr > 0x800000000000ULL) return NO;- // malloc_zone_from_ptr returns NULL for non-malloc pointers — this- // is the safe pre-deref guard. CFArray instances are always heap-- // allocated, so any candidate whose slot value isn't heap-owned is- // definitionally not _sSourceList.- malloc_zone_t *zone = malloc_zone_from_ptr((const void *)val_ptr);- if (!zone) return NO;- // Now safe to dereference: the value is a confirmed heap allocation.- uintptr_t isa = *(uintptr_t *)val_ptr;- uintptr_t isa_class = isa & VCC_ISA_CLASS_MASK;- if (!isa_class) return NO;- static const char *array_classes[] = {- "__NSCFArray", "__NSArrayM", "__NSArrayI", "__NSArray0",- "__NSSingleObjectArrayI", "NSArray", "NSMutableArray",- "NSCFArray", NULL,- };- for (unsigned i = 0; array_classes[i]; i++) {- Class c = objc_getClass(array_classes[i]);- if (!c) continue;- uintptr_t c_class = ((uintptr_t)c) & VCC_ISA_CLASS_MASK;- if (isa_class == c_class) return YES;- }- return NO;-}--// Walk a function's body and collect every (BL <X> ; adrp + str x0,-// [Xn, #imm]) pair into `out_addrs`, returning the count. Useful for-// extracting the data-global init sequence of a static-init block —-// each pair represents one "store the result of a function call into-// a static global" site. The init block for CMCapture's source-list-// statics emits one such pair per global it initializes; the first-// one is `_sSourceList`.-static unsigned vcc_collect_call_then_store_globals(- uintptr_t func,- unsigned maxInsns,- unsigned lookahead,- uintptr_t *out_addrs,- unsigned cap) {- if (!func || !out_addrs || !cap) return 0;- func = (uintptr_t)ptrauth_strip((void *)func, ptrauth_key_function_pointer);- uint32_t *ip = (uint32_t *)func;- unsigned n = 0;- for (unsigned i = 0; i < maxInsns && n < cap; i++) {- uint32_t insn = ip[i];- if ((insn & 0xFC000000u) != 0x94000000u) continue; // BL- for (unsigned j = 1; j <= lookahead && i + j + 1 < maxInsns; j++) {- uint32_t adrp = ip[i + j];- if ((adrp & 0x9F000000u) != 0x90000000u) continue;- uint32_t rd_adrp = adrp & 0x1Fu;- uint32_t str = ip[i + j + 1];- if ((str & 0xFFC00000u) != 0xF9000000u) continue;- uint32_t rt = str & 0x1Fu;- uint32_t rn = (str >> 5) & 0x1Fu;- uint32_t off = ((str >> 10) & 0xFFFu) * 8;- if (rt != 0) continue;- if (rn != rd_adrp) continue;- uintptr_t adrp_pc = (uintptr_t)&ip[i + j];- uintptr_t target = vcc_adrp_target(adrp_pc, adrp) + off;- // Dedup- BOOL dup = NO;- for (unsigned k = 0; k < n; k++) {- if (out_addrs[k] == target) { dup = YES; break; }- }- if (!dup) out_addrs[n++] = target;- break;- }- }- return n;-}--// Resolve a CFString constant by symbol name.-static CFStringRef vcc_cfconst(const char *symname) {- void **slot = dlsym(RTLD_DEFAULT, symname);- if (!slot) {- vcc_log(@" dlsym FAIL: %s", symname);- return NULL;- }- return (CFStringRef)*slot;-}--// Resolve a function symbol by name. On arm64e dlsym returns a PAC-signed-// pointer signed with key IA + discriminator 0 (the standard C ABI signing-// schema) — callable directly as a C function pointer. Returns NULL on miss.-static void *vcc_dlsym_fn(const char *name) {- void *p = dlsym(RTLD_DEFAULT, name);- if (!p) vcc_log(@" dlsym FAIL: %s", name);- return p;-}--// MARK: - synthetic source construction--// Published as the synthetic source's CaptureDeviceID attribute, and matched-// against by the -[BWFigCaptureDeviceVendor copyDeviceWithID:…] hook. One-// declaration: the two must stay identical or the device lookup stops matching.-static NSString *const kVccSynthDeviceID = @"vphone:vcam:device:0";--static id vcc_build_backing(void) {- Class backingClass = NSClassFromString(@"FigCaptureSourceBacking");- if (!backingClass) {- vcc_log(@" FigCaptureSourceBacking class missing");- return nil;- }- CFStringRef k_uid = vcc_cfconst("kFigCaptureSourceAttributeKey_UniqueID");- CFStringRef k_dt = vcc_cfconst("kFigCaptureSourceAttributeKey_DeviceType");- CFStringRef k_ln = vcc_cfconst("kFigCaptureSourceAttributeKey_LocalizedName");- CFStringRef k_mid = vcc_cfconst("kFigCaptureSourceAttributeKey_ModelID");- CFStringRef k_pos = vcc_cfconst("kFigCaptureSourceAttributeKey_Position");- CFStringRef k_st = vcc_cfconst("kFigCaptureSourceAttributeKey_SourceType");- CFStringRef k_cdid = vcc_cfconst("kFigCaptureSourceAttributeKey_CaptureDeviceID");- if (!k_uid || !k_dt) {- vcc_log(@" required attr keys missing");- return nil;- }-- NSMutableDictionary *attrs = [NSMutableDictionary dictionary];- attrs[(__bridge NSString *)k_uid] = @"vphone:vcam:0";- // DeviceType: empirical sweep- // - 1 (BuiltInWideAngleCamera): Camera.app routes to the real ISP /- // hardware path and fails immediately because no hardware backs- // us — viewfinder stream pool isn't even spun up.- // - 2: Camera.app's Photo/Video tabs use the generic / soft path- // and at least start the FigCameraViewfinderStream init pool- // (~2000/sec) before stalling at openWithDestination:. This is- // where we have a chance to inject a destination.- // Keep 2 until the inject-destination shape is figured out.- attrs[(__bridge NSString *)k_dt] = @(2);- if (k_ln) attrs[(__bridge NSString *)k_ln] = @"vphone Virtual Camera";- if (k_mid) attrs[(__bridge NSString *)k_mid] = @"vphone-vcam-1";- if (k_pos) attrs[(__bridge NSString *)k_pos] = @(1);- // sourceType MUST be 1 (video) for the daemon's media-type filter to- // include this source in a vide-typed FigCaptureSourceRemoteCopyCaptureSources- // request. Without it, attrs[SourceType] = nil → intValue = 0 → fails- // the tbnz w8 gate in handleCopySourcesMessage.- if (k_st) attrs[(__bridge NSString *)k_st] = @(1);- // captureSession_buildGraphWithConfiguration (CMCapture vmaddr 0x1ae2b1910)- // iterates the source list and calls- // _FigCaptureSourceGetAttribute(source, kFigCaptureSourceAttributeKey_CaptureDeviceID)- // then -[NSMutableArray addObject:] with the result. If the key is missing- // the call returns nil and the array throws NSInvalidArgumentException- // ("object cannot be nil") inside -[__NSArrayM insertObject:atIndex:] —- // which kills cameracaptured as soon as any AVCaptureSession references- // our synth.- //- // The value must be a string, NOT a number. -[BWFigCaptureDeviceVendor- // _createDevice:reason:clientPID:figCaptureDevice:] sends isEqualToString:- // to it; an NSNumber raises "unrecognized selector". Use a unique opaque- // string outside whatever pattern Apple uses for hardware cameras.- if (k_cdid) attrs[(__bridge NSString *)k_cdid] = kVccSynthDeviceID;-- // After hooking _FigCaptureSourceGetAttribute via lldb we observed- // Camera.app's graph builder also queries these 5 boolean / scheme keys- // against our synth. Provide explicit values so the builder doesn't bail- // on a nil capability check. Verified order observed via lldb:- // SmartCameraSupported, StillImageNoiseReductionAndFusionScheme,- // MidFrameSynchronizationNotSupported, TimeOfFlightAssistedAutoFocusSupported,- // StructuredLightAssistedAutoFocusSupported- // Resolve the canonical CFString constant by symbol name when possible (some- // are defined in a private framework not in the dyld exports trie, so we fall- // back to the plain string after the Fig naming convention:- // kFigSupportedFormat_VideoMinFrameRate → "VideoMinFrameRate").- NSString *(^figKeyN)(const char *) = ^NSString *(const char *symname) {- void **slot = dlsym(RTLD_DEFAULT, symname);- if (slot && *slot) return (__bridge NSString *)(CFStringRef)(*slot);- const char *cs = symname;- const char *u = strrchr(cs, '_');- if (u) cs = u + 1;- return [NSString stringWithUTF8String:cs];- };- attrs[figKeyN("kFigCaptureSourceAttributeKey_SmartCameraSupported")] = @NO;- attrs[figKeyN("kFigCaptureSourceAttributeKey_StillImageNoiseReductionAndFusionScheme")] = @(0);- attrs[figKeyN("kFigCaptureSourceAttributeKey_MidFrameSynchronizationNotSupported")] = @NO;- attrs[figKeyN("kFigCaptureSourceAttributeKey_TimeOfFlightAssistedAutoFocusSupported")] = @NO;- attrs[figKeyN("kFigCaptureSourceAttributeKey_StructuredLightAssistedAutoFocusSupported")] = @NO;-- // Construct a FigCaptureSourceVideoFormat via its private init taking a- // stream format dictionary. Required keys recovered by reversing- // `-[FigCaptureSourceFormat formatDescription]` + `-format` + `-dimensions`:- // "Name" (NSString) -- required by base init's cbz guard- // "Width" (NSNumber) -- becomes dimensions.width- // "Height" (NSNumber) -- becomes dimensions.height- // "PixelFormatType" (NSNumber) -- 4cc fed to CMVideoFormatDescriptionCreate- // All other keys read by the subclass init fall through to default- // (0/nil) values via objectForKeyedSubscript: chains.- NSArray *formats = @[];- Class fmtClass = NSClassFromString(@"FigCaptureSourceVideoFormat");- if (fmtClass) {- // Publish TWO formats: one BGRA, one 420v at the same 1280x720- // dimensions. Clients that filter on BGRA (e.g. Loupe / Magnifier)- // see one; clients that pick the canonical ISP pixel format (AVF's- // _preferredFormatForPreset: matcher for AVCaptureSessionPresetHigh)- // pick the 420v one. Same preset list + frame-rate range on both.- NSDictionary *commonKeys = @{- @"DefaultActiveFormat" : @NO, // overridden on the active one- figKeyN("kFigSupportedFormat_VideoMinFrameRate") : @(1),- figKeyN("kFigSupportedFormat_VideoMaxFrameRate") : @(60),- // -[FigCaptureSourceVideoFormat maxZoomFactor] takes a fast path that- // returns 1.0 for raw bayer formats; for BGRA (our case) it falls to- // a fancy path that reads stabilizationTypeOverrideForCinematic / -ForStandard- // and consults a dimension-table when either equals 3. Setting this- // key to 3 makes the table apply (returns 16.0 for 1280-wide formats),- // which keeps -[AVCaptureFigVideoDevice setVideoZoomFactor:] from- // throwing "out-of-range [1, activeFormat.videoMaxZoomFactor]" when- // Camera.app sets a default zoom > 1.0.- @"VideoStabilizationTypeOverrideForStandard" : @(3),- // Without AVCaptureSessionPresets, -[AVCaptureDevice- // supportsAVCaptureSessionPreset:] returns NO for every preset- // (canAddInput=False everywhere except InputPriority). Camera.app- // uses High/Photo — list them all so common AVF clients pass.- @"AVCaptureSessionPresets" : @[- @"AVCaptureSessionPresetHigh",- @"AVCaptureSessionPreset1280x720",- @"AVCaptureSessionPreset640x480",- @"AVCaptureSessionPresetMedium",- @"AVCaptureSessionPresetLow",- @"AVCaptureSessionPresetPhoto",- @"AVCaptureSessionPreset352x288",- ],- };- NSMutableDictionary *bgra_fmt = [@{- @"Name" : @"vphone-vcam-720p-bgra",- @"Width" : @1280,- @"Height" : @720,- @"PixelFormatType" : @(0x42475241u), // 'BGRA'- } mutableCopy];- [bgra_fmt addEntriesFromDictionary:commonKeys];-- NSMutableDictionary *y420v_fmt = [@{- @"Name" : @"vphone-vcam-720p-420v",- @"Width" : @1280,- @"Height" : @720,- @"PixelFormatType" : @(0x34323076u), // '420v'- } mutableCopy];- [y420v_fmt addEntriesFromDictionary:commonKeys];- // Mark 420v as default — it's what AVF's preset matcher prefers when- // picking _setActiveFormat: under standard presets.- y420v_fmt[@"DefaultActiveFormat"] = @YES;-- SEL fmtInitSel = NSSelectorFromString(- @"initWithFigCaptureStreamFormatDictionary:");- NSMutableArray *formatObjs = [NSMutableArray array];- for (NSDictionary *fmtDict in @[ bgra_fmt, y420v_fmt ]) {- id fmtAlloc = ((id (*)(Class, SEL))objc_msgSend)(fmtClass,- @selector(alloc));- id fmtObj = nil;- if (fmtAlloc) {- fmtObj = ((id (*)(id, SEL, id))objc_msgSend)(- fmtAlloc,- fmtInitSel,- fmtDict);- }- vcc_log(@" FigCaptureSourceVideoFormat (%@) = %p",- fmtDict[@"Name"],- fmtObj);- if (fmtObj) [formatObjs addObject:fmtObj];- }- formats = formatObjs;- } else {- vcc_log(@" FigCaptureSourceVideoFormat class missing");- }-- SEL initSel = NSSelectorFromString(- @"initWithMediaType:attributes:cachedProperties:formats:"- @"missingFormatNames:synchronizedStreamUniqueIDs:"- @"unsynchronizedStreamUniqueIDs:");- id alloced = ((id (*)(Class, SEL))objc_msgSend)(backingClass,- @selector(alloc));- if (!alloced) return nil;- uint32_t mediaTypeVideo = 0x76696465; // 'vide'- id backing = ((id (*)(id, SEL, uint32_t, id, id, id, id, id, id))objc_msgSend)(- alloced,- initSel,- mediaTypeVideo,- attrs,- [NSMutableDictionary dictionary],- formats,- @[],- @[],- @[]);- vcc_log(@" backing = %p (attrs.count=%lu formats.count=%lu)",- backing,- (unsigned long)attrs.count,- (unsigned long)formats.count);- return backing;-}--// FigCaptureSourceCreateFromBacking signature (5 args):-// (CFAllocatorRef allocator, FigCaptureSourceBacking *backing,-// audit_token_t *token, int unused_x3, FigCaptureSource **outSource)-typedef int (*VCC_CreateFn)(CFAllocatorRef, id, void *, int, void **);--static void *vcc_create_synthetic_source(VCC_CreateFn create_fn, id backing) {- audit_token_t self_token;- mach_msg_type_number_t count = TASK_AUDIT_TOKEN_COUNT;- kern_return_t kr = task_info(mach_task_self(), TASK_AUDIT_TOKEN,- (task_info_t)&self_token, &count);- if (kr != KERN_SUCCESS) {- vcc_log(@" task_info(TASK_AUDIT_TOKEN) failed: %d", kr);- return NULL;- }-- void *outSource = NULL;- int ret = create_fn(kCFAllocatorDefault, backing, &self_token, 0, &outSource);- vcc_log(@" CreateFromBacking ret=0x%x outSource=%p", (unsigned)ret,- outSource);- return outSource;-}--// Walk the synthetic's PAC-signed vtable to call CopyProperty (vtable[6]) for-// confirmation of the contract methods. This is purely diagnostic; uses only-// dlsym-resolvable anchors (CMBaseObjectGetVTable) and standard PAC builtins.-static void vcc_probe_contract(void *source) {- void *(*CMBaseObjectGetVTable)(void *) =- (void *(*)(void *))vcc_dlsym_fn("CMBaseObjectGetVTable");- if (!CMBaseObjectGetVTable) return;- void *V = CMBaseObjectGetVTable(source);- vcc_log(@" CMBaseObjectGetVTable(synth) = %p", V);- if (!V) return;-- // Auth the vtable pointer (data key A, address-blended discriminator).- void **vtable_slot = (void **)((char *)V + 8);- void *real_vtable_signed = *vtable_slot;- uintptr_t vt_disc =- __builtin_ptrauth_blend_discriminator(vtable_slot, 47377);- void *real_vtable = __builtin_ptrauth_auth(real_vtable_signed,- ptrauth_key_asda, vt_disc);- vcc_log(@" real_vtable @ %p", real_vtable);-- // Auth method6 (instruction key A) then resign for the C ABI call.- void **method6_slot = (void **)((char *)real_vtable + 48);- void *method6_signed = *method6_slot;- uintptr_t m6_disc =- __builtin_ptrauth_blend_discriminator(method6_slot, 38693);- void *method6 = __builtin_ptrauth_auth_and_resign(- method6_signed, ptrauth_key_asia, m6_disc,- ptrauth_key_function_pointer, 0);- vcc_log(@" CopyProperty (vtable[6]) @ %p", method6);-- typedef int (*VCC_CopyPropFn)(void *src, CFStringRef key,- CFAllocatorRef alloc, CFTypeRef *out);- VCC_CopyPropFn copyProp = (VCC_CopyPropFn)method6;-- CFStringRef k_attrs = vcc_cfconst(- "kFigCaptureSourceProperty_AttributesDictionary");- CFStringRef k_fmts = vcc_cfconst("kFigCaptureSourceProperty_Formats");-- CFTypeRef outAttrs = NULL;- int e1 = copyProp(source, k_attrs, kCFAllocatorDefault, &outAttrs);- vcc_log(@" CopyProperty(AttributesDictionary) ret=%d out=%p (%@)",- e1, outAttrs, outAttrs);- if (outAttrs) CFRelease(outAttrs);-- CFTypeRef outFmts = NULL;- int e2 = copyProp(source, k_fmts, kCFAllocatorDefault, &outFmts);- vcc_log(@" CopyProperty(Formats) ret=%d out=%p (count=%ld)",- e2, outFmts,- outFmts && CFGetTypeID(outFmts) == CFArrayGetTypeID()- ? CFArrayGetCount(outFmts) : -1);- if (outFmts) CFRelease(outFmts);-}--// MARK: - _sSourceList manipulation--static void vcc_install_synthetic(void) {- vcc_image_t img;- int rc = vcc_image_resolve(&img, "FigCaptureSourceServerStart");- if (rc != 0) {- vcc_log(@" image resolve failed rc=%d", rc);- return;- }- vcc_log(@" CMCapture mh=%p slide=0x%lx text=%p words=%zu nsyms=%u",- img.mh, (unsigned long)img.slide, img.text, img.text_words,- img.nsyms);-- // DSC strips per-image LC_SYMTAB names to "<redacted>" — symtab walking- // by name doesn't work. Recover the two private function addresses via- // a structural pattern scan of __text for the daemon's filter chain.- uintptr_t si_fn_addr = 0, prewarm_fn_addr = 0;- uintptr_t hit_pc =- vcc_find_filter_chain(&img, &si_fn_addr, &prewarm_fn_addr);- vcc_log(@" filter-chain scan: pc=0x%lx si_fn=0x%lx prewarm_fn=0x%lx",- (unsigned long)hit_pc, (unsigned long)si_fn_addr,- (unsigned long)prewarm_fn_addr);-- // Patch the per-source ownership/prewarming filter that runs inside the- // iteration loop of handleCopySourcesMessage. Without these patches,- // every source is rejected unless its ClientBundleIdentifier property- // matches the requesting client's signing-id AND PrewarmingEnabled is- // YES — which is never true for our synthetic source nor for the daemon- // bring-up source against a non-Camera.app client.- uintptr_t per_source_pc = vcc_find_per_source_filter(&img);- if (per_source_pc) {- int ok = vcc_patch_two_nops(per_source_pc);- vcc_log(@" per-source NOP patch %s @ 0x%lx",- ok ? "OK" : "FAILED", (unsigned long)per_source_pc);- } else {- vcc_log(@" per-source filter not located — daemon will skip our source");- }-- if (prewarm_fn_addr) {- typedef CFTypeRef (*PrewarmFn)(void);- PrewarmFn pf = (PrewarmFn)ptrauth_sign_unauthenticated(- (void *)prewarm_fn_addr, ptrauth_key_function_pointer, 0);- CFTypeRef setv = pf();- vcc_log(@" prewarming allowlist set = %p (%@)",- setv, (__bridge id)setv);-- // Patch the daemon's prewarming-bundle allowlist so EVERY XPC client- // passes the `[set containsObject:clientSI]` gate in- // _captureSourceServer_handleCopySourcesMessage. We don't mutate the- // set's contents — we object_setClass it to a dynamically-built- // subclass whose -containsObject: implementation always returns YES.- // This is __DATA-clean (no __TEXT writes, no TXM concerns) and- // limited to this single singleton instance.- if (setv) {- id theSet = (__bridge id)setv;- Class origCls = object_getClass(theSet);- Class allowCls = objc_allocateClassPair(- origCls, "vcc_AlwaysAllowSet", 0);- if (allowCls) {- IMP yesImp = imp_implementationWithBlock(- ^BOOL(__unused id self_, __unused id obj) { return YES; });- Method orig = class_getInstanceMethod(origCls,- @selector(containsObject:));- const char *types = orig ? method_getTypeEncoding(orig) : "B@:@";- class_addMethod(allowCls, @selector(containsObject:), yesImp, types);- objc_registerClassPair(allowCls);- object_setClass(theSet, allowCls);- vcc_log(@" swizzled set's class -> vcc_AlwaysAllowSet (orig=%s)",- class_getName(origCls));- } else {- vcc_log(@" objc_allocateClassPair returned nil (already registered?)");- }- }- }--- // Force daemon's source-server init so `_sSourceList` is allocated.- void *start_fn = vcc_dlsym_fn("FigCaptureSourceServerStart");- if (start_fn) {- ((void (*)(void))start_fn)();- vcc_log(@" called FigCaptureSourceServerStart()");- }-- // Resolve _sSourceList structurally:- //- // LC_SYMTAB → __captureSourceServer_initializeStatics_block_invoke- // (the dispatch_once init body — static text symbol, retained- // in the on-device DSC nlist even when static *data* symbols- // like `_sSourceList` itself are stripped)- // → BL CFArrayCreateMutable inside the block body- // → adrp+str x0, [Xn, #imm] ← stores into _sSourceList- //- // Every link is a structural ARM64 pattern, so the chain is stable- // across iOS revisions. The static-init function naming convention- // (`<class>_initializeStatics_block_invoke`) has been used by Apple- // since the iOS 14 era and persists through 26.x.- uintptr_t fnCFArrayCreate = (uintptr_t)dlsym(RTLD_DEFAULT,- "CFArrayCreateMutable");- // The on-device nlist exports static text symbols with leading- // underscores. Block-invoke names take one extra underscore vs the- // outer C symbol — try the canonical first, plus a triple-_ variant- // some clangs emit.- static const char *kInitBlockNames[] = {- "__captureSourceServer_initializeStatics_block_invoke",- "___captureSourceServer_initializeStatics_block_invoke",- NULL,- };- uintptr_t blockInvoke = 0;- for (unsigned i = 0; kInitBlockNames[i]; i++) {- blockInvoke = vcc_lookup_lc_symtab(&img, kInitBlockNames[i]);- if (blockInvoke) {- vcc_log(@" init-statics block-invoke (%s) @ 0x%lx",- kInitBlockNames[i], (unsigned long)blockInvoke);- break;- }- }- // If the symbol is stripped on-device (typical for the DSC), walk- // the structural chain rooted at FigCaptureSourceServerStart to- // find the dispatch_once block-invoke. The chain is:- //- // FigCaptureSourceServerStart (exported, addr known)- // `cmn x?, #0x1 ; b.ne <wrapper>` (onceToken check)- // wrapper (`.cold.1`, static; addr from b.ne)- // `bl <cold.1>` (we land here from b.ne; target IS cold.1)- // cold.1 (5–6 instructions, static)- // `adrp x0,...; add x0, x0, ...` (onceToken pointer)- // `adrp x1,...; add x1, x1, ...` (block-constant pointer)- // `bl <dispatch_once stub>`- // block constant (struct __Block_literal in __DATA_CONST)- // +0x10 = invoke pointer (PAC-signed; raw bytes are the function- // address before signature stripping)- if (!blockInvoke) {- uintptr_t fnFigStart = (uintptr_t)dlsym(RTLD_DEFAULT,- "FigCaptureSourceServerStart");- if (fnFigStart) {- fnFigStart = (uintptr_t)ptrauth_strip((void *)fnFigStart,- ptrauth_key_function_pointer);- uint32_t *ip = (uint32_t *)fnFigStart;- uintptr_t coldWrapper = 0;- // Step 1: find `cmn x?, #0x1; b.ne <target>` and decode target.- // CMN (immediate) 64-bit, no shift:- // 1011 0001 00ii iiii iiii iinn nnn1 1111- // mask 0xFFC0001F, match 0xB100001F.- // B.NE: 0101 0100 iiii iiii iiii iiii iii0 0001- // mask 0xFF00001F, match 0x54000001.- for (unsigned i = 0; i < 256 && !coldWrapper; i++) {- uint32_t cmn = ip[i];- if ((cmn & 0xFFC0001Fu) != 0xB100001Fu) continue;- // imm12 in bits[21:10]- uint32_t imm = (cmn >> 10) & 0xFFFu;- if (imm != 1) continue;- if (i + 1 >= 256) continue;- uint32_t bne = ip[i + 1];- if ((bne & 0xFF00001Fu) != 0x54000001u) continue;- int32_t imm19 = (int32_t)((bne & 0x00FFFFE0u) << 8) >> 11;- coldWrapper = (uintptr_t)&ip[i + 1] + (intptr_t)imm19;- }- if (!coldWrapper) {- vcc_log(@" cmn+b.ne onceToken-check pattern not found in "- @"FigCaptureSourceServerStart");- } else {- vcc_log(@" cold-wrapper site @ 0x%lx", (unsigned long)coldWrapper);- // Step 2: cold wrapper starts with `bl <cold.1>`. Decode.- uint32_t bl = *(uint32_t *)coldWrapper;- uintptr_t cold1 = 0;- if ((bl & 0xFC000000u) == 0x94000000u) {- int32_t imm26 = (int32_t)((bl & 0x03FFFFFFu) << 6) >> 4;- cold1 = coldWrapper + (intptr_t)imm26;- vcc_log(@" cold.1 @ 0x%lx", (unsigned long)cold1);- }- // Step 3: walk cold.1 looking for the LAST `adrp x1,...; add x1,- // x1, #imm` pair BEFORE the dispatch_once `bl`. That's the block- // constant. cold.1 is typically only 5–6 instructions long.- if (cold1) {- uint32_t *cip = (uint32_t *)cold1;- uintptr_t blockConst = 0;- for (unsigned i = 0; i < 16; i++) {- uint32_t add = cip[i];- if ((add & 0xFF800000u) != 0x91000000u) continue;- if ((add & 0x1Fu) != 1) continue; // ADD x1, ...- if (((add >> 5) & 0x1Fu) != 1) continue;- uint32_t add_imm = (add >> 10) & 0xFFFu;- // Walk back for matching adrp x1- for (unsigned k = 1; k <= 4 && k <= i; k++) {- uint32_t adrp = cip[i - k];- if ((adrp & 0x9F000000u) != 0x90000000u) continue;- if ((adrp & 0x1Fu) != 1) continue;- uintptr_t adrp_pc = (uintptr_t)&cip[i - k];- blockConst = vcc_adrp_target(adrp_pc, adrp) + add_imm;- break;- }- if (blockConst) break;- }- if (!blockConst) {- vcc_log(@" block-constant adrp+add not found in cold.1");- } else {- vcc_log(@" block constant @ 0x%lx", (unsigned long)blockConst);- // Step 4: read invoke pointer at offset 0x10 within the- // block constant. PAC-strip and assign as block-invoke.- uintptr_t rawInvoke = *(uintptr_t *)(blockConst + 0x10);- blockInvoke = (uintptr_t)ptrauth_strip(- (void *)rawInvoke, ptrauth_key_function_pointer);- vcc_log(@" init block-invoke (via cold.1 chain) @ 0x%lx",- (unsigned long)blockInvoke);- }- }- }- }- }- uintptr_t sSourceListAddr = 0;- if (blockInvoke) {- uintptr_t globals[8] = {0};- unsigned ng = vcc_collect_call_then_store_globals(blockInvoke,- /*maxInsns*/512,- /*lookahead*/12,- globals, 8);- for (unsigned i = 0; i < ng; i++) {- vcc_log(@" init-statics global #%u: 0x%lx",- i, (unsigned long)globals[i]);- }- // The init block initializes both `_sSourceListLock` (lock- // handle) and `_sSourceList` (CFArray) in order. Walk the- // discovered globals and pick the first one whose slot value- // is actually a CFArray — that's the source list. The lock- // entry has a void* mutex handle which malloc_zone validates- // but isa fails the CFArray-class check.- uintptr_t symLookup = vcc_lookup_lc_symtab(&img, "_sSourceList");- if (symLookup) {- vcc_log(@" _sSourceList also in LC_SYMTAB at 0x%lx — using",- (unsigned long)symLookup);- sSourceListAddr = symLookup;- } else {- for (unsigned i = 0; i < ng; i++) {- if (vcc_slot_value_is_cfarray(globals[i])) {- uintptr_t val = 0;- if (globals[i]) val = *(uintptr_t *)globals[i];- vcc_log(@" _sSourceList chosen (init-store #%u, CFArray @ 0x%lx) at 0x%lx",- i, (unsigned long)val, (unsigned long)globals[i]);- sSourceListAddr = globals[i];- break;- }- }- if (!sSourceListAddr) {- vcc_log(@" no init-store global slot held a CFArray; falling "- @"back to first init-store");- if (ng > 0) sSourceListAddr = globals[0];- }- }- } else {- vcc_log(@" init-statics block-invoke lookup failed");- }- if (!sSourceListAddr) {- vcc_log(@" data global resolve failed: _sSourceList not located");- return;- }-- // For the lock, the call-anchor approach requires knowing which- // mutex-create function the daemon uses (FigSimpleMutexCreate / Init- // / etc. — name varies across iOS). Skip locking entirely: our- // dispatch_after fires after FigCaptureSourceServerStart's- // dispatch_once block has finished, and we're the only writer to- // _sSourceList during this init window.- CFMutableArrayRef *sSourceListSlot =- (CFMutableArrayRef *)sSourceListAddr;- vcc_log(@" lock acquisition skipped (single-threaded init window)");- vcc_log(@" _sSourceList slot @ %p (list=%p)", sSourceListSlot,- *sSourceListSlot);-- // Resolve FigCaptureSourceCreateFromBacking. Marked `external` in- // CMCapture's symtab — should be in the dyld exports trie.- void *create_p = vcc_dlsym_fn("FigCaptureSourceCreateFromBacking");- if (!create_p) {- vcc_log(@" abort: FigCaptureSourceCreateFromBacking not dlsym-resolvable");- return;- }- VCC_CreateFn create_fn = (VCC_CreateFn)create_p;-- id backing = vcc_build_backing();- if (!backing) return;- void *source = vcc_create_synthetic_source(create_fn, backing);- if (!source) {- vcc_log(@" create returned NULL — abort");- return;- }-- vcc_probe_contract(source);-- // Dump ALL existing sources' AttributesDictionary so we can mirror what- // the daemon's stock (bring-up / hardware) sources use for keys like- // DeviceType, SmartCameraSupported, Streams, Ports, etc.- {- CFMutableArrayRef listSnap = *sSourceListSlot;- CFIndex cnt = listSnap ? CFArrayGetCount(listSnap) : 0;- vcc_log(@" --- existing sources (count=%ld) ---", (long)cnt);- void *(*CMBaseObjectGetVTable)(void *) =- (void *(*)(void *))vcc_dlsym_fn("CMBaseObjectGetVTable");- for (CFIndex i = 0; i < cnt; i++) {- void *s = (void *)CFArrayGetValueAtIndex(listSnap, i);- vcc_log(@" source[%ld] = %p", (long)i, s);- if (!CMBaseObjectGetVTable) continue;- void *V = CMBaseObjectGetVTable(s);- if (!V) continue;- void **vtable_slot = (void **)((char *)V + 8);- void *real_vtable_signed = *vtable_slot;- uintptr_t vt_disc =- __builtin_ptrauth_blend_discriminator(vtable_slot, 47377);- void *real_vtable = __builtin_ptrauth_auth(real_vtable_signed,- ptrauth_key_asda, vt_disc);- if (!real_vtable) continue;- void **method6_slot = (void **)((char *)real_vtable + 48);- void *method6_signed = *method6_slot;- uintptr_t m6_disc =- __builtin_ptrauth_blend_discriminator(method6_slot, 38693);- void *method6 = __builtin_ptrauth_auth_and_resign(- method6_signed, ptrauth_key_asia, m6_disc,- ptrauth_key_function_pointer, 0);- typedef int (*CP)(void *, CFStringRef, CFAllocatorRef, CFTypeRef *);- CP copyProp = (CP)method6;- CFStringRef k_attrs = vcc_cfconst(- "kFigCaptureSourceProperty_AttributesDictionary");- CFTypeRef out = NULL;- int e = copyProp(s, k_attrs, kCFAllocatorDefault, &out);- vcc_log(@" attrs ret=%d -> %@", e, (__bridge id)out);- if (out) CFRelease(out);- }- }-- CFMutableArrayRef list = *sSourceListSlot;- if (!list) {- vcc_log(@" _sSourceList is NULL (server init not yet allocated it) — abort");- return;- }- CFIndex preCount = CFArrayGetCount(list);- CFArrayAppendValue(list, source);- CFIndex postCount = CFArrayGetCount(list);- vcc_log(@" appended source — list %ld -> %ld", (long)preCount,- (long)postCount);-- CFStringRef notifNameCF = vcc_cfconst(- "kFigCaptureSourceNotification_SourceInfoArrayChanged");- if (notifNameCF) {- char buf[256];- if (CFStringGetCString(notifNameCF, buf, sizeof(buf),- kCFStringEncodingUTF8)) {- uint32_t status = notify_post(buf);- vcc_log(@" notify_post(%s) -> %u", buf, status);- } else {- vcc_log(@" CFStringGetCString failed for notif name");- }- } else {- vcc_log(@" notif name CFString constant missing");- }-}--// MARK: - frame-sender endpoint observation-//-// AVF capture clients (Camera.app, AVCaptureSession-using apps) tell the-// daemon "I want frames from camera X" by publishing a FrameSenderEndpoint-// — XPC handler `_captureSourceServer_handlePublishFrameSenderEndpointMessage`-// in CMCapture forwards each publish into the daemon-side class-// `CMCaptureFrameSenderEndpointsServerSideSingleton` via the-// `+addEndpoint:endpointUniqueID:endpointType:endpointPID:endpointProxyPID:-// endpointAuditToken:endpointProxyAuditToken:endpointCameraUniqueID:`-// class method. Each endpoint carries the requesting client's audit token-// and the camera unique-ID they want frames for. Our synth's unique-ID is-// "vphone:vcam:0", so any endpoint whose cameraUniqueID matches that string-// is a client expecting frames from us.-//-// We swizzle the class method below to log every registration. Once we-// see Camera.app (or rpcserver_ios) publishing an endpoint for our synth,-// we know the next sub-stage is to build a `-[CMCaptureFrameSenderService-// sendFrame:]` call path that pushes CMSampleBuffers built from our shm-// `vcc_latest_frame` into each registered endpoint.-//-// This hook is observation-only; it does not deliver frames yet.--static IMP vcc_add_endpoint_orig_imp = NULL;--typedef BOOL (*VccAddEndpointFn)(id,- SEL,- id /*endpoint*/,- id /*endpointUniqueID*/,- int /*endpointType*/,- int /*endpointPID*/,- int /*endpointProxyPID*/,- audit_token_t * /*auditToken*/,- audit_token_t * /*proxyAuditToken*/,- id /*endpointCameraUniqueID*/);--static BOOL vcc_add_endpoint_hook(id self,- SEL _cmd,- id endpoint,- id endpointUniqueID,- int endpointType,- int endpointPID,- int endpointProxyPID,- audit_token_t *auditToken,- audit_token_t *proxyAuditToken,- id endpointCameraUniqueID) {- vcc_log(@" +addEndpoint cameraID=%@ pid=%d type=%d endpointUniqueID=%@",- endpointCameraUniqueID, endpointPID, endpointType, endpointUniqueID);- if (!vcc_add_endpoint_orig_imp) return NO;- VccAddEndpointFn orig = (VccAddEndpointFn)vcc_add_endpoint_orig_imp;- BOOL ok = orig(self, _cmd, endpoint, endpointUniqueID, endpointType,- endpointPID, endpointProxyPID, auditToken,- proxyAuditToken, endpointCameraUniqueID);- vcc_log(@" +addEndpoint orig returned %d", ok);- return ok;-}--static void vcc_install_endpoint_hook(void) {- Class cls = NSClassFromString(- @"CMCaptureFrameSenderEndpointsServerSideSingleton");- if (!cls) {- vcc_log(@" endpoint hook: class missing");- return;- }- SEL sel = NSSelectorFromString(- @"addEndpoint:endpointUniqueID:endpointType:endpointPID:"- @"endpointProxyPID:endpointAuditToken:endpointProxyAuditToken:"- @"endpointCameraUniqueID:");- Method m = class_getClassMethod(cls, sel);- if (!m) {- vcc_log(@" endpoint hook: class_getClassMethod returned NULL");- return;- }- vcc_add_endpoint_orig_imp = method_setImplementation(m, (IMP)vcc_add_endpoint_hook);- vcc_log(@" endpoint hook installed (orig=%p)",- vcc_add_endpoint_orig_imp);-}--// MARK: - sink-node diagnostic dump-//-// Enumerate the BWImageQueueSinkNode + BWRemoteQueueSinkNode method tables-// at runtime so we can identify the actual init / setup / render selectors-// the session pipeline invokes. The static class-dump on the DSC binary-// returns garbled selptr references — at runtime the selector table is-// resolved, so this dump is reliable. Result lands in the vcamcaptured.log-// file; we use it to pick the right hook target for stage G.--static void vcc_dump_class(const char *name) {- Class cls = NSClassFromString(@(name));- if (!cls) {- vcc_log(@" class %s NOT FOUND", name);- return;- }- Class super = class_getSuperclass(cls);- vcc_log(@" class %s @ %p (super=%s)", name, cls,- super ? class_getName(super) : "<root>");-- unsigned int count = 0;- Method *list = class_copyMethodList(cls, &count);- vcc_log(@" -- instance methods (%u) --", count);- for (unsigned i = 0; i < count; i++) {- Method m = list[i];- SEL s = method_getName(m);- IMP imp = method_getImplementation(m);- const char *types = method_getTypeEncoding(m);- vcc_log(@" -[%s %@] imp=%p types=%s", name,- NSStringFromSelector(s), (void *)imp,- types ? types : "?");- }- free(list);-- Class meta = object_getClass((id)cls);- count = 0;- Method *clist = class_copyMethodList(meta, &count);- vcc_log(@" -- class methods (%u) --", count);- for (unsigned i = 0; i < count; i++) {- Method m = clist[i];- SEL s = method_getName(m);- IMP imp = method_getImplementation(m);- vcc_log(@" +[%s %@] imp=%p", name,- NSStringFromSelector(s), (void *)imp);- }- free(clist);-}--static void vcc_dump_sink_node_methods(void) {- vcc_log(@"---- sink-node method dump ----");- vcc_dump_class("BWSinkNode");- vcc_dump_class("BWImageQueueSinkNode");- vcc_dump_class("BWRemoteQueueSinkNode");- vcc_dump_class("BWFigCaptureSession");- vcc_dump_class("BWFigCaptureDeviceVendor");- vcc_dump_class("FigCaptureSourceBacking");- vcc_dump_class("FigCaptureVideoSourceBacking");- vcc_dump_class("FigCameraViewfinderStream");- vcc_dump_class("FigCameraViewfinderSessionLocal");- vcc_dump_class("FigCameraViewfinderLocal");- vcc_dump_class("BWPreviewTimeMachineSinkNode");- // Photo-path classes for capturePhoto debugging- vcc_dump_class("BWStillImageCaptureCoordinator");- vcc_dump_class("BWStillImageSampleBufferSinkNode");- vcc_dump_class("BWStillImageProcessorController");- vcc_dump_class("BWFigCaptureStillImageRequest");- vcc_dump_class("FigCaptureCameraSourcePipeline");- vcc_dump_class("FigCaptureSourcePipeline");- vcc_log(@"---- end sink-node method dump ----");-}--// MARK: - sink observation hooks-//-// Stage G observation pass: swizzle the two sink classes' init + render-// methods. Goals:-// 1) Confirm whether sinks are instantiated when an AVF client opens our-// synth source (i.e. is the pipeline starved at the SOURCE end or at the-// configuration end?).-// 2) See whether ANY renderSampleBuffer:forInput: calls fire — if they do,-// we know the pipeline runs and we just need to substitute the-// sample-buffer contents.--static unsigned long vcc_render_call_count = 0;-static unsigned long vcc_iqsn_init_count = 0;-static unsigned long vcc_rqsn_init_count = 0;--static IMP vcc_iqsn_init_orig = NULL;-static IMP vcc_rqsn_init_orig = NULL;-static IMP vcc_iqsn_render_orig = NULL;-static IMP vcc_rqsn_render_orig = NULL;--typedef id (*VccIqsnInitFn)(- id self,- SEL _cmd,- BOOL hfrSupport,- BOOL ispJitterCompensationEnabled,- audit_token_t auditToken,- id sinkID);--typedef id (*VccRqsnInitFn)(- id self,- SEL _cmd,- uint32_t mediaType,- audit_token_t auditToken,- id sinkID,- id cameraInfoByPortType);--typedef void (*VccRenderFn)(- id self,- SEL _cmd,- CMSampleBufferRef cmsb,- id input);--static id vcc_iqsn_init_hook(- id self,- SEL _cmd,- BOOL hfrSupport,- BOOL ispJitterCompensationEnabled,- audit_token_t auditToken,- id sinkID) {- VccIqsnInitFn orig = (VccIqsnInitFn)vcc_iqsn_init_orig;- id ret = orig(self, _cmd, hfrSupport, ispJitterCompensationEnabled,- auditToken, sinkID);- vcc_iqsn_init_count++;- vcc_log(@" [IQSN init] -> %p sinkID=%@ count=%lu",- ret, sinkID, vcc_iqsn_init_count);- return ret;-}--static id vcc_rqsn_init_hook(- id self,- SEL _cmd,- uint32_t mediaType,- audit_token_t auditToken,- id sinkID,- id cameraInfoByPortType) {- VccRqsnInitFn orig = (VccRqsnInitFn)vcc_rqsn_init_orig;- id ret = orig(self, _cmd, mediaType, auditToken, sinkID,- cameraInfoByPortType);- vcc_rqsn_init_count++;- vcc_log(@" [RQSN init] -> %p mediaType=0x%x sinkID=%@ count=%lu",- ret, mediaType, sinkID, vcc_rqsn_init_count);- return ret;-}--static void vcc_iqsn_render_hook(- id self,- SEL _cmd,- CMSampleBufferRef cmsb,- id input) {- vcc_render_call_count++;- if (vcc_render_call_count <= 5 || (vcc_render_call_count & 63) == 1) {- vcc_log(@" [IQSN render] self=%p cmsb=%p input=%p inputCls=%@ #%lu",- self, cmsb, input, NSStringFromClass([input class]),- vcc_render_call_count);- }- VccRenderFn orig = (VccRenderFn)vcc_iqsn_render_orig;- orig(self, _cmd, cmsb, input);-}--static void vcc_rqsn_render_hook(- id self,- SEL _cmd,- CMSampleBufferRef cmsb,- id input) {- vcc_render_call_count++;- if (vcc_render_call_count <= 5 || (vcc_render_call_count & 63) == 1) {- vcc_log(@" [RQSN render] self=%p cmsb=%p input=%p inputCls=%@ #%lu",- self, cmsb, input, NSStringFromClass([input class]),- vcc_render_call_count);- }- VccRenderFn orig = (VccRenderFn)vcc_rqsn_render_orig;- orig(self, _cmd, cmsb, input);-}--static void vcc_swizzle_method(Class cls, SEL sel, IMP newImp, IMP *outOrig) {- Method m = class_getInstanceMethod(cls, sel);- if (!m) {- vcc_log(@" swizzle: -[%s %@] missing", class_getName(cls),- NSStringFromSelector(sel));- return;- }- *outOrig = method_setImplementation(m, newImp);- vcc_log(@" swizzled -[%s %@] (orig imp=%p)", class_getName(cls),- NSStringFromSelector(sel), *outOrig);-}--// Extra observation: hook -[BWFigCaptureDeviceVendor copyDeviceWithID:forClient:informClientWhenDeviceAvailableAgain:error:]-// to see when an AVF client asks for our device. If this fires, we know the-// session is at least requesting a device for our synth. If it doesn't fire,-// the client never even reached the device-vendor stage (gated upstream).--static IMP vcc_copy_device_orig = NULL;--// Type encoding observed on iOS 26.5 cameracaptured:-// @40@0:8@16i24B28^i32-// => id (*)(id self, SEL _cmd, NSString *deviceID, int clientPID,-// BOOL informClient, int *err)-// The earlier disabled stub mis-typed clientPID as `id`, causing ARC to-// emit objc_retain on an integer register and crash inside the hook-// prologue.--typedef id (*VccCopyDeviceFn)(id self,- SEL _cmd,- NSString *deviceID,- int clientPID,- BOOL informClient,- int *err);--static Class vcc_synth_device_class = Nil;--// Forward decls.-static void vcc_init_synth_device_class(void);-__attribute__((ns_returns_retained))-static id vcc_make_synth_device(NSString *deviceID);--static id vcc_copy_device_hook(id self,- SEL _cmd,- NSString *deviceID,- int clientPID,- BOOL informClient,- int *err) {- vcc_log(@" [copyDeviceWithID] deviceID=%@ clientPID=%d inform=%d",- deviceID, clientPID, informClient);-- if ([deviceID isEqualToString:kVccSynthDeviceID]) {- id synth = vcc_make_synth_device(deviceID);- if (err) *err = 0;- vcc_log(@" [copyDeviceWithID] -> synth %p (class=%s err=0)",- synth, object_getClassName(synth));- return synth;- }-- VccCopyDeviceFn orig = (VccCopyDeviceFn)vcc_copy_device_orig;- id ret = orig(self, _cmd, deviceID, clientPID, informClient, err);- int errval = err ? *err : 0;- vcc_log(@" [copyDeviceWithID] returned %p (err=%d)", ret, errval);- return ret;-}--// MARK: - synthetic FigCaptureDevice subclass-//-// Subclass `BWFigCaptureDevice` at runtime via objc_allocateClassPair, then-// instantiate via +alloc. We write the deviceID NSString directly into the-// inherited ivar slot. Ivar offsets are resolved at synth-class init time-// via the ObjC runtime (class_getInstanceVariable + ivar_getOffset) so-// the layout follows whatever Apple ships, not a hardcoded 26.5 value.-//-// To prevent the crash in-// `-[BWFigCaptureDevice _copyProperty:requireSupported:error:]` (where the-// inherited body would deref the NULL figCaptureDevice via-// CMBaseObjectGetVTable), we OVERRIDE the public ObjC wrappers-// (-copyProperty:error:, -getProperty:error:, -copyPropertyIfSupported:error:)-// in our subclass so they never call _copyProperty:. Each override returns-// canned values for known properties and sets *err=-12787 ("property not-// supported") for everything else.--// Resolved at synth-class init. -1 until populated; vcc_init_synth_device_class-// refuses to register the synth class if resolution fails so we never write-// to a stale offset.-static ptrdiff_t kBWFigCaptureDevice_deviceID_Offset = -1;--// Resolve an instance-variable offset by name on `cls`, trying each-// candidate in `names` (NULL-terminated) until one matches. Returns -1-// if none match. Logs the outcome so a future iOS rename surfaces in-// the install log instead of silently writing to a wrong slot.-static ptrdiff_t vcc_resolve_ivar(Class cls,- const char *what,- const char *const *names) {- if (!cls) {- vcc_log(@" ivar %s: class missing", what ? what : "?");- return -1;- }- for (unsigned i = 0; names[i]; i++) {- Ivar iv = class_getInstanceVariable(cls, names[i]);- if (iv) {- ptrdiff_t off = ivar_getOffset(iv);- vcc_log(@" ivar %s -> %s @ +0x%lx", what ? what : "?",- names[i], (long)off);- return off;- }- }- vcc_log(@" ivar %s: no candidate matched on %s", what ? what : "?",- class_getName(cls));- return -1;-}--// Cached CF constant — resolved lazily from CMCaptureCore / CMCaptureDevice.-static CFStringRef vcc_cf_kClock = NULL;--static void vcc_load_synth_cfconsts(void) {- if (!vcc_cf_kClock) vcc_cf_kClock = vcc_cfconst("kFigCaptureDeviceProperty_Clock");-}--// Returns a CMClockRef (CoreMedia host time clock). Lifetime tied to the-// process — we never release it.-static CFTypeRef vcc_get_host_clock(void) {- static CFTypeRef cached = NULL;- if (cached) return cached;- typedef CFTypeRef (*GetHostClockFn)(void);- GetHostClockFn fn = (GetHostClockFn)dlsym(RTLD_DEFAULT, "CMClockGetHostTimeClock");- if (!fn) {- vcc_log(@" synth-dev: CMClockGetHostTimeClock missing");- return NULL;- }- cached = fn();- if (cached) CFRetain(cached); // keep it alive- return cached;-}--// copyProperty: follows the +1 "copy" convention — return must be retained.-__attribute__((ns_returns_retained))-static id vcc_synth_copy_property(id self, SEL _cmd, id property, int *err) {- NSString *propStr = [property description];- if (vcc_cf_kClock &&- [(__bridge id)vcc_cf_kClock isEqual:property]) {- CFTypeRef clk = vcc_get_host_clock();- if (err) *err = clk ? 0 : -12787;- vcc_log(@" [SynthDev copyProperty:Clock] -> %p", clk);- if (!clk) return nil;- CFRetain(clk);- return (__bridge_transfer id)clk; // +1 retained, ns_returns_retained- }- if (err) *err = -12787;- vcc_log(@" [SynthDev copyProperty:%@] -> nil (err=-12787)", propStr);- return nil;-}--__attribute__((ns_returns_retained))-static id vcc_synth_copy_property_if_supported(id self,- SEL _cmd,- id property,- int *err) {- NSString *propStr = [property description];- if (err) *err = 0;- vcc_log(@" [SynthDev copyPropertyIfSupported:%@] -> nil", propStr);- return nil;-}--static int vcc_synth_get_property(id self, SEL _cmd, id property, int *err) {- NSString *propStr = [property description];- if (err) *err = -12787;- vcc_log(@" [SynthDev getProperty:%@] -> 0 (err=-12787)", propStr);- return 0;-}--static id vcc_synth_supported_properties(id self, SEL _cmd) {- // BWFigVideoCaptureDevice expects an NSDictionary here — it queries the- // returned object via -objectForKeyedSubscript: for property keys (e.g.- // kFigCaptureDeviceProperty_SupportedSynchronizedStreamsGroups). Returning- // an NSSet would crash on that selector.- vcc_log(@" [SynthDev supportedProperties] -> empty dict");- return [NSDictionary dictionary];-}--static id vcc_synth_unique_id(id self, SEL _cmd) {- void **slot = (void **)((char *)(__bridge void *)self- + kBWFigCaptureDevice_deviceID_Offset);- id idVal = (__bridge id)(*slot);- return idVal;-}--static void vcc_synth_dealloc(id self, SEL _cmd) {- void **slot = (void **)((char *)(__bridge void *)self- + kBWFigCaptureDevice_deviceID_Offset);- if (*slot) {- CFRelease((CFTypeRef)*slot);- *slot = NULL;- }- // Skip parent's -dealloc and finish destruction ourselves. ARC marks- // objc_destructInstance as unavailable, so resolve via dlsym.- static void *(*destruct)(id) = NULL;- if (!destruct) destruct = dlsym(RTLD_DEFAULT, "objc_destructInstance");- if (destruct) destruct(self);- free((__bridge void *)self);-}--static void vcc_init_synth_device_class(void) {- if (vcc_synth_device_class) return;- Class parent = NSClassFromString(@"BWFigCaptureDevice");- if (!parent) {- vcc_log(@" synth-dev: BWFigCaptureDevice class missing");- return;- }- static const char *const kDeviceIDNames[] = {- "_deviceID", "deviceID", NULL,- };- kBWFigCaptureDevice_deviceID_Offset = vcc_resolve_ivar(- parent, "BWFigCaptureDevice.deviceID", kDeviceIDNames);- if (kBWFigCaptureDevice_deviceID_Offset < 0) {- vcc_log(@" synth-dev: required ivar not found — registration aborted");- return;- }- vcc_load_synth_cfconsts();-- Class cls = objc_allocateClassPair(parent, "VccSynthDevice", 0);- if (!cls) {- vcc_log(@" synth-dev: objc_allocateClassPair failed");- return;- }-- class_addMethod(cls, @selector(copyProperty:error:),- (IMP)vcc_synth_copy_property, "@@:@^i");- class_addMethod(cls, @selector(copyPropertyIfSupported:error:),- (IMP)vcc_synth_copy_property_if_supported, "@@:@^i");- class_addMethod(cls, @selector(getProperty:error:),- (IMP)vcc_synth_get_property, "i@:@^i");- class_addMethod(cls, @selector(supportedProperties),- (IMP)vcc_synth_supported_properties, "@@:");- class_addMethod(cls, @selector(uniqueID),- (IMP)vcc_synth_unique_id, "@@:");- class_addMethod(cls, NSSelectorFromString(@"dealloc"),- (IMP)vcc_synth_dealloc, "v@:");-- objc_registerClassPair(cls);- vcc_synth_device_class = cls;- vcc_log(@" registered VccSynthDevice : BWFigCaptureDevice (cls=%p)", cls);-}--// MARK: - synthetic FigCaptureStream subclass-//-// Subclass BWFigCaptureStream. Ivar offsets are resolved at synth-class-// init time via the ObjC runtime so the layout follows whatever Apple-// ships. Historical disasm of -[BWFigCaptureStream initWith…] and the-// trivial ivar accessors gave us the slot semantics:-//-// figCaptureStream : C handle, leave NULL-// portType : NSString-// uniqueID : NSString-// isSpecialDeviceID : BOOL (we don't touch it)-// property cache : NSDictionary — DO NOT write a non-dict here.-// Earlier iteration put a deviceID string in the slot; the-// inherited -_copyProperty: calls [cache-// objectForKeyedSubscript:key] unconditionally, and the-// unrecognized-selector crashed cameracaptured. Leave NULL-// so the lookup short-circuits to nil.-// streaming : BOOL — set to 1 so -streaming returns YES.--static Class vcc_synth_stream_class = Nil;-// Resolved at synth-class init. portType/uniqueID are required (-1 -> abort-// class registration); streaming is optional (-1 -> skip the YES poke).-static ptrdiff_t kBWFigCaptureStream_portType_Offset = -1;-static ptrdiff_t kBWFigCaptureStream_uniqueID_Offset = -1;-static ptrdiff_t kBWFigCaptureStream_streaming_Offset = -1;--static CFStringRef vcc_cf_kSupportedFormatsArray = NULL;--__attribute__((ns_returns_retained))-static id vcc_synth_stream_copy_property(id self,- SEL _cmd,- id property,- int *err) {- if (!vcc_cf_kSupportedFormatsArray) {- vcc_cf_kSupportedFormatsArray =- vcc_cfconst("kFigCaptureStreamProperty_SupportedFormatsArray");- }- if (vcc_cf_kSupportedFormatsArray &&- [(__bridge id)vcc_cf_kSupportedFormatsArray isEqual:property]) {- if (err) *err = 0;- // Empirically: empty SupportedFormatsArray returns +1-retained per- // ns_returns_retained convention. Non-empty arrays (objects or dicts)- // trip a daemon-side validation that we don't satisfy → isRunning=0.- // The AVCaptureDevice.formats list is populated separately via- // -[FigCaptureSourceBacking initWith…formats:…], so the AVF client- // still sees both formats and selects activeFormat.- vcc_log(@" [SynthStream copyProperty:SupportedFormatsArray] -> empty array");- return [[NSArray alloc] init];- }- if (err) *err = -12787;- vcc_log(@" [SynthStream copyProperty:%@] -> nil (err=-12787)",- [property description]);- return nil;-}--__attribute__((ns_returns_retained))-static id vcc_synth_stream_copy_property_if_supported(id self,- SEL _cmd,- id property,- int *err) {- if (err) *err = 0;- vcc_log(@" [SynthStream copyPropertyIfSupported:%@] -> nil",- [property description]);- return nil;-}--static int vcc_synth_stream_get_property(id self,- SEL _cmd,- id property,- int *err) {- NSString *propStr = [property description];- // The daemon's session-start path queries PixelSize on the stream and- // treats err=-12787 as fatal — propagates up to AVCaptureSessionRuntimeError- // and stops the session. Return 0 with err=0 (supported, zero value) so- // the check passes. Same defensive default for any other property we- // haven't otherwise explicitly handled.- if (err) *err = 0;- vcc_log(@" [SynthStream getProperty:%@] -> 0 err=0", propStr);- return 0;-}--static int vcc_synth_stream_get_property_if_supported(id self,- SEL _cmd,- id property,- int *err) {- if (err) *err = 0;- vcc_log(@" [SynthStream getPropertyIfSupported:%@] -> 0 err=0",- [property description]);- return 0;-}--// Catches the private _copyProperty:requireSupported:error: path. Same-// effective result as -copyProperty:error: (canned values for known-// keys, -12787 otherwise) — just a 3rd BOOL arg.-static id vcc_synth_stream_underscore_copy_property(id self,- SEL _cmd,- id property,- BOOL requireSupported,- int *err) {- return vcc_synth_stream_copy_property(self, @selector(copyProperty:error:),- property, err);-}--static id vcc_synth_stream_supported_properties(id self, SEL _cmd) {- return [NSDictionary dictionary];-}--static int vcc_synth_stream_set_property(id self,- SEL _cmd,- id property,- id value) {- vcc_log(@" [SynthStream setProperty:%@] (ignored)", [property description]);- return 0;-}--static void vcc_synth_stream_dealloc(id self, SEL _cmd) {- void *p = (__bridge void *)self;- void **portTypeSlot = (void **)((char *)p + kBWFigCaptureStream_portType_Offset);- void **uniqueIDSlot = (void **)((char *)p + kBWFigCaptureStream_uniqueID_Offset);- if (*portTypeSlot) { CFRelease(*portTypeSlot); *portTypeSlot = NULL; }- if (*uniqueIDSlot) { CFRelease(*uniqueIDSlot); *uniqueIDSlot = NULL; }- // Skip parent's -dealloc (would touch many uninitialized ivars). Manually- // destruct + free the storage. ARC blocks direct objc_destructInstance,- // so resolve via dlsym.- static void *(*destruct)(id) = NULL;- if (!destruct) destruct = dlsym(RTLD_DEFAULT, "objc_destructInstance");- if (destruct) destruct(self);- free((__bridge void *)self);-}--static void vcc_init_synth_stream_class(void) {- if (vcc_synth_stream_class) return;- Class parent = NSClassFromString(@"BWFigCaptureStream");- if (!parent) {- vcc_log(@" synth-stream: BWFigCaptureStream class missing");- return;- }- static const char *const kPortTypeNames[] = {"_portType", "portType", NULL};- static const char *const kUniqueIDNames[] = {"_uniqueID", "uniqueID", NULL};- static const char *const kStreamingNames[] = {- "_streaming", "streaming", "_isStreaming", "isStreaming", NULL,- };- kBWFigCaptureStream_portType_Offset = vcc_resolve_ivar(- parent, "BWFigCaptureStream.portType", kPortTypeNames);- kBWFigCaptureStream_uniqueID_Offset = vcc_resolve_ivar(- parent, "BWFigCaptureStream.uniqueID", kUniqueIDNames);- kBWFigCaptureStream_streaming_Offset = vcc_resolve_ivar(- parent, "BWFigCaptureStream.streaming", kStreamingNames);- if (kBWFigCaptureStream_portType_Offset < 0 ||- kBWFigCaptureStream_uniqueID_Offset < 0) {- vcc_log(@" synth-stream: required ivar(s) not found — registration aborted");- return;- }- Class cls = objc_allocateClassPair(parent, "VccSynthStream", 0);- if (!cls) {- vcc_log(@" synth-stream: objc_allocateClassPair failed");- return;- }- class_addMethod(cls, @selector(copyProperty:error:),- (IMP)vcc_synth_stream_copy_property, "@@:@^i");- class_addMethod(cls, @selector(copyPropertyIfSupported:error:),- (IMP)vcc_synth_stream_copy_property_if_supported, "@@:@^i");- class_addMethod(cls, @selector(getProperty:error:),- (IMP)vcc_synth_stream_get_property, "i@:@^i");- class_addMethod(cls, @selector(getPropertyIfSupported:error:),- (IMP)vcc_synth_stream_get_property_if_supported, "i@:@^i");- // Also override the underlying _copyProperty:requireSupported:error:- // so any inherited call path that bypasses the public wrappers (e.g.- // -getPropertyIfSupported: in older code paths) still lands here- // instead of crashing on the NULL figCaptureStream vtable deref.- class_addMethod(cls,- NSSelectorFromString(@"_copyProperty:requireSupported:error:"),- (IMP)vcc_synth_stream_underscore_copy_property, "@@:@B^i");- class_addMethod(cls, @selector(supportedProperties),- (IMP)vcc_synth_stream_supported_properties, "@@:");- class_addMethod(cls, @selector(setProperty:value:),- (IMP)vcc_synth_stream_set_property, "i@:@@");- class_addMethod(cls, NSSelectorFromString(@"dealloc"),- (IMP)vcc_synth_stream_dealloc, "v@:");- objc_registerClassPair(cls);- vcc_synth_stream_class = cls;- vcc_log(@" registered VccSynthStream : BWFigCaptureStream (cls=%p)", cls);-}--// Strong references to every manufactured synth stream, so they can't be-// released early by autorelease churn or refcount bugs in our dealloc.-// Memory grows by one stream per session start; acceptable for diagnosis.-static NSMutableArray *vcc_synth_streams_strong_refs = nil;--__attribute__((ns_returns_retained))-static id vcc_make_synth_stream(NSString *uniqueID,- NSString *deviceID,- NSString *portType) {- if (!vcc_synth_stream_class) vcc_init_synth_stream_class();- if (!vcc_synth_stream_class) return nil;- // Use +alloc via runtime — ARC-safe (class_createInstance is- // OBJC_ARC_UNAVAILABLE and the retain-count semantics don't match what- // ARC expects). Function attributed ns_returns_retained so callers- // treat the +1 from alloc correctly without autorelease.- id s = ((id (*)(Class, SEL))objc_msgSend)(vcc_synth_stream_class,- @selector(alloc));- if (!s) return nil;-- void *p = (__bridge void *)s;- *(void **)((char *)p + kBWFigCaptureStream_portType_Offset) =- (void *)CFBridgingRetain([portType copy]);- *(void **)((char *)p + kBWFigCaptureStream_uniqueID_Offset) =- (void *)CFBridgingRetain([uniqueID copy]);- // property-cache NSDictionary ivar intentionally left NULL — the- // parent class unconditionally sends -objectForKeyedSubscript: to it,- // and an earlier iteration that stored deviceID there crashed with- // unrecognized-selector. The deviceID isn't read off the stream by- // inherited code anyway (only a per-stream BOOL comparison result is).- (void)deviceID;- // streaming BOOL — set to 1 so -streaming returns YES. Optional:- // skip if the ivar isn't present on this build.- if (kBWFigCaptureStream_streaming_Offset >= 0) {- *(uint8_t *)((char *)p + kBWFigCaptureStream_streaming_Offset) = 1;- }-- // Pin so dealloc never runs — diagnostic to isolate the autorelease-- // pool-drain crash. Each session start leaks one stream.- if (!vcc_synth_streams_strong_refs) {- vcc_synth_streams_strong_refs = [NSMutableArray new];- }- [vcc_synth_streams_strong_refs addObject:s];-- vcc_log(@" synth-stream: %p uid=%@ port=%@ devID=%@",- s, uniqueID, portType, deviceID);- return s;-}--// MARK: - hook BWFigCaptureDeviceVendor copyStreamsWithUniqueIDs:forDevice:-//-// When forDevice is our synth, manufacture one VccSynthStream per requested-// uniqueID so that the vendor's identity-matching inner loop in-// `-_copyStreamsForAttributes:` produces a result array whose count matches-// the input attributes count.--static IMP vcc_copy_streams_orig = NULL;-typedef id (*VccCopyStreamsFn)(id self,- SEL _cmd,- NSArray *uniqueIDs,- id forDevice,- int priority,- int *err);--static id vcc_copy_streams_hook(id self,- SEL _cmd,- NSArray *uniqueIDs,- id forDevice,- int priority,- int *err) {- if (forDevice && object_getClass(forDevice) == vcc_synth_device_class) {- vcc_log(@" [copyStreamsWithUniqueIDs forDevice:synth] ids=%@", uniqueIDs);- NSMutableArray *out = [NSMutableArray array];- void *p = (__bridge void *)forDevice;- NSString *devID = (__bridge NSString *)(*(void **)((char *)p + kBWFigCaptureDevice_deviceID_Offset));- for (NSString *uid in uniqueIDs) {- id s = vcc_make_synth_stream(uid, devID, @"Back");- if (s) [out addObject:s];- }- if (err) *err = 0;- vcc_log(@" [copyStreamsWithUniqueIDs] -> %lu streams",- (unsigned long)out.count);- return out;- }- VccCopyStreamsFn orig = (VccCopyStreamsFn)vcc_copy_streams_orig;- return orig(self, _cmd, uniqueIDs, forDevice, priority, err);-}--static void vcc_install_copy_streams_hook(void) {- Class cls = NSClassFromString(@"BWFigCaptureDeviceVendor");- if (!cls) return;- SEL sel = NSSelectorFromString(- @"copyStreamsWithUniqueIDs:forDevice:deviceClientPriority:error:");- vcc_swizzle_method(cls, sel, (IMP)vcc_copy_streams_hook, &vcc_copy_streams_orig);-}--static IMP vcc_copy_streams_from_orig = NULL;-typedef id (*VccCopyStreamsFromFn)(id self,- SEL _cmd,- id fromDevice,- NSArray *positions,- NSArray *deviceTypes,- int prio,- BOOL allowsLoss,- int *err);--static id vcc_copy_streams_from_hook(id self,- SEL _cmd,- id fromDevice,- NSArray *positions,- NSArray *deviceTypes,- int prio,- BOOL allowsLoss,- int *err) {- if (fromDevice && object_getClass(fromDevice) == vcc_synth_device_class) {- vcc_log(@" [copyStreamsFromDevice:synth positions=%@ deviceTypes=%@]",- positions, deviceTypes);- NSMutableArray *out = [NSMutableArray array];- void *p = (__bridge void *)fromDevice;- NSString *devID = (__bridge NSString *)(*(void **)((char *)p + kBWFigCaptureDevice_deviceID_Offset));- NSUInteger count = positions.count;- for (NSUInteger i = 0; i < count; i++) {- NSString *uid = [NSString stringWithFormat:@"%@:stream:%lu",- devID, (unsigned long)i];- id s = vcc_make_synth_stream(uid, devID, @"Back");- if (s) [out addObject:s];- }- if (err) *err = 0;- vcc_log(@" [copyStreamsFromDevice] -> %lu streams",- (unsigned long)out.count);- return out;- }- VccCopyStreamsFromFn orig = (VccCopyStreamsFromFn)vcc_copy_streams_from_orig;- return orig(self, _cmd, fromDevice, positions, deviceTypes,- prio, allowsLoss, err);-}--static void vcc_install_copy_streams_from_hook(void) {- Class cls = NSClassFromString(@"BWFigCaptureDeviceVendor");- if (!cls) return;- SEL sel = NSSelectorFromString(- @"copyStreamsFromDevice:positions:deviceTypes:deviceClientPriority:allowsStreamControlLoss:error:");- vcc_swizzle_method(cls, sel, (IMP)vcc_copy_streams_from_hook,- &vcc_copy_streams_from_orig);-}--__attribute__((ns_returns_retained))-static id vcc_make_synth_device(NSString *deviceID) {- if (!vcc_synth_device_class) vcc_init_synth_device_class();- if (!vcc_synth_device_class) return nil;-- // Use +alloc via runtime — ARC-safe. Function attributed- // ns_returns_retained so ARC treats the alloc'd +1 correctly.- id d = ((id (*)(Class, SEL))objc_msgSend)(vcc_synth_device_class,- @selector(alloc));- if (!d) {- vcc_log(@" synth-dev: class_createInstance failed");- return nil;- }- // Write deviceID at the runtime-resolved ivar offset via- // CFBridgingRetain so our -dealloc override CFRelease's it.- NSString *idCopy = [deviceID copy];- void *slotBase = (__bridge void *)d;- void **slot = (void **)((char *)slotBase + kBWFigCaptureDevice_deviceID_Offset);- *slot = (void *)CFBridgingRetain(idCopy);-- // Pin so dealloc never runs — diagnostic to isolate the autorelease- // pool drain crash. Each session start leaks one synth device.- static NSMutableArray *vcc_synth_devs_strong_refs = nil;- if (!vcc_synth_devs_strong_refs) {- vcc_synth_devs_strong_refs = [NSMutableArray new];- }- [vcc_synth_devs_strong_refs addObject:d];-- vcc_log(@" synth-dev: %p deviceID=%@ (slot@+0x%lx=%p)",- d, idCopy, (long)kBWFigCaptureDevice_deviceID_Offset, *slot);- return d;-}--static void vcc_install_device_vendor_hook(void) {- Class cls = NSClassFromString(@"BWFigCaptureDeviceVendor");- if (!cls) {- vcc_log(@" device-vendor hook: class missing");- return;- }- SEL sel = NSSelectorFromString(- @"copyDeviceWithID:forClient:informClientWhenDeviceAvailableAgain:error:");- vcc_swizzle_method(cls, sel, (IMP)vcc_copy_device_hook, &vcc_copy_device_orig);-}--// MARK: - viewfinder stream injection-//-// Camera.app's preview path goes through FigCameraViewfinderStream, NOT-// BWImageQueueSinkNode. The stream exposes -enqueueVideoSampleBuffer: which-// the daemon's normal frame producer calls to deliver each frame to the-// client (Camera.app's AVCaptureVideoPreviewLayer). For our synth source —-// which has no real producer — we hook -[FigCameraViewfinderStream init],-// capture each instance, and drive enqueueVideoSampleBuffer: ourselves on-// a 30 Hz timer, wrapping vcc_latest_frame pixels in a fresh CMSampleBuffer.--// Forward declaration — full definition is later in the file under the-// "shared-frame reader" section.-typedef struct vcc_latest_frame_s {- pthread_mutex_t lock;- uint32_t width;- uint32_t height;- uint32_t bytes_per_row;- uint8_t *pixels;- size_t pixels_capacity;- size_t pixels_length;-} vcc_latest_frame_t;-extern vcc_latest_frame_t vcc_latest_frame;--// CVPixelBuffer release callback for the malloc'd pixel buffer. Has to be-// a real C function (block isn't compatible with the callback signature).-static void vcc_cv_release_bytes(void *refcon, const void *baseAddress) {- (void)refcon;- free((void *)baseAddress);-}--static IMP vcc_vfs_init_orig = NULL;-static IMP vcc_vfs_open_orig = NULL;-static IMP vcc_vfs_close_orig = NULL;-static NSMutableArray *vcc_vf_streams = nil; // strong refs-static dispatch_source_t vcc_vf_timer = NULL;-static dispatch_queue_t vcc_vf_q = NULL;-static uint64_t vcc_vf_pts_ns = 0;-static uint64_t vcc_vf_enqueue_count = 0;-static uint64_t vcc_vf_enqueue_success = 0;--typedef id (*VccVfsInitFn)(id self, SEL _cmd);-typedef void (*VccVfsOpenFn)(id self, SEL _cmd, id dest);-typedef void (*VccVfsCloseFn)(id self, SEL _cmd);--static _Atomic uint64_t vcc_vfs_init_count = 0;--static id vcc_vfs_init_hook(id self, SEL _cmd) {- VccVfsInitFn orig = (VccVfsInitFn)vcc_vfs_init_orig;- id ret = orig(self, _cmd);- // Throttled — Camera.app spins ~2000 inits/sec without ever opening- // (session config silently incomplete). Log every 1024th to keep the log- // file usable.- uint64_t n = atomic_fetch_add(&vcc_vfs_init_count, 1) + 1;- if ((n & 0x3ff) == 1) {- vcc_log(@" [VFS init] -> %p (total=%llu)",- ret, (unsigned long long)n);- }- return ret;-}--static void vcc_vfs_open_hook(id self, SEL _cmd, id dest) {- vcc_log(@" [VFS open] self=%p dest=%@", self, dest);- VccVfsOpenFn orig = (VccVfsOpenFn)vcc_vfs_open_orig;- orig(self, _cmd, dest);- if (!vcc_vf_streams) vcc_vf_streams = [NSMutableArray array];- [vcc_vf_streams addObject:self];- vcc_log(@" [VFS open] captured stream %p (total=%lu)",- self, (unsigned long)vcc_vf_streams.count);-}--static void vcc_vfs_close_hook(id self, SEL _cmd) {- vcc_log(@" [VFS close] self=%p", self);- if (vcc_vf_streams) [vcc_vf_streams removeObject:self];- VccVfsCloseFn orig = (VccVfsCloseFn)vcc_vfs_close_orig;- orig(self, _cmd);-}--// Build a CMSampleBuffer wrapping the latest shm frame. Caller must-// CFRelease the result.-static CMSampleBufferRef vcc_build_cmsb_from_shm(void) {- pthread_mutex_lock(&vcc_latest_frame.lock);- uint32_t w = vcc_latest_frame.width;- uint32_t h = vcc_latest_frame.height;- uint32_t bpr = vcc_latest_frame.bytes_per_row;- size_t len = vcc_latest_frame.pixels_length;- if (!len || !w || !h || !bpr) {- pthread_mutex_unlock(&vcc_latest_frame.lock);- return NULL;- }- void *pixels = malloc(len);- if (!pixels) {- pthread_mutex_unlock(&vcc_latest_frame.lock);- return NULL;- }- memcpy(pixels, vcc_latest_frame.pixels, len);- pthread_mutex_unlock(&vcc_latest_frame.lock);-- CVPixelBufferRef pb = NULL;- CVReturn cvr = CVPixelBufferCreateWithBytes(- kCFAllocatorDefault, w, h, kCVPixelFormatType_32BGRA,- pixels, bpr, vcc_cv_release_bytes, NULL, NULL, &pb);- if (cvr != kCVReturnSuccess || !pb) {- free(pixels);- return NULL;- }-- CMVideoFormatDescriptionRef desc = NULL;- OSStatus s = CMVideoFormatDescriptionCreateForImageBuffer(- kCFAllocatorDefault, pb, &desc);- if (s != noErr || !desc) {- CVPixelBufferRelease(pb);- return NULL;- }-- // Monotonic PTS at 30 fps. The viewfinder's internal jitter buffer- // discards frames whose PTS doesn't advance, so we increment per call.- vcc_vf_pts_ns += 33333333ull; // 1/30s in nanoseconds- CMSampleTimingInfo timing = {- .duration = CMTimeMake(1, 30),- .presentationTimeStamp = CMTimeMake((int64_t)vcc_vf_pts_ns, 1000000000),- .decodeTimeStamp = kCMTimeInvalid,- };-- CMSampleBufferRef cmsb = NULL;- s = CMSampleBufferCreateForImageBuffer(- kCFAllocatorDefault, pb, true, NULL, NULL, desc, &timing, &cmsb);- CFRelease(desc);- CVPixelBufferRelease(pb);- if (s != noErr || !cmsb) return NULL;- return cmsb;-}--static void vcc_vf_drive_once(void) {- if (!vcc_vf_streams || vcc_vf_streams.count == 0) return;- CMSampleBufferRef cmsb = vcc_build_cmsb_from_shm();- if (!cmsb) return;- SEL sel = NSSelectorFromString(@"enqueueVideoSampleBuffer:");- for (id stream in [vcc_vf_streams copy]) {- int ret = ((int (*)(id, SEL, CMSampleBufferRef))objc_msgSend)(- stream, sel, cmsb);- vcc_vf_enqueue_count++;- if (ret == 0) vcc_vf_enqueue_success++;- if ((vcc_vf_enqueue_count & 29) == 1) {- vcc_log(@" [VFS drive] enqueue ret=%d (count=%llu ok=%llu)",- ret,- (unsigned long long)vcc_vf_enqueue_count,- (unsigned long long)vcc_vf_enqueue_success);- }- }- CFRelease(cmsb);-}--static void vcc_install_viewfinder_hooks(void) {- Class cls = NSClassFromString(@"FigCameraViewfinderStream");- if (!cls) {- vcc_log(@" VF hook: class missing");- return;- }- SEL init_sel = NSSelectorFromString(@"init");- SEL open_sel = NSSelectorFromString(@"openWithDestination:");- SEL close_sel = NSSelectorFromString(@"close");- Method m;- if ((m = class_getInstanceMethod(cls, init_sel))) {- vcc_vfs_init_orig = method_setImplementation(m, (IMP)vcc_vfs_init_hook);- }- if ((m = class_getInstanceMethod(cls, open_sel))) {- vcc_vfs_open_orig = method_setImplementation(m, (IMP)vcc_vfs_open_hook);- }- if ((m = class_getInstanceMethod(cls, close_sel))) {- vcc_vfs_close_orig = method_setImplementation(m, (IMP)vcc_vfs_close_hook);- }- vcc_log(@" swizzled FigCameraViewfinderStream init/open/close");-- // Drive at 30 Hz. Frames are enqueued only when at least one stream is- // open AND a fresh shm frame exists (covered by build_cmsb_from_shm).- vcc_vf_q = dispatch_queue_create("com.vphone.vcam.vfdrive",- DISPATCH_QUEUE_SERIAL);- vcc_vf_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,- vcc_vf_q);- dispatch_source_set_timer(vcc_vf_timer,- dispatch_time(DISPATCH_TIME_NOW, 0),- 33333333ull, 2000000ull);- dispatch_source_set_event_handler(vcc_vf_timer, ^{- @autoreleasepool { vcc_vf_drive_once(); }- });- dispatch_resume(vcc_vf_timer);- vcc_log(@" viewfinder drive timer armed (30 Hz)");-}--static void vcc_install_sink_observation(void) {- Class iqsn = NSClassFromString(@"BWImageQueueSinkNode");- Class rqsn = NSClassFromString(@"BWRemoteQueueSinkNode");- if (!iqsn || !rqsn) {- vcc_log(@" sink obs: classes missing iqsn=%p rqsn=%p", iqsn, rqsn);- return;- }-- SEL iqsnInit = NSSelectorFromString(- @"initWithHFRSupport:ispJitterCompensationEnabled:"- @"clientAuditToken:sinkID:");- SEL rqsnInit = NSSelectorFromString(- @"initWithMediaType:clientAuditToken:sinkID:cameraInfoByPortType:");- SEL renderSel = @selector(renderSampleBuffer:forInput:);-- vcc_swizzle_method(iqsn, iqsnInit, (IMP)vcc_iqsn_init_hook,- &vcc_iqsn_init_orig);- vcc_swizzle_method(rqsn, rqsnInit, (IMP)vcc_rqsn_init_hook,- &vcc_rqsn_init_orig);- vcc_swizzle_method(iqsn, renderSel, (IMP)vcc_iqsn_render_hook,- &vcc_iqsn_render_orig);- vcc_swizzle_method(rqsn, renderSel, (IMP)vcc_rqsn_render_hook,- &vcc_rqsn_render_orig);-}--// MARK: - BWStillImageSampleBufferSinkNode observation + injection-//-// AVCapturePhotoOutput attaches a sampleBufferAvailableHandler block to the-// still-image sink node; the upstream graph normally drives the node by-// calling -renderSampleBuffer:forInput:, which routes the buffer through-// the node's internal logic and ultimately invokes the handler. Our synth-// has no upstream graph that produces frames, so the handler never fires.-//-// First pass: observe. Hook -setSampleBufferAvailableHandler: and-// -initWithInputMediaType:sinkID: to capture the node + the handler-// block per session, so we can later push a CMSampleBuffer ourselves.--static NSMutableArray *vcc_still_sinks = nil; // strong refs to nodes-static IMP vcc_still_set_handler_orig = NULL;-static IMP vcc_still_init_orig = NULL;-static IMP vcc_still_render_orig = NULL;--typedef id (*VccStillInitFn)(id self, SEL _cmd, id mediaType, id sinkID);-typedef void (*VccStillSetHandlerFn)(id self, SEL _cmd, id handler);-typedef void (*VccStillRenderFn)(id self, SEL _cmd, CMSampleBufferRef sb, id input);--static id vcc_still_init_hook(id self, SEL _cmd, id mediaType, id sinkID) {- VccStillInitFn orig = (VccStillInitFn)vcc_still_init_orig;- id ret = orig(self, _cmd, mediaType, sinkID);- vcc_log(@" [StillSink init] self=%p mediaType=%@ sinkID=%@",- ret, mediaType, sinkID);- if (ret) {- if (!vcc_still_sinks) vcc_still_sinks = [NSMutableArray new];- [vcc_still_sinks addObject:ret];- }- return ret;-}--static void vcc_still_set_handler_hook(id self, SEL _cmd, id handler) {- vcc_log(@" [StillSink setSampleBufferAvailableHandler:] self=%p handler=%p",- self, handler);- VccStillSetHandlerFn orig = (VccStillSetHandlerFn)vcc_still_set_handler_orig;- orig(self, _cmd, handler);-}--static void vcc_still_render_hook(id self,- SEL _cmd,- CMSampleBufferRef sb,- id input) {- vcc_log(@" [StillSink renderSampleBuffer:forInput:] self=%p sb=%p input=%@",- self, sb, input);- VccStillRenderFn orig = (VccStillRenderFn)vcc_still_render_orig;- orig(self, _cmd, sb, input);-}--static void vcc_install_still_sink_observation(void) {- Class cls = NSClassFromString(@"BWStillImageSampleBufferSinkNode");- if (!cls) {- vcc_log(@" still-sink obs: class missing");- return;- }- SEL initSel = NSSelectorFromString(@"initWithInputMediaType:sinkID:");- SEL setHSel = @selector(setSampleBufferAvailableHandler:);- SEL renderSel = @selector(renderSampleBuffer:forInput:);- vcc_swizzle_method(cls, initSel,- (IMP)vcc_still_init_hook, &vcc_still_init_orig);- vcc_swizzle_method(cls, setHSel,- (IMP)vcc_still_set_handler_hook,- &vcc_still_set_handler_orig);- vcc_swizzle_method(cls, renderSel,- (IMP)vcc_still_render_hook, &vcc_still_render_orig);-}--// MARK: - BWFigCaptureSession graph callback observation-//-// AVCaptureSession.startRunning → cameracaptured graph build → start → these-// delegate callbacks fire on BWFigCaptureSession. If start fails (error != 0),-// the daemon reports failure back over XPC and client.isRunning stays NO.-// Hook these to see exactly where in the graph startup the failure occurs.--static IMP vcc_sess_didFinishStarting_orig = NULL;-static IMP vcc_sess_didStartSourceNode_orig = NULL;-static IMP vcc_sess_didPrepare_orig = NULL;--typedef void (*VccSessDidFinishStartingFn)(id self, SEL _cmd, id graph, int error);-typedef void (*VccSessDidStartSourceFn)(id self, SEL _cmd, id graph, id node, int error);-typedef void (*VccSessDidPrepareFn)(id self, SEL _cmd, id graph);--static void vcc_sess_didFinishStarting_hook(id self,- SEL _cmd,- id graph,- int error) {- vcc_log(@" [Sess graph:didFinishStartingWithError:] self=%p graph=%p err=%d",- self, graph, error);- VccSessDidFinishStartingFn orig =- (VccSessDidFinishStartingFn)vcc_sess_didFinishStarting_orig;- orig(self, _cmd, graph, error);-}--static void vcc_sess_didStartSourceNode_hook(id self,- SEL _cmd,- id graph,- id node,- int error) {- vcc_log(@" [Sess graph:didStartSourceNode:error:] self=%p graph=%p node=%@ err=%d",- self, graph, node, error);- VccSessDidStartSourceFn orig =- (VccSessDidStartSourceFn)vcc_sess_didStartSourceNode_orig;- orig(self, _cmd, graph, node, error);-}--static void vcc_sess_didPrepare_hook(id self, SEL _cmd, id graph) {- vcc_log(@" [Sess graphDidPrepareNodes:] self=%p graph=%p", self, graph);- VccSessDidPrepareFn orig =- (VccSessDidPrepareFn)vcc_sess_didPrepare_orig;- orig(self, _cmd, graph);-}--static void vcc_install_session_graph_observation(void) {- Class cls = NSClassFromString(@"BWFigCaptureSession");- if (!cls) {- vcc_log(@" session-graph obs: class missing");- return;- }- vcc_swizzle_method(cls,- @selector(graph:didFinishStartingWithError:),- (IMP)vcc_sess_didFinishStarting_hook,- &vcc_sess_didFinishStarting_orig);- vcc_swizzle_method(cls,- @selector(graph:didStartSourceNode:error:),- (IMP)vcc_sess_didStartSourceNode_hook,- &vcc_sess_didStartSourceNode_orig);- vcc_swizzle_method(cls,- @selector(graphDidPrepareNodes:),- (IMP)vcc_sess_didPrepare_hook,- &vcc_sess_didPrepare_orig);-}--// MARK: - BWFigCaptureSession init capture + pipelines extraction-//-// To splice our manual sink into a real session, we need a handle to its-// FigCaptureSessionPipelines instance. Hook the session's init and, post-orig,-// reach into the _pipelines ivar via KVC. Store globally so the next-stage-// injector has a live reference.--static IMP vcc_sess_initWithFigSess_orig = NULL;-typedef id (*VccSessInitWithFigSessFn)(id self, SEL _cmd, void *figSess);--static id vcc_captured_bw_session = nil; // strong ref to the BWFigCaptureSession-static id vcc_captured_pipelines = nil; // its _pipelines ivar value--__attribute__((ns_returns_retained))-static id vcc_sess_initWithFigSess_hook(id self, SEL _cmd, void *figSess) {- VccSessInitWithFigSessFn orig =- (VccSessInitWithFigSessFn)vcc_sess_initWithFigSess_orig;- id ret = orig(self, _cmd, figSess);- if (ret) {- vcc_captured_bw_session = ret;- @try {- vcc_captured_pipelines = [ret valueForKey:@"pipelines"];- } @catch (NSException *e) {- @try {- vcc_captured_pipelines = [ret valueForKey:@"_pipelines"];- } @catch (NSException *e2) {- vcc_captured_pipelines = nil;- }- }- vcc_log(@" [BWFigCaptureSession init] -> self=%p figSess=%p _pipelines=%p (class=%@)",- ret, figSess, vcc_captured_pipelines,- NSStringFromClass([vcc_captured_pipelines class]));- }- return ret;-}--static void vcc_install_session_init_capture(void) {- Class cls = NSClassFromString(@"BWFigCaptureSession");- if (!cls) {- vcc_log(@" session-init capture: class missing");- return;- }- vcc_swizzle_method(cls,- @selector(initWithFigCaptureSession:),- (IMP)vcc_sess_initWithFigSess_hook,- &vcc_sess_initWithFigSess_orig);-}--// MARK: - BWFigCaptureSession stillImageCoordinator observation-//-// AVCapturePhotoOutput.capturePhoto → daemon-side BWStillImageCaptureCoordinator-// queues a request and fires these delegate callbacks on BWFigCaptureSession.-// If willBegin… fires but didCapture… doesn't, the photo pipeline received-// the request but couldn't satisfy it (typically because no sample buffer-// arrived for it to wrap into a photo).--static IMP vcc_sess_willBeginPhoto_orig = NULL;-static IMP vcc_sess_willBeginPhotoForSettings_orig = NULL;-static IMP vcc_sess_willPreparePhoto_orig = NULL;-static IMP vcc_sess_willCapturePhoto_orig = NULL;-static IMP vcc_sess_didCapturePhoto_orig = NULL;--typedef void (*VccSessWillBeginPhotoFn)(id self, SEL _cmd, id coord, long settingsID);-typedef void (*VccSessSettingsFn)(id self, SEL _cmd, id coord, id settings);-typedef void (*VccSessWillPrepareFn)(id self, SEL _cmd, id coord, id settings, BOOL clientInitiated);-typedef void (*VccSessWillCaptureFn)(id self, SEL _cmd, id coord, id settings, int err);--static void vcc_sess_willBeginPhoto_hook(id self,- SEL _cmd,- id coord,- long settingsID) {- vcc_log(@" [Sess stillImageCoordinator:willBeginCaptureBeforeResolvingSettingsForID:] coord=%p id=%ld",- coord, settingsID);- VccSessWillBeginPhotoFn orig =- (VccSessWillBeginPhotoFn)vcc_sess_willBeginPhoto_orig;- orig(self, _cmd, coord, settingsID);-}--static void vcc_sess_willBeginPhotoForSettings_hook(id self,- SEL _cmd,- id coord,- id settings) {- vcc_log(@" [Sess stillImageCoordinator:willBeginCaptureForSettings:] coord=%p settings=%@",- coord, settings);- VccSessSettingsFn orig =- (VccSessSettingsFn)vcc_sess_willBeginPhotoForSettings_orig;- orig(self, _cmd, coord, settings);-}--static void vcc_sess_willPreparePhoto_hook(id self,- SEL _cmd,- id coord,- id settings,- BOOL clientInitiated) {- vcc_log(@" [Sess stillImageCoordinator:willPrepareStillImageCaptureWithSettings:clientInitiated:] coord=%p settings=%@ ci=%d",- coord, settings, clientInitiated);- VccSessWillPrepareFn orig =- (VccSessWillPrepareFn)vcc_sess_willPreparePhoto_orig;- orig(self, _cmd, coord, settings, clientInitiated);-}--static void vcc_sess_willCapturePhoto_hook(id self,- SEL _cmd,- id coord,- id settings,- int err) {- vcc_log(@" [Sess stillImageCoordinator:willCapturePhotoForSettings:error:] coord=%p settings=%@ err=%d",- coord, settings, err);- VccSessWillCaptureFn orig =- (VccSessWillCaptureFn)vcc_sess_willCapturePhoto_orig;- orig(self, _cmd, coord, settings, err);-}--static void vcc_sess_didCapturePhoto_hook(id self,- SEL _cmd,- id coord,- id settings) {- vcc_log(@" [Sess stillImageCoordinator:didCapturePhotoForSettings:] coord=%p settings=%@",- coord, settings);- VccSessSettingsFn orig =- (VccSessSettingsFn)vcc_sess_didCapturePhoto_orig;- orig(self, _cmd, coord, settings);-}--static void vcc_install_still_coordinator_observation(void) {- Class cls = NSClassFromString(@"BWFigCaptureSession");- if (!cls) {- vcc_log(@" still-coord obs: BWFigCaptureSession missing");- return;- }- vcc_swizzle_method(cls,- @selector(stillImageCoordinator:willBeginCaptureBeforeResolvingSettingsForID:),- (IMP)vcc_sess_willBeginPhoto_hook,- &vcc_sess_willBeginPhoto_orig);- vcc_swizzle_method(cls,- @selector(stillImageCoordinator:willBeginCaptureForSettings:),- (IMP)vcc_sess_willBeginPhotoForSettings_hook,- &vcc_sess_willBeginPhotoForSettings_orig);- vcc_swizzle_method(cls,- @selector(stillImageCoordinator:willPrepareStillImageCaptureWithSettings:clientInitiated:),- (IMP)vcc_sess_willPreparePhoto_hook,- &vcc_sess_willPreparePhoto_orig);- vcc_swizzle_method(cls,- @selector(stillImageCoordinator:willCapturePhotoForSettings:error:),- (IMP)vcc_sess_willCapturePhoto_hook,- &vcc_sess_willCapturePhoto_orig);- vcc_swizzle_method(cls,- @selector(stillImageCoordinator:didCapturePhotoForSettings:),- (IMP)vcc_sess_didCapturePhoto_hook,- &vcc_sess_didCapturePhoto_orig);-}--// MARK: - BWStillImageCoordinatorNode existence detector-//-// If our synth session never instantiates BWStillImageCoordinatorNode, the-// capturePhoto request has nowhere to land. Swizzle its known internal-// method (-_enqueueRequestWithSettings:serviceRequestsIfNecessary:) so we-// detect whether the coordinator exists and ever sees a capture request.--static IMP vcc_still_coord_enqueue_orig = NULL;-typedef void (*VccStillCoordEnqueueFn)(id self, SEL _cmd, id settings, BOOL serviceIfNecessary);--static void vcc_still_coord_enqueue_hook(id self,- SEL _cmd,- id settings,- BOOL serviceIfNecessary) {- vcc_log(@" [StillCoord enqueueRequest] self=%p settings=%@ service=%d",- self, settings, serviceIfNecessary);- VccStillCoordEnqueueFn orig =- (VccStillCoordEnqueueFn)vcc_still_coord_enqueue_orig;- orig(self, _cmd, settings, serviceIfNecessary);-}--static void vcc_install_still_coord_node_observation(void) {- Class cls = NSClassFromString(@"BWStillImageCoordinatorNode");- if (!cls) {- vcc_log(@" still-coord-node obs: class missing");- return;- }- vcc_swizzle_method(cls,- @selector(_enqueueRequestWithSettings:serviceRequestsIfNecessary:),- (IMP)vcc_still_coord_enqueue_hook,- &vcc_still_coord_enqueue_orig);-}--// MARK: - FigCaptureStillImageSinkPipeline init detector-//-// Per CMCapture symbols, the still pipeline is constructed via:-// -[FigCaptureStillImageSinkPipeline initWithConfiguration:captureDevice:-// sourceOutputsByPortType:captureStatusDelegate:inferenceScheduler:-// graph:name:]-// Hook this to see if it's called for our synth session, and what its-// arguments look like. If it's never called, the daemon's graph-build code-// decides upstream that no still pipeline is needed (probably based on a-// source attribute). If it's called and returns nil, we can inspect the-// arguments to figure out which is missing.--static IMP vcc_still_pipe_init_orig = NULL;-typedef id (*VccStillPipeInitFn)(id self,- SEL _cmd,- id config,- id device,- id outputsByPortType,- id captureStatusDelegate,- id inferenceScheduler,- id graph,- id name);--__attribute__((ns_returns_retained))-static id vcc_still_pipe_init_hook(id self,- SEL _cmd,- id config,- id device,- id outputsByPortType,- id captureStatusDelegate,- id inferenceScheduler,- id graph,- id name) {- vcc_log(@" [StillPipe init] self=%p config=%@ device=%@ outputs.count=%lu name=%@",- self, config, device,- (unsigned long)([outputsByPortType respondsToSelector:@selector(count)]- ? [outputsByPortType count] : 0),- name);- VccStillPipeInitFn orig = (VccStillPipeInitFn)vcc_still_pipe_init_orig;- id ret = orig(self, _cmd, config, device, outputsByPortType,- captureStatusDelegate, inferenceScheduler, graph, name);- vcc_log(@" [StillPipe init] -> %p", ret);- return ret;-}--static void vcc_install_still_pipeline_observation(void) {- Class cls = NSClassFromString(@"FigCaptureStillImageSinkPipeline");- if (!cls) {- vcc_log(@" still-pipe obs: class missing");- return;- }- SEL sel = NSSelectorFromString(- @"initWithConfiguration:captureDevice:sourceOutputsByPortType:"- @"captureStatusDelegate:inferenceScheduler:graph:name:");- vcc_swizzle_method(cls, sel, (IMP)vcc_still_pipe_init_hook,- &vcc_still_pipe_init_orig);-}--// MARK: - FigCaptureSessionPipelines.addStillImageSinkPipelineSessionStorage-//-// Per CMCapture symbols, this is the daemon-side method that registers a-// still-image sink pipeline with the session. If captureSession_buildGraph--// WithConfiguration's still-pipeline branch ever runs for our synth source,-// this method gets called. If it's never called for our test, the upstream-// gate (parsed still-image sink configurations array empty?) is what we-// need to address.--static IMP vcc_pipelines_addStill_orig = NULL;-typedef void (*VccPipelinesAddStillFn)(id self, SEL _cmd, id storage);--static void vcc_pipelines_addStill_hook(id self, SEL _cmd, id storage) {- vcc_log(@" [Pipelines addStillImageSinkPipelineSessionStorage:] self=%p storage=%@",- self, storage);- VccPipelinesAddStillFn orig =- (VccPipelinesAddStillFn)vcc_pipelines_addStill_orig;- orig(self, _cmd, storage);-}--static void vcc_install_pipelines_addStill_observation(void) {- Class cls = NSClassFromString(@"FigCaptureSessionPipelines");- if (!cls) {- vcc_log(@" pipelines obs: class missing");- return;- }- vcc_swizzle_method(cls,- @selector(addStillImageSinkPipelineSessionStorage:),- (IMP)vcc_pipelines_addStill_hook,- &vcc_pipelines_addStill_orig);-}--// MARK: - graph-build error suppressors-//-// captureSession_buildGraphWithConfiguration's per-source iteration bails-// to OSStatus -12783 along three known paths on our synth source:-//-// (1) -[FigCaptureCameraSourcePipeline requiresMasterClock] returns YES,-// and the post-iteration check (OR of all pipelines' returns) bails-// on a virtual source that has no real ISP/HW clock.-// (2) _cs_addObjectToStreamsAttributes returns -12783 when an inherited-// ivar slot is NULL (called from _FigVideoCaptureSourcesActivate--// AndCreateDevices during session activation).-// (3) -[BWFigVideoCaptureStream initWithCaptureStream:…] sets *errOut-// = -12783 in its validation-failure path.-//-// (1) is neutralized by rewriting the function's prologue to `mov w0, #0; ret`.-// The function's address is resolved from CMCapture's LC_SYMTAB by name —-// no hardcoded VMA.-//-// (2)+(3) are neutralized by scanning CMCapture's __text for the specific-// MOVN encodings the compiler used to prepare -12783 in w20 / w8, and-// rewriting each to `MOVZ w?, #0`. -12783 is a capture-specific OSStatus-// emitted only by the daemon; over-application is benign because the-// daemon's only consumer in the VM is our synth.--static void vcc_install_csp_requires_master_clock_hook(void) {- vcc_image_t img;- if (vcc_image_resolve(&img, "FigCaptureSourceServerStart") != 0) {- vcc_log(@" graph-build patches: image resolve failed");- return;- }-- // (1) Resolve -[FigCaptureCameraSourcePipeline requiresMasterClock] via- // LC_SYMTAB. The function is called via direct C dispatch (not in the- // objc method table on observed builds, so swizzling won't work), so- // we rewrite its prologue in place. The PAC-signed address from the- // symtab is stripped before the write.- static const char *const kReqMCSyms[] = {- "_-[FigCaptureCameraSourcePipeline requiresMasterClock]",- "-[FigCaptureCameraSourcePipeline requiresMasterClock]",- NULL,- };- uintptr_t reqMC = 0;- for (unsigned i = 0; kReqMCSyms[i]; i++) {- reqMC = vcc_lookup_lc_symtab(&img, kReqMCSyms[i]);- if (reqMC) {- vcc_log(@" requiresMasterClock @ 0x%lx (sym=%s)",- (unsigned long)reqMC, kReqMCSyms[i]);- break;- }- }- if (reqMC) {- uintptr_t target = (uintptr_t)ptrauth_strip(- (void *)reqMC, ptrauth_key_function_pointer);- uint32_t insn0 = ((const uint32_t *)target)[0];- uint32_t insn1 = ((const uint32_t *)target)[1];- // Sanity anchor: the second prologue insn should be pacibsp on every- // arm64e build that signs return addresses. Refuse the patch if it- // isn't — we'd rather skip than rewrite an unrelated function.- if (insn1 != 0xD503237Fu) {- vcc_log(@" requiresMasterClock @ 0x%lx: insn1=0x%08x != pacibsp; skip",- (unsigned long)target, insn1);- } else {- int ok1 = vcc_patch_word(target, insn0, 0x52800000u); // mov w0, #0- int ok2 = vcc_patch_word(target + 4, insn1, 0xd65f03c0u); // ret- vcc_log(@" requiresMasterClock prologue patch @ 0x%lx: %d/%d",- (unsigned long)target, ok1, ok2);- }- } else {- vcc_log(@" requiresMasterClock symbol not in LC_SYMTAB; patch skipped");- }-- // (2) `mov w20, #-12783` (MOVN encoding 0x12863dd4) -> `mov w20, #0`.- vcc_scan_and_patch(&img, 0x12863dd4u, 0x52800014u,- "mov w20, #-12783 -> #0");- // (3) `mov w8, #-12783` (MOVN encoding 0x12863dc8) -> `mov w8, #0`.- vcc_scan_and_patch(&img, 0x12863dc8u, 0x52800008u,- "mov w8, #-12783 -> #0");-}--// MARK: - Sink node injection — manually-constructed BWStillImageSampleBufferSinkNode-//-// The daemon's session graph for our synth source builds without a still-image-// pipeline → no BWStillImageSampleBufferSinkNode exists → capturePhoto can't-// find a sink to deliver to → -11803 "Cannot Record".-//-// Manually construct a BWStillImageSampleBufferSinkNode at install time.-// Observation pass: prove the class accepts initialization in our daemon-// context. Next iteration adds the wiring path so capturePhoto sees this-// sink and delivers our shm frame through it.--static id vcc_synth_still_sink = nil;--static void vcc_construct_still_sink(void) {- Class cls = NSClassFromString(@"BWStillImageSampleBufferSinkNode");- if (!cls) {- vcc_log(@" manual still-sink: class missing");- return;- }- // Per ipsw symaddr the simpler init is -[BWStillImageSampleBufferSinkNode- // initWithSinkID:] at static 0x1ae333e20. The full init takes inputMediaType- // + sinkID. Try the simpler one first.- SEL sinkIdInit = NSSelectorFromString(@"initWithSinkID:");- id sinkID = @(0xCAFEBABEull); // synthetic sinkID, unique to us- id alloced = ((id (*)(Class, SEL))objc_msgSend)(cls, @selector(alloc));- if (!alloced) {- vcc_log(@" manual still-sink: alloc returned nil");- return;- }- if (![alloced respondsToSelector:sinkIdInit]) {- vcc_log(@" manual still-sink: doesn't respond to %@",- NSStringFromSelector(sinkIdInit));- // Don't init — leak the alloced bytes (cheaper than crashing)- return;- }- @try {- vcc_synth_still_sink =- ((id (*)(id, SEL, id))objc_msgSend)(alloced, sinkIdInit, sinkID);- } @catch (NSException *e) {- vcc_log(@" manual still-sink: init exception: %@", e);- return;- }- vcc_log(@" manual still-sink: created %p (class=%@)",- vcc_synth_still_sink,- NSStringFromClass([vcc_synth_still_sink class]));- if (!vcc_synth_still_sink) return;-- // Probe properties to make sure we got a usable instance.- @try {- SEL hdlrGet = @selector(sampleBufferAvailableHandler);- if ([vcc_synth_still_sink respondsToSelector:hdlrGet]) {- id existing =- ((id (*)(id, SEL))objc_msgSend)(vcc_synth_still_sink, hdlrGet);- vcc_log(@" manual still-sink: initial sampleBufferAvailableHandler=%p",- existing);- } else {- vcc_log(@" manual still-sink: no -sampleBufferAvailableHandler");- }- } @catch (NSException *e) {- vcc_log(@" manual still-sink: probe exception: %@", e);- }-- // Synthesize a sampleBufferAvailableHandler block and set it on our sink.- //- // Per disasm of -[BWStillImageSampleBufferSinkNode renderSampleBuffer:forInput:]- // at static 0x1ae577428, the block invoke at 0x1ae57758c-590 takes:- // x0 = block (auto)- // x1 = CMSampleBufferRef sampleBuffer- // x2 = BOOL flag (always 0 at this site)- // x3 = [x21 requestedSettings] (presumably the AVCapturePhotoSettings)- //- // We don't yet have a real XPC reply path; this handler is currently a- // logging probe that lets us verify our manually-installed handler does- // fire when we drive -renderSampleBuffer:forInput: ourselves.- SEL setHandlerSel = @selector(setSampleBufferAvailableHandler:);- if ([vcc_synth_still_sink respondsToSelector:setHandlerSel]) {- void (^block)(CMSampleBufferRef, BOOL, id) =- ^(CMSampleBufferRef sbuf, BOOL flag, id requestedSettings) {- vcc_log(@" [SyntheticHandler] sbuf=%p flag=%d settings=%@",- sbuf, flag, requestedSettings);- // Extract the image data and write to disk as proof of pipeline integrity.- if (!sbuf) return;- CVImageBufferRef pb = CMSampleBufferGetImageBuffer(sbuf);- if (!pb) {- vcc_log(@" [SyntheticHandler] no image buffer");- return;- }- CVPixelBufferLockBaseAddress(pb, kCVPixelBufferLock_ReadOnly);- size_t w = CVPixelBufferGetWidth(pb);- size_t h = CVPixelBufferGetHeight(pb);- size_t bpr = CVPixelBufferGetBytesPerRow(pb);- OSType fmt = CVPixelBufferGetPixelFormatType(pb);- vcc_log(@" [SyntheticHandler] pb=%p w=%zu h=%zu bpr=%zu fmt=0x%x",- pb, w, h, bpr, (unsigned)fmt);- // Write the raw BGRA bytes to disk for verification.- // ${TMPDIR}-style path — use /var/mobile/Library/vphone-synth-photo.raw- // (writable by mobile uid). If that fails, /tmp is also acceptable.- const char *out_path = "/var/mobile/Library/vphone-synth-photo.bgra";- uint8_t *base = (uint8_t *)CVPixelBufferGetBaseAddress(pb);- if (base) {- int fd = open(out_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);- if (fd >= 0) {- for (size_t y = 0; y < h; y++) {- (void)write(fd, base + y * bpr, w * 4);- }- close(fd);- vcc_log(@" [SyntheticHandler] wrote %s (%zu bytes)",- out_path, w * h * 4);- } else {- vcc_log(@" [SyntheticHandler] open(%s) failed: %d", out_path, errno);- }- }- CVPixelBufferUnlockBaseAddress(pb, kCVPixelBufferLock_ReadOnly);- };- @try {- ((void (*)(id, SEL, id))objc_msgSend)(vcc_synth_still_sink,- setHandlerSel, block);- vcc_log(@" manual still-sink: installed synthetic handler block");- } @catch (NSException *e) {- vcc_log(@" manual still-sink: setHandler exception: %@", e);- }- // Verify the handler was stored- @try {- id stored = ((id (*)(id, SEL))objc_msgSend)(- vcc_synth_still_sink, @selector(sampleBufferAvailableHandler));- vcc_log(@" manual still-sink: post-set sampleBufferAvailableHandler=%p",- stored);- } @catch (NSException *e) {- vcc_log(@" manual still-sink: getHandler exception: %@", e);- }- } else {- vcc_log(@" manual still-sink: doesn't respond to setSampleBufferAvailableHandler:");- }-}--// Trigger-the-handler probe: call -renderSampleBuffer:forInput: on our-// synth sink directly with a synthetic CMSampleBuffer built from-// vcc_latest_frame. If our manually-installed handler fires, we have-// proven the synthetic-handler approach works at the API level.-static void vcc_drive_still_sink_once(void) {- if (!vcc_synth_still_sink) return;- CMSampleBufferRef sbuf = vcc_build_cmsb_from_shm();- if (!sbuf) {- vcc_log(@" still-drive: no shm frame yet");- return;- }- SEL renderSel = @selector(renderSampleBuffer:forInput:);- if (![vcc_synth_still_sink respondsToSelector:renderSel]) {- vcc_log(@" still-drive: sink doesn't respond to renderSampleBuffer:forInput:");- CFRelease(sbuf);- return;- }- vcc_log(@" still-drive: calling renderSampleBuffer: on sink %p with sbuf=%p",- vcc_synth_still_sink, sbuf);- @try {- ((void (*)(id, SEL, CMSampleBufferRef, id))objc_msgSend)(- vcc_synth_still_sink, renderSel, sbuf, nil);- vcc_log(@" still-drive: render call returned");- } @catch (NSException *e) {- vcc_log(@" still-drive: render exception: %@", e);- }- CFRelease(sbuf);-}-// MARK: - FigCaptureSessionParsedConfiguration observation-//-// This is the daemon-side parser that converts the XPC session config into-// the structured configuration the graph builder uses. After init,-// _parsedStillImageSinkConfigurations is populated; if empty, no still-// pipeline will be built.--static IMP vcc_parsed_cfg_init_orig = NULL;-typedef id (*VccParsedCfgInitFn)(id self,- SEL _cmd,- id sessionCfg,- BOOL clientSetsUserInitiated,- id restrictions);--__attribute__((ns_returns_retained))-static id vcc_parsed_cfg_init_hook(id self,- SEL _cmd,- id sessionCfg,- BOOL clientSetsUserInitiated,- id restrictions) {- VccParsedCfgInitFn orig = (VccParsedCfgInitFn)vcc_parsed_cfg_init_orig;- id ret = orig(self, _cmd, sessionCfg, clientSetsUserInitiated, restrictions);- if (ret) {- id stillCfgs = nil;- @try {- stillCfgs = [ret valueForKey:@"parsedStillImageSinkConfigurations"];- } @catch (NSException *e) {- stillCfgs = nil;- }- id cameraCfgs = nil;- @try {- cameraCfgs = [ret valueForKey:@"parsedCameraSourceConfigurations"];- } @catch (NSException *e) {- cameraCfgs = nil;- }- vcc_log(@" [ParsedCfg init] -> %p stillCfgs.count=%lu cameraCfgs.count=%lu",- ret,- (unsigned long)(stillCfgs && [stillCfgs respondsToSelector:@selector(count)]- ? [stillCfgs count] : 0),- (unsigned long)(cameraCfgs && [cameraCfgs respondsToSelector:@selector(count)]- ? [cameraCfgs count] : 0));- if (cameraCfgs && [cameraCfgs respondsToSelector:@selector(count)]- && [cameraCfgs count] > 0) {- vcc_log(@" [ParsedCfg] cameraCfgs[0] class=%@",- NSStringFromClass([[cameraCfgs firstObject] class]));- }- if (stillCfgs && [stillCfgs respondsToSelector:@selector(count)]- && [stillCfgs count] > 0) {- id stillCfg = [stillCfgs firstObject];- vcc_log(@" [ParsedCfg] stillCfgs[0] class=%@ desc=%@",- NSStringFromClass([stillCfg class]), stillCfg);- // Dump the still cfg's properties — what does it tell the graph builder?- id connConfigs = nil, primaryConnConfig = nil, movieCfg = nil, pointCfg = nil;- @try { connConfigs = [stillCfg valueForKey:@"stillImageConnectionConfigurations"]; } @catch (NSException *e) {}- @try {- primaryConnConfig = [stillCfg valueForKey:@"primaryStillImageConnectionConfiguration"];- } @catch (NSException *e) {}- @try { movieCfg = [stillCfg valueForKey:@"movieFileVideoConnectionConfiguration"]; } @catch (NSException *e) {}- @try { pointCfg = [stillCfg valueForKey:@"pointCloudDataConnectionConfiguration"]; } @catch (NSException *e) {}- vcc_log(@" [ParsedCfg] stillCfgs[0].connCfgs=%@",- connConfigs ?: @"(nil)");- vcc_log(@" [ParsedCfg] stillCfgs[0].primary=%@", primaryConnConfig ?: @"(nil)");- // Also dump the camera source config to see what source it's bound to- id cameraCfg = [cameraCfgs firstObject];- id sourceID = nil, deviceType = nil, captureDeviceID = nil;- @try { sourceID = [cameraCfg valueForKey:@"sourceID"]; } @catch (NSException *e) {}- @try { deviceType = [cameraCfg valueForKey:@"sourceDeviceType"]; } @catch (NSException *e) {}- @try { captureDeviceID = [cameraCfg valueForKey:@"captureDeviceID"]; } @catch (NSException *e) {}- vcc_log(@" [ParsedCfg] cameraCfg sourceID=%@ deviceType=%@ captureDeviceID=%@",- sourceID ?: @"(nil)", deviceType ?: @"(nil)",- captureDeviceID ?: @"(nil)");- }- }- return ret;-}--static void vcc_install_parsed_cfg_observation(void) {- Class cls = NSClassFromString(@"FigCaptureSessionParsedConfiguration");- if (!cls) {- vcc_log(@" parsed-cfg obs: class missing");- return;- }- SEL sel = NSSelectorFromString(- @"initWithSessionConfiguration:clientSetsUserInitiatedCaptureRequestTime:restrictions:");- vcc_swizzle_method(cls, sel, (IMP)vcc_parsed_cfg_init_hook,- &vcc_parsed_cfg_init_orig);-}--// MARK: - shared-frame reader--// The latest frame copied out of the vphoned-published shm. Mutated only-// from the reader callback thread; readers (AVF stream production, next-// stage) take the lock for the brief duration of a copy.-// (struct vcc_latest_frame_s is forward-declared above as vcc_latest_frame_t-// for use by the viewfinder injection code.)--vcc_latest_frame_t vcc_latest_frame = {- .lock = PTHREAD_MUTEX_INITIALIZER,-};--static const uint8_t *vcc_shm_base = NULL;-static uint64_t vcc_last_seq_seen = 0;-static uint64_t vcc_frames_received = 0;--static int vcc_shm_map(void) {- int fd = open(VCC_SHM_PATH, O_RDONLY);- if (fd < 0) {- vcc_log(@" shm open(%s) failed: %s", VCC_SHM_PATH, strerror(errno));- return -1;- }- struct stat st;- if (fstat(fd, &st) < 0 || st.st_size < (off_t)VCC_SHM_HEADER_SIZE) {- vcc_log(@" shm fstat failed or undersized");- close(fd);- return -1;- }- void *base = mmap(NULL, VCC_SHM_TOTAL_SIZE, PROT_READ,- MAP_SHARED, fd, 0);- close(fd);- if (base == MAP_FAILED) {- vcc_log(@" shm mmap failed: %s", strerror(errno));- return -1;- }- vcc_shm_base = (const uint8_t *)base;- vcc_log(@" shm mapped %s -> %p", VCC_SHM_PATH, vcc_shm_base);- return 0;-}--// Read the latest frame with seq-stability discipline. Returns 1 on a-// fresh frame, 0 if seq hasn't advanced since last call or a read tore.-static int vcc_shm_read_latest(void) {- if (!vcc_shm_base) return 0;- const vcc_shm_header_t *hdr = (const vcc_shm_header_t *)vcc_shm_base;-- uint64_t seq_a = atomic_load_explicit(- (const _Atomic uint64_t *)&hdr->seq, memory_order_acquire);- if (seq_a == vcc_last_seq_seen) return 0;- if (seq_a & 1ull) return 0; // writer in progress-- uint32_t w = hdr->width;- uint32_t h = hdr->height;- uint32_t bpr = hdr->bytes_per_row;- uint32_t fmt = hdr->pixel_format;- uint64_t idx = hdr->frame_index;- uint32_t pix_len = hdr->pixels_length;-- if (pix_len == 0 || pix_len > VCC_SHM_MAX_PIXELS) return 0;- if (w == 0 || h == 0 || bpr == 0 || pix_len < (size_t)bpr * h) return 0;-- pthread_mutex_lock(&vcc_latest_frame.lock);- if (vcc_latest_frame.pixels_capacity < pix_len) {- free(vcc_latest_frame.pixels);- vcc_latest_frame.pixels = (uint8_t *)malloc(pix_len);- vcc_latest_frame.pixels_capacity =- vcc_latest_frame.pixels ? pix_len : 0;- }- if (vcc_latest_frame.pixels) {- memcpy(vcc_latest_frame.pixels,- vcc_shm_base + VCC_SHM_HEADER_SIZE, pix_len);- vcc_latest_frame.pixels_length = pix_len;- vcc_latest_frame.width = w;- vcc_latest_frame.height = h;- vcc_latest_frame.bytes_per_row = bpr;- }- pthread_mutex_unlock(&vcc_latest_frame.lock);-- // Re-check seq after copy. If it advanced past our snapshot+1 we may- // have torn — but the writer always sets even seq AFTER pixel write,- // so seeing the same even seq means our copy was clean.- uint64_t seq_b = atomic_load_explicit(- (const _Atomic uint64_t *)&hdr->seq, memory_order_acquire);- if (seq_b != seq_a) return 0;-- vcc_last_seq_seen = seq_a;- vcc_frames_received++;- if ((vcc_frames_received & 29) == 1) {- vcc_log(@" shm frame #%llu (idx=%llu) w=%u h=%u bpr=%u fmt=0x%08x",- (unsigned long long)vcc_frames_received,- (unsigned long long)idx, w, h, bpr, fmt);- }- return 1;-}--static void vcc_start_frame_receiver(void) {- if (vcc_shm_map() < 0) {- vcc_log(@" frame receiver disabled (shm not available yet)");- return;- }- // Subscribe to vphoned's notification. Each fire = one frame ready.- int token = -1;- dispatch_queue_t q =- dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0);- uint32_t status = notify_register_dispatch(- VCC_NOTIFY_NAME, &token, q,- ^(__unused int t) {- @autoreleasepool {- (void)vcc_shm_read_latest();- }- });- if (status != NOTIFY_STATUS_OK) {- vcc_log(@" notify_register_dispatch(%s) failed: %u",- VCC_NOTIFY_NAME, status);- return;- }- vcc_log(@" subscribed to %s (token=%d)", VCC_NOTIFY_NAME, token);-}+// The implementation remains one translation unit because these hooks share+// private runtime state and order-sensitive symbol declarations. Each include+// owns one capture subsystem; none becomes a public dylib interface.+#include "VCamImageResolution.inc"+#include "VCamSourceInstallation.inc"+#include "VCamCaptureObservation.inc"+#include "VCamSyntheticDevice.inc"+#include "VCamSyntheticStreams.inc"+#include "VCamViewfinderHooks.inc"+#include "VCamSessionHooks.inc"+#include "VCamStillSink.inc"+#include "VCamFrameReceiver.inc"// MARK: - constructor