Run a virtual iPhone on an Apple Silicon Mac.
Swift
Widen the guest kernel's shared region so iPhone18,x boots iOS 27
Jackyea76afacb686
diff --git a/Documents/Guides/compatibility.md b/Documents/Guides/compatibility.mdindex d6ea007b..81118946 100644--- a/Documents/Guides/compatibility.md+++ b/Documents/Guides/compatibility.md@@ -47,9 +47,9 @@ See [Other iPhone models](iphone-models.md).| Host | iPhone restore IPSW | PCC/cloudOS IPSW | Observed result || --- | --- | --- | --- || Mac17,9 (M5 Pro) 27.0.1 | `18,1_26.6.2_23G90` (iPhone 17 Pro) | `26.4-23E5207q` | Launchpad `vm create` (2.5.1 local bundle): prepare, patch, restore, CFW, boot to the home screen at 402x874 pt @3x, `model` iPhone18,1, vphoned ping |-| Mac17,9 (M5 Pro) 27.0.1 | `18,2_27.0.1_24A446` (iPhone 17 Pro Max) | `26.4-23E5207q` | does not boot: `cfw install` refuses it, see below |+| Mac17,9 (M5 Pro) 27.0.1 | `18,2_27.0.1_24A446` (iPhone 17 Pro Max) | `26.4-23E5207q` | **boots** with the `kernel-boot-shared_region_size` patch (2026-10-06, bundle 2.6.0-local.0d5e6f90): `dyld cache mapped system-wide`, 0 panics, vphoned answers as 27.0.1, home screen at 440x956 pt @3x |-**iPhone18,1 and iPhone18,2 on iOS 27 do not boot**+**iPhone18,1 and iPhone18,2 on iOS 27 need the shared-region patch**([issue #596](https://github.com/Lakr233/vphone-cli/issues/596), 27.0 and27.0.1). Their dyld shared cache records a `sharedRegionSize` of`0x185804000` on 27.0.1, larger than the `0x180000000` shared region of the@@ -57,8 +57,16 @@ cloudOS 26.4 guest kernel, so it cannot map even with `dyld-boot-maxslide`taking its slide away: launchd panics on first boot with `Library not loaded:/usr/lib/libSystem.B.dylib`. iPhone17,3's 27.0.1 cache (`0x17D508000`) stillfits. Since this check, `cfw install` refuses such a cache with that-explanation instead of leaving a guest that panics. Use iPhone17,3 for iOS 27,-or iOS 26 on these devices.+explanation instead of leaving a guest that panics.++`kernel-boot-shared_region_size` (on in `standard` for an iOS 27 base since+2026-10-06) widens the arm64 region to `0x1C0000000` — the largest size that+stays under the 26.4 kernel's own task-map ceilings — and `cfw install`+measures the cache against that widened region when the VM's kernel carries+the patch (its `PatchReceipt.plist` says so), so these devices now install and+boot; validated on iPhone18,2 27.0.1 as above. Without the patch+(an older bundle, or the patch unticked) the refusal stands: use iPhone17,3+for iOS 27, or iOS 26 on these devices.## iPadOSdiff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex 50bd5b20..7413d59d 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -9,7 +9,7 @@> identifier is the record identifier the patcher already emits, or the common> prefix when one patch writes several sites — so `jb.kcall10` is one selectable> patch covering its four records, and `sandbox_ext` covers every-> `sandbox_ext_<index>`. 121 patches are declared in total. `vphone-cli fw patches`+> `sandbox_ext_<index>`. 122 patches are declared in total. `vphone-cli fw patches`> prints them; `--json` is what the Launchpad patch editor reads.>> Two presets ship, prewritten, in@@ -509,6 +509,7 @@| JB-18 | B | `patch_mac_mount` | `___mac_mount` | Upstream mount-role wrapper bypass (`tbnz` NOP + role-byte zeroing) | Y || JB-19 | B | `patch_nvram_verify_permission` | `_verifyPermission` (NVRAM) | Allow NVRAM writes | Y || JB-20 | B | `patch_shared_region_map` | `_shared_region_map_and_slide_setup` | Force root-vs-process-root mount compare to succeed before Cryptex fallback | Y |+| JB-20b| B | `patch_shared_region_size` | `vm_shared_region_create` arm64 case | **Widen the shared region 6→7 GiB for an iOS 27 userland (2026-10-06, issue #596).** `kernel-boot-shared_region_size`, applicability `iOSBase: .major(27)`, runs under the existing `applyIOS27` gate so a 26.x/18.x base keeps a stock kernel. The 26.4 kernel bakes `SHARED_REGION_BASE_ARM64 == SHARED_REGION_SIZE_ARM64 == 0x180000000`; a 27.0.1 iPhone18,x cache spans `0x185804000`, over the region even at slide 0, so `_shared_region_map_and_slide` ENOMEMs and launchd dies on libSystem — zeroing `maxSlide` (row 10) is not enough. Because base == size, the compiler issued one register for both and `dup v0.2d`-splatted it into the nesting pair, so the arm64 case is rewritten as a 4-instruction block (anchor: the `dup Vd.2d, Xn` between two `#0x180000000` materialisations; window confirmed with Capstone; exactly one hit required; branch preserved): `movz/movk x22` build size `0x1C0000000`, the kernel's own single-instruction base word (`mov x26, #0x180000000`, an ORR logical-immediate alias — one `movz` cannot spell `0x180000000`, bits 31+32 straddle lanes) is reused verbatim, and `stp x26, x22, [sp, #0x70]` replaces the dup/str nesting pair. Replacement words keystone 0.9.2 via `ARM64Encoder.encodeMovzX/encodeMovkX/encodeStpX`; downstream `csm_setup_nested_address_space`, `pmap_set_shared_region` and both `vm_map_create_options` calls take x26/x22 as base/size (verified register-for-register against `vm_shared_region.c` on both variants — research `0x1E0F4E8` / release `0x1D074E8`, byte-identical). Size choice: Apple's iOS 27 value `0x380000000` cannot be copied — the 26.4 kernel's task-map ceilings (`ARM64_MAX_OFFSET_DEVICE_SMALL 0x358000000`, `LARGE 0x458000000`) are compiled from the stock region and iOS 27 raised its own; `0x1C0000000` tops the region at `0x340000000`, under every tier, while covering the worst known cache + full 512 MiB slide (`0x1A5804000`). `cfw install` mirrors this: the region check uses `DyldSharedCacheMaxSlidePatcher.patchedKernelSharedRegionSize` when the VM's kernelcache receipt lists the patch (a VM with no receipt falls back to a `27.*` base), so iPhone18,x installs proceed instead of refusing; `patch-dsc-maxslide` still zeroes the slide (conservative slide-0 first boot). Full analysis: `Research/KernelCustomFirmwarePatches/patch_shared_region_size.md`. **Boot validated 2026-10-06** on iPhone18,2 27.0.1 + cloudOS 26.4 (bundle 2.6.0-local.0d5e6f90, `cfw update-kernel` + `cfw install` over the #596 repro machine): `dyld cache mapped system-wide`, 0 panics, vphoned answers as 27.0.1, home screen at 440x956 @3x — SPTM and TXM accept the `0x1C0000000` nesting range. | `27.*` || JB-21 | B | `patch_spawn_validate_persona` | `_spawn_validate_persona` | Upstream dual-`cbz` persona helper bypass | Y || JB-22 | B | `patch_task_for_pid` | `_task_for_pid` | Allow task_for_pid via upstream early `pid == 0` gate NOP | Y || JB-23 | B | `patch_thid_should_crash` | `_thid_should_crash` | Prevent GUARD_TYPE_MACH_PORT crash | Y |diff --git a/Research/KernelCustomFirmwarePatches/README.md b/Research/KernelCustomFirmwarePatches/README.mdindex 32d19ae9..112f75e6 100644--- a/Research/KernelCustomFirmwarePatches/README.md+++ b/Research/KernelCustomFirmwarePatches/README.md@@ -9,7 +9,7 @@ These notes explain the source anchors, binary matches and validation evidence f| Boot, root and mount | [BSD init auth](patch_bsd_init_auth.md), [IO secure BSD root](patch_io_secure_bsd_root.md), [dounmount](patch_dounmount.md), [mac mount](patch_mac_mount.md), [load dylinker](patch_load_dylinker.md) || AMFI, credentials and policy | [CDHash in trust cache](patch_amfi_cdhash_in_trustcache.md), [execve kill path](patch_amfi_execve_kill_path.md), [credential label update](patch_cred_label_update_execve.md), [credential hook](patch_hook_cred_label_update_execve.md), [proc security policy](patch_proc_security_policy.md), [persona validation](patch_spawn_validate_persona.md), [sandbox hooks](patch_sandbox_hooks_extended.md), [NVRAM permission](patch_nvram_verify_permission.md) || Tasks, ports and threads | [convert port to map](patch_convert_port_to_map.md), [task conversion](patch_task_conversion_eval_internal.md), [task for PID](patch_task_for_pid.md), [thread set state](patch_thread_set_state.md), [thread crash gate](patch_thid_should_crash.md) |-| VM and shared regions | [VM fault](patch_vm_fault_enter_prepare.md), [immutable map delete](patch_vm_map_delete_immutable_code.md), [VM map protect](patch_vm_map_protect.md), [shared region map](patch_shared_region_map.md) |+| VM and shared regions | [VM fault](patch_vm_fault_enter_prepare.md), [immutable map delete](patch_vm_map_delete_immutable_code.md), [VM map protect](patch_vm_map_protect.md), [shared region map](patch_shared_region_map.md), [shared region size](patch_shared_region_size.md) || Process and syscall paths | [proc PID info](patch_proc_pidinfo.md), [syscall mask](patch_syscallmask_apply_to_proc.md), [kcall10](patch_kcall10.md) || Follow-up evidence | [26.5 hook fixes](26.5_jb_hook_fixes.md), [post-validation additions](patch_post_validation_additional.md), [runtime verification archive](RuntimeVerification/README.md) |diff --git a/Research/KernelCustomFirmwarePatches/patch_shared_region_size.md b/Research/KernelCustomFirmwarePatches/patch_shared_region_size.mdnew file mode 100644index 00000000..354f86f2--- /dev/null+++ b/Research/KernelCustomFirmwarePatches/patch_shared_region_size.md@@ -0,0 +1,236 @@+# patch_shared_region_size — widen the arm64 shared region for an iOS 27 userland++## 1. Patch Metadata++- Patch ID: `kernel-boot-shared_region_size` (record: one, same ID)+- Patcher: `KernelCustomFirmwarePatcher.patchSharedRegionSize()` in+ `VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Memory/KernelCustomFirmwarePatchSharedRegionSize.swift`+- Declaration: `FirmwareKernelCustomFirmwarePatchSet`+ (`com.vphone.patchset.kernel.cfw`), `bootEssential`, applicability+ `iOSBase: .major(27)` — the same gate `applyIOS27` already uses. On a 26.x /+ 18.x base the patch never runs and the kernel stays byte-identical.+- Analysis date: 2026-10-06+- Analyst note: static analysis plus a full guest validation the same day+ (§14). Both vphone600 26.4 variants verified byte-exactly, and the patched+ kernel booted an iPhone18,2 27.0.1 guest to its home screen.++## 2. Patch Goal++The vphone600 26.4 kernel bakes `SHARED_REGION_BASE_ARM64 ==+SHARED_REGION_SIZE_ARM64 == 0x180000000` (6 GiB) into+`vm_shared_region_create`'s arm64 case. An iOS 27.0.1 iPhone18,1/18,2 dyld+shared cache spans `0x185804000` — over 6 GiB at slide 0, so+`_shared_region_map_and_slide` returns `ENOMEM`, dyld cannot map+`libSystem.B.dylib`, and launchd panics on first boot (issue #596; the+`cfw install` region check added the same day refuses such installs with+exactly this explanation).++Zeroing `maxSlide` (row 10 of `0_binary_patch_comparison.md`) only reclaims+the slide: `0x185804000 > 0x180000000` still. The region itself must grow.++Apple's own answer in the iOS 27 kernel is a three-table lookup by cpu class+with the arm64 default row at `0x380000000` (14 GiB). That value cannot be+copied into the 26.4 kernel wholesale — see §12 for the ceiling arithmetic —+so this patch grows the region to `0x1C0000000` (7 GiB), the largest size+whose top stays under the 26.4 kernel's own task-map ceilings, and keeps the+base at `0x180000000`.++## 3. Target Function(s) and Binary Location++The block is the arm64 case of the subtype dispatch inside+`vm_shared_region_create` (inlined into its caller; the research kernel keeps+no local symbol at the site):++| Kernel | Block file offset | Block VA | Branch target |+| --- | --- | --- | --- |+| `kernelcache.research.vphone600` | `0x1E0F4E8` | `0xfffffe0008e134e8` | `0xfffffe0008e13558` |+| `kernelcache.release.vphone600` | `0x1D074E8` | `0xfffffe0008d0b4e8` | `0xfffffe0008d0b558` |++The two variants are byte-identical across the whole 20-byte block.++## 4. Kernel Source File Location++- `osfmk/vm/vm_shared_region.c`, `vm_shared_region_create` — the+ `case CPU_TYPE_ARM64:` arm of the settings switch+ (`base_address = SHARED_REGION_BASE_ARM64; size = SHARED_REGION_SIZE_ARM64;+ pmap_nesting_start/size = …`). Constants from+ `osfmk/mach/shared_region.h`:+ `SHARED_REGION_BASE_ARM64 0x180000000`, `SHARED_REGION_SIZE_ARM64+ 0x180000000`, and `SHARED_REGION_NESTING_BASE/SIZE_ARM64` defined as the+ same two. Confidence: **high** (xnu checkout in `Research/Reference/xnu`+ matches the disassembly register-for-register).++## 5. Function Call Stack++Caller (the `queue_enter`/`vm_shared_region_lastid` loop,+`vm_shared_region_lookup_or_create`) → `vm_shared_region_create` →, with the+patched values in `x26` (base) and `x22` (size):++- `pmap_set_nested` (`0xfffffe0008e52c20` research)+- `csm_setup_nested_address_space(nested_pmap, base, size)` (TXM)+- `pmap_set_shared_region(config_pmap, nested_pmap, base, size)` (SPTM)+- `vm_map_create_options(nested_pmap, 0, size)` — the sub map+- `vm_map_create_options(config_pmap, base, base + size)` — the config map++The `[sp, #0x70]` pair the original `dup`/`str` fills is the+{`pmap_nesting_start`, `pmap_nesting_size`} pair, later consumed as the+nesting range — same values as base/size in this kernel.++## 6. Patch Hit Points++Before (5 instructions; every word identical in both variants):++```+f6 07 61 b2 mov x22, #0x180000000 ; size — ORR logical-immediate alias+c0 0e 08 4e dup v0.2d, x22+e0 1f 80 3d str q0, [sp, #0x70] ; nesting pair {base, size}+fa 07 61 b2 mov x26, #0x180000000 ; base — same alias+18 00 00 14 b <common> ; preserved+```++After (the first four words; the branch untouched):++```+16 00 b8 d2 movz x22, #0xc000, lsl #16+36 00 c0 f2 movk x22, #0x1, lsl #32 ; x22 = 0x1C0000000+fa 07 61 b2 mov x26, #0x180000000 ; the kernel's own base word, verbatim+fa 5b 07 a9 stp x26, x22, [sp, #0x70] ; nesting pair {base, size}+```++All three new words are keystone 0.9.2 (`kstool`, Homebrew, outside the+repository), the provenance `ARM64EncoderKeystoneParityTests` pins. The base+word is copied, not re-encoded: `0x180000000` spans bits 31 and 32, so one+`movz` cannot spell it and the kernel's single-instruction ORR+logical-immediate is the only one-instruction form; reproducing it would mean+hand-rolling the logical-immediate encode table the guardrails keep out.++Why a block rewrite at all: because stock base == size, the compiler used one+register for both and splatted it into the nesting pair. Patching only the+`mov x22` would leave the `dup`-shaped pair carrying the old constant into+one lane — and the new size needs two lanes of its own, so the pair must+become an `stp` of two different registers. Four instructions in, four out.++## 7. Current Patch Search Logic++- Anchor: raw scan of `__TEXT_EXEC` for `dup Vd.2d, Xn`+ (`word & 0xFFFFFC00 == 0x4E080C00`; Rn/Rd free) — the one instruction only+ this block issues between two `#0x180000000` materialisations.+- Capstone window confirm at each hit (`dupOff-4 ..< dupOff+16`):+ i0 `mov Xs, #0x180000000` (mov/movz 2-operand or unaliased `orr Xs, xzr,+ #…` 3-operand), i1 `dup Vd.2d, Xs` sourcing i0's register, i2+ `str Vd, [sp, #disp]` with the same vector lane (dup says `v0`, str says+ `q0`; Capstone gives them different register ids, so lanes are compared by+ number), i3 `mov Xb, #0x180000000` with `Xb != Xs`, i4 an unconditional `b`.+- Exactly one hit must survive, else the patch fails and logs how many+ candidates it saw. i0 is taken as the size register and i3 as the base+ register — the layout both shipped variants use; the roles are not+ distinguishable inside the window alone, only from the downstream call+ flow (§5).+- The rewrite reuses the block's own registers and pair slot, so a future+ kernel with a different allocation still patches correctly.+- Replacement bytes come only from `ARM64Encoder.encodeMovzX`,+ `encodeMovkX`, `encodeStpX` plus the verified original base word.++## 8. Pseudocode (Before)++```+case cpu_subtype class of+0x100000c (arm64, 16k): base = 0x180000000; size = 0x180000000;+ nesting = {0x180000000, 0x180000000}+0x200000c (arm64_32): base = 0x1a000000; size = 0x88000000; …+0xc (arm): base = 0x40000000; size = 0x40000000; …+```++## 9. Pseudocode (After)++```+0x100000c (arm64, 16k): base = 0x180000000; size = 0x1C0000000;+ nesting = {0x180000000, 0x1C0000000}+(others untouched)+```++## 10. Validation (Static Evidence)++- `ipsw macho disass` over both decompressed kernels around the block and+ downstream through the `csm_setup_nested_address_space` /+ `pmap_set_shared_region` / both `vm_map_create_options` calls; register+ flow matches `vm_shared_region.c` exactly (`x1/x2 = base/size` in the+ first, `x2/x3` in the second, `0,size` and `base,base+size` in the maps).+- The dyld cache contract read from the 24A446 iPhone18,2 IPSW: header of the+ main cache records `sharedRegionStart 0x180000000`,+ `sharedRegionSize 0x185804000`, `maxSlide 0x20000000`; subcache+ `sharedRegionStart` fields run `0x180400000 … 0x2dd25c000` — the whole+ cache maps inside `[0x180000000, 0x340000000)`.+- Unit tests: `KernelCustomFirmwarePatchSharedRegionSizeTests` (synthetic+ kernels: stock rewrite, idempotence over patched bytes, wrong-constant+ refusal, register/disp genericity) plus the env-gated+ `VPHONE_VP600_KERNEL` case over a real IM4P, which pinned the offsets in+ §3 on both variants.++## 11. Expected Failure/Panic if Unpatched++Exactly issue #596: `dyld cache '(null)' not loaded: syscall to map cache+into shared region failed` → `initproc failed to start -- Library not loaded:+/usr/lib/libSystem.B.dylib`. (Since the refusal commit, `cfw install` stops+earlier with `RegionOverflow` naming both sizes.)++## 12. Risk / Side Effects++- **Why not Apple's 0x380000000:** the 26.4 kernel's task-map ceilings are+ compile-time constants derived from the stock 6 GiB region —+ `ARM64_MIN_MAX_ADDRESS = 0x320000000`, `ARM64_MAX_OFFSET_DEVICE_SMALL+ 0x358000000`, `LARGE 0x458000000` (`osfmk/arm64/sptm/pmap/pmap.c`). iOS 27+ raised its own ceilings along with the region; this kernel did not, and a+ `[0x180000000, 0x500000000)` region would overrun every ceiling, leaving+ processes no address space above it. `0x1C0000000` tops the region at+ `0x340000000`, under even the SMALL tier, so no other constant needs to+ move. A guest with ≤1 GiB RAM (min tier `0x320000000`) still would not fit,+ but iOS 27 userland does not run there anyway.+- **Headroom:** worst known cache + full slide = `0x185804000 + 0x20000000 =+ 0x1A5804000` ≤ `0x1C0000000`, so even with `maxSlide` intact every mapping+ fits deterministically (kernel picks 16 KiB-aligned slides strictly below+ `maxSlide`; `size + maxSlide ≤ region` is the sufficient test, row 10 of+ the comparison doc).+- **commpage** lives at fixed absolute addresses, not region-relative, so it+ does not move.+- **SPTM/TXM acceptance of the wider nesting range is proven by the 2026-10-06+ boot** (§14): `pmap_set_shared_region` and `csm_setup_nested_address_space`+ took the `0x1C0000000` range and the guest reached userspace.+- **`patch-dsc-maxslide` still zeroes the 27 cache's slide** — it self-gates+ against the stock `0x180000000`, so a 27 install maps at slide 0 inside the+ widened region. That is the conservative first-boot posture (the slide-0+ path is what real 17,3 27.0.1 guests already boot on). Keeping the full+ 512 MiB slide is a possible follow-up: teach the verb the patched region+ and pass it from `cfw install` on 27.x.++## 13. Symbol Consistency Check++No symbol at the site in either variant (`ipsw macho a2s` finds none in the+`com.apple.kernel` entry); identification is structural, from the subtype+dispatch and the §5 call flow. `match` by structure, no symbol to mismatch+with. The XNU source in `Research/Reference/xnu` is the same generation+(cloudOS 26.4) — constants and call order agree instruction for instruction.++## 14. Open Questions and Confidence++- ~~Does SPTM and TXM accept a nesting range of `0x1C0000000`?~~ **Answered by+ the 2026-10-06 validation** — they do. Procedure as run: bundle+ `2.6.0-local.0d5e6f90` (this branch) installed local, `vm set-bundle+ issue596-ip18` (the half-built #596 repro machine, whose `cfw install` had+ refused that morning), `cfw update-kernel` re-patched the pristine+ kernelcache from `FirmwareOriginals` with the machine's standard selection —+ receipt records `kernel-boot-shared_region_size` under writer+ `cfw update-kernel`, 95 kernel patches total — and swapped it into Preboot+ under the original IM4M; `cfw install` then passed the region check against+ `0x1C0000000` and completed (vphoned installed, maxSlide still zeroed by+ `patch-dsc-maxslide`, restore tree cleaned). `vm start --headless --wait`+ returned with vphoned answering: `dyld[1]: dyld cache mapped system-wide`,+ 0 `panic` lines in the console log, `device.info` reporting+ `ios_version 27.0.1` with vphoned at pid 112, `apps.foreground`+ `com.apple.springboard`, screen 440x956 @3x on at the lock screen.+- ~~Does iOS 27 userland tolerate the region being smaller than its own+ `0x380000000` expectation?~~ It does not observe the difference on this+ path: the whole 24A446 cache maps from `sharedRegionStart 0x180000000` with+ every subcache header address resolving inside `[0x180000000, 0x340000000)`,+ and userspace ran to the home screen as above.+- Confidence: **high** — bytes, semantics and now guest boot are all proven.diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swiftindex a5c34d19..60159a04 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swift@@ -83,6 +83,14 @@ public enum DyldSharedCacheMaxSlidePatcher {/// region map ENOMEMs.public static let kernelSharedRegionSize: UInt64 = 0x1_8000_0000+ /// The same kernel with the `kernel-boot-shared_region_size` patch applied+ /// (`KernelCustomFirmwarePatchSharedRegionSize`): the arm64 region grows to+ /// 0x1C0000000 while the base stays 0x180000000. The region top+ /// (0x340000000) remains under the kernel's own task map ceilings, so+ /// nothing else moves with it. `cfw install` checks the cache against this+ /// size when the VM's kernelcache receipt lists the patch.+ public static let patchedKernelSharedRegionSize: UInt64 = 0x1_C000_0000+/// Byte offsets of the `dyld_cache_header` fields this patcher reads, from/// dyld's `dyld_cache_format.h`. Stable across every iOS this project/// targets, and corroborated at run time — see ``readHeader(from:)``.diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Memory/KernelCustomFirmwarePatchSharedRegionSize.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Memory/KernelCustomFirmwarePatchSharedRegionSize.swiftnew file mode 100644index 00000000..4d90519c--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Memory/KernelCustomFirmwarePatchSharedRegionSize.swift@@ -0,0 +1,247 @@+// KernelCustomFirmwarePatchSharedRegionSize.swift — CFW kernel patch: grow the+// arm64 shared region so an iOS 27 userland's dyld shared cache fits.+//+// The vphone600 26.4 kernel bakes SHARED_REGION_BASE_ARM64 ==+// SHARED_REGION_SIZE_ARM64 == 0x180000000 into `vm_shared_region_create`'s+// arm64 case (iOS 27 grew the arm64 default to 0x380000000 and raised the task+// map ceiling with it; this kernel's ceiling did not move, so Apple's value+// cannot simply be copied in). An iOS 27.0.1 iPhone18,x cache spans+// 0x185804000 — over the 6 GiB region even at slide 0, so+// `_shared_region_map_and_slide` ENOMEMs and launchd dies on "Library not+// loaded: /usr/lib/libSystem.B.dylib" (issue #596).+//+// The patch widens the region to 0x1C0000000 (7 GiB) and leaves the base+// alone. That value is the largest that keeps the region top (0x340000000)+// under this kernel's own task map ceilings — ARM64_MAX_OFFSET_DEVICE_SMALL+// 0x358000000 and LARGE 0x458000000, both compiled from the stock 6 GiB region+// — while still covering every iOS 27 cache read so far with its full 512 MiB+// slide (0x185804000 + 0x20000000 = 0x1A5804000).+//+// The block rewrite+// -----------------+// Because stock base and size are the same constant, the compiler issued one+// register for both and splatted it into the nesting pair:+//+// mov x22, #0x180000000 ; size (ORR logical-immediate alias)+// dup v0.2d, x22+// str q0, [sp, #0x70] ; nesting pair {base, size}+// mov x26, #0x180000000 ; base+// b <common>+//+// A size-only edit cannot work: `dup` would carry the old base into the pair,+// and the stock constant itself needs its own two-lane materialisation+// (0x180000000 is bits 31 and 32 — one movz cannot spell it, which is why the+// compiler chose the single-instruction ORR alias). The four instructions are+// rewritten as a unit, reusing the kernel's own base instruction verbatim, and+// the branch is left alone:+//+// movz x22, #0xC000, lsl #16 ; size low lane+// movk x22, #0x1, lsl #32 ; size high lane (0x1C0000000)+// mov x26, #0x180000000 ; base — the original ORR word, unchanged+// stp x26, x22, [sp, #0x70] ; nesting pair {base, size}+//+// The base word is copied, not re-encoded: the matcher has already verified it+// materialises exactly 0x180000000 into the base register, and reproducing an+// ORR logical immediate would mean hand-rolling the encode table the patcher+// guardrails keep out (see `ARM64Inst.isORRImmW`'s comment for the same+// refusal on the decode side).+//+// Downstream — verified by disassembling both vphone600 variants against+// vm_shared_region.c — x26 feeds `base_address` and x22 `size` into+// `csm_setup_nested_address_space`, `pmap_set_shared_region` and both+// `vm_map_create_options` calls, and the stack pair becomes the nesting range,+// so one block covers every consumer. The size/base roles of the two+// registers are not distinguishable inside the window alone; the matcher takes+// i0 as size and i3 as base, the layout both shipped variants use (byte+// identical). Whether SPTM/TXM accept the wider nesting range is only+// provable by booting the guest.++import Foundation+import VPhonePatchKit++extension KernelCustomFirmwarePatcher {+ /// SHARED_REGION_BASE_ARM64 == SHARED_REGION_SIZE_ARM64 as baked into the+ /// vphone600 26.4 kernel's arm64 case. The matcher refuses anything else,+ /// which also makes a second run over a patched image a clean no-hit.+ private static let stockRegionBaseAndSize: UInt64 = 0x1_8000_0000++ /// `DUP Vd.2d, Xn` — general-register-to-vector duplicate, Q form. Rn (the+ /// source X register, bits 9:5) and Rd (the destination V register, 4:0)+ /// stay free; everything else in 0x4E080EC0 is fixed.+ private static let dupV2dMask: UInt32 = 0xFFFF_FC00+ private static let dupV2dValue: UInt32 = 0x4E08_0C00++ /// Widen the arm64 shared region. See the file header for the values and+ /// the reason the whole block is rewritten instead of one instruction.+ ///+ /// Anchor: the `dup Vd.2d, Xs` that splats the single shared-region+ /// constant into the nesting pair — the one instruction that only this+ /// block issues between a `mov #0x180000000` pair. The surrounding window+ /// is confirmed with Capstone, register by register, before anything is+ /// written.+ @discardableResult+ func patchSharedRegionSize() -> Bool {+ let stock = Self.stockRegionBaseAndSize+ let size = DyldSharedCacheMaxSlidePatcher.patchedKernelSharedRegionSize+ log("\n[CFW]vm_shared_region_create: arm64 region size \(hex(stock)) → \(hex(size))")++ guard let (textStart, textEnd) = kernTextRange else {+ log(" [-] __TEXT_EXEC not found")+ return false+ }++ let raw = buffer.original+ var hits: [(sizeReg: UInt32, baseReg: UInt32, pairDisp: Int32, blockOff: Int, baseInsn: Data)] = []++ var off = textStart+ while off + 20 <= min(textEnd, raw.count) {+ defer { off += 4 }+ // The dup sits one instruction after the size materialisation.+ let word = raw.loadLE(UInt32.self, at: off)+ guard word & Self.dupV2dMask == Self.dupV2dValue else { continue }++ guard let hit = matchRegionBlock(atDup: off, stockValue: stock) else { continue }+ hits.append(hit)+ }++ guard hits.count == 1 else {+ log(" [-] arm64 shared region block not found uniquely (\(hits.count) candidates)")+ return false+ }++ let hit = hits[0]+ let sizeLo = UInt16((size >> 16) & 0xFFFF)+ let sizeHi = UInt16((size >> 32) & 0xFFFF)+ // Both lanes must be live for the two-instruction materialisation the+ // rewrite uses; 0x1C0000000 has lane 1 = 0xC000 and lane 2 = 1.+ guard size & 0xFFFF == 0, sizeLo != 0, sizeHi != 0 else {+ log(" [-] patched size \(hex(size)) does not fit the movz+movk shape")+ return false+ }++ guard+ let lo = ARM64Encoder.encodeMovzX(rd: hit.sizeReg, imm16: sizeLo, shift: 16),+ let hi = ARM64Encoder.encodeMovkX(rd: hit.sizeReg, imm16: sizeHi, shift: 32),+ let pair = ARM64Encoder.encodeStpX(rt1: hit.baseReg, rt2: hit.sizeReg, rn: 31, offset: hit.pairDisp)+ else {+ log(" [-] replacement instructions unencodable (rd size=\(hit.sizeReg) base=\(hit.baseReg) disp=\(hit.pairDisp))")+ return false+ }++ var replacement = Data()+ replacement.append(lo)+ replacement.append(hi)+ replacement.append(hit.baseInsn)+ replacement.append(pair)++ let va = fileOffsetToVA(hit.blockOff)+ emit(+ hit.blockOff,+ replacement,+ patchID: "kernel-boot-shared_region_size",+ virtualAddress: va,+ description: "arm64 shared region size \(hex(stock)) → \(hex(size)) [vm_shared_region_create]"+ )+ return true+ }++ // MARK: - Private helpers++ /// Confirm the four-instruction window around the `dup` at `dupOff`:+ /// `mov #stock` into Xs, `dup Vd.2d, Xs`, `str Vd, [sp, #disp]`,+ /// `mov #stock` into Xb. Returns the two X-register numbers, the stack+ /// pair displacement, the file offset of the block start and the base+ /// instruction's own bytes (reused verbatim by the rewrite), or nil.+ private func matchRegionBlock(atDup dupOff: Int, stockValue: UInt64) -> (sizeReg: UInt32, baseReg: UInt32, pairDisp: Int32, blockOff: Int, baseInsn: Data)? {+ guard dupOff >= 4 else { return nil }+ let insns = disasm.disassemble(in: buffer.original, at: dupOff - 4, count: 4)+ guard insns.count == 4 else { return nil }++ // i0 — the size: `mov`/`movz`/`orr`-aliased `mov Xs, #stock`.+ guard let sizeReg = materialisedRegister(insns[0], value: stockValue) else { return nil }++ // i1 — `dup Vd.2d, Xs`, sourcing the register i0 wrote.+ guard insns[1].mnemonic == "dup",+ let dupOps = insns[1].detail?.operands, dupOps.count == 2,+ dupOps[0].type == .register, dupOps[1].type == .register,+ dupOps[1].reg == .x(Int(sizeReg))+ else { return nil }++ // i2 — `str Vd, [sp, #disp]`, storing the pair the dup filled. The dup+ // names the register `v0.2d` and the store `q0`; Capstone gives those+ // two spellings different register ids, so they are compared by lane.+ guard insns[2].mnemonic == "str",+ let strOps = insns[2].detail?.operands, strOps.count == 2,+ strOps[0].type == .register,+ let strLane = vectorLane(strOps[0].reg),+ let dupLane = vectorLane(dupOps[0].reg),+ strLane == dupLane,+ strOps[1].type == .memory,+ strOps[1].mem.base == .sp, strOps[1].mem.index == .invalid+ else { return nil }++ // i3 — the base: same constant, a different register.+ guard let baseReg = materialisedRegister(insns[3], value: stockValue),+ baseReg != sizeReg+ else { return nil }++ // i4 — an unconditional branch closes the block; it is preserved, so+ // only its shape is checked.+ guard jbDecodeBBranch(at: dupOff + 12) != nil else { return nil }++ let baseInsn = Data(buffer.original[(dupOff + 8) ..< (dupOff + 12)])+ return (sizeReg: sizeReg, baseReg: baseReg, pairDisp: strOps[1].mem.disp, blockOff: dupOff - 4, baseInsn: baseInsn)+ }++ /// The destination X-register of `mov Xd, #value` in any of its encodings+ /// (`movz` with a shift, or the ORR logical-immediate alias the 26.4+ /// compiler picked for 0x180000000), or nil when it is anything else.+ private func materialisedRegister(_ insn: ARM64Instruction, value: UInt64) -> UInt32? {+ let ops = insn.detail?.operands+ let wanted = Int64(bitPattern: value)++ // `mov Xd, #imm` / `movz Xd, #imm, lsl #…`: two operands.+ if ["mov", "movz"].contains(insn.mnemonic),+ let ops, ops.count == 2,+ ops[0].type == .register, ops[1].type == .immediate,+ ops[1].imm == wanted+ {+ return xRegisterNumber(ops[0].reg)+ }++ // `orr Xd, XZR, #bitmask` as Capstone spells it unaliased: the middle+ // operand must be xzr for this to be a plain materialisation.+ if insn.mnemonic == "orr",+ let ops, ops.count == 3,+ ops[0].type == .register, ops[1].type == .register, ops[1].reg == .xzr,+ ops[2].type == .immediate,+ ops[2].imm == wanted+ {+ return xRegisterNumber(ops[0].reg)+ }++ return nil+ }++ /// The number of an x0…x30 register, or nil for anything else.+ private func xRegisterNumber(_ reg: ARM64Register) -> UInt32? {+ for n in 0 ... 30 where ARM64Register.x(n) == reg {+ return UInt32(n)+ }+ return nil+ }++ /// The lane number of a vector register in any Capstone spelling — `v0`,+ /// `q0`, `d0` — or nil for anything else.+ private func vectorLane(_ reg: ARM64Register) -> Int? {+ guard let name = reg.name,+ let prefix = name.first, "vqdhsb".contains(prefix),+ let lane = Int(name.dropFirst())+ else { return nil }+ return lane+ }++ private func hex(_ v: UInt64) -> String {+ "0x\(String(v, radix: 16))"+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swiftindex 8485d251..97cedfbd 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift@@ -65,9 +65,13 @@ public final class KernelCustomFirmwarePatcher: KernelCustomFirmwarePatcherBase,// RegisterNotificationPort off-by-one, so the personalized DDI attaches// (/System/Developer auto-mount). Pairs with the sandbox ops[124] allow// and the diskimagesiod isMountComplete→YES userland patch (cfw_install).+ // - Shared region size: the arm64 region widens from 6 GiB to 7 GiB so a+ // 27 cache (0x185804000 on 27.0.1 iPhone18,x) maps at all. A 26.x base's+ // own cache fits the stock region, so the kernel is left stock there.if applyIOS27 {patchIoucFailedSandbox()patchDiskImages2ClientAbi()+ patchSharedRegionSize()} else if applyParavirtUserClients {patchParavirtUserClientsNarrow()}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swiftindex f30fd373..163e5af2 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift@@ -141,6 +141,14 @@ public enum FirmwareKernelCustomFirmwarePatchSet {target: .firmware(.kernelcache),bootEssential: true,),+ VPhonePatchDeclaration(+ identifier: "kernel-boot-shared_region_size",+ title: "Shared region size",+ summary: "Widens the arm64 shared region from 6 GiB to 7 GiB so an iOS 27 cache spans it.",+ target: .firmware(.kernelcache),+ applicability: ios27,+ bootEssential: true,+ ),// MARK: Filesystemdiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swiftindex 29b9758f..a183004d 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift@@ -17,6 +17,13 @@// `operandCoverageCases` then exercises the rest of each encoder's operand range// (encoding-boundary immediates, backward branches, every shift amount), because// the call sites alone leave most fields pinned at one value.+//+// `encodeMovkX` and `encodeStpX` came after the Python was gone. Their words+// are keystone 0.9.2 (Homebrew `keystone`) through a ten-line C driver outside+// the repository: `ks_asm` on the KS_ARCH_ARM64 / KS_MODE_LITTLE_ENDIAN engine,+// one instruction per line. The same driver reproduced the kernel's own bytes for+// `mov x26, #0x180000000`, `dup v0.2d, x22` and `str q0, [sp, #0x70]` before+// it was trusted with these.@testable import FirmwarePatcherimport Foundation@@ -426,6 +433,62 @@ struct ARM64EncoderKeystoneParityTests {encoded: ARM64Encoder.encodeLdrWUnsignedOffset(rt: 30, rn: 29, offset: 0x3FFC),origin: "LDR W max imm12",),+ // --- the shared region size patch, and encodeMovkX's lanes ----------+ ARM64EncodingCase(+ source: "movz x22, #0xc000, lsl #16",+ keystone: 0xD2B8_0016,+ encoded: ARM64Encoder.encodeMovzX(rd: 22, imm16: 0xC000, shift: 16),+ origin: "kernel-boot-shared_region_size size movz lo",+ ),+ ARM64EncodingCase(+ source: "movk x22, #0x1, lsl #32",+ keystone: 0xF2C0_0036,+ encoded: ARM64Encoder.encodeMovkX(rd: 22, imm16: 0x1, shift: 32),+ origin: "kernel-boot-shared_region_size size movk hi",+ ),+ ARM64EncodingCase(+ source: "movk x0, #0xffff",+ keystone: 0xF29F_FFE0,+ encoded: ARM64Encoder.encodeMovkX(rd: 0, imm16: 0xFFFF, shift: 0),+ origin: "MOVK X hw=0",+ ),+ ARM64EncodingCase(+ source: "movk x9, #0xbeef, lsl #16",+ keystone: 0xF2B7_DDE9,+ encoded: ARM64Encoder.encodeMovkX(rd: 9, imm16: 0xBEEF, shift: 16),+ origin: "MOVK X hw=1",+ ),+ ARM64EncodingCase(+ source: "movk x30, #0x1234, lsl #48",+ keystone: 0xF2E2_469E,+ encoded: ARM64Encoder.encodeMovkX(rd: 30, imm16: 0x1234, shift: 48),+ origin: "MOVK X hw=3",+ ),+ // --- encodeStpX: the patch's store, zero, both imm7 ends ----------+ ARM64EncodingCase(+ source: "stp x26, x22, [sp, #0x70]",+ keystone: 0xA907_5BFA,+ encoded: ARM64Encoder.encodeStpX(rt1: 26, rt2: 22, rn: 31, offset: 0x70),+ origin: "kernel-boot-shared_region_size stp",+ ),+ ARM64EncodingCase(+ source: "stp x3, x4, [x5]",+ keystone: 0xA900_10A3,+ encoded: ARM64Encoder.encodeStpX(rt1: 3, rt2: 4, rn: 5, offset: 0),+ origin: "STP X offset 0",+ ),+ ARM64EncodingCase(+ source: "stp x0, x1, [x2, #-0x200]",+ keystone: 0xA920_0440,+ encoded: ARM64Encoder.encodeStpX(rt1: 0, rt2: 1, rn: 2, offset: -0x200),+ origin: "STP X min imm7",+ ),+ ARM64EncodingCase(+ source: "stp x29, x30, [sp, #0x1f8]",+ keystone: 0xA91F_FBFD,+ encoded: ARM64Encoder.encodeStpX(rt1: 29, rt2: 30, rn: 31, offset: 0x1F8),+ origin: "STP X max imm7",+ ),]static let allCases: [ARM64EncodingCase] = asmCallSiteCases + operandCoverageCases@@ -559,6 +622,15 @@ struct ARM64EncoderRangeTests {@Test func `movz refuses unrepresentable shift`() {#expect(ARM64Encoder.encodeMovzW(rd: 0, imm16: 1, shift: 32) == nil, "W has hw 0..1")#expect(ARM64Encoder.encodeMovzX(rd: 0, imm16: 1, shift: 64) == nil, "X has hw 0..3")+ #expect(ARM64Encoder.encodeMovkX(rd: 0, imm16: 1, shift: 64) == nil, "X has hw 0..3")+ #expect(ARM64Encoder.encodeMovkX(rd: 0, imm16: 1, shift: 8) == nil, "a lane is 16 bits")+ }++ @Test func `stp refuses unscalable offsets`() {+ #expect(ARM64Encoder.encodeStpX(rt1: 0, rt2: 1, rn: 31, offset: 0x74) == nil, "multiple of 8")+ #expect(ARM64Encoder.encodeStpX(rt1: 0, rt2: 1, rn: 31, offset: 0x200) == nil, "one past imm7")+ #expect(ARM64Encoder.encodeStpX(rt1: 0, rt2: 1, rn: 31, offset: -0x208) == nil, "one below imm7")+ #expect(ARM64Encoder.encodeStpX(rt1: 32, rt2: 1, rn: 31, offset: 0) == nil)}// MARK: CSETdiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelCustomFirmwarePatchSharedRegionSizeTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelCustomFirmwarePatchSharedRegionSizeTests.swiftnew file mode 100644index 00000000..886987c4--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelCustomFirmwarePatchSharedRegionSizeTests.swift@@ -0,0 +1,233 @@+// KernelCustomFirmwarePatchSharedRegionSizeTests.swift — The shared region+// size patch against the block as it exists in both vphone600 26.4 variants.+//+// The five words below are the kernel's own bytes (verified against the+// research kernel at 0xfffffe0008e134e8 and the release kernel at+// 0xfffffe0008d0b4e8, byte-identical in both): the 26.4 compiler materialised+// 0x180000000 as an ORR logical-immediate alias (`mov x22, #0x180000000` — one+// movz cannot spell it, bits 31 and 32 straddle two 16-bit lanes), splatted it+// into the nesting pair with `dup v0.2d, x22`, stored the pair and+// re-materialised the same constant for the base register.+//+// The replacement words are keystone 0.9.2 (Homebrew `kstool`, outside this+// repository), the same provenance as the ARM64Encoder keystone-parity cases:+//+// movz x22, #0xc000, lsl #16 = 16 00 b8 d2 (size low lane)+// movk x22, #0x1, lsl #32 = 36 00 c0 f2 (size high lane → 0x1C0000000)+// stp x26, x22, [sp, #0x70] = fa 5b 07 a9 (nesting pair {base, size})+//+// The third replacement word is not listed there: it is the kernel's own base+// instruction, copied verbatim by the patch. The trailing `b` is preserved+// too, so the test pins it.++@testable import FirmwarePatcher+import Foundation+import Testing+import VPhonePatchKit++@Suite("kernel-boot-shared_region_size")+struct KernelCustomFirmwarePatchSharedRegionSizeTests {+ // MARK: - Synthetic kernel++ /// `mov x22/x26, #0x180000000` — the ORR logical-immediate alias, exactly+ /// as the kernel encodes it (keystone: the same word with any other Rd+ /// differs only in bits 4:0).+ static let movRegionConstantX22: [UInt8] = [0xF6, 0x07, 0x61, 0xB2]+ static let movRegionConstantX26: [UInt8] = [0xFA, 0x07, 0x61, 0xB2]+ static let dupV0x22: [UInt8] = [0xC0, 0x0E, 0x08, 0x4E]+ static let strQ0Sp70: [UInt8] = [0xE0, 0x1F, 0x80, 0x3D]+ /// `b .+0x60` — closes the block; the patch must leave it alone.+ static let branchForward: [UInt8] = [0x18, 0x00, 0x00, 0x14]++ /// The four words the patch writes over the block: the size's two lanes+ /// (into the block's own size register), the kernel's own base word, and+ /// the pair store. Every word keystone-verified.+ static func expectedReplacement(sizeLo: [UInt8], sizeHi: [UInt8], baseInsn: [UInt8], stp: [UInt8]) -> [UInt8] {+ sizeLo + sizeHi + baseInsn + stp+ }++ /// A minimal arm64 kernel image: header + one `__TEXT_EXEC` segment whose+ /// text holds the shared region block. `blockOff` is where the block lands.+ static func kernel(withBlock block: [UInt8]) -> (data: Data, blockOff: Int) {+ let textStart = 0x100+ var text = [UInt8](repeating: 0xD4, count: 0x20) // UDF padding before+ let blockOff = textStart + text.count+ text += block+ text += [UInt8](repeating: 0xD4, count: 0x20) // UDF padding after+ while text.count % 0x100 != 0 { text.append(0xD4) }++ var image = Data()+ func append32(_ value: UInt32) {+ withUnsafeBytes(of: value.littleEndian) { image.append(contentsOf: $0) }+ }+ func append64(_ value: UInt64) {+ withUnsafeBytes(of: value.littleEndian) { image.append(contentsOf: $0) }+ }++ append32(0xFEED_FACF) // magic+ append32(0x0100_000C) // cputype: arm64+ append32(2) // cpusubtype: arm64e+ append32(2) // filetype+ append32(1) // ncmds+ append32(72) // sizeofcmds+ append32(0) // flags+ append32(0) // reserved+ // LC_SEGMENT_64 __TEXT_EXEC+ append32(0x19)+ append32(72)+ var segname = Data("__TEXT_EXEC".utf8).prefix(16)+ segname.append(contentsOf: [UInt8](repeating: 0, count: 16 - segname.count))+ image.append(segname)+ append64(0xFFFF_FE00_0700_4000) // vmaddr+ append64(UInt64(text.count)) // vmsize+ append64(UInt64(textStart)) // fileoff+ append64(UInt64(text.count)) // filesize+ append32(5) // maxprot r-x+ append32(5) // initprot r-x+ append32(0) // nsects+ append32(0) // flags++ image.append(contentsOf: [UInt8](repeating: 0, count: textStart - image.count))+ image.append(contentsOf: text)+ return (image, blockOff)+ }++ /// The block as the 26.4 kernel ships it.+ static var stockBlock: [UInt8] {+ movRegionConstantX22 + dupV0x22 + strQ0Sp70 + movRegionConstantX26 + branchForward+ }++ // MARK: - The patch++ @Test func `rewrites the block and preserves the branch`() throws {+ let (data, blockOff) = Self.kernel(withBlock: Self.stockBlock)+ let patcher = KernelCustomFirmwarePatcher(data: data, verbose: false)+ patcher.parseMachO()++ #expect(patcher.patchSharedRegionSize())++ let records = patcher.patches+ #expect(records.count == 1)+ let record = try #require(records.first)+ #expect(record.patchID == "kernel-boot-shared_region_size")+ #expect(record.fileOffset == blockOff)++ // movz x22, #0xc000, lsl #16 and movk x22, #0x1, lsl #32 build the+ // 0x1C0000000 size; the kernel's own base word follows unchanged;+ // stp x26, x22, [sp, #0x70] stores the nesting pair {base, size}.+ let expected = Self.expectedReplacement(+ sizeLo: [0x16, 0x00, 0xB8, 0xD2],+ sizeHi: [0x36, 0x00, 0xC0, 0xF2],+ baseInsn: Self.movRegionConstantX26,+ stp: [0xFA, 0x5B, 0x07, 0xA9],+ )+ #expect(Array(patcher.patchedData[blockOff ..< (blockOff + 16)]) == expected)+ // The branch that closes the block is untouched.+ #expect(Array(patcher.patchedData[(blockOff + 16) ..< (blockOff + 20)]) == Self.branchForward)+ }++ @Test func `does not match a second time over patched bytes`() throws {+ let (data, _) = Self.kernel(withBlock: Self.stockBlock)+ let patcher = KernelCustomFirmwarePatcher(data: data, verbose: false)+ patcher.parseMachO()+ #expect(patcher.patchSharedRegionSize())++ // A fresh patcher over the patched image: the `dup` that carried the+ // single constant into both lanes is gone, so there is nothing to find.+ let second = KernelCustomFirmwarePatcher(data: patcher.patchedData, verbose: false)+ second.parseMachO()+ #expect(!second.patchSharedRegionSize())+ #expect(second.patches.isEmpty)+ }++ @Test func `refuses a block whose constant is not the stock region`() throws {+ // movz x22, #0x7000, lsl #16 (0xD2AE0016): a different constant, so the+ // window must not match even though the dup and the store are present.+ let other: [UInt8] = [0x16, 0x00, 0xAE, 0xD2]+ let block = other + Self.dupV0x22 + Self.strQ0Sp70 + Self.movRegionConstantX26 + Self.branchForward+ let (data, _) = Self.kernel(withBlock: block)+ let patcher = KernelCustomFirmwarePatcher(data: data, verbose: false)+ patcher.parseMachO()++ #expect(!patcher.patchSharedRegionSize())+ #expect(patcher.patches.isEmpty)+ }++ @Test func `follows the registers and displacement of the block`() throws {+ // The same shape with a different register allocation and pair slot —+ // x19 size, x20 base, pair at [sp, #0x80] — so the matcher cannot be+ // pinned to x22/x26/0x70. All words keystone-verified:+ // mov x19, #0x180000000 / dup v1.2d, x19 / str q1, [sp, #0x80] /+ // mov x20, #0x180000000 / stp x20, x19, [sp, #0x80]+ let block: [UInt8] = [+ 0xF3, 0x07, 0x61, 0xB2,+ 0x61, 0x0E, 0x08, 0x4E,+ 0xE1, 0x23, 0x80, 0x3D,+ 0xF4, 0x07, 0x61, 0xB2,+ ] + Self.branchForward+ let (data, blockOff) = Self.kernel(withBlock: block)+ let patcher = KernelCustomFirmwarePatcher(data: data, verbose: false)+ patcher.parseMachO()++ #expect(patcher.patchSharedRegionSize())+ #expect(patcher.patches.count == 1)+ // The size lanes follow x19 (movz x19, #0xc000, lsl #16 = 13 00 b8 d2,+ // movk x19, #0x1, lsl #32 = 33 00 c0 f2), the pair store keeps the+ // block's own registers and slot, and the kernel's base word is+ // copied verbatim.+ let expected = Self.expectedReplacement(+ sizeLo: [0x13, 0x00, 0xB8, 0xD2],+ sizeHi: [0x33, 0x00, 0xC0, 0xF2],+ baseInsn: [0xF4, 0x07, 0x61, 0xB2],+ stp: [0xF4, 0x4F, 0x08, 0xA9],+ )+ #expect(Array(patcher.patchedData[blockOff ..< (blockOff + 16)]) == expected)+ }++ // MARK: - The real kernel++ /// Runs the patch over a real vphone600 kernelcache (IM4P or raw) and+ /// pins the one record it must produce. Gated on `VPHONE_VP600_KERNEL`+ /// because the kernel is 30-odd MB of machine-local firmware; a machine+ /// without it skips. Both variants qualify — the block is byte-identical:+ ///+ /// VPHONE_VP600_KERNEL=~/.vphone/machines/<vm>/FirmwareOriginals/\+ /// <restore>/kernelcache.research.vphone600 xcodebuild … test+ @Test(.enabled(+ if: ProcessInfo.processInfo.environment["VPHONE_VP600_KERNEL"] != nil,+ "VPHONE_VP600_KERNEL is not set; point it at a kernelcache.*.vphone600 to run"+ ))+ func `patches a real vphone600 kernel`() throws {+ let path = ProcessInfo.processInfo.environment["VPHONE_VP600_KERNEL"]!+ let (payload, _) = try IM4PHandler.load(contentsOf: URL(fileURLWithPath: path))++ let patcher = KernelCustomFirmwarePatcher(data: payload, verbose: true)+ patcher.parseMachO()+ #expect(patcher.patchSharedRegionSize())++ let record = try #require(patcher.patches.first)+ #expect(record.patchID == "kernel-boot-shared_region_size")++ // The record covers the whole four-instruction block: size low lane,+ // size high lane, the kernel's own base word, the pair store. The+ // original bytes are a `Data` slice whose indices may not start at 0,+ // so they are rebased through an Array before indexing; the base word+ // is the fourth original word — the rewrite moves it up one slot.+ let originalWords = Array(record.originalBytes)+ #expect(originalWords.count == 16)+ let expected = Self.expectedReplacement(+ sizeLo: [0x16, 0x00, 0xB8, 0xD2],+ sizeHi: [0x36, 0x00, 0xC0, 0xF2],+ baseInsn: Array(originalWords[12 ..< 16]),+ stp: [0xFA, 0x5B, 0x07, 0xA9],+ )+ #expect(Array(record.patchedBytes) == expected)+ // And the branch after the block survived untouched, byte for byte+ // against the payload as loaded. `payloadBytes` is an Array so the+ // absolute file offsets index it directly.+ let payloadBytes = Array(payload)+ let patched = Array(patcher.patchedData)+ let after = patched[(record.fileOffset + 16) ..< (record.fileOffset + 20)]+ #expect(after == payloadBytes[(record.fileOffset + 16) ..< (record.fileOffset + 20)])+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex 265c2a81..032fbab9 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -168,9 +168,13 @@ struct VPhoneCustomFirmwareInstaller {// `withLateGuestPatches` added from the current selection. A VM that was// never installed has an empty prior set (its guest is pristine); that// is decided below, where the mounted volume says whether it was.- let receiptGuest = (try? bundleDirectory.readData(VPhonePatchPresetStore.receiptFileName))- .flatMap { try? VPhoneVirtualMachinePatchReceipt.decode($0) }?- .parts[VPhoneVirtualMachinePatchReceipt.guestPart]+ let receipt = (try? bundleDirectory.readData(VPhonePatchPresetStore.receiptFileName))+ .flatMap { try? VPhoneVirtualMachinePatchReceipt.decode($0) }+ let receiptGuest = receipt?.parts[VPhoneVirtualMachinePatchReceipt.guestPart]+ .map { Set($0.patches) }+ // The kernel patches the restore or the last `cfw update-kernel` put in+ // this VM's kernelcache, which decide the shared region size below.+ let receiptKernel = receipt?.parts[VPhoneVirtualMachinePatchReceipt.part(for: .firmware(.kernelcache))].map { Set($0.patches) }let guestTargets = FirmwareGuestPatchResolution.guestTargetIdentifierslet effectiveEnabled = Set(plan?.enabledPatches ?? [])@@ -340,6 +344,7 @@ struct VPhoneCustomFirmwareInstaller {owner: callerUID,plan: plan,priorGuest: priorGuest,+ kernelPatches: receiptKernel,environmentOnly: false,)case .environmentOnly:@@ -357,6 +362,7 @@ struct VPhoneCustomFirmwareInstaller {owner: nil,plan: plan,priorGuest: priorGuest,+ kernelPatches: receiptKernel,environmentOnly: true,)}@@ -985,6 +991,7 @@ struct VPhoneCustomFirmwareInstaller {owner: uid_t?,plan: VPhoneVirtualMachinePatchPlan?,priorGuest: Set<String>,+ kernelPatches: Set<String>?,environmentOnly: Bool,) throws -> Set<String> {var live = Set<String>()@@ -1063,9 +1070,24 @@ struct VPhoneCustomFirmwareInstaller {// maps at no slide, and the guest panics on first boot. Refuse before// the redeploy and the cache patches. A header this check cannot read// is left to the dyld patches below, as it was before the check.+ //+ // The region is the widened 0x1C0000000 only when this VM's kernel+ // carries `kernel-boot-shared_region_size`, as its receipt records:+ // a 27.x VM restored by an older bundle, or with the patch unticked,+ // still has the stock 6 GiB and must still be refused. A VM with no+ // kernelcache receipt falls back to the patch's applicability, the+ // 27.x base.let dsc = try verifiedDyldCacheDirectory(system: system)+ let widenedRegion = kernelPatches.map { $0.contains("kernel-boot-shared_region_size") }+ ?? version.hasPrefix("27.")+ let kernelRegionSize = widenedRegion+ ? DyldSharedCacheMaxSlidePatcher.patchedKernelSharedRegionSize+ : DyldSharedCacheMaxSlidePatcher.kernelSharedRegionSizedo {- try DyldSharedCacheMaxSlidePatcher.requireFitsAtSlideZero(chunksDirectory: URL(fileURLWithPath: dsc))+ try DyldSharedCacheMaxSlidePatcher.requireFitsAtSlideZero(+ chunksDirectory: URL(fileURLWithPath: dsc),+ kernelRegionSize: kernelRegionSize,+ )} catch let overflow as DyldSharedCacheMaxSlidePatcher.RegionOverflow {throw overflow} catch {diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swiftindex abe95aa3..6ca426b6 100644--- a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift@@ -150,6 +150,19 @@ public enum ARM64Encoder {return ARM64.encodeU32(insn)}+ /// Encode MOVK Xd, #imm16, LSL #shift (64-bit) — replace one 16-bit lane of+ /// Xd and keep the others.+ ///+ /// Format: `[31] = 1 (sf)`, `[30:29] = 11`, `[28:23] = 100101`,+ /// `[22:21] = hw`, `[20:5] = imm16`, `[4:0] = Rd`+ public static func encodeMovkX(rd: UInt32, imm16: UInt16, shift: UInt32 = 0) -> Data? {+ guard shift % 16 == 0 else { return nil }+ let hw = shift / 16+ guard hw <= 3 else { return nil }+ let insn: UInt32 = (0b1_1110_0101 << 23) | (hw << 21) | (UInt32(imm16) << 5) | (rd & 0x1F)+ return ARM64.encodeU32(insn)+ }+/// Encode `MOV Xd, Xm` (the ORR Xd, XZR, Xm alias). With `rm == 31` (XZR) this/// is the canonical "zero a 64-bit register" (`mov xd, xzr`).///@@ -208,6 +221,33 @@ public enum ARM64Encoder {return ARM64.encodeU32(insn)}+ // MARK: - Stores++ /// Encode `STP Xt1, Xt2, [Xn, #offset]` — 64-bit store pair, signed scaled+ /// offset, no writeback.+ ///+ /// Format: `[31:30] = 10 (opc = 64-bit)`, `[29:27] = 101`, `[26] = 0 (V)`,+ /// `[25:23] = 010 (signed offset)`, `[22] = 0 (L = store)`,+ /// `[21:15] = imm7`, `[14:10] = Rt2`, `[9:5] = Rn`, `[4:0] = Rt1`+ ///+ /// `imm7` is scaled by 8, so `offset` must be a multiple of 8 in+ /// `-512...504`. `rn == 31` means SP.+ public static func encodeStpX(rt1: UInt32, rt2: UInt32, rn: UInt32, offset: Int32) -> Data? {+ guard rt1 < 32, rt2 < 32, rn < 32 else { return nil }+ guard offset % 8 == 0 else { return nil }+ let imm7 = offset / 8+ guard imm7 >= -64, imm7 <= 63 else { return nil }++ var insn: UInt32 = 0b10 << 30+ insn |= 0b101 << 27+ insn |= 0b010 << 23+ insn |= (UInt32(bitPattern: imm7) & 0x7F) << 15+ insn |= rt2 << 10+ insn |= rn << 5+ insn |= rt1+ return ARM64.encodeU32(insn)+ }+// MARK: - Decode Helpers/// Decode a B or BL target address from an instruction at `pc`.