Run a virtual iPhone on an Apple Silicon Mac.
Swift
Re-attest the dyld cache header page after clamping maxSlide
Chenx Dusta68a5331f127
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex 40b4723f..a7a3781d 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -621,7 +621,7 @@ do NOT execute these).| 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 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 |+| 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. Page 0 of the main chunk is re-attested (since 2026-10-13). The kernel does not need it: a cache left with page 0's original slot boots, as validated below. Xcode does: `xcodebuild -prepareDeviceSupport` copies the guest's cache and its `dsc_extractor` stops on `dyld shared cache code signature for page 0 is incorrect`, yet marks the copy done, so Device Support holds only the DriverKit cache and LLDB reads every system library from guest memory (minutes of black screen for any app launched under the debugger, e.g. a Flutter debug run). Seen on `iPhone17,3 27.0.1 (24A446)`: the stored slot matched the header with `maxSlide 0x20000000`, not the patched one. A run over a header already at `maxSlide 0` re-attests page 0 too, and `cfw install`/`update-environment` re-run this verb whenever it is live (`dyldPatchesRerunWhenLive`), because its undo record cannot tell the old implementation from the new. 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; 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 |diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swiftindex f4fdfe7c..6fe82992 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swift@@ -34,29 +34,8 @@// The fix is to zero `maxSlide`, so the cache maps at slide 0 and fits — iOS// 27.0 leaves ~58 MiB spare. ASLR of the shared cache is lost; nothing else is.//-// This patcher does NOT re-attest, and that is deliberate-// --------------------------------------------------------// Every other DSC patcher in this module rewrites an instruction inside a-// dylib's `__TEXT` and has to repair the 16 KiB page slot that covers it, or-// the guest takes a KERN_PROTECTION_FAILURE on the first demand-page-in.-//-// `maxSlide` is not that. It is a field of `dyld_cache_header`, read by the-// kernel while it is setting the mapping up — not a `cs_validate`'d code page.-// The Python reference states the same thing and backs it with a live test: a-// cache poked to maxSlide=0 booted with "dyld cache mapped system-wide" and 0-// panics, and `Research/0_binary_patch_comparison.md` row 10 records the-// on-device validation on `17,3_27.0_24A5380h` + cloudOS 26.4.-//-// So `DyldSharedCacheCodeSignature.reattestRecordedWrites(in:)` is *not* called here, and-// after this patcher runs the main chunk's page 0 hashes to something its code-// slot no longer claims. `DyldSharedCacheMaxSlidePatcherTests` pins that state rather than-// leaving it as a thing someone has to remember.-//-// To keep a later batch re-attestation from silently undoing that decision,-// this patcher opens its own `DyldSharedCacheChunkSet` over the directory instead of-// borrowing the caller's. Its write is recorded in a chunk set that goes out of-// scope with the call, so no caller's `reattestRecordedWrites(in:)` can sweep-// the header page up with the code pages it legitimately owns.+// Page 0 is re-attested although the kernel boots without it: Xcode's+// `dsc_extractor` rejects a stale header slot (see row 10 of 0_binary_patch_comparison.md).//// On the CLAUDE.md patcher guardrails// -----------------------------------@@ -167,13 +146,15 @@ public enum DyldSharedCacheMaxSlidePatcher {public let record: PatchRecord?/// The span that landed on disk, or `nil` on a dry run or a no-op.public let writtenSpan: DyldSharedCacheWriteSpan?+ /// Page 0's re-attestation, or `nil` when the gate left the header alone.+ public let reattestation: DyldSharedCacheReattestation?/// Sites patched — the Python function's return value, which is 0 or 1.public var siteCount: Int {record == nil ? 0 : 1}- /// Whether bytes actually reached the chunk file.+ /// Whether the `maxSlide` field was written; slot rewrites are in `reattestation`.public var didWrite: Bool {writtenSpan != nil}@@ -264,8 +245,6 @@ public enum DyldSharedCacheMaxSlidePatcher {throw PatcherError.fileNotFound("main DSC chunk not found: \(mainChunk.path)")}- // The patcher's own chunk set: see the note at the top of the file about- // why its write log must not be the caller's.let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory, architecture: architecture, captureUndo: captureUndo,)@@ -296,6 +275,18 @@ public enum DyldSharedCacheMaxSlidePatcher {)}+ let fieldVMA = headerVMA &+ UInt64(HeaderField.maxSlide)+ let log: ((String) -> Void)? = if verbose { DyldSharedCacheCodeSignature.stderrLog } else { nil }+ func attestClampedHeader() throws -> DyldSharedCacheReattestation? {+ guard header.maxSlide == 0 else { return nil }+ return try DyldSharedCacheCodeSignature.reattest(+ in: chunks,+ modifiedSpans: [DyldSharedCacheWriteSpan(vma: fieldVMA, length: 8)],+ dryRun: dryRun,+ log: log,+ )+ }+let fits = combined <= kernelRegionSizeif fits, !force {if verbose {@@ -304,26 +295,28 @@ public enum DyldSharedCacheMaxSlidePatcher {+ "region \(hex(kernelRegionSize)); no change",)}- return Result(+ return try Result(outcome: .fits(combined: combined, region: kernelRegionSize),sharedRegionStart: header.sharedRegionStart,sharedRegionSize: header.sharedRegionSize,maxSlide: header.maxSlide,record: nil,writtenSpan: nil,+ reattestation: attestClampedHeader(),)}guard header.maxSlide != 0 else {if verbose {print(" [=] maxSlide already 0; no change")}- return Result(+ return try Result(outcome: .alreadyZero,sharedRegionStart: header.sharedRegionStart,sharedRegionSize: header.sharedRegionSize,maxSlide: header.maxSlide,record: nil,writtenSpan: nil,+ reattestation: attestClampedHeader(),)}@@ -338,7 +331,6 @@ public enum DyldSharedCacheMaxSlidePatcher {)}- let fieldVMA = headerVMA &+ UInt64(HeaderField.maxSlide)let originalBytes = littleEndianBytes(header.maxSlide)let patchedBytes = littleEndianBytes(0)let record = PatchRecord(@@ -366,6 +358,7 @@ public enum DyldSharedCacheMaxSlidePatcher {maxSlide: header.maxSlide,record: record,writtenSpan: nil,+ reattestation: nil,)}@@ -382,10 +375,7 @@ public enum DyldSharedCacheMaxSlidePatcher {)}- // No `DyldSharedCacheCodeSignature.reattestRecordedWrites(in: chunks)` here. See the- // file header: this field is kernel-read cache metadata, not a- // cs_validate'd code page, and leaving the slot alone is the behaviour- // that was validated on device.+ let reattestation = try DyldSharedCacheCodeSignature.reattestRecordedWrites(in: chunks, log: log)if verbose {print(" [+] DSC maxSlide patch complete")@@ -397,6 +387,7 @@ public enum DyldSharedCacheMaxSlidePatcher {maxSlide: header.maxSlide,record: record,writtenSpan: span,+ reattestation: reattestation,)}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMaxSlidePatcherTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMaxSlidePatcherTests.swiftindex ea6c9477..8291a84a 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMaxSlidePatcherTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMaxSlidePatcherTests.swift@@ -58,8 +58,9 @@ private enum FrozenReference {////// `cmp -s` against the pristine tree afterwards: exactly one file moved,/// the main chunk, to this digest (`shasum -a 256 <output>/…arm64e`). The- /// other 79 files were untouched — this patch deliberately does not- /// re-attest, so no code-directory slot moves.+ /// other 79 files were untouched. The reference did not re-attest page 0;+ /// the Swift now does, so its output matches this digest once page 0's+ /// slot is put back to the pristine one — see `Digest.sha256(of:splicing:)`.static let realChangedChunks: [String: String] = ["dyld_shared_cache_arm64e":"3d7197cc0714e95c0e49434ab8bbb6311952a96d5b0425b10f87d2cc060c0110",@@ -292,6 +293,29 @@ private enum Digest {}return hasher.finalize().map { String(format: "%02x", $0) }.joined()}++ /// The digest `url` would have with `bytes` written at `offset` — how a+ /// re-attested chunk is compared with the reference, which left the slot+ /// alone.+ static func sha256(of url: URL, splicing bytes: Data, at offset: Int) throws -> String {+ var data = try Data(contentsOf: url)+ data.replaceSubrange(offset ..< offset + bytes.count, with: bytes)+ return SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()+ }++ /// Page 0's stored slot in `chunk`, and where it lives.+ static func pageZeroSlot(of chunk: URL) throws -> (offset: Int, bytes: Data) {+ let directory = try #require(try DyldSharedCacheCodeSignature.readCodeDirectory(ofChunk: chunk))+ let offset = directory.slotOffset(forPage: 0)+ return (offset, try Bytes.read(chunk, offset: UInt64(offset), length: directory.hashSize))+ }++ /// The reference's digest, given Swift output whose only extra change is+ /// page 0's slot.+ static func referenceDigest(ofSwiftOutput chunk: URL, pristine pristineChunk: URL) throws -> String {+ let pristineSlot = try pageZeroSlot(of: pristineChunk)+ return try sha256(of: chunk, splicing: pristineSlot.bytes, at: pristineSlot.offset)+ }}// MARK: - Byte comparison@@ -401,7 +425,10 @@ struct DyldSharedCacheMaxSlideRealCacheTests {#expect(changed == FrozenReference.realChangedChunks.keys.sorted())#expect(unchanged >= 79, "only \(unchanged) files were left alone")for name in changed {- let digest = try Digest.sha256(of: swiftSide.appendingPathComponent(name))+ let digest = try Digest.referenceDigest(+ ofSwiftOutput: swiftSide.appendingPathComponent(name),+ pristine: pristine.appendingPathComponent(name),+ )let frozen = FrozenReference.realChangedChunks[name] ?? "(not a file the Python moved)"#expect(digest == frozen, "\(name): Swift \(digest), reference \(frozen)")}@@ -419,15 +446,14 @@ struct DyldSharedCacheMaxSlideRealCacheTests {== Bytes.read(pristineMain, offset: tailOffset, length: tailLength))}- /// The deliberate divergence from every other DSC patcher, pinned so nobody- /// "fixes" it: the header page's code slot is left stale on purpose, because- /// `maxSlide` is kernel-read cache metadata rather than a `cs_validate`'d- /// code page. The code directory must come out of the patch untouched.+ /// Page 0 carries the header, and `dsc_extractor` checks its slot like any+ /// other: left stale, `xcodebuild -prepareDeviceSupport` extracts nothing+ /// from the cache. The patch re-hashes that one slot and no other.@Test- func `The patch leaves the code directory alone and the header page unattested`() throws {+ func `The patch re-attests the header page and no other slot`() throws {let pristine = try #require(MaxSlideFixture.pristine, MaxSlideFixture.missing)- let clone = try MaxSlideFixture.cloneMainChunk(named: "noreattest")+ let clone = try MaxSlideFixture.cloneMainChunk(named: "reattest")defer { MaxSlideFixture.discard(clone) }let main = clone.appendingPathComponent(MaxSlideFixture.mainChunkName)let pristineMain = pristine.appendingPathComponent(MaxSlideFixture.mainChunkName)@@ -445,32 +471,65 @@ struct DyldSharedCacheMaxSlideRealCacheTests {let result = try DyldSharedCacheMaxSlidePatcher.patch(chunksDirectory: clone)#expect(result.siteCount == 1)+ #expect(result.reattestation?.updated.map(\.pageIndex) == [0])+ #expect(result.reattestation?.isFullyAttested == true)- // The blob itself: byte-identical to pristine, so no slot moved.+ let after = try DyldSharedCacheCodeSignature.pageHashes(+ chunkURL: main,+ pageIndex: 0,+ directory: directory,+ )+ #expect(after.computed == after.stored, "page 0's slot does not match the patched header")+ #expect(after.stored != before.stored)++ // Outside slot 0 the code directory is byte-identical to pristine.+ let slot = directory.slotOffset(forPage: 0) - directory.blobOffsetlet mineBlob = try Bytes.read(main,offset: UInt64(directory.blobOffset),length: directory.blobLength,)- let pristineBlob = try Bytes.read(+ var pristineBlob = try Bytes.read(pristineMain,offset: UInt64(directory.blobOffset),length: directory.blobLength,)- #expect(mineBlob == pristineBlob, "the patch rewrote a code slot it must not rewrite")+ pristineBlob.replaceSubrange(slot ..< slot + directory.hashSize, with: after.stored)+ #expect(mineBlob == pristineBlob, "the patch rewrote a code slot other than page 0's")+ }- let after = try DyldSharedCacheCodeSignature.pageHashes(+ /// A guest clamped before the patch re-attested carries `maxSlide` 0 and+ /// page 0's pristine slot. A re-run must repair the slot without writing+ /// the field — the path `cfw update-environment` takes on such a guest.+ @Test+ func `A re-run repairs a header clamped without re-attestation`() throws {+ let pristine = try #require(MaxSlideFixture.pristine, MaxSlideFixture.missing)++ let clone = try MaxSlideFixture.cloneMainChunk(named: "repair")+ defer { MaxSlideFixture.discard(clone) }+ let main = clone.appendingPathComponent(MaxSlideFixture.mainChunkName)++ try DyldSharedCacheMaxSlidePatcher.patch(chunksDirectory: clone)+ let pristineSlot = try Digest.pageZeroSlot(+ of: pristine.appendingPathComponent(MaxSlideFixture.mainChunkName),+ )+ let handle = try FileHandle(forUpdating: main)+ try handle.seek(toOffset: UInt64(pristineSlot.offset))+ try handle.write(contentsOf: pristineSlot.bytes)+ try handle.close()++ let repaired = try DyldSharedCacheMaxSlidePatcher.patch(chunksDirectory: clone)+ #expect(repaired.siteCount == 0)+ #expect(!repaired.didWrite)+ #expect(repaired.reattestation?.updated.map(\.pageIndex) == [0])++ let directory = try #require(try DyldSharedCacheCodeSignature.readCodeDirectory(ofChunk: main))+ let hashes = try DyldSharedCacheCodeSignature.pageHashes(chunkURL: main,pageIndex: 0,directory: directory,)- #expect(after.stored == before.stored)- #expect(- after.computed != after.stored,- "page 0's slot still matches, so something re-attested it",- )- print("[no re-attest] page 0 stored \(after.stored.hex.prefix(16))… "- + "computed \(after.computed.hex.prefix(16))… — stale on purpose")+ #expect(hashes.computed == hashes.stored)}/// The reference's `--dry-run` printed `would set maxSlide 0x20000000 ->@@ -502,7 +561,7 @@ struct DyldSharedCacheMaxSlideRealCacheTests {/// second write.@Testfunc `A second pass over an already-clamped cache is a no-op`() throws {- _ = try #require(MaxSlideFixture.pristine, MaxSlideFixture.missing)+ let pristine = try #require(MaxSlideFixture.pristine, MaxSlideFixture.missing)let swiftSide = try MaxSlideFixture.cloneMainChunk(named: "idem_swift")defer { MaxSlideFixture.discard(swiftSide) }@@ -515,6 +574,7 @@ struct DyldSharedCacheMaxSlideRealCacheTests {let mineAgain = try DyldSharedCacheMaxSlidePatcher.patch(chunksDirectory: swiftSide)#expect(mineAgain.siteCount == 0)#expect(!mineAgain.didWrite)+ #expect(mineAgain.reattestation?.updated.isEmpty == true, "page 0 was attested by the first pass")// Which gate stops the second pass is worth being precise about. Once// the slide is gone this cache's span fits the region on its own// (0x17D504000 <= 0x180000000) — that is the whole point of the patch —@@ -538,7 +598,11 @@ struct DyldSharedCacheMaxSlideRealCacheTests {of: swiftSide.appendingPathComponent(MaxSlideFixture.mainChunkName),)#expect(afterThird == afterFirst, "a no-op pass rewrote the chunk")- #expect(afterThird == FrozenReference.realChangedChunks[MaxSlideFixture.mainChunkName])+ let referenceDigest = try Digest.referenceDigest(+ ofSwiftOutput: swiftSide.appendingPathComponent(MaxSlideFixture.mainChunkName),+ pristine: pristine.appendingPathComponent(MaxSlideFixture.mainChunkName),+ )+ #expect(referenceDigest == FrozenReference.realChangedChunks[MaxSlideFixture.mainChunkName])}}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swiftindex f61f9792..a0172704 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift@@ -302,8 +302,10 @@ struct VPhoneCustomFirmwarePatchDyldSharedCacheMaxSlideCommand: ParsableCommand--force zeroes maxSlide even when the cache fits. It is for running thisverb by hand; `cfw install` never passes it.- No re-attestation: maxSlide lives in the cache header, which is not one- of the cs_validate'd code pages.+ Page 0's slot is re-attested after the write, and on any run over a+ header already at maxSlide 0. The kernel does not check that page, but+ Xcode's dsc_extractor does: with a stale slot it extracts no symbols+ from the cache, and LLDB reads every system library from the guest.""",)diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex e585a47d..477dd89c 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -1427,6 +1427,12 @@ struct VPhoneCustomFirmwareInstaller {return live}+ /// Live dyld patches whose verb runs again on every install. Each is cheap+ /// and idempotent, and its earlier implementation left records identical to+ /// the current one's, so `hasOutdatedImplementation` cannot single it out:+ /// `dyld-boot-maxslide` once left page 0's slot stale, and a re-run repairs it.+ private static let dyldPatchesRerunWhenLive: Set<String> = ["dyld-boot-maxslide"]+/// Apply the enabled dyld cache patches whose state differs from what was/// live before, and revert the disabled ones from the undo log the earlier/// install wrote. A patch already in the prior-live set is left alone — no@@ -1460,7 +1466,14 @@ struct VPhoneCustomFirmwareInstaller {// 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) {+ if Self.dyldPatchesRerunWhenLive.contains(entry.id) {+ do {+ try patch(entry.verb, entry.args + ["--undo-log", undoAbsolute, "--undo-id", entry.id])+ } catch {+ failures.append(entry.id)+ print(" [!] \(entry.id): re-running the applied patch failed, left as it was: \(error)")+ }+ } else 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])