Run a virtual iPhone on an Apple Silicon Mac.
Swift
Upgrade an installed iOS 27 guest's force-kern patch on its own
Jackyf496cfe23ac4
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex 8160aa36..3a21aabb 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -550,7 +550,7 @@ do NOT execute these).| 8 | (removed — was: standalone-binary mangle in 6 rootfs Mach-Os via SSH) | n/a | Removed in the blacklist-flip redesign. With the EXP kernel rename in place, the 6 rootfs binaries (MobileActivationMigrator, CheckerBoard, StoreKitUISceneService, storekitd, appstored, CorePrescriptionService) get the desired "cache 0 / not in a VM" behavior for free: they keep their original cstring, hit ENOENT on the renamed kernel sysctl, defensive `cbnz w0, skip` leaves the cached byte at BSS-zero. No SSH-time standalone patch needed. | - | - | - || 9 | `mov w3,#<size>` -> `mov w3,#<base-size>` in `_kern_SwapEnd` — **26.0/26.0.1 and 18.x** | DSC `IOMobileFramebuffer` | Fixes host VZ GUI black-screen with the available PCC vphone600 userclient: the userclient does an exact `checkStructureInputSize` check on external-method-5 (SwapEnd) input, so a userland whose `_kern_SwapEnd` sends a different-sized state gets `kIOReturnBadArgument` and the host display stays black (guest still renders — the Apple logo is visible over VNC, just not in the vphone-cli view). **The accepted size is a property of the base kernel, not the userland**: 26.1 base -> **0x560**, 26.4 base (xnu-12377) -> **0x588**. The 0x588 value is confirmed two ways: the sole dispatch-shaped entry in `kernelcache.*.vphone600` with `checkStructureInputSize==0x588` (scalarIn=0, scalarOut=0, structOut=0, preceded by a ptrauth code ptr, at decompressed file offset 0x9c7228), and empirically — native 26.5 userland sends 0x588 and displays correctly on this stack. Source (userland-sent) sizes observed: 18.6.2 = 0x514, 26.0/26.0.1 = 0x548, 27.0 (24A5380h) = 0x6e0. The patcher is semantic (anchors on `mov w1,#5` -> `mov w3,#imm` -> `mov x4,#0`/`mov x5,#0` -> `bl` inside `_kern_SwapEnd`) and idempotent — rewrites the size to `--target-size` regardless of source and re-attests the modified DSC page. Install gate: `26.0*` / `18.*` -> 0x560 (26.1 base). Validated after host install on `17,3_26.0_23A341`, `17,3_26.0.1_23A355`, and `17,3_18.6.2_22G100` (Apple logo renders) against the 26.1 base. **CORRECTION (2026-07-15): iOS 27.0 is NO LONGER handled here.** 27 presents the paravirt display via IOMFB's `_virt_*` callback path — external method 5 is NEVER called — so no SwapEnd *size* change can help 27 (confirmed by kernel trace + live AppleParavirtGPU idle scheduler). iOS 27 now uses **force-kern (item 11)** to route present back onto method 5; this row applies to 26.0/26.0.1/18.x only. | Y | Y | Y || 10 | Zero `maxSlide` in `dyld_cache_header` (`@0xF0`) — **iOS 27.0 / any userland whose cache overflows the 6 GiB region** | DSC `dyld_shared_cache_arm64e` header | Fixes pid-1 `launchd` panic at boot on the vphone600 26.x kernel. The kernel reserves `SHARED_REGION_SIZE_ARM64 = 0x180000000` (6 GiB) and, at map time, needs room for the cache's mapped span **plus** the header `maxSlide` (ASLR range). iOS 27.0's cache (span `0x17c830000` ≈ 5.95 GiB) + `maxSlide 0x20000000` = `0x19c830000` > 6 GiB, so `_shared_region_map_and_slide` returns `ENOMEM`, dyld cannot map `libSystem.B.dylib`, and `launchd` panics (`initproc failed to start`). Zeroing `maxSlide` (LE u64) in the main chunk maps the cache at slide 0 (fits with ~58 MiB spare). Install gate: **`27.*`** (hard-gated in `cfw_install.sh` as of 2026-07-20 — an 18.x/26.x base skips it entirely). The patcher additionally self-gates (`patch-dsc-maxslide`): no-op unless span + maxSlide > `0x180000000`, kept as defense-in-depth so 26.x / 18.x are untouched even if the install gate were removed. **The non-27 opt-in is gone** (2026-09-30): `FORCE_DSC_MAXSLIDE=1`, later `--force-dsc-maxslide`, no longer exists on any command or in Launchpad. `dyld-boot-maxslide` is declared `iOSBase: .major(27)`, so non-27 bases keep their native slide. `patch-dsc-maxslide --force` remains on the standalone verb for hand use; `cfw install` never passes it. **24A435 (27.0 RC) checked 2026-09-30** for issue #531: the pristine SystemOS cryptex header reads `sharedRegionStart 0x180000000`, `sharedRegionSize 0x17D504000`, `maxSlide 0x20000000`, so span + slide is `0x19D504000`. `vphone-cli cfw patch-dsc-maxslide --dry-run` (2.1.6) reports `overflow` and would zero it; an installed 24A435 guest reads `maxSlide 0x0` and boots. The self-gate therefore patches 24A435 without force. The 512 MiB slide is the cache builder's fixed iOS arm64 value, so every 27 cache overflows this region. Source check (xnu-12377, `shared_region_map_and_slide_2_np`, `vm_shared_region_map_file_setup`, `vm_map_locate_space_fixed`): the kernel picks a 16 KiB-aligned slide strictly below `maxSlide` and maps each range FIXED inside the `0x180000000` submap. With no twig rounding and no reserved area, `size + maxSlide <= 0x180000000` is a sufficient test, one 16 KiB page stricter than needed. The #531 panic therefore came from a guest whose cache was never patched. Most likely its CFW install had not completed, because `cfw install` swaps in its clone only on success. It did not come from the gate. **No** page re-attestation (header metadata, not a `cs_validate`'d code page — confirmed empirically). Validated on `17,3_27.0_24A5380h` + cloudOS 26.4 (`c0ecdb4b…`): `dyld cache mapped system-wide`, launchd reaches first unlock, vphoned connects as iOS 27.0.0, 0 panics. See `scripts/patchers/cfw_patch_dsc_maxslide.py`. | Y | Y | Y |-| 11 | Retarget public `_IOMobileFramebufferSwap*` trampolines -> `b _kern_Swap*` (force-kern) — **iOS 27.0** | DSC `IOMobileFramebuffer` | **iOS-27 VZ-view (host paravirt-GPU scanout) fix, userland half.** The host `VZVirtualMachineView` is fed by the guest `AppleParavirtGPU` scanout, which the 26.4 kernel drives ONLY from the IOMFB userclient SwapEnd (external method 5) — the `_kern_Swap*` path. iOS 27 defaults the paravirt display's present to IOMFB's parallel `_virt_Swap*` path (`_virt_SwapEnd` does no userclient call — it invokes an in-process callback `blraaz [conn+0xe68]` and hands the IOSurface to a virtual-display consumer), so the paravirt GPU never scans out → host VZ window black (guest still composites; GUI visible over in-guest TrollVNC; AppleParavirtGPU `SchedulerState` idle). The public `_IOMobileFramebufferSwap*` entrypoints are thin trampolines (`cbz x0; ldr xN,[x0,#slot]; cbz xN; braaz xN`) that tail-call the per-connection swap fp (kern or virt impl). This patch rewrites each trampoline's first insn to `b _kern_Swap<Name>`, forcing present onto method 5 regardless of how 27 classified the display (tail-call, args intact → behaviourally identical to selecting the kern fp). Fully dynamic: public + `_kern_` addrs resolved by name via `ipsw dyld symaddr`, trampoline shape verified by Capstone, branch bytes from Keystone `asm_at()`, modified DSC code pages re-attested. Requires ≥{SwapBegin,SwapEnd,SwapSetLayer} or raises (dry-run retargets 31 entrypoints on 24A5380h, skips 4 non-trampolines). **Pairs with the JB kernel patches (`patchIomfbSwapEndVariableSize` + `patchIomfbSwapEndHandlerSize`)** which relax the 26.4 userclient's two exact `0x588` size gates to accept 27's native `0x6e0` IOMFBSwapRec (prefix matches 26.x, so the paravirt swap handler reads valid fields). Install gate: `27.*`. See `scripts/patchers/cfw_patch_iomfb_force_kern.py`. **VALIDATED on-device (2026-07-15, `17,3_27.0_24A5380h` + cloudOS 26.4 `c0ecdb4b…`, JB): iOS 27 userland renders AND is interactive in the native VZ view (not just TrollVNC); clean boot — no `kIOReturnBadArgument`/SwapEnd rejection/panic.** Runtime confirmed 31 entrypoints retargeted (4 non-trampoline setters left on virt). **Conditional since 2026-10-07 (DeviceHub):** forcing every trampoline also sent the capture display that Xcode's DeviceHub stream adds to the kernel; it has no userclient port, so backboardd logged `display 2 swap_end returned error 10000003` (`MACH_SEND_INVALID_DEST`) and the stream was black. Each trampoline is now `cbz x0, <fail>` / `ldr w16, [x0, #0x14]` / `cbnz w16, _kern_Swap<Name>` / `b _virt_Swap<Name>`: a connection with an IOConnect port (the paravirtual main display) still presents through method 5, a virtual display keeps its in-process path. Only operations with public, `_kern_` and `_virt_` siblings take part (ten on 24A446; `SwapSignal` is not a trampoline). The `0x14` port offset is the one every `_kern_Swap*` passes to the external method, verified on 24A446. The identifier is unchanged, so an installed guest needs the old 31 four-byte sites reverted (`fw set-patches --block dyld-boot-iomfb_force_kern`, `cfw update-environment`) before the new ten 16-byte sites are written. Validated on `iPhone17,3 27.0.1 (24A446)`: VZ scanout unchanged, DeviceHub live. See `Research/Guest/devicehub_screen_viewing.md`. | Y | Y | Y |+| 11 | Retarget public `_IOMobileFramebufferSwap*` trampolines -> `b _kern_Swap*` (force-kern) — **iOS 27.0** | DSC `IOMobileFramebuffer` | **iOS-27 VZ-view (host paravirt-GPU scanout) fix, userland half.** The host `VZVirtualMachineView` is fed by the guest `AppleParavirtGPU` scanout, which the 26.4 kernel drives ONLY from the IOMFB userclient SwapEnd (external method 5) — the `_kern_Swap*` path. iOS 27 defaults the paravirt display's present to IOMFB's parallel `_virt_Swap*` path (`_virt_SwapEnd` does no userclient call — it invokes an in-process callback `blraaz [conn+0xe68]` and hands the IOSurface to a virtual-display consumer), so the paravirt GPU never scans out → host VZ window black (guest still composites; GUI visible over in-guest TrollVNC; AppleParavirtGPU `SchedulerState` idle). The public `_IOMobileFramebufferSwap*` entrypoints are thin trampolines (`cbz x0; ldr xN,[x0,#slot]; cbz xN; braaz xN`) that tail-call the per-connection swap fp (kern or virt impl). This patch rewrites each trampoline's first insn to `b _kern_Swap<Name>`, forcing present onto method 5 regardless of how 27 classified the display (tail-call, args intact → behaviourally identical to selecting the kern fp). Fully dynamic: public + `_kern_` addrs resolved by name via `ipsw dyld symaddr`, trampoline shape verified by Capstone, branch bytes from Keystone `asm_at()`, modified DSC code pages re-attested. Requires ≥{SwapBegin,SwapEnd,SwapSetLayer} or raises (dry-run retargets 31 entrypoints on 24A5380h, skips 4 non-trampolines). **Pairs with the JB kernel patches (`patchIomfbSwapEndVariableSize` + `patchIomfbSwapEndHandlerSize`)** which relax the 26.4 userclient's two exact `0x588` size gates to accept 27's native `0x6e0` IOMFBSwapRec (prefix matches 26.x, so the paravirt swap handler reads valid fields). Install gate: `27.*`. See `scripts/patchers/cfw_patch_iomfb_force_kern.py`. **VALIDATED on-device (2026-07-15, `17,3_27.0_24A5380h` + cloudOS 26.4 `c0ecdb4b…`, JB): iOS 27 userland renders AND is interactive in the native VZ view (not just TrollVNC); clean boot — no `kIOReturnBadArgument`/SwapEnd rejection/panic.** Runtime confirmed 31 entrypoints retargeted (4 non-trampoline setters left on virt). **Conditional since 2026-10-07 (DeviceHub):** forcing every trampoline also sent the capture display that Xcode's DeviceHub stream adds to the kernel; it has no userclient port, so backboardd logged `display 2 swap_end returned error 10000003` (`MACH_SEND_INVALID_DEST`) and the stream was black. Each trampoline is now `cbz x0, <fail>` / `ldr w16, [x0, #0x14]` / `cbnz w16, _kern_Swap<Name>` / `b _virt_Swap<Name>`: a connection with an IOConnect port (the paravirtual main display) still presents through method 5, a virtual display keeps its in-process path. Only operations with public, `_kern_` and `_virt_` siblings take part (ten on 24A446; `SwapSignal` is not a trampoline). The `0x14` port offset is the one every `_kern_Swap*` passes to the external method, verified on 24A446. The identifier is unchanged; the installer recognizes the old 4-byte undo records (`DyldSharedCacheUndoLog.outdatedImplementations`), reverts them and applies the conditional form in the same `cfw install` or environment update, so an installed guest upgrades without manual steps. Validated on `iPhone17,3 27.0.1 (24A446)`: VZ scanout unchanged, DeviceHub live. See `Research/Guest/devicehub_screen_viewing.md`. | Y | Y | Y || 12 | NOP `-[_LSDModifyClient clientIsEntitledForEmbeddedRegistrationOperations]` entitlement gate + per-page re-attest — **iOS 27.0** | DSC `CoreServices` (LaunchServices) | **iOS-27 app-registration fix.** lsd gates `-[_LSDModifyClient performPostInstallationRegistration:operationUUID:reply:]` (and the containerized/rebuild registration paths) behind `clientIsEntitledForEmbeddedRegistrationOperations`, which does `xpc_connection_copy_entitlement_value` on the XPC peer for any of `com.apple.private.coreservices.lsaw` / `com.apple.private.installcoordinationd.daemon` / `com.apple.private.coreservices.can-register-install-results`. A client without one gets `NSOSStatusErrorDomain -54` (permErr, `LSDModifyService.mm:1639`), so `registerApplicationDictionary:` / `registerContainerizedApplicationWithInfoDictionaries:` fail and no app can (re)register — blocking vphoned's installer, TrollStore, and uicache/Sileo alike. The entitlement route is a dead end even for a launchd platform daemon (vphoned) whose validated csblob (`csops CS_OPS_ENTITLEMENTS_BLOB`) contains all three: LS registration is proxied, so the XPC peer lsd inspects is not the registering process. Fix: NOP the final `cbz w0, <not_entitled>` (the conditional branch whose fall-through sets the `mov w<reg>,#1` result) so the method always returns YES. Fully dynamic: method resolved via the DSC's own `.symbols` in-image local-symbol table (ipsw `symaddr -a`/`a2s` time out on this cache), gate located by control-flow shape in Capstone, NOP from Keystone `asm("nop")`, modified 16 KiB page re-attested (`cfw_dsc_codesign.py`; TXM enforces per-page). The resulting CDHash change is accepted by the JB always-true AMFI cdhash-trust patch. Install gate: **`27.*`** (hard-gated in `cfw_install.sh` as of 2026-07-20 — an 18.x/26.x base does not apply it). The patcher additionally self-gates (`patch-lsd-embedded-reg`): no-op on pre-iOS-27 userlands where the method is absent. **Pairs with vphoned's `vp_register_path` containerized-registration fallback** (`registerContainerizedApplicationWithInfoDictionaries:...:registrationError:`, treating a nil `registrationError` as success since it returns NO even when it registers). Also paired with **`/cores/vpregister`** (built + deployed by `cfw_install_jb.sh` / `cfw_install_exp.sh`, invoked by `vphone_jb_setup.sh` at first boot — 27-gated by DEPLOYMENT: `cfw_install_jb.sh`/`cfw_install_exp.sh` copy `/cores/vpregister` only when the mounted rootfs `SystemVersion.plist` is `27.*`, and the setup script's `[ -x /cores/vpregister ]` presence check is the runtime gate. Do NOT gate the invocation on a guest `sw_vers` check — the hybrid guest does not reliably report the 27 userland version at first boot, which silently skipped registration): it registers JB app bundles (Sileo) via the same containerized API, because `uicache -a`'s `registerApplicationDictionary:` is a deprecated no-op on iOS 27 (lsd logs *"you cannot use ... to register applications anymore. These interfaces have been deprecated for years."*). **VALIDATED (2026-07-17, `17,3_27.0_24A5380h` + cloudOS 26.4, JB): -54 gone; Sileo registers (`uicache -l` 0→1) via `vpregister`; vphoned installs+registers a test IPA (`com.vphone.vptest`) to `/var/containers/Bundle/Application/` end-to-end. Clean boot (re-attest correct; no CoreServices page rejection).** See `scripts/patchers/cfw_patch_lsd_embedded_reg.py` and `Siblings/VPRegister/vpregister.m`. **FIX (2026-08-10):** `_find_gate` only matched the live `cbz`/`cbnz` branch shape, so re-running `cfw install` (host-mount flow, `myphone` VM, `17,3_27.0_24A5390f`) against a cache where this gate was already NOP'd from a prior pass raised `ValueError: ... entitled-result gate ... not found` instead of recognizing the idempotent state (unlike the Cryptex/IOMFB steps, which log `already ... idempotent` and skip cleanly). Confirmed live via host-mount disassembly: the third check's `bl <check3>` is followed by a bare `nop` at the gate site (exact match against `asm("nop")` bytes) immediately before `mov w20, #1` — i.e. already patched. `_find_gate` now also matches `nop` immediately preceding `mov w<reg>,#1` as an already-patched gate, so a re-run just re-attests the page instead of erroring. | Y | Y | Y || 13 | `mov x0,#1; ret` on `-[DIDiskArb isMountCompleteWithExpectedCount:diskTracker:]` — **iOS 27.0** | `diskimagesiod` | **iOS-27 DDI (`/System/Developer`) auto-mount — mount-gate.** After the personalized DDI attaches (kernel side: JB-28 + JB-09), MobileStorageMounter waits on diskimagesiod's `-[DIDiskArb waitForDAMountWithExpectedCount:diskTracker:]` before it does the real (nobrowse) mount at `/System/Developer`. That wait loops until `isMountComplete` (= `callbackReached \|\| (appearedDiskCount>=expectedCount && mountedDiskCount>=mountableDiskCount)`) is YES; on the 26.4-kernel / 27-userland hybrid it never becomes true (not all of the DMG's IOMedia "appear" to diskimagesiod's DiskArbitration session, and diskarbitrationd never auto-mounts the volume), so the wait hangs and pmd3 times out. diskimagesiod itself does NOT mount the DDI (its `-[DIDiskArb mountWithDeviceName:...]` is dead code) — it only gates MobileStorageMounter. Forcing `isMountComplete` → YES lets the wait return so MobileStorageMounter proceeds. IMP resolved via LC_SYMTAB or ObjC metadata (selector → `__objc_selrefs` → `__TEXT,__objc_methlist` relative method list → IMP); prologue overwritten `mov x0,#1 ; ret` (safe — the method returns to the caller's unsigned LR without pushing a frame). **Gated to 27.\*** in `cfw_install.sh` (same `$IOS_VERSION` as the DSC patches): on a version-matched userland the native wait completes correctly and forcing it early could race the real mount, so it is NOT applied there. Embedded sandbox profile + private DA/apfs entitlements preserved on re-sign (`ldid_sign_ent`). **Validated on `c0ecdb4b` 26.4 + 27.0 userland: `pmd3 mounter auto-mount` → rc=0, DDI at `/System/Developer`, idempotent across fresh boots.** See `scripts/patchers/cfw_patch_diskimagesiod.py`. | Y | Y | Y || 14 | Merge backboard/frontboard launch mach-services into `com.apple.security.exception.mach-lookup.global-name` + `ldid_sign_ent` re-sign — **iOS 27.0** | `/Applications/Campo.app/Campo` | **iOS-27 Campo (wallpaper renderer) crash-loop fix — sandbox half.** Campo declares `com.apple.private.sandbox.profile:embedded = temporary-sandbox` + `no-container`, so it runs under the `temporary-sandbox` profile. On the 26.4 vphone600 kernel that builtin profile predates iOS 27 and DENIES the `mach-lookup` of the backboard/frontboard launch services, so `BKSDisplayServicesStart` (looks up `com.apple.backboard.display.services`) and then `+[BKSHIDEventDeliveryManager sharedInstance]` (HID) fail, log *"backboardd isn't running -- or we couldn't talk to it"*, and `brk #0` ~34 ms after launch → continuous crash-loop, no wallpaper (launchd eventually throttles it off). **JB-02d is NOT sufficient here:** it stops the exec-time container-manager-upcall autobox *KILL*, but Campo is still placed in `temporary-sandbox` (its own declared profile — confirmed the JB-02d `b`-flip is present in the running kernel yet Campo still traps), and that profile still denies the lookups. Fix: append the needed services to Campo's OWN `com.apple.security.exception.mach-lookup.global-name` array — the Apple-sanctioned escape hatch, which `temporary-sandbox` honors (Campo already ships ~20 such exceptions; these launch services simply aren't among them because 27's profile allows them directly). Services added (backboard names exact, from `com.apple.backboardd.plist` MachServices): `com.apple.backboard.display.services`, `com.apple.iohideventsystem`, `com.apple.CARenderServer`, `com.apple.backboard.hid.services`, `com.apple.backboard.hid-services.xpc`, `com.apple.backboard.TouchDeliveryPolicyServer`, `com.apple.backboard.system-app-server`, `com.apple.backboard.watchdog`, `com.apple.backboard.oswatchdog`, `com.apple.backboard.altsysapp`, `com.apple.AttentionAwareness`, `PurpleSystemEventPort`, `PurpleWorkspacePort`, `com.apple.frontboard.systemappservices`, `com.apple.frontboard.workspace`, `com.apple.frontboardservices.systemappmanager`, `com.apple.frontboard.watchdog`. Merge is done by the external helper `scripts/patchers/campo_mach_lookup_exceptions.py` (Python `plistlib`, not `plutil` — the entitlement key contains dots that `plutil` keypaths would mis-split; idempotent, preserves the existing array); re-signed with the JB `signcert.p12` via `ldid_sign_ent` (AMFI enforcement is relaxed on the research VM, so the re-signed cdhash loads and the entitlements are honored). Applied at host-mount build time in `cfw_install_jb.sh` / `cfw_install_exp.sh` step **[JB-3b]**, **hard-gated to `27.*`** via the mounted rootfs `SystemVersion.plist` `ProductVersion` (same gate as the vpregister/DSC patches) — skipped entirely on 26.x/18.x, which don't need it and where `Campo.app` also exists. **VALIDATED on-device (2026-07-21, `17,3_27.0_24A5390f` + cloudOS 26.4, JB): Campo launches and stays up (stable pid, no BKSDisplayServicesStart/BKSHIDEventDeliveryManager trap, no crash-loop); first-cut display-only exception advanced the trap from display→HID, confirming the mechanism, then the full service set cleared it.** See `scripts/cfw_install_jb.sh` / `scripts/cfw_install_exp.sh` step JB-3b and the merge helper `scripts/patchers/campo_mach_lookup_exceptions.py`. | - | - | Y |diff --git a/Research/Guest/devicehub_screen_viewing.md b/Research/Guest/devicehub_screen_viewing.mdindex b96d9f07..35cfdf01 100644--- a/Research/Guest/devicehub_screen_viewing.md+++ b/Research/Guest/devicehub_screen_viewing.md@@ -217,20 +217,30 @@ spans are re-attested. On 24A446 it rewrites ten entry points and leaves### Upgrading an existing iOS 27 guest-The patch identifier did not change, and `applyDyldPatches` skips an enabled-patch whose identifier is already in the guest receipt. A guest installed-with the old unconditional patch therefore keeps its 31 four-byte sites until-they are reverted:--1. Stop the VM and run `fw set-patches --block dyld-boot-iomfb_force_kern`,- then `cfw update-environment`. This reverts the old sites.-2. Restore the standard selection and update again with the new bundle. It- writes ten 16-byte sites; the guest's undo log should list ten 16-byte- originals.--A successful install and a receipt listing the identifier do not prove which-bytes are in the cache; read the undo log or the cache itself. A new-`vm create` needs none of this.+Nothing to do by hand: bind the machine to the new bundle with its guest+environment (Launchpad's bundle switch, or `vm set-bundle <vm> <version>+--update-environment`), or run `cfw install` / `cfw update-environment`.++The patch identifier did not change, and `applyDyldPatches` normally skips an+enabled patch whose identifier is already in the guest receipt, which would+leave the old 31 four-byte sites in place for good. The undo log tells the two+implementations apart: the old one recorded 4 bytes per entry point, the new+one 16. `DyldSharedCacheUndoLog.outdatedImplementations` names that shape, and+for such a patch the installer reverts its records and applies the current+implementation in the same run. A second run finds 16-byte records and leaves+the cache alone. If the revert succeeds and the new write fails, the patch is+reported as failed and left out of the receipt rather than listed as applied.++A guest patched before the undo log existed has no records, so it cannot be+reverted this way and keeps the old bytes; it needs a restore.++**Validated (2026-10-07, `iPhone17,3 27.0.1`):** the guest was put back on the+old implementation with bundle 2.6.0 (`31 newly forced`), then bound to the new+bundle with `--update-environment`. The log shows `an earlier implementation is+applied; reverting it and applying the current one`, 31 four-byte reverts and+`10 newly forced, 0 already conditional`. A further `cfw update-environment`+did not touch the patch. After boot the VZ window scanned out and DeviceHub+showed the guest live, 30–40 ms behind the VZ window.## Validationdiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheUndoLog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheUndoLog.swiftindex f7cd5453..4207e695 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheUndoLog.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheUndoLog.swift@@ -220,3 +220,29 @@ public struct DyldSharedCacheUndoLog: Codable, Sendable, Hashable {return spans}}++// MARK: - Earlier implementations++extension DyldSharedCacheUndoLog {+ /// Patches whose implementation changed under the same identifier, and how+ /// a record written by an earlier one looks. A guest receipt only names the+ /// identifier, so without this an installed guest would keep the old bytes+ /// for good; `cfw install` and the environment update use it to revert the+ /// old records and apply the current implementation in the same run.+ ///+ /// `dyld-boot-iomfb_force_kern` first rewrote each swap trampoline's first+ /// instruction, one 4-byte record per entry point. It now writes a 16-byte+ /// conditional dispatcher per entry point, so a 4-byte record is the+ /// unconditional version, which leaves DeviceHub's capture display black.+ public static let outdatedImplementations: [String: @Sendable (Record) -> Bool] = [+ "dyld-boot-iomfb_force_kern": { $0.original.count == 4 },+ ]++ /// Whether any record of `patchID` was written by an earlier+ /// implementation. False for a patch with no records, which cannot be+ /// reverted from this log anyway.+ public func hasOutdatedImplementation(of patchID: String) -> Bool {+ guard let outdated = Self.outdatedImplementations[patchID] else { return false }+ return records(forPatchIDs: [patchID]).contains(where: outdated)+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheUndoLogTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheUndoLogTests.swiftindex 7a3ca93d..4f0f45be 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheUndoLogTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheUndoLogTests.swift@@ -210,3 +210,25 @@ struct DyldSharedCacheUndoLogTests {}}}++@Suite("Dyld patches whose implementation changed")+struct DyldSharedCacheOutdatedImplementationTests {+ private func record(_ id: String, bytes: Int, offset: Int = 0) -> DyldSharedCacheUndoLog.Record {+ .init(patchID: id, chunk: "dyld_shared_cache_arm64e", fileOffset: offset, vma: 0x1_8000_0000, original: Data(count: bytes))+ }++ @Test func `The unconditional force-kern records are an earlier implementation`() {+ let id = "dyld-boot-iomfb_force_kern"+ let old = DyldSharedCacheUndoLog(records: (0..<31).map { record(id, bytes: 4, offset: $0 * 64) })+ #expect(old.hasOutdatedImplementation(of: id))+ let current = DyldSharedCacheUndoLog(records: (0..<10).map { record(id, bytes: 16, offset: $0 * 64) })+ #expect(!current.hasOutdatedImplementation(of: id))+ }++ @Test func `Patches without a recorded change, or without records, are never outdated`() {+ let log = DyldSharedCacheUndoLog(records: [record("dyld-boot-maxslide", bytes: 4)])+ #expect(!log.hasOutdatedImplementation(of: "dyld-boot-maxslide"))+ #expect(!log.hasOutdatedImplementation(of: "dyld-boot-iomfb_force_kern"))+ #expect(!DyldSharedCacheUndoLog().hasOutdatedImplementation(of: "dyld-boot-iomfb_force_kern"))+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex 032fbab9..3dd822bf 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -1342,8 +1342,8 @@ struct VPhoneCustomFirmwareInstaller {func enabled(_ id: String) -> Bool { plan?.isEnabled(id) ?? true }let undoAbsolute = (dsc as NSString).appendingPathComponent(Self.dscUndoLogLeaf)let undoRelative = "\(Self.dscCacheRelative)/\(Self.dscUndoLogLeaf)"- let recorded = (try? system.readData(undoRelative))- .flatMap { try? DyldSharedCacheUndoLog.decode($0) }?.patchIDs ?? []+ let undoLog = (try? system.readData(undoRelative)).flatMap { try? DyldSharedCacheUndoLog.decode($0) }+ let recorded = undoLog?.patchIDs ?? []var revertable: [String] = []for entry in dyld {@@ -1351,7 +1351,27 @@ struct VPhoneCustomFirmwareInstaller {let had = priorGuest.contains(entry.id)switch (want, had) {case (true, true):- // Already applied; leave it, no scan.+ // Already applied; leave it, no scan — unless the bytes on disk+ // are an earlier implementation of the same identifier. Then put+ // the originals back and apply the current one, in this run.+ if let undoLog, undoLog.hasOutdatedImplementation(of: entry.id) {+ print(" [*] \(entry.id): an earlier implementation is applied; reverting it and applying the current one")+ do {+ try patch("patch-dsc-revert", [dsc, "--undo-log", undoAbsolute, "--patch", entry.id])+ } catch {+ failures.append(entry.id)+ live.insert(entry.id)+ print(" [!] \(entry.id): reverting the earlier implementation failed, left as it was: \(error)")+ continue+ }+ do {+ try patch(entry.verb, entry.args + ["--undo-log", undoAbsolute, "--undo-id", entry.id])+ } catch {+ failures.append(entry.id)+ print(" [!] \(entry.id): the earlier implementation was reverted but the current one failed; the cache is unpatched for it: \(error)")+ continue+ }+ }live.insert(entry.id)case (true, false):do {