Run a virtual iPhone on an Apple Silicon Mac.
Swift
Skip cameracaptured's GPU prewarm on the paravirtual Metal driver
Jacky88552e1ecf1f
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 7a52e312..5a7fb9ab 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -60,3 +60,4 @@ jobs:run: |make -C VPhoneGuestComponents test-loader-linksmake -C VPhoneGuestComponents test-vcam-dataplane+ make -C VPhoneGuestComponents test-vcam-prewarmdiff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex b5b608c3..ac13e96b 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -527,6 +527,7 @@ do NOT execute these).| 20 | No binary change: the launchd hook inserts `libmisfix.dylib` into `SpringBoard` at spawn, beside SystemHook, and both spawn hooks do the same for `installd`, `misagent`, `lockdownd` and `remoted` (the last two for the UDID override only) — **all bases** | none (the guest environment's `launchdhook-vphone.dylib` and `SystemHook-vphone.dylib`) | **Let an installed developer-signed app launch.** SpringBoard validates the app with MIS again before launch and, on a hacktivated guest, fails row 17's `checkTrustAndAuthorization` with `0xE8008026` ("Unable to Verify App"). The hook's `MISValidateSignatureAndCopyInfoWithProgress` detour passes `RespectUppTrustAndAuthorization = false`, so the check is never called — row 17's effect with no shared-cache write, which is what makes it usable on 27.0. launchd starts SpringBoard itself rather than through xpcproxy, so the libraries it gets are the launchd hook's choice; that hook now asks the same `vpIsMISFixTarget` SystemHook does. `MISFixInstallPolicy` stays out of it. No declaration of its own: it ships with `system-launchdaemons-boot-environment`. A load-command version (`/mf` alias, `LC_SOURCE_VERSION` dropped) was committed and reverted the same day. See "One route for libmisfix, SpringBoard included (2026-09-30)" below. | Y | Y | Y || 21 | No binary change: SystemHook `dlopen`s `libhapticsfix.dylib` into `SpringBoard` at startup, where it replaces every `CHHapticEngine` initialiser's IMP so the initialiser returns nil — **all bases** | none (new guest dylib `VPhoneGuestComponents/HapticsFix/libhapticsfix.c`, installed at `/usr/lib/libhapticsfix.dylib`) | **Stop SpringBoard dying the first time UIKit plays a haptic.** The VM has no haptic device — Virtualization.framework exposes none on any base — and a real device without one gets nil from `CHHapticEngine`'s initialisers, so UIKit runs with no feedback, as on every non-Pro iPad. A guest reporting an iPad Pro model instead has an OS that *expects* the haptic stack, and CoreHaptics treats its absence as an internal error: measured on `iPad16,1 26.6.2 (23G90)`, 4h14m after launch, the first feedback event ran `-[_UIFeedbackCoreHapticsIgnoreCaptureHapticsOnlyEngine _internal_createCoreHapticsEngine]` → `-[CHHapticEngine initWithAudioSession:sessionIsShared:options:error:]` → `createHapticPlayerWithOptions:` → `Haptic_RaiseException` → `objc_exception_throw`, and the unwind resumed at an address inside a `---/---` Memory Tag 255 COW region next to the commpage — `EXC_BAD_ACCESS (SIGBUS)`, `KERN_PROTECTION_FAILURE`, a dead SpringBoard. The hook restores the no-hardware answer before UIKit can reach an initialiser: the constructor `dlopen`s CoreHaptics (it is not loaded that early, and the class must be in the runtime before UIKit asks), then `method_setImplementation` on every selector that is `init` or `init` + uppercase part — covering `initWithAudioSession:sessionIsShared:options:error:` today and any renamed sibling on other bases — with one IMP that ignores its arguments and returns nil, the framework's own answer on haptic-less hardware. Scope is SpringBoard only (`vpIsSpringBoard` in SystemHook, loaded before the app/bootstrap gate that would otherwise return first): it is the one UIKit process measured creating the haptics-only engine without asking CoreHaptics first, and apps that follow the documented `capabilitiesForHardware` path already answer no on the guest. Loaded like the camera hooks rather than inserted like libmisfix because interposing must be in place at launch while a method swizzle just has to run before first use; `DISABLE_TWEAKS` and safe mode skip it with everything else SystemHook loads. Ships with `system-launchdaemons-boot-environment`; existing guests receive it through the vphoned environment update (a missing file reports no hash, which is what triggers the push) and need a respring, which is deliberately the caller's call. See `VPhoneGuestComponents/HapticsFix/libhapticsfix.c`. | Y | Y | Y || 22 | No binary change: `libvcamcaptured.dylib` (already loaded into `cameracaptured` by SystemHook) wraps `+[FigCaptureSourceBackingsProvider sharedCaptureSourceBackingsProvider]` from its constructor; when the original returns nil it returns a microphone-only provider instead — **iOS 26.6+ layout, measured on iOS 27.0** | none (`VPhoneGuestComponents/VCamCaptured/Microphone/VCamMicrophoneSource.m`) | **Give an audio-only `AVCaptureSession` its microphone on a guest with no camera.** The built-in sources come from one provider that CMCapture builds only after `BWFigCaptureDeviceVendor` creates the `Default` camera device; a VM has no ISP plugin, so `Cannot create device without create function!`, -12786, `Wiping com.apple.cameracapture.volatile`, and no provider — the microphone, described by the same `AVCaptureSession.plist` call, is lost with the camera, and iOS 27 Voice Memos fails with `CaptureSessionRecorderError` 1 (`failedToCreateAudioDevice`). The wrapper feeds the exported `FigCaptureCreateSourceInfoArrayFromDeviceAndModelSpecificPlist` a NULL device and the shipped product plist (the guest's own `VPHONE600` has none; `D47` on the iPhone17,3 image) reduced to its `"soun"` entries, without persisting, and builds the provider with `-initWithSourceInfoDictionaries:commonSettings:`. A provider the daemon built itself passes through untouched. While that provider is in use, the same dylib also makes `-[AudioRemixSessionManager startNewSessionBlocking]` report success (0) without building the SoundAnalysis Audio Mix session, whose neural net faults cameracaptured 2 s into every spatial recording on the guest (`BNNSGraphContextMakeStreaming`, `KERN_INVALID_ADDRESS 0x300`). Success, not an error: `BWAudioRemixAnalysisMetadataNode` forwards a Stop marker on its metadata output only when the next session starts, and an error there left the movie-file sink waiting forever (measured with the first version, which returned -16992). With no session the node passes audio through and the Audio Mix metadata track is written without samples. It also logs the level of the audio passing the node. `VCamCaptured/Microphone/VCamMicrophoneRemix.m`. See `Research/Guest/ios27_capture_microphone_source.md`. | Y | Y | Y |+| 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 |### Swift port status — the eight DSC patchers (2026-09-23)@@ -2598,8 +2599,8 @@ the records the reference was taken from.**Why.** On an iPadOS 26.6.2 guest with the old `standard`, `cameracaptured`crash-loops at every boot: its shader prewarm (`FigCapturePreloadShadersInternal`-→ CMCapture `PrewarmThreadSafeSBPs` → NRFV3 `-[NRFProcessorV3 prewarm]`) is-refused the GPU at this gate and dies with SIGSEGV at `0xc` inside+→ CMCapture `PrewarmThreadSafeSBPs` → NRFV3 `-[NRFProcessorV3 prewarm]`)+dies with SIGSEGV at `0xc` inside`AppleParavirtGPUMetalIOGPUFamily`. While it crash-loops, the first process totouch the AVCapture defaults blocks on a synchronous XPC to it; when a guest appstarts recording that is SpringBoard's main thread (Control Center's sensor@@ -2608,6 +2609,12 @@ indicator → `AVCaptureDeviceDiscoverySession` →UI freezes, `audiomxd`'s recording `StartIO` waits 18 s, and the first recordingafter boot fails.+**Corrected the same day:** this gate was not the cause. `cameracaptured`+already has a Metal device; it dies on a bug in the paravirtual driver's heap+textures, and row 23 of the CFW table (`libvcamcaptured` skipping the+prewarm) is what stops it. The allowlist stays on for daemons and tools that+want the GPU (#22).+**What it widens, and why that is acceptable.** Every process whose sandboxrefuses one of those classes at this gate — daemons, command-line tools andsystem XPC services such as `cameracaptured`, WebKit, `spotlightknowledged`,diff --git a/Research/Guest/gpu_acceleration.md b/Research/Guest/gpu_acceleration.mdindex 91d60e52..8f8e9f19 100644--- a/Research/Guest/gpu_acceleration.md+++ b/Research/Guest/gpu_acceleration.md@@ -98,13 +98,17 @@ there.### On in `standard`-`standard` stopped blocking the patch on 2026-10-04. The case that decided it is-`cameracaptured`, measured on an iPadOS 26.6.2 guest with the old `standard`:+`standard` stopped blocking the patch on 2026-10-04. The case put forward for it+was `cameracaptured`, measured on an iPadOS 26.6.2 guest with the old+`standard`. **Corrected the same day:** the crash below is not the gate+refusing the GPU. `cameracaptured` already has a Metal device (its preload+returns early without one), and it dies on a bug in the paravirtual driver's+heap textures, which the patch does not touch ("Heap Textures Have No CPU+Layout" below). What was observed:- At every boot it prewarms its capture shaders(`FigCapturePreloadShadersInternal` → CMCapture `PrewarmThreadSafeSBPs` →- NRFV3 `-[NRFProcessorV3 prewarm]`). It is a daemon, so the gate refuses it the- GPU, and it dies with SIGSEGV at `0xc` inside+ NRFV3 `-[NRFProcessorV3 prewarm]`) and dies with SIGSEGV at `0xc` inside`AppleParavirtGPUMetalIOGPUFamily`. launchd restarts it, and it crash-loops.- While it does, the first process to touch the AVCapture defaults blocks on asynchronous XPC to it (`AVCaptureProprietaryDefaultsSingleton` →@@ -114,9 +118,10 @@ there.`audiomxd`'s recording `StartIO` waits 18 s on the same path, and the firstrecording after boot fails.-So a daemon reaching the GPU is not a niche need: a stock system daemon expects-it. A separate change makes `libvcamcaptured` skip the prewarm defensively; this-one gives `cameracaptured` the device it expects, so it runs normally.+What stops the crash is `libvcamcaptured` skipping that prewarm, below. The+patch stays on in `standard` for what #22 asked: a daemon or a tool on a 26.x+or 18.x guest gets the GPU and the other paravirtual devices an app already+reaches.**What this widens.** The edit is at the IOUserClient sandbox gate only. Aprocess whose own sandbox profile refuses `iokit-open-user-client` for a class@@ -217,6 +222,115 @@ recompile is therefore a limitation of the host paravirtual GPU, not a guestpatch we can write. (A per-app `MTLBinaryArchive` inside a guest app wouldpersist that app's own pipelines, but that is an app change, not a VM one.)+## Heap Textures Have No CPU Layout++On the iPadOS 26.6.2 iPad Pro guest (cloudOS 26.4 driver, `standard` preset),+`cameracaptured` crashed at every boot and launchd throttled its restarts+(`successive crashes = 6`): `SIGSEGV`, `KERN_INVALID_ADDRESS` at `0xc`, on the+precompilation queue:++```+AppleParavirtGPUMetalIOGPUFamily +35956+NRFV3 -[ToneMappingCurves initWithWithContext:] +1076+NRFV3 -[RawDFInferenceGen initWithMetalContext:] +112+NRFV3 -[RawDFProcessor initWithCommandQueue:] +1048+NRFV3 -[NRFProcessorV3 prewarm] +224+CMCapture PrewarmThreadSafeSBPs +9392+CMCapture __FigCapturePreloadShadersInternal_block_invoke_2 +1084+```++While it crash-loops, any process that first touches AVCapture defaults waits+in a synchronous XPC to it. SpringBoard's main thread did, through the Control+Center sensor indicator's `AVCaptureDeviceDiscoverySession`, as soon as an app+started recording, and the guest UI froze until the VM was restarted. audiomxd's+`StartIO` for the recording blocked 18 s the same way, so the first recording+after each boot failed.++It is a bug in the guest's Metal driver, not the sandbox gate above:++- `-[ToneMappingCurves initWithWithContext:]` makes a shared `MTLHeap`+ (`setStorageMode:0`, `setSize:0xc800`), takes textures from it with+ `-newTextureWithDescriptor:`, and fills each with+ `-replaceRegion:mipmapLevel:slice:withBytes:bytesPerRow:bytesPerImage:`.+ `+1076` is the return address of that call.+- `AppleParavirtTexture` keeps a texture's CPU layout in the ivar `_dimension`.+ Every initialiser fills it except+ `-initWithHeap:resource:offset:length:descriptor:`, the one+ `-[AppleParavirtHeap newTextureWithDescriptor:]` uses.+ `-replaceRegion:…` (`0x8c28` in the 23E5207q driver; `+35956` is `0x8c74`)+ starts with `ldr x8, [x0, _dimension]; ldur x19, [x8, #0xc]`. That fault is+ at `0xc`. `-getBytes:…fromRegion:…` reads it the same way.+- The daemon has a Metal device. `FigCapturePreloadShadersInternal` takes+ `[[FigMetalContext metalDevice] newCommandQueue]` first and returns early+ when it is nil, and the faulting frame is a method of a real+ `AppleParavirtTexture`. `kernel-exp-paravirt_user_clients` therefore changes+ nothing here; a guest with it crashes the same way.++Any CPU upload into or readback from a heap-allocated texture faults on this+driver, in any process. The prewarm is where `cameracaptured` meets it at every+launch.++To reveal it in a driver, look for the ivar offset slot named `_dimension` in+`xcrun llvm-objdump --macho --objc-meta-data` (`0x6b7ac` in 23E5207q). List the+`ldrsw xN, [x8, #0x7ac]` loads of it with `ipsw macho disass <driver> --vaddr+0xdc8 --count 41000`. In 23E5207q these are every `AppleParavirtTexture` init+except `initWithHeap:…`, plus `dealloc`, `getBytes:…` and `replaceRegion:…`.++### Skipping the prewarm++`libvcamcaptured` removes the one call to `PrewarmThreadSafeSBPs`+(`VPhoneGuestComponents/VCamCaptured/Prewarm/`). Prewarming only compiles+shaders ahead of first use, and nothing waits on that function: it returns+nothing, stores no global and signals nothing. The rest of the preload still+runs. That includes the processor flags `FigCapturePreloadShadersInternal`+records, `DMPerformMigrationIfNeeded`, and the deferred shader cache copy.+Deferred photo processing waits up to 180 s on that copy's semaphore+(`FigWaitForDeferredShaderCacheCopyCompletion`), so skipping the whole preload+would not be safe.++The hook runs synchronously in the dylib's constructor, so it runs before the+daemon's own launch code, and only when+`/System/Library/Extensions/AppleParavirtGPUMetalIOGPUFamily.bundle` is+installed. The call site is found from the one exported symbol, with no fixed+address:++1. `FigCapturePreloadShaders` is `mov w0, #0; b FigCapturePreloadShadersInternal`.+2. In that function, before its return, exactly one+ `adrp x16; add x16, x16, #imm; pacia x16, xN`. This is the block's invoke,+ `__FigCapturePreloadShadersInternal_block_invoke_2`.+3. In the block, before its return, exactly one `ldr x0, [xN, #0x20]; bl`+ whose target is a function of CMCapture's `__text`. That is+ `PrewarmThreadSafeSBPs(commandQueue)`, with the queue as the block's first+ capture. iOS 27 has a second captured load in the block, but it calls a+ stub outside `__text`.++The `bl` becomes a `nop` (`vcc_patch_word`, which checks the old word first).+Over the real bytes, the scan gives these unslid addresses:++| Build | Internal | Block | Call | `PrewarmThreadSafeSBPs` |+| --- | --- | --- | --- | --- |+| iPadOS 26.6.2 (23G90), and the 26.6 cache | `0x1aeb2f06c` | `0x1aeb2f930` | `0x1aeb2fd68` | `0x1aeb300d4` |+| iOS 27.0 (24A435) | `0x1b0758ff0` | `0x1b07598c4` | `0x1b0759d10` | `0x1b075a070` |++`make -C VPhoneGuestComponents test-vcam-prewarm` runs the same scan over a+synthetic stream with these decoys and checks each refusal.++On a guest, check these:++- `/var/mobile/Media/SimulatedCamera/vcamcaptured.log` (and `vcamcaptured:` in+ the system log) has+ `gpu prewarm: internal 0x… block 0x… call 0x… -> PrewarmThreadSafeSBPs 0x…: skipped`,+ with the 23G90 addresses above. Any `gpu prewarm: kept, …` line names the+ step that refused.+- `logs.crashes` has no `cameracaptured` report newer than the update.+- `services.print` with label `com.apple.cameracaptured` shows+ `successive crashes = 0`.+- Starting a recording in an app neither freezes SpringBoard nor delays the+ first recording.++This does not fix the driver. NRF or RawDF processing during a real capture,+or any other heap texture upload, would still fault.+## Settings That Do Nothing HereBoth are private properties of `VZMacGraphicsDeviceConfiguration`, tried ondiff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefileindex fccc13bc..5bbd4d2b 100644--- a/VPhoneGuestComponents/Makefile+++ b/VPhoneGuestComponents/Makefile@@ -222,3 +222,12 @@ $(GPU_PROVENANCE): GraphicLoader/README.md | $(STAGE)/gpuclean:@rm -rf $(OUT)++# Host proof harness for the scan that finds cameracaptured's GPU prewarm call.+.PHONY: test-vcam-prewarm+test-vcam-prewarm:+ @mkdir -p $(OUT)+ xcrun --sdk macosx clang -O1 -Wall -Wextra -Werror -IVCamCaptured/Prewarm \+ -o $(OUT)/VCamPrewarmScanTests \+ Tests/VCamPrewarmScanTests.c VCamCaptured/Prewarm/VCamPrewarmScan.c+ @$(OUT)/VCamPrewarmScanTestsdiff --git a/VPhoneGuestComponents/Tests/VCamPrewarmScanTests.c b/VPhoneGuestComponents/Tests/VCamPrewarmScanTests.cnew file mode 100644index 00000000..4fbf061f--- /dev/null+++ b/VPhoneGuestComponents/Tests/VCamPrewarmScanTests.c@@ -0,0 +1,204 @@+/*+ * Host proof harness for the scan that finds cameracaptured's call to+ * PrewarmThreadSafeSBPs (VCamCaptured/Prewarm/VCamPrewarmScan.c).+ *+ * The instruction streams are synthetic and laid out like CMCapture's on+ * iPadOS 26.6.2 and iOS 27.0, decoys included: a captured load that calls+ * a stub outside __text (27 has one), a call into __text with no captured+ * argument, and a captured call in the function after the block's return.+ * The encodings match the words in those caches (`pacia x16, x8` is+ * 0xdac10110, `ldr x0, [x20, #0x20]` 0xf9401280, `bl` +0x36c 0x940000db).+ *+ * Build/run: make -C VPhoneGuestComponents test-vcam-prewarm+ */++#include "VCamPrewarmScan.h"++#include <stdio.h>+#include <string.h>++static int g_checks = 0;+static int g_fails = 0;++#define CHECK(cond, ...) \+ do { \+ g_checks++; \+ if (!(cond)) { \+ g_fails++; \+ printf("FAIL %s:%d: ", __FILE__, __LINE__); \+ printf(__VA_ARGS__); \+ printf("\n"); \+ } \+ } while (0)++// MARK: - encoders++#define BASE ((uintptr_t)0x1aeb2f000u)+#define WORDS 512u+#define AT(index) (BASE + (uintptr_t)(index) * 4)++static const uint32_t kMovW0Zero = 0x52800000u;+static const uint32_t kRetab = 0xD65F0FFFu;+static const uint32_t kRet = 0xD65F03C0u;+static const uint32_t kMovW0Shader = 0x52916620u; // mov w0, #0x8b31++static uint32_t enc_branch(uint32_t op, uintptr_t pc, uintptr_t target) {+ return op | ((uint32_t)((int64_t)(target - pc) / 4) & 0x03FFFFFFu);+}+static uint32_t enc_b(uintptr_t pc, uintptr_t target) {+ return enc_branch(0x14000000u, pc, target);+}+static uint32_t enc_bl(uintptr_t pc, uintptr_t target) {+ return enc_branch(0x94000000u, pc, target);+}+static uint32_t enc_adrp(unsigned rd, uintptr_t pc, uintptr_t target) {+ int64_t pages = (int64_t)(target >> 12) - (int64_t)(pc >> 12);+ uint32_t imm = (uint32_t)pages & 0x1FFFFFu;+ return 0x90000000u | ((imm & 3u) << 29) | ((imm >> 2) << 5) | rd;+}+static uint32_t enc_add_imm(unsigned rd, unsigned rn, unsigned imm) {+ return 0x91000000u | (imm << 10) | (rn << 5) | rd;+}+static uint32_t enc_pacia(unsigned rd, unsigned rn) {+ return 0xDAC10000u | (rn << 5) | rd;+}+static uint32_t enc_ldr_x(unsigned rt, unsigned rn, unsigned offset) {+ return 0xF9400000u | ((offset / 8) << 10) | (rn << 5) | rt;+}++// MARK: - layout++enum {+ kEntry = 0, // mov w0, #0; b internal+ kInternal = 8,+ kSignedInvoke = 20, // adrp/add/pacia triple+ kInternalEnd = 40,+ kBlock = 64,+ kStubCall = 70, // ldr x0, [x20, #0x20]; bl <outside __text>+ kPlainCall = 80, // mov w0, #0x8b31; bl <in __text>+ kPrewarmCall = 90, // ldr x0, [x20, #0x20]; bl prewarm+ kBlockEnd = 120,+ kNext = 121, // next function, with its own captured call+ kPrewarm = 200,+};++static uint32_t g_text[WORDS];++static void build_text(void) {+ for (unsigned i = 0; i < WORDS; i++) g_text[i] = VCC_A64_NOP;++ g_text[kEntry] = kMovW0Zero;+ g_text[kEntry + 1] = enc_b(AT(kEntry + 1), AT(kInternal));++ g_text[kInternal] = VCC_A64_PACIBSP;+ // A lone add x16 and an adrp x16 not followed by add/pacia: not a match.+ g_text[kInternal + 3] = enc_add_imm(16, 16, 0x10);+ g_text[kInternal + 6] = enc_adrp(16, AT(kInternal + 6), AT(kBlock));+ g_text[kSignedInvoke] = enc_adrp(16, AT(kSignedInvoke), AT(kBlock));+ g_text[kSignedInvoke + 1] = enc_add_imm(16, 16, (unsigned)(AT(kBlock) & 0xFFFu));+ g_text[kSignedInvoke + 2] = enc_pacia(16, 8);+ g_text[kInternalEnd] = kRetab;+ // After the return: another signed pointer that must not count.+ g_text[kInternalEnd + 2] = enc_adrp(16, AT(kInternalEnd + 2), AT(kPrewarm));+ g_text[kInternalEnd + 3] = enc_add_imm(16, 16, (unsigned)(AT(kPrewarm) & 0xFFFu));+ g_text[kInternalEnd + 4] = enc_pacia(16, 9);++ g_text[kBlock] = VCC_A64_PACIBSP;+ g_text[kStubCall - 1] = enc_ldr_x(0, 20, 0x20);+ g_text[kStubCall] = enc_bl(AT(kStubCall), BASE + 0x8000000u);+ g_text[kPlainCall - 1] = kMovW0Shader;+ g_text[kPlainCall] = enc_bl(AT(kPlainCall), AT(kPrewarm));+ g_text[kPrewarmCall - 1] = enc_ldr_x(0, 20, 0x20);+ g_text[kPrewarmCall] = enc_bl(AT(kPrewarmCall), AT(kPrewarm));+ g_text[kBlockEnd] = kRetab;++ g_text[kNext] = VCC_A64_PACIBSP;+ g_text[kNext + 2] = enc_ldr_x(0, 20, 0x20);+ g_text[kNext + 3] = enc_bl(AT(kNext + 3), AT(kPrewarm));+ g_text[kNext + 4] = kRet;++ g_text[kPrewarm] = VCC_A64_PACIBSP;+ g_text[kPrewarm + 1] = kRetab;+}++static int scan(uintptr_t entry, vcc_prewarm_site_t *site) {+ vcc_prewarm_text_t text = {g_text, BASE, WORDS};+ memset(site, 0, sizeof(*site));+ return vcc_find_prewarm_call(&text, entry, site);+}++// MARK: - tests++static void test_encodings_match_the_cache(void) {+ CHECK(enc_pacia(16, 8) == 0xDAC10110u, "pacia x16, x8");+ CHECK(enc_ldr_x(0, 20, 0x20) == 0xF9401280u, "ldr x0, [x20, #0x20]");+ CHECK(enc_bl(0x1aeb2fd68u, 0x1aeb300d4u) == 0x940000DBu, "bl +0x36c");+ CHECK(enc_add_imm(16, 16, 0x930) == 0x9124C210u, "add x16, x16, #0x930");+ CHECK(enc_adrp(16, 0x1aeb2f7a0u, 0x1aeb2f930u) == 0x90000010u, "adrp x16, same page");+}++static void test_finds_the_call(void) {+ build_text();+ vcc_prewarm_site_t site;+ int rc = scan(AT(kEntry), &site);+ CHECK(rc == 0, "scan returned %d", rc);+ CHECK(site.internal == AT(kInternal), "internal 0x%lx", (unsigned long)site.internal);+ CHECK(site.block_invoke == AT(kBlock), "block 0x%lx", (unsigned long)site.block_invoke);+ CHECK(site.call_site == AT(kPrewarmCall), "call 0x%lx", (unsigned long)site.call_site);+ CHECK(site.prewarm == AT(kPrewarm), "prewarm 0x%lx", (unsigned long)site.prewarm);+}++static void test_entry_that_is_the_function(void) {+ build_text();+ vcc_prewarm_site_t site;+ int rc = scan(AT(kInternal), &site);+ CHECK(rc == 0 && site.internal == AT(kInternal),+ "folded entry: rc %d internal 0x%lx", rc, (unsigned long)site.internal);+}++static void test_refusals(void) {+ vcc_prewarm_site_t site;++ build_text();+ CHECK(scan(BASE + WORDS * 4, &site) == -1, "entry outside __text");++ build_text();+ g_text[kInternal] = VCC_A64_NOP;+ CHECK(scan(AT(kEntry), &site) == -1, "branch target without a prologue");++ build_text();+ g_text[kSignedInvoke + 2] = VCC_A64_NOP;+ CHECK(scan(AT(kEntry), &site) == -2, "no signed invoke");++ build_text();+ g_text[kSignedInvoke + 5] = enc_adrp(16, AT(kSignedInvoke + 5), AT(kBlock));+ g_text[kSignedInvoke + 6] = enc_add_imm(16, 16, (unsigned)(AT(kBlock) & 0xFFFu));+ g_text[kSignedInvoke + 7] = enc_pacia(16, 8);+ CHECK(scan(AT(kEntry), &site) == -2, "two signed invokes");++ build_text();+ g_text[kBlock] = VCC_A64_NOP;+ CHECK(scan(AT(kEntry), &site) == -3, "invoke without a prologue");++ build_text();+ g_text[kPrewarmCall - 1] = kMovW0Zero;+ CHECK(scan(AT(kEntry), &site) == -4, "no captured call");++ build_text();+ g_text[kPrewarmCall + 4] = enc_ldr_x(0, 19, 0x20);+ g_text[kPrewarmCall + 5] = enc_bl(AT(kPrewarmCall + 5), AT(kPrewarm));+ CHECK(scan(AT(kEntry), &site) == -4, "two captured calls");++ build_text();+ g_text[kPrewarm] = VCC_A64_NOP;+ CHECK(scan(AT(kEntry), &site) == -4, "callee without a prologue");+}++int main(void) {+ test_encodings_match_the_cache();+ test_finds_the_call();+ test_entry_that_is_the_function();+ test_refusals();+ printf("%d checks, %d failures\n", g_checks, g_fails);+ return g_fails ? 1 : 0;+}diff --git a/VPhoneGuestComponents/VCamCaptured/Prewarm/VCamGPUPrewarm.m b/VPhoneGuestComponents/VCamCaptured/Prewarm/VCamGPUPrewarm.mnew file mode 100644index 00000000..d5585b44--- /dev/null+++ b/VPhoneGuestComponents/VCamCaptured/Prewarm/VCamGPUPrewarm.m@@ -0,0 +1,79 @@+// Keeps cameracaptured from prewarming its GPU sample buffer processors on+// the paravirtual GPU, where the prewarm faults at every launch.+//+// At launch the daemon calls FigCapturePreloadShaders. The block it queues+// on com.apple.coremedia.precompilation calls PrewarmThreadSafeSBPs(queue),+// which loads each video processor bundle and runs its -prewarm. NRFV3's+// runs -[RawDFProcessor initWithCommandQueue:] ->+// -[RawDFInferenceGen initWithMetalContext:] ->+// -[ToneMappingCurves initWithWithContext:], which makes textures from a+// shared MTLHeap and fills them with -replaceRegion:mipmapLevel:slice:+// withBytes:bytesPerRow:bytesPerImage:. The guest's Metal driver,+// AppleParavirtGPUMetalIOGPUFamily (cloudOS 26.4, 23E5207q), keeps a+// texture's CPU layout in the AppleParavirtTexture ivar _dimension. Every+// initialiser fills it except -initWithHeap:resource:offset:length:+// descriptor:, the one -[AppleParavirtHeap newTextureWithDescriptor:] uses,+// and -replaceRegion: reads it without a check: KERN_INVALID_ADDRESS at+// 0xc. The daemon has a working Metal device (the preload stops by itself+// when it has none: it needs a command queue first), so this is not the+// sandbox gate on the GPU's user client and kernel-exp-paravirt_user_clients+// does not change it. While the daemon crash-loops, every process that+// first touches AVCapture blocks in a synchronous XPC to it; SpringBoard's+// main thread among them.+//+// Prewarming only compiles shaders before first use, and nothing waits on+// PrewarmThreadSafeSBPs: it returns nothing, stores no global and signals+// nothing. So with the paravirtual driver installed, its one call is+// replaced with a NOP. The rest of the preload still runs: the processor+// flags it records, the data migration, and the deferred shader cache copy+// whose semaphore deferred photo processing waits on for up to 180 s.+// See Research/Guest/gpu_acceleration.md.++#include <ptrauth.h>++#include "VCamImage.h"+#include "VCamPrewarmScan.h"++// Present on every guest this project restores; its absence means another+// GPU, whose driver has not been seen to have the heap texture fault.+static const char *const kParavirtMetalDriver =+ "/System/Library/Extensions/AppleParavirtGPUMetalIOGPUFamily.bundle/"+ "AppleParavirtGPUMetalIOGPUFamily";++void vcc_install_gpu_prewarm_skip(void) {+ if (access(kParavirtMetalDriver, F_OK) != 0) {+ vcc_log(@"gpu prewarm: kept, no paravirtual Metal driver (errno %d)",+ errno);+ return;+ }++ vcc_image_t img;+ int rc = vcc_image_resolve(&img, "FigCapturePreloadShaders");+ if (rc != 0) {+ vcc_log(@"gpu prewarm: kept, CMCapture not resolved (step %d)", rc);+ return;+ }+ void *entry = ptrauth_strip(dlsym(RTLD_DEFAULT, "FigCapturePreloadShaders"),+ ptrauth_key_function_pointer);++ vcc_prewarm_text_t text = {img.text, (uintptr_t)img.text, img.text_words};+ vcc_prewarm_site_t site;+ rc = vcc_find_prewarm_call(&text, (uintptr_t)entry, &site);+ if (rc != 0) {+ vcc_log(@"gpu prewarm: kept, PrewarmThreadSafeSBPs call not found "+ @"(step %d)", rc);+ return;+ }++ // Unslid addresses, as `ipsw dyld symaddr` prints them for this cache.+ uintptr_t slide = (uintptr_t)img.slide;+ uint32_t call = *(const uint32_t *)site.call_site;+ int ok = vcc_patch_word(site.call_site, call, VCC_A64_NOP);+ vcc_log(@"gpu prewarm: internal 0x%lx block 0x%lx call 0x%lx -> "+ @"PrewarmThreadSafeSBPs 0x%lx: %@",+ (unsigned long)(site.internal - slide),+ (unsigned long)(site.block_invoke - slide),+ (unsigned long)(site.call_site - slide),+ (unsigned long)(site.prewarm - slide),+ ok ? @"skipped" : @"patch failed, kept");+}diff --git a/VPhoneGuestComponents/VCamCaptured/Prewarm/VCamPrewarmScan.c b/VPhoneGuestComponents/VCamCaptured/Prewarm/VCamPrewarmScan.cnew file mode 100644index 00000000..4f0ed998--- /dev/null+++ b/VPhoneGuestComponents/VCamCaptured/Prewarm/VCamPrewarmScan.c@@ -0,0 +1,156 @@+#include "VCamPrewarmScan.h"++// The shape the scan expects, as built on iPadOS 26.6.2 (23G90) and+// iOS 27.0 (24A435):+//+// _FigCapturePreloadShaders:+// mov w0, #0+// b _FigCapturePreloadShadersInternal+//+// _FigCapturePreloadShadersInternal: (one return, at the end)+// ...+// adrp x16, block_invoke_2@PAGE+// add x16, x16, block_invoke_2@PAGEOFF+// pacia x16, x8 the stack block's invoke+// ... dispatch_async / dispatch_sync on com.apple.coremedia.precompilation+//+// ___FigCapturePreloadShadersInternal_block_invoke_2:+// ...+// ldr x0, [x20, #0x20] the captured command queue+// bl _PrewarmThreadSafeSBPs+//+// Only the last pair loads x0 from a block capture right before calling a+// function of the same __text; other captured loads in that block (27 has+// one) go to stubs outside it.++// MARK: - decoding++#define VCC_SCAN_LIMIT 4096u // words; each function here is under 600++static int64_t vcc_sign_extend(uint64_t value, unsigned bits) {+ uint64_t sign = 1ull << (bits - 1);+ return (int64_t)((value ^ sign) - sign);+}++static int vcc_is_b(uint32_t w) { return (w & 0xFC000000u) == 0x14000000u; }+static int vcc_is_bl(uint32_t w) { return (w & 0xFC000000u) == 0x94000000u; }++static uintptr_t vcc_branch_target(uintptr_t pc, uint32_t w) {+ return pc + (uintptr_t)(vcc_sign_extend(w & 0x03FFFFFFu, 26) * 4);+}++// ret, retaa, retab.+static int vcc_is_return(uint32_t w) {+ return w == 0xD65F03C0u || w == 0xD65F0BFFu || w == 0xD65F0FFFu;+}++// adrp x16, <page>+static int vcc_is_adrp_x16(uint32_t w) {+ return (w & 0x9F00001Fu) == 0x90000010u;+}++static uintptr_t vcc_adrp_page(uintptr_t pc, uint32_t w) {+ uint64_t imm = (((uint64_t)(w >> 5) & 0x7FFFFu) << 2) | ((w >> 29) & 0x3u);+ return (pc & ~(uintptr_t)0xFFF) ++ (uintptr_t)(vcc_sign_extend(imm, 21) * 4096);+}++// add x16, x16, #imm (unshifted)+static int vcc_is_add_x16_x16(uint32_t w) {+ return (w & 0xFFC003FFu) == 0x91000210u;+}++// pacia x16, <any>+static int vcc_is_pacia_x16(uint32_t w) {+ return (w & 0xFFFFFC1Fu) == 0xDAC10010u;+}++// ldr x0, [x<n>, #0x20], n != sp: the first capture of a block literal.+static int vcc_is_ldr_x0_capture(uint32_t w) {+ return (w & 0xFFFFFC1Fu) == 0xF9401000u && ((w >> 5) & 0x1Fu) != 31;+}++// MARK: - text access++static const uint32_t *vcc_word(const vcc_prewarm_text_t *t, uintptr_t addr) {+ if (addr < t->addr || (addr & 3)) return NULL;+ size_t index = (addr - t->addr) / 4;+ return index < t->count ? &t->words[index] : NULL;+}++static size_t vcc_words_from(const vcc_prewarm_text_t *t, uintptr_t addr) {+ size_t left = t->count - (addr - t->addr) / 4;+ return left < VCC_SCAN_LIMIT ? left : VCC_SCAN_LIMIT;+}++static int vcc_is_function(const vcc_prewarm_text_t *t, uintptr_t addr) {+ const uint32_t *w = vcc_word(t, addr);+ return w && *w == VCC_A64_PACIBSP;+}++// Another function starts here: the scans stop at a return or at the next+// prologue, whichever comes first.+static int vcc_ends_function(const uint32_t *w, size_t i) {+ return vcc_is_return(w[i]) || (i > 0 && w[i] == VCC_A64_PACIBSP);+}++// MARK: - scan++int vcc_find_prewarm_call(const vcc_prewarm_text_t *text,+ uintptr_t preload_entry,+ vcc_prewarm_site_t *out) {+ // 1. The exported entry tail-calls the internal function. Accept the+ // entry itself when it branches nowhere first (a build that folded+ // the two).+ const uint32_t *entry = vcc_word(text, preload_entry);+ if (!entry) return -1;+ uintptr_t internal = preload_entry;+ size_t entry_words = vcc_words_from(text, preload_entry);+ for (size_t i = 0; i < 4 && i < entry_words; i++) {+ if (vcc_is_b(entry[i])) {+ internal = vcc_branch_target(preload_entry + i * 4, entry[i]);+ break;+ }+ if (vcc_is_bl(entry[i]) || vcc_ends_function(entry, i)) break;+ }+ if (!vcc_is_function(text, internal)) return -1;++ // 2. The block's invoke is the one function pointer the internal+ // function signs with pacia x16.+ const uint32_t *fn = vcc_word(text, internal);+ size_t fn_words = vcc_words_from(text, internal);+ uintptr_t invoke = 0;+ unsigned invokes = 0;+ for (size_t i = 0; i < fn_words && !vcc_ends_function(fn, i); i++) {+ if (i < 2 || !vcc_is_pacia_x16(fn[i])) continue;+ if (!vcc_is_add_x16_x16(fn[i - 1]) || !vcc_is_adrp_x16(fn[i - 2])) continue;+ invoke = vcc_adrp_page(internal + (i - 2) * 4, fn[i - 2]) ++ ((fn[i - 1] >> 10) & 0xFFFu);+ invokes++;+ }+ if (invokes != 1) return -2;+ if (!vcc_is_function(text, invoke)) return -3;++ // 3. In the block, the one call whose argument is the block's first+ // capture and whose callee is a function of this image.+ const uint32_t *block = vcc_word(text, invoke);+ size_t block_words = vcc_words_from(text, invoke);+ uintptr_t site = 0, callee = 0;+ unsigned calls = 0;+ for (size_t i = 1; i < block_words && !vcc_ends_function(block, i); i++) {+ if (!vcc_is_bl(block[i]) || !vcc_is_ldr_x0_capture(block[i - 1])) continue;+ uintptr_t pc = invoke + i * 4;+ uintptr_t target = vcc_branch_target(pc, block[i]);+ if (!vcc_is_function(text, target)) continue;+ site = pc;+ callee = target;+ calls++;+ }+ if (calls != 1) return -4;++ out->internal = internal;+ out->block_invoke = invoke;+ out->call_site = site;+ out->prewarm = callee;+ return 0;+}diff --git a/VPhoneGuestComponents/VCamCaptured/Prewarm/VCamPrewarmScan.h b/VPhoneGuestComponents/VCamCaptured/Prewarm/VCamPrewarmScan.hnew file mode 100644index 00000000..57b38e3a--- /dev/null+++ b/VPhoneGuestComponents/VCamCaptured/Prewarm/VCamPrewarmScan.h@@ -0,0 +1,46 @@+#ifndef VCAM_PREWARM_SCAN_H+#define VCAM_PREWARM_SCAN_H++// Locates cameracaptured's call to PrewarmThreadSafeSBPs by decoding the+// instructions of FigCapturePreloadShaders and the block it dispatches. It+// reads words only, never the process, so the host test runs the same code+// over synthetic and real instruction streams.++#include <stddef.h>+#include <stdint.h>++#pragma GCC visibility push(hidden)++// The instructions the scan matches and the one the patch writes.+#define VCC_A64_NOP 0xD503201Fu+#define VCC_A64_PACIBSP 0xD503237Fu++// An image's __text: `words` as readable memory, `addr` the address the+// code runs at (the same as `words` in the guest; anything in a test).+typedef struct {+ const uint32_t *words;+ uintptr_t addr;+ size_t count;+} vcc_prewarm_text_t;++typedef struct {+ uintptr_t internal; // FigCapturePreloadShadersInternal+ uintptr_t block_invoke; // the invoke function of the block it dispatches+ uintptr_t call_site; // `bl PrewarmThreadSafeSBPs` in that block+ uintptr_t prewarm; // PrewarmThreadSafeSBPs+} vcc_prewarm_site_t;++// Finds the call starting from the address of the exported+// FigCapturePreloadShaders. Returns 0 and fills *out on success, or the+// negative number of the step that failed:+// -1 the entry or its branch target is outside __text or not a function+// -2 the preload function signs no block invoke, or more than one+// -3 the block invoke is outside __text or not a function+// -4 the block holds no call of a captured value, or more than one+int vcc_find_prewarm_call(const vcc_prewarm_text_t *text,+ uintptr_t preload_entry,+ vcc_prewarm_site_t *out);++#pragma GCC visibility pop++#endifdiff --git a/VPhoneGuestComponents/VCamCaptured/VCamCapturedPrivate.h b/VPhoneGuestComponents/VCamCaptured/VCamCapturedPrivate.hindex 6549c989..a4a80490 100644--- a/VPhoneGuestComponents/VCamCaptured/VCamCapturedPrivate.h+++ b/VPhoneGuestComponents/VCamCaptured/VCamCapturedPrivate.h@@ -74,6 +74,11 @@ void vcc_install_device_vendor_hook(void);void vcc_install_copy_streams_hook(void);void vcc_install_copy_streams_from_hook(void);+// On the paravirtual GPU, removes the daemon's call to PrewarmThreadSafeSBPs,+// whose NRF prewarm faults in the guest's Metal driver. Installed+// synchronously in the constructor, before the daemon starts its preload.+void vcc_install_gpu_prewarm_skip(void);+#pragma GCC visibility pop#endifdiff --git a/VPhoneGuestComponents/VCamCaptured/libvcamcaptured.m b/VPhoneGuestComponents/VCamCaptured/libvcamcaptured.mindex 0cd8e0e7..d6fd8804 100644--- a/VPhoneGuestComponents/VCamCaptured/libvcamcaptured.m+++ b/VPhoneGuestComponents/VCamCaptured/libvcamcaptured.m@@ -42,6 +42,7 @@// Synthetic/ the synthetic source, device and stream classes// Frames/ the shm frame reader and viewfinder / sink delivery// Hooks/ observation and delivery hooks on the capture graph+// Prewarm/ the GPU prewarm skip for the paravirtual Metal driver// Cross-file symbols are declared in each folder's header with hidden// visibility, so none becomes a public dylib interface.@@ -135,5 +136,9 @@ __attribute__((constructor)) static void vcc_init(void) {vcc_install_copy_streams_from_hook();}});++ // Not delayed: the daemon starts its shader preload at launch, and the+ // call has to be gone before the precompilation queue reaches it.+ vcc_install_gpu_prewarm_skip();}}