Run a virtual iPhone on an Apple Silicon Mac.
Swift
Stop the vcam text patcher from racing cameracaptured's XPC threads
Jackyf5f34505d5e3
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex 18a5bb03..50bd5b20 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -563,6 +563,7 @@ do NOT execute these).| 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 || 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 |### Swift port status — the eight DSC patchers (2026-09-23)diff --git a/Research/Guest/virtual_camera_transport.md b/Research/Guest/virtual_camera_transport.mdindex e8cc5d8e..bceae26d 100644--- a/Research/Guest/virtual_camera_transport.md+++ b/Research/Guest/virtual_camera_transport.md@@ -67,3 +67,44 @@ passed its guest test, the stale`/var/mobile/Library/vphone-vcam.log` files from the earlier build wereremoved through the guest API. A subsequent directory listing containedneither file.++## The patch race that froze the whole VM (2026-10-05)++"Opening the camera freezes the VM" had two crashes behind it, both in+`cameracaptured`, and the freeze itself was never a camera-graph problem:+when the daemon crash-loops and launchd throttles it, every process that+first touches AVCapture — SpringBoard included — blocks in a synchronous+XPC to it, and the whole UI stops answering. The prewarm crash (row 23 of+the CFW table) was the first trigger; the second, still present after that+fix, was ours.++`vcc_patch_word` rewrites CMCapture shared-cache `__text` through+`vm_protect(RW|COPY)` → write → `vm_protect(RX)`. During that window the+whole 16K page has no execute permission, and the pages it touches are live+XPC server code the daemon runs constantly. Two crash reports caught the+race red-handed, both with the patching thread (`vcc_install_csp_requires_+master_clock_hook` → `vcc_scan_and_patch` → `vcc_patch_word`) in the same+process when another thread died fetching an instruction in a page mid-flip+(region snapshot: `r-x/rwx`, `SM=COW`):++| Report | Faulting queue | Dying frame |+| --- | --- | --- |+| `ipad-mini-01` `cameracaptured-2026-10-03-045638.ips` | `com.apple.coremedia.flashlight(34)-messages` | `__FigFlashlightGetClassID_block_invoke`, SIGBUS `KERN_PROTECTION_FAILURE` |+| `ipad-pro-13` `cameracaptured-2026-10-04-225558.ips` | `com.apple.coremedia.capturesource(523)-messages` | `captureSourceServer_handleRegisterNotificationForProprietaryDefaultChangesMessage`, same exception |++The capturesource queue is exactly what fires when a client opens the+camera: registering for source-change notifications is part of enumeration.+So "open camera" both restarts the daemon's traffic (after any crash or+restart, the hook reinstall at +3 s re-opens the window) and supplies the+thread that dies in it.++The fix (row 25 of the CFW table) stops the world around the flip:+`task_threads` + `thread_suspend` of every other thread, the two+`vm_protect` calls, the word write and the icache invalidation, then+`thread_resume`. The stopped section takes no locks, allocates nothing and+logs nothing — a frozen thread holding the malloc lock must not deadlock+the patcher — and all `vcc_log` calls moved after the resume. A mutex+serialises patchers. Kill-and-relaunch stress (killing `cameracaptured`+with Camera.app auto-reconnecting, the same collision the crashes came+from) is the validation.+diff --git a/VPhoneGuestComponents/VCamCaptured/Image/VCamCodePatch.m b/VPhoneGuestComponents/VCamCaptured/Image/VCamCodePatch.mindex 88547787..7b1430a4 100644--- a/VPhoneGuestComponents/VCamCaptured/Image/VCamCodePatch.m+++ b/VPhoneGuestComponents/VCamCaptured/Image/VCamCodePatch.m@@ -1,16 +1,69 @@#include <libkern/OSCacheControl.h>#include <mach/mach.h>+#include <pthread.h>#include "VCamImage.h"// MARK: - in-place code patching+// The patch targets are shared-cache __text pages of CMCapture — live XPC+// server code that other cameracaptured threads execute at any moment.+// vm_protect(RW) strips the execute permission for the whole page until+// the matching vm_protect(RX) returns, so a thread whose PC lands in that+// page inside the window dies with SIGBUS KERN_PROTECTION_FAILURE (two+// such crashes were caught on the flashlight and capturesource reply+// queues while this very patcher was in-flight). Stopping every other+// thread for the few-hundred-µs window makes the flip safe; the stopped+// section runs no locks, no allocation and no logging, so a thread caught+// holding any userspace lock cannot deadlock us.+static pthread_mutex_t s_patch_world_lock = PTHREAD_MUTEX_INITIALIZER;++typedef struct {+ thread_act_t *threads;+ mach_msg_type_number_t count;+} vcc_stopped_world_t;++static void vcc_stop_world(vcc_stopped_world_t *world) {+ world->threads = NULL;+ world->count = 0;+ if (task_threads(mach_task_self(), &world->threads,+ &world->count) != KERN_SUCCESS) {+ return;+ }+ mach_port_t self = mach_thread_self();+ for (mach_msg_type_number_t i = 0; i < world->count; i++) {+ if (world->threads[i] != self) {+ (void)thread_suspend(world->threads[i]);+ }+ }+ mach_port_deallocate(mach_task_self(), self);+}++static void vcc_resume_world(vcc_stopped_world_t *world) {+ if (!world->threads) return;+ mach_port_t self = mach_thread_self();+ for (mach_msg_type_number_t i = 0; i < world->count; i++) {+ if (world->threads[i] != self) {+ (void)thread_resume(world->threads[i]);+ }+ mach_port_deallocate(mach_task_self(), world->threads[i]);+ }+ mach_port_deallocate(mach_task_self(), self);+ vm_deallocate(mach_task_self(), (vm_address_t)world->threads,+ world->count * sizeof(thread_act_t));+ world->threads = NULL;+ world->count = 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.+// Returns 1 on success. All logging happens after the world is resumed:+// inside the stopped section nothing may touch malloc or a lock a frozen+// thread could be holding.int vcc_patch_two_nops(uintptr_t pc) {uintptr_t page_size = (uintptr_t)getpagesize();uintptr_t page_start = pc & ~(page_size - 1);@@ -19,6 +72,13 @@ int vcc_patch_two_nops(uintptr_t pc) {((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();+ int result = 0;+ kern_return_t kr_a_copy = KERN_SUCCESS, kr_a_rx = KERN_SUCCESS;+ kern_return_t kr_b = KERN_SUCCESS;++ pthread_mutex_lock(&s_patch_world_lock);+ vcc_stopped_world_t world;+ vcc_stop_world(&world);// (a) vm_protect with VM_PROT_COPY (= 0x10) to force COW.kern_return_t kr = vm_protect(@@ -27,6 +87,7 @@ int vcc_patch_two_nops(uintptr_t pc) {span,FALSE,VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY);+ kr_a_copy = kr;if (kr == KERN_SUCCESS) {uint32_t nop = 0xD503201Fu;((uint32_t *)pc)[0] = nop;@@ -37,79 +98,82 @@ int vcc_patch_two_nops(uintptr_t pc) {span,FALSE,VM_PROT_READ | VM_PROT_EXECUTE);+ kr_a_rx = kr;if (kr == KERN_SUCCESS) {sys_icache_invalidate((void *)pc, 8);- vcc_log(@" vm_protect+COPY patch OK @ 0x%lx",- (unsigned long)pc);- return 1;+ result = 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);}+ if (result) goto out;// (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 scratch = 0;+ kr_b = vm_allocate(self_task, &scratch, span, VM_FLAGS_ANYWHERE);+ if (kr_b != KERN_SUCCESS) goto out;+ 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_b = vm_protect(+ self_task,+ scratch,+ span,+ FALSE,+ VM_PROT_READ | VM_PROT_EXECUTE);+ if (kr_b != KERN_SUCCESS) {+ vm_deallocate(self_task, scratch, span);+ goto out;+ }+ vm_address_t target = (vm_address_t)page_start;+ vm_prot_t cur_prot = 0, max_prot = 0;+ kr_b = 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_b != KERN_SUCCESS) {+ vm_deallocate(self_task, scratch, span);+ goto out;+ }+ sys_icache_invalidate((void *)pc, 8);+ result = 1;}- 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;++out:+ vcc_resume_world(&world);+ pthread_mutex_unlock(&s_patch_world_lock);++ if (result && kr_a_copy == KERN_SUCCESS) {+ vcc_log(@" vm_protect+COPY patch OK @ 0x%lx", (unsigned long)pc);+ } else if (result) {+ vcc_log(@" vm_remap OK: page=0x%lx span=%zu", (unsigned long)page_start,+ (size_t)span);+ } else if (kr_a_copy != KERN_SUCCESS) {+ vcc_log(@" vm_protect+COPY failed: %d", kr_a_copy);+ vcc_log(@" vm_remap failed: %d", kr_b);+ } else {+ vcc_log(@" vm_protect restore RX failed: %d (page=0x%lx)", kr_a_rx,+ (unsigned long)page_start);+ vcc_log(@" vm_remap failed: %d", kr_b);}- 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;+ return result;}// 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.+// Uses the same stop-the-world 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.int vcc_patch_word(uintptr_t pc,uint32_t expected_word,uint32_t new_word) {@@ -127,6 +191,12 @@ int vcc_patch_word(uintptr_t pc,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_rw = KERN_SUCCESS, kr_rx = KERN_SUCCESS;+ int result = 0;++ pthread_mutex_lock(&s_patch_world_lock);+ vcc_stopped_world_t world;+ vcc_stop_world(&world);kern_return_t kr = vm_protect(self_task,@@ -134,27 +204,36 @@ int vcc_patch_word(uintptr_t pc,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;+ kr_rw = kr;+ if (kr == KERN_SUCCESS) {+ ((uint32_t *)pc)[0] = new_word;+ kr = vm_protect(+ self_task,+ (vm_address_t)page_start,+ span,+ FALSE,+ VM_PROT_READ | VM_PROT_EXECUTE);+ kr_rx = kr;+ if (kr == KERN_SUCCESS) {+ sys_icache_invalidate((void *)pc, 4);+ result = 1;+ }}- ((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;++ vcc_resume_world(&world);+ pthread_mutex_unlock(&s_patch_world_lock);++ if (result) {+ vcc_log(@" patch_word OK @ 0x%lx: 0x%08x -> 0x%08x",+ (unsigned long)pc,+ expected_word,+ new_word);+ } else if (kr_rw != KERN_SUCCESS) {+ vcc_log(@" patch_word vm_protect+COPY failed: %d", kr_rw);+ } else {+ vcc_log(@" patch_word restore RX failed: %d", kr_rx);}- 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;+ return result;}// Scan the image's __text for every occurrence of `needle` and rewrite