Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Let Xcode's DeviceHub show a guest's screen

Jacky62b388d85f31
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 7413d59d..2e2966b6 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -565,6 +565,7 @@ do NOT execute these).
| 23 | No binary change: `libvcamcaptured.dylib`, which SystemHook already loads into `cameracaptured`, rewrites the `bl PrewarmThreadSafeSBPs` in `__FigCapturePreloadShadersInternal_block_invoke_2` to `nop` in the daemon's own memory. This runs from the dylib's constructor and only when the paravirtual Metal driver is installed — **all bases** | none (guest dylib `VPhoneGuestComponents/VCamCaptured/Prewarm/`, installed at `/usr/lib/libvcamcaptured.dylib`) | **Stop `cameracaptured` crashing at every boot, and the SpringBoard freeze that follows.** At launch the daemon preloads its shaders. `PrewarmThreadSafeSBPs` runs each video processor's `-prewarm`, and NRFV3's reaches `-[ToneMappingCurves initWithWithContext:]`, which fills textures made from a shared `MTLHeap` with `-replaceRegion:…`. The cloudOS 26.4 `AppleParavirtGPUMetalIOGPUFamily` never sets `_dimension` (a texture's CPU layout) in `-initWithHeap:resource:offset:length:descriptor:`, and `-replaceRegion:` loads it unchecked, so the daemon faults with `KERN_INVALID_ADDRESS` at `0xc` (measured on `iPad16,1 26.6.2 (23G90)`, `standard`: launchd at `successive crashes = 6`). While the daemon crash-loops, SpringBoard's main thread blocked in a synchronous XPC to it as soon as an app started recording. The daemon does have a Metal device, so `kernel-exp-paravirt_user_clients` does not help. Prewarming is only an optimisation, and nothing waits on that function: no return value, no global, no signal. The rest of the preload (processor flags, data migration, and the deferred shader cache copy, whose semaphore deferred processing waits on) is kept. The call site is found from the exported `FigCapturePreloadShaders`: its `b` to the internal function, that function's one `adrp/add/pacia x16` block invoke, then the block's one `ldr x0, [xN, #0x20]; bl` into CMCapture's `__text`. That gives `0x1aeb2fd68` on 23G90 and `0x1b0759d10` on 24A435. Any mismatch leaves the prewarm in place and logs the step that failed. Host test: `make -C VPhoneGuestComponents test-vcam-prewarm`. Validation: `vcamcaptured.log` has `gpu prewarm: … skipped`, no new `cameracaptured` crash report, and `successive crashes = 0`. See `Research/Guest/gpu_acceleration.md` ("Heap Textures Have No CPU Layout"). | Y | Y | Y |
| 24 | No binary change: both spawn hooks insert `libbatteryhealthfix.dylib` into `Settings` (`/Applications/Preferences.app/Preferences`) beside SystemHook, where it interposes `IOPSCopyPowerSourcesInfo`, `IOPSCopyPowerSourcesByType`, `IOPSCopyPowerSourcesByTypePrecise`, `notify_register_check` / `notify_get_state` / `notify_cancel` and `MGGetBoolAnswer` — **all bases** | none (new guest dylib `VPhoneGuestComponents/BatteryHealthFix/libbatteryhealthfix.c`, installed at `/usr/lib/libbatteryhealthfix.dylib`) | **Stop Settings → Battery → Battery Health & Charging loading forever.** The VM's battery is Virtualization.framework's synthetic power source (charge and connectivity only), and the health half of a real battery's description comes from AppleSmartBattery, which no VM has. Measured on `iPhone17,3 27.0 (24A435)`: powerd's internal battery description has one `BatteryPacks` entry holding only `PackID`, `Cycle count` and `Transport Type`, no `Battery Service State`/`Flags` or `Maximum Capacity Percent` anywhere, and `com.apple.thermalmonitor.ageAwareMitigationState` stays 0. `-[BatteryHealthUIController specifiers]` asks `-[BatteryHealthUIInformation batteryDataUnavailable]`, which answers YES while `+getManagementState` is 0, while no pack parses (`-[BatteryHealthUIPackInformation initWithPowerSourceInformation:]` drops a pack without service flags and state), or while the overall genuine status is -1 — and it is -1 because `MGGetBoolAnswer("D6/BMDrlb8V3WSiqL8gL+w")` (HasBatteryModuleAuth, `+[PLGestaltUtilities hasBatteryModuleAuth]`) answers 1 on the guest, sending `+genuineBatteryStatusForPackIndex:` to an `AppleBatteryAuth`/`AppleAuthCPRelay` service that does not exist. The controller then shows its global spinner and re-asks on a timer. iPadOS 26.6.2 (23G90) has the same gate in `+[BatteryUIResourceClass batteryDataUnavailable]`, reading the flat keys of `IOPSCopyPowerSourcesByType`'s array, the same notify name and the same MobileGestalt key. The hook answers as a new battery without battery authentication: each internal-battery description is copied with `Battery Service State` 0, `Battery Service Flags` 0, `Maximum Capacity Percent` 100 and `Cycle count` 0 at the top level, and each of powerd's packs (or one new pack) completed with a `BatteryHealth` dictionary of the same three numbers plus `Date of manufacture`/`Date of first use` (the birth time of `/private/var/mobile`, i.e. the restore); keys already present are never replaced, and a description that already has them is passed through. A mitigation state of 0 on a token registered for the age-aware name reads as 2 ("supporting normal peak performance"). HasBatteryModuleAuth reads as no only while `IOServiceGetMatchingService("AppleBatteryAuth")` finds nothing. Interposing reaches the callers because `BatteryUsageUI.bundle` is a standalone Mach-O bound through dyld's interposing table (cache-to-cache calls are not; see `MISFix/MISFixSignature.c`), and inserting it — rather than SystemHook `dlopen`ing it like row 21 — is what puts the table in place before the bundle loads. `vpInsertedLibraryFor` in `Shared/InjectionEnvironment.h` picks it or libmisfix for a path; the two target sets do not overlap. Ships with `system-launchdaemons-boot-environment`; existing guests get it from the vphoned environment update on their next start with the new bundle (offline `cfw update-environment` only replaces libraries a VM already has). launchd starts Settings itself, so it is the launchd hook that inserts it: a guest updated only by that online sync needs one more reboot before launchd runs the new hook, which the update already reports as `reboot_required`; an offline environment update replaces the hook before boot. **Validated (2026-10-04, `bhtest-iphone`, `iPhone17,3 27.0 (24A435)` + cloudOS 26.4):** before, the page showed only the spinner and the two charging switches; after, Maximum Capacity 100%, Peak Performance Capability "Your battery is currently supporting normal peak performance", the two switches, no spinner; the hook's log shows all three answers taken once per process. Re-checked on the final bundle after a reboot of the same guest, with the launchd hook logging `inserted+batteryhealthfix` for each Settings launch. **iPad16,1 26.6.2 (23G90), `bhtest-ipad`, created with the new bundle:** the hook is inserted and stays inert, and Settings runs without a crash; that iPad has no Battery Health page at all, because `-[BatteryUIController setUpBatteryHealthGroup]` offers the row only on an iPhone or, through `+[PLBatteryUIBackendModel shouldShowModifiedHealthController]`, on an iPad that supports the fixed charge limit with the `PerfPowerServices/battery_health_details` feature on — the model decides, as on hardware. The 26.x gate inside the page is from static analysis; no 26.x iPhone image was at hand to run it. | Y | Y | Y |
| 25 | No binary change: `libvcamcaptured.dylib` stops every other thread in `cameracaptured` (`task_threads` + `thread_suspend`, self excluded, one patcher at a time) around each `vcc_patch_word` / `vcc_patch_two_nops` text rewrite — **all bases** | none (guest dylib `VPhoneGuestComponents/VCamCaptured/Image/VCamCodePatch.m`, installed at `/usr/lib/libvcamcaptured.dylib`) | **Stop the hook's own runtime patching from crashing `cameracaptured`, which froze the whole VM when the camera was opened.** The hook rewrites CMCapture shared-cache `__text` through `vm_protect(RW|COPY)` → write → `vm_protect(RX)`; for the whole flip the 16K page carries no execute permission, and the pages it touches (the `-12783` error-code sites, the master-clock gate, the prewarm call) are live XPC server code. Two crash reports caught a thread fetching an instruction in a page mid-flip while the patching thread was in `vcc_patch_word` on the same boot: `ipad-mini-01` `cameracaptured-2026-10-03-045638.ips` died in `__FigFlashlightGetClassID_block_invoke` on `com.apple.coremedia.flashlight(34)-messages`, and `ipad-pro-13` `cameracaptured-2026-10-04-225558.ips` died in `captureSourceServer_handleRegisterNotificationForProprietaryDefaultChangesMessage` on `com.apple.coremedia.capturesource(523)-messages` — the register-for-source-changes XPC that camera enumeration itself sends. Both are `EXC_BAD_ACCESS (SIGBUS)`, `KERN_PROTECTION_FAILURE` on an instruction fetch, in a region snapshotted `r-x/rwx`, `SM=COW` (the rwx max-protection is the flip's fingerprint). The card: with row 23 removing the boot crash, any later `cameracaptured` restart (jetsam, another crash) while a camera client reconnects sends its first XPCs straight into the +3 s reinstall window; one SIGBUS → launchd throttles → every AVCapture client, SpringBoard's main thread included, blocks forever in a synchronous XPC — the "VM 卡死" report of 2026-10-05. The stopped section is exactly two `vm_protect` calls, the word write and `sys_icache_invalidate`: no locks, no allocation, no logging, so a frozen thread holding any userspace lock cannot deadlock the patcher; every `vcc_log` moved after the resume, and a mutex serialises patchers (constructor prewarm patch vs the +3 s install block). All five runtime text-patching call sites (`vcc_scan_and_patch` ×2, the prewarm NOP, the session-hook pair, the source-installation NOPs) funnel through the two fixed functions. Validation: kill-and-relaunch stress with Camera.app auto-reconnecting (the same collision that produced both crashes) produces no new `cameracaptured` crash report, and the boot log's `patch_word OK` lines are unchanged. See `Research/Guest/virtual_camera_transport.md` ("The patch race that froze the whole VM"). | Y | Y | Y |
+| 26 | No binary change: both spawn hooks insert `libdevicehubfix.dylib` into `cryptexd` and the DDI's `dtremotedisplayd`. In `cryptexd` it interposes `fcntl` and reports an `EPERM` from `F_SETPROTECTIONCLASS` as `ENOTSUP`; in `dtremotedisplayd` it interposes `MediaStreamSupportedFeatures.current` (answers `0x8c`) and `CurrentDevice.isCustomerRestricted` (answers false) from the DDI's `CoreDeviceUtilities` — **all bases** | none (new guest dylib `VPhoneGuestComponents/DeviceHubFix/libdevicehubfix.c`, installed at `/usr/lib/libdevicehubfix.dylib`) | **Let Xcode 27's DeviceHub show the guest's screen.** On iOS 27 `cryptexd` stages each DDI asset with `open(O_RDWR)` + `fcntl(F_SETPROTECTIONCLASS, 4)` and accepts only `ENOTSUP` as a failure; a guest answers `EPERM` (`set protection class: [1: Operation not permitted]`, `staging failed`), so CoreDevice shows the device as "connected (no DDI)" for good. With the DDI mounted, DeviceHub asks `dtremotedisplayd` for its media stream features and gets 0 from CoreDeviceUtilities' policy: `isCustomerRestricted` (`isProductionFused && !hasInternalOSBuild && hasInternalDDI == false`) refuses every pre-27.0 device, and remote control is limited to iPhone, Apple Watch and Apple TV, which refuses every iPad. `0x8c` is what a Mac host reports for itself (mirrored primary display 0x4, system audio 0x8, display information 0x80). Interposing reaches all three because `cryptexd`, `dtremotedisplayd` and `CoreDeviceUtilities` are standalone images; the two Swift symbols are weak flat-namespace imports, resolving to nothing in `cryptexd`. Ships with `system-launchdaemons-boot-environment`; an existing guest gets it from the environment update. Details: `Research/Guest/devicehub_screen_viewing.md`. **Validated (2026-10-06):** `dhtest-ipad`, `iPad16,1 26.6.2 (23G90)`: DeviceHub receives `supportedFeatures: 140`, `MediaStreamStart` succeeds and the window shows the live home screen. `dhtest-iphone27`, `iPhone17,3 27.0.1 (24A446)`: the DDI mounts (`F_SETPROTECTIONCLASS EPERM, reported as ENOTSUP`), features 140, `MediaStreamStart` succeeds, but the view stays black — backboardd logs `display 2 get_wireless_surface_options returned error` and `swap_end returned error 10000003` for the capture display; not solved here. | Y | Y | Y |
### Swift port status — the eight DSC patchers (2026-09-23)
diff --git a/Research/Guest/devicehub_screen_viewing.md b/Research/Guest/devicehub_screen_viewing.md
new file mode 100644
index 00000000..b414a834
--- /dev/null
+++ b/Research/Guest/devicehub_screen_viewing.md
@@ -0,0 +1,166 @@
+# DeviceHub screen viewing
+
+Xcode 27 ships `DeviceHub.app` (`Xcode.app/Contents/Applications`, bundle id
+`com.apple.dt.Devices`). It lists vphone guests as "iPad / iPhone — Virtual
+Machine" and, for a paired guest with its developer disk image mounted, opens
+a live view of the screen. Before the fix the view spun forever for every
+guest, 26.x and 27.x alike, and a second window reported "Connection timed
+out". The two versions stop at different places: a 27.x guest never mounts
+the DDI, and a 26.x guest mounts it and then reports no media stream
+features.
+
+Measured with Xcode 27.0 (27A266a), CoreDevice 642.16, on `iPad16,1 26.6.2
+(23G90)` and `iPhone17,3 27.0.1 (24A446)` guests over cloudOS 26.4.
+
+## iOS 27: the DDI does not mount
+
+CoreDevice personalizes the cryptex DDI (TSS succeeds) and hands it to the
+guest, then nothing more happens; the device stays "connected (no DDI)" and
+DeviceHub logs `No providers can handle Display ID: 1 … (bootState: Booted,
+ddi: false)`. The guest's `cryptexd` says why:
+
+```text
+[protex] set protection class: [1: Operation not permitted]
+[protex] copy asset: im4m: [1: Operation not permitted]
+[protex] copy assets failed: [1: Operation not permitted]
+[codex] system: staging failed [1: Operation not permitted]
+```
+
+In `__protex_stage_continue` (`/usr/libexec/cryptexd`, 27.0.1) each staged
+asset is opened `O_RDWR` and given class D with
+`fcntl(fd, F_SETPROTECTIONCLASS, 4)`; a failure other than `ENOTSUP` (45)
+aborts staging. The guest returns `EPERM`. `cryptexd` already treats
+`ENOTSUP` as a filesystem without protection classes, so the hook reports
+this one `EPERM` as `ENOTSUP`. iOS 26 guests mount the DDI without it.
+
+## Where a mounted guest stops
+
+DeviceHub asks the device for its media stream features before it starts a
+stream (`MediaStreamGetSupportInfoActionDeclaration`, forwarded to the device
+feature `com.apple.coredevice.feature.getmediasupportinfo`). It repeats the
+question with backoff (1 s, 2 s, 4 s … 30 s) until the answer is non-empty.
+A guest answers every time with
+
+```text
+SupportInfo: supportedFeatures: 0 (No supported features are available: (Raw Value: 0),
+ avcFrameworkVersion: Optional("2215.5.1"), coreDeviceVersion: nil)
+```
+
+and DeviceHub logs `No framebuffer provider found for Display ID: 1 —
+creators tried: [… AVConferenceDisplayViewFramebufferProviderCreator=
+canProvideView:false …]`. The Mac side's own features are fine
+(`found supported features: Primary video display mirrored output stream,
+System audio output stream, Display information (Raw Value: 140)`).
+
+`devicectl device capture screen-record` is a separate feature
+(`com.apple.coredevice.feature.screenrecording`) that a guest does not list,
+so it is not a way around this.
+
+## The device side
+
+The answer comes from the DDI's `dtremotedisplayd`
+(`/System/Developer/usr/libexec/dtremotedisplayd`, LaunchDaemon
+`com.apple.coredevice.dtremotedisplayd`, user `mobile`). Its remote service
+`com.apple.coredevice.displayservice` carries `getmediasupportinfo`,
+`getmediastreamserverstatus`, `startaudiooutput`, `startvideooutput`,
+`startmediastream` and `stopmediastream`. It returns
+`MediaStreamSupportedFeatures.current` from the DDI's
+`CoreDeviceUtilities.framework`
+(`$s19CoreDeviceUtilities28MediaStreamSupportedFeaturesV7currentACvgZ`).
+
+`current` builds a `CurrentDevice` and calls
+`forDeviceInfo(osBuildUpdate:platform:deviceType:isVirtualDevice:mode:isProductionFused:hasInternalOSBuild:hasInternalDDI:)`.
+Its log strings name the policies; none of them is a capability check:
+
+- `Remote control restricted. Device is customer-restricted (production
+ fused, customer OS, customer DDI) and running pre-27.0 OS (major: …).
+ Returning no supported features.` The predicate
+ `CurrentDevice.isCustomerRestricted(isProductionFused:hasInternalOSBuild:hasInternalDDI:)`
+ disassembles to `isProductionFused && !hasInternalOSBuild &&
+ hasInternalDDI == false`. Every 26.x guest is refused here.
+- `Remote control is only available on iOS 27.0, watchOS 27.0, or tvOS 27.0
+ or later.` — shown when the device is not an iPhone, Apple Watch or Apple
+ TV. Every iPad guest is refused here whatever its version.
+- a per-build table (`MediaStreamSupportedFeatures.MinimumVersions`) keyed by
+ build, platform and device type, which also takes `isVirtualDevice`.
+
+The guest does not persist the info-level `inputs:` line, and the hook
+replaces the answer on every version, so the branch a 27.x iPhone guest
+would take on its own was not observed.
+
+Feature bits (`MediaStreamSupportedFeatures` static getters):
+
+| Bit | Meaning |
+| --- | --- |
+| `0x4` | primary display mirrored output (screen sharing) |
+| `0x8` | system audio output |
+| `0x40` | virtual external / secondary virtual display output |
+| `0x80` | display information |
+| `0x100` | video output by display ID |
+| `0x200` | screenshot capture |
+
+## The fix
+
+`VPhoneGuestComponents/DeviceHubFix/libdevicehubfix.c`, installed as
+`/usr/lib/libdevicehubfix.dylib`, is inserted by both spawn hooks into
+`cryptexd` and `dtremotedisplayd` only (`vpIsDeviceHubFixTarget` in
+`Shared/InjectionEnvironment.h`). In `cryptexd` it interposes `fcntl` as
+above. In `dtremotedisplayd` it interposes two getters:
+
+- `MediaStreamSupportedFeatures.current` answers `0x8c`, the features a Mac
+ host reports for itself. The struct is resilient (the framework is built
+ for library evolution), so the getter returns it indirectly through `x8`;
+ the replacement is three instructions of assembly. The host intersects the
+ answer with its own features.
+- `CurrentDevice.isCustomerRestricted` answers false.
+
+Interposing works because both `dtremotedisplayd` and `CoreDeviceUtilities`
+are DDI images, not shared-cache ones, so dyld binds their imports through the
+interposing table. The imports are weak flat-namespace symbols (`-Wl,-U`),
+because neither image is in the SDK.
+
+The stream itself is AVConference screen capture inside the guest. It needs
+nothing else: once the answer is non-empty DeviceHub's
+`MediaStreamStartActionDeclaration` succeeds for audio and video and the view
+shows the live screen.
+
+## Validation
+
+**`dhtest-ipad`, `iPad16,1 26.6.2 (23G90)` (2026-10-06):** prototype pushed
+through the environment update (built in the `libbatteryhealthfix.dylib` slot,
+with a SystemHook that inserted that slot into `dtremotedisplayd`). The hook's
+log showed `features=0x8c current=interposed isCustomerRestricted=interposed`.
+DeviceHub then received `supportedFeatures: 140 (Primary video display
+mirrored output stream, System audio output stream, Display information)`,
+`MediaStreamStart` returned success, and the window opened with
+`devices://device/open?id=<CoreDevice identifier>` showed the guest's home
+screen live. The user's own 26.6.2 iPad, without the hook, kept answering 0
+throughout.
+
+The same day, on the built bundle (`2.6.1-local`, bound with `vm set-bundle
+--update-environment`): after a cold start SystemHook logged
+`dtremotedisplayd decision=inserted+devicehubfix` and the view came up again.
+
+**`dhtest-iphone27`, `iPhone17,3 27.0.1 (24A446)` (2026-10-06):** without the
+hook the DDI never mounted (above). With it `cryptexd` logged
+`F_SETPROTECTIONCLASS EPERM, reported as ENOTSUP` once, CoreDevice showed the
+device as `connected` with DDI services, DeviceHub received 140 and
+`MediaStreamStart` succeeded — and the view stayed black while the guest's own
+screen was on and unlocked.
+
+## Open: a black view on iOS 27
+
+During the 27.0.1 stream backboardd logs, about fifty times a second,
+
+```text
+[WindowServer] display 2 get_wireless_surface_options returned error e00002d5 / e00002be
+[WindowServer] display 2 swap_end returned error 10000003
+```
+
+Display 2 is the capture display the stream adds; the 26.6.2 iPad logs none of
+this while streaming. The frames die in the IOMobileFramebuffer swap path for
+that display, the same layer rows 9 and 11 of
+`Research/0_binary_patch_comparison.md` patch for the main display
+(`_kern_SwapEnd`, the `_IOMobileFramebufferSwap*` trampolines). That is where
+the next step starts. A `locationd` crash (`EXC_ARM_PAC_FAIL`) on the same
+guest predates the hook and does not involve it.
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Environment.swift b/VPhoneDaemon/Daemon/GuestAPI+Environment.swift
index 6dca2b90..bee7ea57 100644
--- a/VPhoneDaemon/Daemon/GuestAPI+Environment.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI+Environment.swift
@@ -17,6 +17,7 @@ extension GuestAPI {
"libmisfix.dylib",
"libhapticsfix.dylib",
"libbatteryhealthfix.dylib",
+ "libdevicehubfix.dylib",
]
static let environmentStaging = "/var/root/Library/Caches/vphone-environment"
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
index 4efa1421..59310e17 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
@@ -173,8 +173,11 @@ public enum FirmwareGuestSystemPatchSet {
and into lockdownd and remoted, which tell the host a configured UDID. It also \
ships libhapticsfix.dylib, which SystemHook loads into SpringBoard so UIKit's \
feedback engine takes the no-haptics path instead of crashing on the VM's absent \
- haptic hardware, and libbatteryhealthfix.dylib, inserted into Settings, which gives \
- the virtual battery the health record Battery Health waits for.
+ haptic hardware, libbatteryhealthfix.dylib, inserted into Settings, which gives \
+ the virtual battery the health record Battery Health waits for, and \
+ libdevicehubfix.dylib, inserted into cryptexd, which then stages the iOS 27 \
+ developer disk image, and into the image's dtremotedisplayd, which then reports \
+ the media stream features Xcode's DeviceHub needs to show the screen.
""",
target: .guestFile(path: "/Library/LaunchDaemons"),
bootEssential: true,
diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
index 3e93d5a6..ad3b04a4 100755
--- a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
+++ b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
@@ -75,6 +75,7 @@ fi
/bin/cp "$guest_products/misfix/libmisfix.plist" "$guest/libmisfix.plist"
/bin/cp "$guest_products/hapticsfix/libhapticsfix.dylib" "$guest/libhapticsfix.dylib"
/bin/cp "$guest_products/batteryhealthfix/libbatteryhealthfix.dylib" "$guest/libbatteryhealthfix.dylib"
+/bin/cp "$guest_products/devicehubfix/libdevicehubfix.dylib" "$guest/libdevicehubfix.dylib"
/bin/cp "$guest_products/gpu/libAppleParavirtCompilerPluginIOGPUFamily.dylib" \
"$guest/libAppleParavirtCompilerPluginIOGPUFamily.dylib"
# The HAL plugin is a bundle, signed whole by the Makefile; copied as a tree so
diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
index 0e18f844..d34f369f 100755
--- a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
+++ b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
@@ -88,7 +88,7 @@ for preset in "$resources/patches_presets/"*.plist; do
done
for name in vphoned launchdhook-vphone.dylib SystemHook-vphone.dylib libcamfix.dylib \
- libvcamcaptured.dylib libmisfix.dylib libhapticsfix.dylib libbatteryhealthfix.dylib \
+ libvcamcaptured.dylib libmisfix.dylib libhapticsfix.dylib libbatteryhealthfix.dylib libdevicehubfix.dylib \
libAppleParavirtCompilerPluginIOGPUFamily.dylib; do
require_signed_macho "$guest/$name"
done
diff --git a/VPhoneGuestComponents/DeviceHubFix/libdevicehubfix.c b/VPhoneGuestComponents/DeviceHubFix/libdevicehubfix.c
new file mode 100644
index 00000000..0fd14185
--- /dev/null
+++ b/VPhoneGuestComponents/DeviceHubFix/libdevicehubfix.c
@@ -0,0 +1,151 @@
+// libdevicehubfix.c — let Xcode's DeviceHub show a vphone guest's screen.
+//
+// DeviceHub (Xcode 27) views a device through the developer disk image's
+// dtremotedisplayd. Two things stop it on a vphone guest, one per process.
+//
+// ## cryptexd: the DDI does not mount on iOS 27
+//
+// On iOS 27 the DDI is a cryptex, and cryptexd stages its assets before it
+// grafts them. For each one it opens the staged copy and asks for data
+// protection class D:
+//
+// fd = open(path, O_RDWR);
+// if (fcntl(fd, F_SETPROTECTIONCLASS, 4) == -1 && errno != ENOTSUP)
+// fail; // "set protection class: %{darwin.errno}d"
+//
+// A guest answers EPERM, so staging fails ("copy asset: im4m: [1: Operation
+// not permitted]", "system: staging failed") and CoreDevice reports the
+// device as "connected (no DDI)" for good. Measured on iPhone17,3 27.0.1
+// (24A446). iOS 26 guests mount the DDI without this.
+//
+// cryptexd already accepts a filesystem that does not do protection classes
+// (ENOTSUP). An EPERM from F_SETPROTECTIONCLASS is reported as ENOTSUP, so it
+// takes that path; every other fcntl, and every other failure, is untouched.
+//
+// ## dtremotedisplayd: no media stream features
+//
+// Before it starts a stream, DeviceHub asks the device which media stream
+// features it has (MediaStreamGetSupportInfo) and keeps asking, with backoff,
+// until the answer is non-empty. A guest always answers
+//
+// SupportInfo: supportedFeatures: 0 (No supported features are available),
+// avcFrameworkVersion: "2215.5.1"
+//
+// so the viewer spins forever. dtremotedisplayd takes the answer from
+// `MediaStreamSupportedFeatures.current` in the DDI's CoreDeviceUtilities
+// (CoreDevice-642.16, Xcode 27A266a), whose policy refuses, among others:
+//
+// "Remote control restricted. Device is customer-restricted (production
+// fused, customer OS, customer DDI) and running pre-27.0 OS" — every
+// 26.x guest: `CurrentDevice.isCustomerRestricted` is
+// `isProductionFused && !hasInternalOSBuild && hasInternalDDI == false`.
+// "Remote control is only available on iOS 27.0, watchOS 27.0, or tvOS
+// 27.0 or later … the device is not an iPhone, Apple Watch, or Apple TV"
+// — every iPad guest, whatever its version.
+//
+// Neither is a capability check. The stream itself is AVConference screen
+// capture inside the guest, which does not ask either of them.
+//
+// The getter is interposed to answer with the features a Mac host offers
+// (primary display mirrored video, system audio and display information), and
+// `isCustomerRestricted`, which dtremotedisplayd also reads, answers no. The
+// host still intersects the answer with its own features, so asking for more
+// than the Mac can take changes nothing.
+//
+// ## Reach
+//
+// The interposes reach both callers because cryptexd, dtremotedisplayd and
+// CoreDeviceUtilities are standalone images, not shared-cache ones: dyld binds
+// their imports through the interposing table. CoreDeviceUtilities is on the
+// DDI and not in the SDK, so its two symbols are weak flat-namespace imports;
+// in cryptexd they resolve to nothing and dyld skips those entries. The spawn
+// hooks insert this into those two processes only — `vpIsDeviceHubFixTarget`
+// in Shared/InjectionEnvironment.h.
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdarg.h>
+#include <stdatomic.h>
+#include <stdio.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+// The features a Mac host reports for itself (raw 0x8c): primary display
+// mirrored output 0x4, system audio output 0x8, display information 0x80.
+#define VP_DEVICEHUB_FEATURES 0x8c
+
+#define VP_STRINGIFY_(value) #value
+#define VP_STRINGIFY(value) VP_STRINGIFY_(value)
+
+// MARK: - Log
+
+// dtremotedisplayd runs as mobile and cryptexd as root; the mode keeps a root
+// writer of the same log from silencing later ones, as in SystemHook.
+static void vpLog(const char *format, const char *a, const char *b) {
+ int fd = open("/var/mobile/Library/Caches/vphone-devicehubfix.log",
+ O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0666);
+ if (fd < 0)
+ return;
+ fchmod(fd, 0666);
+ dprintf(fd, "pid=%d ", getpid());
+ dprintf(fd, format, a, b);
+ dprintf(fd, "\n");
+ close(fd);
+}
+
+// MARK: - cryptexd
+
+static int vpFcntl(int fd, int command, ...) {
+ va_list arguments;
+ va_start(arguments, command);
+ void *argument = va_arg(arguments, void *);
+ va_end(arguments);
+ int result = fcntl(fd, command, argument);
+ if (result == -1 && command == F_SETPROTECTIONCLASS && errno == EPERM) {
+ static atomic_int logged;
+ if (!atomic_exchange(&logged, 1))
+ vpLog("F_SETPROTECTIONCLASS %s, reported as %s", "EPERM", "ENOTSUP");
+ errno = ENOTSUP;
+ }
+ return result;
+}
+
+// MARK: - dtremotedisplayd
+
+// static MediaStreamSupportedFeatures.current.getter
+// MediaStreamSupportedFeatures is a resilient struct (the framework is built
+// for library evolution), so the getter returns it indirectly through x8.
+extern void vpOriginalCurrentFeatures(void)
+ __asm__("_$s19CoreDeviceUtilities28MediaStreamSupportedFeaturesV7currentACvgZ") __attribute__((weak_import));
+// CurrentDevice.isCustomerRestricted.getter -> Bool
+extern void vpOriginalIsCustomerRestricted(void)
+ __asm__("_$s19CoreDeviceUtilities07CurrentB0V20isCustomerRestrictedSbvg") __attribute__((weak_import));
+
+__attribute__((naked)) static void vpCurrentFeatures(void) {
+ __asm__ volatile("mov x9, #" VP_STRINGIFY(VP_DEVICEHUB_FEATURES) "\n"
+ "str x9, [x8]\n"
+ "ret\n");
+}
+
+__attribute__((naked)) static void vpIsCustomerRestricted(void) {
+ __asm__ volatile("mov w0, #0\n"
+ "ret\n");
+}
+
+__attribute__((constructor)) static void vpLogLoad(void) {
+ if (vpOriginalCurrentFeatures || vpOriginalIsCustomerRestricted)
+ vpLog("media stream features=" VP_STRINGIFY(VP_DEVICEHUB_FEATURES) " current=%s isCustomerRestricted=%s",
+ vpOriginalCurrentFeatures ? "interposed" : "absent",
+ vpOriginalIsCustomerRestricted ? "interposed" : "absent");
+}
+
+int vphone_devicehubfix_version(void) { return 1; }
+
+__attribute__((used, section("__DATA,__interpose"))) static const struct {
+ const void *replacement;
+ const void *replacee;
+} vpInterpose[] = {
+ {(const void *)vpFcntl, (const void *)fcntl},
+ {(const void *)vpCurrentFeatures, (const void *)vpOriginalCurrentFeatures},
+ {(const void *)vpIsCustomerRestricted, (const void *)vpOriginalIsCustomerRestricted},
+};
diff --git a/VPhoneGuestComponents/LaunchHook/launchdhook-vphone.c b/VPhoneGuestComponents/LaunchHook/launchdhook-vphone.c
index 22dcee17..37c95d6a 100644
--- a/VPhoneGuestComponents/LaunchHook/launchdhook-vphone.c
+++ b/VPhoneGuestComponents/LaunchHook/launchdhook-vphone.c
@@ -93,15 +93,16 @@ static int vpSpawnWith(VPSpawnFunction spawn, pid_t *restrict pid, const char *r
if (!path || strcmp(path, "/sbin/launchd") == 0)
return spawn(pid, path, actions, attributes, argv, envp);
// launchd starts some jobs itself rather than through xpcproxy — SpringBoard
- // is one — so the MIS and battery health hooks have to be decided here as
- // well as in SystemHook.
+ // is one — so the MIS, battery health and DeviceHub hooks have to be
+ // decided here as well as in SystemHook.
const char *library = vpInsertedLibraryFor(path);
VPInjectionEnvironment injected = vpInsertHooks(envp, vpBootRoot, library);
int status = spawn(pid, path, actions, attributes, argv, injected.values ? injected.values : envp);
if (bootstrapProgram || appProgram || library || strcmp(path, "/usr/libexec/xpcproxy") == 0) {
const char *event = !injected.values ? "unchanged" :
library && strcmp(library, VP_MIS_FIX) == 0 ? "inserted+misfix" :
- library ? "inserted+batteryhealthfix" :
+ library && strcmp(library, VP_BATTERY_HEALTH_FIX) == 0 ? "inserted+batteryhealthfix" :
+ library ? "inserted+devicehubfix" :
vpInjectionDisabled(envp) ? "inserted-tweaks-disabled" : "inserted";
vpLogInjection(event, path, status);
vpLogSpawn(event, path, status == 0 && pid ? *pid : -1, status);
diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefile
index 6e7ba173..025db09f 100644
--- a/VPhoneGuestComponents/Makefile
+++ b/VPhoneGuestComponents/Makefile
@@ -56,6 +56,15 @@ HAPTICSFIX_INCLUDES := $(wildcard HapticsFix/*.h)
BATTERYHEALTHFIX := $(STAGE)/batteryhealthfix/libbatteryhealthfix.dylib
BATTERYHEALTHFIX_SOURCES := $(wildcard BatteryHealthFix/*.c)
BATTERYHEALTHFIX_INCLUDES := $(wildcard BatteryHealthFix/*.h)
+# CoreDeviceUtilities lives on the developer disk image, not in the SDK, and
+# the image is mounted only after the host enables developer services. The two
+# interposed Swift getters are weak flat-namespace imports.
+DEVICEHUBFIX := $(STAGE)/devicehubfix/libdevicehubfix.dylib
+DEVICEHUBFIX_SOURCES := $(wildcard DeviceHubFix/*.c)
+DEVICEHUBFIX_INCLUDES := $(wildcard DeviceHubFix/*.h)
+DEVICEHUBFIX_DYNAMIC_LOOKUP_SYMS := \
+ '-Wl,-U,_$$s19CoreDeviceUtilities28MediaStreamSupportedFeaturesV7currentACvgZ' \
+ '-Wl,-U,_$$s19CoreDeviceUtilities07CurrentB0V20isCustomerRestrictedSbvg'
GPU_PLUGIN := $(STAGE)/gpu/libAppleParavirtCompilerPluginIOGPUFamily.dylib
GPU_PLUGIN_SOURCES := $(wildcard GraphicLoader/*.mm)
GPU_PLUGIN_INCLUDES := $(wildcard GraphicLoader/*.h GraphicLoader/*.hpp GraphicLoader/*.inc)
@@ -89,7 +98,7 @@ GPU_DYNAMIC_LOOKUP_SYMS := \
VIRTIOSOUND := $(STAGE)/virtiosound/VPhoneVirtIOSound.driver
VIRTIOSOUND_SOURCES := $(wildcard VirtIOSound/*.m VirtIOSound/*.c)
VIRTIOSOUND_INCLUDES := $(wildcard VirtIOSound/*.h) VirtIOSound/Info.plist VirtIOSound/AudioServerDriver.tbd
-ARTIFACTS := $(CAMFIX) $(VCAMCAPTURED) $(LAUNCHHOOK) $(SYSTEMHOOK) $(MISFIX) $(HAPTICSFIX) $(BATTERYHEALTHFIX) $(GPU_PLUGIN) $(VIRTIOSOUND)
+ARTIFACTS := $(CAMFIX) $(VCAMCAPTURED) $(LAUNCHHOOK) $(SYSTEMHOOK) $(MISFIX) $(HAPTICSFIX) $(BATTERYHEALTHFIX) $(DEVICEHUBFIX) $(GPU_PLUGIN) $(VIRTIOSOUND)
PLISTS := $(STAGE)/camfix/libcamfix.plist $(STAGE)/vcamcaptured/libvcamcaptured.plist \
$(STAGE)/misfix/libmisfix.plist
GPU_PROVENANCE := $(STAGE)/gpu/README.md
@@ -104,7 +113,7 @@ gpu: $(GPU_PLUGIN)
package: all
@rm -f $(ARCHIVE)
- @/usr/bin/tar -cf $(ARCHIVE) -C $(STAGE) camfix vcamcaptured launchhook systemhook misfix hapticsfix batteryhealthfix gpu virtiosound
+ @/usr/bin/tar -cf $(ARCHIVE) -C $(STAGE) camfix vcamcaptured launchhook systemhook misfix hapticsfix batteryhealthfix devicehubfix gpu virtiosound
@echo "Packaged $(ARCHIVE)"
test-loader-links:
@@ -153,7 +162,7 @@ test-vcam-dataplane:
-framework CoreGraphics
@$(OUT)/VCamDataPlaneTests
-$(STAGE)/camfix $(STAGE)/vcamcaptured $(STAGE)/launchhook $(STAGE)/systemhook $(STAGE)/misfix $(STAGE)/hapticsfix $(STAGE)/batteryhealthfix $(STAGE)/gpu $(STAGE)/virtiosound:
+$(STAGE)/camfix $(STAGE)/vcamcaptured $(STAGE)/launchhook $(STAGE)/systemhook $(STAGE)/misfix $(STAGE)/hapticsfix $(STAGE)/batteryhealthfix $(STAGE)/devicehubfix $(STAGE)/gpu $(STAGE)/virtiosound:
@mkdir -p $@
$(CAMFIX): $(CAMFIX_SOURCES) $(CAMFIX_INPUTS) | $(STAGE)/camfix
@@ -208,6 +217,13 @@ $(BATTERYHEALTHFIX): $(BATTERYHEALTHFIX_SOURCES) $(BATTERYHEALTHFIX_INCLUDES) Ba
-Wl,-not_for_dyld_shared_cache
@codesign --force --sign - $@
+$(DEVICEHUBFIX): $(DEVICEHUBFIX_SOURCES) $(DEVICEHUBFIX_INCLUDES) DeviceHubFix | $(STAGE)/devicehubfix
+ $(CLANG) $(GUEST_C_FLAGS) -dynamiclib \
+ -install_name /usr/lib/libdevicehubfix.dylib \
+ -o $@ $(DEVICEHUBFIX_SOURCES) $(DEVICEHUBFIX_DYNAMIC_LOOKUP_SYMS) \
+ -Wl,-not_for_dyld_shared_cache
+ @codesign --force --sign - $@
+
$(STAGE)/misfix/libmisfix.plist: MISFix/libmisfix.plist | $(STAGE)/misfix
@cp $< $@
diff --git a/VPhoneGuestComponents/Shared/InjectionEnvironment.h b/VPhoneGuestComponents/Shared/InjectionEnvironment.h
index 8ad769b9..dad69c6b 100644
--- a/VPhoneGuestComponents/Shared/InjectionEnvironment.h
+++ b/VPhoneGuestComponents/Shared/InjectionEnvironment.h
@@ -80,11 +80,30 @@ static const char *vpBatteryHealthFixFor(const char *path) {
: NULL;
}
+// The DeviceHub hook, which lets Xcode's device viewer stream the guest's
+// screen; see DeviceHubFix/libdevicehubfix.c. Inserted because its
+// interposes have to be in place when the target's imports are bound.
+#define VP_DEVICEHUB_FIX "/usr/lib/libdevicehubfix.dylib"
+
+// cryptexd, which stages and grafts the developer disk image, and the DDI's
+// display server. The DDI is mounted under /System/Developer, so the
+// suffixes are matched like the other targets.
+static int vpIsDeviceHubFixTarget(const char *path) {
+ return path && (vpPathHasSuffix(path, "/usr/libexec/cryptexd") ||
+ vpPathHasSuffix(path, "/usr/libexec/dtremotedisplayd"));
+}
+
+static const char *vpDeviceHubFixFor(const char *path) {
+ return vpIsDeviceHubFixTarget(path) && access(VP_DEVICEHUB_FIX, R_OK) == 0 ? VP_DEVICEHUB_FIX : NULL;
+}
+
// The one library, if any, the spawn hooks insert beside SystemHook for
-// `path`. The MIS and battery health targets do not overlap.
+// `path`. The MIS, battery health and DeviceHub targets do not overlap.
static const char *vpInsertedLibraryFor(const char *path) {
const char *library = vpMISFixFor(path);
- return library ? library : vpBatteryHealthFixFor(path);
+ if (!library)
+ library = vpBatteryHealthFixFor(path);
+ return library ? library : vpDeviceHubFixFor(path);
}
typedef struct {
diff --git a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
index 410c23d7..4cc70ddf 100644
--- a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
+++ b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
@@ -100,12 +100,13 @@ static void vpPrepareLoaderLink(const char *path) {
static VPInjectionEnvironment vpPrepareChild(const char *path, char *const envp[], const char *kind) {
const int misFix = vpIsMISFixTarget(path);
const int batteryHealthFix = vpIsBatteryHealthFixTarget(path);
+ const int deviceHubFix = vpIsDeviceHubFixTarget(path);
VPInjectionEnvironment injected = vpInsertHooks(envp, getenv("VPHONE_JB_ROOT"), vpInsertedLibraryFor(path));
- if (vpIsInjectionTarget(path) || misFix) {
+ if (vpIsInjectionTarget(path) || misFix || deviceHubFix) {
vpPrepareLoaderLink(path);
char decision[96];
snprintf(decision, sizeof(decision), "%s%s%s%s", kind, !injected.values ? "unchanged" : "inserted",
- misFix ? "+misfix" : batteryHealthFix ? "+batteryhealthfix" : "",
+ misFix ? "+misfix" : batteryHealthFix ? "+batteryhealthfix" : deviceHubFix ? "+devicehubfix" : "",
vpInjectionDisabled(envp) ? "-tweaks-disabled" : "");
vpLogSpawn(path, decision);
}
diff --git a/VPhoneGuestComponents/Tests/InjectionEnvironmentTests.c b/VPhoneGuestComponents/Tests/InjectionEnvironmentTests.c
index 97bc529f..eca6b49b 100644
--- a/VPhoneGuestComponents/Tests/InjectionEnvironmentTests.c
+++ b/VPhoneGuestComponents/Tests/InjectionEnvironmentTests.c
@@ -61,12 +61,27 @@ static void namesTheBatteryHealthFixTarget(void) {
assert(!vpInsertedLibraryFor(NULL));
}
+static void namesTheDeviceHubFixTarget(void) {
+ // The developer disk image is mounted under /System/Developer.
+ assert(vpIsDeviceHubFixTarget("/System/Developer/usr/libexec/dtremotedisplayd"));
+ assert(vpIsDeviceHubFixTarget("/usr/libexec/dtremotedisplayd"));
+ assert(vpIsDeviceHubFixTarget("/usr/libexec/cryptexd"));
+ assert(!vpIsDeviceHubFixTarget("/usr/libexec/cryptexdx"));
+ assert(!vpIsDeviceHubFixTarget("/System/Developer/usr/libexec/dtremotedisplaydx"));
+ assert(!vpIsDeviceHubFixTarget("/System/Developer/usr/libexec/remoted"));
+ assert(!vpIsDeviceHubFixTarget(NULL));
+ assert(!vpIsMISFixTarget("/System/Developer/usr/libexec/dtremotedisplayd"));
+ assert(!vpIsMISFixTarget("/usr/libexec/cryptexd"));
+ assert(!vpIsBatteryHealthFixTarget("/System/Developer/usr/libexec/dtremotedisplayd"));
+}
+
int main(void) {
insertsBoth();
addsExtraBesideAnExistingHook();
leavesACompleteEnvironmentAlone();
namesTheMISFixTargets();
namesTheBatteryHealthFixTarget();
+ namesTheDeviceHubFixTarget();
puts("InjectionEnvironmentTests: ok");
return 0;
}
diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift
index 71710a2f..fcbc115f 100644
--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift
+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift
@@ -14,5 +14,6 @@ public enum VPhoneGuestEnvironment {
"libmisfix.dylib",
"libhapticsfix.dylib",
"libbatteryhealthfix.dylib",
+ "libdevicehubfix.dylib",
]
}