Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

kernel: jb: Fix iOS 27 native VZ-view display (force the kern present path)

zqxwce9c1227f89b98
diff --git a/research/0_binary_patch_comparison.md b/research/0_binary_patch_comparison.md
index ede8035d..a0788a7a 100644
--- a/research/0_binary_patch_comparison.md
+++ b/research/0_binary_patch_comparison.md
@@ -127,7 +127,6 @@
| JB-01 | A | `patch_amfi_cdhash_in_trustcache` | `AMFIIsCDHashInTrustCache` | Always return true + store hash | Y |
| JB-02 | A | `patch_amfi_execve_kill_path` | AMFI execve kill return site | Convert shared kill return from deny to allow (superseded by C21; standalone only) | N |
| JB-02b| C | `patch_exec_security_policy_kill` | XNU exec `imgp->ip_mac_return` gate (kern_exec, `os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SECURITY_POLICY)` site) | Flip `cbz wN, <skip>` → unconditional `b <skip>` so the exec-time MAC-verdict `SECURITY_POLICY` kill is unreachable. **Needed to run a userland NEWER than the kernel (iOS 27.0 on the 26.4 kernel):** AMFI's exec hooks reject the newer binaries' code-sign validation category, setting `ip_mac_return != 0` → core daemons (backboardd/cfprefsd/containermanagerd/…) die at exec (`namespace 9 / code 0x8`) → boot deadlock. Validated on 27.0/26.4: 0 SECURITY_POLICY kills, daemons launch, networking + SSH come up. No-op-in-effect for version-matched userlands (ip_mac_return == 0 there, so the original cbz already skips). | Y |
-| JB-02c| B | `patch_paravirt_display_primary` | `AppleParavirtDisplay` IOKit `setProperty("primary", <flag>, 32)` value load (`ldr w2,[xN,#imm]`) | Rewrite the value load to `mov w2,#1` so the VM's single paravirt display is published `primary=1`. **Needed for the display on iOS 27:** 27 refactored FrontBoard (`FBSDisplayMonitor`) to REQUIRE a designated main display (`_initWithDisplays:mainDisplay:` hard-asserts non-nil; new `isMainDisplay:` threading — foldable/multi-display groundwork). The paravirt display was published `primary=0` / `Transport=Other`, so CoreDisplay/FrontBoard saw no built-in main display → `mainDisplay=nil` → SpringBoard crash-loops (`failed to initialize mainDisplay source`) → black screen. Anchor (structural): exact `"primary\0"` cstring xref whose site is the `setProperty(key,value,32)` form (`add …,#<primary>` → `mov w3,#0x20` → `blraa`), then the nearest preceding `ldr w2,[…]`. **DISABLED — WRONG THEORY, HARMFUL on iOS 27 (2026-07-15).** primary=1 was based on the mistaken belief that iOS 27 keys mainDisplay off the IOMFB `primary` property. It does not; instead 27 reads the `primary` property VALUE and appends it as the display-name suffix → the display is named `"primary-1"`, which then FAILS the render server's exact-name match → still no mainDisplay. The real cause was the IOUC sandbox gate (see JB-10b), which is the actual fix. Keep this OFF (primary must stay 0 so the name is `"primary"`). | N |
| JB-03 | C | `patch_cred_label_update_execve` | `_cred_label_update_execve` | Reworked C21-v3: C21-v1 already boots; v3 keeps split late exits and additionally ORs success-only helper bits `0xC` after clearing `0x3F00`; still disabled pending boot validation | N |
| JB-04 | C | `patch_hook_cred_label_update_execve` | sandbox `mpo_cred_label_update_execve` wrapper (`ops[18]` -> `sub_FFFFFE00093BDB64`) | Faithful upstream C23 trampoline: copy `VSUID`/`VSGID` owner state into pending cred, set `P_SUGID`, then branch back to wrapper | Y |
| JB-05 | C | `patch_kcall10` | `sysent[439]` (`SYS_kas_info` replacement) | Rebuilt ABI-correct kcall cave: `target + 7 args -> uint64 x0`; re-enabled after focused dry-run validation | Y |
@@ -152,6 +151,8 @@
| JB-23 | B | `patch_thid_should_crash` | `_thid_should_crash` | Prevent GUARD_TYPE_MACH_PORT crash | Y |
| JB-24 | B | `patch_vm_fault_enter_prepare` | `_vm_fault_enter_prepare` | Force `cs_bypass` fast path in runtime fault validation | Y |
| JB-25 | B | `patch_vm_map_protect` | `_vm_map_protect` | Skip upstream write-downgrade gate. Shape A (26.1–26.4) active; **Shape B (26.5) disabled 2026-07-05** — widened the `~VM_PROT_WRITE` COW strip (vm_map.c:6202) instead of the RWX gate (vm_map.c:5997), breaking COW and crashing the debugger (SPTM `VIOLATION_ILLEGAL_MAP`). Retired on 26.5+: SPTM code-mod (debugger + Substrate tweaks) uses write-then-flip via `vm_protect(VM_PROT_COPY)` → `XNU_USER_DEBUG`, so no RWX patch is needed. | Y/N |
+| JB-26 | B | `patch_iomfb_swapend_variable_size` | IOMFB userclient method-5 (SwapEnd) `__DATA_CONST` dispatch entry (`checkStructureInputSize`) | **iOS-27 VZ-view fix, kernel half — paired with DSC force-kern (DSC-patch item 11).** The 26.4 userclient's method-5 dispatch entry hard-checks `checkStructureInputSize == 0x588`; forced-kern iOS 27 sends its native `0x6e0`. Rewrite the size field to `kIOUCVariableStructureSize (0xFFFFFFFF)` so `IOUserClient::externalMethod` accepts 27's struct and reaches the handler. Anchor (structural): the sole `__DATA_CONST` entry `{ptr(ptrauth, top-byte≥0x80), scalarIn=0, structIn=0x588, scalarOut=0, structOut=0}` (verified unique; decompressed file-off 0x9c7228). No-op-in-effect for version-matched 26.x (sends 0x588). Re-enabled 2026-07-15 (was disabled when 27 present-path was still unknown). | Y |
+| JB-27 | B | `patch_iomfb_swapend_handler_size` | method-5 handler internal size gate (`cmp w2,#0x588 ; b.ne <err>`) | Companion to JB-26: beyond the dispatch-table check the handler re-checks the struct size (`cmp w2,#0x588 ; b.ne <kIOReturnBadArgument>`; verified unique at decompressed file-off 0x16ae22c; success path forwards the raw struct ptr to a `vtable+0x590` paravirt swap method). Retarget the `cmp` immediate to `0x6e0` so forced-kern iOS 27's native SwapEnd reaches real swap processing (27's IOMFBSwapRec prefix matches 26.x → handler reads valid fields). Semantic anchor (`cmp w2,#imm` word + following `b.ne` decode). Enabled together with JB-26 + DSC force-kern for iOS 27. | Y |
### EXP-Only Kernel Methods (Reference List)
@@ -177,8 +178,9 @@ do NOT execute these).
| 6 | Weak dylib load injection | `launchd` | Load short alias `/b` (copy of `launchdhook.dylib`) at launch. On by default; set `DISABLE_LAUNCHD_HOOK=1` to skip because this pid-1 hook path is boot-critical and has produced boot-analysis failures | - | Y | Y |
| 7 | cstring byte 5 mangle `'h' → 'X'` (`"kern.hv_vmm_present"` → `"kern.Xv_vmm_present"`) + per-page slot-hash re-attestation, BLACKLIST semantics — **EXP only** | DSC dylibs | Companion to EXP kernel rename (`KernelEXPPatcher.patchHvVmmRename`). The mangle is applied to every DSC dylib EXCEPT those in `DONT_PATCH_INSTALL_NAMES` (sign-in / device-likeness consumers, ~15 entries). Patched dylibs query `kern.Xv_vmm_present` and get the truthful 1 (graphics / accel passthrough). Blacklisted dylibs keep the original cstring, hit ENOENT on the renamed kernel, cache 0, lie about VM presence. On `codeSigningMonitor == 2` hardware the byte-mangle alone causes `CODESIGNING/Invalid Page` SIGKILL because TXM enforces per-page hashes; the re-attestation pass recomputes the SHA-256 slot in the chunk's `CS_CodeDirectory` for every modified 16 KiB page. See `scripts/patchers/cfw_dsc_codesign.py` and `cfw_patch_hv_vmm_dsc.py`. | - | - | - |
| 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, 18.x, and 27.0** | 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. **Target is chosen per base**: because reliably reading it from the kernelcache needs the IOMFB userclient dispatch table (a blind shape-scan is ambiguous — 8 candidates), the install keys the target off the userland version as an interim proxy for the validated base pairing — `27.*` -> 0x588 (26.4 base), `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; 26.4-base + 27.0 (-> 0x588) patched + re-attested clean on the 24A5380h DSC, pending on-device display confirmation. TODO: replace the version proxy with real per-kernel `checkStructureInputSize` detection. | Y | Y | Y |
+| 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). Self-gating (`patch-dsc-maxslide`): no-op unless span + maxSlide > `0x180000000`, so 26.x / 18.x are untouched. **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). | Y | Y | Y |
### Installed Components
diff --git a/scripts/cfw_install.sh b/scripts/cfw_install.sh
index ce106f92..e66bf888 100755
--- a/scripts/cfw_install.sh
+++ b/scripts/cfw_install.sh
@@ -300,22 +300,32 @@ fi
# Known userland-sent sizes: 18.x -> 0x514, 26.0/26.0.1 -> 0x548, 27.0 -> 0x6e0.
# Patch only that immediate in the installed DSC; the patcher is semantic +
# idempotent (rewrites the SwapEnd size to the target, no-op if already there).
-# NOTE: iOS 27 is intentionally NOT truncated here — its swap struct (0x6e0) has
-# a new layout, so size-truncation to 0x588 feeds the kernel misaligned data.
-# Instead the JB kernel patch `patchIomfbSwapEndVariableSize` makes the userclient
-# accept iOS 27's native 0x6e0 struct (variable-size dispatch), so 27 must send
-# its native size — leave it unpatched here.
+# NOTE: iOS 27 is NOT handled by the size-truncation path — its swap struct
+# (0x6e0) has a new layout, and more fundamentally 27 defaults the paravirt
+# display's present to IOMFB's `_virt_*` callback path, which never enters the
+# userclient at all (method 5 is never called), so no size change would help.
+# iOS 27 instead gets `patch-iomfb-force-kern` below, which retargets IOMFB's
+# public Swap* trampolines to their `_kern_*` (method-5) siblings — the path the
+# 26.4 paravirt GPU scans out to the host — paired with the KernelJBPatchIomfbSwap
+# kernel patches that make the userclient accept 27's native 0x6e0 struct.
IOS_VERSION=$(/usr/bin/plutil -extract ProductVersion raw -o - "$MNT1/System/Library/CoreServices/SystemVersion.plist" 2>/dev/null || true)
+DSC_DIR="$MNT1/System/Cryptexes/OS/System/Library/Caches/com.apple.dyld"
IOMFB_TARGET=""
case "$IOS_VERSION" in
26.0*|18.*) IOMFB_TARGET=0x560 ;;
esac
if [[ -n "$IOMFB_TARGET" ]]; then
echo " [*] Patching IOMobileFramebuffer SwapEnd payload size (iOS $IOS_VERSION -> $IOMFB_TARGET)..."
- DSC_DIR="$MNT1/System/Cryptexes/OS/System/Library/Caches/com.apple.dyld"
[[ -d "$DSC_DIR" ]] || die "dyld cache dir missing: $DSC_DIR"
"$PYTHON3" "$SCRIPT_DIR/patchers/cfw.py" patch-iomfb-swapend "$DSC_DIR" --target-size "$IOMFB_TARGET"
fi
+case "$IOS_VERSION" in
+ 27.*)
+ echo " [*] Forcing IOMobileFramebuffer present onto the kern (method-5) path (iOS $IOS_VERSION)..."
+ [[ -d "$DSC_DIR" ]] || die "dyld cache dir missing: $DSC_DIR"
+ "$PYTHON3" "$SCRIPT_DIR/patchers/cfw.py" patch-iomfb-force-kern "$DSC_DIR"
+ ;;
+esac
# Newer userlands ship a dyld shared cache that nearly fills the vphone600 26.x
# kernel's fixed 6 GiB shared region. The kernel reserves the cache's mapped span
diff --git a/scripts/patchers/cfw.py b/scripts/patchers/cfw.py
index 146564bd..f04b1732 100755
--- a/scripts/patchers/cfw.py
+++ b/scripts/patchers/cfw.py
@@ -34,6 +34,15 @@ Commands:
payload size from 0x548 to 0x560 for the PCC vphone600 userclient,
then re-attest the modified DSC page hash.
+ patch-iomfb-force-kern <chunks_dir> [--dry-run]
+ iOS 27 VZ-view fix: retarget IOMobileFramebuffer's public
+ _IOMobileFramebufferSwap* dispatch trampolines to their _kern_Swap*
+ siblings, forcing present onto the userclient method-5 path the 26.4
+ paravirt GPU scans out to the host (27 defaults to the _virt_* callback
+ path the paravirt GPU never receives). Re-attests modified DSC pages.
+ Pairs with the KernelJBPatchIomfbSwap kernel patches (accept 27's 0x6e0
+ SwapEnd struct).
+
patch-dsc-maxslide <chunks_dir> [--dry-run]
Zero the dyld_cache_header maxSlide when the userland cache would overflow
the vphone600 26.x kernel's 6 GiB shared region (cache span + maxSlide >
@@ -90,6 +99,7 @@ if __name__ == "__main__":
from patchers.cfw_patch_jetsam import patch_launchd_jetsam
from patchers.cfw_patch_hv_vmm_dsc import patch_hv_vmm_in_dsc
from patchers.cfw_patch_iomfb_swapend import patch_iomfb_swapend
+ from patchers.cfw_patch_iomfb_force_kern import patch_iomfb_force_kern
from patchers.cfw_patch_dsc_maxslide import patch_dsc_maxslide
from patchers.cfw_patch_camera_dsc import apply_all_camera_patches
from patchers.cfw_patch_watchdogd import patch_watchdogd
@@ -101,6 +111,7 @@ else:
from .cfw_patch_jetsam import patch_launchd_jetsam
from .cfw_patch_hv_vmm_dsc import patch_hv_vmm_in_dsc
from .cfw_patch_iomfb_swapend import patch_iomfb_swapend
+ from .cfw_patch_iomfb_force_kern import patch_iomfb_force_kern
from .cfw_patch_dsc_maxslide import patch_dsc_maxslide
from .cfw_patch_camera_dsc import apply_all_camera_patches
from .cfw_patch_watchdogd import patch_watchdogd
@@ -175,6 +186,18 @@ def main():
sys.exit(1)
sys.exit(0)
+ elif cmd == "patch-iomfb-force-kern":
+ if len(sys.argv) < 3:
+ print("Usage: patch_cfw.py patch-iomfb-force-kern <chunks_dir> [--dry-run]")
+ sys.exit(1)
+ dry_run = "--dry-run" in sys.argv[3:]
+ try:
+ patch_iomfb_force_kern(sys.argv[2], dry_run=dry_run)
+ except ValueError as e:
+ print(f"[-] {e}")
+ sys.exit(1)
+ sys.exit(0)
+
elif cmd == "patch-dsc-maxslide":
if len(sys.argv) < 3:
print("Usage: patch_cfw.py patch-dsc-maxslide <chunks_dir> [--dry-run]")
@@ -244,7 +267,7 @@ def main():
print(f"Unknown command: {cmd}")
print("Commands: cryptex-paths, patch-seputil, patch-launchd-cache-loader, patch-camera-dsc,")
print(" patch-mobileactivationd, patch-launchd-jetsam,")
- print(" patch-hv-vmm-dsc, patch-iomfb-swapend, patch-dsc-maxslide, patch-watchdogd,")
+ print(" patch-hv-vmm-dsc, patch-iomfb-swapend, patch-iomfb-force-kern, patch-dsc-maxslide, patch-watchdogd,")
print(" inject-daemons, patch-dropbear-plist, inject-dylib")
sys.exit(1)
diff --git a/scripts/patchers/cfw_patch_iomfb_force_kern.py b/scripts/patchers/cfw_patch_iomfb_force_kern.py
new file mode 100644
index 00000000..1988efdc
--- /dev/null
+++ b/scripts/patchers/cfw_patch_iomfb_force_kern.py
@@ -0,0 +1,159 @@
+"""Force IOMobileFramebuffer to present through the kern (userclient method-5)
+path instead of the virt (in-process callback) path.
+
+Why: on the vphone600 26.x kernel the host VZ display is fed by the guest
+AppleParavirtGPU scanout, which is driven ONLY by the IOMFB userclient swap
+methods — the `_kern_Swap*` family (`_kern_SwapEnd` == external method 5).
+26.x userlands presented via `_kern_*` (which is why the SwapEnd size patch,
+cfw_patch_iomfb_swapend, fixed the VZ view on 26.0/18.x). iOS 27 routes the
+paravirt display's present through the PARALLEL `_virt_Swap*` family instead —
+`_virt_SwapEnd` performs no userclient call; it invokes an in-process callback
+and hands the composited IOSurface to a virtual-display consumer. Those frames
+never enter the kernel userclient, so the paravirt GPU never scans out and the
+host VZ window stays black (the guest still composites — the GUI is visible
+over the in-guest TrollVNC capturer, and AppleParavirtGPU's scheduler sits idle).
+
+The public `_IOMobileFramebufferSwap*` entrypoints are thin dispatch
+trampolines that tail-call a per-connection function pointer:
+
+ cbz x0, <fail>
+ ldr xN, [x0, #<slot>] ; the connection's swap fp (kern or virt impl)
+ cbz xN, <fail>
+ braaz xN ; tail-call, all argument registers intact
+
+This patcher rewrites the FIRST instruction of each such trampoline to an
+unconditional `b _kern_Swap<Name>`. Because the trampoline tail-calls with the
+argument registers untouched, `b _kern_Swap<Name>` is behaviourally identical
+to the connection having selected the kern fp — every present call now routes
+through the kern/method-5 implementation regardless of how iOS 27 classified
+the display.
+
+Companion kernel patch (KernelJBPatchIomfbSwap): make the 26.4 userclient
+accept iOS 27's native 0x6e0 SwapEnd struct (26.x sent 0x588). Both are
+required together — forcing kern without the kernel size-accept makes method 5
+return kIOReturnBadArgument.
+
+Nothing is hardcoded: the public entrypoints and their `_kern_` counterparts
+are resolved by NAME via `ipsw dyld symaddr`, the trampoline shape is verified
+by Capstone decode, and the replacement branch bytes come from the
+Keystone-backed `asm_at()` helper. The modified DSC code page(s) are re-attested.
+"""
+
+import os
+import re
+import shutil
+import subprocess
+
+try:
+ from .cfw_asm import asm_at, _cs
+ from .cfw_dsc_chunks import DSCChunks
+ from .cfw_dsc_codesign import reattest_modified_pages
+except ImportError: # direct execution
+ from cfw_asm import asm_at, _cs
+ from cfw_dsc_chunks import DSCChunks
+ from cfw_dsc_codesign import reattest_modified_pages
+
+
+IOMFB = "/System/Library/PrivateFrameworks/IOMobileFramebuffer.framework/IOMobileFramebuffer"
+
+# The present transaction the render server drives; each public entrypoint is
+# retargeted to its `_kern_` sibling if (and only if) it is a thin dispatch
+# trampoline. The set is discovered at runtime — this is the minimum that MUST
+# be present for the patch to be meaningful (else we raise, rather than ship a
+# half-forced, incoherent swap path).
+REQUIRED = ("SwapBegin", "SwapEnd", "SwapSetLayer")
+
+
+def _all_symbols(dsc_path, image):
+ """Return {symbol_name: vmaddr} for every symbol `ipsw` reports in `image`."""
+ ipsw_bin = shutil.which("ipsw")
+ if not ipsw_bin:
+ raise RuntimeError("`ipsw` not in PATH")
+ out = subprocess.run(
+ [ipsw_bin, "dyld", "symaddr", dsc_path, "--image", image],
+ capture_output=True, text=True, check=True,
+ ).stdout
+ syms = {}
+ for line in out.splitlines():
+ line = re.sub(r"\x1b\[[0-9;]*m", "", line)
+ m = re.match(r"\s*(0x[0-9A-Fa-f]+):\s+\([^)]*\)\s+(\S+)", line)
+ if m:
+ syms.setdefault(m.group(2), int(m.group(1), 16))
+ return syms
+
+
+def _is_dispatch_trampoline(chunks, va):
+ """True iff the 4 insns at `va` are `cbz x0,.. ; ldr xN,[x0,#imm] ; cbz xN,.. ; braaz xN`."""
+ insns = list(_cs.disasm(chunks.bytes_at_vma(va, 4 * 4), va))
+ if len(insns) < 4:
+ return False
+ i0, i1, i2, i3 = insns[:4]
+ if i0.mnemonic != "cbz" or not i0.op_str.startswith("x0,"):
+ return False
+ if i1.mnemonic != "ldr" or "[x0, #" not in i1.op_str:
+ return False
+ reg = i1.op_str.split(",")[0].strip() # scratch reg the fp is loaded into
+ if i2.mnemonic != "cbz" or not i2.op_str.startswith(reg + ","):
+ return False
+ if i3.mnemonic not in ("braaz", "braa", "br") or not i3.op_str.startswith(reg):
+ return False
+ return True
+
+
+def patch_iomfb_force_kern(chunks_dir, *, dsc_path=None, dry_run=False):
+ chunks = DSCChunks(chunks_dir)
+ print(f" [.] {chunks!r}")
+
+ if dsc_path is None:
+ dsc_path = os.path.join(chunks_dir, "dyld_shared_cache_arm64e")
+
+ syms = _all_symbols(dsc_path, IOMFB)
+
+ # Every public swap entrypoint with a `_kern_` sibling.
+ pub_prefix = "_IOMobileFramebufferSwap"
+ candidates = []
+ for name, va in syms.items():
+ if not name.startswith(pub_prefix):
+ continue
+ suffix = "Swap" + name[len(pub_prefix):] # e.g. "SwapEnd"
+ kern = "_kern_" + suffix
+ if kern in syms:
+ candidates.append((suffix, name, va, kern, syms[kern]))
+ candidates.sort()
+
+ modified = []
+ forced = set()
+ for suffix, pub_name, pub_va, kern_name, kern_va in candidates:
+ if not _is_dispatch_trampoline(chunks, pub_va):
+ print(f" [=] {pub_name} not a thin trampoline; leaving on virt path")
+ continue
+ b_bytes = asm_at(f"b #{kern_va}", pub_va)
+ if len(b_bytes) != 4:
+ raise RuntimeError(f"expected 4 bytes for b, got {len(b_bytes)}")
+ before = next(_cs.disasm(chunks.bytes_at_vma(pub_va, 4), pub_va))
+ print(f" [+] {pub_name} @ 0x{pub_va:X}: "
+ f"'{before.mnemonic} {before.op_str}' -> 'b {kern_name}' (0x{kern_va:X})")
+ if not dry_run:
+ chunks.write_at_vma(pub_va, b_bytes)
+ modified.append(pub_va)
+ forced.add(suffix)
+
+ missing = [s for s in REQUIRED if s not in forced]
+ if missing:
+ raise ValueError(
+ f"force-kern did not retarget required entrypoints {missing} "
+ f"(found trampolines: {sorted(forced)})"
+ )
+
+ if not dry_run:
+ print(f" [.] re-attesting {len(set(modified))} modified page(s)...")
+ reattest_modified_pages(chunks, modified, dry_run=False)
+ for va in modified:
+ ins = next(_cs.disasm(chunks.bytes_at_vma(va, 4), va))
+ if ins.mnemonic != "b":
+ raise RuntimeError(f"post-write verify failed at 0x{va:X} ({ins.mnemonic})")
+ else:
+ print(f" [.] dry-run: would re-attest {len(set(modified))} page(s)")
+
+ print(f" [+] IOMFB force-kern complete: {len(modified)} entrypoint(s) -> _kern_*")
+ return len(modified)
diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchParavirtDisplay.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchParavirtDisplay.swift
deleted file mode 100644
index 0d700a3c..00000000
--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchParavirtDisplay.swift
+++ /dev/null
@@ -1,110 +0,0 @@
-// KernelJBPatchParavirtDisplay.swift — JB kernel patch: publish the VM's single
-// AppleParavirtDisplay as the primary/main display.
-//
-// iOS 27 refactored FrontBoard (FBSDisplayMonitor) to REQUIRE a designated main
-// display: `-[FBSDisplayMonitor _initWithDisplays:mainDisplay:bookendObserver:transformer:]`
-// hard-asserts `mainDisplay != nil`, and the new `isMainDisplay:` flag is threaded
-// through display construction. (Groundwork for multi-display/foldable hardware.)
-//
-// The VZ paravirt display is published generic: `AppleParavirtDisplay` sets its IOKit
-// "primary" property from a per-display field that is 0, so CoreDisplay/FrontBoard
-// never sees a built-in/primary display → mainDisplay stays nil → SpringBoard
-// crash-loops ("failed to initialize mainDisplay source -> mainDisplay=(null)") →
-// black screen. iOS 26.x had no main-display requirement, so the same VM booted fine.
-//
-// Force the published value to 1. In AppleParavirtDisplay the property is set via
-// IOKit `setProperty("primary", value, 32)`; the value is loaded into w2 by a
-// `ldr w2,[xN,#imm]` immediately before the call. Rewrite that load to `mov w2,#1`
-// so the sole display is always published primary=1.
-//
-// Anchor (structural, no hardcoded offsets): the exact "primary\0" cstring xref
-// whose call site is the `setProperty(key, value, numberOfBits=32)` form — an
-// `add xN,xN,#<primary>` followed within a few insns by `mov w3,#0x20` then a
-// `blraa` — distinguishing it from the sibling getProperty("primary") ref. From
-// that ADRP, the nearest preceding `ldr w2,[…]` is the value load to rewrite.
-//
-// Safe for iOS 26.x too: a single display legitimately IS the primary display, so
-// forcing primary=1 matches reality; 26.x simply didn't require it.
-
-import Foundation
-
-extension KernelJBPatcher {
- @discardableResult
- func patchParavirtDisplayPrimary() -> Bool {
- log("\n[JB] AppleParavirtDisplay 'primary' -> 1 (publish VM display as main; iOS 27 FBSDisplayMonitor)")
-
- guard let (ks, ke) = kernTextRange else {
- log(" [-] no kernel text range")
- return false
- }
-
- // ADRP+ADD refs to the exact "primary\0" cstring within kext __TEXT_EXEC.
- let refs = findStringRefs(in: (start: ks, end: ke), string: "primary")
- guard !refs.isEmpty else {
- log(" [-] no refs to \"primary\" cstring")
- return false
- }
-
- var hits: [Int] = []
- for (adrpOff, addOff) in refs {
- // Confirm the setProperty(key, value, numberOfBits=32) shape: after the
- // ADD that completes the "primary" pointer, a `mov w3,#0x20` then a
- // `blraa`. Skips the sibling getProperty("primary") reference.
- var sawBits = false
- var sawCall = false
- var o = addOff + 4
- var steps = 0
- while steps < 8, o + 4 <= ke {
- guard let ins = disasAt(o) else { break }
- if ins.mnemonic == "mov",
- ins.operandString.contains("w3"),
- ins.operandString.contains("0x20") {
- sawBits = true
- }
- if ins.mnemonic == "blraa" {
- sawCall = true
- break
- }
- o += 4
- steps += 1
- }
- guard sawBits, sawCall else { continue }
-
- // The setProperty value lives in w2, loaded just before the ADRP via
- // `ldr w2,[xN,#imm]` (the per-display primary flag == 0). Find it.
- var l = adrpOff - 4
- var back = 0
- while back < 12, l >= ks {
- if let ins = disasAt(l),
- ins.mnemonic == "ldr",
- ins.operandString.hasPrefix("w2,") {
- hits.append(l)
- break
- }
- l -= 4
- back += 1
- }
- }
-
- guard hits.count == 1 else {
- log(" [-] paravirt-display primary value-load not found uniquely (found \(hits.count))")
- return false
- }
-
- let ldrOff = hits[0]
- guard let movBytes = ARM64Encoder.encodeMovzW(rd: 2, imm16: 1) else {
- log(" [-] failed to encode mov w2,#1")
- return false
- }
-
- let va = fileOffsetToVA(ldrOff)
- emit(
- ldrOff,
- movBytes,
- patchID: "paravirt_display_primary",
- virtualAddress: va,
- description: "ldr w2,[primary flag] -> mov w2,#1 [publish VM display as primary/main for iOS 27]"
- )
- return true
- }
-}
diff --git a/sources/FirmwarePatcher/Kernel/KernelJBPatcher.swift b/sources/FirmwarePatcher/Kernel/KernelJBPatcher.swift
index b89693b6..07a57dbb 100644
--- a/sources/FirmwarePatcher/Kernel/KernelJBPatcher.swift
+++ b/sources/FirmwarePatcher/Kernel/KernelJBPatcher.swift
@@ -72,29 +72,26 @@ public final class KernelJBPatcher: KernelJBPatcherBase, Patcher {
// No-op-in-effect for version-matched userlands (ip_mac_return == 0 there).
patchExecSecurityPolicyKill()
- // DISABLED (kept off): these three were an earlier, WRONG theory that the
- // iOS-27 black screen was an IOMFB SwapEnd size/struct ABI issue. Root
- // cause is actually the IOUC *sandbox* gate denying backboardd the
- // framebuffer — fixed by patchIoucFailedSandbox() above. Leave these off:
- // - patchParavirtDisplayPrimary sets the display's "primary" property=1,
- // which iOS 27 turns into the device NAME suffix ("primary-1"), which
- // then fails the render server's exact name match → HARMFUL.
- // - the SwapEnd patches target a present path iOS 27 never takes (method
- // 5 is never called) and would break 26.x's native 0x588 SwapEnd.
+ // iOS 27 VZ-view (host paravirt-GPU scanout) fix — kernel half of the
+ // "force the kern present path" pair:
//
- // Publish the VM's single paravirt display as primary=1 so iOS 27's
- // FBSDisplayMonitor finds a main display (else SpringBoard crash-loops on a
- // nil mainDisplay assertion → black screen). Harmless for iOS 26.x bases.
- // patchParavirtDisplayPrimary()
-
- // Accept iOS 27's native 0x6e0 IOMFBSwapRec (variable-size dispatch)
- // instead of truncating userland to 0x588 (which misaligns 27's layout).
- // Paired with leaving iOS 27 userland at native size (cfw_install gate).
- // patchIomfbSwapEndVariableSize()
- // The handler has a SECOND internal exact-size gate (cmp w2,#0x588) beyond
- // the dispatch check; retarget it to iOS 27's 0x6e0 so the native struct
- // reaches the real swap processing.
- // patchIomfbSwapEndHandlerSize()
+ // The 26.4 kernel's paravirt GPU only scans a frame out to the host when
+ // the guest presents via the IOMFB userclient SwapEnd (external method 5).
+ // iOS 27 defaults the paravirt display's present to IOMFB's parallel
+ // `_virt_*` path (an in-process callback that never enters the userclient),
+ // so the paravirt GPU never scans out → host VZ window is black (the guest
+ // still composites; visible over in-guest TrollVNC). cfw_patch_iomfb_force_kern
+ // (userland half) retargets IOMFB's public `_IOMobileFramebufferSwap*`
+ // trampolines to `_kern_Swap*`, forcing present back onto method 5. But
+ // iOS 27's native SwapEnd struct is 0x6e0 bytes (26.x sent 0x588), and the
+ // 26.4 userclient exact-checks 0x588 in TWO places, so method 5 would return
+ // kIOReturnBadArgument. These two patches relax both size gates to accept
+ // 27's 0x6e0 (its IOMFBSwapRec prefix matches 26.x, so the paravirt swap
+ // handler reads valid fields):
+ // 1. dispatch-table checkStructureInputSize 0x588 → variable
+ patchIomfbSwapEndVariableSize()
+ // 2. the handler's internal `cmp w2,#0x588` gate → 0x6e0
+ patchIomfbSwapEndHandlerSize()
return patches
}