Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

feat(dsc): port the eight dyld-cache patchers to Swift

Lakr85ebd7b7132f
diff --git a/research/0_binary_patch_comparison.md b/research/0_binary_patch_comparison.md
index b01ffd8a..4fc496a2 100644
--- a/research/0_binary_patch_comparison.md
+++ b/research/0_binary_patch_comparison.md
@@ -196,6 +196,72 @@ do NOT execute these).
| 15 | Derive `matched` from `error_code` + drop the `brk #1` in libxpc `_xpc_token_satisfies_lwcr` (`cset w8,ne; eor w8,w0,w8; tbz w8,#0` → `cset w0,eq; nop; nop`) + per-page re-attest — **iOS 27.0** | DSC `libxpc.dylib` | **iOS-27 daemon crash-loop fix (Lightweight Code Requirement).** iOS 27 lets an XPC server pin a "lightweight code requirement" (LWCR) on its listener — `xpc_connection_set_peer_lightweight_code_requirement`, or the Swift `XPCPeerRequirement.hasEntitlement(_:)` wrapper (→ `xpc_peer_requirement_create_entitlement_exists` → `_xpc_peer_requirement_create_lwcr_entitlement_requirement` → `xpc_peer_requirement_create_lwcr`). Creating the requirement runs a self-check, `_xpc_token_satisfies_lwcr`, which calls an internal matcher returning a `matched` bool (w0) plus a `match_result.error_code` (`AICMR_MATCH == 0`), then hard-asserts they agree (`matched == (error_code == 0)`) via `_os_crash_msg` → `brk #1`. On stock iOS the two always agree; under our JB code-signing environment the matcher's query writes `error_code = MATCH(0)` yet returns a failure status, so the matcher yields the forbidden `(matched=0, error_code=0)` pair and libxpc aborts. Because EVERY daemon that pins an entitlement peer-requirement at startup hits it, `intelligencetasksd` / `searchpartyd` / `transparencyd` / `bluetoothd` (and others) crash-loop continuously from boot (launchd re-spawn + ReportCrash churn). Fix: recompute `matched` from `error_code` and make the abort unreachable — `cset w8,ne; eor w8,w0,w8; tbz w8,#0,<abort>` → `cset w0,eq; nop; nop`; the function now returns `(error_code == 0)`, which reproduces stock's verdict when the two agree and resolves the contradiction toward "satisfied" when error_code says MATCH (real allow/deny for genuinely (un)satisfied peers is unchanged, since those set `error_code` != 0). Fully dynamic: resolved via the DSC's own `.symbols` in-image local-symbol table as `__xpc_token_satisfies_lwcr` (the double-underscore mangled name; a single-underscore lookup silently skipped every iOS-27 build until fixed 2026-08-11), the check located by control-flow shape in Capstone (`cset wC,ne; eor wE,w0,wC; tbz wE,#0`), replacements from Keystone, modified 16 KiB page re-attested (`cfw_dsc_codesign.py`; TXM enforces per-page; CDHash change accepted by the JB always-true AMFI cdhash-trust patch). Install gate: **`27.*`** (in `cfw_install.sh`, same block as maxSlide/lsd). Patcher additionally self-gates (`patch-xpc-lwcr`): no-op on pre-iOS-27 userlands where the symbol is absent. **VALIDATED on-device (2026-07-22, `17,3_27.0_24A5390f` + cloudOS 26.4, JB, host-mount deploy): patched bytes live (`e0179f1a 1f2003d5 1f2003d5`); the four LWCR crash-loopers disappear from the crash census after boot; launchd itself (which links libxpc) boots clean past first unlock — patch does not brick boot. NOTE: does NOT stop the resprings — those are a separate `FileProviderResolver` ResolverService memory-balloon → jetsam → backboardd kill (see investigation notes).** See `scripts/patchers/cfw_patch_xpc_lwcr.py`. **FIX (2026-09-22):** same idempotence gap as row 12, and for the same structural reason: `_find_consistency_check` searches for `cset wC,ne; eor wE,w0,wC; tbz wE,#0`, which is precisely the idiom this patch replaces, so on a cache it had already patched the search returned `None` and raised `ValueError: LWCR consistency idiom ... not found`. The per-edit `already patched` byte comparison further down could never run, because it needs the addresses that search has to supply first. Hit live on `17,3_27.0_24A435` (RC) + cloudOS 26.4, JB, host-mount flow, when a first `cfw_install_host` pass completed phase 1/7 and then failed later at JB-1 (missing `insert_dylib`); the retry died here. Confirmed by read-only host-mount disassembly of `__xpc_token_satisfies_lwcr` @ `0x1805DD5BC`: `cmp w8,#0; cset w0,eq; nop; nop` — already patched. A new `_find_patched_shape` now recognizes that post-patch shape (`cset w0,eq` + two `nop`s, anchored on the `cmp wX,#0` that feeds it) and returns a no-op instead of raising. Checked against the live cache (dry run returns rather than raises) and with negative controls: fed the pre-patch stream the detector stays silent and the normal idiom search still matches, so the patching path is intact on a pristine cache. | Y | Y | Y |
| 16 | NOP the sysctl-error `b.eq <os_crash>` in libSystem `___os_lockdown_mode_enabled_block_invoke` (`cmn w0,#1; b.eq <crash>` → `nop`) + per-page re-attest — **iOS 27.0** | DSC `libSystem` (`lockdown_mode.c`) | **iOS-27 launchd (pid 1) boot-panic fix.** iOS 27's `os_lockdown_mode_enabled()` resolves Lockdown Mode once via `sysctlbyname("security.mac.lockdown_mode_state_public", &out, &len, 0, 0)`; on a -1 return it `os_crash`es (`lockdown_mode.c:os_lockdown_mode_enabled_block_invoke:47`). The vphone base kernel (cloudOS 26.x) does not implement that MAC sysctl, so the call returns -1/ENOENT and the first process to query Lockdown Mode after "Continuing system boot" aborts — that process is launchd (pid 1), so the kernel panics `initproc exited -- exit reason namespace 2 subcode 0x6 description: none`. b4 (24A5390f) boots on the same kernel; the sysctl query is new in b5 (24A5408d). The block pre-zeroes its output buffer (`stp x8, xzr, [sp]`), so NOPping the error branch falls through to the normal path, reads 0, records "Lockdown Mode disabled", and returns cleanly; on a kernel that implements the sysctl the branch is never taken (w0==0), so the patch is behavior-neutral. Dynamic: `___os_lockdown_mode_enabled_block_invoke` resolved via the DSC's own `.symbols` local-symbol table; the `cmn wR,#1; b.eq` sysctl-error idiom located by control-flow shape in Capstone; NOP from Keystone; modified 16 KiB page re-attested (`cfw_dsc_codesign.py`). Install gate: **`27.*`** (same block as maxSlide/lsd/lwcr). Self-gates: no-op where the symbol is absent (pre-iOS-27 userlands). **Root-caused + verified on-device 2026-08-11** (`17,3_27.0_24A5408d` + cloudOS 26.4, JB): abort message read live via the kernel GDB stub (patched `_abort`→`b .` to freeze launchd's spinning vCPU, then read its registers + the libSystem crash-info global) = `lockdown_mode.c:os_lockdown_mode_enabled_block_invoke:47: No such file or directory`; with the NOP applied the panic is gone and boot continues past "Got first unlock" into normal daemon startup. See `scripts/patchers/cfw_patch_lockdown_mode.py`. **FIX (2026-09-22):** third instance of the row-12 idempotence gap, found immediately after the row-15 one on the same `17,3_27.0_24A435` (RC) + cloudOS 26.4 JB host-mount re-run. `_find_error_gate` required the slot after `cmn wR,#1` to be a `b.eq`; once patched it holds the `nop` this patch writes, so the search returned `None` and raised `ValueError: ... sysctl-error gate not found` — again before the `cur == nop` byte comparison below it could ever be reached. Confirmed by read-only host-mount disassembly of `___os_lockdown_mode_enabled_block_invoke` @ `0x237EF2260`: `bl <sysctlbyname>; cmn w0,#1; nop` at `0x237EF2298`. The gate slot now also matches `nop`, which lets the existing byte comparison report the already-patched state; the `bl` + `cmn wR,#1` anchor is unchanged, and re-writing a NOP over a NOP is inert. Negative controls checked: an unrelated instruction in the slot, a `cmn` with no preceding `bl`, and a `cmn` with the wrong immediate are all still rejected, and the pre-patch stream still resolves to the `b.eq`. | Y | Y | Y |
+### Swift port status — the eight DSC patchers (2026-09-23)
+
+The rows above describe the patches, which have not changed. What is new is that
+each now has an in-process Swift implementation on the validated DSC foundation
+(`DSCChunkSet`, `DSCCodeSignature`, `DSCLocalSymbolTable`, `DSCSymbolResolver`).
+Every one was proven on the real 24A435 arm64e cache — `ipsws/ref_extract/dsc_pristine`,
+79 chunks + `.symbols` = 80 files, 6.7 GB — by running the Python on one `cp -c`
+clone and the Swift on another and comparing all 80 files. The Python stays in
+place until a `vphone-cli` verb replaces each `cfw.py` call site.
+
+| Python | Swift | Sites | Parity on the real cache |
+| --- | --- | --- | --- |
+| `cfw_patch_dsc_maxslide.py` | `DSCMaxSlidePatcher` | 1 (header `@0xF0`) | 80/80 identical. vs pristine exactly 1 byte differs (`0xF3`, `0x20`→`0x00`). Logs character-identical. No re-attestation on either side (header, not a code page) — confirmed by hashing the CD blob. |
+| `cfw_patch_lockdown_mode.py` | `DSCLockdownModePatcher` | 1 + 1 slot | Same gate `b.eq @0x237EF2298` (`20010054`→`1f2003d5`), same slot 7868 of `.40`, same hash. `diff -rq` clean over 80 files; second pass a no-op both sides. |
+| `cfw_patch_lsd_embedded_reg.py` | `DSCLSDEmbeddedRegPatcher` | 1 + 1 slot | Same gate `cbz w0 @0x186EEA024`, same slot 6842 of `.01`. 0 differing files. Cross-run both ways: each re-run over the other's output is a no-op. |
+| `cfw_patch_xpc_lwcr.py` | `DSCXPCLWCRPatcher` | 3 + 1 slot | Same three addresses `0x1805DD644/8/C`, same slot 119 of `.01`. `diff -rq` clean. |
+| `cfw_patch_camera_dsc.py` | `DSCCameraPatcher` | 6 + 5 slots | Both families. 0 differing files; exactly 2 chunks differ from pristine. |
+| `cfw_patch_iomfb_force_kern.py` | `DSCIOMFBForceKernPatcher` | 31 retargeted | Trampoline shape verified by Capstone, branch bytes from Keystone. |
+| `cfw_patch_iomfb_swapend.py` | `DSCIOMFBSwapEndPatcher` | 1 | Size **discovered, never matched**; anchored on the method-5 call set-up. |
+| `cfw_patch_hv_vmm_dsc.py` **+** `cfw_patch_hv_vmm.py` | `DSCHVVMMPatcher` | blacklist-flip mangle | Both halves in one type. The migration plan called `cfw_patch_hv_vmm.py` dead code; **it is not** — the DSC module live-imports `NEEDLE` / `MANGLED_NEEDLE` / `MANGLE_OFFSET` / `ORIGINAL_BYTE` / `MANGLED_BYTE` from it. |
+
+Each port was checked by a second agent that rebuilt the evidence rather than
+reading it: own drivers linked against the module, whole-cache byte comparison,
+and for `lsdreg` a differential sweep of both gate-finders over 33,000 function
+addresses (49 gates each, zero verdict differences).
+
+**Two defects that review found and this branch fixed:**
+
+* `DSCCameraPatcher` wrote each site as it classified it and re-attested once at
+ the end, so a throw in the second family left the first family's five writes on
+ disk with stale signature slots — half-patched *and* SIGKILL-on-page-in under
+ `codeSigningMonitor == 2`. `apply` now plans every family before writing any of
+ them, so a failure writes nothing. Pinned by
+ `DSCCameraPatcherTests.failureWritesNothing`, which fails and names
+ `dyld_shared_cache_arm64e.15` if the old shape is restored.
+* `DSCLockdownModePatcher.disassembleBlock` did not stop at an undecodable word.
+ `ARM64Disassembler` sets `cs.skipData = true` and the reference's `_cs`
+ (`cfw_asm.py:14`) does not, so where the Python's stream ends this one walked
+ past the data to its 60-instruction ceiling. On a userland with an inline
+ literal before the gate that inverts the failure mode: the Python stops the
+ install loudly, this would decode into unrelated code and could NOP a branch
+ there *and re-attest that page*. It now breaks on `insn.id == 0`, as
+ `DSCLSDEmbeddedRegPatcher.disassembleFunction` already did.
+
+**Known, not fixed** (all LOW, none changes a byte on this cache):
+
+* `DSCIOMFBSwapEndPatcher` — on the already-correct path it clears recorded
+ writes and re-attests nothing, so the returned `DSCReattestation` has empty
+ arrays and `isFullyAttested` is **vacuously true**. The Python re-hashes the
+ page and compares. Unreachable through today's shell graph; a footgun for the
+ Swift driver that is meant to replace it.
+* `DSCXPCLWCRPatcher` — a dry run returns `status == .patched, siteCount == 3`
+ although nothing was written; `DSCIOMFBSwapEndPatcher` takes the opposite
+ convention (`0`). A driver summing these for a preview gets a wrong total.
+* `DSCLSDEmbeddedRegPatcher` — record text says `cbz w0, 0x186eea048` where the
+ captured Python reference says `cbz w0, #0x186eea048`. libcapstone-spm
+ (Capstone 6) omits the `#` the venv's Capstone 5.0.7 emits. Bytes are
+ identical; a field-level diff against `reference_patches/` will flag it.
+* `DSCHVVMMPatcher.findStringSites(inMachO:)` skips a string section whose
+ declared extent overruns EOF, where the Python truncates and scans what is
+ there — a malformed binary reads as a clean no-op. No caller in the repo today.
+* `DSCMaxSlidePatcher` — the `sharedRegionSize >= mapped span` corroboration
+ couples the patch to `DSCChunkSet`'s file-exclusion policy, so a stray
+ cache-shaped file in the chunks directory turns a working patch into a hard
+ abort. Fail-closed, and left alone deliberately.
+
### Installed Components
| # | Component | Description | Regular | Dev | JB |
@@ -230,32 +296,54 @@ Before (cstring section bytes, 20 bytes total):
"kern.hv_vmm_present\0"
6B 65 72 6E 2E 68 76 5F 76 6D 6D 5F 70 72 65 73 65 6E 74 00
-After (1 byte change at offset 0):
- "Xern.hv_vmm_present\0"
- 58 65 72 6E 2E 68 76 5F 76 6D 6D 5F 70 72 65 73 65 6E 74 00
- ^^
+After (1 byte change at offset 5):
+ "kern.Xv_vmm_present\0"
+ 6B 65 72 6E 2E 58 76 5F 76 6D 6D 5F 70 72 65 73 65 6E 74 00
+ ^^
```
-The kernel's name-to-MIB translation fails with `ENOENT` when the
-caller asks for `"Xern.hv_vmm_present"`, so `sysctlbyname` returns
--1. The canonical post-call check (`cbnz w0, skip` or
-`cmp w0,#0 ; b.ne skip`) then takes the skip-cache path; the cached
-"is_vmm" byte stays at its initial value (BSS-zero = 0).
+**Byte 5, not byte 0.** The mangle has to keep the `kern.` top-level
+namespace intact or the kernel's name-to-MIB resolver routes the call to
+nothing at all. Byte 0 would give `Xern.hv_vmm_present`, and `Xern` is not
+a registered top-level sysctl namespace, so it could never resolve — see
+the comment at `scripts/patchers/cfw_patch_hv_vmm.py:40-47`.
+
+**Which way the lie runs.** This is the part that reads backwards if you
+have the pre-blacklist-flip design in mind. The companion kernel patch
+(`KernelEXPPatcher.patchHvVmmRename`) renames the OID itself, so after
+both halves are installed:
+
+* a **mangled** dylib asks for `kern.Xv_vmm_present`, which **resolves**
+ to the renamed OID and returns the truthful `1` — that is what keeps
+ graphics and accel passthrough working;
+* a **blacklisted** dylib keeps `kern.hv_vmm_present`, which now hits
+ `ENOENT`. Its post-call check (`cbnz w0, skip` or
+ `cmp w0,#0 ; b.ne skip`) takes the skip-cache path, the cached "is_vmm"
+ byte stays at BSS-zero, and that dylib believes it is not in a VM.
+
+So mangling is what tells a dylib the truth, and *not* mangling is what
+makes it lie. The blacklist is therefore the list of consumers that must
+be deceived (sign-in, device likeness), not the list of ones to fix.
We don't modify executable code at all — only one byte of read-only
-string data. The kernel call still happens (with the wrong name), so
-any sysctl-tracing infrastructure can still see activity.
+string data. The kernel call still happens, so any sysctl-tracing
+infrastructure can still see activity.
+
+Idempotent: the patcher scans for `MANGLED_NEEDLE` first
+(`cfw_patch_hv_vmm_dsc.py:133`) and each site re-checks byte 5 before
+writing, so a re-run does no work.
-Idempotent: a re-scan for the literal `"kern.hv_vmm_present\0"` finds
-no occurrences in already-mangled dylibs, so the patcher does no work
-on a re-run.
+**DSC-side patches** — driven by an explicit **blacklist**
+(`DONT_PATCH_INSTALL_NAMES` in `scripts/patchers/cfw_patch_hv_vmm_dsc.py`,
+~15 entries) applied to chunks under
+`SystemOS/System/Library/Caches/com.apple.dyld/`. Every dylib that is not
+named there gets mangled. Add a line to the blacklist to stop patching
+that dylib on the next install — useful for bisecting which consumer is
+responsible for an observable change.
-**DSC-side patches** — driven by an explicit whitelist
-(`PATCH_INSTALL_NAMES` in `scripts/patchers/cfw_patch_hv_vmm_dsc.py`)
-applied to chunks under
-`SystemOS/System/Library/Caches/com.apple.dyld/`. Comment a line in
-the whitelist to skip that dylib on the next install — useful for
-bisecting which consumer is responsible for an observable change.
+> The table below lists dylibs that ARE mangled, i.e. ones absent from the
+> blacklist. It used to be introduced as a `PATCH_INSTALL_NAMES` whitelist;
+> that name no longer exists in the module.
| Dylib | Component role (paraphrased) |
| --------------------------------------------------------- | ------------------------------------------------------------- |
@@ -322,11 +410,11 @@ System/Library/ExtensionKit/Extensions/HostInferenceProviderService.appex/HostIn
* `scripts/patchers/cfw_patch_hv_vmm_dsc.py` — DSC-native orchestrator.
No external `ipsw` dependency. For every `"kern.hv_vmm_present\0"`
occurrence in any executable mapping, walks back to the containing
- dylib's Mach-O header, reads `LC_ID_DYLIB`, and — if the install
- name is in the explicit `PATCH_INSTALL_NAMES` whitelist — rewrites
- the first byte of the cstring through `DSCChunks.write_at_vma`.
- Pure Python. Whitelist-based by design so an operator can comment
- out individual entries to bisect.
+ dylib's Mach-O header, reads `LC_ID_DYLIB`, and — unless the install
+ name is in the `DONT_PATCH_INSTALL_NAMES` blacklist — rewrites byte 5
+ of the cstring through `DSCChunks.write_at_vma`. Pure Python.
+ Blacklist-based by design so an operator can add an entry to take one
+ dylib out of the patch set and bisect.
* ~~`scripts/patchers/cfw.py patch-hv-vmm <binary>`~~ — **gone.** The
standalone-Mach-O subcommand and its backing patcher
(`cfw_patch_hv_vmm_rootfs.py`) were removed with item 8 in the
diff --git a/sources/FirmwarePatcher/DSC/Patchers/DSCCameraPatcher.swift b/sources/FirmwarePatcher/DSC/Patchers/DSCCameraPatcher.swift
new file mode 100644
index 00000000..b36d1f08
--- /dev/null
+++ b/sources/FirmwarePatcher/DSC/Patchers/DSCCameraPatcher.swift
@@ -0,0 +1,463 @@
+// DSCCameraPatcher.swift — The two camera DSC patch families, EXP only.
+//
+// Port of `scripts/patchers/cfw_patch_camera_dsc.py`, which stays the
+// independent reference: the parity gate is the Python run on one clone of the
+// real cache and this run on another, with the two clones compared byte for
+// byte.
+//
+// Two families, six sites
+// -----------------------
+//
+// 1. **NeutrinoCore short-circuit** — the five
+// `+[_NUStyleTransfer*Processor processWithInputs:arguments:output:error:]`
+// class methods become `mov w0, #0; ret`. Together with the DT
+// `/product/camera` node (`DeviceTreePatcher`), this lets Camera.app reach
+// the viewfinder: the style-thumbnail pipeline returns NO before it can
+// reach `_NUStyleEngineMemoryResource init…`, which asserts on a nil
+// descriptor when ANE detection comes back NO on this VM and SIGABRTs on
+// the first viewfinder render.
+//
+// 2. **AVCaptureDevice authorization gate** — `+[AVCaptureDevice
+// authorizationStatusForMediaType:]` in `AVFCapture` becomes
+// `mov w0, #3; ret`, `AVAuthorizationStatusAuthorized`. Every media type,
+// not just video: the VM does not service audio capture either, so an app
+// probing audio auth would have failed downstream regardless. Stage 0 of
+// the vcam stack — apps stop bailing on the auth check; frame delivery is
+// still owed by the downstream pipeline.
+//
+// What this port does not inherit
+// -------------------------------
+//
+// * **`ipsw dyld symaddr`.** The Python shells out to the Go tool and parses
+// its coloured output. Here the six symbols come from `DSCSymbolResolver`,
+// which reads the cache's own `.symbols` table. `DSCSymbolResolverTests`
+// pins all six against `ipsw` on the real cache, so the addresses are the
+// same addresses.
+// * **The raw-byte prologue test.** The Python compares the first four bytes
+// against `7f 23 03 d5`. Here the first instruction is decoded and its
+// mnemonic checked, per the patcher guardrails — an encoding of `pacibsp`
+// is recognised as `pacibsp`, not as four bytes.
+// * **Re-attesting per family.** The Python re-attests after each family, off
+// a list of bare addresses. Here every write is recorded by `DSCChunkSet`
+// and `reattestRecordedWrites` runs once at the end, off spans. Same pages
+// on this cache — the six sites are 8 bytes each and none is within 8 bytes
+// of a 16 KiB boundary — but a site that did straddle one would be fully
+// covered here and half-covered there.
+//
+// It does inherit the idempotence lesson the DSC gates taught three times
+// (`cfw_patch_lsd_embedded_reg`, `cfw_patch_xpc_lwcr`,
+// `cfw_patch_lockdown_mode` all raised on their own output). A prologue that is
+// already the replacement is recognised as such and rewritten inertly, so a
+// second install re-attests rather than throwing.
+//
+// CLI contract preserved from the Python
+// --------------------------------------
+//
+// cfw.py patch-camera-dsc <chunks_dir> <dsc_header> [--dry-run] [--force]
+// cfw_patch_camera_dsc.py <chunks_dir> <dsc_header> [--dry-run] [--force]
+// [--avf-only]
+//
+// `patch_camera_userland.sh dsc <chunks_dir> <dsc_header>` is the shape
+// `cfw_install_exp.sh` calls, and it passes neither flag. `<chunks_dir>` is the
+// directory of `dyld_shared_cache_arm64e*` files; `<dsc_header>` is the
+// unsuffixed chunk inside it, which the Python needed only because `ipsw` wants
+// a file rather than a directory. `applyAll` therefore takes the directory
+// alone and finds the header itself; `symbolCacheURL` still lets a caller name
+// the header separately, which is the only part of the two-argument shape a CLI
+// wrapper has to keep accepting.
+//
+// `--avf-only` is `applyAVFAuthorizationOnly`: the composition mode for a chunk
+// pulled off a device that already carries the NeutrinoCore patches.
+
+import Capstone
+import Foundation
+
+/// The camera-related patches applied to the SystemOS cryptex's shared cache.
+public enum DSCCameraPatcher {
+ // MARK: - Targets
+
+ /// Which of the two patch families a site belongs to.
+ public enum Family: String, Sendable, CaseIterable {
+ case neutrinoStyleTransfer = "nu_styletransfer"
+ case avfAuthorization = "avf_authorization"
+
+ /// The image the family's symbols live in.
+ public var imagePath: String {
+ switch self {
+ case .neutrinoStyleTransfer:
+ "/System/Library/PrivateFrameworks/NeutrinoCore.framework/NeutrinoCore"
+ case .avfAuthorization:
+ "/System/Library/PrivateFrameworks/AVFCapture.framework/AVFCapture"
+ }
+ }
+
+ /// The symbols the family rewrites, in the Python's order.
+ public var symbols: [String] {
+ switch self {
+ case .neutrinoStyleTransfer: DSCCameraPatcher.styleTransferSymbols
+ case .avfAuthorization: [DSCCameraPatcher.authorizationStatusSymbol]
+ }
+ }
+
+ /// The `w0` value the rewritten method returns.
+ ///
+ /// `0` is `NO` — the style-transfer processors report "did not
+ /// process". `3` is `AVAuthorizationStatusAuthorized`.
+ public var returnValue: UInt16 {
+ switch self {
+ case .neutrinoStyleTransfer: 0
+ case .avfAuthorization: 3
+ }
+ }
+
+ var headline: String {
+ switch self {
+ case .neutrinoStyleTransfer:
+ "+[_NUStyleTransfer*Processor processWithInputs:...] → return NO"
+ case .avfAuthorization:
+ "+[AVCaptureDevice authorizationStatusForMediaType:] → return Authorized"
+ }
+ }
+ }
+
+ /// The five NeutrinoCore class methods, in the reference's order.
+ public static let styleTransferSymbols: [String] = [
+ "+[_NUStyleTransferProcessor processWithInputs:arguments:output:error:]",
+ "+[_NUStyleTransferThumbnailProcessor processWithInputs:arguments:output:error:]",
+ "+[_NUStyleTransferApplyProcessor processWithInputs:arguments:output:error:]",
+ "+[_NUStyleTransferLearnProcessor processWithInputs:arguments:output:error:]",
+ "+[_NUStyleTransferInterpolateProcessor processWithInputs:arguments:output:error:]",
+ ]
+
+ /// The AVFCapture authorization entry point.
+ public static let authorizationStatusSymbol =
+ "+[AVCaptureDevice authorizationStatusForMediaType:]"
+
+ // MARK: - Results
+
+ /// One method entry point rewritten.
+ public struct Site: Sendable {
+ public let family: Family
+ public let symbol: String
+ /// `camera_dsc.<family>.<slug>` — the id `cfw_records.next_site` gives
+ /// the same write, so a capture taken either side of this port lines up.
+ public let patchID: String
+ public let vma: UInt64
+ public let originalBytes: Data
+ public let patchedBytes: Data
+ /// True when the entry point already held the replacement and the write
+ /// was inert. Never true on a pristine cache.
+ public let wasAlreadyPatched: Bool
+
+ public var patchDescription: String {
+ switch family {
+ case .neutrinoStyleTransfer:
+ "\(symbol) -> mov w0, #0; ret"
+ case .avfAuthorization:
+ "\(symbol) -> mov w0, #3 (AVAuthorizationStatusAuthorized); ret"
+ }
+ }
+ }
+
+ /// What one run of the patcher did.
+ public struct Result: Sendable {
+ /// Every entry point the run covered, in the order it covered them.
+ public let sites: [Site]
+ /// The re-attestation pass, or `nil` on a dry run, which does not write
+ /// and so has nothing to re-attest.
+ public let reattestation: DSCReattestation?
+ public let dryRun: Bool
+
+ public var siteCount: Int { sites.count }
+
+ /// True when every site was written and every page they dirtied now
+ /// carries a matching slot hash. A dry run is never complete.
+ public var isComplete: Bool {
+ !dryRun && (reattestation?.isFullyAttested ?? false)
+ }
+ }
+
+ // MARK: - Entry points
+
+ /// Where diagnostics go when the caller does not say. The Python prints its
+ /// progress to stdout and `cfw_install_exp.sh` logs it, so silence is not
+ /// the default here either.
+ public static let stdoutLog: @Sendable (String) -> Void = { print($0) }
+
+ /// Apply both families — the `cfw.py patch-camera-dsc` path.
+ ///
+ /// - Parameters:
+ /// - chunksDirectory: the directory of `dyld_shared_cache_arm64e*` files.
+ /// - symbolCacheURL: the unsuffixed chunk symbols are resolved against.
+ /// Defaults to the one inside `chunksDirectory`, which is what every
+ /// caller passes; the Python takes it separately only because `ipsw`
+ /// wants a file.
+ /// - dryRun: report the sites and write nothing.
+ /// - force: accept an entry point whose prologue is neither `pacibsp` nor
+ /// the replacement. The Python's `--force`.
+ @discardableResult
+ public static func applyAll(
+ chunksDirectory: URL,
+ symbolCacheURL: URL? = nil,
+ dryRun: Bool = false,
+ force: Bool = false,
+ log: ((String) -> Void)? = stdoutLog
+ ) throws -> Result {
+ try apply(
+ families: Family.allCases,
+ chunksDirectory: chunksDirectory,
+ symbolCacheURL: symbolCacheURL,
+ dryRun: dryRun,
+ force: force,
+ log: log
+ )
+ }
+
+ /// Apply only the AVFCapture authorization gate — the Python's
+ /// `--avf-only`, for a chunk pulled off a device that already carries the
+ /// NeutrinoCore short-circuits.
+ @discardableResult
+ public static func applyAVFAuthorizationOnly(
+ chunksDirectory: URL,
+ symbolCacheURL: URL? = nil,
+ dryRun: Bool = false,
+ force: Bool = false,
+ log: ((String) -> Void)? = stdoutLog
+ ) throws -> Result {
+ try apply(
+ families: [.avfAuthorization],
+ chunksDirectory: chunksDirectory,
+ symbolCacheURL: symbolCacheURL,
+ dryRun: dryRun,
+ force: force,
+ log: log
+ )
+ }
+
+ // MARK: - The run
+
+ static func apply(
+ families: [Family],
+ chunksDirectory: URL,
+ symbolCacheURL: URL?,
+ dryRun: Bool,
+ force: Bool,
+ log: ((String) -> Void)?
+ ) throws -> Result {
+ let chunks = try DSCChunkSet(directory: chunksDirectory)
+ let resolver = try DSCSymbolResolver(
+ mainCacheURL: symbolCacheURL ?? chunks.mainCacheURL
+ )
+ // Every symbol here is an ObjC class method, and those live only in the
+ // stripped local-symbol table. Without it the six lookups would each
+ // report "not found", which reads as "this build renamed them".
+ try resolver.requireLocalSymbols()
+
+ let disassembler = ARM64Disassembler()
+ var sites: [Site] = []
+
+ // Plan every family before writing any of them. Nothing in this loop
+ // touches the cache.
+ //
+ // This used to write each site as it was classified, with one
+ // re-attestation pass after the last family. Anything that threw after
+ // the first write — a renamed AVF symbol, a prologue that is neither
+ // `pacibsp` nor `mov w0,#3; ret` — left the NeutrinoCore sites on disk
+ // with their code-signature slot hashes still describing the old bytes.
+ // On `codeSigningMonitor == 2` hardware TXM checks those hashes per
+ // page, so that cache SIGKILLs on the first demand-page-in of a
+ // modified page: a half-patched cache that also fails to load.
+ // Reproduced on two identical clones by nop-ing only the AVF entry
+ // point — both patchers throw, but the old Swift left four pages of
+ // `dyld_shared_cache_arm64e.15` stale where the Python left none.
+ //
+ // The Python avoids it by resolving both families up front and
+ // re-attesting after each one. Planning everything first is stronger:
+ // a failure here leaves the cache untouched rather than patched and
+ // re-signed up to the failure point.
+ for (index, family) in families.enumerated() {
+ log?("")
+ log?(" [\(index + 1)/\(families.count)] \(family.headline)")
+
+ let replacement = try replacement(returning: family.returnValue)
+ log?(" resolving \(family.symbols.count) symbol(s) in \(family.imagePath)")
+ let addresses = try resolver.addresses(
+ of: family.symbols,
+ inImage: family.imagePath
+ )
+
+ // Sorted by symbol, as the Python's `sorted(vmas.items())` is. Only
+ // the report order depends on it — the bytes do not.
+ for symbol in addresses.keys.sorted() {
+ // `addresses` is keyed by the names just asked for, so the
+ // lookup cannot miss; `addresses(of:inImage:)` throws first.
+ guard let vma = addresses[symbol] else { continue }
+ let original = try chunks.bytesAtVMA(vma, length: replacement.count)
+
+ log?(" \(symbol) @ 0x\(String(vma, radix: 16, uppercase: true))")
+ log?(" \(original.hex) → \(replacement.hex)")
+
+ let alreadyPatched = try classifyPrologue(
+ original,
+ at: vma,
+ symbol: symbol,
+ returning: family.returnValue,
+ disassembler: disassembler,
+ force: force,
+ log: log
+ )
+
+ sites.append(
+ Site(
+ family: family,
+ symbol: symbol,
+ patchID: "camera_dsc.\(family.rawValue).\(symbolSlug(symbol))",
+ vma: vma,
+ originalBytes: original,
+ patchedBytes: replacement,
+ wasAlreadyPatched: alreadyPatched
+ )
+ )
+ }
+ }
+
+ guard !dryRun else {
+ log?(" [DRY RUN] \(sites.count) site(s) would be written")
+ return Result(sites: sites, reattestation: nil, dryRun: true)
+ }
+
+ // Commit. Every fallible step is behind us, so the only thing between
+ // the first write and the re-attestation below is more writes.
+ for site in sites {
+ try chunks.write(at: site.vma, site.patchedBytes)
+ }
+
+ // One pass, off the spans the writes recorded. Nothing has to tell it
+ // which addresses were touched, so nothing can under-attest.
+ let reattestation = try DSCCodeSignature.reattestRecordedWrites(
+ in: chunks,
+ log: log
+ )
+ log?(" re-attested \(reattestation.pagesAttested) page(s)")
+
+ // Read the bytes back through the chunk set rather than trusting the
+ // write: a site that landed in the wrong chunk would otherwise only
+ // show up as a page fault in the guest.
+ for site in sites {
+ let written = try chunks.bytesAtVMA(site.vma, length: site.patchedBytes.count)
+ guard written == site.patchedBytes else {
+ throw PatcherError.patchVerificationFailed(
+ "post-write verify failed at 0x\(String(site.vma, radix: 16, uppercase: true)): "
+ + "read back \(written.hex), expected \(site.patchedBytes.hex)"
+ )
+ }
+ }
+
+ log?("")
+ log?(" [+] camera DSC patches applied: \(families.count)/\(families.count), "
+ + "\(sites.count) site(s)")
+ return Result(sites: sites, reattestation: reattestation, dryRun: false)
+ }
+
+ // MARK: - The replacement
+
+ /// `mov w0, #<value>; ret`, both halves from the Keystone-checked encoders.
+ static func replacement(returning value: UInt16) throws -> Data {
+ guard let mov = ARM64Encoder.encodeMovzW(rd: 0, imm16: value) else {
+ throw PatcherError.patchVerificationFailed("could not encode mov w0, #\(value)")
+ }
+ let bytes = mov + ARM64.ret
+ guard bytes.count == 8 else {
+ throw PatcherError.patchVerificationFailed("expected 8 bytes, got \(bytes.count)")
+ }
+ return bytes
+ }
+
+ // MARK: - The prologue
+
+ /// Decide whether an entry point may be rewritten, and whether it already was.
+ ///
+ /// Three shapes are acceptable, and the difference matters:
+ ///
+ /// * `pacibsp` — a pristine signed-prologue method. The expected case, and
+ /// the only one the Python accepts without `--force`.
+ /// * the replacement itself — this patcher's own output, so the run is a
+ /// re-install. Reported, rewritten inertly, and re-attested, rather than
+ /// raising the way three sibling DSC patchers used to on their own work.
+ /// * anything at all, under `force`.
+ ///
+ /// - Returns: true when the entry point already held the replacement.
+ static func classifyPrologue(
+ _ bytes: Data,
+ at vma: UInt64,
+ symbol: String,
+ returning value: UInt16,
+ disassembler: ARM64Disassembler,
+ force: Bool,
+ log: ((String) -> Void)?
+ ) throws -> Bool {
+ let decoded = disassembler.disassemble(bytes, at: vma, count: 2)
+
+ if decoded.first?.mnemonic == "pacibsp" { return false }
+
+ if isReturnConstantShape(decoded, returning: value, disassembler: disassembler) {
+ log?(" [=] already `mov w0, #\(value); ret` — re-install, rewriting inertly")
+ return true
+ }
+
+ guard force else {
+ let head = decoded.first
+ .map { "\($0.mnemonic) \($0.operandString)".trimmingCharacters(in: .whitespaces) }
+ ?? "<undecodable>"
+ throw PatcherError.patchVerificationFailed(
+ "\(symbol) @ 0x\(String(vma, radix: 16, uppercase: true)): prologue is not "
+ + "pacibsp (got \(head), bytes \(bytes.prefix(4).hex)); pass force to override"
+ )
+ }
+ log?(" [!] prologue is not pacibsp — forced")
+ return false
+ }
+
+ /// Is this decode `mov w0, #<value>; ret`?
+ ///
+ /// Matched on the decode, not on the bytes: the question is "does this
+ /// method already return that constant", and a byte comparison would answer
+ /// a narrower one that only happens to coincide. `movz` is accepted
+ /// alongside its `mov` alias so the answer does not depend on which of the
+ /// two Capstone prints.
+ static func isReturnConstantShape(
+ _ decoded: [Instruction],
+ returning value: UInt16,
+ disassembler: ARM64Disassembler
+ ) -> Bool {
+ guard decoded.count == 2,
+ decoded[1].mnemonic == "ret",
+ decoded[0].mnemonic == "mov" || decoded[0].mnemonic == "movz",
+ let operands = decoded[0].aarch64?.operands,
+ operands.count == 2,
+ operands[0].type == AARCH64_OP_REG,
+ operands[1].type == AARCH64_OP_IMM,
+ disassembler.firstRegisterName(decoded[0]) == "w0"
+ else { return false }
+ return operands[1].imm == Int64(value)
+ }
+
+ // MARK: - Patch ids
+
+ /// `cfw_patch_camera_dsc._sym_slug` — every run of non-alphanumerics
+ /// becomes one underscore, and the ends are trimmed.
+ static func symbolSlug(_ symbol: String) -> String {
+ var slug = ""
+ var pendingSeparator = false
+ for character in symbol {
+ if character.isASCII, character.isLetter || character.isNumber {
+ if pendingSeparator, !slug.isEmpty { slug.append("_") }
+ pendingSeparator = false
+ slug.append(character)
+ } else {
+ pendingSeparator = true
+ }
+ }
+ return slug
+ }
+}
diff --git a/sources/FirmwarePatcher/DSC/Patchers/DSCHVVMMPatcher.swift b/sources/FirmwarePatcher/DSC/Patchers/DSCHVVMMPatcher.swift
new file mode 100644
index 00000000..7ee0a24f
--- /dev/null
+++ b/sources/FirmwarePatcher/DSC/Patchers/DSCHVVMMPatcher.swift
@@ -0,0 +1,707 @@
+// DSCHVVMMPatcher.swift — the `kern.hv_vmm_present` user-mode cstring mangle.
+//
+// Port of BOTH `scripts/patchers/cfw_patch_hv_vmm_dsc.py` (the DSC orchestrator)
+// and `scripts/patchers/cfw_patch_hv_vmm.py` (the cstring definition and the
+// standalone-Mach-O patcher it exports). The two are one patch, split across two
+// files only because Python needed somewhere to keep the shared constants: the
+// DSC module imports `NEEDLE` / `MANGLED_NEEDLE` / `MANGLE_OFFSET` /
+// `ORIGINAL_BYTE` / `MANGLED_BYTE` from the other one at import time. Porting the
+// orchestrator alone would have left this file restating those five values from
+// memory, with nothing tying them back to the module that defines them — so both
+// halves live here, in one type, and the constants have exactly one definition.
+//
+// What the patch is
+// -----------------
+// This is the user-mode half of the EXP blacklist-flip. The kernel half —
+// `KernelEXPPatcher.patchHvVmmRename`, in
+// `Kernel/EXPPatches/KernelEXPPatchHvVmmRename.swift` — renames the sysctl OID
+// from `hv_vmm_present` to `Xv_vmm_present`. After it:
+//
+// * `sysctlbyname("kern.hv_vmm_present", …)` returns ENOENT, and the canonical
+// defensive post-call check (`cbnz w0, skip`) leaves the caller's cached
+// `is_vmm` byte at its BSS zero. The caller concludes it is NOT in a VM.
+// * `sysctlbyname("kern.Xv_vmm_present", …)` returns 1 — the OID's real int
+// value, because this device really is a VM. The caller concludes it IS in a
+// VM, exactly as it would on stock.
+//
+// So which answer a dylib gets is decided entirely by which name its cstring
+// asks for, and this patcher decides that per dylib: flip byte 5 of
+// `"kern.hv_vmm_present\0"` from `'h'` to `'X'` and the dylib sees 1; leave it
+// alone and the dylib sees ENOENT and caches 0.
+//
+// Byte 5 and not byte 0
+// ---------------------
+// Byte 5 is the first byte after the `kern.` namespace prefix. Mangling byte 0
+// would produce `Xern.hv_vmm_present`, which can never resolve, because `Xern`
+// is not a registered top-level sysctl namespace — the name-to-MIB walk fails
+// before it ever reaches an OID. Keeping `kern.` intact is what lets the mangled
+// name route to the renamed OID.
+//
+// Blacklist semantics — the list names what stays ORIGINAL
+// --------------------------------------------------------
+// `dontPatchInstallNames` holds the dylibs that must believe they are on real
+// hardware: identity, activation, anti-abuse, store, and the consumer services
+// that refuse to sign in from a VM. Those keep the pristine cstring.
+//
+// Every OTHER dylib carrying the cstring gets the mangle, which is what keeps
+// the graphics path (libMobileGestalt, CoreVideo, PhotoFoundation,
+// AirPlaySupport, VisionKitCore) and the compute/accel fast paths (CoreML,
+// Espresso, AppleNeuralEngine, caulk, IOSurfaceAccelerator) on the answer they
+// were written against. A lib that thinks it is on bare metal when it is not
+// will try to talk to silicon that is not there.
+//
+// TXM and the page hashes
+// -----------------------
+// On `codeSigningMonitor == 2` hardware the mangled byte is not enough on its
+// own: TXM holds the SHA-256 slot hash the page was registered with, and the
+// first process to demand-page that 16 KiB page dies with
+// `KERN_PROTECTION_FAILURE` / `CODESIGNING / Invalid Page`. Every site written
+// here is therefore followed by `DSCCodeSignature`, which re-hashes the pages
+// that were actually dirtied. This patcher never names those pages itself —
+// `DSCChunkSet` records each write and the re-attestation pass consumes the
+// record, so a site cannot be written and left unattested.
+//
+// One deliberate divergence from the reference
+// --------------------------------------------
+// `cfw_patch_hv_vmm_dsc.py` queues the address of the cstring's FIRST byte for
+// re-attestation, although the byte it wrote is five bytes further on. The two
+// are in the same 16 KiB page for all 44 occurrences on the 24A435 arm64e cache,
+// so the reference is right there by margin — but a cstring whose first byte
+// falls in the last five bytes of a page would have the wrong page re-hashed and
+// the patched one left stale, reported as success. Here the span comes from the
+// write itself, so it is the page that changed by construction.
+
+import Foundation
+
+/// The user-mode `kern.hv_vmm_present` cstring mangle, over a chunked dyld
+/// shared cache and over standalone Mach-Os.
+public enum DSCHVVMMPatcher {
+ // MARK: - The cstring and its mangle
+ //
+ // Port of the five constants `cfw_patch_hv_vmm.py` exports. They are derived
+ // from the sysctl name rather than written out as bytes, so "byte 5" is the
+ // length of the namespace prefix and cannot drift away from it.
+
+ /// The top-level sysctl namespace the name lives under. Preserved by the
+ /// mangle — see the file comment.
+ public static let sysctlNamespace = "kern."
+
+ /// The OID's own name, as userland spells it.
+ public static let sysctlOIDName = "hv_vmm_present"
+
+ /// `"kern.hv_vmm_present\0"` — the pristine cstring, NUL included, because a
+ /// match has to cover the terminator to be the whole literal.
+ public static let needle = Data((sysctlNamespace + sysctlOIDName + "\0").utf8)
+
+ /// Index of the mangled byte within ``needle``: the first byte after
+ /// `kern.`, which is the `'h'` of `hv_vmm_present`.
+ public static let mangleOffset = sysctlNamespace.utf8.count
+
+ /// What that byte is before the patch.
+ public static let originalByte = UInt8(ascii: "h")
+
+ /// What it becomes — the same letter `KernelEXPPatchHvVmmRename` renames the
+ /// OID to, which is the only reason the mangled name resolves at all.
+ public static let mangledByte = UInt8(ascii: "X")
+
+ /// `"kern.Xv_vmm_present\0"` — what a patched site reads as.
+ public static let mangledNeedle: Data = {
+ var mangled = needle
+ mangled[mangled.startIndex + mangleOffset] = mangledByte
+ return mangled
+ }()
+
+ /// Mach-O sections a cstring literal can live in.
+ ///
+ /// `__cstring` is where the linker puts unique C string literals. The ObjC
+ /// name pools could in principle hold the same bytes, and the reference
+ /// scans them too, so this does as well.
+ static let cstringSectionNames: Set<String> = [
+ "__cstring", "__objc_methname", "__objc_classname",
+ ]
+
+ // MARK: - Blacklist
+ //
+ // A dylib named here keeps `"kern.hv_vmm_present\0"`. With the kernel rename
+ // in place that name is ENOENT, the dylib's defensive check takes the skip
+ // path, its cached `is_vmm` byte stays at BSS zero, and it concludes the
+ // device is not a VM.
+ //
+ // A dylib NOT named here is mangled to `"kern.Xv_vmm_present\0"`, resolves to
+ // the renamed OID, reads 1, and concludes the device is a VM — the same
+ // answer it would get on stock hardware.
+ //
+ // Commenting out a single line moves that dylib OUT of the blacklist and
+ // back into the patched set, which is how you bisect which consumer
+ // regressed an observable. The grouping is for the reader; order does not
+ // affect what is patched.
+
+ /// The dylibs that stay unpatched, by `LC_ID_DYLIB` install name.
+ public static let dontPatchInstallNames: [String] = [
+ // ── Identity / activation / anti-abuse.
+ "/System/Library/PrivateFrameworks/AAAFoundation.framework/AAAFoundation",
+ "/System/Library/PrivateFrameworks/AuthKit.framework/AuthKit",
+ "/System/Library/PrivateFrameworks/IDSFoundation.framework/IDSFoundation",
+ "/System/Library/PrivateFrameworks/DeviceIdentity.framework/DeviceIdentity",
+ "/System/Library/PrivateFrameworks/DeviceCheckInternal.framework/DeviceCheckInternal",
+ "/System/Library/PrivateFrameworks/MobileActivation.framework/MobileActivation",
+ "/System/Library/PrivateFrameworks/ApplePushService.framework/ApplePushService",
+
+ // ── Store / IAP.
+ "/System/Library/PrivateFrameworks/AppStoreUtilities.framework/AppStoreUtilities",
+
+ // ── Consumer services.
+ "/System/Library/PrivateFrameworks/CorePrescription.framework/CorePrescription",
+ "/System/Library/PrivateFrameworks/CoreCDP.framework/CoreCDP",
+ "/System/Library/PrivateFrameworks/EmailFoundation.framework/EmailFoundation",
+ "/System/Library/PrivateFrameworks/FindMyBase.framework/FindMyBase",
+ "/System/Library/PrivateFrameworks/TrialServer.framework/TrialServer",
+ "/System/Library/PrivateFrameworks/DVTInstrumentsUtilities.framework/DVTInstrumentsUtilities",
+ "/System/Library/PrivateFrameworks/WatchdogServiceManagement.framework/WatchdogServiceManagement",
+ ]
+
+ /// Set form, for the per-site membership test.
+ public static let dontPatchSet = Set(dontPatchInstallNames)
+
+ /// What a site with no resolvable install name is called in the result map,
+ /// matching the reference's `"<unknown dylib>"`.
+ public static let unknownDylibLabel = "<unknown dylib>"
+
+ // MARK: - Result
+
+ /// What one DSC run did, site by site and in total.
+ ///
+ /// `mangledCountByInstallName` is the reference's return value: every dylib
+ /// the scan reached, mapped to how many of its cstring sites this run
+ /// mangled. A blacklisted, unclassified or already-mangled dylib appears
+ /// with a count of zero, which is how the caller can tell "seen and left
+ /// alone" from "never seen".
+ public struct Result: Sendable {
+ /// Occurrences of the pristine cstring found in executable mappings.
+ public let pristineSiteCount: Int
+ /// Occurrences of the already-mangled cstring found alongside them.
+ public let alreadyMangledSiteCount: Int
+ /// Per-dylib count of sites this run mangled.
+ public let mangledCountByInstallName: [String: Int]
+ /// Sites mangled (or, on a dry run, that would have been).
+ public let mangled: Int
+ /// Sites left pristine because their dylib is blacklisted.
+ public let skippedInBlacklist: Int
+ /// Sites whose containing dylib could not be named, so were not touched.
+ public let skippedUnclassified: Int
+ /// Sites refused: unreadable, or bytes that are neither form.
+ public let refused: Int
+ /// Already-mangled sites queued only so their page hash is brought back
+ /// into sync.
+ public let reattestOnly: Int
+ /// Blacklisted dylibs found already mangled on disk — an out-of-band
+ /// edit, reported loudly and re-attested rather than reverted.
+ public let blacklistDrift: Int
+ /// The re-attestation pass, or `nil` when there were no pages to cover.
+ public let reattestation: DSCReattestation?
+
+ /// True when nothing was left in a state the guest would fault on: every
+ /// page this run touched carries a slot hash that matches its bytes.
+ public var isFullyAttested: Bool {
+ reattestation?.isFullyAttested ?? true
+ }
+
+ static let empty = Result(
+ pristineSiteCount: 0,
+ alreadyMangledSiteCount: 0,
+ mangledCountByInstallName: [:],
+ mangled: 0,
+ skippedInBlacklist: 0,
+ skippedUnclassified: 0,
+ refused: 0,
+ reattestOnly: 0,
+ blacklistDrift: 0,
+ reattestation: nil
+ )
+ }
+
+ // MARK: - The DSC patch
+
+ /// Apply the blacklist-flip mangle to the cache under `chunksDirectory`.
+ ///
+ /// This is `cfw.py patch-hv-vmm-dsc <chunks_dir> [--dry-run]`, which
+ /// `scripts/patch_hv_vmm_userland.sh dsc` wraps and `cfw_install_exp.sh`
+ /// calls while the SystemOS cryptex is still mounted on the host.
+ @discardableResult
+ public static func patch(
+ chunksDirectory: URL,
+ dryRun: Bool = false,
+ log: ((String) -> Void)? = DSCCodeSignature.stderrLog
+ ) throws -> Result {
+ let chunks = try DSCChunkSet(directory: chunksDirectory)
+ log?(
+ " [.] \(chunksDirectory.path): \(chunks.chunkURLs.count) chunk(s), "
+ + "\(chunks.mappings.count) mapping(s), "
+ + "vm 0x\(hex(chunks.addressRange.lowerBound))"
+ + "..0x\(hex(chunks.addressRange.upperBound))"
+ )
+ return try patch(in: chunks, dryRun: dryRun, log: log)
+ }
+
+ /// Apply the mangle to an already-open cache.
+ ///
+ /// Split out so a caller that has other DSC work to do on the same chunk set
+ /// can share it, and so tests can inspect the chunk set afterwards.
+ ///
+ /// A shared chunk set's earlier writes are re-attested along with this
+ /// patch's, since the re-attestation pass reads the set's whole write log. A
+ /// page whose slot is already correct is skipped, so that costs one hash and
+ /// never the wrong answer — and the alternative, filtering the log down to
+ /// this patch's own spans, is how a page ends up written and unattested.
+ @discardableResult
+ public static func patch(
+ in chunks: DSCChunkSet,
+ dryRun: Bool = false,
+ log: ((String) -> Void)? = DSCCodeSignature.stderrLog
+ ) throws -> Result {
+ log?(" [.] locating cstring \"kern.hv_vmm_present\\0\"…")
+ let pristineSites = try chunks.findStringVMAs(needle).sorted()
+ // Sites a previous run already mangled. Nothing is written for these,
+ // but their pages still have to join the re-attestation set: a re-run
+ // over a cache patched by an older pass (or by the Python) has to leave
+ // the slot hashes in sync with the bytes on disk.
+ let alreadyMangledSites = try chunks.findStringVMAs(mangledNeedle).sorted()
+
+ guard !pristineSites.isEmpty || !alreadyMangledSites.isEmpty else {
+ log?(
+ " [-] cstring not present in any executable mapping; nothing to "
+ + "do (either patched already or absent)"
+ )
+ return .empty
+ }
+ log?(
+ " [.] \(pristineSites.count) pristine + \(alreadyMangledSites.count) "
+ + "already-mangled cstring occurrence(s) found"
+ )
+ log?(
+ " [.] resolving containing dylib for each occurrence (blacklist has "
+ + "\(dontPatchSet.count) entries — these stay unpatched)…"
+ )
+
+ var mangledCountByInstallName: [String: Int] = [:]
+ var mangled = 0
+ var skippedInBlacklist = 0
+ var skippedUnclassified = 0
+ var refused = 0
+ // Stand-ins for the writes, used on a dry run where `DSCChunkSet` has no
+ // record because nothing was written. On a live run the record is the
+ // authority and these are not consulted.
+ var plannedSpans: [DSCWriteSpan] = []
+ // Pages that need re-hashing although this run wrote nothing to them.
+ var reattestOnlySpans: [DSCWriteSpan] = []
+
+ for vma in pristineSites {
+ let installName = classify(vma, in: chunks)
+ let label = installName ?? unknownDylibLabel
+
+ guard let installName else {
+ // An unnamed dylib is not in the blacklist, so it would normally
+ // be patched. Refuse it instead: a site nobody can audit is not
+ // a site worth flipping.
+ log?(" [.] SKIP (no install name resolvable) string@0x\(hex(vma))")
+ skippedUnclassified += 1
+ note(label, in: &mangledCountByInstallName)
+ continue
+ }
+
+ if dontPatchSet.contains(installName) {
+ log?(
+ " [.] SKIP (blacklisted — stays unpatched, will hit "
+ + "ENOENT): \(installName) string@0x\(hex(vma))"
+ )
+ skippedInBlacklist += 1
+ note(label, in: &mangledCountByInstallName)
+ continue
+ }
+
+ // The bytes have to still look like the cstring we matched.
+ let current: Data
+ do {
+ current = try chunks.bytesAtVMA(vma, length: needle.count)
+ } catch {
+ log?(" [-] read failed at 0x\(hex(vma)): \(error)")
+ refused += 1
+ continue
+ }
+
+ if current[current.startIndex + mangleOffset] == mangledByte {
+ // Mangled by an earlier run. Nothing to write; the second pass
+ // below picks the page up through `alreadyMangledSites`.
+ log?(
+ " [.] already mangled at byte \(mangleOffset): \(label) "
+ + "string@0x\(hex(vma))"
+ )
+ note(label, in: &mangledCountByInstallName)
+ continue
+ }
+ guard current == needle else {
+ log?(
+ " [-] unexpected bytes at 0x\(hex(vma)) (\(current.hex)); "
+ + "refusing (\(label))"
+ )
+ refused += 1
+ continue
+ }
+
+ let writeVMA = vma &+ UInt64(mangleOffset)
+ if dryRun {
+ plannedSpans.append(DSCWriteSpan.byte(at: writeVMA))
+ } else {
+ try chunks.write(at: writeVMA, Data([mangledByte]))
+ }
+ log?(
+ " [+] \(dryRun ? "would mangle" : "mangled") \(label) "
+ + "string@0x\(hex(vma)) byte \(mangleOffset) "
+ + "(\(Character(UnicodeScalar(originalByte))) -> "
+ + "\(Character(UnicodeScalar(mangledByte)))) now queries "
+ + "kern.Xv_vmm_present, will see 1 (in a VM)"
+ )
+ mangledCountByInstallName[label, default: 0] += 1
+ mangled += 1
+ }
+
+ // Second pass: cstrings a previous run already mangled. Their pages join
+ // the re-attestation set so a re-run brings the slot hashes back into
+ // sync with what is on disk.
+ //
+ // A mangled cstring inside a BLACKLISTED dylib is deliberately not
+ // refused. It means someone took that dylib out of the blacklist, ran
+ // the patch, and put it back — an out-of-band action this code cannot
+ // undo safely, since reverting the byte would leave the page hash right
+ // and the operator's intent wrong. It is reported loudly and the page is
+ // re-attested to the bytes that are actually there.
+ var reattestOnly = 0
+ var blacklistDrift = 0
+ for vma in alreadyMangledSites {
+ guard let installName = classify(vma, in: chunks) else { continue }
+ // The whole cstring, not just the mangled byte: nothing was written
+ // this run, so there is no write span to inherit, and a literal that
+ // straddles a page boundary needs both of its pages.
+ let span = DSCWriteSpan(vma: vma, length: needle.count)
+ if dontPatchSet.contains(installName) {
+ log?(
+ " [!] drift: \(installName) is in the blacklist but "
+ + "already mangled at string@0x\(hex(vma)) — slot will be "
+ + "re-attested to current bytes; consider whether you "
+ + "actually want this dylib re-patched"
+ )
+ reattestOnlySpans.append(span)
+ blacklistDrift += 1
+ continue
+ }
+ reattestOnlySpans.append(span)
+ reattestOnly += 1
+ }
+ if reattestOnly > 0 {
+ log?(
+ " [.] also queueing \(reattestOnly) already-mangled cstring "
+ + "page(s) for re-attestation"
+ )
+ }
+ if blacklistDrift > 0 {
+ log?(
+ " [.] \(blacklistDrift) blacklisted dylib(s) found mangled on "
+ + "disk — see drift warnings above"
+ )
+ }
+
+ // Page-hash re-attestation. On `codeSigningMonitor == 2` hardware TXM
+ // holds the slot hashes the cache was registered with, so a mangled byte
+ // without a re-hash is a SIGKILL on the first demand-page-in of that
+ // page, with nothing pointing back at this patch. The CD blob's own
+ // cdHash changes as a side effect; that is survivable only because the
+ // JB kernel patch `KernelJBPatchAmfiTrustcache` short-circuits AMFI's
+ // per-image trust-cache lookup.
+ //
+ // The write spans come from `DSCChunkSet` itself rather than from a list
+ // this function keeps, so a site cannot be written and left out.
+ let spans = (dryRun ? plannedSpans : chunks.recordedWrites) + reattestOnlySpans
+ var reattestation: DSCReattestation?
+ if !spans.isEmpty {
+ log?(
+ " [.] \(dryRun ? "dry-run: would re-attest" : "re-attesting") "
+ + "\(spans.count) modified page span(s)…"
+ )
+ reattestation = try DSCCodeSignature.reattest(
+ in: chunks,
+ modifiedSpans: spans,
+ dryRun: dryRun,
+ log: log
+ )
+ }
+
+ log?(
+ " [+] DSC patch complete: \(mangled) cstring(s) mangled, "
+ + "\(skippedInBlacklist) in-blacklist (left unpatched), "
+ + "\(skippedUnclassified) unclassified, \(refused) refused/error"
+ )
+ return Result(
+ pristineSiteCount: pristineSites.count,
+ alreadyMangledSiteCount: alreadyMangledSites.count,
+ mangledCountByInstallName: mangledCountByInstallName,
+ mangled: mangled,
+ skippedInBlacklist: skippedInBlacklist,
+ skippedUnclassified: skippedUnclassified,
+ refused: refused,
+ reattestOnly: reattestOnly,
+ blacklistDrift: blacklistDrift,
+ reattestation: reattestation
+ )
+ }
+
+ /// Name the dylib that contains `vma`, by walking back to its Mach-O header
+ /// and reading `LC_ID_DYLIB`.
+ ///
+ /// `nil` covers both "no header found" and "the walk-back threw", which is
+ /// what the reference's blanket `except Exception` does: a site whose dylib
+ /// cannot be named is left alone either way, so the two cases lead to the
+ /// same place.
+ static func classify(_ vma: UInt64, in chunks: DSCChunkSet) -> String? {
+ let headerVMA: UInt64?
+ do {
+ headerVMA = try chunks.findMachOHeaderBefore(vma)
+ } catch {
+ return nil
+ }
+ guard let headerVMA else { return nil }
+ return chunks.readInstallName(atHeaderVMA: headerVMA)
+ }
+
+ /// Put `label` in the per-dylib map at zero if it is not there yet.
+ ///
+ /// A dylib the scan reached but did not patch still belongs in the result,
+ /// with a count of zero — that is what separates "seen and deliberately left
+ /// alone" from "never seen", and the reference's `results.get(label, 0)`
+ /// spelling of it is easy to mistake for a no-op.
+ private static func note(_ label: String, in counts: inout [String: Int]) {
+ if counts[label] == nil { counts[label] = 0 }
+ }
+
+ // MARK: - Standalone Mach-O
+ //
+ // The other half of `cfw_patch_hv_vmm.py`: the same mangle applied to a
+ // Mach-O on disk rather than to a dylib inside the cache. No caller in this
+ // repo reaches it today — `patch_hv_vmm_userland.sh` lost its `standalone`
+ // op when the rootfs patcher was removed, and the one standalone binary that
+ // still carries its own copy of the cstring (`watchdogd`) is handled by a
+ // dedicated two-instruction patch instead. It is here because it is the rest
+ // of the module this file ports, it is the only way to check the cstring
+ // definition above against a real Mach-O, and the EXP rootfs list in
+ // `research/0_binary_patch_comparison.md` still names six files it applies
+ // to.
+
+ /// One occurrence of the pristine cstring in a standalone Mach-O.
+ public struct MachOStringSite: Sendable, Equatable {
+ /// Address the literal is mapped at.
+ public let stringVMA: UInt64
+ /// Offset of the literal in the file.
+ public let fileOffset: Int
+ /// `"segment,section"` it was found in.
+ public let section: String
+ }
+
+ /// Every pristine `"kern.hv_vmm_present\0"` in `data`'s string sections.
+ ///
+ /// Hits are anchored at a cstring boundary — the start of the section, or
+ /// just after a NUL — so the tail of some longer literal that happens to end
+ /// in these bytes is not returned.
+ ///
+ /// - Throws: ``PatcherError/invalidFormat(_:)`` when `data` is not a 64-bit
+ /// little-endian Mach-O. A fat binary has to be sliced first.
+ public static func findStringSites(inMachO data: Data) throws -> [MachOStringSite] {
+ let image = data.startIndex == 0 ? data : Data(data)
+ var sites: [MachOStringSite] = []
+ for (name, section) in try machOSections(of: image)
+ where cstringSectionNames.contains(section.sectionName)
+ {
+ let start = Int(section.fileOffset)
+ let end = start + Int(section.size)
+ guard start >= 0, end <= image.count, start <= end else { continue }
+ let buffer = image[start ..< end]
+
+ var searchFrom = buffer.startIndex
+ while searchFrom < buffer.endIndex,
+ let found = buffer.range(of: needle, in: searchFrom ..< buffer.endIndex)
+ {
+ let position = found.lowerBound - buffer.startIndex
+ if position == 0 || buffer[buffer.startIndex + position - 1] == 0 {
+ sites.append(
+ MachOStringSite(
+ stringVMA: section.address &+ UInt64(position),
+ fileOffset: start + position,
+ section: name
+ )
+ )
+ }
+ searchFrom = found.lowerBound + 1
+ }
+ }
+ return sites
+ }
+
+ /// True when `data` holds the mangled form anywhere.
+ ///
+ /// Only for saying something useful in the log: ``findStringSites(inMachO:)``
+ /// already returns nothing for an already-patched binary, so the patch flow
+ /// is idempotent with or without this.
+ public static func isAlreadyMangled(_ data: Data) -> Bool {
+ data.range(of: mangledNeedle) != nil
+ }
+
+ /// Mangle every cstring site in the Mach-O at `url`.
+ ///
+ /// - Returns: how many sites were mangled. Idempotent: a second run finds
+ /// the pristine literal gone and returns 0.
+ @discardableResult
+ public static func patchStandaloneMachO(
+ at url: URL,
+ dryRun: Bool = false,
+ log: ((String) -> Void)? = DSCCodeSignature.stderrLog
+ ) throws -> Int {
+ guard FileManager.default.fileExists(atPath: url.path) else {
+ throw PatcherError.fileNotFound(url.path)
+ }
+ var data = try Data(contentsOf: url)
+ let sites = try findStringSites(inMachO: data)
+ guard !sites.isEmpty else {
+ if isAlreadyMangled(data) {
+ log?(
+ " [.] \(url.path): already mangled (no original "
+ + "'kern.hv_vmm_present' cstring present)"
+ )
+ } else {
+ log?(
+ " [.] \(url.path): 'kern.hv_vmm_present' cstring not "
+ + "present — nothing to do"
+ )
+ }
+ return 0
+ }
+
+ log?(" [+] \(sites.count) cstring occurrence(s) in \(url.path)")
+ var patched = 0
+ for site in sites {
+ let range = site.fileOffset ..< (site.fileOffset + needle.count)
+ guard range.upperBound <= data.count else { continue }
+ let original = data[range]
+ if original[original.startIndex + mangleOffset] == mangledByte {
+ log?(
+ " [.] string@0x\(hex(site.stringVMA)) already mangled "
+ + "(byte \(mangleOffset) is already "
+ + "'\(Character(UnicodeScalar(mangledByte)))')"
+ )
+ continue
+ }
+ guard original == needle else {
+ log?(
+ " [-] string@0x\(hex(site.stringVMA)) bytes look unexpected "
+ + "(\(Data(original).hex)); skipping"
+ )
+ continue
+ }
+ log?(
+ " patching string@0x\(hex(site.stringVMA)) (sect=\(site.section)): "
+ + "byte \(mangleOffset) "
+ + "'\(Character(UnicodeScalar(originalByte)))' -> "
+ + "'\(Character(UnicodeScalar(mangledByte)))' "
+ + "('kern.hv_vmm_present' -> 'kern.Xv_vmm_present')"
+ )
+ data[data.startIndex + site.fileOffset + mangleOffset] = mangledByte
+ patched += 1
+ }
+
+ if dryRun {
+ log?(" [.] dry-run — not writing back")
+ return patched
+ }
+ if patched > 0 {
+ try data.write(to: url)
+ log?(" [+] \(url.path): mangled \(patched) cstring occurrence(s)")
+ }
+ return patched
+ }
+
+ // MARK: - Minimal Mach-O section table
+
+ /// One `section_64`, reduced to what the string scan needs.
+ struct MachOSection {
+ let segmentName: String
+ let sectionName: String
+ let address: UInt64
+ let size: UInt64
+ let fileOffset: UInt32
+ }
+
+ /// `LC_SEGMENT_64` sections of a thin 64-bit Mach-O, as
+ /// `("segment,section", section)` pairs.
+ ///
+ /// Later sections with the same `"segment,section"` name replace earlier
+ /// ones while keeping the earlier one's position, which is what the
+ /// reference's dict does and is the only reason the two agree on the order
+ /// sites come back in.
+ static func machOSections(of data: Data) throws -> [(String, MachOSection)] {
+ guard data.count >= 32 else {
+ throw PatcherError.invalidFormat("truncated Mach-O header (\(data.count) bytes)")
+ }
+ let magic = data.loadLE(UInt32.self, at: 0)
+ guard magic == 0xFEED_FACF else {
+ throw PatcherError.invalidFormat(
+ "not a 64-bit Mach-O (magic=0x\(String(magic, radix: 16, uppercase: true)))"
+ )
+ }
+
+ let commandCount = Int(data.loadLE(UInt32.self, at: 16))
+ var ordered: [String] = []
+ var byName: [String: MachOSection] = [:]
+ var offset = 32
+ for _ in 0 ..< commandCount {
+ guard offset + 8 <= data.count else { break }
+ let command = data.loadLE(UInt32.self, at: offset)
+ let commandSize = Int(data.loadLE(UInt32.self, at: offset + 4))
+ guard commandSize >= 8, offset + commandSize <= data.count else { break }
+
+ if command == 0x19 { // LC_SEGMENT_64
+ let segmentName = fixedWidthName(data, at: offset + 8)
+ let sectionCount = Int(data.loadLE(UInt32.self, at: offset + 64))
+ var sectionOffset = offset + 72
+ for _ in 0 ..< sectionCount {
+ guard sectionOffset + 80 <= data.count else { break }
+ let sectionName = fixedWidthName(data, at: sectionOffset)
+ let key = "\(segmentName),\(sectionName)"
+ if byName[key] == nil { ordered.append(key) }
+ byName[key] = MachOSection(
+ segmentName: segmentName,
+ sectionName: sectionName,
+ address: data.loadLE(UInt64.self, at: sectionOffset + 32),
+ size: data.loadLE(UInt64.self, at: sectionOffset + 40),
+ fileOffset: data.loadLE(UInt32.self, at: sectionOffset + 48)
+ )
+ sectionOffset += 80
+ }
+ }
+ offset += commandSize
+ }
+ return ordered.compactMap { key in byName[key].map { (key, $0) } }
+ }
+
+ /// A 16-byte NUL-padded Mach-O name field.
+ private static func fixedWidthName(_ data: Data, at offset: Int) -> String {
+ let start = data.startIndex + offset
+ let end = min(start + 16, data.endIndex)
+ guard start < end else { return "" }
+ let field = data[start ..< end]
+ let terminated = field.prefix { $0 != 0 }
+ return String(decoding: terminated, as: UTF8.self)
+ }
+
+ // MARK: - Formatting
+
+ private static func hex(_ value: UInt64) -> String {
+ String(value, radix: 16, uppercase: true)
+ }
+}
diff --git a/sources/FirmwarePatcher/DSC/Patchers/DSCIOMFBForceKernPatcher.swift b/sources/FirmwarePatcher/DSC/Patchers/DSCIOMFBForceKernPatcher.swift
new file mode 100644
index 00000000..30536f4e
--- /dev/null
+++ b/sources/FirmwarePatcher/DSC/Patchers/DSCIOMFBForceKernPatcher.swift
@@ -0,0 +1,445 @@
+// DSCIOMFBForceKernPatcher.swift — Force IOMobileFramebuffer's present onto the
+// kernel (userclient method-5) path instead of the virt (in-process callback) one.
+//
+// Why
+// ---
+// On vphone600 26.x the host `VZVirtualMachineView` is fed by the guest
+// `AppleParavirtGPU` scanout, and the 26.4 kernel drives that scanout ONLY from
+// the IOMFB userclient swap methods — the `_kern_Swap*` family, of which
+// `_kern_SwapEnd` is external method 5. A 26.x userland presents through
+// `_kern_*`, which is why the SwapEnd size patch fixed the VZ view on 26.0/18.x.
+//
+// iOS 27 routes the paravirt display's present through the PARALLEL `_virt_Swap*`
+// family instead. `_virt_SwapEnd` performs no userclient call: it invokes an
+// in-process callback and hands the composited IOSurface to a virtual-display
+// consumer. Those frames never enter the kernel userclient, so the paravirt GPU
+// never scans out and the host VZ window stays black — the guest still
+// composites (the GUI is visible over the in-guest TrollVNC capturer) and
+// AppleParavirtGPU's scheduler sits idle.
+//
+// What is rewritten
+// -----------------
+// The public `_IOMobileFramebufferSwap*` entry points are thin dispatch
+// trampolines that tail-call a per-connection function pointer:
+//
+// cbz x0, <fail>
+// ldr xN, [x0, #<slot>] ; the connection's swap fp (kern or virt impl)
+// cbz xN, <fail>
+// braaz xN ; tail-call, all argument registers intact
+//
+// The FIRST instruction of each such trampoline becomes an unconditional
+// `b _kern_Swap<Name>`. Because the trampoline tail-calls with the argument
+// registers untouched, that is behaviourally identical to the connection having
+// selected the kern fp — every present call now routes through the kern/method-5
+// implementation regardless of how iOS 27 classified the display.
+//
+// Companion kernel patch: `KernelJBPatcher.patchIomfbSwapEndVariableSize` /
+// `…HandlerSize`, which make the 26.4 userclient accept iOS 27's native 0x6e0
+// SwapEnd struct (26.x sent 0x588). Both halves are required together — forcing
+// kern without the kernel size-accept makes method 5 return
+// `kIOReturnBadArgument`.
+//
+// Nothing is hardcoded. The public entry points and their `_kern_` counterparts
+// are resolved by NAME through `DSCSymbolResolver` (export trie plus the cache's
+// own `.symbols` table — no `ipsw` subprocess), the trampoline shape is verified
+// by Capstone decode of typed operands rather than operand text, the replacement
+// branch comes from `ARM64Encoder.encodeB`, and every DSC page the writes
+// dirtied is re-attested through the span log `DSCChunkSet` keeps.
+//
+// Port of `scripts/patchers/cfw_patch_iomfb_force_kern.py`, which stays the
+// independent reference — `DSCIOMFBForceKernTests` runs the Python on one clone
+// of the real cache and this on another, and compares the two byte for byte.
+//
+// One place diverges from the reference on purpose. The Python writes every site
+// first and only then checks that the three required entry points were covered,
+// so a cache missing one is left half-patched AND un-attested — the worst of the
+// three possible states, because an un-attested DSC page is a
+// `KERN_PROTECTION_FAILURE` on first demand-page-in rather than a visible
+// failure. Here the whole candidate set is classified before anything is
+// written, so that check happens while the cache is still untouched. On the
+// success path the bytes are identical.
+
+import Capstone
+import Foundation
+
+/// Retargets IOMobileFramebuffer's public swap trampolines at their `_kern_`
+/// implementations, inside a chunked dyld shared cache.
+public enum DSCIOMFBForceKernPatcher {
+ /// The image that carries both halves of every pair.
+ public static let imagePath =
+ "/System/Library/PrivateFrameworks/IOMobileFramebuffer.framework/IOMobileFramebuffer"
+
+ /// Prefix of the public entry points. Everything after it names the swap
+ /// operation: `_IOMobileFramebufferSwapEnd` → `End`.
+ public static let publicPrefix = "_IOMobileFramebufferSwap"
+
+ /// Prefix of the kernel-path siblings. `End` → `_kern_SwapEnd`.
+ public static let kernPrefix = "_kern_Swap"
+
+ /// The present transaction the render server drives. Discovery finds
+ /// whatever the cache has, but these three must come out covered or the
+ /// patch is not meaningful: a half-forced swap path is incoherent — some
+ /// calls reaching the kernel userclient, some staying in-process — and
+ /// shipping it is worse than not patching at all.
+ public static let requiredSuffixes: [String] = ["SwapBegin", "SwapEnd", "SwapSetLayer"]
+
+ /// Record group name, matching `records.set_group("iomfb_force_kern")`.
+ public static let recordGroup = "iomfb_force_kern"
+
+ /// Where diagnostics go when the caller does not say. Mirrors the
+ /// reference's `print`, so the two runs can be diffed line by line.
+ public static let stdoutLog: @Sendable (String) -> Void = { line in
+ FileHandle.standardOutput.write(Data((line + "\n").utf8))
+ }
+
+ // MARK: - Model
+
+ /// A public entry point paired with the `_kern_` implementation it should
+ /// branch to.
+ public struct EntryPoint: Sendable, Hashable {
+ /// The swap operation, spelled as the reference spells it in a record
+ /// ID: `SwapEnd`, not `End`.
+ public let suffix: String
+ public let publicName: String
+ public let publicAddress: UInt64
+ public let kernName: String
+ public let kernAddress: UInt64
+ }
+
+ /// What was decided about one entry point.
+ public enum Disposition: String, Sendable {
+ /// A thin trampoline whose first instruction this run rewrote.
+ case forced
+ /// Already `b _kern_Swap<Name>` — a previous run did it.
+ case alreadyForced
+ /// Not a thin dispatch trampoline; left on whatever path it had.
+ case notATrampoline
+ }
+
+ /// One entry point and its disposition.
+ public struct Site: Sendable {
+ public let entry: EntryPoint
+ public let disposition: Disposition
+ /// The first instruction as it was found, e.g. `cbz x0, #0x22ac0c1c0`.
+ public let originalDisassembly: String
+ }
+
+ /// What one run did.
+ public struct Outcome: Sendable {
+ /// Every discovered pair, in the order they were considered.
+ public let sites: [Site]
+ /// One record per site written, for the Python/Swift record comparison.
+ public let records: [PatchRecord]
+ /// The re-attestation pass, or `nil` when nothing was written.
+ public let reattestation: DSCReattestation?
+
+ public var forced: [Site] { sites.filter { $0.disposition == .forced } }
+ public var alreadyForced: [Site] { sites.filter { $0.disposition == .alreadyForced } }
+ public var notTrampolines: [Site] { sites.filter { $0.disposition == .notATrampoline } }
+
+ /// How many 4-byte sites this run put on disk. The reference returns
+ /// exactly this number.
+ public var writtenSiteCount: Int { forced.count }
+
+ /// Suffixes now on the kern path, whether this run did it or a previous
+ /// one did.
+ public var coveredSuffixes: Set<String> {
+ Set(sites.filter { $0.disposition != .notATrampoline }.map(\.entry.suffix))
+ }
+ }
+
+ // MARK: - Entry points
+
+ /// Force-kern the cache under `chunksDirectory`.
+ ///
+ /// - Returns: the outcome, whose `writtenSiteCount` is what the reference
+ /// returns.
+ @discardableResult
+ public static func patch(
+ chunksDirectory: URL,
+ dryRun: Bool = false,
+ log: ((String) -> Void)? = stdoutLog
+ ) throws -> Outcome {
+ let chunks = try DSCChunkSet(directory: chunksDirectory)
+ let resolver = try DSCSymbolResolver(chunks: chunks)
+ return try patch(chunks: chunks, resolver: resolver, dryRun: dryRun, log: log)
+ }
+
+ /// Force-kern a cache that is already open.
+ ///
+ /// Re-attestation consumes `chunks.recordedWrites`, so anything written
+ /// through this chunk set earlier in the same session is re-attested here
+ /// too. That is the intended direction: over-attesting a page costs one
+ /// SHA-256, under-attesting one is a page fault the guest dies on.
+ @discardableResult
+ public static func patch(
+ chunks: DSCChunkSet,
+ resolver: DSCSymbolResolver,
+ dryRun: Bool = false,
+ log: ((String) -> Void)? = stdoutLog
+ ) throws -> Outcome {
+ log?(" [.] \(chunks.chunkURLs.count) chunk(s), \(chunks.mappings.count) mapping(s)")
+
+ // `_kern_Swap*` are stripped local symbols, so without the `.symbols`
+ // side file discovery would find zero pairs and report it as "this
+ // cache has no such functions".
+ try resolver.requireLocalSymbols()
+
+ let disassembler = ARM64Disassembler()
+ let entries = try discoverEntryPoints(resolver: resolver)
+
+ // Classify everything before writing anything: the required-coverage
+ // check below has to be able to refuse while the cache is still clean.
+ var sites: [Site] = []
+ for entry in entries {
+ sites.append(try classify(entry, chunks: chunks, disassembler: disassembler))
+ }
+
+ let covered = Set(sites.filter { $0.disposition != .notATrampoline }.map(\.entry.suffix))
+ let missing = requiredSuffixes.filter { !covered.contains($0) }
+ guard missing.isEmpty else {
+ let forcible = sites.filter { $0.disposition == .forced }.map(\.entry.suffix).sorted()
+ let already = sites.filter { $0.disposition == .alreadyForced }.map(\.entry.suffix).sorted()
+ throw PatcherError.patchSiteNotFound(
+ "force-kern did not cover required entrypoints \(missing) "
+ + "(forcible: \(forcible); already forced: \(already))"
+ )
+ }
+
+ for site in sites {
+ switch site.disposition {
+ case .alreadyForced:
+ log?(" [=] \(site.entry.publicName) already -> b \(site.entry.kernName) (idempotent)")
+ case .notATrampoline:
+ log?(" [=] \(site.entry.publicName) not a thin trampoline; leaving on virt path")
+ case .forced:
+ log?(
+ " [+] \(site.entry.publicName) @ 0x\(hex(site.entry.publicAddress)): "
+ + "'\(site.originalDisassembly)' -> 'b \(site.entry.kernName)' "
+ + "(0x\(hex(site.entry.kernAddress)))"
+ )
+ }
+ }
+
+ let toWrite = sites.filter { $0.disposition == .forced }
+ guard !dryRun else {
+ log?(" [.] dry-run: would force \(toWrite.count) entrypoint(s); nothing written")
+ return Outcome(sites: sites, records: [], reattestation: nil)
+ }
+
+ var records: [PatchRecord] = []
+ for site in toWrite {
+ records.append(try force(site, chunks: chunks))
+ }
+
+ var reattestation: DSCReattestation?
+ if records.isEmpty {
+ log?(
+ " [=] all \(sites.count { $0.disposition == .alreadyForced }) entrypoint(s) "
+ + "already forced; nothing to patch/re-attest"
+ )
+ } else {
+ log?(" [.] re-attesting the pages \(records.count) write(s) dirtied...")
+ let result = try DSCCodeSignature.reattestRecordedWrites(in: chunks, log: log)
+ guard result.isFullyAttested else {
+ throw PatcherError.patchVerificationFailed(
+ "re-attestation skipped \(result.skipped.count) page(s): "
+ + result.skipped.map(\.description).joined(separator: "; ")
+ )
+ }
+ reattestation = result
+ try verify(toWrite, chunks: chunks, disassembler: disassembler)
+ }
+
+ let forcedCount = toWrite.count
+ let alreadyCount = sites.count { $0.disposition == .alreadyForced }
+ log?(
+ " [+] IOMFB force-kern complete: \(forcedCount) newly forced, "
+ + "\(alreadyCount) already -> _kern_*"
+ )
+ return Outcome(sites: sites, records: records, reattestation: reattestation)
+ }
+
+ // MARK: - Discovery
+
+ /// Every `_IOMobileFramebufferSwap*` in the image that has a `_kern_Swap*`
+ /// sibling, sorted by suffix.
+ ///
+ /// The set is discovered rather than listed: which swap operations exist,
+ /// and which of them kept a kern implementation, is a property of the cache
+ /// being patched and changes between OS versions.
+ public static func discoverEntryPoints(
+ resolver: DSCSymbolResolver
+ ) throws -> [EntryPoint] {
+ let all = try resolver.symbols(inImage: imagePath)
+ let publicEntries = try resolver.symbols(inImage: imagePath, withPrefix: publicPrefix)
+
+ var entries: [EntryPoint] = []
+ for (publicName, publicAddress) in publicEntries {
+ let suffix = "Swap" + publicName.dropFirst(publicPrefix.count)
+ let kernName = kernPrefix + publicName.dropFirst(publicPrefix.count)
+ guard let kern = all[kernName] else { continue }
+ entries.append(
+ EntryPoint(
+ suffix: suffix,
+ publicName: publicName,
+ publicAddress: publicAddress,
+ kernName: kernName,
+ kernAddress: kern.address
+ )
+ )
+ }
+ entries.sort { ($0.suffix, $0.publicName) < ($1.suffix, $1.publicName) }
+ return entries
+ }
+
+ // MARK: - Classification
+
+ private static func classify(
+ _ entry: EntryPoint,
+ chunks: DSCChunkSet,
+ disassembler: ARM64Disassembler
+ ) throws -> Site {
+ let instructions = disassembler.disassemble(
+ try chunks.bytesAtVMA(entry.publicAddress, length: 4 * 4),
+ at: entry.publicAddress,
+ count: 4
+ )
+ let first = instructions.first
+ let text = first.map { "\($0.mnemonic) \($0.operandString)" } ?? "<undecodable>"
+
+ // Idempotent: a prior run already rewrote this entry point.
+ if let first, first.mnemonic == "b",
+ let target = immediate(first, at: 0), UInt64(bitPattern: target) == entry.kernAddress
+ {
+ return Site(entry: entry, disposition: .alreadyForced, originalDisassembly: text)
+ }
+
+ let disposition: Disposition =
+ isDispatchTrampoline(instructions) ? .forced : .notATrampoline
+ return Site(entry: entry, disposition: disposition, originalDisassembly: text)
+ }
+
+ /// True iff the four instructions are
+ /// `cbz x0, … ; ldr xN, [x0, #imm] ; cbz xN, … ; braaz xN`.
+ ///
+ /// Matched on typed Capstone operands rather than on the operand text: the
+ /// base register of the load, the register the fp lands in and the register
+ /// the tail-call branches through are compared as register identities, so
+ /// `x1` cannot match the `x10` that a prefix test on the printed string
+ /// would accept.
+ public static func isDispatchTrampoline(_ instructions: [Instruction]) -> Bool {
+ guard instructions.count >= 4 else { return false }
+ let (check, load, guardBranch, tailCall) =
+ (instructions[0], instructions[1], instructions[2], instructions[3])
+
+ // cbz x0, <fail> — the connection pointer.
+ guard check.mnemonic == "cbz", register(check, at: 0) == AARCH64_REG_X0 else {
+ return false
+ }
+
+ // ldr xN, [x0, #slot] — the connection's swap fp. Plain base+displacement
+ // only: an indexed load is reading something else.
+ guard load.mnemonic == "ldr",
+ let scratch = register(load, at: 0),
+ let memory = memory(load),
+ memory.base == AARCH64_REG_X0,
+ memory.index == AARCH64_REG_INVALID,
+ memory.disp != 0
+ else { return false }
+
+ // cbz xN, <fail> — the fp's own null check.
+ guard guardBranch.mnemonic == "cbz", register(guardBranch, at: 0) == scratch else {
+ return false
+ }
+
+ // braaz/braa/br xN — the tail-call itself, signed or not.
+ guard ["braaz", "braa", "br"].contains(tailCall.mnemonic),
+ register(tailCall, at: 0) == scratch
+ else { return false }
+
+ return true
+ }
+
+ // MARK: - Writing
+
+ private static func force(_ site: Site, chunks: DSCChunkSet) throws -> PatchRecord {
+ let entry = site.entry
+ guard let branch = ARM64Encoder.encodeB(
+ from: Int(entry.publicAddress),
+ to: Int(entry.kernAddress)
+ ), branch.count == 4 else {
+ throw PatcherError.patchVerificationFailed(
+ "cannot encode b 0x\(hex(entry.publicAddress)) -> 0x\(hex(entry.kernAddress)) "
+ + "for \(entry.publicName)"
+ )
+ }
+
+ let span = DSCWriteSpan(vma: entry.publicAddress, length: 4)
+ let (chunkURL, range) = try chunks.fileRange(of: span)
+ let original = try chunks.bytesAtVMA(entry.publicAddress, length: 4)
+ try chunks.write(at: entry.publicAddress, branch)
+
+ return PatchRecord(
+ patchID: "\(recordGroup).\(entry.suffix)",
+ component: chunkURL.lastPathComponent,
+ fileOffset: range.lowerBound,
+ virtualAddress: entry.publicAddress,
+ originalBytes: original,
+ patchedBytes: branch,
+ beforeDisasm: site.originalDisassembly,
+ afterDisasm: "b #0x\(hex(entry.kernAddress).lowercased())",
+ description: "\(entry.publicName) trampoline -> b \(entry.kernName) "
+ + "(0x\(hex(entry.kernAddress)))"
+ )
+ }
+
+ /// Re-read every site after re-attestation and confirm it decodes as a
+ /// branch, which is what the reference's post-write verify checks.
+ private static func verify(
+ _ sites: [Site],
+ chunks: DSCChunkSet,
+ disassembler: ARM64Disassembler
+ ) throws {
+ for site in sites {
+ let address = site.entry.publicAddress
+ let data = try chunks.bytesAtVMA(address, length: 4)
+ guard let instruction = disassembler.disassembleOne(data, at: address),
+ instruction.mnemonic == "b",
+ let target = immediate(instruction, at: 0),
+ UInt64(bitPattern: target) == site.entry.kernAddress
+ else {
+ throw PatcherError.patchVerificationFailed(
+ "post-write verify failed at 0x\(hex(address)) for \(site.entry.publicName)"
+ )
+ }
+ }
+ }
+
+ // MARK: - Typed operand access
+
+ private static func register(_ instruction: Instruction, at index: Int) -> aarch64_reg? {
+ guard let operands = instruction.aarch64?.operands, index < operands.count,
+ operands[index].type == AARCH64_OP_REG
+ else { return nil }
+ return operands[index].reg
+ }
+
+ private static func immediate(_ instruction: Instruction, at index: Int) -> Int64? {
+ guard let operands = instruction.aarch64?.operands, index < operands.count,
+ operands[index].type == AARCH64_OP_IMM
+ else { return nil }
+ return operands[index].imm
+ }
+
+ private static func memory(_ instruction: Instruction) -> aarch64_op_mem? {
+ guard let operands = instruction.aarch64?.operands,
+ let operand = operands.first(where: { $0.type == AARCH64_OP_MEM })
+ else { return nil }
+ return operand.mem
+ }
+
+ private static func hex(_ value: UInt64) -> String {
+ String(value, radix: 16, uppercase: true)
+ }
+}
diff --git a/sources/FirmwarePatcher/DSC/Patchers/DSCIOMFBSwapEndPatcher.swift b/sources/FirmwarePatcher/DSC/Patchers/DSCIOMFBSwapEndPatcher.swift
new file mode 100644
index 00000000..d20c1d1c
--- /dev/null
+++ b/sources/FirmwarePatcher/DSC/Patchers/DSCIOMFBSwapEndPatcher.swift
@@ -0,0 +1,355 @@
+// DSCIOMFBSwapEndPatcher.swift — Make IOMobileFramebuffer's SwapEnd payload
+// size match what the base kernel's userclient will accept.
+//
+// The SwapEnd input-state size is enforced kernel-side, not negotiated: the PCC
+// vphone600 kernel's `IOMobileFramebufferUserClient` external method 5
+// (SwapEnd / swap_submit) does an *exact* `checkStructureInputSize` comparison.
+// A userland whose `_kern_SwapEnd` sends any other size gets
+// `kIOReturnBadArgument` back, so no frame is ever presented and the host VZ
+// display stays black — while the guest happily keeps rendering, which is why
+// the Apple logo is visible over VNC and not in the vphone-cli window.
+//
+// The accepted size is a property of the BASE KERNEL, never of the userland:
+//
+// * 26.1 base (older): the userclient expects 0x560.
+// * 26.4 base (xnu-12377, current): the userclient expects 0x588. Confirmed
+// twice over — the sole dispatch-shaped entry in
+// `kernelcache.*.vphone600` with `checkStructureInputSize == 0x588`
+// (scalarIn 0, scalarOut 0, structOut 0, preceded by a ptrauth code
+// pointer), and empirically, in that a native 26.5 userland sends 0x588 and
+// displays correctly on this stack.
+//
+// Sizes userlands are known to send: 18.6.2 → 0x514, 26.0/26.0.1 → 0x548,
+// 26.5 → 0x588 (the native match on a 26.4 base), 27.0 (24A5380h) → 0x6e0.
+//
+// `_kern_SwapEnd` sets up an external-method-5 call:
+//
+// ldr w0, [x0, #0x14]
+// add x2, x19, #0x18
+// mov w1, #5 <- external method selector 5
+// mov w3, #<size> <- input-state size (source; version-specific)
+// mov x4, #0
+// mov x5, #0
+// bl _io_connect_method
+//
+// The `mov w3, #<size>` immediate is the one thing this patcher rewrites.
+//
+// Nothing about the *source* size is written down here: it is discovered, never
+// matched, so the patch fires on any userland that has this call shape. The site
+// is found by resolving `_kern_SwapEnd` through the cache's own symbol tables,
+// disassembling it, and anchoring on the semantic call-setup shape — the
+// selector `mov w1, #5`, then the size `mov w3, #imm`, then the zeroed
+// `mov x4, #0` / `mov x5, #0`, then the `bl`. The replacement word comes from
+// `ARM64Encoder`.
+//
+// Port of `scripts/patchers/cfw_patch_iomfb_swapend.py`, which stays the
+// independent reference — `DSCIOMFBSwapEndTests` runs the Python on one clone of
+// the real cache and this on another, and compares the two byte for byte.
+//
+// One thing is deliberately not ported: the Python resolves `_kern_SwapEnd` by
+// shelling out to `ipsw dyld symaddr`. Here that is `DSCSymbolResolver`, which
+// reads the cache's export tries and its `.symbols` side file directly — same
+// addresses, no Go tool on the patch path.
+
+import Capstone
+import Foundation
+
+/// What one run of the SwapEnd size patch did.
+public struct DSCIOMFBSwapEndPatch: Sendable {
+ /// Address `_kern_SwapEnd` resolved to.
+ public let functionVMA: UInt64
+ /// Address of the `mov w3, #imm` that carries the payload size.
+ public let siteVMA: UInt64
+ /// The size the userland was sending before the patch.
+ public let originalSize: UInt32
+ /// The size the base kernel's userclient accepts.
+ public let targetSize: UInt32
+ /// True when the userland already sent `targetSize`, so nothing was written.
+ public let wasAlreadyCorrect: Bool
+ /// Sites written. 1 when the immediate was rewritten, 0 otherwise — the
+ /// number the Python's `patched`/`already` distinction implies, made
+ /// explicit so a parity run can compare it.
+ public let sitesWritten: Int
+ /// Re-attestation of the pages the write dirtied; `nil` on a dry run.
+ public let reattestation: DSCReattestation?
+
+ /// The Python's return value: one site *considered*, patched or not.
+ public var sitesConsidered: Int { 1 }
+}
+
+public enum DSCIOMFBSwapEndPatcher {
+ /// The image that carries `_kern_SwapEnd`.
+ public static let imagePath =
+ "/System/Library/PrivateFrameworks/IOMobileFramebuffer.framework/IOMobileFramebuffer"
+
+ /// The function that sets up the external-method call.
+ public static let symbolName = "_kern_SwapEnd"
+
+ /// `IOMobileFramebufferUserClient` external method 5 — SwapEnd / swap_submit.
+ ///
+ /// This is an anchor: it is what identifies the call among the several
+ /// `io_connect_method` set-ups in the image.
+ public static let selector: Int64 = 5
+
+ /// The input-state size the 26.4 vphone600 userclient accepts.
+ ///
+ /// A goal, not an anchor. The source immediate (0x6e0 on a 27.0 userland,
+ /// 0x548 on 26.0) is discovered by disassembly and never compared against
+ /// anything written down here. Pass `targetSize:` to build against a
+ /// different base kernel — a 26.1 base wants 0x560.
+ public static let defaultTargetSize: UInt32 = 0x588
+
+ /// Argument register 4 of `io_connect_method(port, selector, input,
+ /// inputCount, inputState, inputStateCount, …)` — the input-state size.
+ static let sizeRegister = "w3"
+ /// Argument registers 5 and 6, both zeroed in this call.
+ static let zeroedRegisters = ["x4", "x5"]
+ /// How far into `_kern_SwapEnd` to look. The call set-up is in the first
+ /// dozen instructions on every userland seen so far; the Python uses the
+ /// same bound.
+ static let maximumInstructions = 64
+
+ // MARK: - Entry points
+
+ /// Patch the cache under `chunksDirectory`.
+ ///
+ /// - Parameters:
+ /// - chunksDirectory: the directory of `dyld_shared_cache_arm64e*` chunks.
+ /// - targetSize: the size the base kernel's userclient accepts.
+ /// - dryRun: report the site and the rewrite without touching the cache.
+ /// - log: where the per-site lines go. `nil` for silence.
+ @discardableResult
+ public static func patch(
+ chunksDirectory: URL,
+ targetSize: UInt32 = defaultTargetSize,
+ dryRun: Bool = false,
+ log: ((String) -> Void)? = DSCCodeSignature.stderrLog
+ ) throws -> DSCIOMFBSwapEndPatch {
+ // Before opening a 6.7 GB cache and its 1.2 GB symbol table: a target
+ // size that cannot be encoded is an argument error, and it should read
+ // as one rather than as whatever the cache happens to say first.
+ _ = try replacement(forTargetSize: targetSize)
+
+ let chunks = try DSCChunkSet(directory: chunksDirectory)
+ let resolver = try DSCSymbolResolver(chunks: chunks)
+ return try patch(
+ chunks: chunks,
+ resolver: resolver,
+ targetSize: targetSize,
+ dryRun: dryRun,
+ log: log
+ )
+ }
+
+ /// Patch a cache that is already open.
+ ///
+ /// The re-attestation at the end covers only the writes this call made:
+ /// `recordedWrites` is cleared first, so a caller that runs several DSC
+ /// patchers over one `DSCChunkSet` does not re-hash the previous one's
+ /// pages on every subsequent patch.
+ @discardableResult
+ public static func patch(
+ chunks: DSCChunkSet,
+ resolver: DSCSymbolResolver,
+ targetSize: UInt32 = defaultTargetSize,
+ dryRun: Bool = false,
+ log: ((String) -> Void)? = DSCCodeSignature.stderrLog
+ ) throws -> DSCIOMFBSwapEndPatch {
+ let replacement = try replacement(forTargetSize: targetSize)
+
+ log?(" [.] \(chunks.chunkURLs.count) chunk(s), \(chunks.mappings.count) mapping(s)")
+
+ let functionVMA = try resolver.address(of: symbolName, inImage: imagePath)
+ log?(" [.] \(symbolName) @ 0x\(hex(functionVMA))")
+
+ let disassembler = ARM64Disassembler()
+ let instructions = try disassembleFunction(
+ in: chunks,
+ at: functionVMA,
+ maximumInstructions: maximumInstructions,
+ disassembler: disassembler
+ )
+ guard let site = findSizeInstruction(in: instructions, disassembler: disassembler),
+ let current = movRegisterImmediate(site.instruction, disassembler: disassembler)
+ else {
+ throw PatcherError.patchSiteNotFound(
+ "\(symbolName) SwapEnd size site (mov w1, #\(selector) -> "
+ + "mov \(sizeRegister), #imm -> mov x4, #0 -> mov x5, #0 -> bl) not found"
+ )
+ }
+
+ let siteVMA = site.instruction.address
+ let originalSize = UInt32(truncatingIfNeeded: current.immediate)
+ let wasAlreadyCorrect = originalSize == targetSize
+
+ if wasAlreadyCorrect {
+ log?(
+ " [=] already 0x\(hex(targetSize)) at 0x\(hex(siteVMA)); "
+ + "re-attesting page only"
+ )
+ } else {
+ log?(
+ " [\(dryRun ? "~" : "+")] \(dryRun ? "would patch" : "patched") "
+ + "\(imagePath) \(symbolName) size 0x\(hex(originalSize)) -> "
+ + "0x\(hex(targetSize)) at 0x\(hex(siteVMA))"
+ )
+ }
+
+ var reattestation: DSCReattestation?
+ if dryRun {
+ log?(" [.] dry-run: would re-attest the page holding 0x\(hex(siteVMA))")
+ } else {
+ chunks.clearRecordedWrites()
+ if !wasAlreadyCorrect {
+ try chunks.write(at: siteVMA, replacement)
+ }
+ log?(" [.] re-attesting modified page(s)...")
+ reattestation = try DSCCodeSignature.reattestRecordedWrites(in: chunks, log: log)
+
+ let readBack = try chunks.bytesAtVMA(siteVMA, length: replacement.count)
+ guard readBack == replacement else {
+ throw PatcherError.patchVerificationFailed(
+ "\(symbolName) size site at 0x\(hex(siteVMA)) reads back "
+ + "\(readBack.hex), expected \(replacement.hex)"
+ )
+ }
+ }
+
+ log?(" [+] IOMFB SwapEnd patch complete")
+ return DSCIOMFBSwapEndPatch(
+ functionVMA: functionVMA,
+ siteVMA: siteVMA,
+ originalSize: originalSize,
+ targetSize: targetSize,
+ wasAlreadyCorrect: wasAlreadyCorrect,
+ sitesWritten: (dryRun || wasAlreadyCorrect) ? 0 : 1,
+ reattestation: reattestation
+ )
+ }
+
+ // MARK: - The replacement instruction
+
+ /// The `mov w3, #targetSize` that replaces the userland's own size move.
+ ///
+ /// Assembled by `ARM64Encoder`, whose MOVZ encoding is asserted against
+ /// keystone's `asm("mov w3, #0x588")` in `ARM64EncoderTests`. No byte
+ /// sequence is written down anywhere on this path.
+ static func replacement(forTargetSize targetSize: UInt32) throws -> Data {
+ guard let immediate = UInt16(exactly: targetSize) else {
+ throw PatcherError.invalidFormat(
+ "SwapEnd target size 0x\(hex(targetSize)) does not fit a MOVZ immediate"
+ )
+ }
+ guard let encoded = ARM64Encoder.encodeMovzW(rd: 3, imm16: immediate),
+ encoded.count == 4
+ else {
+ throw PatcherError.invalidFormat(
+ "could not encode mov \(sizeRegister), #0x\(hex(targetSize))"
+ )
+ }
+ return encoded
+ }
+
+ // MARK: - Finding the site
+
+ /// The `mov w3, #imm` found inside the external-method call set-up, with the
+ /// index it sits at — the index is what the tests assert the shape on.
+ struct SizeSite {
+ let instruction: Instruction
+ let index: Int
+ }
+
+ /// Locate the `mov w3, #imm` that carries the SwapEnd input-state size.
+ ///
+ /// Anchored entirely on the call set-up's semantics: the selector
+ /// `mov w1, #5`, then a `mov w3, #imm` whose immediate is whatever this
+ /// userland happens to send, then the two zeroed argument registers, then
+ /// the `bl` into `io_connect_method`. Every comparison here is on a decoded
+ /// operand — register identity and immediate value — never on the rendered
+ /// operand string.
+ static func findSizeInstruction(
+ in instructions: [Instruction],
+ disassembler: ARM64Disassembler
+ ) -> SizeSite? {
+ // selector, size, the zeroed argument registers, then the call.
+ let shapeLength = 3 + zeroedRegisters.count
+ guard instructions.count >= shapeLength else { return nil }
+
+ for index in 0 ... (instructions.count - shapeLength) {
+ guard let selectorMove = movRegisterImmediate(
+ instructions[index],
+ disassembler: disassembler
+ ), selectorMove.register == "w1", selectorMove.immediate == selector
+ else { continue }
+
+ guard let sizeMove = movRegisterImmediate(
+ instructions[index + 1],
+ disassembler: disassembler
+ ), sizeMove.register == sizeRegister
+ else { continue }
+
+ let zeroed = zeroedRegisters.enumerated().allSatisfy { offset, name in
+ guard let move = movRegisterImmediate(
+ instructions[index + 2 + offset],
+ disassembler: disassembler
+ ) else { return false }
+ return move.register == name && move.immediate == 0
+ }
+ guard zeroed else { continue }
+ guard instructions[index + shapeLength - 1].mnemonic == "bl" else { continue }
+
+ return SizeSite(instruction: instructions[index + 1], index: index + 1)
+ }
+ return nil
+ }
+
+ /// `(register, immediate)` when `instruction` is `mov <reg>, #<imm>`, else
+ /// `nil`.
+ ///
+ /// The register name comes from Capstone's own register table rather than
+ /// from splitting `operandString`, so `w3` and `w13` cannot be confused and
+ /// a change in how Capstone renders an operand cannot move the site.
+ static func movRegisterImmediate(
+ _ instruction: Instruction,
+ disassembler: ARM64Disassembler
+ ) -> (register: String, immediate: Int64)? {
+ guard instruction.mnemonic == "mov" else { return nil }
+ guard let operands = instruction.aarch64?.operands, operands.count == 2,
+ operands[0].type == AARCH64_OP_REG,
+ operands[1].type == AARCH64_OP_IMM,
+ let name = disassembler.registerName(UInt32(operands[0].reg.rawValue))
+ else { return nil }
+ return (name, operands[1].imm)
+ }
+
+ /// Disassemble from `vma` up to the first `ret`/`retab` or
+ /// `maximumInstructions`, whichever comes first.
+ ///
+ /// `allowShort` so a function that sits near the end of its contiguous run
+ /// still disassembles as far as it goes, rather than throwing because the
+ /// full instruction budget would overrun the mapping.
+ static func disassembleFunction(
+ in chunks: DSCChunkSet,
+ at vma: UInt64,
+ maximumInstructions: Int,
+ disassembler: ARM64Disassembler
+ ) throws -> [Instruction] {
+ let code = try chunks.readAtVMA(
+ vma,
+ length: maximumInstructions * 4,
+ allowShort: true
+ )
+ var result: [Instruction] = []
+ for instruction in disassembler.disassemble(code, at: vma, count: maximumInstructions) {
+ result.append(instruction)
+ if instruction.mnemonic == "ret" || instruction.mnemonic == "retab" { break }
+ }
+ return result
+ }
+
+ // MARK: - Formatting
+
+ private static func hex(_ value: some FixedWidthInteger) -> String {
+ String(value, radix: 16, uppercase: true)
+ }
+}
diff --git a/sources/FirmwarePatcher/DSC/Patchers/DSCLSDEmbeddedRegPatcher.swift b/sources/FirmwarePatcher/DSC/Patchers/DSCLSDEmbeddedRegPatcher.swift
new file mode 100644
index 00000000..15a162cf
--- /dev/null
+++ b/sources/FirmwarePatcher/DSC/Patchers/DSCLSDEmbeddedRegPatcher.swift
@@ -0,0 +1,358 @@
+// DSCLSDEmbeddedRegPatcher.swift — open lsd's embedded-registration gate.
+//
+// Swift port of `scripts/patchers/cfw_patch_lsd_embedded_reg.py`, driven by
+// `cfw.py patch-lsd-embedded-reg <chunks_dir> [--dry-run]`.
+//
+// iOS 27's lsd gates `-[_LSDModifyClient performPostInstallationRegistration:…]`
+// — and its containerized/rebuild siblings — behind
+// `-[_LSDModifyClient clientIsEntitledForEmbeddedRegistrationOperations]`, which
+// calls `xpc_connection_copy_entitlement_value` on the XPC *peer* for any of
+// three privileged entitlements (`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) out of
+// `LSDModifyService.mm`, so `registerApplicationDictionary:` returns NO. That
+// blocks JB app registration (uicache/Sileo), vphoned's IPA installer and
+// TrollStore alike.
+//
+// The entitlement route is a dead end on this stack: even a launchd-spawned
+// platform daemon (vphoned) carrying all three in its *validated* csblob
+// (`csops CS_OPS_ENTITLEMENTS_BLOB` confirms) is still refused, because LS
+// registration is proxied — the XPC peer lsd inspects is not the registering
+// process.
+//
+// So the check is forced to succeed. The method ORs three entitlement probes:
+//
+// bl <check ent1> ; cbnz w0, entitled
+// bl <check ent2> ; cbnz w0, entitled
+// bl <check ent3> ; cbz w0, not_entitled <- the gate; this is NOP'd
+// entitled:
+// mov w20, #1 <- the YES result
+// … ; mov x0, x20 ; retab
+// not_entitled:
+// mov w20, #0
+//
+// NOP'ing that final `cbz w0, <not_entitled>` — the conditional branch whose
+// fall-through is the `mov w<reg>, #1` that becomes the return value — makes
+// every path reach YES. One instruction, one site.
+//
+// Nothing is hardcoded. The method is resolved from the cache's own
+// `.symbols` local-symbol table, disassembled with Capstone, and the gate is
+// found by control-flow shape rather than by address. The replacement is
+// `ARM64.nop`. Writing a cache page invalidates its 16 KiB code slot, so the
+// page is re-attested (TXM enforces per-page); the CDHash change that follows
+// is accepted by the JB's always-true AMFI cdhash-trust patch.
+
+import Capstone
+import Foundation
+
+/// Forces `-[_LSDModifyClient clientIsEntitledForEmbeddedRegistrationOperations]`
+/// to return YES, by NOP'ing the branch that skips its YES result.
+public enum DSCLSDEmbeddedRegPatcher {
+ /// The image the method lives in. Reported only — the symbol is resolved
+ /// through the cache-wide local table, exactly as the Python does, because
+ /// `ipsw dyld symaddr -a` times out on a cache this size.
+ public static let image =
+ "/System/Library/Frameworks/CoreServices.framework/CoreServices"
+
+ /// The ObjC method whose entitlement check is opened.
+ public static let method =
+ "-[_LSDModifyClient clientIsEntitledForEmbeddedRegistrationOperations]"
+
+ /// Record identity, matching the Python's `records.next_site` label so a
+ /// captured reference and this port sort together.
+ public static let patchID = "lsd_embedded_reg.entitlement_gate"
+
+ /// How far into the method to look. The gate sits within the first handful
+ /// of basic blocks; 96 instructions is the Python's window and is ample.
+ static let maxInstructions = 96
+
+ // MARK: - Results
+
+ /// The conditional branch (or the NOP that already replaced it) that guards
+ /// the method's YES result.
+ public struct Gate: Sendable, Equatable {
+ /// Address of the gating instruction.
+ public let vma: UInt64
+ /// Its mnemonic as Capstone decoded it — `cbz`, `cbnz`, or `nop` when
+ /// a previous run already patched this cache.
+ public let mnemonic: String
+ /// Its operand text, for logging.
+ public let operandString: String
+ /// The `w` register the fall-through sets to 1 — the YES value that
+ /// later becomes the method's return.
+ public let resultRegister: String
+
+ /// True when the site already holds this patch's own output.
+ public var wasAlreadyNOP: Bool { mnemonic == "nop" }
+
+ /// How the gate reads in disassembly.
+ public var text: String {
+ operandString.isEmpty ? mnemonic : "\(mnemonic) \(operandString)"
+ }
+ }
+
+ /// What a run did.
+ public enum Outcome: String, Sendable, Equatable {
+ /// The method is not in this cache — a pre-iOS-27 userland, where the
+ /// gate does not exist and there is nothing to open.
+ case methodAbsent
+ /// The gate already held a NOP; the page was re-attested and nothing
+ /// else changed.
+ case alreadyPatched
+ /// `dryRun` was set, so the site was located and reported only.
+ case wouldPatch
+ /// The branch was replaced with a NOP and its page re-attested.
+ case patched
+ }
+
+ /// The outcome of one run, and the site it acted on.
+ public struct Report: Sendable {
+ public let outcome: Outcome
+ /// The gate, when the method was present.
+ public let gate: Gate?
+ /// The write, in the shape the Python's reference capture records it.
+ /// `nil` unless bytes actually changed.
+ public let record: PatchRecord?
+
+ /// Sites whose bytes this run changed. The parity number: the Python
+ /// writes exactly one, and so must this.
+ public var sitesWritten: Int { record == nil ? 0 : 1 }
+
+ /// Whether the gate method exists in this cache at all. Mirrors the
+ /// Python's return value, which is 0 when absent and 1 otherwise.
+ public var methodIsPresent: Bool { outcome != .methodAbsent }
+ }
+
+ /// Where progress goes when the caller does not say. The Python prints to
+ /// stdout and `cfw_install*.sh` captures that, so this does too.
+ public static let stdoutLog: @Sendable (String) -> Void = { print($0) }
+
+ // MARK: - Patching
+
+ /// Open the gate in the cache under `chunksDirectory`.
+ ///
+ /// Self-gating, like the Python: the method exists only on iOS 27+
+ /// LaunchServices, so a cache without it reports `.methodAbsent` and
+ /// changes nothing. A cache whose `.symbols` side file is *missing*, by
+ /// contrast, throws — "there is nowhere to look" must not be reported as
+ /// "this userland predates the gate", or an install against a stripped
+ /// cache would silently skip the patch and boot into a guest where no app
+ /// can register.
+ ///
+ /// - Throws: ``PatcherError/patchSiteNotFound(_:)`` when the method is
+ /// present but its control-flow shape no longer matches — a LaunchServices
+ /// rewrite, which has to stop the install rather than be guessed at.
+ @discardableResult
+ public static func patch(
+ chunksDirectory: URL,
+ dryRun: Bool = false,
+ log: ((String) -> Void)? = stdoutLog
+ ) throws -> Report {
+ let chunks = try DSCChunkSet(directory: chunksDirectory)
+ log?(" [.] \(chunksDirectory.path): \(chunks.chunkURLs.count) chunk(s), "
+ + "\(chunks.mappings.count) mapping(s)")
+
+ guard let located = try locateGate(in: chunks) else {
+ log?(" [=] \(method) not present (pre-iOS-27 userland); nothing to patch")
+ return Report(outcome: .methodAbsent, gate: nil, record: nil)
+ }
+ log?(" [.] \(method) @ 0x\(hex(located.functionVMA))")
+
+ let gate = located.gate
+ log?(" [.] gate: \(gate.text) @ 0x\(hex(gate.vma)) "
+ + "(fall-through sets \(gate.resultRegister)=1)")
+
+ let nop = ARM64.nop
+ let original = try chunks.bytesAtVMA(gate.vma, length: nop.count)
+ let alreadyNOP = original == nop
+
+ if alreadyNOP {
+ log?(" [=] already NOP at 0x\(hex(gate.vma)); re-attesting page only")
+ } else {
+ log?(" [+] \(dryRun ? "would NOP" : "NOP'd") gate \(gate.mnemonic) -> nop "
+ + "at 0x\(hex(gate.vma)) (bytes \(original.hex) -> \(nop.hex))")
+ }
+
+ guard !dryRun else {
+ // The Python signs off with "patch complete" here too. This does
+ // not: a dry run patched nothing, and a log line that says
+ // otherwise is the one an operator would quote back later.
+ log?(" [.] dry-run: would re-attest page for 0x\(hex(gate.vma))")
+ return Report(outcome: .wouldPatch, gate: gate, record: nil)
+ }
+
+ // Written unconditionally, including when the bytes already match. The
+ // Python re-attests the gate's page on every non-dry run, patched or
+ // not, and re-attestation here consumes the chunk set's own write log
+ // rather than an address a caller hands it — so the idempotent case has
+ // to go through the same door. The bytes on disk are identical either
+ // way, and `DSCCodeSignature` leaves a page whose stored slot already
+ // matches alone.
+ try chunks.write(at: gate.vma, nop)
+
+ log?(" [.] re-attesting modified page...")
+ try DSCCodeSignature.reattestRecordedWrites(in: chunks, log: log)
+
+ let written = try chunks.bytesAtVMA(gate.vma, length: nop.count)
+ guard written == nop else {
+ throw PatcherError.patchVerificationFailed(
+ "\(method): gate at 0x\(hex(gate.vma)) reads \(written.hex) after write"
+ )
+ }
+
+ log?(" [+] lsd embedded-registration gate patch complete")
+
+ guard !alreadyNOP else {
+ return Report(outcome: .alreadyPatched, gate: gate, record: nil)
+ }
+ return Report(
+ outcome: .patched,
+ gate: gate,
+ record: try record(for: gate, in: chunks, original: original, patched: nop)
+ )
+ }
+
+ // MARK: - Locating the gate
+
+ /// Find the entitlement gate without touching the cache.
+ ///
+ /// Returns `nil` when the method is absent, which is the pre-iOS-27 no-op
+ /// case rather than an error.
+ public static func locateGate(
+ in chunks: DSCChunkSet
+ ) throws -> (functionVMA: UInt64, gate: Gate)? {
+ guard let functionVMA = try chunks.resolveLocalSymbol(method) else { return nil }
+
+ let instructions = try disassembleFunction(in: chunks, at: functionVMA)
+ guard let gate = findGate(in: instructions) else {
+ throw PatcherError.patchSiteNotFound(
+ "\(method): entitled-result gate (cbz/cbnz w0 -> mov w<reg>,#1) not found"
+ )
+ }
+ return (functionVMA, gate)
+ }
+
+ /// Disassemble from `vma` up to the first `ret`/`retab`, or
+ /// ``maxInstructions``, whichever comes first.
+ ///
+ /// `allowShort` because the window is a fixed instruction count, not a
+ /// claim about what is mapped: a method that ends near the tail of its
+ /// mapping must not turn into an unmapped-span error.
+ static func disassembleFunction(
+ in chunks: DSCChunkSet,
+ at vma: UInt64
+ ) throws -> [Instruction] {
+ let buffer = try chunks.readAtVMA(
+ vma,
+ length: maxInstructions * 4,
+ allowShort: true
+ )
+ let decoded = ARM64Disassembler().disassemble(buffer, at: vma)
+ var result: [Instruction] = []
+ for instruction in decoded {
+ // The shared disassembler has `skipData` on, so a word Capstone
+ // cannot decode arrives as a data pseudo-instruction (id 0) rather
+ // than ending the stream. The Python's `cs.disasm` stops there, and
+ // so does this: past an undecodable word the window is no longer
+ // this function's instructions, and matching a "gate" in it would
+ // be matching noise.
+ guard instruction.id != 0 else { break }
+ result.append(instruction)
+ if instruction.mnemonic == "ret" || instruction.mnemonic == "retab" { break }
+ }
+ return result
+ }
+
+ /// The conditional branch that gates the entitled result: the `cbz`/`cbnz`
+ /// on `w0` whose fall-through is `mov w<reg>, #1`.
+ ///
+ /// A bare `nop` in that position matches too. That is this patch's own
+ /// output, so a second run over an already-patched cache recognises the
+ /// idempotent state instead of failing to find a branch that is no longer
+ /// there — which is exactly how a re-run of `cfw install` used to die.
+ static func findGate(in instructions: [Instruction]) -> Gate? {
+ let disassembler = ARM64Disassembler()
+ guard instructions.count >= 2 else { return nil }
+
+ for index in 0 ..< (instructions.count - 1) {
+ let candidate = instructions[index]
+ switch candidate.mnemonic {
+ case "cbz", "cbnz":
+ guard disassembler.firstRegisterName(candidate) == "w0" else { continue }
+ case "nop":
+ break
+ default:
+ continue
+ }
+ guard let next = movRegisterImmediate(instructions[index + 1], disassembler),
+ next.immediate == 1,
+ next.register.hasPrefix("w")
+ else { continue }
+ return Gate(
+ vma: candidate.address,
+ mnemonic: candidate.mnemonic,
+ operandString: candidate.operandString,
+ resultRegister: next.register
+ )
+ }
+ return nil
+ }
+
+ /// `mov <reg>, #<imm>` decomposed, or `nil` when the instruction is
+ /// something else.
+ ///
+ /// Matched on decoded operand types — register destination, immediate
+ /// source — rather than on operand text.
+ static func movRegisterImmediate(
+ _ instruction: Instruction,
+ _ disassembler: ARM64Disassembler
+ ) -> (register: String, immediate: Int64)? {
+ guard instruction.mnemonic == "mov",
+ let operands = instruction.aarch64?.operands,
+ operands.count == 2,
+ operands[0].type == AARCH64_OP_REG,
+ operands[1].type == AARCH64_OP_IMM,
+ let register = disassembler.firstRegisterName(instruction)
+ else { return nil }
+ return (register, operands[1].imm)
+ }
+
+ // MARK: - Recording
+
+ /// Describe the write the way `cfw_records.record_span` does: component is
+ /// the chunk file's basename, the offset is into that chunk, and the
+ /// virtual address rides along.
+ private static func record(
+ for gate: Gate,
+ in chunks: DSCChunkSet,
+ original: Data,
+ patched: Data
+ ) throws -> PatchRecord {
+ let span = DSCWriteSpan(vma: gate.vma, length: patched.count)
+ let (chunkURL, range) = try chunks.fileRange(of: span)
+ return PatchRecord(
+ patchID: patchID,
+ component: chunkURL.lastPathComponent,
+ fileOffset: range.lowerBound,
+ virtualAddress: gate.vma,
+ originalBytes: original,
+ patchedBytes: patched,
+ beforeDisasm: disassemblyText(of: original, at: gate.vma),
+ afterDisasm: disassemblyText(of: patched, at: gate.vma),
+ description: "NOP `\(gate.text)` in \(method) so the fall-through "
+ + "sets \(gate.resultRegister)=1 (entitled)"
+ )
+ }
+
+ private static func disassemblyText(of bytes: Data, at vma: UInt64) -> String {
+ ARM64Disassembler()
+ .disassemble(bytes, at: vma)
+ .map { $0.operandString.isEmpty ? $0.mnemonic : "\($0.mnemonic) \($0.operandString)" }
+ .joined(separator: "; ")
+ }
+
+ private static func hex(_ value: UInt64) -> String {
+ String(value, radix: 16, uppercase: true)
+ }
+}
diff --git a/sources/FirmwarePatcher/DSC/Patchers/DSCLockdownModePatcher.swift b/sources/FirmwarePatcher/DSC/Patchers/DSCLockdownModePatcher.swift
new file mode 100644
index 00000000..33133f49
--- /dev/null
+++ b/sources/FirmwarePatcher/DSC/Patchers/DSCLockdownModePatcher.swift
@@ -0,0 +1,332 @@
+// DSCLockdownModePatcher.swift — Stop libSystem's `os_lockdown_mode_enabled`
+// from crashing on the vphone kernel.
+//
+// iOS 27's `os_lockdown_mode_enabled()` resolves Lockdown Mode once, from a
+// block, via `sysctlbyname("security.mac.lockdown_mode_state_public", …)` and
+// `os_crash`es when the sysctl returns -1 (`lockdown_mode.c`). The vphone base
+// kernel (cloudOS 26.x) does not implement that MAC sysctl, so the call fails
+// with ENOENT and every process that queries Lockdown Mode aborts — including
+// launchd (pid 1), which panics the system right after "Continuing system
+// boot".
+//
+// The block pre-zeroes its output buffer (`stp x8, xzr, [sp]`), so dropping the
+// error branch makes the failure path fall through to the normal path, read 0,
+// and record "Lockdown Mode disabled". On a kernel that does implement the
+// sysctl the branch is never taken, so the patch is behaviour-neutral there.
+//
+// Shape (in `___os_lockdown_mode_enabled_block_invoke`):
+//
+// bl <sysctlbyname>
+// cmn w0, #1 ; w0 == -1 ?
+// b.eq <os_crash> ; -> NOP
+//
+// Anchored on the in-image local symbol; the sysctl-error idiom is located by
+// control-flow shape through Capstone; the NOP comes from `ARM64.nop`; the
+// modified page is re-attested through `DSCCodeSignature`.
+//
+// Port of `scripts/patchers/cfw_patch_lockdown_mode.py`, which stays the
+// independent reference — `DSCLockdownModePatcherTests` runs the Python on one
+// clone of the real cache and this on another, and compares the two byte for
+// byte.
+//
+// One cosmetic divergence, in text only: this links Capstone 6 and the
+// reference runs Capstone 5, which prints a branch target as `0x237ef22bc`
+// where the older one prints `#0x237ef22bc`. That string reaches the log line
+// and the `PatchRecord` description, never a patched byte, and nothing here
+// matches on operand text.
+
+import Capstone
+import Foundation
+
+public enum DSCLockdownModePatcher {
+ // MARK: - Anchors
+
+ /// The block the sysctl lives in, under both manglings seen across
+ /// toolchains. The first one that resolves wins, exactly as in the Python.
+ public static let symbolCandidates = [
+ "___os_lockdown_mode_enabled_block_invoke",
+ "__os_lockdown_mode_enabled_block_invoke",
+ ]
+
+ /// How far into the block to decode. The idiom sits within a dozen
+ /// instructions of the entry on every build seen so far; the decode also
+ /// stops at the block's first `ret`/`retab`, so this is only a ceiling.
+ static let maxInstructions = 60
+
+ /// One disassembler for the whole patcher — `ARM64Disassembler` is
+ /// `Sendable` and stateless across calls.
+ private static let disassembler = ARM64Disassembler()
+
+ // MARK: - Outcome
+
+ /// What one run did, in the terms the Python prints.
+ public struct Outcome: Sendable {
+ public enum Verdict: Sendable, Equatable, CustomStringConvertible {
+ /// No `os_lockdown_mode_enabled` block in this cache — a pre-iOS-27
+ /// userland. Not an error: the crash it guards against cannot
+ /// happen there.
+ case symbolAbsent
+ /// The gate already holds the NOP this patch writes. Nothing was
+ /// written and nothing needed re-attesting.
+ case alreadyPatched
+ /// A dry run that located a live gate and stopped short of writing.
+ case wouldPatch
+ /// The NOP was written and the page it dirtied re-attested.
+ case patched
+
+ public var description: String {
+ switch self {
+ case .symbolAbsent: "symbol absent"
+ case .alreadyPatched: "already patched"
+ case .wouldPatch: "would patch"
+ case .patched: "patched"
+ }
+ }
+ }
+
+ public let verdict: Verdict
+ /// Which of `symbolCandidates` resolved, when one did.
+ public let symbolName: String?
+ /// Address of the block the gate was found in.
+ public let functionVMA: UInt64?
+ /// Address of the branch that was (or would be) NOPed.
+ public let gateVMA: UInt64?
+ /// The record of the single write, on a run that wrote or would write.
+ public let record: PatchRecord?
+ /// What re-attestation did, on a run that wrote.
+ public let reattestation: DSCReattestation?
+
+ public init(
+ verdict: Verdict,
+ symbolName: String? = nil,
+ functionVMA: UInt64? = nil,
+ gateVMA: UInt64? = nil,
+ record: PatchRecord? = nil,
+ reattestation: DSCReattestation? = nil
+ ) {
+ self.verdict = verdict
+ self.symbolName = symbolName
+ self.functionVMA = functionVMA
+ self.gateVMA = gateVMA
+ self.record = record
+ self.reattestation = reattestation
+ }
+
+ /// Sites this run put on disk — 1 on a live patch, 0 otherwise.
+ public var sitesWritten: Int { verdict == .patched ? 1 : 0 }
+
+ /// Sites this run found, patched or already patched. This is the number
+ /// `patch_lockdown_mode` returns: 0 when the symbol is absent, 1
+ /// otherwise.
+ public var sitesFound: Int { verdict == .symbolAbsent ? 0 : 1 }
+ }
+
+ // MARK: - Entry points
+
+ /// Patch the cache under `chunksDirectory`.
+ @discardableResult
+ public static func patch(
+ chunksDirectory: URL,
+ dryRun: Bool = false,
+ log: ((String) -> Void)? = DSCCodeSignature.stderrLog
+ ) throws -> Outcome {
+ try patch(in: DSCChunkSet(directory: chunksDirectory), dryRun: dryRun, log: log)
+ }
+
+ /// Patch an already-open cache.
+ ///
+ /// Writes go through `DSCChunkSet.write(at:_:)`, so the span is recorded
+ /// and `reattestRecordedWrites` cannot be handed the wrong address. A
+ /// caller sharing one chunk set across patchers therefore also gets any
+ /// earlier patcher's pages re-attested here, which is a no-op for pages
+ /// that are already correct.
+ @discardableResult
+ public static func patch(
+ in chunks: DSCChunkSet,
+ dryRun: Bool = false,
+ log: ((String) -> Void)? = DSCCodeSignature.stderrLog
+ ) throws -> Outcome {
+ log?(
+ " [.] \(chunks.directory.path) "
+ + "(\(chunks.chunkURLs.count) chunk(s), \(chunks.mappings.count) mapping(s))"
+ )
+
+ guard let block = try resolveBlockInvoke(in: chunks) else {
+ log?(
+ " [=] os_lockdown_mode_enabled not present "
+ + "(pre-iOS-27 userland); nothing to patch"
+ )
+ return Outcome(verdict: .symbolAbsent)
+ }
+ log?(" [.] \(block.name) @ 0x\(hex(block.vma))")
+
+ let instructions = try disassembleBlock(in: chunks, at: block.vma)
+ guard let gate = findErrorGate(instructions) else {
+ throw PatcherError.patchSiteNotFound(
+ "lockdown_mode: `cmn wR,#1; b.eq <crash>` sysctl-error gate not found "
+ + "(nor an already-NOPed one)"
+ )
+ }
+ log?(" [.] gate @ 0x\(hex(gate.address)): \(gate.mnemonic) \(gate.operandString)")
+
+ let nop = ARM64.nop
+ let current = try chunks.bytesAtVMA(gate.address, length: nop.count)
+ guard current != nop else {
+ log?(
+ " [=] already patched at 0x\(hex(gate.address)); "
+ + "nothing to patch/re-attest"
+ )
+ return Outcome(
+ verdict: .alreadyPatched,
+ symbolName: block.name,
+ functionVMA: block.vma,
+ gateVMA: gate.address
+ )
+ }
+
+ let record = try record(for: gate, original: current, replacement: nop, in: chunks)
+ log?(
+ " [+] \(dryRun ? "would write" : "wrote") nop at 0x\(hex(gate.address)) "
+ + "(\(current.hex) -> \(nop.hex))"
+ )
+ guard !dryRun else {
+ return Outcome(
+ verdict: .wouldPatch,
+ symbolName: block.name,
+ functionVMA: block.vma,
+ gateVMA: gate.address,
+ record: record
+ )
+ }
+
+ try chunks.write(at: gate.address, nop)
+ let reattestation = try DSCCodeSignature.reattestRecordedWrites(in: chunks, log: log)
+ guard try chunks.bytesAtVMA(gate.address, length: nop.count) == nop else {
+ throw PatcherError.patchVerificationFailed(
+ "lockdown_mode: post-write verify failed at 0x\(hex(gate.address))"
+ )
+ }
+ log?(" [+] lockdown-mode crash patch complete")
+
+ return Outcome(
+ verdict: .patched,
+ symbolName: block.name,
+ functionVMA: block.vma,
+ gateVMA: gate.address,
+ record: record,
+ reattestation: reattestation
+ )
+ }
+
+ // MARK: - Reveal
+
+ /// The first of `symbolCandidates` the cache's own `.symbols` table knows.
+ ///
+ /// A missing symbol is `nil` — the pre-iOS-27 case. A missing or
+ /// unparseable symbol table throws, because "there is nothing to look in"
+ /// must not be reported as "this userland does not have the block".
+ static func resolveBlockInvoke(in chunks: DSCChunkSet) throws -> (name: String, vma: UInt64)? {
+ for name in symbolCandidates {
+ if let vma = try chunks.resolveLocalSymbol(name) {
+ return (name, vma)
+ }
+ }
+ return nil
+ }
+
+ /// Decode the block from `vma` up to its first `ret`/`retab`, or
+ /// `maxInstructions`, whichever comes first.
+ ///
+ /// The window is truncated at the end of what is addressable rather than
+ /// padded with whatever follows in the chunk file, which is where this
+ /// differs from `_disasm_function` in the reference: a block sitting at the
+ /// very end of a mapping decodes as far as it really extends here, instead
+ /// of running on into the next region's bytes. On this cache the block is
+ /// nowhere near a boundary, so both read the same instructions.
+ /// Stops at an undecodable word as well. `ARM64Disassembler` sets
+ /// `cs.skipData = true` and the reference's `_cs` (`cfw_asm.py:14`) does
+ /// not, so where Capstone cannot decode a word the Python's `cs.disasm`
+ /// ends the stream and this one hands back a data pseudo-instruction
+ /// (`id == 0`) and carries on. Left alone that inverts the failure mode on
+ /// a userland whose block carries an inline literal before the gate: the
+ /// Python truncates, `findErrorGate` finds nothing and the install stops
+ /// loudly, while this would decode on past the data into whatever follows
+ /// the block and — if a `bl` / `cmn wR,#1` / `b.eq` triple happened to
+ /// appear there — NOP a branch in unrelated code and re-attest that page.
+ /// A wrong patch that passes its own signature check is worse than a
+ /// failed install. `DSCLSDEmbeddedRegPatcher.disassembleFunction` breaks on
+ /// the same condition for the same reason.
+ static func disassembleBlock(in chunks: DSCChunkSet, at vma: UInt64) throws -> [Instruction] {
+ let window = try chunks.readAtVMA(vma, length: maxInstructions * 4, allowShort: true)
+ var decoded: [Instruction] = []
+ for insn in disassembler.disassemble(window, at: vma, count: maxInstructions) {
+ guard insn.id != 0 else { break }
+ decoded.append(insn)
+ if insn.mnemonic == "ret" || insn.mnemonic == "retab" { break }
+ }
+ return decoded
+ }
+
+ /// The `cmn wR, #1; b.eq` sysctl-error idiom, preceded by a call.
+ ///
+ /// The branch slot also matches once it holds the NOP this patch writes.
+ /// Without that, a second pass over an already-installed cache never
+ /// reaches the byte comparison in `patch(in:dryRun:log:)` — the idiom it
+ /// searches for is the one the patch has already replaced — and the run
+ /// fails instead of reporting a no-op. The `bl` + `cmn wR, #1` anchor is
+ /// unchanged, so widening the slot does not weaken where a match can land,
+ /// and re-writing a NOP over a NOP is inert.
+ static func findErrorGate(_ instructions: [Instruction]) -> Instruction? {
+ guard instructions.count >= 2 else { return nil }
+ var sawCall = false
+ for index in 0 ..< (instructions.count - 1) {
+ let insn = instructions[index]
+ if insn.mnemonic == "bl" { sawCall = true }
+ guard sawCall else { continue }
+ guard insn.mnemonic == "cmn", immediate(of: insn, at: 1) == 1 else { continue }
+ let gate = instructions[index + 1]
+ if gate.mnemonic == "b.eq" || gate.mnemonic == "nop" { return gate }
+ }
+ return nil
+ }
+
+ /// The instruction's operand at `index`, when that operand is an immediate.
+ ///
+ /// Semantic, not textual: the `#1` of `cmn w0, #1` is read off the decode,
+ /// so a build that prints it as `#0x1` matches just the same.
+ static func immediate(of insn: Instruction, at index: Int) -> Int64? {
+ guard let operands = insn.aarch64?.operands,
+ index < operands.count,
+ operands[index].type == AARCH64_OP_IMM
+ else { return nil }
+ return operands[index].imm
+ }
+
+ // MARK: - Reporting
+
+ private static func record(
+ for gate: Instruction,
+ original: Data,
+ replacement: Data,
+ in chunks: DSCChunkSet
+ ) throws -> PatchRecord {
+ let span = DSCWriteSpan(vma: gate.address, length: replacement.count)
+ let (chunkURL, range) = try chunks.fileRange(of: span)
+ return PatchRecord(
+ patchID: "lockdown_mode.sysctl_error_gate",
+ component: chunkURL.lastPathComponent,
+ fileOffset: range.lowerBound,
+ virtualAddress: gate.address,
+ originalBytes: original,
+ patchedBytes: replacement,
+ beforeDisasm: "\(gate.mnemonic) \(gate.operandString)",
+ afterDisasm: "nop",
+ description: "NOP `\(gate.mnemonic) \(gate.operandString)` so a missing "
+ + "security.mac.lockdown_mode_state_public sysctl reads 0 instead of aborting"
+ )
+ }
+
+ private static func hex(_ value: UInt64) -> String {
+ String(value, radix: 16, uppercase: true)
+ }
+}
diff --git a/sources/FirmwarePatcher/DSC/Patchers/DSCMaxSlidePatcher.swift b/sources/FirmwarePatcher/DSC/Patchers/DSCMaxSlidePatcher.swift
new file mode 100644
index 00000000..99954293
--- /dev/null
+++ b/sources/FirmwarePatcher/DSC/Patchers/DSCMaxSlidePatcher.swift
@@ -0,0 +1,424 @@
+// DSCMaxSlidePatcher.swift — Clamp the dyld shared cache's recorded maxSlide so
+// a large userland cache fits the PCC vphone600 26.x kernel's fixed 6 GiB
+// shared region.
+//
+// Swift port of `scripts/patchers/cfw_patch_dsc_maxslide.py`, driven by
+// `cfw.py patch-dsc-maxslide <chunks_dir> [--dry-run] [--force]` from
+// `cfw_install.sh` and `cfw-kit/lib/base_stages.sh`.
+//
+// Why the patch exists
+// --------------------
+// The vphone600 26.x kernel reserves SHARED_REGION_SIZE_ARM64 = 0x180000000
+// (6 GiB) at SHARED_REGION_BASE_ARM64 = 0x180000000 (verified by disassembling
+// the arm64 case of the kernel's `shared_region_create`). At map time the kernel
+// needs room for the cache's mapped span PLUS the cache header's `maxSlide` —
+// the ASLR range it will pick a slide from. A newer userland whose cache nearly
+// fills the region overflows it:
+//
+// iOS 27.0 (24A5380h): span 0x17C830000 (~5.95 GiB)
+// + maxSlide 0x20000000 (512 MiB)
+// = 0x19C830000 (~6.46 GiB) > 0x180000000 (6 GiB)
+//
+// `_shared_region_map_and_slide` then returns ENOMEM, dyld cannot map
+// libSystem, and launchd (pid 1) panics: "initproc failed to start -- Library
+// not loaded: /usr/lib/libSystem.B.dylib". Older userlands (26.x / 18.x) fit
+// with their full slide and are unaffected.
+//
+// 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 `DSCCodeSignature.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. `DSCMaxSlidePatcherTests` 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 `DSCChunkSet` 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.
+//
+// On the CLAUDE.md patcher guardrails
+// -----------------------------------
+// There is no instruction here to decode and none to assemble: the patch writes
+// a little-endian u64 metadata field, so Capstone and the Keystone-backed
+// `ARM64Encoder` have nothing to contribute. What replaces them is the
+// structural check in `readHeader`: the field offsets come from
+// `dyld_cache_header` in dyld's `dyld_cache_format.h`, and before they are
+// trusted this code applies dyld's own version gate (`mappingOffset` must reach
+// past the field) and cross-checks the values it reads against the mapping
+// table it parsed independently. A cache whose header does not corroborate the
+// layout is refused rather than written into blind.
+
+import Foundation
+
+/// Zeroes `dyld_cache_header.maxSlide` when the cache would otherwise overflow
+/// the kernel's fixed shared region.
+public enum DSCMaxSlidePatcher {
+ // MARK: - Constants
+
+ /// `SHARED_REGION_SIZE_ARM64` as baked into the PCC vphone600 26.x kernel.
+ /// A cache's span plus its `maxSlide` must fit inside this or the shared
+ /// region map ENOMEMs.
+ public static let kernelSharedRegionSize: UInt64 = 0x1_8000_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:)``.
+ enum HeaderField {
+ /// `char magic[16]` — "dyld_v1" followed by the architecture.
+ static let magic = 0x00
+ /// `uint32_t mappingOffset` — also dyld's own "is this field present"
+ /// gate: a field is present when `mappingOffset` reaches past it.
+ static let mappingOffset = 0x10
+ /// `uint64_t sharedRegionStart`.
+ static let sharedRegionStart = 0xE0
+ /// `uint64_t sharedRegionSize`.
+ static let sharedRegionSize = 0xE8
+ /// `uint64_t maxSlide` — the one field this patcher writes.
+ static let maxSlide = 0xF0
+ }
+
+ /// The `dyld_v1` prefix, checked exactly as the Python checks it: the first
+ /// seven bytes, so any architecture suffix passes.
+ static let magicPrefix = Data("dyld_v1".utf8)
+
+ /// The patch identifier the reference capture records under.
+ public static let patchID = "dsc_maxslide.zero"
+
+ // MARK: - Result
+
+ /// What the gate decided.
+ public enum Outcome: Sendable, Equatable {
+ /// Span + maxSlide already fits the region, and `force` was not set.
+ case fits(combined: UInt64, region: UInt64)
+ /// `maxSlide` was already 0, so there is nothing left to clamp.
+ case alreadyZero
+ /// The cache overflows the region: the patch applies.
+ case overflow(combined: UInt64, region: UInt64)
+ /// The cache fits but `force` was set, so the patch applies anyway.
+ case forced(combined: UInt64, region: UInt64)
+
+ /// True when this outcome means bytes are (or would be) written.
+ public var patches: Bool {
+ switch self {
+ case .fits, .alreadyZero: false
+ case .overflow, .forced: true
+ }
+ }
+
+ /// The sentence the Python prints as its reason, reproduced verbatim so
+ /// the two implementations' logs diff cleanly.
+ var reason: String? {
+ switch self {
+ case .fits, .alreadyZero:
+ nil
+ case let .overflow(combined, region):
+ "overflow: span+maxSlide \(DSCMaxSlidePatcher.hex(combined)) > "
+ + "region \(DSCMaxSlidePatcher.hex(region))"
+ case let .forced(combined, region):
+ "forced: span+maxSlide \(DSCMaxSlidePatcher.hex(combined)) fits "
+ + "region \(DSCMaxSlidePatcher.hex(region)) but --force set"
+ }
+ }
+ }
+
+ /// Everything one run learned and did.
+ public struct Result: Sendable {
+ /// What the gate decided.
+ public let outcome: Outcome
+ /// `dyld_cache_header.sharedRegionStart`, as found.
+ public let sharedRegionStart: UInt64
+ /// `dyld_cache_header.sharedRegionSize`, as found.
+ public let sharedRegionSize: UInt64
+ /// `dyld_cache_header.maxSlide`, as found — before any write.
+ public let maxSlide: UInt64
+ /// The patch, when one applies. Present on a dry run too: the Python
+ /// returns 1 in that case, meaning "this cache needs the patch".
+ public let record: PatchRecord?
+ /// The span that landed on disk, or `nil` on a dry run or a no-op.
+ public let writtenSpan: DSCWriteSpan?
+
+ /// 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.
+ public var didWrite: Bool { writtenSpan != nil }
+ }
+
+ // MARK: - Patching
+
+ /// Clamp `maxSlide` in the cache under `chunksDirectory`.
+ ///
+ /// Self-gating, exactly as the Python is: a cache whose span plus slide
+ /// already fits `kernelRegionSize` is left alone unless `force` is set, and
+ /// a cache already at `maxSlide == 0` is left alone either way. That keeps
+ /// an 18.x / 26.x base untouched even when the install-side `27.*` gate is
+ /// removed, and makes a re-run over an already-patched cache a no-op rather
+ /// than an error.
+ ///
+ /// - Parameters:
+ /// - chunksDirectory: the directory of `dyld_shared_cache_<arch>*` chunks.
+ /// - architecture: cache architecture suffix; `arm64e` on every device
+ /// this project targets.
+ /// - kernelRegionSize: the guest kernel's `SHARED_REGION_SIZE_ARM64`.
+ /// - dryRun: decide and report, but write nothing.
+ /// - force: clamp even when the cache already fits — the `--force` flag
+ /// behind `FORCE_DSC_MAXSLIDE=1`.
+ /// - verbose: print the Python's log lines.
+ @discardableResult
+ public static func patch(
+ chunksDirectory: URL,
+ architecture: String = "arm64e",
+ kernelRegionSize: UInt64 = kernelSharedRegionSize,
+ dryRun: Bool = false,
+ force: Bool = false,
+ verbose: Bool = true
+ ) throws -> Result {
+ let mainChunkName = "dyld_shared_cache_\(architecture)"
+ let mainChunk = chunksDirectory.appendingPathComponent(mainChunkName)
+ // Checked before the chunk set is built so the error names the file the
+ // Python's FileNotFoundError names, rather than the directory.
+ guard FileManager.default.fileExists(atPath: mainChunk.path) else {
+ 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 DSCChunkSet(directory: chunksDirectory, architecture: architecture)
+ let headerVMA = try headerVMA(of: chunks)
+ let header = try readHeader(from: chunks, at: headerVMA, chunkName: mainChunkName)
+
+ if verbose {
+ print(
+ " [.] \(mainChunkName): start=\(hex(header.sharedRegionStart)) "
+ + "size=\(hex(header.sharedRegionSize)) maxSlide=\(hex(header.maxSlide))"
+ )
+ }
+
+ // Python does this in arbitrary-precision arithmetic. A u64 header where
+ // the two fields sum past 2^64 is not a cache, and clamping a field we
+ // evidently cannot parse is worse than saying so.
+ let (combined, overflowed) = header.sharedRegionSize
+ .addingReportingOverflow(header.maxSlide)
+ guard !overflowed else {
+ throw PatcherError.invalidFormat(
+ "\(mainChunk.path): sharedRegionSize \(hex(header.sharedRegionSize)) + maxSlide "
+ + "\(hex(header.maxSlide)) overflows 64 bits; header is not a dyld_cache_header"
+ )
+ }
+
+ let fits = combined <= kernelRegionSize
+ if fits, !force {
+ if verbose {
+ print(
+ " [=] fits: span+maxSlide \(hex(combined)) <= "
+ + "region \(hex(kernelRegionSize)); no change"
+ )
+ }
+ return Result(
+ outcome: .fits(combined: combined, region: kernelRegionSize),
+ sharedRegionStart: header.sharedRegionStart,
+ sharedRegionSize: header.sharedRegionSize,
+ maxSlide: header.maxSlide,
+ record: nil,
+ writtenSpan: nil
+ )
+ }
+ guard header.maxSlide != 0 else {
+ if verbose { print(" [=] maxSlide already 0; no change") }
+ return Result(
+ outcome: .alreadyZero,
+ sharedRegionStart: header.sharedRegionStart,
+ sharedRegionSize: header.sharedRegionSize,
+ maxSlide: header.maxSlide,
+ record: nil,
+ writtenSpan: nil
+ )
+ }
+
+ let outcome: Outcome = fits
+ ? .forced(combined: combined, region: kernelRegionSize)
+ : .overflow(combined: combined, region: kernelRegionSize)
+ let reason = outcome.reason ?? ""
+ if verbose {
+ print(
+ " [+] \(reason); \(dryRun ? "would set" : "set") "
+ + "maxSlide \(hex(header.maxSlide)) -> 0x0"
+ )
+ }
+
+ let fieldVMA = headerVMA &+ UInt64(HeaderField.maxSlide)
+ let originalBytes = littleEndianBytes(header.maxSlide)
+ let patchedBytes = littleEndianBytes(0)
+ let record = PatchRecord(
+ patchID: patchID,
+ component: mainChunkName,
+ fileOffset: HeaderField.maxSlide,
+ virtualAddress: fieldVMA,
+ originalBytes: originalBytes,
+ patchedBytes: patchedBytes,
+ description: "dyld_cache_header maxSlide \(hex(header.maxSlide)) -> 0 (\(reason))"
+ )
+
+ guard !dryRun else {
+ // The Python prints its completion line on a dry run too — the run
+ // did complete, it just wrote nothing. Every log line in this
+ // function is kept identical to the Python's, so a `--dry-run` of
+ // one can be diffed against a `--dry-run` of the other.
+ if verbose { print(" [+] DSC maxSlide patch complete") }
+ return Result(
+ outcome: outcome,
+ sharedRegionStart: header.sharedRegionStart,
+ sharedRegionSize: header.sharedRegionSize,
+ maxSlide: header.maxSlide,
+ record: record,
+ writtenSpan: nil
+ )
+ }
+
+ let span = try chunks.write(at: fieldVMA, patchedBytes)
+
+ // Read the field back through the same addressing the write used, the
+ // way the Python re-reads and unpacks it. A write that reported success
+ // and left the old value is the one failure mode that would boot into
+ // the panic this patch exists to prevent.
+ let readBack = try chunks.bytesAtVMA(fieldVMA, length: 8).loadLE(UInt64.self, at: 0)
+ guard readBack == 0 else {
+ throw PatcherError.patchVerificationFailed(
+ "maxSlide write verify failed: \(hex(readBack))"
+ )
+ }
+
+ // No `DSCCodeSignature.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.
+
+ if verbose { print(" [+] DSC maxSlide patch complete") }
+ return Result(
+ outcome: outcome,
+ sharedRegionStart: header.sharedRegionStart,
+ sharedRegionSize: header.sharedRegionSize,
+ maxSlide: header.maxSlide,
+ record: record,
+ writtenSpan: span
+ )
+ }
+
+ // MARK: - Header
+
+ /// The three header fields the gate runs on.
+ struct Header: Sendable, Equatable {
+ let sharedRegionStart: UInt64
+ let sharedRegionSize: UInt64
+ let maxSlide: UInt64
+ }
+
+ /// The address the main chunk's byte 0 is mapped at.
+ ///
+ /// Derived from the mapping table rather than written down: the header lives
+ /// at file offset 0 of the unsuffixed chunk, so the mapping that carries
+ /// file offset 0 of that chunk is the one that carries the header.
+ static func headerVMA(of chunks: DSCChunkSet) throws -> UInt64 {
+ let main = chunks.mainCacheURL
+ guard let mapping = chunks.mappings.first(where: {
+ $0.chunkURL == main && $0.fileOffset == 0
+ }) else {
+ throw PatcherError.invalidFormat(
+ "\(main.path): no mapping covers the cache header at file offset 0"
+ )
+ }
+ return mapping.address
+ }
+
+ /// Read and corroborate the header fields.
+ ///
+ /// Three checks stand in for the Capstone decode a code patcher would do:
+ ///
+ /// * the `dyld_v1` magic, checked over seven bytes as the Python checks it;
+ /// * dyld's own field-presence gate — `mappingOffset` is where the mapping
+ /// table starts, so the header struct runs out at that offset, and a field
+ /// only exists in this cache version if `mappingOffset` reaches past it;
+ /// * agreement with the mapping table this code parsed on its own:
+ /// `sharedRegionStart` has to be the lowest address the cache maps, and
+ /// `sharedRegionSize` has to cover everything it maps. Both hold on the
+ /// 24A435 arm64e cache (start 0x180000000, size 0x17D504000 against a
+ /// 0x17D500000 span). If they did not, the offsets would be describing
+ /// some other struct and the write would land in an unknown field.
+ static func readHeader(
+ from chunks: DSCChunkSet,
+ at headerVMA: UInt64,
+ chunkName: String
+ ) throws -> Header {
+ let header = try chunks.bytesAtVMA(headerVMA, length: 0x100)
+
+ guard header.prefix(magicPrefix.count) == magicPrefix else {
+ let magic = header.subdata(in: HeaderField.magic ..< (HeaderField.magic + 16))
+ throw PatcherError.invalidFormat(
+ "\(chunkName): not a dyld shared cache (magic=\(magic.hex))"
+ )
+ }
+
+ let mappingOffset = Int(header.loadLE(UInt32.self, at: HeaderField.mappingOffset))
+ let fieldEnd = HeaderField.maxSlide + MemoryLayout<UInt64>.size
+ guard mappingOffset >= fieldEnd else {
+ throw PatcherError.invalidFormat(
+ "\(chunkName): dyld_cache_header ends at \(hex(UInt64(mappingOffset))), before "
+ + "maxSlide at \(hex(UInt64(HeaderField.maxSlide))); this cache version has no "
+ + "maxSlide field"
+ )
+ }
+
+ let parsed = Header(
+ sharedRegionStart: header.loadLE(UInt64.self, at: HeaderField.sharedRegionStart),
+ sharedRegionSize: header.loadLE(UInt64.self, at: HeaderField.sharedRegionSize),
+ maxSlide: header.loadLE(UInt64.self, at: HeaderField.maxSlide)
+ )
+
+ let mapped = chunks.addressRange
+ guard parsed.sharedRegionStart == mapped.lowerBound else {
+ throw PatcherError.invalidFormat(
+ "\(chunkName): sharedRegionStart \(hex(parsed.sharedRegionStart)) is not the "
+ + "cache's lowest mapped address \(hex(mapped.lowerBound)); the header layout "
+ + "is not the one these offsets describe"
+ )
+ }
+ let span = mapped.upperBound &- mapped.lowerBound
+ guard parsed.sharedRegionSize >= span else {
+ throw PatcherError.invalidFormat(
+ "\(chunkName): sharedRegionSize \(hex(parsed.sharedRegionSize)) is smaller than "
+ + "the \(hex(span)) the cache actually maps; the header layout is not the one "
+ + "these offsets describe"
+ )
+ }
+ return parsed
+ }
+
+ // MARK: - Formatting
+
+ /// The 8 bytes a little-endian `uint64_t` field holds for `value`.
+ ///
+ /// Spelled as a value conversion rather than a byte literal: nothing here is
+ /// an instruction, and nothing here should read like one.
+ static func littleEndianBytes(_ value: UInt64) -> Data {
+ withUnsafeBytes(of: value.littleEndian) { Data($0) }
+ }
+
+ /// `0x%X`, matching the Python's f-strings so the two logs diff cleanly.
+ static func hex(_ value: UInt64) -> String {
+ "0x" + String(value, radix: 16, uppercase: true)
+ }
+}
diff --git a/sources/FirmwarePatcher/DSC/Patchers/DSCXPCLWCRPatcher.swift b/sources/FirmwarePatcher/DSC/Patchers/DSCXPCLWCRPatcher.swift
new file mode 100644
index 00000000..16d49793
--- /dev/null
+++ b/sources/FirmwarePatcher/DSC/Patchers/DSCXPCLWCRPatcher.swift
@@ -0,0 +1,435 @@
+// DSCXPCLWCRPatcher.swift — libxpc's Lightweight Code Requirement self-check.
+//
+// Swift port of `scripts/patchers/cfw_patch_xpc_lwcr.py` (`cfw.py
+// patch-xpc-lwcr`). See research/0_binary_patch_comparison.md #15.
+//
+// What breaks
+// -----------
+// iOS 27 introduced XPC "lightweight code requirements": a server pins a code
+// requirement on its listener — `xpc_connection_set_peer_lightweight_code_
+// requirement`, or the Swift `XPCPeerRequirement.hasEntitlement(_:)` wrapper —
+// and libxpc evaluates whether a token satisfies it in
+// `_xpc_token_satisfies_lwcr`. That function calls an internal matcher which
+// returns two things — a `matched` bool in w0 and a `match_result.error_code`
+// in memory — and then hard-asserts that the two agree:
+//
+// bl <matcher> ; w0 = matched
+// ldr wC, [xR] ; wC = match_result.error_code
+// cmp wC, #0 ; AICMR_MATCH == 0
+// cset wC, ne ; wC = (error_code != 0)
+// eor wE, w0, wC ; wE = matched ^ (error_code != 0)
+// tbz wE, #0, <abort> ; _os_crash_msg → brk #1 when they disagree
+//
+// On stock iOS the two always agree. Under the JB's code-signing environment
+// the matcher's query writes `error_code = MATCH(0)` and then returns a failure
+// status, producing the forbidden `(matched = 0, error_code = 0)` pair. libxpc
+// aborts, so every daemon that pins an entitlement peer-requirement at startup
+// — intelligencetasksd, searchpartyd, transparencyd, bluetoothd — crash-loops
+// from boot.
+//
+// The fix
+// -------
+// Make `matched` consistent with `error_code` by construction and drop the
+// abort. The return is derived from `error_code`, which is the matcher's own
+// verdict, and the xor plus the conditional branch become NOPs:
+//
+// cset wC, ne -> cset w0, eq ; w0 = matched = (error_code == 0)
+// eor wE,… -> nop
+// tbz wE,#0,… -> nop ; falls through to the normal return
+//
+// Real allow/deny survives: `error_code` drives it exactly as stock does when
+// the two agree, and only the internally contradictory case is resolved — in
+// favour of "satisfied", because that is what `error_code` said.
+//
+// Nothing here is hardcoded. `_xpc_token_satisfies_lwcr` comes out of the
+// cache's own local-symbol table, the function is disassembled with Capstone,
+// the check is located by the shape of its control flow, and every replacement
+// word comes from `ARM64Encoder` / `ARM64`. The pages the writes dirty are
+// re-attested through `DSCCodeSignature`, because TXM validates the shared
+// cache per 16 KiB page; the resulting cdHash change is accepted by the JB's
+// always-true AMFI cdhash-trust patch.
+
+import Capstone
+import Foundation
+
+/// Patches `_xpc_token_satisfies_lwcr` in the shared cache's libxpc.
+public enum DSCXPCLWCRPatcher {
+ /// The source-level name of the function this patches.
+ public static let symbol = "_xpc_token_satisfies_lwcr"
+
+ /// Spellings to try, in order.
+ ///
+ /// Mach-O prefixes C symbols with an underscore, so a source name that
+ /// already starts with one lands in the symbol table with two. Looking up
+ /// only the single-underscore spelling is how this patch silently skipped
+ /// every iOS 27 build until 2026-08-11, which is why the mangled name is
+ /// tried first and both are tried at all.
+ public static let symbolCandidates = ["__xpc_token_satisfies_lwcr", symbol]
+
+ /// How far into the function to disassemble before giving up.
+ ///
+ /// The real function is 48 instructions and ends in `retab`; the walk stops
+ /// there. This is the ceiling for a build whose epilogue moved, not a size.
+ static let maxInstructions = 160
+
+ /// The record group this patcher writes under, matching `cfw_records`.
+ public static let recordGroup = "xpc_lwcr"
+
+ // MARK: - Outcome
+
+ /// What a run did.
+ public struct Outcome: Sendable {
+ public enum Status: Sendable, Equatable {
+ /// The three sites were rewritten (or, on a dry run, would have been).
+ case patched
+ /// The cache already carries this patch; nothing was written.
+ case alreadyPatched
+ /// No `_xpc_token_satisfies_lwcr` in this cache — a pre-iOS-27
+ /// userland, where there is no LWCR path to break.
+ case symbolAbsent
+ }
+
+ public let status: Status
+ /// Address of `_xpc_token_satisfies_lwcr`, when it was found.
+ public let functionVMA: UInt64?
+ /// The symbol spelling that resolved.
+ public let resolvedName: String?
+ /// One record per site this run changed. Empty for the two no-op statuses.
+ public let records: [PatchRecord]
+
+ /// Sites written — the number the Python prints, and the number the
+ /// parity test compares.
+ public var siteCount: Int { records.count }
+ }
+
+ // MARK: - Entry point
+
+ /// Apply the patch to the cache under `directory`.
+ ///
+ /// Mirrors `patch_xpc_lwcr(chunks_dir, dry_run=)`: a cache without the
+ /// symbol is a no-op rather than a failure, a cache that already carries
+ /// the patch is a no-op too, and a cache that has the symbol but not the
+ /// idiom is an error.
+ @discardableResult
+ public static func apply(
+ directory: URL,
+ dryRun: Bool = false,
+ log: ((String) -> Void)? = DSCCodeSignature.stderrLog
+ ) throws -> Outcome {
+ let chunks = try DSCChunkSet(directory: directory)
+ return try apply(chunks: chunks, dryRun: dryRun, log: log)
+ }
+
+ /// Apply the patch to an already-open cache.
+ ///
+ /// Re-attestation goes through `reattestRecordedWrites(in:)`, so it covers
+ /// every page this chunk set has been written through — this patcher's
+ /// three words, and anything an earlier patcher wrote and has not yet
+ /// re-attested. A caller batching patchers that wants the pages split per
+ /// patcher calls `clearRecordedWrites()` between them.
+ @discardableResult
+ public static func apply(
+ chunks: DSCChunkSet,
+ dryRun: Bool = false,
+ log: ((String) -> Void)? = DSCCodeSignature.stderrLog
+ ) throws -> Outcome {
+ log?(" [.] \(chunks.directory.path) — \(chunks.chunkURLs.count) chunk(s), "
+ + "\(chunks.mappings.count) mapping(s)")
+
+ // Self-gating: the LWCR path only exists on iOS 27+ libxpc, so on an
+ // older userland the symbol is simply absent and there is nothing to
+ // patch. A *missing* `.symbols` file is a different answer and throws.
+ var functionVMA: UInt64?
+ var resolvedName: String?
+ for candidate in symbolCandidates {
+ if let address = try chunks.resolveLocalSymbol(candidate) {
+ functionVMA = address
+ resolvedName = candidate
+ break
+ }
+ }
+ guard let functionVMA, let resolvedName else {
+ log?(" [=] \(symbol) not present (pre-iOS-27 userland); nothing to patch")
+ return Outcome(
+ status: .symbolAbsent,
+ functionVMA: nil,
+ resolvedName: nil,
+ records: []
+ )
+ }
+ log?(" [.] \(resolvedName) @ 0x\(hex(functionVMA))")
+
+ let disassembler = ARM64Disassembler()
+ let instructions = try disassembleFunction(
+ in: chunks,
+ at: functionVMA,
+ disassembler: disassembler
+ )
+
+ guard let site = findConsistencyCheck(in: instructions, disassembler: disassembler) else {
+ if let already = findPatchedShape(in: instructions, disassembler: disassembler) {
+ log?(" [=] already patched at 0x\(hex(already.address)) "
+ + "(cset w0,eq; nop; nop); nothing to patch/re-attest")
+ log?(" [+] libxpc LWCR self-check patch complete")
+ return Outcome(
+ status: .alreadyPatched,
+ functionVMA: functionVMA,
+ resolvedName: resolvedName,
+ records: []
+ )
+ }
+ throw PatcherError.patchSiteNotFound(
+ "\(symbol): LWCR consistency idiom (cset wC,ne; eor wE,w0,wC; tbz wE,#0) "
+ + "not found at 0x\(hex(functionVMA))"
+ )
+ }
+
+ for (label, insn) in [("cset", site.cset), ("eor ", site.eor), ("tbz ", site.tbz)] {
+ log?(" [.] \(label) @ 0x\(hex(insn.address)): \(text(insn))")
+ }
+
+ // Every replacement word comes from the encoders, never from a literal.
+ guard let csetW0EQ = ARM64Encoder.encodeCsetW(rd: 0, condition: .eq) else {
+ throw PatcherError.patchVerificationFailed("could not encode `cset w0, eq`")
+ }
+ let edits: [Edit] = [
+ Edit(address: site.cset.address, bytes: csetW0EQ, label: "cset w0, eq"),
+ Edit(address: site.eor.address, bytes: ARM64.nop, label: "nop"),
+ Edit(address: site.tbz.address, bytes: ARM64.nop, label: "nop"),
+ ]
+
+ var records: [PatchRecord] = []
+ var wrote = false
+ for edit in edits {
+ let current = try chunks.bytesAtVMA(edit.address, length: edit.bytes.count)
+ if current == edit.bytes {
+ log?(" [=] already patched at 0x\(hex(edit.address)) (\(edit.label))")
+ continue
+ }
+ log?(" [+] \(dryRun ? "would write" : "wrote") \(edit.label) "
+ + "at 0x\(hex(edit.address)) (\(current.hex) -> \(edit.bytes.hex))")
+ if !dryRun {
+ try chunks.write(at: edit.address, edit.bytes)
+ wrote = true
+ }
+ let location = chunks.findChunk(forVMA: edit.address)
+ records.append(record(
+ for: edit,
+ original: current,
+ chunkName: location?.chunkURL.lastPathComponent ?? chunks.directory.lastPathComponent,
+ fileOffset: location?.fileOffset ?? 0,
+ disassembler: disassembler
+ ))
+ }
+
+ if wrote {
+ log?(" [.] re-attesting modified page(s)...")
+ try DSCCodeSignature.reattestRecordedWrites(in: chunks, dryRun: false, log: log)
+ for edit in edits {
+ let readBack = try chunks.bytesAtVMA(edit.address, length: edit.bytes.count)
+ guard readBack == edit.bytes else {
+ throw PatcherError.patchVerificationFailed(
+ "post-write verify failed at 0x\(hex(edit.address))"
+ )
+ }
+ }
+ } else if dryRun, !records.isEmpty {
+ log?(" [.] dry-run: would re-attest page for "
+ + records.map { "0x\(hex($0.virtualAddress ?? 0))" }.joined(separator: ", "))
+ }
+
+ log?(" [+] libxpc LWCR self-check patch complete")
+ return Outcome(
+ status: records.isEmpty ? .alreadyPatched : .patched,
+ functionVMA: functionVMA,
+ resolvedName: resolvedName,
+ records: records
+ )
+ }
+
+ // MARK: - Site discovery
+
+ /// The three instructions the patch rewrites.
+ struct ConsistencyCheck {
+ let cset: Instruction
+ let eor: Instruction
+ let tbz: Instruction
+ }
+
+ /// Locate the LWCR self-consistency idiom.
+ ///
+ /// cset wC, ne
+ /// eor wE, w0, wC
+ /// tbz wE, #0, <abort>
+ ///
+ /// Anchored on the `eor`, because that is the only instruction in the
+ /// function that xors the matcher's return register with anything: the
+ /// `cset` and the `tbz` are common shapes on their own, and the register
+ /// dataflow between the three is what makes the match unambiguous.
+ static func findConsistencyCheck(
+ in instructions: [Instruction],
+ disassembler: ARM64Disassembler
+ ) -> ConsistencyCheck? {
+ guard instructions.count >= 2 else { return nil }
+ for index in 0 ..< (instructions.count - 1) {
+ let eor = instructions[index]
+ guard eor.mnemonic == "eor",
+ let destination = register(eor, 0, disassembler),
+ let left = register(eor, 1, disassembler),
+ let source = register(eor, 2, disassembler),
+ left == "w0"
+ else { continue }
+
+ // `tbz wE, #0` — bit 0 of the xor, i.e. "the two disagree".
+ let tbz = instructions[index + 1]
+ guard tbz.mnemonic == "tbz",
+ register(tbz, 0, disassembler) == destination,
+ let bit = immediate(tbz, 1), bit == 0
+ else { continue }
+
+ // The `cset wC, ne` feeding the xor, within a short window back.
+ var cset: Instruction?
+ var back = index - 1
+ while back >= 0, back >= index - 5 {
+ let candidate = instructions[back]
+ if candidate.mnemonic == "cset", register(candidate, 0, disassembler) == source {
+ // The condition is read off Capstone's decode, not the
+ // printed operand text.
+ if candidate.aarch64?.conditionCode == AArch64CC_NE { cset = candidate }
+ break
+ }
+ back -= 1
+ }
+ guard let cset else { continue }
+ return ConsistencyCheck(cset: cset, eor: eor, tbz: tbz)
+ }
+ return nil
+ }
+
+ /// Locate the shape this patch itself leaves behind, so a second run over
+ /// an installed cache reports a no-op instead of failing.
+ ///
+ /// cmp wX, #0 ; error_code == AICMR_MATCH
+ /// cset w0, eq ; the replacement for `cset wC, ne`
+ /// nop ; was eor wE, w0, wC
+ /// nop ; was tbz wE, #0, <abort>
+ ///
+ /// The per-edit byte comparison in `apply` cannot stand in for this: it
+ /// needs addresses that `findConsistencyCheck` has to supply first, and
+ /// that search looks for the very instructions this patch replaced. On an
+ /// already-patched cache the idiom is gone by construction.
+ static func findPatchedShape(
+ in instructions: [Instruction],
+ disassembler: ARM64Disassembler
+ ) -> Instruction? {
+ guard instructions.count >= 3 else { return nil }
+ for index in 0 ..< (instructions.count - 2) {
+ let cset = instructions[index]
+ guard cset.mnemonic == "cset",
+ register(cset, 0, disassembler) == "w0",
+ cset.aarch64?.conditionCode == AArch64CC_EQ,
+ instructions[index + 1].mnemonic == "nop",
+ instructions[index + 2].mnemonic == "nop"
+ else { continue }
+
+ // The `cmp wX, #0` feeding it keeps this from matching an unrelated
+ // `cset w0, eq` that happens to sit in front of padding.
+ var back = index - 1
+ while back >= 0, back >= index - 4 {
+ let candidate = instructions[back]
+ guard candidate.mnemonic == "cmp" else {
+ back -= 1
+ continue
+ }
+ let operands = candidate.aarch64?.operands ?? []
+ if operands.count == 2, let value = immediate(candidate, 1), value == 0 {
+ return cset
+ }
+ break
+ }
+ }
+ return nil
+ }
+
+ // MARK: - Disassembly
+
+ /// Disassemble from `vma` up to the function's `ret`/`retab`, or
+ /// `maxInstructions`, whichever comes first.
+ ///
+ /// The read is allowed to come up short so a function that sits near the
+ /// end of its mapping still disassembles as far as the mapping goes,
+ /// instead of failing the whole patch on a window that overshoots.
+ static func disassembleFunction(
+ in chunks: DSCChunkSet,
+ at vma: UInt64,
+ disassembler: ARM64Disassembler
+ ) throws -> [Instruction] {
+ let window = try chunks.readAtVMA(vma, length: maxInstructions * 4, allowShort: true)
+ var result: [Instruction] = []
+ for insn in disassembler.disassemble(window, at: vma) {
+ result.append(insn)
+ if insn.mnemonic == "ret" || insn.mnemonic == "retab" { break }
+ }
+ return result
+ }
+
+ // MARK: - Operand helpers
+
+ /// Canonical name of operand `index` when it is a register, else `nil`.
+ static func register(
+ _ insn: Instruction,
+ _ index: Int,
+ _ disassembler: ARM64Disassembler
+ ) -> String? {
+ guard let operands = insn.aarch64?.operands, index < operands.count else { return nil }
+ let operand = operands[index]
+ guard operand.type == AARCH64_OP_REG else { return nil }
+ return disassembler.registerName(UInt32(operand.reg.rawValue))
+ }
+
+ /// Value of operand `index` when it is an immediate, else `nil`.
+ static func immediate(_ insn: Instruction, _ index: Int) -> Int64? {
+ guard let operands = insn.aarch64?.operands, index < operands.count else { return nil }
+ let operand = operands[index]
+ guard operand.type == AARCH64_OP_IMM else { return nil }
+ return operand.imm
+ }
+
+ // MARK: - Records and formatting
+
+ struct Edit {
+ let address: UInt64
+ let bytes: Data
+ let label: String
+ }
+
+ private static func record(
+ for edit: Edit,
+ original: Data,
+ chunkName: String,
+ fileOffset: Int,
+ disassembler: ARM64Disassembler
+ ) -> PatchRecord {
+ PatchRecord(
+ patchID: "\(recordGroup).\(edit.label.split(separator: " ").first ?? "")"
+ + "@0x\(hex(edit.address))",
+ component: chunkName,
+ fileOffset: fileOffset,
+ virtualAddress: edit.address,
+ originalBytes: original,
+ patchedBytes: edit.bytes,
+ beforeDisasm: disassembler.disassembleOne(original, at: edit.address).map(text) ?? "",
+ afterDisasm: disassembler.disassembleOne(edit.bytes, at: edit.address).map(text) ?? "",
+ description: "\(symbol): `\(edit.label)` — derive matched from error_code "
+ + "and drop the abort"
+ )
+ }
+
+ private static func text(_ insn: Instruction) -> String {
+ insn.operandString.isEmpty ? insn.mnemonic : "\(insn.mnemonic) \(insn.operandString)"
+ }
+
+ private static func hex(_ value: UInt64) -> String {
+ String(value, radix: 16, uppercase: true)
+ }
+}
diff --git a/tests/FirmwarePatcherTests/DSCCameraPatcherTests.swift b/tests/FirmwarePatcherTests/DSCCameraPatcherTests.swift
new file mode 100644
index 00000000..8ee1a19f
--- /dev/null
+++ b/tests/FirmwarePatcherTests/DSCCameraPatcherTests.swift
@@ -0,0 +1,686 @@
+// DSCCameraPatcherTests.swift — Parity gate for the camera DSC patcher.
+//
+// The claim these tests exist to defend is narrow and checkable: running
+// `scripts/patchers/cfw_patch_camera_dsc.py` on one clone of the real shared
+// cache and `DSCCameraPatcher` on another leaves the two clones byte for byte
+// identical, across all 79 chunk files — patched instructions, rewritten code
+// slots and everything neither touched. Nothing here asserts against a number
+// this repo wrote down once; the Python is run for real and its output is the
+// reference.
+//
+// The tests need the real cache. `VPHONE_DSC_PRISTINE` points at a directory of
+// `dyld_shared_cache_arm64e*` chunks, defaulting to
+// `ipsws/ref_extract/dsc_pristine`.
+//
+// Without it they FAIL. A bare `return` in place of a fixture is reported by
+// Swift Testing as a pass, so "the camera port is green" would be equally
+// compatible with "the camera port was never run". A machine that genuinely
+// cannot carry the 6.7 GB fixture sets `VPHONE_DSC_FIXTURE_OPTIONAL=1`, which
+// turns the failure into a visible *skip*.
+//
+// Nothing here writes into the pristine directory, or anywhere else in the
+// working tree. Clones go to the system temp directory — `clonefile`, so
+// instant and near-free on APFS — and are discarded afterwards.
+// `VPHONE_DSC_SCRATCH` moves them somewhere else on the same volume.
+
+@testable import FirmwarePatcher
+import CryptoKit
+import Foundation
+import Testing
+
+// MARK: - Fixture discovery
+
+private enum CameraFixture {
+ static let repoRoot = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+
+ /// The read-only reference cache.
+ static var pristine: URL? {
+ let url = ProcessInfo.processInfo.environment["VPHONE_DSC_PRISTINE"]
+ .map { URL(fileURLWithPath: $0) }
+ ?? repoRoot.appendingPathComponent("ipsws/ref_extract/dsc_pristine")
+ let main = url.appendingPathComponent("dyld_shared_cache_arm64e")
+ return FileManager.default.fileExists(atPath: main.path) ? url : nil
+ }
+
+ /// Opt-out for a machine that cannot carry the fixture. Set it and the suite
+ /// reports as skipped; leave it unset and a missing cache is a failure,
+ /// which is the only reading of "green" a byte-parity gate can afford.
+ static var isOptional: Bool {
+ ProcessInfo.processInfo.environment["VPHONE_DSC_FIXTURE_OPTIONAL"] == "1"
+ }
+
+ static var runs: Bool { pristine != nil || !isOptional }
+
+ static let missing: Comment = """
+ the real 24A435 arm64e shared cache is required — put it at \
+ ipsws/ref_extract/dsc_pristine, point VPHONE_DSC_PRISTINE at it, or set \
+ VPHONE_DSC_FIXTURE_OPTIONAL=1 to skip these tests instead of failing
+ """
+
+ static let skipReason: Comment =
+ "VPHONE_DSC_FIXTURE_OPTIONAL=1 and no dyld_shared_cache_arm64e fixture present"
+
+ /// Where clones are made. Outside the working tree by default: the
+ /// reference extract is what every other DSC suite compares against, and a
+ /// scratch directory has no business living inside it.
+ static var scratchRoot: URL {
+ ProcessInfo.processInfo.environment["VPHONE_DSC_SCRATCH"]
+ .map { URL(fileURLWithPath: $0) }
+ ?? URL(fileURLWithPath: NSTemporaryDirectory())
+ .appendingPathComponent("vphone-dsc-camera")
+ }
+
+ /// The project venv, which is where the reference Python lives.
+ static var python: URL? {
+ let url = repoRoot.appendingPathComponent(".venv/bin/python3")
+ return FileManager.default.fileExists(atPath: url.path) ? url : nil
+ }
+
+ /// `ipsw`, which the reference Python shells out to for symbol resolution.
+ /// The Swift port does not need it; running the reference does.
+ static var ipswDirectory: String? {
+ for candidate in ["/opt/homebrew/bin", "/usr/local/bin"]
+ where FileManager.default.isExecutableFile(atPath: candidate + "/ipsw")
+ {
+ return candidate
+ }
+ return nil
+ }
+
+ /// Clone the pristine cache into a fresh directory the caller may write to.
+ static func cloneCache(named name: String) throws -> URL {
+ let pristine = try #require(pristine, missing)
+ let destination = scratchRoot.appendingPathComponent(name)
+ try? FileManager.default.removeItem(at: destination)
+ try FileManager.default.createDirectory(
+ at: destination,
+ withIntermediateDirectories: true
+ )
+ let result = try CameraSubprocess.run(
+ executable: URL(fileURLWithPath: "/bin/cp"),
+ arguments: ["-c", "-R"]
+ + (try FileManager.default.contentsOfDirectory(atPath: pristine.path))
+ .sorted()
+ .map { pristine.appendingPathComponent($0).path }
+ + [destination.path]
+ )
+ #expect(result.status == 0, "cp -c failed: \(result.stderr)")
+ return destination
+ }
+
+ /// Discard clones, and the scratch root with them once the last one is gone.
+ ///
+ /// `VPHONE_DSC_KEEP_CLONES=1` leaves them behind, so the same comparison
+ /// this suite makes with SHA-256 can be redone from a shell with `cmp`.
+ /// They are clones, so keeping them costs only what the patches changed.
+ static func discard(_ clones: URL...) {
+ guard ProcessInfo.processInfo.environment["VPHONE_DSC_KEEP_CLONES"] != "1" else {
+ return
+ }
+ for clone in clones {
+ try? FileManager.default.removeItem(at: clone)
+ }
+ let remaining = (try? FileManager.default
+ .contentsOfDirectory(atPath: scratchRoot.path)) ?? []
+ if remaining.isEmpty {
+ try? FileManager.default.removeItem(at: scratchRoot)
+ }
+ }
+
+ /// SHA-256 of every file in a cache directory, keyed by name.
+ ///
+ /// Streamed, because the cache is 6.7 GB and reading it into `Data` would
+ /// be a different kind of test failure.
+ static func digests(of directory: URL) throws -> [String: String] {
+ var result: [String: String] = [:]
+ for name in try FileManager.default.contentsOfDirectory(atPath: directory.path).sorted() {
+ let handle = try FileHandle(forReadingFrom: directory.appendingPathComponent(name))
+ defer { try? handle.close() }
+ var hasher = SHA256()
+ while let block = try handle.read(upToCount: 8 * 1024 * 1024), !block.isEmpty {
+ hasher.update(data: block)
+ }
+ result[name] = Data(hasher.finalize()).hex
+ }
+ return result
+ }
+}
+
+// MARK: - Subprocess helper
+
+private enum CameraSubprocess {
+ struct Result {
+ let status: Int32
+ let stdout: String
+ let stderr: String
+ }
+
+ @discardableResult
+ static func run(
+ executable: URL,
+ arguments: [String],
+ environment: [String: String]? = nil
+ ) throws -> Result {
+ let process = Process()
+ process.executableURL = executable
+ process.arguments = arguments
+ if let environment { process.environment = environment }
+ let out = Pipe()
+ let err = Pipe()
+ process.standardOutput = out
+ process.standardError = err
+ try process.run()
+ // Drain before waiting: a full pipe buffer would deadlock the patcher.
+ let outData = out.fileHandleForReading.readDataToEndOfFile()
+ let errData = err.fileHandleForReading.readDataToEndOfFile()
+ process.waitUntilExit()
+ return Result(
+ status: process.terminationStatus,
+ stdout: String(decoding: outData, as: UTF8.self),
+ stderr: String(decoding: errData, as: UTF8.self)
+ )
+ }
+}
+
+// MARK: - The reference Python, run for real
+
+private enum CameraReference {
+ /// Run `cfw_patch_camera_dsc.py` over `cache`, exactly as
+ /// `patch_camera_userland.sh dsc` does.
+ @discardableResult
+ static func run(on cache: URL, extraArguments: [String] = []) throws -> CameraSubprocess.Result {
+ let python = try #require(CameraFixture.python, "project venv is required for the cross-check")
+ let ipswDirectory = try #require(
+ CameraFixture.ipswDirectory,
+ "`ipsw` is required to run the reference Python (the Swift port does not use it)"
+ )
+ var environment = ProcessInfo.processInfo.environment
+ environment["PATH"] = ipswDirectory + ":/usr/bin:/bin:/usr/sbin:/sbin"
+ let result = try CameraSubprocess.run(
+ executable: python,
+ arguments: [
+ CameraFixture.repoRoot
+ .appendingPathComponent("scripts/patchers/cfw_patch_camera_dsc.py").path,
+ cache.path,
+ cache.appendingPathComponent("dyld_shared_cache_arm64e").path,
+ ] + extraArguments,
+ environment: environment
+ )
+ #expect(result.status == 0, "reference Python failed: \(result.stderr)")
+ return result
+ }
+
+ /// The sites the reference reported, as `symbol -> "before → after"`.
+ ///
+ /// Parsed off the two lines it prints per site rather than off a count, so
+ /// a run that silently patched five of six cannot pass as six.
+ static func sites(in output: String) -> [String: (before: String, after: String)] {
+ var sites: [String: (String, String)] = [:]
+ var pendingSymbol: String?
+ for rawLine in output.split(separator: "\n", omittingEmptySubsequences: false) {
+ let line = String(rawLine)
+ let trimmed = line.trimmingCharacters(in: .whitespaces)
+ if trimmed.hasPrefix("+["), let at = trimmed.range(of: " @ 0x") {
+ pendingSymbol = String(trimmed[trimmed.startIndex ..< at.lowerBound])
+ continue
+ }
+ if let symbol = pendingSymbol, trimmed.contains("→") {
+ let halves = trimmed.components(separatedBy: "→")
+ if halves.count == 2 {
+ sites[symbol] = (
+ halves[0].trimmingCharacters(in: .whitespaces),
+ halves[1].trimmingCharacters(in: .whitespaces)
+ )
+ }
+ pendingSymbol = nil
+ }
+ }
+ return sites
+ }
+
+ /// `_sym_slug` from the reference module, for the six real symbols.
+ static func symbolSlugs(for symbols: [String]) throws -> [String] {
+ let python = try #require(CameraFixture.python)
+ let result = try CameraSubprocess.run(
+ executable: python,
+ arguments: [
+ "-c",
+ """
+ import json, sys
+ sys.path.insert(0, sys.argv[1])
+ from cfw_patch_camera_dsc import _sym_slug
+ print(json.dumps([_sym_slug(s) for s in json.loads(sys.argv[2])]))
+ """,
+ CameraFixture.repoRoot.appendingPathComponent("scripts/patchers").path,
+ String(decoding: try JSONSerialization.data(withJSONObject: symbols), as: UTF8.self),
+ ]
+ )
+ #expect(result.status == 0, "python _sym_slug failed: \(result.stderr)")
+ return try JSONDecoder().decode([String].self, from: Data(result.stdout.utf8))
+ }
+
+ /// What keystone assembles for a source string, through the module the
+ /// patchers use.
+ static func assemble(_ source: String) throws -> String {
+ let python = try #require(CameraFixture.python)
+ let result = try CameraSubprocess.run(
+ executable: python,
+ arguments: [
+ "-c",
+ """
+ import sys
+ sys.path.insert(0, sys.argv[1])
+ from cfw_asm import asm
+ print(asm(sys.argv[2]).hex())
+ """,
+ CameraFixture.repoRoot.appendingPathComponent("scripts/patchers").path,
+ source,
+ ]
+ )
+ #expect(result.status == 0, "keystone failed: \(result.stderr)")
+ return result.stdout.trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+}
+
+// MARK: - The parity gate
+
+@Suite(.serialized, .enabled(if: CameraFixture.runs, CameraFixture.skipReason))
+struct DSCCameraPatcherParityTests {
+ /// The gate. Two clones, two implementations, one byte-for-byte comparison
+ /// across every chunk file in the cache.
+ @Test("Swift and Python leave the real cache byte-identical")
+ func swiftAndPythonAgreeByteForByte() throws {
+ _ = try #require(CameraFixture.pristine, CameraFixture.missing)
+
+ let swiftSide = try CameraFixture.cloneCache(named: "camera_swift")
+ let pythonSide = try CameraFixture.cloneCache(named: "camera_python")
+ defer { CameraFixture.discard(swiftSide, pythonSide) }
+
+ // The reference, run for real.
+ let referenceOutput = try CameraReference.run(on: pythonSide).stdout
+ let referenceSites = CameraReference.sites(in: referenceOutput)
+ #expect(
+ referenceSites.count == 6,
+ "the reference reported \(referenceSites.count) sites, not 6"
+ )
+
+ // The port.
+ var log: [String] = []
+ let result = try DSCCameraPatcher.applyAll(
+ chunksDirectory: swiftSide,
+ log: { log.append($0) }
+ )
+ #expect(result.siteCount == 6, "the port wrote \(result.siteCount) sites, not 6")
+ #expect(result.isComplete)
+ #expect(result.sites.allSatisfy { !$0.wasAlreadyPatched })
+
+ // Same addresses, same bytes before, same bytes after — checked against
+ // what the reference printed, not against what the port believes.
+ for site in result.sites {
+ let theirs = try #require(
+ referenceSites[site.symbol],
+ "the reference did not report \(site.symbol)"
+ )
+ #expect(site.originalBytes.hex == theirs.before, "\(site.symbol) original bytes")
+ #expect(site.patchedBytes.hex == theirs.after, "\(site.symbol) patched bytes")
+ #expect(
+ referenceOutput.contains("@ 0x\(String(site.vma, radix: 16, uppercase: true))"),
+ "the reference did not report \(site.symbol) at the port's address"
+ )
+ }
+
+ // And the caches themselves, whole.
+ let mine = try CameraFixture.digests(of: swiftSide)
+ let theirs = try CameraFixture.digests(of: pythonSide)
+ #expect(mine.keys.sorted() == theirs.keys.sorted())
+ var differing: [String] = []
+ for (name, digest) in mine.sorted(by: { $0.key < $1.key })
+ where theirs[name] != digest
+ {
+ differing.append(name)
+ }
+ #expect(differing.isEmpty, "chunks differ after patching: \(differing)")
+ #expect(mine.count >= 79, "only \(mine.count) chunk files were compared")
+
+ // The comparison is only worth anything if the two caches moved at all.
+ let pristineDigests = try CameraFixture.digests(
+ of: try #require(CameraFixture.pristine)
+ )
+ let changed = mine.filter { pristineDigests[$0.key] != $0.value }.keys.sorted()
+ #expect(
+ changed.count == 2,
+ "expected both families to land in their own chunk; changed: \(changed)"
+ )
+
+ print("[camera parity] \(result.siteCount) sites, "
+ + "\(result.reattestation?.updated.count ?? 0) slots rewritten, "
+ + "\(mine.count) chunk files identical to the Python's")
+ print("[camera parity] chunks that changed: \(changed.joined(separator: ", "))")
+ for line in log where line.contains("re-attest: wrote") { print(line) }
+ }
+
+ /// The reference re-attests per family off bare addresses; this re-attests
+ /// once at the end off recorded spans. Same pages on this cache — which is
+ /// worth checking rather than assuming, because it is the only reason the
+ /// two runs can come out identical.
+ @Test("The port re-attests exactly the pages the reference does")
+ func reattestedPagesMatchTheReference() throws {
+ _ = try #require(CameraFixture.pristine, CameraFixture.missing)
+
+ let swiftSide = try CameraFixture.cloneCache(named: "camera_pages_swift")
+ let pythonSide = try CameraFixture.cloneCache(named: "camera_pages_python")
+ defer { CameraFixture.discard(swiftSide, pythonSide) }
+
+ let referenceOutput = try CameraReference.run(on: pythonSide).stdout
+ var referencePages: Set<String> = []
+ for rawLine in referenceOutput.split(separator: "\n") {
+ let line = String(rawLine)
+ guard line.contains("re-attest: wrote slot ") else { continue }
+ let parts = line.components(separatedBy: "re-attest: wrote slot ")
+ guard parts.count == 2 else { continue }
+ let fields = parts[1].split(separator: " ")
+ guard fields.count >= 3 else { continue }
+ referencePages.insert("\(fields[2]):\(fields[0])")
+ }
+ #expect(!referencePages.isEmpty, "the reference re-attested nothing")
+
+ let result = try DSCCameraPatcher.applyAll(chunksDirectory: swiftSide, log: nil)
+ let minePages = Set(
+ (result.reattestation?.updated ?? []).map {
+ "\($0.chunkURL.lastPathComponent):\($0.pageIndex)"
+ }
+ )
+ #expect(minePages == referencePages, "swift \(minePages.sorted()) vs python \(referencePages.sorted())")
+ print("[camera pages] \(minePages.sorted().joined(separator: ", "))")
+ }
+
+ /// Patch ids feed `cfw_records`, which is what a captured reference is
+ /// keyed on. A port that renames them writes records nothing lines up with.
+ @Test("Patch ids match the reference's _sym_slug")
+ func patchIDsMatchTheReference() throws {
+ _ = try #require(CameraFixture.pristine, CameraFixture.missing)
+
+ let symbols = DSCCameraPatcher.styleTransferSymbols
+ + [DSCCameraPatcher.authorizationStatusSymbol]
+ let theirs = try CameraReference.symbolSlugs(for: symbols)
+ let mine = symbols.map(DSCCameraPatcher.symbolSlug)
+ #expect(mine == theirs)
+ #expect(
+ mine.first == "NUStyleTransferProcessor_processWithInputs_arguments_output_error"
+ )
+ print("[camera slugs] \(mine.count) ids agreed, e.g. camera_dsc.nu_styletransfer.\(mine[0])")
+ }
+
+ /// Both replacements come out of the Keystone-checked encoders, and both
+ /// have to be what keystone itself assembles.
+ @Test("Both replacements are the bytes keystone assembles")
+ func replacementsMatchKeystone() throws {
+ _ = try #require(CameraFixture.python, "project venv is required for the cross-check")
+
+ let styleTransfer = try DSCCameraPatcher.replacement(
+ returning: DSCCameraPatcher.Family.neutrinoStyleTransfer.returnValue
+ )
+ let authorization = try DSCCameraPatcher.replacement(
+ returning: DSCCameraPatcher.Family.avfAuthorization.returnValue
+ )
+ let keystoneStyleTransfer = try CameraReference.assemble("mov w0, #0\nret")
+ let keystoneAuthorization = try CameraReference.assemble("mov w0, #3\nret")
+ #expect(styleTransfer.hex == keystoneStyleTransfer)
+ #expect(authorization.hex == keystoneAuthorization)
+ #expect(styleTransfer.count == 8)
+ #expect(authorization.count == 8)
+ print("[camera bytes] mov w0,#0;ret = \(styleTransfer.hex), mov w0,#3;ret = \(authorization.hex)")
+ }
+}
+
+// MARK: - Behaviour the reference does not pin
+
+@Suite(.serialized, .enabled(if: CameraFixture.runs, CameraFixture.skipReason))
+struct DSCCameraPatcherBehaviourTests {
+ @Test("A dry run finds every site and writes nothing")
+ func dryRunWritesNothing() throws {
+ let pristine = try #require(CameraFixture.pristine, CameraFixture.missing)
+
+ let clone = try CameraFixture.cloneCache(named: "camera_dryrun")
+ defer { CameraFixture.discard(clone) }
+
+ let result = try DSCCameraPatcher.applyAll(
+ chunksDirectory: clone,
+ dryRun: true,
+ log: nil
+ )
+ #expect(result.siteCount == 6)
+ #expect(result.dryRun)
+ #expect(result.reattestation == nil)
+ #expect(!result.isComplete, "a dry run is never a completed patch")
+
+ let after = try CameraFixture.digests(of: clone)
+ let before = try CameraFixture.digests(of: pristine)
+ #expect(after == before, "a dry run touched the cache")
+ print("[camera dry run] \(result.siteCount) sites reported, \(after.count) files unchanged")
+ }
+
+ @Test("AVF-only mode patches one site and leaves NeutrinoCore alone")
+ func avfOnlyPatchesOneSite() throws {
+ let pristine = try #require(CameraFixture.pristine, CameraFixture.missing)
+
+ let clone = try CameraFixture.cloneCache(named: "camera_avf_only")
+ defer { CameraFixture.discard(clone) }
+
+ let result = try DSCCameraPatcher.applyAVFAuthorizationOnly(
+ chunksDirectory: clone,
+ log: nil
+ )
+ #expect(result.siteCount == 1)
+ #expect(result.sites.first?.family == .avfAuthorization)
+ #expect(result.sites.first?.symbol == DSCCameraPatcher.authorizationStatusSymbol)
+ #expect(result.isComplete)
+
+ // Exactly one chunk moved — the one AVFCapture lives in.
+ let after = try CameraFixture.digests(of: clone)
+ let before = try CameraFixture.digests(of: pristine)
+ let changed = after.filter { before[$0.key] != $0.value }.keys.sorted()
+ #expect(changed.count == 1, "avf-only changed \(changed)")
+
+ // And the NeutrinoCore entry points still carry their signed prologue.
+ let chunks = try DSCChunkSet(directory: clone)
+ let resolver = try DSCSymbolResolver(chunks: chunks)
+ let untouched = try resolver.addresses(
+ of: DSCCameraPatcher.styleTransferSymbols,
+ inImage: DSCCameraPatcher.Family.neutrinoStyleTransfer.imagePath
+ )
+ for (symbol, vma) in untouched {
+ let head = try chunks.bytesAtVMA(vma, length: 4)
+ #expect(head == ARM64.pacibsp, "\(symbol) was rewritten by avf-only mode")
+ }
+ print("[camera avf-only] 1 site, chunk \(changed[0]), 5 NeutrinoCore prologues intact")
+ }
+
+ /// Three sibling DSC gates shipped a version that raised on their own
+ /// output. This one recognises it.
+ @Test("A second run over an already-patched cache is inert, not an error")
+ func reRunIsIdempotent() throws {
+ _ = try #require(CameraFixture.pristine, CameraFixture.missing)
+
+ let clone = try CameraFixture.cloneCache(named: "camera_idempotent")
+ defer { CameraFixture.discard(clone) }
+
+ let first = try DSCCameraPatcher.applyAll(chunksDirectory: clone, log: nil)
+ #expect(first.siteCount == 6)
+ #expect(first.sites.allSatisfy { !$0.wasAlreadyPatched })
+ let afterFirst = try CameraFixture.digests(of: clone)
+
+ let second = try DSCCameraPatcher.applyAll(chunksDirectory: clone, log: nil)
+ #expect(second.siteCount == 6)
+ #expect(
+ second.sites.allSatisfy { $0.wasAlreadyPatched },
+ "a re-run did not recognise its own output"
+ )
+ #expect(second.reattestation?.updated.isEmpty == true, "a re-run rewrote slot hashes")
+ #expect(second.isComplete)
+
+ let afterSecond = try CameraFixture.digests(of: clone)
+ #expect(afterSecond == afterFirst, "a re-run changed the cache")
+ print("[camera idempotence] second run: 6 sites recognised as already patched, 0 slots rewritten")
+ }
+
+ /// A failure in the second family must not leave the first family's writes
+ /// on disk, because nothing would have re-attested the pages they dirtied.
+ ///
+ /// This is the shape that was real: `apply` wrote each site as it
+ /// classified it and re-attested once at the end, so a throw in the AVF
+ /// family left the five NeutrinoCore sites written with their code-signature
+ /// slots still describing the old bytes. TXM checks those per page on
+ /// `codeSigningMonitor == 2`, so the result was a cache that was both
+ /// half-patched and unloadable — it SIGKILLs on the first demand-page-in of
+ /// a modified page. `apply` now plans every family before it writes any of
+ /// them, so a failure writes nothing at all.
+ @Test("A failure part-way through leaves the cache untouched")
+ func failureWritesNothing() throws {
+ _ = try #require(CameraFixture.pristine, CameraFixture.missing)
+
+ let clone = try CameraFixture.cloneCache(named: "camera_midrun_failure")
+ defer { CameraFixture.discard(clone) }
+
+ // Break only the AVF entry point — the family that runs second. The
+ // five NeutrinoCore sites are pristine and would patch cleanly, which
+ // is what makes this a half-patch rather than a no-op.
+ let chunks = try DSCChunkSet(directory: clone)
+ let resolver = try DSCSymbolResolver(chunks: chunks)
+ let avf = try resolver.address(
+ of: DSCCameraPatcher.authorizationStatusSymbol,
+ inImage: DSCCameraPatcher.Family.avfAuthorization.imagePath
+ )
+ try chunks.write(at: avf, ARM64.nop)
+ try DSCCodeSignature.reattestRecordedWrites(in: chunks, log: nil)
+
+ let before = try CameraFixture.digests(of: clone)
+
+ #expect(throws: PatcherError.self) {
+ _ = try DSCCameraPatcher.applyAll(chunksDirectory: clone, log: nil)
+ }
+
+ let after = try CameraFixture.digests(of: clone)
+ let changed = before.keys.filter { after[$0] != before[$0] }.sorted()
+ #expect(changed.isEmpty, "a failed run wrote to \(changed.joined(separator: ", "))")
+ print(
+ changed.isEmpty
+ ? "[camera failure] applyAll threw and wrote nothing — \(before.count) files unchanged"
+ : "[camera failure] applyAll threw AFTER writing \(changed.joined(separator: ", "))"
+ )
+ }
+
+ /// The reference's `--force`, and what it is a guard against.
+ @Test("An unexpected prologue is refused unless forced")
+ func unexpectedPrologueIsRefused() throws {
+ _ = try #require(CameraFixture.pristine, CameraFixture.missing)
+
+ let clone = try CameraFixture.cloneCache(named: "camera_force")
+ defer { CameraFixture.discard(clone) }
+
+ // Put something that is neither pacibsp nor the replacement at one of
+ // the six entry points, without going through the patcher.
+ let chunks = try DSCChunkSet(directory: clone)
+ let resolver = try DSCSymbolResolver(chunks: chunks)
+ let vma = try resolver.address(
+ of: DSCCameraPatcher.authorizationStatusSymbol,
+ inImage: DSCCameraPatcher.Family.avfAuthorization.imagePath
+ )
+ try chunks.write(at: vma, ARM64.nop)
+ try DSCCodeSignature.reattestRecordedWrites(in: chunks, log: nil)
+
+ #expect(throws: PatcherError.self) {
+ _ = try DSCCameraPatcher.applyAVFAuthorizationOnly(
+ chunksDirectory: clone,
+ log: nil
+ )
+ }
+
+ var log: [String] = []
+ let forced = try DSCCameraPatcher.applyAVFAuthorizationOnly(
+ chunksDirectory: clone,
+ force: true,
+ log: { log.append($0) }
+ )
+ #expect(forced.siteCount == 1)
+ #expect(forced.sites.first?.wasAlreadyPatched == false)
+ #expect(log.contains { $0.contains("forced") })
+
+ let fresh = try DSCChunkSet(directory: clone)
+ let written = try fresh.bytesAtVMA(vma, length: 8)
+ let expected = try DSCCameraPatcher.replacement(returning: 3)
+ #expect(written == expected)
+ print("[camera force] a nop prologue was refused, then accepted under force")
+ }
+
+ /// The prologue classifier decides whether a site may be written at all, so
+ /// it is worth exercising away from the cache too — including the shape a
+ /// byte comparison would get right only by coincidence.
+ @Test("The prologue classifier reads instructions, not bytes")
+ func prologueClassifierIsSemantic() throws {
+ let disassembler = ARM64Disassembler()
+ let replacement = try DSCCameraPatcher.replacement(returning: 3)
+
+ func classify(_ bytes: Data, force: Bool = false) throws -> Bool {
+ try DSCCameraPatcher.classifyPrologue(
+ bytes,
+ at: 0x1_0000_0000,
+ symbol: "test",
+ returning: 3,
+ disassembler: disassembler,
+ force: force,
+ log: nil
+ )
+ }
+
+ // pacibsp — pristine, and not already patched.
+ let pristinePrologue = try classify(ARM64.pacibsp + ARM64.nop)
+ #expect(pristinePrologue == false)
+
+ // The replacement itself — already patched.
+ let ownOutput = try classify(replacement)
+ #expect(ownOutput == true)
+
+ // The *other* family's replacement returns a different constant, so it
+ // is not this family's output and must not pass as one.
+ let otherFamily = try DSCCameraPatcher.replacement(returning: 0)
+ #expect(throws: PatcherError.self) { _ = try classify(otherFamily) }
+
+ // `mov w0, #3` without the `ret` is not the replacement either.
+ let movOnly = try #require(ARM64Encoder.encodeMovzW(rd: 0, imm16: 3)) + ARM64.nop
+ #expect(throws: PatcherError.self) { _ = try classify(movOnly) }
+
+ // And `mov x0, #3; ret` writes the 64-bit register, which is a
+ // different instruction with the same shape.
+ let wrongWidth = try #require(ARM64Encoder.encodeMovzX(rd: 0, imm16: 3)) + ARM64.ret
+ #expect(throws: PatcherError.self) { _ = try classify(wrongWidth) }
+
+ // Under force, all of them are accepted and none is "already patched".
+ for bytes in [movOnly, wrongWidth, ARM64.nop + ARM64.nop] {
+ let forced = try classify(bytes, force: true)
+ #expect(forced == false)
+ }
+ print("[camera prologue] pacibsp, replacement, near-misses and force all classified")
+ }
+
+ /// A cache with no `.symbols` side file cannot resolve an ObjC method, and
+ /// has to say so rather than reporting six renamed symbols.
+ @Test("A cache without local symbols fails loudly")
+ func missingLocalSymbolsFailsLoudly() throws {
+ _ = try #require(CameraFixture.pristine, CameraFixture.missing)
+
+ let clone = try CameraFixture.cloneCache(named: "camera_no_symbols")
+ defer { CameraFixture.discard(clone) }
+ try FileManager.default.removeItem(
+ at: clone.appendingPathComponent("dyld_shared_cache_arm64e.symbols")
+ )
+
+ #expect(throws: DSCError.self) {
+ _ = try DSCCameraPatcher.applyAll(chunksDirectory: clone, dryRun: true, log: nil)
+ }
+ print("[camera symbols] a cache with no .symbols table is refused, not silently empty")
+ }
+}
diff --git a/tests/FirmwarePatcherTests/DSCFoundationTests.swift b/tests/FirmwarePatcherTests/DSCFoundationTests.swift
index fbe75ac0..24b48fbd 100644
--- a/tests/FirmwarePatcherTests/DSCFoundationTests.swift
+++ b/tests/FirmwarePatcherTests/DSCFoundationTests.swift
@@ -62,8 +62,15 @@ private enum DSCFixture {
/// Where clones are made. Same filesystem as the pristine copy, so
/// `cp -c` is a clone rather than 6.7 GB of reads.
+ ///
+ /// Deliberately a sibling of `ref_extract/`, not a child of it. This used
+ /// to sit at `ref_extract/scratch_dscfoundation`, inside the pristine tree
+ /// the whole suite compares against: the cleanup works, but any run that
+ /// is interrupted leaves multi-GB clones in there, and a reference tree
+ /// with scratch in it is no longer a reference. `ipsws/` is the same
+ /// filesystem, so the clone is still a clone.
static var scratchRoot: URL {
- repoRoot.appendingPathComponent("ipsws/ref_extract/scratch_dscfoundation")
+ repoRoot.appendingPathComponent("ipsws/scratch_dscfoundation")
}
/// The project venv, which is where the reference Python lives.
diff --git a/tests/FirmwarePatcherTests/DSCHVVMMPatcherTests.swift b/tests/FirmwarePatcherTests/DSCHVVMMPatcherTests.swift
new file mode 100644
index 00000000..fb9d187f
--- /dev/null
+++ b/tests/FirmwarePatcherTests/DSCHVVMMPatcherTests.swift
@@ -0,0 +1,660 @@
+// DSCHVVMMPatcherTests.swift — Python-vs-Swift parity for the hv_vmm_present
+// user-mode cstring mangle.
+//
+// There is no external oracle for this patch. `codesign -v` does not apply to a
+// dyld shared cache chunk, and the only statement of what the patch should do is
+// `scripts/patchers/cfw_patch_hv_vmm_dsc.py` plus the module it imports its
+// constants from, `cfw_patch_hv_vmm.py`. So the test is not "does the Swift
+// write 29 sites" — that number is this repo's own claim. It is: run the
+// reference on one clone of the real cache, the Swift on another, and require
+// the two 6.7 GB trees to come out byte for byte identical, chunk files and
+// re-attested code directories alike.
+//
+// The fixture is the real 24A435 arm64e cache. Point `VPHONE_DSC_PRISTINE` at a
+// directory of `dyld_shared_cache_arm64e*` chunks, or leave the default
+// `ipsws/ref_extract/dsc_pristine` in place.
+//
+// Without it these tests FAIL. A `guard … else { return }` would be reported by
+// Swift Testing as a pass, so on a machine that never extracted the cache a
+// green run would mean nothing. A machine that genuinely cannot carry the
+// fixture sets `VPHONE_DSC_FIXTURE_OPTIONAL=1` and gets a visible *skip*
+// instead.
+//
+// Nothing here writes to the pristine directory, or anywhere else inside it.
+// Clones go to `VPHONE_DSC_SCRATCH`, or to the system temporary directory, and
+// are made with `clonefile` so a 6.7 GB copy is instant and costs almost no
+// disk.
+
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+
+// MARK: - Fixture discovery
+
+private enum HVVMMFixture {
+ static let repoRoot = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+
+ /// The read-only reference cache.
+ static var pristine: URL? {
+ let url = ProcessInfo.processInfo.environment["VPHONE_DSC_PRISTINE"]
+ .map { URL(fileURLWithPath: $0) }
+ ?? repoRoot.appendingPathComponent("ipsws/ref_extract/dsc_pristine")
+ let main = url.appendingPathComponent("dyld_shared_cache_arm64e")
+ return FileManager.default.fileExists(atPath: main.path) ? url : nil
+ }
+
+ /// Pristine standalone Mach-Os, for the other half of the port.
+ static func machO(_ name: String) -> URL? {
+ let url = repoRoot
+ .appendingPathComponent("ipsws/ref_extract/macho_pristine")
+ .appendingPathComponent(name)
+ return FileManager.default.fileExists(atPath: url.path) ? url : nil
+ }
+
+ /// Opt-out for a machine that cannot carry the fixture. Set it and the
+ /// suites report as skipped; leave it unset and a missing cache is a
+ /// failure, which is the only reading of "green" this layer can afford.
+ static var isOptional: Bool {
+ ProcessInfo.processInfo.environment["VPHONE_DSC_FIXTURE_OPTIONAL"] == "1"
+ }
+
+ /// The suites run unless the cache is absent *and* the caller opted out.
+ static var runs: Bool { pristine != nil || !isOptional }
+
+ /// Same rule for the standalone Mach-O fixtures, which live under the same
+ /// gitignored `ipsws/` tree and are therefore absent on a fresh clone.
+ static var machORuns: Bool {
+ (machO("watchdogd") != nil && machO("mobileactivationd") != nil) || !isOptional
+ }
+
+ static let machOSkipReason: Comment =
+ "VPHONE_DSC_FIXTURE_OPTIONAL=1 and no ipsws/ref_extract/macho_pristine binaries present"
+
+ static let missing: Comment = """
+ the real 24A435 arm64e shared cache is required — put it at \
+ ipsws/ref_extract/dsc_pristine, point VPHONE_DSC_PRISTINE at it, or set \
+ VPHONE_DSC_FIXTURE_OPTIONAL=1 to skip these tests instead of failing
+ """
+
+ static let skipReason: Comment =
+ "VPHONE_DSC_FIXTURE_OPTIONAL=1 and no dyld_shared_cache_arm64e fixture present"
+
+ /// Where clones are made.
+ ///
+ /// Deliberately NOT inside `ipsws/ref_extract/`: that tree is the pristine
+ /// reference the whole suite compares against, and a scratch directory next
+ /// to it is one `rm -rf` typo away from destroying a 6.7 GB extraction
+ /// nobody wants to redo. `VPHONE_DSC_SCRATCH` overrides, for a host whose
+ /// temporary directory is on a different volume from the cache and would
+ /// therefore turn `clonefile` into a real copy.
+ static var scratchRoot: URL {
+ if let override = ProcessInfo.processInfo.environment["VPHONE_DSC_SCRATCH"] {
+ return URL(fileURLWithPath: override)
+ }
+ return FileManager.default.temporaryDirectory
+ .appendingPathComponent("vphone-hvvmm-parity")
+ }
+
+ /// The project venv, which is where the reference Python lives.
+ static var python: URL? {
+ let url = repoRoot.appendingPathComponent(".venv/bin/python3")
+ return FileManager.default.fileExists(atPath: url.path) ? url : nil
+ }
+
+ static let pythonMissing: Comment = """
+ the project venv is required — the reference implementation is the only \
+ oracle this patch has. Create it with `make setup_venv`.
+ """
+
+ /// Clone the pristine cache into a fresh directory the caller may write to.
+ static func cloneCache(named name: String) throws -> URL {
+ guard let pristine else { throw CocoaError(.fileNoSuchFile) }
+ let destination = scratchRoot.appendingPathComponent(name)
+ try? FileManager.default.removeItem(at: destination)
+ try FileManager.default.createDirectory(
+ at: destination,
+ withIntermediateDirectories: true
+ )
+ let sources = try FileManager.default
+ .contentsOfDirectory(atPath: pristine.path)
+ .sorted()
+ .map { pristine.appendingPathComponent($0).path }
+
+ // `-c` asks for clonefile. On a host where the scratch directory is on
+ // another volume that fails outright, so fall back to a real copy rather
+ // than reporting a fixture problem as a patch failure.
+ var result = try Subprocess.run(
+ executable: URL(fileURLWithPath: "/bin/cp"),
+ arguments: ["-c", "-R"] + sources + [destination.path]
+ )
+ if result.status != 0 {
+ result = try Subprocess.run(
+ executable: URL(fileURLWithPath: "/bin/cp"),
+ arguments: ["-R"] + sources + [destination.path]
+ )
+ }
+ guard result.status == 0 else { throw CocoaError(.fileWriteUnknown) }
+ return destination
+ }
+
+ /// Copy one file into scratch under a fresh name.
+ static func copyFile(_ source: URL, named name: String) throws -> URL {
+ try FileManager.default.createDirectory(
+ at: scratchRoot,
+ withIntermediateDirectories: true
+ )
+ let destination = scratchRoot.appendingPathComponent(name)
+ try? FileManager.default.removeItem(at: destination)
+ try FileManager.default.copyItem(at: source, to: destination)
+ return destination
+ }
+
+ /// Discard clones, and the scratch root with them once the last one is gone,
+ /// so a test run leaves the tree as it found it.
+ static func discard(_ items: URL...) {
+ for item in items {
+ try? FileManager.default.removeItem(at: item)
+ }
+ let remaining = (try? FileManager.default
+ .contentsOfDirectory(atPath: scratchRoot.path)) ?? []
+ if remaining.isEmpty {
+ try? FileManager.default.removeItem(at: scratchRoot)
+ }
+ }
+}
+
+// MARK: - Subprocess helper
+
+private enum Subprocess {
+ struct Result {
+ let status: Int32
+ let stdout: String
+ let stderr: String
+ }
+
+ @discardableResult
+ static func run(executable: URL, arguments: [String]) throws -> Result {
+ let process = Process()
+ process.executableURL = executable
+ process.arguments = arguments
+ let out = Pipe()
+ let err = Pipe()
+ process.standardOutput = out
+ process.standardError = err
+ try process.run()
+ // Drain before waiting: the reference prints a line per site, and a full
+ // pipe buffer would deadlock the run.
+ let outData = out.fileHandleForReading.readDataToEndOfFile()
+ let errData = err.fileHandleForReading.readDataToEndOfFile()
+ process.waitUntilExit()
+ return Result(
+ status: process.terminationStatus,
+ stdout: String(decoding: outData, as: UTF8.self),
+ stderr: String(decoding: errData, as: UTF8.self)
+ )
+ }
+}
+
+// MARK: - Byte-for-byte tree comparison
+
+private enum TreeComparison {
+ /// Files present in one tree but not the other, and files whose bytes differ.
+ struct Difference: CustomStringConvertible {
+ var onlyInLeft: [String] = []
+ var onlyInRight: [String] = []
+ var differingBytes: [String] = []
+
+ var isEmpty: Bool {
+ onlyInLeft.isEmpty && onlyInRight.isEmpty && differingBytes.isEmpty
+ }
+
+ var description: String {
+ var parts: [String] = []
+ if !onlyInLeft.isEmpty { parts.append("only in left: \(onlyInLeft)") }
+ if !onlyInRight.isEmpty { parts.append("only in right: \(onlyInRight)") }
+ if !differingBytes.isEmpty { parts.append("bytes differ: \(differingBytes)") }
+ return parts.isEmpty ? "identical" : parts.joined(separator: "; ")
+ }
+ }
+
+ /// Compare two directories file by file, byte by byte.
+ ///
+ /// `cmp` rather than a digest: it stops at the first differing byte, so a
+ /// tree that really does differ is reported in milliseconds instead of after
+ /// hashing 6.7 GB twice.
+ static func compare(_ left: URL, _ right: URL) throws -> Difference {
+ let leftNames = Set(try FileManager.default.contentsOfDirectory(atPath: left.path))
+ let rightNames = Set(try FileManager.default.contentsOfDirectory(atPath: right.path))
+
+ var difference = Difference()
+ difference.onlyInLeft = leftNames.subtracting(rightNames).sorted()
+ difference.onlyInRight = rightNames.subtracting(leftNames).sorted()
+
+ for name in leftNames.intersection(rightNames).sorted() {
+ let result = try Subprocess.run(
+ executable: URL(fileURLWithPath: "/usr/bin/cmp"),
+ arguments: [
+ "-s",
+ left.appendingPathComponent(name).path,
+ right.appendingPathComponent(name).path,
+ ]
+ )
+ if result.status != 0 { difference.differingBytes.append(name) }
+ }
+ return difference
+ }
+}
+
+// MARK: - The reference Python, driven as an oracle
+
+/// A driver around `cfw_patch_hv_vmm_dsc` / `cfw_patch_hv_vmm`, written to a
+/// temp file at test time.
+///
+/// It adds no logic of its own: it calls the reference entry points and prints
+/// what they return. That is the point — the comparison has to be against that
+/// code running, not against a transcription of it.
+private enum PythonOracle {
+ static let source = #"""
+import contextlib
+import json
+import os
+import sys
+
+sys.path.insert(0, os.path.join(sys.argv[1], "scripts"))
+
+from patchers.cfw_patch_hv_vmm import (
+ NEEDLE, MANGLED_NEEDLE, MANGLE_OFFSET, ORIGINAL_BYTE, MANGLED_BYTE,
+ find_string_sites, patch_hv_vmm,
+)
+from patchers.cfw_patch_hv_vmm_dsc import (
+ DONT_PATCH_INSTALL_NAMES, patch_hv_vmm_in_dsc,
+)
+
+command = sys.argv[2]
+
+if command == "constants":
+ print(json.dumps({
+ "needle": NEEDLE.hex(),
+ "mangled_needle": MANGLED_NEEDLE.hex(),
+ "mangle_offset": MANGLE_OFFSET,
+ "original_byte": ORIGINAL_BYTE.hex(),
+ "mangled_byte": MANGLED_BYTE.hex(),
+ "blacklist": list(DONT_PATCH_INSTALL_NAMES),
+ }))
+
+elif command == "patch_dsc":
+ # argv[3] = chunks dir, argv[4] = "1" for a dry run.
+ dry_run = len(sys.argv) > 4 and sys.argv[4] == "1"
+ # The patcher narrates to stdout; keep that on stderr so stdout is JSON.
+ with contextlib.redirect_stdout(sys.stderr):
+ results = patch_hv_vmm_in_dsc(sys.argv[3], dry_run=dry_run)
+ print(json.dumps({"results": results}))
+
+elif command == "macho_sites":
+ with open(sys.argv[3], "rb") as f:
+ data = f.read()
+ print(json.dumps({"sites": find_string_sites(data)}))
+
+elif command == "patch_macho":
+ with contextlib.redirect_stdout(sys.stderr):
+ count = patch_hv_vmm(sys.argv[3], dry_run=False)
+ print(json.dumps({"count": count}))
+
+else:
+ raise SystemExit(f"unknown command {command}")
+"""#
+
+ static func scriptURL() throws -> URL {
+ let url = FileManager.default.temporaryDirectory
+ .appendingPathComponent(
+ "hv_vmm_oracle_\(ProcessInfo.processInfo.processIdentifier).py"
+ )
+ if !FileManager.default.fileExists(atPath: url.path) {
+ try source.write(to: url, atomically: true, encoding: .utf8)
+ }
+ return url
+ }
+
+ static func run(_ command: String, _ extra: [String] = []) throws -> Data {
+ guard let python = HVVMMFixture.python else { throw CocoaError(.fileNoSuchFile) }
+ let script = try scriptURL()
+ let result = try Subprocess.run(
+ executable: python,
+ arguments: [script.path, HVVMMFixture.repoRoot.path, command] + extra
+ )
+ guard result.status == 0 else {
+ Issue.record("python oracle \(command) failed: \(result.stderr)")
+ throw CocoaError(.fileReadUnknown)
+ }
+ return Data(result.stdout.utf8)
+ }
+
+ struct Constants: Decodable {
+ let needle: String
+ let mangled_needle: String
+ let mangle_offset: Int
+ let original_byte: String
+ let mangled_byte: String
+ let blacklist: [String]
+ }
+
+ struct DSCRun: Decodable {
+ let results: [String: Int]
+ }
+
+ struct MachOSites: Decodable {
+ struct Site: Decodable {
+ let string_vma: UInt64
+ let file_offset: Int
+ let section: String
+ }
+
+ let sites: [Site]
+ }
+
+ struct MachORun: Decodable {
+ let count: Int
+ }
+}
+
+// MARK: - Constants
+
+/// No cache fixture here, so no fixture gate: the only thing this suite needs is
+/// the venv that holds the reference modules, and a missing venv has to fail
+/// rather than skip — without it there is no oracle and nothing was checked.
+@Suite(.serialized)
+struct DSCHVVMMConstantsTests {
+ @Test("The cstring, its mangle and the blacklist match the reference modules")
+ func constantsMatchPython() throws {
+ try #require(HVVMMFixture.python != nil, HVVMMFixture.pythonMissing)
+ let reference = try JSONDecoder().decode(
+ PythonOracle.Constants.self,
+ from: PythonOracle.run("constants")
+ )
+
+ #expect(DSCHVVMMPatcher.needle.hex == reference.needle)
+ #expect(DSCHVVMMPatcher.mangledNeedle.hex == reference.mangled_needle)
+ #expect(DSCHVVMMPatcher.mangleOffset == reference.mangle_offset)
+ #expect(Data([DSCHVVMMPatcher.originalByte]).hex == reference.original_byte)
+ #expect(Data([DSCHVVMMPatcher.mangledByte]).hex == reference.mangled_byte)
+ #expect(DSCHVVMMPatcher.dontPatchInstallNames == reference.blacklist)
+
+ // The mangle has to preserve the namespace prefix, or the name cannot
+ // resolve to any OID — see the patcher's file comment. This is the one
+ // property of the patch that is not a transcription of the reference.
+ let prefix = Data(DSCHVVMMPatcher.sysctlNamespace.utf8)
+ #expect(DSCHVVMMPatcher.needle.prefix(prefix.count) == prefix)
+ #expect(DSCHVVMMPatcher.mangledNeedle.prefix(prefix.count) == prefix)
+ #expect(DSCHVVMMPatcher.needle.count == DSCHVVMMPatcher.mangledNeedle.count)
+ let differing = zip(DSCHVVMMPatcher.needle, DSCHVVMMPatcher.mangledNeedle)
+ .enumerated()
+ .filter { $0.element.0 != $0.element.1 }
+ .map(\.offset)
+ #expect(differing == [DSCHVVMMPatcher.mangleOffset])
+ }
+}
+
+// MARK: - The real cache
+
+@Suite(.serialized, .enabled(if: HVVMMFixture.runs, HVVMMFixture.skipReason))
+struct DSCHVVMMCacheParityTests {
+ /// The parity gate.
+ ///
+ /// Reference on one clone, Swift on another, then require the two trees to
+ /// be byte identical — every chunk file, including the code directories the
+ /// re-attestation pass rewrote. A port that writes a different number of
+ /// sites, or the same number in different places, or the right bytes with
+ /// the wrong page re-hashed, fails here.
+ ///
+ /// The idempotence and blacklist checks ride on the same clones rather than
+ /// cloning 6.7 GB again for each: they are assertions about the state this
+ /// test has already produced.
+ @Test("The Swift patch and the Python reference produce identical caches")
+ func swiftMatchesPythonOnTheRealCache() throws {
+ _ = try #require(HVVMMFixture.pristine, HVVMMFixture.missing)
+ try #require(HVVMMFixture.python != nil, HVVMMFixture.pythonMissing)
+
+ let pythonClone = try HVVMMFixture.cloneCache(named: "python")
+ let swiftClone = try HVVMMFixture.cloneCache(named: "swift")
+ defer { HVVMMFixture.discard(pythonClone, swiftClone) }
+
+ let reference = try JSONDecoder().decode(
+ PythonOracle.DSCRun.self,
+ from: PythonOracle.run("patch_dsc", [pythonClone.path])
+ )
+ let result = try DSCHVVMMPatcher.patch(chunksDirectory: swiftClone, log: nil)
+
+ // Same verdict per dylib, including the zero-count entries that record
+ // "seen and deliberately left alone".
+ #expect(result.mangledCountByInstallName == reference.results)
+
+ let referenceTotal = reference.results.values.reduce(0, +)
+ #expect(result.mangled == referenceTotal)
+ #expect(result.mangled > 0, "the reference patched nothing — wrong fixture?")
+ #expect(result.skippedInBlacklist == DSCHVVMMPatcher.dontPatchInstallNames.count)
+ #expect(result.skippedUnclassified == 0)
+ #expect(result.refused == 0)
+ #expect(result.isFullyAttested)
+ // One slot per dirtied page, and no site left unattested. Sites can in
+ // principle share a page, so this is a bound rather than an equality —
+ // the tree comparison below is what actually pins the code directories.
+ let slotsRewritten = result.reattestation?.updated.count ?? 0
+ #expect(slotsRewritten > 0)
+ #expect(slotsRewritten <= result.mangled)
+ print(
+ "[hv_vmm] python \(referenceTotal) site(s), swift \(result.mangled) site(s), "
+ + "\(result.skippedInBlacklist) blacklisted, "
+ + "\(slotsRewritten) slot(s) re-attested"
+ )
+
+ let difference = try TreeComparison.compare(pythonClone, swiftClone)
+ #expect(difference.isEmpty, "patched caches differ: \(difference)")
+
+ // Idempotence, on the cache the Swift run just produced. A second pass
+ // finds no pristine cstring left, queues the mangled ones so their slots
+ // stay in sync, and must not move a byte.
+ let second = try DSCHVVMMPatcher.patch(chunksDirectory: swiftClone, log: nil)
+ #expect(second.mangled == 0)
+ #expect(second.pristineSiteCount == result.skippedInBlacklist)
+ #expect(second.alreadyMangledSiteCount == result.mangled)
+ #expect(second.reattestOnly == result.mangled)
+ #expect(second.blacklistDrift == 0)
+ #expect(second.reattestation?.updated.isEmpty == true)
+ let afterRerun = try TreeComparison.compare(pythonClone, swiftClone)
+ #expect(afterRerun.isEmpty, "a second run moved bytes: \(afterRerun)")
+
+ // The blacklist is the whole point of the design, so check it against
+ // the bytes rather than against the run's own bookkeeping: every
+ // blacklisted dylib in the cache must still hold the pristine cstring.
+ let chunks = try DSCChunkSet(directory: swiftClone)
+ var blacklistedSitesSeen = 0
+ for vma in try chunks.findStringVMAs(DSCHVVMMPatcher.needle) {
+ let installName = try #require(
+ DSCHVVMMPatcher.classify(vma, in: chunks),
+ "a pristine cstring survived in a dylib that cannot be named"
+ )
+ #expect(
+ DSCHVVMMPatcher.dontPatchSet.contains(installName),
+ "\(installName) is not blacklisted but kept the original cstring"
+ )
+ blacklistedSitesSeen += 1
+ }
+ #expect(blacklistedSitesSeen == result.skippedInBlacklist)
+
+ for vma in try chunks.findStringVMAs(DSCHVVMMPatcher.mangledNeedle) {
+ let installName = try #require(DSCHVVMMPatcher.classify(vma, in: chunks))
+ #expect(
+ !DSCHVVMMPatcher.dontPatchSet.contains(installName),
+ "\(installName) is blacklisted but was mangled"
+ )
+ }
+ }
+
+ @Test("A dry run reports the same sites and leaves every byte alone")
+ func dryRunTouchesNothing() throws {
+ let pristine = try #require(HVVMMFixture.pristine, HVVMMFixture.missing)
+ try #require(HVVMMFixture.python != nil, HVVMMFixture.pythonMissing)
+
+ let clone = try HVVMMFixture.cloneCache(named: "dryrun")
+ defer { HVVMMFixture.discard(clone) }
+
+ let result = try DSCHVVMMPatcher.patch(
+ chunksDirectory: clone,
+ dryRun: true,
+ log: nil
+ )
+ #expect(result.mangled > 0)
+ // A dry run writes nothing, so every page still hashes to exactly what
+ // its slot says and no slot would be rewritten. What has to be true is
+ // that the pass REACHED every page the patch would dirty — otherwise a
+ // dry run would be quietly narrower than the real thing.
+ #expect(result.reattestation?.updated.isEmpty == true)
+ let pagesReached = result.reattestation?.pagesAttested ?? 0
+ #expect(pagesReached > 0)
+ #expect(pagesReached <= result.mangled)
+ #expect(result.isFullyAttested)
+
+ let difference = try TreeComparison.compare(pristine, clone)
+ #expect(difference.isEmpty, "a dry run wrote to the cache: \(difference)")
+
+ // And the same for the reference, so "dry run changes nothing" is a
+ // property of both implementations and not just of this one.
+ _ = try PythonOracle.run("patch_dsc", [clone.path, "1"])
+ let afterPython = try TreeComparison.compare(pristine, clone)
+ #expect(afterPython.isEmpty, "the reference dry run wrote too: \(afterPython)")
+ }
+
+ /// The drift branch, which is the one deliberate behaviour in this patch that
+ /// a port could plausibly get backwards.
+ ///
+ /// A blacklisted dylib found already mangled means somebody took it out of
+ /// the blacklist, ran the patch, and put it back. The reference does NOT
+ /// revert the byte and does NOT refuse: it says so loudly and re-attests the
+ /// page to the bytes that are actually there, because reverting would leave
+ /// the page hash right and the operator's intent wrong. A port that "fixed"
+ /// this by reverting, or by treating it as an error, would pass every other
+ /// test in this file.
+ @Test("A blacklisted dylib found mangled is reported as drift, not reverted")
+ func blacklistDriftIsReportedNotReverted() throws {
+ _ = try #require(HVVMMFixture.pristine, HVVMMFixture.missing)
+ try #require(HVVMMFixture.python != nil, HVVMMFixture.pythonMissing)
+
+ let pythonClone = try HVVMMFixture.cloneCache(named: "drift-python")
+ let swiftClone = try HVVMMFixture.cloneCache(named: "drift-swift")
+ defer { HVVMMFixture.discard(pythonClone, swiftClone) }
+
+ // The lowest-addressed site inside a blacklisted dylib, so the choice is
+ // the same on every run.
+ let probe = try DSCChunkSet(directory: swiftClone)
+ let driftVMA = try #require(
+ try probe.findStringVMAs(DSCHVVMMPatcher.needle).sorted().first {
+ guard let name = DSCHVVMMPatcher.classify($0, in: probe) else { return false }
+ return DSCHVVMMPatcher.dontPatchSet.contains(name)
+ },
+ "no blacklisted dylib carries the cstring in this cache"
+ )
+ let driftedDylib = try #require(DSCHVVMMPatcher.classify(driftVMA, in: probe))
+
+ // Mangle it by hand in both clones, without re-attesting — exactly the
+ // state a prior out-of-band run would have left behind.
+ for clone in [pythonClone, swiftClone] {
+ let chunks = try DSCChunkSet(directory: clone)
+ try chunks.write(
+ at: driftVMA &+ UInt64(DSCHVVMMPatcher.mangleOffset),
+ Data([DSCHVVMMPatcher.mangledByte])
+ )
+ }
+
+ _ = try PythonOracle.run("patch_dsc", [pythonClone.path])
+ let result = try DSCHVVMMPatcher.patch(chunksDirectory: swiftClone, log: nil)
+
+ #expect(result.blacklistDrift == 1)
+ #expect(result.alreadyMangledSiteCount == 1)
+ #expect(result.reattestOnly == 0)
+ #expect(result.refused == 0)
+ #expect(
+ result.skippedInBlacklist == DSCHVVMMPatcher.dontPatchInstallNames.count - 1,
+ "the drifted site is no longer pristine, so it is not counted as skipped"
+ )
+ #expect(result.mangledCountByInstallName[driftedDylib] == nil)
+ #expect(result.isFullyAttested)
+
+ // Not reverted: the byte is still mangled afterwards.
+ let after = try DSCChunkSet(directory: swiftClone)
+ .bytesAtVMA(driftVMA, length: DSCHVVMMPatcher.needle.count)
+ #expect(after == DSCHVVMMPatcher.mangledNeedle)
+
+ let difference = try TreeComparison.compare(pythonClone, swiftClone)
+ #expect(difference.isEmpty, "drift handling differs from the reference: \(difference)")
+ print("[hv_vmm] drift on \(driftedDylib) at 0x\(String(driftVMA, radix: 16, uppercase: true))")
+ }
+}
+
+// MARK: - Standalone Mach-O
+
+@Suite(.serialized, .enabled(if: HVVMMFixture.machORuns, HVVMMFixture.machOSkipReason))
+struct DSCHVVMMStandaloneTests {
+ /// The other half of `cfw_patch_hv_vmm.py`, against the binaries the repo
+ /// keeps pristine copies of.
+ ///
+ /// `watchdogd` carries one occurrence of the cstring and `mobileactivationd`
+ /// two, so between them they cover the single-site and multi-site paths.
+ @Test(
+ "Standalone Mach-O mangling matches the reference",
+ arguments: ["watchdogd", "mobileactivationd"]
+ )
+ func standaloneMatchesPython(name: String) throws {
+ let pristine = try #require(
+ HVVMMFixture.machO(name),
+ """
+ ipsws/ref_extract/macho_pristine/\(name) is required — it is the \
+ only standalone Mach-O oracle this half of the port has
+ """
+ )
+ try #require(HVVMMFixture.python != nil, HVVMMFixture.pythonMissing)
+
+ let pythonCopy = try HVVMMFixture.copyFile(pristine, named: "\(name).python")
+ let swiftCopy = try HVVMMFixture.copyFile(pristine, named: "\(name).swift")
+ defer { HVVMMFixture.discard(pythonCopy, swiftCopy) }
+
+ // Same sites, in the same order, before anything is written.
+ let referenceSites = try JSONDecoder().decode(
+ PythonOracle.MachOSites.self,
+ from: PythonOracle.run("macho_sites", [pristine.path])
+ ).sites
+ let sites = try DSCHVVMMPatcher.findStringSites(
+ inMachO: Data(contentsOf: pristine)
+ )
+ #expect(sites.count == referenceSites.count)
+ #expect(!sites.isEmpty, "\(name) holds no kern.hv_vmm_present cstring")
+ for (mine, theirs) in zip(sites, referenceSites) {
+ #expect(mine.stringVMA == theirs.string_vma)
+ #expect(mine.fileOffset == theirs.file_offset)
+ #expect(mine.section == theirs.section)
+ }
+
+ let referenceCount = try JSONDecoder().decode(
+ PythonOracle.MachORun.self,
+ from: PythonOracle.run("patch_macho", [pythonCopy.path])
+ ).count
+ let count = try DSCHVVMMPatcher.patchStandaloneMachO(at: swiftCopy, log: nil)
+ #expect(count == referenceCount)
+ #expect(count == sites.count)
+
+ let pristineBytes = try Data(contentsOf: pristine)
+ let patchedByPython = try Data(contentsOf: pythonCopy)
+ let patchedBySwift = try Data(contentsOf: swiftCopy)
+ #expect(patchedByPython == patchedBySwift, "\(name): patched bytes differ")
+ #expect(patchedBySwift != pristineBytes, "\(name): nothing was written")
+
+ // Idempotent: the pristine literal is gone, so a second pass is a no-op.
+ let rerun = try DSCHVVMMPatcher.patchStandaloneMachO(at: swiftCopy, log: nil)
+ let afterRerun = try Data(contentsOf: swiftCopy)
+ #expect(rerun == 0)
+ #expect(afterRerun == patchedBySwift)
+ print("[hv_vmm] \(name): \(count) standalone cstring site(s), bytes match")
+ }
+}
diff --git a/tests/FirmwarePatcherTests/DSCIOMFBForceKernTests.swift b/tests/FirmwarePatcherTests/DSCIOMFBForceKernTests.swift
new file mode 100644
index 00000000..6106272a
--- /dev/null
+++ b/tests/FirmwarePatcherTests/DSCIOMFBForceKernTests.swift
@@ -0,0 +1,473 @@
+// DSCIOMFBForceKernTests.swift — Parity for the IOMFB force-kern DSC patcher.
+//
+// There is no independent oracle for a patched dyld shared cache: `codesign -v`
+// does not apply to a cache chunk, and nothing but the guest kernel reads the
+// slot hashes. The only reference is `scripts/patchers/cfw_patch_iomfb_force_kern.py`,
+// so the central test here runs THAT on one clone of the real cache, runs the
+// Swift on a second clone, and compares the two byte for byte — every chunk,
+// every code-directory slot, the `.symbols` side file, all of it. A port that
+// writes a different number of sites, or the same number in different places,
+// or re-attests a different set of pages, fails.
+//
+// The tests need the real cache. Point `VPHONE_DSC_PRISTINE` at a directory of
+// `dyld_shared_cache_arm64e*` chunks, or leave the default
+// `ipsws/ref_extract/dsc_pristine` in place.
+//
+// Without it they FAIL. There is no bare `return` anywhere below, because Swift
+// Testing reports one as a pass — "all tests passed" would then be equally
+// compatible with "the cache was never there". A machine that genuinely cannot
+// carry the 6.7 GB fixture sets `VPHONE_DSC_FIXTURE_OPTIONAL=1`, which turns the
+// failure into a visible skip.
+//
+// Nothing here writes into the pristine directory. Clones are made with
+// `cp -c` — an APFS clone, so instant and near-free — into
+// `ipsws/scratch_dsc_forcekern`, and removed again at the end.
+
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+
+// MARK: - Fixture discovery
+
+private enum ForceKernFixture {
+ static let repoRoot = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+
+ static let imagePath =
+ "/System/Library/PrivateFrameworks/IOMobileFramebuffer.framework/IOMobileFramebuffer"
+
+ /// The read-only reference cache. Never written to.
+ static var pristine: URL? {
+ let url = ProcessInfo.processInfo.environment["VPHONE_DSC_PRISTINE"]
+ .map { URL(fileURLWithPath: $0) }
+ ?? repoRoot.appendingPathComponent("ipsws/ref_extract/dsc_pristine")
+ let main = url.appendingPathComponent("dyld_shared_cache_arm64e")
+ return FileManager.default.fileExists(atPath: main.path) ? url : nil
+ }
+
+ /// Opt-out for a machine that cannot carry the fixture.
+ static var isOptional: Bool {
+ ProcessInfo.processInfo.environment["VPHONE_DSC_FIXTURE_OPTIONAL"] == "1"
+ }
+
+ /// The suite runs unless the cache is absent *and* the caller opted out.
+ static var runs: Bool { pristine != nil || !isOptional }
+
+ static let missing: Comment = """
+ the real arm64e shared cache is required — put it at \
+ ipsws/ref_extract/dsc_pristine, point VPHONE_DSC_PRISTINE at it, or set \
+ VPHONE_DSC_FIXTURE_OPTIONAL=1 to skip these tests instead of failing
+ """
+
+ static let skipReason: Comment =
+ "VPHONE_DSC_FIXTURE_OPTIONAL=1 and no dyld_shared_cache_arm64e fixture present"
+
+ /// Where clones are made. Deliberately NOT under `ipsws/ref_extract`: that
+ /// tree is the pristine reference the whole suite compares against, and a
+ /// clone left behind in it is a corrupted reference for every later run.
+ /// Same filesystem, so `cp -c` is still a clone rather than 6.7 GB of I/O.
+ static var scratchRoot: URL {
+ ProcessInfo.processInfo.environment["VPHONE_DSC_SCRATCH"]
+ .map { URL(fileURLWithPath: $0) }
+ ?? repoRoot.appendingPathComponent("ipsws/scratch_dsc_forcekern")
+ }
+
+ /// The project venv, which is where the reference Python lives.
+ static var python: URL? {
+ let url = repoRoot.appendingPathComponent(".venv/bin/python3")
+ return FileManager.default.fileExists(atPath: url.path) ? url : nil
+ }
+
+ static var cfwDriver: URL {
+ repoRoot.appendingPathComponent("scripts/patchers/cfw.py")
+ }
+
+ static func cloneCache(named name: String) throws -> URL {
+ guard let pristine else { throw CocoaError(.fileNoSuchFile) }
+ let destination = scratchRoot.appendingPathComponent(name)
+ try? FileManager.default.removeItem(at: destination)
+ try FileManager.default.createDirectory(
+ at: destination,
+ withIntermediateDirectories: true
+ )
+ let result = try ForceKernShell.run(
+ executable: URL(fileURLWithPath: "/bin/cp"),
+ arguments: ["-c", "-R"]
+ + (try FileManager.default.contentsOfDirectory(atPath: pristine.path))
+ .sorted()
+ .map { pristine.appendingPathComponent($0).path }
+ + [destination.path]
+ )
+ guard result.status == 0 else {
+ throw CocoaError(.fileWriteUnknown)
+ }
+ return destination
+ }
+
+ /// Drop clones, and the scratch root with them once the last one is gone —
+ /// the working tree has to be left as it was found.
+ static func discard(_ clones: URL...) {
+ for clone in clones {
+ try? FileManager.default.removeItem(at: clone)
+ }
+ let remaining = (try? FileManager.default
+ .contentsOfDirectory(atPath: scratchRoot.path)) ?? []
+ if remaining.isEmpty {
+ try? FileManager.default.removeItem(at: scratchRoot)
+ }
+ }
+}
+
+// MARK: - Subprocess helper
+
+private enum ForceKernShell {
+ struct Result {
+ let status: Int32
+ let stdout: String
+ let stderr: String
+ }
+
+ @discardableResult
+ static func run(executable: URL, arguments: [String]) throws -> Result {
+ let process = Process()
+ process.executableURL = executable
+ process.arguments = arguments
+ let out = Pipe()
+ let err = Pipe()
+ process.standardOutput = out
+ process.standardError = err
+ try process.run()
+ // Drain before waiting: a full pipe buffer would deadlock the patcher's
+ // per-site log.
+ let outData = out.fileHandleForReading.readDataToEndOfFile()
+ let errData = err.fileHandleForReading.readDataToEndOfFile()
+ process.waitUntilExit()
+ return Result(
+ status: process.terminationStatus,
+ stdout: String(decoding: outData, as: UTF8.self),
+ stderr: String(decoding: errData, as: UTF8.self)
+ )
+ }
+
+ /// Run the reference patcher through the CLI the install scripts use.
+ static func runReference(on chunks: URL, dryRun: Bool) throws -> Result {
+ guard let python = ForceKernFixture.python else { throw CocoaError(.fileNoSuchFile) }
+ return try run(
+ executable: python,
+ arguments: [
+ ForceKernFixture.cfwDriver.path,
+ "patch-iomfb-force-kern",
+ chunks.path,
+ ] + (dryRun ? ["--dry-run"] : [])
+ )
+ }
+
+ /// `N` out of the reference's `complete: N newly forced, M already -> _kern_*`.
+ static func newlyForced(in output: String) -> Int? {
+ guard let line = output.split(separator: "\n").last(where: {
+ $0.contains("IOMFB force-kern complete:")
+ }) else { return nil }
+ let after = line.split(separator: ":").last ?? ""
+ return Int(after.trimmingCharacters(in: .whitespaces).split(separator: " ").first ?? "")
+ }
+
+ /// Byte-compare two cache directories, file by file. Returns the paths that
+ /// differ, plus the count compared.
+ static func diffTrees(_ left: URL, _ right: URL) throws -> (differing: [String], compared: Int) {
+ let manager = FileManager.default
+ let leftNames = try manager.contentsOfDirectory(atPath: left.path).sorted()
+ let rightNames = try manager.contentsOfDirectory(atPath: right.path).sorted()
+ guard leftNames == rightNames else {
+ return (Array(Set(leftNames).symmetricDifference(rightNames)).sorted(), 0)
+ }
+ var differing: [String] = []
+ for name in leftNames {
+ let result = try run(
+ executable: URL(fileURLWithPath: "/usr/bin/cmp"),
+ arguments: [
+ "-s",
+ left.appendingPathComponent(name).path,
+ right.appendingPathComponent(name).path,
+ ]
+ )
+ if result.status != 0 { differing.append(name) }
+ }
+ return (differing, leftNames.count)
+ }
+}
+
+// MARK: - Parity against the reference Python
+
+@Suite(.serialized, .enabled(if: ForceKernFixture.runs, ForceKernFixture.skipReason))
+struct DSCIOMFBForceKernParityTests {
+ /// The one test that decides whether this port is done.
+ @Test("Python and Swift force-kern produce byte-identical caches")
+ func matchesReferenceByteForByte() throws {
+ _ = try #require(ForceKernFixture.pristine, ForceKernFixture.missing)
+ try #require(
+ ForceKernFixture.python != nil,
+ "project venv is required to run the reference patcher"
+ )
+
+ let pythonClone = try ForceKernFixture.cloneCache(named: "python")
+ let swiftClone = try ForceKernFixture.cloneCache(named: "swift")
+ defer { ForceKernFixture.discard(pythonClone, swiftClone) }
+
+ // Both clones start identical — otherwise the comparison below proves
+ // nothing at all.
+ let before = try ForceKernShell.diffTrees(pythonClone, swiftClone)
+ #expect(before.differing.isEmpty, "clones differed before patching: \(before.differing)")
+ #expect(before.compared > 1)
+
+ let reference = try ForceKernShell.runReference(on: pythonClone, dryRun: false)
+ #expect(reference.status == 0, "reference patcher failed:\n\(reference.stderr)")
+ let referenceSites = try #require(
+ ForceKernShell.newlyForced(in: reference.stdout),
+ "could not read the reference's site count from:\n\(reference.stdout)"
+ )
+
+ let outcome = try DSCIOMFBForceKernPatcher.patch(
+ chunksDirectory: swiftClone,
+ log: nil
+ )
+
+ print("[force-kern] python wrote \(referenceSites) site(s), swift wrote \(outcome.writtenSiteCount)")
+ #expect(
+ outcome.writtenSiteCount == referenceSites,
+ "swift wrote \(outcome.writtenSiteCount) sites, python wrote \(referenceSites)"
+ )
+ #expect(referenceSites > 0, "the reference patched nothing — the fixture is not force-kernable")
+
+ let after = try ForceKernShell.diffTrees(pythonClone, swiftClone)
+ #expect(
+ after.differing.isEmpty,
+ "patched clones differ in: \(after.differing)"
+ )
+ #expect(after.compared == before.compared)
+ print("[force-kern] \(after.compared) file(s) compared byte for byte, all identical")
+
+ // And the other direction: the reference must recognise the Swift's
+ // output as already forced. That is a sharper check than the byte
+ // comparison — it says the branch this port encodes is the one the
+ // reference's own idempotence test decodes and accepts, rather than
+ // some other encoding that happens to hash the same.
+ let reRun = try ForceKernShell.runReference(on: swiftClone, dryRun: false)
+ #expect(reRun.status == 0, "reference re-run failed:\n\(reRun.stderr)")
+ #expect(
+ ForceKernShell.newlyForced(in: reRun.stdout) == 0,
+ "the reference re-forced sites the Swift had already written:\n\(reRun.stdout)"
+ )
+ let afterReRun = try ForceKernShell.diffTrees(pythonClone, swiftClone)
+ #expect(afterReRun.differing.isEmpty, "the reference's re-run changed bytes")
+ }
+
+ /// The reference's own idempotence claim, applied across implementations:
+ /// the Swift run over a cache the Python already patched must write nothing
+ /// and leave every byte alone.
+ @Test("Swift is a no-op on a cache the Python already forced")
+ func swiftIsIdempotentOverPythonOutput() throws {
+ _ = try #require(ForceKernFixture.pristine, ForceKernFixture.missing)
+ try #require(ForceKernFixture.python != nil, "project venv is required")
+
+ let clone = try ForceKernFixture.cloneCache(named: "idempotence")
+ defer { ForceKernFixture.discard(clone) }
+
+ let reference = try ForceKernShell.runReference(on: clone, dryRun: false)
+ #expect(reference.status == 0, "reference patcher failed:\n\(reference.stderr)")
+
+ let hashesBefore = try Self.chunkDigests(of: clone)
+ let second = try DSCIOMFBForceKernPatcher.patch(chunksDirectory: clone, log: nil)
+
+ #expect(second.writtenSiteCount == 0, "a second pass rewrote \(second.writtenSiteCount) site(s)")
+ #expect(second.reattestation == nil, "a second pass re-attested pages it did not dirty")
+ #expect(!second.alreadyForced.isEmpty)
+ let hashesAfter = try Self.chunkDigests(of: clone)
+ #expect(hashesAfter == hashesBefore, "a no-op run changed bytes")
+ }
+
+ /// A dry run must classify everything and touch nothing.
+ @Test("A dry run reports the same sites and writes no bytes")
+ func dryRunWritesNothing() throws {
+ _ = try #require(ForceKernFixture.pristine, ForceKernFixture.missing)
+
+ let clone = try ForceKernFixture.cloneCache(named: "dryrun")
+ defer { ForceKernFixture.discard(clone) }
+
+ let hashesBefore = try Self.chunkDigests(of: clone)
+ let dry = try DSCIOMFBForceKernPatcher.patch(
+ chunksDirectory: clone,
+ dryRun: true,
+ log: nil
+ )
+ #expect(dry.writtenSiteCount > 0, "the dry run classified no forcible site")
+ #expect(dry.records.isEmpty)
+ #expect(dry.reattestation == nil)
+ let hashesAfter = try Self.chunkDigests(of: clone)
+ #expect(hashesAfter == hashesBefore, "a dry run wrote to the cache")
+
+ let wet = try DSCIOMFBForceKernPatcher.patch(chunksDirectory: clone, log: nil)
+ #expect(wet.writtenSiteCount == dry.writtenSiteCount)
+ }
+
+ /// SHA-256 of every chunk file, so "nothing changed" is checkable without
+ /// keeping a second copy around.
+ private static func chunkDigests(of directory: URL) throws -> [String: String] {
+ var digests: [String: String] = [:]
+ for name in try FileManager.default.contentsOfDirectory(atPath: directory.path).sorted() {
+ let result = try ForceKernShell.run(
+ executable: URL(fileURLWithPath: "/usr/bin/shasum"),
+ arguments: ["-a", "256", directory.appendingPathComponent(name).path]
+ )
+ guard result.status == 0 else { throw CocoaError(.fileReadUnknown) }
+ digests[name] = String(result.stdout.prefix(64))
+ }
+ return digests
+ }
+}
+
+// MARK: - Discovery and classification
+
+@Suite(.serialized, .enabled(if: ForceKernFixture.runs, ForceKernFixture.skipReason))
+struct DSCIOMFBForceKernDiscoveryTests {
+ /// Discovery has to agree with the reference's, which reads the same image
+ /// through `ipsw dyld symaddr`. Compared here without `ipsw`: the pairs the
+ /// resolver finds are the pairs the reference logs.
+ @Test("Every discovered pair matches the reference's, name and address")
+ func discoveryMatchesReference() throws {
+ let pristine = try #require(ForceKernFixture.pristine, ForceKernFixture.missing)
+ try #require(ForceKernFixture.python != nil, "project venv is required")
+
+ let resolver = try DSCSymbolResolver(
+ mainCacheURL: pristine.appendingPathComponent("dyld_shared_cache_arm64e")
+ )
+ let entries = try DSCIOMFBForceKernPatcher.discoverEntryPoints(resolver: resolver)
+ #expect(entries.count >= DSCIOMFBForceKernPatcher.requiredSuffixes.count)
+
+ // The reference names every pair it considers in its dry-run log, as
+ // either a `[+] <public> @ 0xVA: … -> 'b <kern>' (0xVA)` or a
+ // `[=] <public> not a thin trampoline` line.
+ let clone = try ForceKernFixture.cloneCache(named: "discovery")
+ defer { ForceKernFixture.discard(clone) }
+ let reference = try ForceKernShell.runReference(on: clone, dryRun: true)
+ #expect(reference.status == 0, "reference dry run failed:\n\(reference.stderr)")
+
+ var referencePairs: [String: UInt64] = [:]
+ var referenceNames: Set<String> = []
+ for line in reference.stdout.split(separator: "\n") {
+ guard let name = line.split(separator: " ").first(where: {
+ $0.hasPrefix(DSCIOMFBForceKernPatcher.publicPrefix)
+ }) else { continue }
+ referenceNames.insert(String(name))
+ // "… @ 0x22AC0C1B0: …" — the public address it decided to rewrite.
+ guard let at = line.range(of: " @ 0x") else { continue }
+ let rest = line[at.upperBound...].prefix { $0.isHexDigit }
+ if let address = UInt64(rest, radix: 16) { referencePairs[String(name)] = address }
+ }
+
+ let discovered = Set(entries.map(\.publicName))
+ let disagreement = discovered.symmetricDifference(referenceNames).sorted()
+ #expect(discovered == referenceNames, "discovery differs from the reference: \(disagreement)")
+ for entry in entries {
+ guard let referenceAddress = referencePairs[entry.publicName] else { continue }
+ let mine = String(entry.publicAddress, radix: 16)
+ let theirs = String(referenceAddress, radix: 16)
+ #expect(
+ referenceAddress == entry.publicAddress,
+ "\(entry.publicName): swift 0x\(mine) vs reference 0x\(theirs)"
+ )
+ }
+ }
+
+ /// The three the reference refuses to ship without.
+ @Test("The required entry points are present and forcible")
+ func requiredEntryPointsAreForcible() throws {
+ let pristine = try #require(ForceKernFixture.pristine, ForceKernFixture.missing)
+ let chunks = try DSCChunkSet(directory: pristine)
+ let resolver = try DSCSymbolResolver(chunks: chunks)
+ let entries = try DSCIOMFBForceKernPatcher.discoverEntryPoints(resolver: resolver)
+
+ let disassembler = ARM64Disassembler()
+ for required in DSCIOMFBForceKernPatcher.requiredSuffixes {
+ let entry = try #require(
+ entries.first { $0.suffix == required },
+ "no entry point discovered for \(required)"
+ )
+ let instructions = disassembler.disassemble(
+ try chunks.bytesAtVMA(entry.publicAddress, length: 16),
+ at: entry.publicAddress,
+ count: 4
+ )
+ #expect(
+ DSCIOMFBForceKernPatcher.isDispatchTrampoline(instructions),
+ "\(entry.publicName) is not a thin dispatch trampoline"
+ )
+ }
+ }
+
+ /// The shape check has to be discriminating, not a rubber stamp: the
+ /// reference leaves several entry points on the virt path on this cache, and
+ /// so must this. A matcher that accepted everything would still pass the
+ /// byte comparison only if it happened to agree — it does not, so pin it.
+ @Test("Non-trampoline entry points are recognised and left alone")
+ func nonTrampolinesAreLeftAlone() throws {
+ let pristine = try #require(ForceKernFixture.pristine, ForceKernFixture.missing)
+
+ let clone = try ForceKernFixture.cloneCache(named: "shapes")
+ defer { ForceKernFixture.discard(clone) }
+ let dry = try DSCIOMFBForceKernPatcher.patch(
+ chunksDirectory: clone,
+ dryRun: true,
+ log: nil
+ )
+
+ #expect(!dry.notTrampolines.isEmpty, "every discovered entry point matched the shape")
+ #expect(dry.forced.count + dry.notTrampolines.count + dry.alreadyForced.count == dry.sites.count)
+
+ // And each rejection is a real one: its first instruction is not the
+ // trampoline's `cbz x0`, or the three that follow are not the load,
+ // null-check and tail-call.
+ let chunks = try DSCChunkSet(directory: pristine)
+ let disassembler = ARM64Disassembler()
+ for site in dry.notTrampolines {
+ let instructions = disassembler.disassemble(
+ try chunks.bytesAtVMA(site.entry.publicAddress, length: 16),
+ at: site.entry.publicAddress,
+ count: 4
+ )
+ #expect(!DSCIOMFBForceKernPatcher.isDispatchTrampoline(instructions))
+ print("[force-kern] left on virt: \(site.entry.publicName) — \(site.originalDisassembly)")
+ }
+ }
+
+ /// Each written site is a 4-byte `b` at the public entry point, aimed at the
+ /// kern sibling — checked from the record the patcher emits, which is what
+ /// the record-comparison harness consumes.
+ @Test("Every record is a four-byte branch to the paired kern implementation")
+ func recordsDescribeTheBranches() throws {
+ _ = try #require(ForceKernFixture.pristine, ForceKernFixture.missing)
+
+ let clone = try ForceKernFixture.cloneCache(named: "records")
+ defer { ForceKernFixture.discard(clone) }
+ let outcome = try DSCIOMFBForceKernPatcher.patch(chunksDirectory: clone, log: nil)
+
+ #expect(outcome.records.count == outcome.writtenSiteCount)
+ let chunks = try DSCChunkSet(directory: clone)
+ let disassembler = ARM64Disassembler()
+ for record in outcome.records {
+ #expect(record.patchID.hasPrefix("\(DSCIOMFBForceKernPatcher.recordGroup)."))
+ #expect(record.patchedBytes.count == 4)
+ #expect(record.originalBytes.count == 4)
+ #expect(record.originalBytes != record.patchedBytes)
+ let address = try #require(record.virtualAddress)
+ let instruction = try #require(
+ disassembler.disassembleOne(
+ try chunks.bytesAtVMA(address, length: 4),
+ at: address
+ )
+ )
+ #expect(instruction.mnemonic == "b")
+ }
+ }
+}
diff --git a/tests/FirmwarePatcherTests/DSCIOMFBSwapEndTests.swift b/tests/FirmwarePatcherTests/DSCIOMFBSwapEndTests.swift
new file mode 100644
index 00000000..3939d5c4
--- /dev/null
+++ b/tests/FirmwarePatcherTests/DSCIOMFBSwapEndTests.swift
@@ -0,0 +1,582 @@
+// DSCIOMFBSwapEndTests.swift — Parity for the IOMFB SwapEnd payload-size patch.
+//
+// There is no independent checker for a patched dyld shared cache: `codesign -v`
+// does not apply to a cache chunk, and the only other implementation of this
+// patch is `scripts/patchers/cfw_patch_iomfb_swapend.py`. So the parity test is
+// literal. Two clones of the real 24A435 arm64e cache; the Python patches one
+// through its own CLI (`cfw.py patch-iomfb-swapend`, exactly as
+// `cfw_install*.sh` and `cfw-kit` invoke it), `DSCIOMFBSwapEndPatcher` patches
+// the other, and then all 79 chunk files are compared byte for byte. Anything
+// short of byte-identical is a failing port, including a patch that lands in the
+// right place but re-attests a different page.
+//
+// The cache is required. `VPHONE_DSC_PRISTINE` points at it, defaulting to
+// `ipsws/ref_extract/dsc_pristine`, and its absence FAILS rather than passing
+// quietly: a `guard let … else { return }` is reported by Swift Testing as a
+// pass, so "the tests are green" would be equally compatible with "the tests did
+// nothing". A machine that genuinely cannot carry the 6.7 GB fixture sets
+// `VPHONE_DSC_FIXTURE_OPTIONAL=1` and gets a visible *skip* instead.
+//
+// Nothing here writes into the pristine directory. Clones are made with
+// `clonefile` (`cp -c`) into `ipsws/scratch_dsciomfbswapend`, which is on the
+// same filesystem, so a clone is instant and costs only the pages that change.
+// Override the location with `VPHONE_DSC_SCRATCH`.
+//
+// The shape tests below need none of that: they assemble the call set-up with
+// `ARM64Encoder` — the same instructions `cfw_patch_iomfb_swapend._self_test()`
+// builds with keystone — and run the finder over it, so the anchor's semantics
+// are pinned on every machine, fixture or no fixture.
+
+import Capstone
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+
+// MARK: - Fixture discovery
+
+private enum SwapEndFixture {
+ static let repoRoot = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+
+ /// The read-only reference cache. Never written to.
+ static var pristine: URL? {
+ let url = ProcessInfo.processInfo.environment["VPHONE_DSC_PRISTINE"]
+ .map { URL(fileURLWithPath: $0) }
+ ?? repoRoot.appendingPathComponent("ipsws/ref_extract/dsc_pristine")
+ let main = url.appendingPathComponent("dyld_shared_cache_arm64e")
+ return FileManager.default.fileExists(atPath: main.path) ? url : nil
+ }
+
+ /// Opt-out for a machine that cannot carry the fixture. Set it and the
+ /// parity suite reports as skipped; leave it unset and a missing cache is a
+ /// failure, which is the only reading of "green" this patch can afford.
+ static var isOptional: Bool {
+ ProcessInfo.processInfo.environment["VPHONE_DSC_FIXTURE_OPTIONAL"] == "1"
+ }
+
+ static var runs: Bool { pristine != nil || !isOptional }
+
+ static let missing: Comment = """
+ the real 24A435 arm64e shared cache is required — put it at \
+ ipsws/ref_extract/dsc_pristine, point VPHONE_DSC_PRISTINE at it, or set \
+ VPHONE_DSC_FIXTURE_OPTIONAL=1 to skip these tests instead of failing
+ """
+
+ static let skipReason: Comment =
+ "VPHONE_DSC_FIXTURE_OPTIONAL=1 and no dyld_shared_cache_arm64e fixture present"
+
+ static let venvMissing: Comment = """
+ the project venv is required for the cross-check against \
+ scripts/patchers/cfw_patch_iomfb_swapend.py — run `make setup_venv`
+ """
+
+ /// Where clones go. Deliberately *not* under `ipsws/ref_extract`: that tree
+ /// is the pristine reference the rest of the suite compares against, and
+ /// nothing here may leave anything in it.
+ static var scratchRoot: URL {
+ ProcessInfo.processInfo.environment["VPHONE_DSC_SCRATCH"]
+ .map { URL(fileURLWithPath: $0) }
+ ?? repoRoot.appendingPathComponent("ipsws/scratch_dsciomfbswapend")
+ }
+
+ /// The project venv, which is where the reference Python lives.
+ static var python: URL? {
+ let url = repoRoot.appendingPathComponent(".venv/bin/python3")
+ return FileManager.default.fileExists(atPath: url.path) ? url : nil
+ }
+
+ /// The CLI the install scripts call, which is the contract being preserved.
+ static var patcherCLI: URL {
+ repoRoot.appendingPathComponent("scripts/patchers/cfw.py")
+ }
+
+ /// Clone the pristine cache into a fresh directory the caller may write to.
+ static func cloneCache(named name: String) throws -> URL {
+ guard let pristine else { throw CocoaError(.fileNoSuchFile) }
+ let destination = scratchRoot.appendingPathComponent(name)
+ try? FileManager.default.removeItem(at: destination)
+ try FileManager.default.createDirectory(
+ at: destination,
+ withIntermediateDirectories: true
+ )
+ let result = try SwapEndSubprocess.run(
+ executable: URL(fileURLWithPath: "/bin/cp"),
+ arguments: ["-c", "-R"]
+ + (try FileManager.default.contentsOfDirectory(atPath: pristine.path))
+ .sorted()
+ .map { pristine.appendingPathComponent($0).path }
+ + [destination.path]
+ )
+ guard result.status == 0 else { throw CocoaError(.fileWriteUnknown) }
+ return destination
+ }
+
+ /// Discard clones, and the scratch root with them once the last one is
+ /// gone, so a green run leaves the working tree exactly as it found it.
+ static func discard(_ clones: URL...) {
+ for clone in clones {
+ try? FileManager.default.removeItem(at: clone)
+ }
+ let remaining = (try? FileManager.default
+ .contentsOfDirectory(atPath: scratchRoot.path)) ?? []
+ if remaining.isEmpty {
+ try? FileManager.default.removeItem(at: scratchRoot)
+ }
+ }
+}
+
+// MARK: - Subprocess helper
+
+private enum SwapEndSubprocess {
+ struct Result {
+ let status: Int32
+ let stdout: String
+ let stderr: String
+ }
+
+ @discardableResult
+ static func run(executable: URL, arguments: [String]) throws -> Result {
+ let process = Process()
+ process.executableURL = executable
+ process.arguments = arguments
+ let out = Pipe()
+ let err = Pipe()
+ process.standardOutput = out
+ process.standardError = err
+ try process.run()
+ // Drain before waiting: a full pipe buffer would deadlock the patcher.
+ let outData = out.fileHandleForReading.readDataToEndOfFile()
+ let errData = err.fileHandleForReading.readDataToEndOfFile()
+ process.waitUntilExit()
+ return Result(
+ status: process.terminationStatus,
+ stdout: String(decoding: outData, as: UTF8.self),
+ stderr: String(decoding: errData, as: UTF8.self)
+ )
+ }
+}
+
+// MARK: - What the reference Python did, read back off its own output
+
+/// The Python prints one line per site it writes. Parsing that is how the test
+/// learns the *number of sites* and the address the reference chose, without
+/// this file writing either of them down.
+private struct PythonSwapEndRun {
+ /// Addresses the Python said it wrote.
+ let siteVMAs: [UInt64]
+ /// The address it reported when it found the size already correct.
+ let alreadyCorrectVMA: UInt64?
+ let output: String
+
+ var sitesWritten: Int { siteVMAs.count }
+ var alreadyCorrect: Bool { alreadyCorrectVMA != nil }
+ /// The site the Python landed on, whether or not it wrote to it.
+ var siteVMA: UInt64? { siteVMAs.first ?? alreadyCorrectVMA }
+
+ init(output: String) {
+ self.output = output
+ var written: [UInt64] = []
+ var already: UInt64?
+ for line in output.split(separator: "\n") {
+ if line.contains("[+] patched"), line.contains("_kern_SwapEnd size"),
+ let match = line.firstMatch(of: /\bat 0x([0-9A-Fa-f]+)\b/),
+ let vma = UInt64(match.1, radix: 16)
+ {
+ written.append(vma)
+ }
+ if line.contains("[=] already"),
+ let match = line.firstMatch(of: /\bat 0x([0-9A-Fa-f]+)\b/),
+ let vma = UInt64(match.1, radix: 16)
+ {
+ already = vma
+ }
+ }
+ siteVMAs = written
+ alreadyCorrectVMA = already
+ }
+}
+
+// MARK: - Byte-for-byte cache comparison
+
+private enum CacheComparison {
+ /// Every file in `left` that is not byte-identical to its twin in `right`.
+ ///
+ /// `cmp` rather than a hash: it stops at the first differing byte, so an
+ /// identical pair of 6.7 GB trees costs one streaming read and a mismatch
+ /// costs almost nothing.
+ static func differingFiles(_ left: URL, _ right: URL) throws -> [String] {
+ let leftNames = try FileManager.default.contentsOfDirectory(atPath: left.path).sorted()
+ let rightNames = try FileManager.default.contentsOfDirectory(atPath: right.path).sorted()
+ guard leftNames == rightNames else {
+ return Array(Set(leftNames).symmetricDifference(rightNames)).sorted()
+ }
+ var differing: [String] = []
+ for name in leftNames {
+ let result = try SwapEndSubprocess.run(
+ executable: URL(fileURLWithPath: "/usr/bin/cmp"),
+ arguments: [
+ "-s",
+ left.appendingPathComponent(name).path,
+ right.appendingPathComponent(name).path,
+ ]
+ )
+ if result.status != 0 { differing.append(name) }
+ }
+ return differing
+ }
+}
+
+// MARK: - The call-setup shape, assembled rather than transcribed
+
+/// The `_kern_SwapEnd` external-method call set-up, built out of `ARM64Encoder`.
+///
+/// This is `cfw_patch_iomfb_swapend._self_test()`'s sequence, instruction for
+/// instruction, with the source size (0x548) deliberately unlike the target —
+/// so a finder that accidentally anchored on the *target* size would fail here.
+private enum SwapEndCallSetup {
+ static let baseAddress: UInt64 = 0x1000
+ static let sourceSize: UInt16 = 0x548
+ /// Where the `mov w3, #imm` sits: three instructions in.
+ static let sizeIndex = 3
+
+ static func assemble(
+ selector: UInt16 = 5,
+ size: UInt16 = sourceSize,
+ terminator: Data? = nil
+ ) -> Data? {
+ let branchPC = Int(baseAddress) + 24
+ guard let ldr = ARM64Encoder.encodeLdrWUnsignedOffset(rt: 0, rn: 0, offset: 0x14),
+ let add = ARM64Encoder.encodeAddImm12(rd: 2, rn: 19, imm12: 0x18),
+ let selectorMove = ARM64Encoder.encodeMovzW(rd: 1, imm16: selector),
+ let sizeMove = ARM64Encoder.encodeMovzW(rd: 3, imm16: size),
+ let zeroX4 = ARM64Encoder.encodeMovzX(rd: 4, imm16: 0),
+ let zeroX5 = ARM64Encoder.encodeMovzX(rd: 5, imm16: 0),
+ let call = ARM64Encoder.encodeBL(from: branchPC, to: branchPC + 0x40)
+ else { return nil }
+ return ldr + add + selectorMove + sizeMove + zeroX4 + zeroX5 + (terminator ?? call)
+ }
+
+ static func disassemble(_ code: Data, _ disassembler: ARM64Disassembler) -> [Instruction] {
+ disassembler.disassemble(code, at: baseAddress, count: code.count / 4)
+ }
+}
+
+// MARK: - 1 · The anchor, with no cache in sight
+
+@Suite
+struct DSCIOMFBSwapEndShapeTests {
+ @Test("The finder lands on the size move of the external-method call set-up")
+ func findsTheSizeMove() throws {
+ let disassembler = ARM64Disassembler()
+ let code = try #require(SwapEndCallSetup.assemble())
+ let instructions = SwapEndCallSetup.disassemble(code, disassembler)
+ #expect(instructions.count == 7)
+
+ let site = try #require(
+ DSCIOMFBSwapEndPatcher.findSizeInstruction(
+ in: instructions,
+ disassembler: disassembler
+ )
+ )
+ #expect(site.index == SwapEndCallSetup.sizeIndex)
+ #expect(
+ site.instruction.address
+ == SwapEndCallSetup.baseAddress + UInt64(SwapEndCallSetup.sizeIndex * 4)
+ )
+
+ let decoded = try #require(
+ DSCIOMFBSwapEndPatcher.movRegisterImmediate(
+ site.instruction,
+ disassembler: disassembler
+ )
+ )
+ #expect(decoded.register == DSCIOMFBSwapEndPatcher.sizeRegister)
+ #expect(decoded.immediate == Int64(SwapEndCallSetup.sourceSize))
+ print("[shape] size move at index \(site.index): \(site.instruction)")
+ }
+
+ @Test("A different selector is not this call, and is not patched")
+ func rejectsAnotherSelector() throws {
+ let disassembler = ARM64Disassembler()
+ // Selector 6 is some other external method of the same userclient; the
+ // size it passes is none of this patcher's business.
+ let code = try #require(SwapEndCallSetup.assemble(selector: 6))
+ let instructions = SwapEndCallSetup.disassemble(code, disassembler)
+ #expect(
+ DSCIOMFBSwapEndPatcher.findSizeInstruction(
+ in: instructions,
+ disassembler: disassembler
+ ) == nil
+ )
+ }
+
+ @Test("Without the call itself the shape is not a call set-up")
+ func rejectsASequenceThatNeverCalls() throws {
+ let disassembler = ARM64Disassembler()
+ let code = try #require(SwapEndCallSetup.assemble(terminator: ARM64.nop))
+ let instructions = SwapEndCallSetup.disassemble(code, disassembler)
+ #expect(
+ DSCIOMFBSwapEndPatcher.findSizeInstruction(
+ in: instructions,
+ disassembler: disassembler
+ ) == nil
+ )
+ }
+
+ @Test("The replacement is the encoder's MOVZ, for every size a base kernel wants")
+ func replacementComesFromTheEncoder() throws {
+ // 0x560 is the 26.1 base, 0x588 the 26.4 one; both are passed by
+ // `cfw_install*.sh` / `cfw-kit` today.
+ for size: UInt16 in [0x560, 0x588] {
+ let encoded = try #require(ARM64Encoder.encodeMovzW(rd: 3, imm16: size))
+ #expect(encoded.count == 4)
+ let decoded = try #require(
+ ARM64Disassembler().disassembleOne(encoded, at: SwapEndCallSetup.baseAddress)
+ )
+ let move = try #require(
+ DSCIOMFBSwapEndPatcher.movRegisterImmediate(
+ decoded,
+ disassembler: ARM64Disassembler()
+ )
+ )
+ #expect(move.register == DSCIOMFBSwapEndPatcher.sizeRegister)
+ #expect(move.immediate == Int64(size))
+ }
+ }
+
+ @Test("A size that will not fit a MOVZ immediate is refused, not truncated")
+ func oversizedTargetIsRefused() throws {
+ #expect(throws: PatcherError.self) {
+ _ = try DSCIOMFBSwapEndPatcher.replacement(forTargetSize: 0x1_0000)
+ }
+ // And it is refused before the 6.7 GB cache is opened, so the caller
+ // gets "that size cannot be encoded" rather than whatever the cache
+ // would have said first. A path that does not exist proves the order:
+ // if the guard moved after the open, this would throw a DSCError.
+ var thrown: (any Error)?
+ do {
+ _ = try DSCIOMFBSwapEndPatcher.patch(
+ chunksDirectory: URL(fileURLWithPath: "/nonexistent-dyld-cache"),
+ targetSize: 0x1_0000,
+ dryRun: true,
+ log: nil
+ )
+ } catch {
+ thrown = error
+ }
+ let error = try #require(thrown)
+ #expect("\(error)".contains("MOVZ"), "unexpected error: \(error)")
+ }
+}
+
+// MARK: - 2 · Parity against the Python, on the real cache
+
+@Suite(.serialized, .enabled(if: SwapEndFixture.runs, SwapEndFixture.skipReason))
+struct DSCIOMFBSwapEndParityTests {
+ /// Run the reference Python through the CLI the install scripts use.
+ private func runPython(on directory: URL, targetSize: UInt32) throws -> PythonSwapEndRun {
+ let python = try #require(SwapEndFixture.python, SwapEndFixture.venvMissing)
+ let result = try SwapEndSubprocess.run(
+ executable: python,
+ arguments: [
+ SwapEndFixture.patcherCLI.path,
+ "patch-iomfb-swapend",
+ directory.path,
+ "--target-size",
+ "0x" + String(targetSize, radix: 16),
+ ]
+ )
+ #expect(result.status == 0, "python patcher failed: \(result.stdout)\(result.stderr)")
+ return PythonSwapEndRun(output: result.stdout)
+ }
+
+ /// The three sizes that matter: the 26.4 base's, the 26.1 base's, and the
+ /// size this cache's own userland already sends — which is the case where
+ /// the right answer is to write nothing at all.
+ ///
+ /// 0x6e0 is not an anchor and the patcher never compares against it; it is
+ /// here because a cache that already agrees with the target is the one
+ /// shape where "wrote one site" and "wrote none" are both plausible bugs.
+ static let targetSizes: [UInt32] = [0x588, 0x560, 0x6E0]
+
+ @Test(
+ "Swift and Python patch the real cache to the same bytes",
+ arguments: targetSizes
+ )
+ func matchesPythonByteForByte(targetSize: UInt32) throws {
+ let pristine = try #require(SwapEndFixture.pristine, SwapEndFixture.missing)
+ let suffix = String(targetSize, radix: 16)
+
+ let pythonClone = try SwapEndFixture.cloneCache(named: "python_\(suffix)")
+ let swiftClone = try SwapEndFixture.cloneCache(named: "swift_\(suffix)")
+ defer { SwapEndFixture.discard(pythonClone, swiftClone) }
+
+ let reference = try runPython(on: pythonClone, targetSize: targetSize)
+ let mine = try DSCIOMFBSwapEndPatcher.patch(
+ chunksDirectory: swiftClone,
+ targetSize: targetSize,
+ log: nil
+ )
+
+ // Same number of sites, at the same address, from the same source size.
+ #expect(
+ mine.sitesWritten == reference.sitesWritten,
+ "swift wrote \(mine.sitesWritten) site(s), python wrote \(reference.sitesWritten)"
+ )
+ #expect(mine.wasAlreadyCorrect == reference.alreadyCorrect)
+ let referenceVMA = try #require(
+ reference.siteVMA,
+ "the Python reported no SwapEnd site at all: \(reference.output)"
+ )
+ #expect(mine.siteVMA == referenceVMA)
+ #expect(mine.targetSize == targetSize)
+
+ // And, the part that actually matters: identical caches.
+ let differing = try CacheComparison.differingFiles(pythonClone, swiftClone)
+ #expect(differing.isEmpty, "chunks differ between Swift and Python: \(differing)")
+
+ // A patch that changed nothing would also pass the comparison above, so
+ // pin what changed relative to the untouched cache.
+ let touched = try CacheComparison.differingFiles(pristine, swiftClone)
+ if mine.sitesWritten == 0 {
+ #expect(touched.isEmpty, "nothing should have been written, but \(touched) changed")
+ } else {
+ #expect(
+ touched.count == 1,
+ "expected exactly one chunk to change, got \(touched)"
+ )
+ let reattested = try #require(mine.reattestation)
+ #expect(reattested.updated.count == 1)
+ #expect(reattested.isFullyAttested)
+ }
+
+ print(
+ "[parity 0x\(suffix)] python \(reference.sitesWritten) site(s), "
+ + "swift \(mine.sitesWritten) site(s) "
+ + "(0x\(String(mine.originalSize, radix: 16, uppercase: true)) -> "
+ + "0x\(String(mine.targetSize, radix: 16, uppercase: true)) at "
+ + "0x\(String(mine.siteVMA, radix: 16, uppercase: true))); "
+ + "chunks changed: \(touched); swift vs python: identical"
+ )
+ }
+
+ @Test("A dry run reports the site and leaves every chunk untouched")
+ func dryRunWritesNothing() throws {
+ let pristine = try #require(SwapEndFixture.pristine, SwapEndFixture.missing)
+ let clone = try SwapEndFixture.cloneCache(named: "dry")
+ defer { SwapEndFixture.discard(clone) }
+
+ let mine = try DSCIOMFBSwapEndPatcher.patch(
+ chunksDirectory: clone,
+ targetSize: 0x588,
+ dryRun: true,
+ log: nil
+ )
+ #expect(mine.sitesWritten == 0)
+ #expect(mine.reattestation == nil)
+ #expect(mine.siteVMA != 0)
+ #expect(mine.originalSize != 0)
+
+ let touched = try CacheComparison.differingFiles(pristine, clone)
+ #expect(touched.isEmpty, "a dry run wrote to \(touched)")
+ print(
+ "[dry-run] would patch 0x\(String(mine.originalSize, radix: 16, uppercase: true)) "
+ + "-> 0x588 at 0x\(String(mine.siteVMA, radix: 16, uppercase: true)); "
+ + "0 chunks changed"
+ )
+ }
+
+ @Test("Patching an already-patched cache is a no-op, not a second write")
+ func secondRunChangesNothing() throws {
+ try #require(SwapEndFixture.pristine != nil, SwapEndFixture.missing)
+ let clone = try SwapEndFixture.cloneCache(named: "idempotent")
+ let afterFirst = try SwapEndFixture.cloneCache(named: "idempotent_snapshot")
+ defer { SwapEndFixture.discard(clone, afterFirst) }
+
+ let first = try DSCIOMFBSwapEndPatcher.patch(
+ chunksDirectory: clone,
+ targetSize: 0x588,
+ log: nil
+ )
+ #expect(first.sitesWritten == 1)
+ #expect(!first.wasAlreadyCorrect)
+
+ // Snapshot the patched cache, then run again over it.
+ try? FileManager.default.removeItem(at: afterFirst)
+ let copy = try SwapEndSubprocess.run(
+ executable: URL(fileURLWithPath: "/bin/cp"),
+ arguments: ["-c", "-R", clone.path, afterFirst.path]
+ )
+ #expect(copy.status == 0)
+
+ let second = try DSCIOMFBSwapEndPatcher.patch(
+ chunksDirectory: clone,
+ targetSize: 0x588,
+ log: nil
+ )
+ #expect(second.wasAlreadyCorrect)
+ #expect(second.sitesWritten == 0)
+ #expect(second.siteVMA == first.siteVMA)
+ #expect(second.originalSize == second.targetSize)
+
+ let differing = try CacheComparison.differingFiles(afterFirst, clone)
+ #expect(differing.isEmpty, "a second run rewrote \(differing)")
+ print("[idempotent] second run wrote 0 sites and changed 0 chunks")
+ }
+
+ @Test("The symbol and the site are found without `ipsw` on the patch path")
+ func resolvesWithoutIpsw() throws {
+ let pristine = try #require(SwapEndFixture.pristine, SwapEndFixture.missing)
+ let chunks = try DSCChunkSet(directory: pristine)
+ let resolver = try DSCSymbolResolver(chunks: chunks)
+ try resolver.requireLocalSymbols()
+
+ let functionVMA = try resolver.address(
+ of: DSCIOMFBSwapEndPatcher.symbolName,
+ inImage: DSCIOMFBSwapEndPatcher.imagePath
+ )
+ #expect(functionVMA != 0)
+
+ let disassembler = ARM64Disassembler()
+ let instructions = try DSCIOMFBSwapEndPatcher.disassembleFunction(
+ in: chunks,
+ at: functionVMA,
+ maximumInstructions: DSCIOMFBSwapEndPatcher.maximumInstructions,
+ disassembler: disassembler
+ )
+ #expect(!instructions.isEmpty)
+
+ let site = try #require(
+ DSCIOMFBSwapEndPatcher.findSizeInstruction(
+ in: instructions,
+ disassembler: disassembler
+ ),
+ "the SwapEnd call set-up was not found in \(DSCIOMFBSwapEndPatcher.symbolName)"
+ )
+ // The shape, on the real function: selector, size, two zeros, the call.
+ let selector = try #require(
+ DSCIOMFBSwapEndPatcher.movRegisterImmediate(
+ instructions[site.index - 1],
+ disassembler: disassembler
+ )
+ )
+ #expect(selector.register == "w1")
+ #expect(selector.immediate == DSCIOMFBSwapEndPatcher.selector)
+ #expect(instructions[site.index + 3].mnemonic == "bl")
+
+ let size = try #require(
+ DSCIOMFBSwapEndPatcher.movRegisterImmediate(
+ site.instruction,
+ disassembler: disassembler
+ )
+ )
+ print(
+ "[resolve] \(DSCIOMFBSwapEndPatcher.symbolName) @ "
+ + "0x\(String(functionVMA, radix: 16, uppercase: true)), size move "
+ + "0x\(String(size.immediate, radix: 16, uppercase: true)) @ "
+ + "0x\(String(site.instruction.address, radix: 16, uppercase: true))"
+ )
+ }
+}
diff --git a/tests/FirmwarePatcherTests/DSCLSDEmbeddedRegTests.swift b/tests/FirmwarePatcherTests/DSCLSDEmbeddedRegTests.swift
new file mode 100644
index 00000000..9360433e
--- /dev/null
+++ b/tests/FirmwarePatcherTests/DSCLSDEmbeddedRegTests.swift
@@ -0,0 +1,378 @@
+// DSCLSDEmbeddedRegTests.swift — parity for the lsd embedded-registration gate.
+//
+// The patch is one instruction in a 6.7 GB cache, and a wrong one is a boot
+// panic rather than a failing assertion, so the reference these tests grade
+// against is the Python that has already shipped: `cfw.py
+// patch-lsd-embedded-reg`. The centre of the suite runs both implementations
+// over two clones of the *real* cache and compares every byte of all 79 chunks
+// plus the `.symbols` side file.
+//
+// The cache is required. Point `VPHONE_DSC_PRISTINE` at a directory of
+// `dyld_shared_cache_arm64e*` chunks, or leave the default
+// `ipsws/ref_extract/dsc_pristine` in place. Without it these tests FAIL — the
+// suite never opens with a bare `return`, which Swift Testing reports as a
+// pass, so a green run cannot mean the cache was absent. A machine that
+// genuinely cannot carry the fixture sets `VPHONE_DSC_FIXTURE_OPTIONAL=1`,
+// which turns the failure into a visible skip.
+//
+// Nothing here writes to the pristine tree. Clones are made with `clonefile`
+// (instant and near-free on APFS) under the system temporary directory, or
+// under `VPHONE_DSC_SCRATCH` when the caller names one.
+
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+
+// MARK: - Fixture discovery
+
+private enum LSDRegFixture {
+ static let repoRoot = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+
+ /// The read-only reference cache.
+ static var pristine: URL? {
+ let url = ProcessInfo.processInfo.environment["VPHONE_DSC_PRISTINE"]
+ .map { URL(fileURLWithPath: $0) }
+ ?? repoRoot.appendingPathComponent("ipsws/ref_extract/dsc_pristine")
+ let main = url.appendingPathComponent("dyld_shared_cache_arm64e")
+ return FileManager.default.fileExists(atPath: main.path) ? url : nil
+ }
+
+ /// Opt-out for a machine that cannot carry the 6.7 GB fixture.
+ static var isOptional: Bool {
+ ProcessInfo.processInfo.environment["VPHONE_DSC_FIXTURE_OPTIONAL"] == "1"
+ }
+
+ /// The suite runs unless the cache is absent *and* the caller opted out.
+ static var runs: Bool { pristine != nil || !isOptional }
+
+ static let missing: Comment = """
+ the real 24A435 arm64e shared cache is required — put it at \
+ ipsws/ref_extract/dsc_pristine, point VPHONE_DSC_PRISTINE at it, or set \
+ VPHONE_DSC_FIXTURE_OPTIONAL=1 to skip these tests instead of failing
+ """
+
+ /// Where clones go. Deliberately *not* inside `ipsws/ref_extract`: that
+ /// tree is the pristine reference every DSC test compares against, and a
+ /// scratch directory next to it is one `rm -rf` typo away from destroying
+ /// a 6.7 GB extraction nobody can regenerate quickly.
+ static var scratchRoot: URL {
+ ProcessInfo.processInfo.environment["VPHONE_DSC_SCRATCH"]
+ .map { URL(fileURLWithPath: $0) }
+ ?? URL(fileURLWithPath: NSTemporaryDirectory())
+ .appendingPathComponent("vphone-dsc-lsd-embedded-reg")
+ }
+
+ /// The project venv, which is where the reference Python lives.
+ static var python: URL? {
+ let url = repoRoot.appendingPathComponent(".venv/bin/python3")
+ return FileManager.default.fileExists(atPath: url.path) ? url : nil
+ }
+
+ static var cfwPy: URL { repoRoot.appendingPathComponent("scripts/patchers/cfw.py") }
+
+ /// Clone the pristine cache into a fresh directory the caller may write to.
+ ///
+ /// `cp -c` asks for a `clonefile`, which costs no space and no time when
+ /// the scratch root is on the same APFS volume as the fixture. When it is
+ /// not — a caller who pointed `VPHONE_DSC_SCRATCH` at another disk — the
+ /// clone is refused, and the fallback is an ordinary copy rather than a
+ /// failed test.
+ static func cloneCache(named name: String) throws -> URL {
+ let pristine = try #require(self.pristine, missing)
+ let destination = scratchRoot.appendingPathComponent(name)
+ try? FileManager.default.removeItem(at: destination)
+ try FileManager.default.createDirectory(
+ at: destination,
+ withIntermediateDirectories: true
+ )
+ let entries = try FileManager.default
+ .contentsOfDirectory(atPath: pristine.path)
+ .sorted()
+ .map { pristine.appendingPathComponent($0).path }
+
+ for flags in [["-c", "-R"], ["-R"]] {
+ let result = try Shell.run(
+ executable: URL(fileURLWithPath: "/bin/cp"),
+ arguments: flags + entries + [destination.path]
+ )
+ if result.status == 0 { return destination }
+ }
+ Issue.record("could not clone the pristine cache into \(destination.path)")
+ throw CocoaError(.fileWriteUnknown)
+ }
+
+ /// Discard clones, and the scratch root with them once the last one is
+ /// gone, so a test run leaves the filesystem as it found it.
+ static func discard(_ clones: URL...) {
+ for clone in clones {
+ try? FileManager.default.removeItem(at: clone)
+ }
+ let remaining = (try? FileManager.default
+ .contentsOfDirectory(atPath: scratchRoot.path)) ?? []
+ if remaining.isEmpty {
+ try? FileManager.default.removeItem(at: scratchRoot)
+ }
+ }
+
+ /// Run the shipped Python patcher over `directory`.
+ static func runPython(on directory: URL, dryRun: Bool = false) throws -> Shell.Result {
+ let python = try #require(
+ self.python,
+ "the reference Python is required — run `make setup_venv`"
+ )
+ return try Shell.run(
+ executable: python,
+ arguments: [cfwPy.path, "patch-lsd-embedded-reg", directory.path]
+ + (dryRun ? ["--dry-run"] : []),
+ currentDirectory: repoRoot
+ )
+ }
+}
+
+// MARK: - Subprocess helper
+
+private enum Shell {
+ struct Result {
+ let status: Int32
+ let stdout: String
+ let stderr: String
+ }
+
+ @discardableResult
+ static func run(
+ executable: URL,
+ arguments: [String],
+ currentDirectory: URL? = nil
+ ) throws -> Result {
+ let process = Process()
+ process.executableURL = executable
+ process.arguments = arguments
+ if let currentDirectory { process.currentDirectoryURL = currentDirectory }
+ let out = Pipe()
+ let err = Pipe()
+ process.standardOutput = out
+ process.standardError = err
+ try process.run()
+ let outData = out.fileHandleForReading.readDataToEndOfFile()
+ let errData = err.fileHandleForReading.readDataToEndOfFile()
+ process.waitUntilExit()
+ return Result(
+ status: process.terminationStatus,
+ stdout: String(decoding: outData, as: UTF8.self),
+ stderr: String(decoding: errData, as: UTF8.self)
+ )
+ }
+}
+
+// MARK: - Byte-for-byte cache comparison
+
+private enum CacheComparison {
+ /// Every file name that differs between two cache directories.
+ ///
+ /// `cmp -s` rather than loading 6.7 GB into memory twice; file names are
+ /// compared first so a missing or extra chunk is reported as such.
+ static func differences(between lhs: URL, and rhs: URL) throws -> [String] {
+ let manager = FileManager.default
+ let left = Set(try manager.contentsOfDirectory(atPath: lhs.path))
+ let right = Set(try manager.contentsOfDirectory(atPath: rhs.path))
+ var differing = Array(left.symmetricDifference(right)).sorted()
+
+ for name in left.intersection(right).sorted() {
+ let result = try Shell.run(
+ executable: URL(fileURLWithPath: "/usr/bin/cmp"),
+ arguments: [
+ "-s",
+ lhs.appendingPathComponent(name).path,
+ rhs.appendingPathComponent(name).path,
+ ]
+ )
+ if result.status != 0 { differing.append(name) }
+ }
+ return differing.sorted()
+ }
+
+ /// How many chunk files differ from the pristine tree.
+ static func changedFiles(in directory: URL) throws -> [String] {
+ let pristine = try #require(LSDRegFixture.pristine, LSDRegFixture.missing)
+ return try differences(between: pristine, and: directory)
+ }
+}
+
+// MARK: - Gate discovery
+
+@Suite(
+ "DSC lsd embedded-registration gate",
+ .enabled(if: LSDRegFixture.runs, LSDRegFixture.missing),
+ .serialized
+)
+struct DSCLSDEmbeddedRegGateTests {
+ @Test("the gate is a cbz/cbnz on w0 whose fall-through sets a w register to 1")
+ func gateShape() throws {
+ let pristine = try #require(LSDRegFixture.pristine, LSDRegFixture.missing)
+ let chunks = try DSCChunkSet(directory: pristine)
+ let located = try #require(
+ try DSCLSDEmbeddedRegPatcher.locateGate(in: chunks),
+ "the iOS 27 fixture must carry \(DSCLSDEmbeddedRegPatcher.method)"
+ )
+
+ #expect(["cbz", "cbnz"].contains(located.gate.mnemonic))
+ #expect(!located.gate.wasAlreadyNOP)
+ #expect(located.gate.resultRegister.hasPrefix("w"))
+ #expect(located.gate.vma > located.functionVMA)
+ // The gate is inside the disassembly window, by construction.
+ #expect(
+ located.gate.vma
+ < located.functionVMA + UInt64(DSCLSDEmbeddedRegPatcher.maxInstructions * 4)
+ )
+ }
+
+ @Test("the symbol resolves through the cache's own local symbol table")
+ func symbolIsLocal() throws {
+ let pristine = try #require(LSDRegFixture.pristine, LSDRegFixture.missing)
+ let chunks = try DSCChunkSet(directory: pristine)
+ let address = try #require(
+ try chunks.resolveLocalSymbol(DSCLSDEmbeddedRegPatcher.method),
+ "\(DSCLSDEmbeddedRegPatcher.method) must be in the .symbols table"
+ )
+ // It has to live in an executable mapping, or it is not the method.
+ let mapping = try #require(chunks.mapping(forVMA: address))
+ #expect(mapping.isExecutable)
+ }
+}
+
+// MARK: - Parity against the Python
+
+@Suite(
+ "DSC lsd embedded-registration parity",
+ .enabled(if: LSDRegFixture.runs, LSDRegFixture.missing),
+ .serialized
+)
+struct DSCLSDEmbeddedRegParityTests {
+ @Test("Swift and Python produce byte-identical caches, one site each")
+ func byteForByteParity() throws {
+ let swiftClone = try LSDRegFixture.cloneCache(named: "swift")
+ let pythonClone = try LSDRegFixture.cloneCache(named: "python")
+ defer { LSDRegFixture.discard(swiftClone, pythonClone) }
+
+ let report = try DSCLSDEmbeddedRegPatcher.patch(
+ chunksDirectory: swiftClone,
+ log: nil
+ )
+ #expect(report.outcome == .patched)
+ #expect(report.sitesWritten == 1)
+ #expect(report.methodIsPresent)
+
+ let python = try LSDRegFixture.runPython(on: pythonClone)
+ #expect(python.status == 0, "python failed: \(python.stdout)\(python.stderr)")
+ // The Python names each site it writes; one NOP is the whole patch.
+ let pythonSites = python.stdout
+ .split(separator: "\n")
+ .filter { $0.contains("NOP'd gate") }
+ #expect(pythonSites.count == 1, "python wrote \(pythonSites.count) sites")
+
+ let differences = try CacheComparison.differences(between: swiftClone, and: pythonClone)
+ #expect(differences.isEmpty, "chunks differ between Swift and Python: \(differences)")
+
+ // …and both changed exactly the one chunk holding the gate's page.
+ let changed = try CacheComparison.changedFiles(in: swiftClone)
+ #expect(changed.count == 1, "Swift touched \(changed.count) chunk(s): \(changed)")
+ #expect(changed == (try CacheComparison.changedFiles(in: pythonClone)))
+ }
+
+ @Test("the recorded write names the chunk, its offset and the gate address")
+ func recordDescribesTheSite() throws {
+ let clone = try LSDRegFixture.cloneCache(named: "record")
+ defer { LSDRegFixture.discard(clone) }
+
+ let report = try DSCLSDEmbeddedRegPatcher.patch(chunksDirectory: clone, log: nil)
+ let record = try #require(report.record)
+ let gate = try #require(report.gate)
+
+ #expect(record.patchID == DSCLSDEmbeddedRegPatcher.patchID)
+ #expect(record.component.hasPrefix("dyld_shared_cache_arm64e"))
+ #expect(record.virtualAddress == gate.vma)
+ #expect(record.patchedBytes == ARM64.nop)
+ #expect(record.originalBytes != ARM64.nop)
+ #expect(record.originalBytes.count == 4)
+ #expect(record.afterDisasm == "nop")
+ #expect(record.beforeDisasm.hasPrefix(gate.mnemonic))
+
+ // The offset has to name the byte that changed, in the file it names.
+ let handle = try FileHandle(
+ forReadingFrom: clone.appendingPathComponent(record.component)
+ )
+ defer { try? handle.close() }
+ try handle.seek(toOffset: UInt64(record.fileOffset))
+ #expect(try handle.read(upToCount: 4) == ARM64.nop)
+ }
+}
+
+// MARK: - Re-runs and dry runs
+
+@Suite(
+ "DSC lsd embedded-registration re-runs",
+ .enabled(if: LSDRegFixture.runs, LSDRegFixture.missing),
+ .serialized
+)
+struct DSCLSDEmbeddedRegRerunTests {
+ @Test("a second Swift run is idempotent and leaves the bytes alone")
+ func swiftIsIdempotent() throws {
+ let clone = try LSDRegFixture.cloneCache(named: "idempotent")
+ defer { LSDRegFixture.discard(clone) }
+
+ let first = try DSCLSDEmbeddedRegPatcher.patch(chunksDirectory: clone, log: nil)
+ #expect(first.outcome == .patched)
+ let afterFirst = try CacheComparison.changedFiles(in: clone)
+
+ let second = try DSCLSDEmbeddedRegPatcher.patch(chunksDirectory: clone, log: nil)
+ #expect(second.outcome == .alreadyPatched)
+ #expect(second.sitesWritten == 0)
+ #expect(second.gate?.wasAlreadyNOP == true)
+ #expect(second.gate?.vma == first.gate?.vma)
+
+ #expect(try CacheComparison.changedFiles(in: clone) == afterFirst)
+ }
+
+ @Test("Python over a Swift-patched cache is a no-op, and the reverse too")
+ func crossImplementationRerunsAgree() throws {
+ let clone = try LSDRegFixture.cloneCache(named: "cross")
+ defer { LSDRegFixture.discard(clone) }
+
+ try DSCLSDEmbeddedRegPatcher.patch(chunksDirectory: clone, log: nil)
+ let afterSwift = try Data(
+ contentsOf: clone.appendingPathComponent("dyld_shared_cache_arm64e")
+ ).count
+
+ let python = try LSDRegFixture.runPython(on: clone)
+ #expect(python.status == 0, "python failed: \(python.stdout)\(python.stderr)")
+ #expect(python.stdout.contains("already NOP"))
+ #expect(!python.stdout.contains("NOP'd gate"))
+
+ // The Python re-run must not have moved anything.
+ #expect(
+ try Data(contentsOf: clone.appendingPathComponent("dyld_shared_cache_arm64e"))
+ .count == afterSwift
+ )
+ let report = try DSCLSDEmbeddedRegPatcher.patch(chunksDirectory: clone, log: nil)
+ #expect(report.outcome == .alreadyPatched)
+ }
+
+ @Test("a dry run locates the gate and writes nothing")
+ func dryRunWritesNothing() throws {
+ let clone = try LSDRegFixture.cloneCache(named: "dryrun")
+ defer { LSDRegFixture.discard(clone) }
+
+ let report = try DSCLSDEmbeddedRegPatcher.patch(
+ chunksDirectory: clone,
+ dryRun: true,
+ log: nil
+ )
+ #expect(report.outcome == .wouldPatch)
+ #expect(report.sitesWritten == 0)
+ #expect(report.gate != nil)
+ #expect(try CacheComparison.changedFiles(in: clone).isEmpty)
+ }
+}
diff --git a/tests/FirmwarePatcherTests/DSCLockdownModePatcherTests.swift b/tests/FirmwarePatcherTests/DSCLockdownModePatcherTests.swift
new file mode 100644
index 00000000..e0028a52
--- /dev/null
+++ b/tests/FirmwarePatcherTests/DSCLockdownModePatcherTests.swift
@@ -0,0 +1,484 @@
+// DSCLockdownModePatcherTests.swift — Parity for the lockdown-mode DSC patch.
+//
+// The only independent reference for this patch is
+// `scripts/patchers/cfw_patch_lockdown_mode.py`, driven exactly as
+// `cfw_install.sh` drives it: `cfw.py patch-lockdown-mode <chunks_dir>`. So the
+// central test here clones the real cache twice, runs the Python on one clone
+// and `DSCLockdownModePatcher` on the other, and compares the two patched
+// directories byte for byte — chunk bytes and re-attested code slots alike.
+//
+// The tests need the real cache. Point `VPHONE_DSC_PRISTINE` at a directory of
+// `dyld_shared_cache_arm64e*` chunks, or leave the default
+// `ipsws/ref_extract/dsc_pristine` in place.
+//
+// Without it they FAIL. They do not open with a bare `return` on a missing
+// fixture: Swift Testing reports that as a pass, so "all tests passed" would be
+// equally compatible with "no test touched a cache". A machine that genuinely
+// cannot carry the 6.7 GB fixture sets `VPHONE_DSC_FIXTURE_OPTIONAL=1`, which
+// turns the failure into a visible *skip*.
+//
+// Nothing here writes into the pristine directory, or anywhere else in the
+// working tree. Clones are made with `clonefile` under the system temp
+// directory — instant and near-free on APFS — and removed again.
+
+import Capstone
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+
+// MARK: - Fixture discovery
+
+private enum LockdownFixture {
+ static let repoRoot = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+
+ /// The read-only reference cache.
+ static var pristine: URL? {
+ let url = ProcessInfo.processInfo.environment["VPHONE_DSC_PRISTINE"]
+ .map { URL(fileURLWithPath: $0) }
+ ?? repoRoot.appendingPathComponent("ipsws/ref_extract/dsc_pristine")
+ let main = url.appendingPathComponent("dyld_shared_cache_arm64e")
+ return FileManager.default.fileExists(atPath: main.path) ? url : nil
+ }
+
+ /// Opt-out for a machine that cannot carry the fixture. Set it and the
+ /// suite reports as skipped; leave it unset and a missing cache is a
+ /// failure, which is the only reading of "green" this patch can afford.
+ static var isOptional: Bool {
+ ProcessInfo.processInfo.environment["VPHONE_DSC_FIXTURE_OPTIONAL"] == "1"
+ }
+
+ /// The suite runs unless the cache is absent *and* the caller opted out.
+ static var runs: Bool { pristine != nil || !isOptional }
+
+ static let missing: Comment = """
+ the real 24A435 arm64e shared cache is required — put it at \
+ ipsws/ref_extract/dsc_pristine, point VPHONE_DSC_PRISTINE at it, or set \
+ VPHONE_DSC_FIXTURE_OPTIONAL=1 to skip these tests instead of failing
+ """
+
+ static let skipReason: Comment =
+ "VPHONE_DSC_FIXTURE_OPTIONAL=1 and no dyld_shared_cache_arm64e fixture present"
+
+ /// The project venv, which is where the reference Python lives.
+ static var python: URL? {
+ let url = repoRoot.appendingPathComponent(".venv/bin/python3")
+ return FileManager.default.fileExists(atPath: url.path) ? url : nil
+ }
+
+ /// `scripts/patchers/cfw.py`, the entry point `cfw_install.sh` calls.
+ static var cfwCLI: URL { repoRoot.appendingPathComponent("scripts/patchers/cfw.py") }
+
+ /// Where clones go. Deliberately outside the working tree: the reference
+ /// cache's directory is what the whole DSC suite compares against, and a
+ /// scratch clone has no business living inside it.
+ static var scratchRoot: URL {
+ FileManager.default.temporaryDirectory
+ .appendingPathComponent("vphone-dsc-lockdown", isDirectory: true)
+ }
+
+ /// Clone the pristine cache into a fresh directory the caller may write to.
+ ///
+ /// `cp -c` is `clonefile(2)`: the copy shares the original's blocks until
+ /// something writes to one, so this costs neither time nor 6.7 GB.
+ static func cloneCache(named name: String) throws -> URL {
+ let pristine = try #require(Self.pristine, missing)
+ let destination = scratchRoot.appendingPathComponent(name, isDirectory: true)
+ try? FileManager.default.removeItem(at: destination)
+ try FileManager.default.createDirectory(
+ at: destination,
+ withIntermediateDirectories: true
+ )
+ let entries = try FileManager.default.contentsOfDirectory(atPath: pristine.path).sorted()
+ let result = try Subprocess.run(
+ executable: URL(fileURLWithPath: "/bin/cp"),
+ arguments: ["-c", "-R"]
+ + entries.map { pristine.appendingPathComponent($0).path }
+ + [destination.path]
+ )
+ guard result.status == 0 else {
+ Issue.record("clone failed: \(result.stderr)")
+ throw CocoaError(.fileWriteUnknown)
+ }
+ return destination
+ }
+
+ /// Discard clones, and the scratch root with them once the last one is
+ /// gone, so a test run leaves nothing behind.
+ static func discard(_ clones: URL...) {
+ for clone in clones {
+ try? FileManager.default.removeItem(at: clone)
+ }
+ let remaining = (try? FileManager.default
+ .contentsOfDirectory(atPath: scratchRoot.path)) ?? []
+ if remaining.isEmpty {
+ try? FileManager.default.removeItem(at: scratchRoot)
+ }
+ }
+}
+
+// MARK: - Subprocess helper
+
+private enum Subprocess {
+ struct Result {
+ let status: Int32
+ let stdout: String
+ let stderr: String
+ }
+
+ @discardableResult
+ static func run(executable: URL, arguments: [String]) throws -> Result {
+ let process = Process()
+ process.executableURL = executable
+ process.arguments = arguments
+ let out = Pipe()
+ let err = Pipe()
+ process.standardOutput = out
+ process.standardError = err
+ try process.run()
+ // Drain before waiting: a full pipe buffer would deadlock the patcher.
+ let outData = out.fileHandleForReading.readDataToEndOfFile()
+ let errData = err.fileHandleForReading.readDataToEndOfFile()
+ process.waitUntilExit()
+ return Result(
+ status: process.terminationStatus,
+ stdout: String(decoding: outData, as: UTF8.self),
+ stderr: String(decoding: errData, as: UTF8.self)
+ )
+ }
+}
+
+// MARK: - The reference Python, driven the way the installer drives it
+
+private enum PythonReference {
+ struct Run {
+ let stdout: String
+ /// Sites the Python says it wrote, counted off its own log lines.
+ let sitesWritten: Int
+ /// Sites it reached at all — written, already patched, or (on a dry
+ /// run) would-be-written.
+ let sitesFound: Int
+ /// The gate address it reported, if any.
+ let gateVMA: UInt64?
+ /// The block address it resolved, if any.
+ let functionVMA: UInt64?
+ }
+
+ /// `cfw.py patch-lockdown-mode <chunks_dir> [--dry-run]`, which is the
+ /// exact contract `cfw_install.sh` and `cfw-kit/lib/base_stages.sh` use.
+ static func patchLockdownMode(directory: URL, dryRun: Bool) throws -> Run {
+ let python = try #require(LockdownFixture.python, "project venv is required")
+ let result = try Subprocess.run(
+ executable: python,
+ arguments: [LockdownFixture.cfwCLI.path, "patch-lockdown-mode", directory.path]
+ + (dryRun ? ["--dry-run"] : [])
+ )
+ guard result.status == 0 else {
+ Issue.record("cfw.py patch-lockdown-mode failed: \(result.stdout)\n\(result.stderr)")
+ throw CocoaError(.fileReadUnknown)
+ }
+ let lines = result.stdout.split(separator: "\n").map(String.init)
+ return Run(
+ stdout: result.stdout,
+ sitesWritten: lines.filter { $0.contains("wrote nop at 0x") }.count,
+ sitesFound: lines.filter {
+ $0.contains("wrote nop at 0x")
+ || $0.contains("would write nop at 0x")
+ || $0.contains("already patched at 0x")
+ }.count,
+ gateVMA: lines.compactMap { line in
+ line.contains("gate @ 0x") ? hexAddress(after: "gate @ 0x", in: line) : nil
+ }.first,
+ functionVMA: lines.compactMap { line in
+ line.contains("_block_invoke @ 0x")
+ ? hexAddress(after: "_block_invoke @ 0x", in: line) : nil
+ }.first
+ )
+ }
+
+ private static func hexAddress(after marker: String, in line: String) -> UInt64? {
+ guard let range = line.range(of: marker) else { return nil }
+ let digits = line[range.upperBound...].prefix { $0.isHexDigit }
+ return UInt64(digits, radix: 16)
+ }
+}
+
+// MARK: - Byte-for-byte directory comparison
+
+private enum DirectoryComparison {
+ /// Every file that differs between two cache directories, by name.
+ ///
+ /// Compared with `cmp(1)` per file rather than by digest, so a mismatch is
+ /// reported as the first differing byte and not merely as "these hashes
+ /// differ".
+ static func differences(between lhs: URL, and rhs: URL) throws -> [String] {
+ let manager = FileManager.default
+ let left = try manager.contentsOfDirectory(atPath: lhs.path).sorted()
+ let right = try manager.contentsOfDirectory(atPath: rhs.path).sorted()
+ guard left == right else {
+ return ["directory listings differ: \(left.count) vs \(right.count) entries"]
+ }
+ var differing: [String] = []
+ for name in left {
+ let result = try Subprocess.run(
+ executable: URL(fileURLWithPath: "/usr/bin/cmp"),
+ arguments: [
+ lhs.appendingPathComponent(name).path,
+ rhs.appendingPathComponent(name).path,
+ ]
+ )
+ if result.status != 0 {
+ differing.append("\(name): \(result.stdout)\(result.stderr)".trimmingCharacters(
+ in: .whitespacesAndNewlines
+ ))
+ }
+ }
+ return differing
+ }
+
+ /// A digest of every file in a cache directory, for before/after checks
+ /// that only need to know whether anything moved.
+ static func fingerprint(of directory: URL) throws -> [String: String] {
+ let names = try FileManager.default.contentsOfDirectory(atPath: directory.path).sorted()
+ var digests: [String: String] = [:]
+ for name in names {
+ let result = try Subprocess.run(
+ executable: URL(fileURLWithPath: "/sbin/md5"),
+ arguments: ["-q", directory.appendingPathComponent(name).path]
+ )
+ digests[name] = result.stdout.trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+ return digests
+ }
+}
+
+// MARK: - Parity against the Python
+
+@Suite(.serialized, .enabled(if: LockdownFixture.runs, LockdownFixture.skipReason))
+struct DSCLockdownModeParityTests {
+ /// The one that matters: same cache, both patchers, identical bytes out.
+ @Test("Swift and Python produce byte-identical patched caches")
+ func patchedCachesAreIdentical() throws {
+ _ = try #require(LockdownFixture.pristine, LockdownFixture.missing)
+ _ = try #require(LockdownFixture.python, "project venv is required for the cross-check")
+
+ let pythonClone = try LockdownFixture.cloneCache(named: "python")
+ let swiftClone = try LockdownFixture.cloneCache(named: "swift")
+ defer { LockdownFixture.discard(pythonClone, swiftClone) }
+
+ let reference = try PythonReference.patchLockdownMode(directory: pythonClone, dryRun: false)
+ let outcome = try DSCLockdownModePatcher.patch(chunksDirectory: swiftClone, log: nil)
+
+ #expect(outcome.verdict == .patched)
+ #expect(outcome.sitesWritten == 1)
+ #expect(reference.sitesWritten == 1)
+ #expect(
+ outcome.sitesWritten == reference.sitesWritten,
+ "site counts must match: Swift \(outcome.sitesWritten), Python \(reference.sitesWritten)"
+ )
+ #expect(outcome.gateVMA == reference.gateVMA)
+ #expect(outcome.functionVMA == reference.functionVMA)
+
+ let differences = try DirectoryComparison.differences(between: pythonClone, and: swiftClone)
+ #expect(differences.isEmpty, "patched caches differ: \(differences.joined(separator: "; "))")
+
+ let fileCount = try FileManager.default
+ .contentsOfDirectory(atPath: swiftClone.path).count
+ print(
+ "[lockdown] 1 site @ 0x"
+ + String(outcome.gateVMA ?? 0, radix: 16, uppercase: true)
+ + " — \(fileCount) files byte-identical to the Python's output"
+ )
+ }
+
+ /// The write has to be covered by exactly one re-attested page, or the
+ /// guest takes a `KERN_PROTECTION_FAILURE` the first time it faults the
+ /// page in. The Python re-attests one slot here; so must this.
+ @Test("The write is re-attested, and only the page it dirtied")
+ func reattestationCoversTheWrite() throws {
+ _ = try #require(LockdownFixture.pristine, LockdownFixture.missing)
+
+ let clone = try LockdownFixture.cloneCache(named: "reattest")
+ defer { LockdownFixture.discard(clone) }
+
+ let outcome = try DSCLockdownModePatcher.patch(chunksDirectory: clone, log: nil)
+ let reattestation = try #require(outcome.reattestation)
+ #expect(reattestation.updated.count == 1)
+ #expect(reattestation.isFullyAttested)
+ #expect(reattestation.skipped.isEmpty)
+ }
+
+ /// A second pass over an installed cache is how this patch is actually met
+ /// in the field — `cfw_install` re-runs. It must report a no-op rather than
+ /// raise, and must not move a byte.
+ @Test("A second run is a no-op on an already-patched cache")
+ func secondRunIsANoOp() throws {
+ _ = try #require(LockdownFixture.pristine, LockdownFixture.missing)
+
+ let clone = try LockdownFixture.cloneCache(named: "idempotence")
+ defer { LockdownFixture.discard(clone) }
+
+ let first = try DSCLockdownModePatcher.patch(chunksDirectory: clone, log: nil)
+ #expect(first.verdict == .patched)
+ let afterFirst = try DirectoryComparison.fingerprint(of: clone)
+
+ let second = try DSCLockdownModePatcher.patch(chunksDirectory: clone, log: nil)
+ #expect(second.verdict == .alreadyPatched)
+ #expect(second.sitesWritten == 0)
+ #expect(second.sitesFound == 1)
+ #expect(second.gateVMA == first.gateVMA)
+ #expect(second.record == nil)
+
+ let afterSecond = try DirectoryComparison.fingerprint(of: clone)
+ #expect(afterFirst == afterSecond, "a no-op run still rewrote something")
+ }
+
+ /// The Python's dry run is the cheapest oracle for the reveal, and it runs
+ /// against the pristine cache without touching it.
+ @Test("Symbol and gate resolve to the same addresses as the Python")
+ func revealMatchesTheReference() throws {
+ let pristine = try #require(LockdownFixture.pristine, LockdownFixture.missing)
+ _ = try #require(LockdownFixture.python, "project venv is required for the cross-check")
+
+ let reference = try PythonReference.patchLockdownMode(directory: pristine, dryRun: true)
+ #expect(reference.sitesWritten == 0, "a dry run must not write")
+ #expect(reference.sitesFound == 1)
+
+ let chunks = try DSCChunkSet(directory: pristine)
+ let resolved = try DSCLockdownModePatcher.resolveBlockInvoke(in: chunks)
+ let block = try #require(
+ resolved,
+ "the cache must carry an os_lockdown_mode_enabled block to compare against"
+ )
+ #expect(block.vma == reference.functionVMA)
+ #expect(block.name == DSCLockdownModePatcher.symbolCandidates.first)
+
+ let instructions = try DSCLockdownModePatcher.disassembleBlock(in: chunks, at: block.vma)
+ let gate = try #require(DSCLockdownModePatcher.findErrorGate(instructions))
+ #expect(gate.address == reference.gateVMA)
+ #expect(gate.mnemonic == "b.eq")
+
+ // The decode stops at the block's own return, not at the ceiling.
+ #expect(instructions.count < DSCLockdownModePatcher.maxInstructions)
+ let last = try #require(instructions.last)
+ #expect(last.mnemonic == "ret" || last.mnemonic == "retab")
+ }
+}
+
+// MARK: - What the gate search must and must not match
+
+@Suite(.serialized, .enabled(if: LockdownFixture.runs, LockdownFixture.skipReason))
+struct DSCLockdownModeGateTests {
+ /// The real instruction stream, and the index of the real gate in it.
+ private struct Stream {
+ let instructions: [Instruction]
+ let gateIndex: Int
+ let comparisonIndex: Int
+ }
+
+ private func realStream() throws -> Stream {
+ let pristine = try #require(LockdownFixture.pristine, LockdownFixture.missing)
+ let chunks = try DSCChunkSet(directory: pristine)
+ let resolved = try DSCLockdownModePatcher.resolveBlockInvoke(in: chunks)
+ let block = try #require(resolved)
+ let instructions = try DSCLockdownModePatcher.disassembleBlock(in: chunks, at: block.vma)
+ let gate = try #require(DSCLockdownModePatcher.findErrorGate(instructions))
+ let gateIndex = try #require(instructions.firstIndex { $0.address == gate.address })
+ #expect(gateIndex > 0)
+ return Stream(
+ instructions: instructions,
+ gateIndex: gateIndex,
+ comparisonIndex: gateIndex - 1
+ )
+ }
+
+ /// Rebuild an ADD/SUB-immediate instruction with a different `imm12`.
+ ///
+ /// The word comes from a real decoded `cmn` in the cache; only the
+ /// documented `[21:10]` immediate field (see `ARM64Inst.addSubImm12`) is
+ /// rewritten, so this is derived test data rather than a hand-written
+ /// encoding.
+ private func word(of insn: Instruction, withImmediate imm12: UInt32) -> Data {
+ let original = insn.bytes.enumerated().reduce(UInt32(0)) { accumulated, byte in
+ accumulated | (UInt32(byte.element) << (8 * UInt32(byte.offset)))
+ }
+ let rewritten = (original & ~(0xFFF << 10)) | ((imm12 & 0xFFF) << 10)
+ return ARM64.encodeU32(rewritten)
+ }
+
+ @Test("The live b.eq gate is found, and it is the one the patch NOPs")
+ func findsTheLiveGate() throws {
+ let stream = try realStream()
+ let comparison = stream.instructions[stream.comparisonIndex]
+ #expect(comparison.mnemonic == "cmn")
+ #expect(DSCLockdownModePatcher.immediate(of: comparison, at: 1) == 1)
+ #expect(stream.instructions[stream.gateIndex].mnemonic == "b.eq")
+ // Something before the comparison has to be the sysctl call.
+ #expect(stream.instructions[..<stream.comparisonIndex].contains { $0.mnemonic == "bl" })
+ }
+
+ @Test("A cmn with no preceding call is not a gate")
+ func rejectsComparisonWithoutACall() throws {
+ let stream = try realStream()
+ let withoutCalls = stream.instructions.filter { $0.mnemonic != "bl" }
+ #expect(DSCLockdownModePatcher.findErrorGate(withoutCalls) == nil)
+ }
+
+ @Test("A cmn with the wrong immediate is not a gate")
+ func rejectsWrongImmediate() throws {
+ let stream = try realStream()
+ let comparison = stream.instructions[stream.comparisonIndex]
+ let disassembler = ARM64Disassembler()
+ let mutated = try #require(disassembler.disassembleOne(
+ word(of: comparison, withImmediate: 2),
+ at: comparison.address
+ ))
+ #expect(mutated.mnemonic == "cmn")
+ #expect(DSCLockdownModePatcher.immediate(of: mutated, at: 1) == 2)
+
+ var instructions = stream.instructions
+ instructions[stream.comparisonIndex] = mutated
+ #expect(DSCLockdownModePatcher.findErrorGate(instructions) == nil)
+ }
+
+ @Test("An unrelated instruction in the branch slot is not a gate")
+ func rejectsUnrelatedBranchSlot() throws {
+ let stream = try realStream()
+ let filler = try #require(
+ stream.instructions.first { $0.mnemonic != "b.eq" && $0.mnemonic != "nop" },
+ "the block must contain some instruction that is neither b.eq nor nop"
+ )
+ var instructions = stream.instructions
+ instructions[stream.gateIndex] = filler
+ #expect(DSCLockdownModePatcher.findErrorGate(instructions) == nil)
+ }
+
+ @Test("A truncated stream that ends on the cmn is not a gate")
+ func rejectsTruncatedStream() throws {
+ let stream = try realStream()
+ let truncated = Array(stream.instructions[...stream.comparisonIndex])
+ #expect(DSCLockdownModePatcher.findErrorGate(truncated) == nil)
+ }
+
+ /// The already-patched shape, read off a cache this code actually patched
+ /// rather than off a synthesised stream.
+ @Test("A NOPed gate is still recognised, at the same address")
+ func findsAnAlreadyNOPedGate() throws {
+ _ = try #require(LockdownFixture.pristine, LockdownFixture.missing)
+ let clone = try LockdownFixture.cloneCache(named: "nopedgate")
+ defer { LockdownFixture.discard(clone) }
+
+ let outcome = try DSCLockdownModePatcher.patch(chunksDirectory: clone, log: nil)
+ let gateVMA = try #require(outcome.gateVMA)
+
+ let chunks = try DSCChunkSet(directory: clone)
+ let resolved = try DSCLockdownModePatcher.resolveBlockInvoke(in: chunks)
+ let block = try #require(resolved)
+ let instructions = try DSCLockdownModePatcher.disassembleBlock(in: chunks, at: block.vma)
+ let gate = try #require(DSCLockdownModePatcher.findErrorGate(instructions))
+ #expect(gate.address == gateVMA)
+ #expect(gate.mnemonic == "nop")
+ }
+}
diff --git a/tests/FirmwarePatcherTests/DSCMaxSlidePatcherTests.swift b/tests/FirmwarePatcherTests/DSCMaxSlidePatcherTests.swift
new file mode 100644
index 00000000..4da069bf
--- /dev/null
+++ b/tests/FirmwarePatcherTests/DSCMaxSlidePatcherTests.swift
@@ -0,0 +1,791 @@
+// DSCMaxSlidePatcherTests.swift — Parity cross-checks for `DSCMaxSlidePatcher`.
+//
+// There is no `codesign -v` for a dyld shared cache chunk and no second
+// implementation of this patch anywhere, so the only independent reference is
+// `scripts/patchers/cfw_patch_dsc_maxslide.py` — driven here through the exact
+// CLI the install scripts use, `cfw.py patch-dsc-maxslide <dir> [--dry-run]
+// [--force]`. Every claim below is "the Python did X on one clone, the Swift
+// did X on another, and the two clones are the same bytes".
+//
+// The tests need the real cache. Point `VPHONE_DSC_PRISTINE` at a directory of
+// `dyld_shared_cache_arm64e*` chunks, or leave the default
+// `ipsws/ref_extract/dsc_pristine` in place.
+//
+// Without it they FAIL, following `DSCFoundationTests`: a `guard … else
+// { return }` is reported by Swift Testing as a pass, so a green run on a
+// machine with no fixture would be indistinguishable from a green run that
+// proved something. A machine that genuinely cannot carry the 5.3 GB cache sets
+// `VPHONE_DSC_FIXTURE_OPTIONAL=1`, which turns the failure into a visible skip.
+//
+// Nothing here writes to the pristine directory, and nothing here writes
+// anywhere under `ipsws/ref_extract/` at all: clones land in
+// `ipsws/scratch_dscmaxslide/`, on the same filesystem, so `cp -c` is a
+// `clonefile` rather than 10 GB of copying.
+
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+
+// MARK: - Fixture discovery
+
+private enum MaxSlideFixture {
+ static let repoRoot = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+
+ static let mainChunkName = "dyld_shared_cache_arm64e"
+
+ /// The read-only reference cache.
+ static var pristine: URL? {
+ let url = ProcessInfo.processInfo.environment["VPHONE_DSC_PRISTINE"]
+ .map { URL(fileURLWithPath: $0) }
+ ?? repoRoot.appendingPathComponent("ipsws/ref_extract/dsc_pristine")
+ let main = url.appendingPathComponent(mainChunkName)
+ return FileManager.default.fileExists(atPath: main.path) ? url : nil
+ }
+
+ /// Opt-out for a machine that cannot carry the fixture.
+ static var isOptional: Bool {
+ ProcessInfo.processInfo.environment["VPHONE_DSC_FIXTURE_OPTIONAL"] == "1"
+ }
+
+ /// The suites run unless the cache is absent *and* the caller opted out.
+ static var runs: Bool { pristine != nil || !isOptional }
+
+ static let missing: Comment = """
+ the real 24A435 arm64e shared cache is required — put it at \
+ ipsws/ref_extract/dsc_pristine, point VPHONE_DSC_PRISTINE at it, or set \
+ VPHONE_DSC_FIXTURE_OPTIONAL=1 to skip these tests instead of failing
+ """
+
+ static let skipReason: Comment =
+ "VPHONE_DSC_FIXTURE_OPTIONAL=1 and no dyld_shared_cache_arm64e fixture present"
+
+ static let venvMissing: Comment = """
+ the project venv is required: these tests are a comparison against \
+ scripts/patchers/cfw_patch_dsc_maxslide.py, and without it there is nothing \
+ to compare against — run `make setup_venv`
+ """
+
+ /// Where clones are made. Same filesystem as the repo, and deliberately
+ /// *not* under `ipsws/ref_extract/`, which is the pristine reference the
+ /// whole suite compares against.
+ static var scratchRoot: URL {
+ repoRoot.appendingPathComponent("ipsws/scratch_dscmaxslide")
+ }
+
+ /// The project venv, which is where the reference Python lives.
+ static var python: URL? {
+ let url = repoRoot.appendingPathComponent(".venv/bin/python3")
+ return FileManager.default.fileExists(atPath: url.path) ? url : nil
+ }
+
+ /// Clone the whole pristine cache into a fresh directory the caller may
+ /// write to. `cp -c` is `clonefile(2)`: instant, and near-zero disk until
+ /// something is written.
+ static func cloneCache(named name: String) throws -> URL {
+ guard let pristine else { throw CocoaError(.fileNoSuchFile) }
+ let destination = scratchRoot.appendingPathComponent(name)
+ try? FileManager.default.removeItem(at: destination)
+ try FileManager.default.createDirectory(
+ at: destination,
+ withIntermediateDirectories: true
+ )
+ let sources = try FileManager.default
+ .contentsOfDirectory(atPath: pristine.path)
+ .sorted()
+ .map { pristine.appendingPathComponent($0).path }
+
+ var result = try Subprocess.run(
+ executable: URL(fileURLWithPath: "/bin/cp"),
+ arguments: ["-c", "-R"] + sources + [destination.path]
+ )
+ if result.status != 0 {
+ // A fixture pointed at another volume cannot be cloned. Copying is
+ // slow but correct, and a refusal here would look like a patch bug.
+ result = try Subprocess.run(
+ executable: URL(fileURLWithPath: "/bin/cp"),
+ arguments: ["-R"] + sources + [destination.path]
+ )
+ }
+ guard result.status == 0 else { throw CocoaError(.fileWriteUnknown) }
+ return destination
+ }
+
+ /// Clone only the chunk this patcher touches — enough for a
+ /// `DSCChunkSet`, and cheap enough for the gate-logic tests to make many.
+ static func cloneMainChunk(named name: String) throws -> URL {
+ guard let pristine else { throw CocoaError(.fileNoSuchFile) }
+ let destination = scratchRoot.appendingPathComponent(name)
+ try? FileManager.default.removeItem(at: destination)
+ try FileManager.default.createDirectory(
+ at: destination,
+ withIntermediateDirectories: true
+ )
+ try FileManager.default.copyItem(
+ at: pristine.appendingPathComponent(mainChunkName),
+ to: destination.appendingPathComponent(mainChunkName)
+ )
+ return destination
+ }
+
+ /// Discard clones, and the scratch root with them once the last one is
+ /// gone, so a test run leaves the working tree as it found it.
+ static func discard(_ clones: URL...) {
+ for clone in clones {
+ try? FileManager.default.removeItem(at: clone)
+ }
+ let remaining = (try? FileManager.default
+ .contentsOfDirectory(atPath: scratchRoot.path)) ?? []
+ if remaining.isEmpty {
+ try? FileManager.default.removeItem(at: scratchRoot)
+ }
+ }
+}
+
+// MARK: - Subprocess helper
+
+private enum Subprocess {
+ struct Result {
+ let status: Int32
+ let stdout: String
+ let stderr: String
+ }
+
+ @discardableResult
+ static func run(executable: URL, arguments: [String]) throws -> Result {
+ let process = Process()
+ process.executableURL = executable
+ process.arguments = arguments
+ let out = Pipe()
+ let err = Pipe()
+ process.standardOutput = out
+ process.standardError = err
+ try process.run()
+ // Drain before waiting, or a full pipe buffer deadlocks the child.
+ let outData = out.fileHandleForReading.readDataToEndOfFile()
+ let errData = err.fileHandleForReading.readDataToEndOfFile()
+ process.waitUntilExit()
+ return Result(
+ status: process.terminationStatus,
+ stdout: String(decoding: outData, as: UTF8.self),
+ stderr: String(decoding: errData, as: UTF8.self)
+ )
+ }
+}
+
+// MARK: - The reference Python, driven through its real CLI
+
+/// `cfw.py patch-dsc-maxslide <chunks_dir> [--dry-run] [--force]` — the exact
+/// contract `scripts/cfw_install.sh` and `cfw-kit/lib/base_stages.sh` call.
+private enum PythonReference {
+ struct Run {
+ let stdout: String
+
+ /// The Python's return value, recovered from the lines it prints: it
+ /// returns 1 once it has decided the cache needs the clamp (including
+ /// on a dry run), and 0 from either "no change" branch.
+ var siteCount: Int { stdout.contains("[+] DSC maxSlide patch complete") ? 1 : 0 }
+ var saidNoChange: Bool { stdout.contains("no change") }
+ var saidWouldSet: Bool { stdout.contains("would set maxSlide") }
+ }
+
+ static func patch(
+ directory: URL,
+ dryRun: Bool = false,
+ force: Bool = false
+ ) throws -> Run {
+ let python = try #require(MaxSlideFixture.python, MaxSlideFixture.venvMissing)
+ var arguments = [
+ MaxSlideFixture.repoRoot.appendingPathComponent("scripts/patchers/cfw.py").path,
+ "patch-dsc-maxslide",
+ directory.path,
+ ]
+ if dryRun { arguments.append("--dry-run") }
+ if force { arguments.append("--force") }
+
+ let result = try Subprocess.run(executable: python, arguments: arguments)
+ guard result.status == 0 else {
+ Issue.record("cfw.py patch-dsc-maxslide failed: \(result.stderr)")
+ throw CocoaError(.fileReadUnknown)
+ }
+ return Run(stdout: result.stdout)
+ }
+}
+
+// MARK: - Byte comparison
+
+private enum Bytes {
+ /// `cmp -s`, which is a C memcmp over two files and does not need either of
+ /// them in this process's memory. Returns true when the two are identical.
+ static func identical(_ lhs: URL, _ rhs: URL) throws -> Bool {
+ try Subprocess.run(
+ executable: URL(fileURLWithPath: "/usr/bin/cmp"),
+ arguments: ["-s", lhs.path, rhs.path]
+ ).status == 0
+ }
+
+ /// Every file in `lhs` compared with its namesake in `rhs`.
+ ///
+ /// - Returns: how many files matched, and the names that did not.
+ static func compareTrees(_ lhs: URL, _ rhs: URL) throws -> (matched: Int, differing: [String]) {
+ let leftNames = try FileManager.default.contentsOfDirectory(atPath: lhs.path).sorted()
+ let rightNames = try FileManager.default.contentsOfDirectory(atPath: rhs.path).sorted()
+ #expect(leftNames == rightNames, "the two clones do not even hold the same files")
+
+ var matched = 0
+ var differing: [String] = []
+ for name in leftNames {
+ if try identical(
+ lhs.appendingPathComponent(name),
+ rhs.appendingPathComponent(name)
+ ) {
+ matched += 1
+ } else {
+ differing.append(name)
+ }
+ }
+ return (matched, differing)
+ }
+
+ static func read(_ url: URL, offset: UInt64, length: Int) throws -> Data {
+ try DSCChunkSet.read(url: url, offset: offset, length: length)
+ }
+
+ /// The `maxSlide` field of a chunk on disk.
+ static func maxSlide(of chunk: URL) throws -> UInt64 {
+ try read(chunk, offset: UInt64(DSCMaxSlidePatcher.HeaderField.maxSlide), length: 8)
+ .loadLE(UInt64.self, at: 0)
+ }
+}
+
+// MARK: - The real cache
+
+@Suite(.serialized, .enabled(if: MaxSlideFixture.runs, MaxSlideFixture.skipReason))
+struct DSCMaxSlideRealCacheTests {
+ /// The gate this cache trips, stated once: 24A435's arm64e cache records a
+ /// 0x17D504000 span and a 0x20000000 slide, which together overrun the
+ /// kernel's 0x180000000 region by 0x1D504000.
+ @Test("The pristine cache is one that overflows the kernel's shared region")
+ func pristineCacheOverflowsTheRegion() throws {
+ let pristine = try #require(MaxSlideFixture.pristine, MaxSlideFixture.missing)
+
+ let chunks = try DSCChunkSet(directory: pristine)
+ let headerVMA = try DSCMaxSlidePatcher.headerVMA(of: chunks)
+ let header = try DSCMaxSlidePatcher.readHeader(
+ from: chunks,
+ at: headerVMA,
+ chunkName: MaxSlideFixture.mainChunkName
+ )
+
+ #expect(header.sharedRegionStart == chunks.addressRange.lowerBound)
+ #expect(header.maxSlide != 0, "the fixture is already patched; re-extract it")
+ #expect(
+ header.sharedRegionSize + header.maxSlide > DSCMaxSlidePatcher.kernelSharedRegionSize,
+ "this fixture does not exercise the patch: it fits the region as it stands"
+ )
+ print(
+ "[pristine] start=0x\(String(header.sharedRegionStart, radix: 16, uppercase: true)) "
+ + "size=0x\(String(header.sharedRegionSize, radix: 16, uppercase: true)) "
+ + "maxSlide=0x\(String(header.maxSlide, radix: 16, uppercase: true))"
+ )
+ }
+
+ /// The gate from the task: run each implementation on its own clone of the
+ /// real cache and require the two clones to come out byte-identical, over
+ /// every one of the 79 chunks and the symbol side file — not just over the
+ /// eight bytes the patch is about.
+ @Test("Swift and the Python patch the real cache into byte-identical clones")
+ func realCacheParityWithPython() throws {
+ let pristine = try #require(MaxSlideFixture.pristine, MaxSlideFixture.missing)
+ _ = try #require(MaxSlideFixture.python, MaxSlideFixture.venvMissing)
+
+ let pythonSide = try MaxSlideFixture.cloneCache(named: "parity_python")
+ let swiftSide = try MaxSlideFixture.cloneCache(named: "parity_swift")
+ defer { MaxSlideFixture.discard(pythonSide, swiftSide) }
+
+ let theirs = try PythonReference.patch(directory: pythonSide)
+ #expect(theirs.siteCount == 1, "the Python did not patch the real cache")
+ #expect(!theirs.saidNoChange)
+
+ let mine = try DSCMaxSlidePatcher.patch(chunksDirectory: swiftSide)
+ #expect(mine.siteCount == 1, "the Swift did not patch the real cache")
+ #expect(mine.didWrite)
+ #expect(mine.outcome == .overflow(
+ combined: mine.sharedRegionSize + mine.maxSlide,
+ region: DSCMaxSlidePatcher.kernelSharedRegionSize
+ ))
+ #expect(mine.writtenSpan?.length == 8, "one site, one u64")
+
+ let (matched, differing) = try Bytes.compareTrees(pythonSide, swiftSide)
+ #expect(differing.isEmpty, "clones differ in: \(differing.joined(separator: ", "))")
+ #expect(matched >= 79, "only \(matched) files compared")
+ print("[parity] \(matched) files byte-identical between the two patched clones")
+
+ // And both differ from pristine in exactly one file, by exactly the
+ // eight bytes of the field.
+ let pristineMain = pristine.appendingPathComponent(MaxSlideFixture.mainChunkName)
+ let head = DSCMaxSlidePatcher.HeaderField.maxSlide
+ let tailOffset = UInt64(head + 8)
+ let tailLength = 0x100 - head - 8
+ let pristineHead = try Bytes.read(pristineMain, offset: 0, length: head)
+ let pristineTail = try Bytes.read(pristineMain, offset: tailOffset, length: tailLength)
+ for side in [pythonSide, swiftSide] {
+ let main = side.appendingPathComponent(MaxSlideFixture.mainChunkName)
+ let differsFromPristine = try !Bytes.identical(main, pristineMain)
+ #expect(differsFromPristine)
+ let slide = try Bytes.maxSlide(of: main)
+ #expect(slide == 0)
+
+ // Everything either side of the field is untouched.
+ let patchedHead = try Bytes.read(main, offset: 0, length: head)
+ let patchedTail = try Bytes.read(main, offset: tailOffset, length: tailLength)
+ #expect(patchedHead == pristineHead)
+ #expect(patchedTail == pristineTail)
+ }
+
+ let (unchanged, changed) = try Bytes.compareTrees(pristine, swiftSide)
+ #expect(changed == [MaxSlideFixture.mainChunkName])
+ print("[parity] \(unchanged) files unchanged from pristine; only \(changed) differs")
+ print("[parity] python: \(theirs.siteCount) site, swift: \(mine.siteCount) site")
+ }
+
+ /// 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.
+ @Test("The patch leaves the code directory alone and the header page unattested")
+ func headerPageIsDeliberatelyNotReattested() throws {
+ let pristine = try #require(MaxSlideFixture.pristine, MaxSlideFixture.missing)
+
+ let clone = try MaxSlideFixture.cloneMainChunk(named: "noreattest")
+ defer { MaxSlideFixture.discard(clone) }
+ let main = clone.appendingPathComponent(MaxSlideFixture.mainChunkName)
+ let pristineMain = pristine.appendingPathComponent(MaxSlideFixture.mainChunkName)
+
+ let directory = try #require(
+ try DSCCodeSignature.readCodeDirectory(ofChunk: main),
+ "the main chunk should carry a code directory"
+ )
+ let before = try DSCCodeSignature.pageHashes(
+ chunkURL: main,
+ pageIndex: 0,
+ directory: directory
+ )
+ #expect(before.computed == before.stored, "page 0 was not attested before the patch")
+
+ let result = try DSCMaxSlidePatcher.patch(chunksDirectory: clone)
+ #expect(result.siteCount == 1)
+
+ // The blob itself: byte-identical to pristine, so no slot moved.
+ let mineBlob = try Bytes.read(
+ main,
+ offset: UInt64(directory.blobOffset),
+ length: directory.blobLength
+ )
+ let 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")
+
+ let after = try DSCCodeSignature.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")
+ }
+
+ @Test("A dry run reports the site the Python reports, and writes nothing")
+ func dryRunMatchesPythonAndWritesNothing() throws {
+ let pristine = try #require(MaxSlideFixture.pristine, MaxSlideFixture.missing)
+ _ = try #require(MaxSlideFixture.python, MaxSlideFixture.venvMissing)
+
+ let pythonSide = try MaxSlideFixture.cloneMainChunk(named: "dryrun_python")
+ let swiftSide = try MaxSlideFixture.cloneMainChunk(named: "dryrun_swift")
+ defer { MaxSlideFixture.discard(pythonSide, swiftSide) }
+
+ let theirs = try PythonReference.patch(directory: pythonSide, dryRun: true)
+ #expect(theirs.siteCount == 1)
+ #expect(theirs.saidWouldSet)
+
+ let mine = try DSCMaxSlidePatcher.patch(chunksDirectory: swiftSide, dryRun: true)
+ #expect(mine.siteCount == 1, "a dry run still reports the site, as the Python does")
+ #expect(!mine.didWrite)
+ #expect(mine.record?.patchID == DSCMaxSlidePatcher.patchID)
+ #expect(mine.record?.patchedBytes == Data(count: 8))
+ #expect(mine.record?.originalBytes.loadLE(UInt64.self, at: 0) == mine.maxSlide)
+
+ let pristineMain = pristine.appendingPathComponent(MaxSlideFixture.mainChunkName)
+ for side in [pythonSide, swiftSide] {
+ let untouched = try Bytes.identical(
+ side.appendingPathComponent(MaxSlideFixture.mainChunkName),
+ pristineMain
+ )
+ #expect(untouched, "a dry run wrote to the chunk")
+ }
+ print("[dry run] python and swift both report 1 site and leave the chunk pristine")
+ }
+
+ /// `8eb6c8b`'s lesson again: a patcher has to recognise its own output. A
+ /// second pass over a clamped cache is a no-op, not an error and not a
+ /// second write.
+ @Test("A second pass over an already-clamped cache is a no-op")
+ func secondPassIsANoOp() throws {
+ _ = try #require(MaxSlideFixture.pristine, MaxSlideFixture.missing)
+ _ = try #require(MaxSlideFixture.python, MaxSlideFixture.venvMissing)
+
+ let pythonSide = try MaxSlideFixture.cloneMainChunk(named: "idem_python")
+ let swiftSide = try MaxSlideFixture.cloneMainChunk(named: "idem_swift")
+ defer { MaxSlideFixture.discard(pythonSide, swiftSide) }
+
+ _ = try PythonReference.patch(directory: pythonSide)
+ let theirsAgain = try PythonReference.patch(directory: pythonSide)
+ #expect(theirsAgain.siteCount == 0)
+ #expect(theirsAgain.saidNoChange)
+
+ let first = try DSCMaxSlidePatcher.patch(chunksDirectory: swiftSide)
+ let mineAgain = try DSCMaxSlidePatcher.patch(chunksDirectory: swiftSide)
+ #expect(mineAgain.siteCount == 0)
+ #expect(!mineAgain.didWrite)
+ // 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 —
+ // so the *fits* gate is what returns, and the already-zero gate behind
+ // it is never reached. The Python says the same thing in words: its
+ // second run prints "fits: … no change", not "maxSlide already 0".
+ #expect(mineAgain.outcome == .fits(
+ combined: first.sharedRegionSize,
+ region: DSCMaxSlidePatcher.kernelSharedRegionSize
+ ))
+
+ // `--force` skips the fits gate, so it is the one path that does reach
+ // the already-zero check — and it still writes nothing.
+ let theirsForced = try PythonReference.patch(directory: pythonSide, force: true)
+ #expect(theirsForced.siteCount == 0)
+ let mineForced = try DSCMaxSlidePatcher.patch(chunksDirectory: swiftSide, force: true)
+ #expect(mineForced.siteCount == 0)
+ #expect(mineForced.outcome == .alreadyZero)
+
+ let (_, differing) = try Bytes.compareTrees(pythonSide, swiftSide)
+ #expect(differing.isEmpty)
+ print("[idempotence] both implementations report 0 sites on the second and third pass")
+ }
+}
+
+// MARK: - The gate, on synthetic caches
+
+/// The four branches `cfw_patch_dsc_maxslide._self_test` covers, run against
+/// both implementations on identical synthetic caches.
+///
+/// Synthetic rather than real because the real cache can only exercise one of
+/// the four: it overflows. A cache that *fits* — an 18.x or 26.x base, the case
+/// the self-gate exists to protect — cannot be demonstrated with the fixture on
+/// hand, so it is built.
+@Suite(.serialized, .enabled(if: MaxSlideFixture.runs, MaxSlideFixture.skipReason))
+struct DSCMaxSlideGateTests {
+ /// A minimal but *real* cache: header plus a one-entry mapping table that
+ /// covers it. The Python's own self-test fixture has no mapping table at
+ /// all, which the Swift refuses — see `noMappingTableIsRefused`.
+ ///
+ /// - Parameters:
+ /// - regionSize: what the header records as `sharedRegionSize`.
+ /// - maxSlide: what the header records as `maxSlide`.
+ static func writeCache(
+ into directory: URL,
+ regionSize: UInt64,
+ maxSlide: UInt64,
+ mappingOffset: Int = 0x238,
+ magic: String = "dyld_v1 arm64e"
+ ) throws {
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ var bytes = [UInt8](repeating: 0, count: 0x4000)
+
+ func put(_ value: UInt64, at offset: Int) {
+ withUnsafeBytes(of: value.littleEndian) { source in
+ for (index, byte) in source.enumerated() { bytes[offset + index] = byte }
+ }
+ }
+ func put32(_ value: UInt32, at offset: Int) {
+ withUnsafeBytes(of: value.littleEndian) { source in
+ for (index, byte) in source.enumerated() { bytes[offset + index] = byte }
+ }
+ }
+
+ for (index, byte) in Array(magic.utf8).prefix(16).enumerated() { bytes[index] = byte }
+ put32(UInt32(mappingOffset), at: 0x10)
+ put32(1, at: 0x14) // mappingCount
+
+ // dyld_cache_mapping_info: address, size, fileOffset, maxProt, initProt.
+ put(Self.mappingAddress, at: mappingOffset)
+ put(0x4000, at: mappingOffset + 8)
+ put(0, at: mappingOffset + 16)
+ put32(5, at: mappingOffset + 24)
+ put32(5, at: mappingOffset + 28)
+
+ put(Self.mappingAddress, at: 0xE0) // sharedRegionStart
+ put(regionSize, at: 0xE8) // sharedRegionSize
+ put(maxSlide, at: 0xF0) // maxSlide
+
+ try Data(bytes).write(
+ to: directory.appendingPathComponent(MaxSlideFixture.mainChunkName)
+ )
+ }
+
+ /// SHARED_REGION_BASE_ARM64, which is also where the real cache starts.
+ static let mappingAddress: UInt64 = 0x1_8000_0000
+
+ /// Build the same synthetic cache twice, hand one to each implementation,
+ /// and require the two files to come out identical.
+ private func compare(
+ named name: String,
+ regionSize: UInt64,
+ maxSlide: UInt64,
+ force: Bool = false,
+ expectedSites: Int,
+ expectedOutcome: DSCMaxSlidePatcher.Outcome,
+ expectedMaxSlideAfter: UInt64
+ ) throws {
+ _ = try #require(MaxSlideFixture.python, MaxSlideFixture.venvMissing)
+
+ let pythonSide = MaxSlideFixture.scratchRoot.appendingPathComponent("\(name)_python")
+ let swiftSide = MaxSlideFixture.scratchRoot.appendingPathComponent("\(name)_swift")
+ defer { MaxSlideFixture.discard(pythonSide, swiftSide) }
+ for side in [pythonSide, swiftSide] {
+ try Self.writeCache(into: side, regionSize: regionSize, maxSlide: maxSlide)
+ }
+
+ let theirs = try PythonReference.patch(directory: pythonSide, force: force)
+ let mine = try DSCMaxSlidePatcher.patch(chunksDirectory: swiftSide, force: force)
+
+ #expect(theirs.siteCount == expectedSites, "python: \(theirs.stdout)")
+ #expect(mine.siteCount == expectedSites)
+ #expect(mine.outcome == expectedOutcome)
+
+ let pythonMain = pythonSide.appendingPathComponent(MaxSlideFixture.mainChunkName)
+ let swiftMain = swiftSide.appendingPathComponent(MaxSlideFixture.mainChunkName)
+ let same = try Bytes.identical(pythonMain, swiftMain)
+ #expect(same, "\(name): the two caches differ")
+ let swiftSlide = try Bytes.maxSlide(of: swiftMain)
+ let pythonSlide = try Bytes.maxSlide(of: pythonMain)
+ #expect(swiftSlide == expectedMaxSlideAfter)
+ #expect(pythonSlide == expectedMaxSlideAfter)
+ print("[gate \(name)] both wrote \(expectedSites) site(s); maxSlide now "
+ + "0x\(String(expectedMaxSlideAfter, radix: 16, uppercase: true))")
+ }
+
+ @Test("An overflowing cache is clamped by both implementations")
+ func overflowIsClamped() throws {
+ // iOS 27.0-like: 0x17C830000 + 0x20000000 > 0x180000000.
+ try compare(
+ named: "overflow",
+ regionSize: 0x1_7C83_0000,
+ maxSlide: 0x2000_0000,
+ expectedSites: 1,
+ expectedOutcome: .overflow(
+ combined: 0x1_9C83_0000,
+ region: DSCMaxSlidePatcher.kernelSharedRegionSize
+ ),
+ expectedMaxSlideAfter: 0
+ )
+ }
+
+ @Test("A cache that fits is left alone by both implementations")
+ func fittingCacheIsUntouched() throws {
+ // 26.4-like: 0x140904000 + 0x20000000 <= 0x180000000.
+ try compare(
+ named: "fits",
+ regionSize: 0x1_4090_4000,
+ maxSlide: 0x2000_0000,
+ expectedSites: 0,
+ expectedOutcome: .fits(
+ combined: 0x1_6090_4000,
+ region: DSCMaxSlidePatcher.kernelSharedRegionSize
+ ),
+ expectedMaxSlideAfter: 0x2000_0000
+ )
+ }
+
+ @Test("--force clamps a cache that fits, on both implementations")
+ func forceClampsAFittingCache() throws {
+ try compare(
+ named: "forced",
+ regionSize: 0x1_4090_4000,
+ maxSlide: 0x2000_0000,
+ force: true,
+ expectedSites: 1,
+ expectedOutcome: .forced(
+ combined: 0x1_6090_4000,
+ region: DSCMaxSlidePatcher.kernelSharedRegionSize
+ ),
+ expectedMaxSlideAfter: 0
+ )
+ }
+
+ @Test("--force over an already-zero cache is a no-op on both implementations")
+ func forceOverZeroIsANoOp() throws {
+ try compare(
+ named: "forced_zero",
+ regionSize: 0x1_4090_4000,
+ maxSlide: 0,
+ force: true,
+ expectedSites: 0,
+ expectedOutcome: .alreadyZero,
+ expectedMaxSlideAfter: 0
+ )
+ }
+
+ /// The fourth branch, and the only one that needs no `--force` to reach the
+ /// already-zero check: a span that overruns the region on its own, with no
+ /// slide left to give back. Both implementations report the cache as
+ /// unpatchable rather than writing a zero over a zero.
+ ///
+ /// The span has to exceed the region by itself — a 0x17C830000 span with a
+ /// zero slide *fits*, and takes the fits branch instead, which is what both
+ /// implementations do and what an earlier version of this test got wrong.
+ @Test("A cache that overruns the region with no slide left is left alone")
+ func overflowWithZeroSlideIsANoOp() throws {
+ try compare(
+ named: "overflow_zero",
+ regionSize: 0x1_9000_0000,
+ maxSlide: 0,
+ expectedSites: 0,
+ expectedOutcome: .alreadyZero,
+ expectedMaxSlideAfter: 0
+ )
+ }
+
+ // MARK: - Refusals
+
+ @Test("A missing main chunk is a named failure, not a crash")
+ func missingMainChunkThrows() throws {
+ let empty = MaxSlideFixture.scratchRoot.appendingPathComponent("empty")
+ try FileManager.default.createDirectory(at: empty, withIntermediateDirectories: true)
+ defer { MaxSlideFixture.discard(empty) }
+
+ #expect(throws: PatcherError.self) {
+ _ = try DSCMaxSlidePatcher.patch(chunksDirectory: empty, verbose: false)
+ }
+ }
+
+ /// The Python checks `hdr[:7] != b"dyld_v1"`; so does this. A `dyld_v2`
+ /// header still parses as a cache far enough to reach the check, which is
+ /// what makes the check worth having.
+ @Test("A file that is not a dyld_v1 cache is refused")
+ func wrongMagicIsRefused() throws {
+ let directory = MaxSlideFixture.scratchRoot.appendingPathComponent("badmagic")
+ defer { MaxSlideFixture.discard(directory) }
+ try Self.writeCache(
+ into: directory,
+ regionSize: 0x1_7C83_0000,
+ maxSlide: 0x2000_0000,
+ magic: "dyld_v2 arm64e"
+ )
+
+ #expect(throws: PatcherError.self) {
+ _ = try DSCMaxSlidePatcher.patch(chunksDirectory: directory, verbose: false)
+ }
+ }
+
+ /// dyld's own field-presence rule: the header struct ends where the mapping
+ /// table begins, so a `mappingOffset` that does not reach past `maxSlide`
+ /// means this cache version has no such field. The Python has no equivalent
+ /// gate and would write eight zero bytes into whatever is at 0xF0 — here
+ /// that is a `dyld_cache_mapping_info.fileOffset`.
+ @Test("A header too short to hold maxSlide is refused, where the Python would write")
+ func truncatedHeaderIsRefused() throws {
+ let directory = MaxSlideFixture.scratchRoot.appendingPathComponent("shortheader")
+ defer { MaxSlideFixture.discard(directory) }
+ // Mapping table at 0xC0: the header struct then ends at 0xC0, well
+ // before the 0xF0 these offsets want to write at. The mapping itself is
+ // still valid, so the run gets as far as the version gate.
+ try Self.writeCache(
+ into: directory,
+ regionSize: 0x1_7C83_0000,
+ maxSlide: 0x2000_0000,
+ mappingOffset: 0xC0
+ )
+
+ #expect(throws: PatcherError.self) {
+ _ = try DSCMaxSlidePatcher.patch(chunksDirectory: directory, verbose: false)
+ }
+ }
+
+ /// The corroboration check: a header whose `sharedRegionStart` is not the
+ /// cache's lowest mapped address is not laid out the way these offsets
+ /// assume, so the write is refused rather than aimed at an unknown field.
+ @Test("A header that disagrees with the mapping table is refused")
+ func headerDisagreeingWithMappingsIsRefused() throws {
+ let directory = MaxSlideFixture.scratchRoot.appendingPathComponent("mismatch")
+ defer { MaxSlideFixture.discard(directory) }
+ try Self.writeCache(
+ into: directory,
+ regionSize: 0x1_7C83_0000,
+ maxSlide: 0x2000_0000
+ )
+ // Move sharedRegionStart away from the mapping's address.
+ let main = directory.appendingPathComponent(MaxSlideFixture.mainChunkName)
+ let handle = try FileHandle(forUpdating: main)
+ try handle.seek(toOffset: 0xE0)
+ try handle.write(contentsOf: withUnsafeBytes(of: UInt64(0x1_9000_0000).littleEndian) {
+ Data($0)
+ })
+ try handle.close()
+
+ #expect(throws: PatcherError.self) {
+ _ = try DSCMaxSlidePatcher.patch(chunksDirectory: directory, verbose: false)
+ }
+ }
+
+ /// The Python's own self-test fixture: a bare 0x100-byte header with no
+ /// mapping table. The Python patches it; this refuses it, because every
+ /// write here goes through `DSCChunkSet`, which has nothing to address it
+ /// with. A documented divergence, and a strictly safer one — the input is
+ /// not a shared cache.
+ @Test("A header with no mapping table is refused, where the Python patches it")
+ func noMappingTableIsRefused() throws {
+ _ = try #require(MaxSlideFixture.python, MaxSlideFixture.venvMissing)
+
+ let pythonSide = MaxSlideFixture.scratchRoot.appendingPathComponent("headeronly_python")
+ let swiftSide = MaxSlideFixture.scratchRoot.appendingPathComponent("headeronly_swift")
+ defer { MaxSlideFixture.discard(pythonSide, swiftSide) }
+
+ for side in [pythonSide, swiftSide] {
+ try FileManager.default.createDirectory(at: side, withIntermediateDirectories: true)
+ var bytes = [UInt8](repeating: 0, count: 0x100)
+ for (index, byte) in Array("dyld_v1 arm64e".utf8).enumerated() { bytes[index] = byte }
+ func put(_ value: UInt64, at offset: Int) {
+ withUnsafeBytes(of: value.littleEndian) { source in
+ for (index, byte) in source.enumerated() { bytes[offset + index] = byte }
+ }
+ }
+ put(Self.mappingAddress, at: 0xE0)
+ put(0x1_7C83_0000, at: 0xE8)
+ put(0x2000_0000, at: 0xF0)
+ try Data(bytes).write(
+ to: side.appendingPathComponent(MaxSlideFixture.mainChunkName)
+ )
+ }
+
+ let theirs = try PythonReference.patch(directory: pythonSide)
+ #expect(theirs.siteCount == 1, "the Python patches a mapping-less header")
+
+ #expect(throws: DSCError.self) {
+ _ = try DSCMaxSlidePatcher.patch(chunksDirectory: swiftSide, verbose: false)
+ }
+ let untouchedSlide = try Bytes.maxSlide(
+ of: swiftSide.appendingPathComponent(MaxSlideFixture.mainChunkName)
+ )
+ #expect(untouchedSlide == 0x2000_0000, "the refusal still wrote")
+ print("[no mappings] python clamped it; swift refused and left it alone")
+ }
+}
diff --git a/tests/FirmwarePatcherTests/DSCXPCLWCRPatcherTests.swift b/tests/FirmwarePatcherTests/DSCXPCLWCRPatcherTests.swift
new file mode 100644
index 00000000..f1ac6d4e
--- /dev/null
+++ b/tests/FirmwarePatcherTests/DSCXPCLWCRPatcherTests.swift
@@ -0,0 +1,483 @@
+// DSCXPCLWCRPatcherTests.swift — Parity for the libxpc LWCR patch.
+//
+// The only independent reference for this patch is
+// `scripts/patchers/cfw_patch_xpc_lwcr.py`, so every test here runs that
+// Python on one clone of the real shared cache, runs `DSCXPCLWCRPatcher` on a
+// second clone, and compares the two byte for byte. A port that writes the
+// right instruction at the wrong address, or re-attests a different page,
+// fails on the bytes rather than on a number this file wrote down.
+//
+// Fixture: `VPHONE_DSC_PRISTINE`, or `ipsws/ref_extract/dsc_pristine` by
+// default. Without it these FAIL. A bare `guard let … else { return }` is
+// reported by Swift Testing as a pass, so "all green" on a machine that never
+// extracted the 6.7 GB cache would mean nothing. A machine that genuinely
+// cannot carry the fixture sets `VPHONE_DSC_FIXTURE_OPTIONAL=1` and gets a
+// visible *skip* instead.
+//
+// Nothing here writes to the pristine directory. Clones are made with
+// `cp -c` — APFS `clonefile`, so instant and near-free — under the system
+// temporary directory, or `VPHONE_DSC_SCRATCH` when it is set.
+
+@testable import FirmwarePatcher
+import Capstone
+import Foundation
+import Testing
+
+// MARK: - Fixture
+
+private enum LWCRFixture {
+ static let repoRoot = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+
+ /// The read-only reference cache.
+ static var pristine: URL? {
+ let url = ProcessInfo.processInfo.environment["VPHONE_DSC_PRISTINE"]
+ .map { URL(fileURLWithPath: $0) }
+ ?? repoRoot.appendingPathComponent("ipsws/ref_extract/dsc_pristine")
+ let main = url.appendingPathComponent("dyld_shared_cache_arm64e")
+ return FileManager.default.fileExists(atPath: main.path) ? url : nil
+ }
+
+ /// Opt-out for a machine that cannot carry the fixture.
+ static var isOptional: Bool {
+ ProcessInfo.processInfo.environment["VPHONE_DSC_FIXTURE_OPTIONAL"] == "1"
+ }
+
+ /// The suites run unless the cache is absent *and* the caller opted out.
+ static var runs: Bool { pristine != nil || !isOptional }
+
+ static let missing: Comment = """
+ the real 24A435 arm64e shared cache is required — put it at \
+ ipsws/ref_extract/dsc_pristine, point VPHONE_DSC_PRISTINE at it, or set \
+ VPHONE_DSC_FIXTURE_OPTIONAL=1 to skip these tests instead of failing
+ """
+
+ static let skipReason: Comment =
+ "VPHONE_DSC_FIXTURE_OPTIONAL=1 and no dyld_shared_cache_arm64e fixture present"
+
+ /// Where clones go. Must be on the same APFS volume as the pristine copy
+ /// or `cp -c` degrades from a clone into 6.7 GB of reads; the system
+ /// temporary directory is, and `VPHONE_DSC_SCRATCH` is there for a layout
+ /// where it is not.
+ static var scratchRoot: URL {
+ ProcessInfo.processInfo.environment["VPHONE_DSC_SCRATCH"]
+ .map { URL(fileURLWithPath: $0) }
+ ?? FileManager.default.temporaryDirectory
+ .appendingPathComponent("vphone_dsc_xpclwcr")
+ }
+
+ /// The project venv, which is where the reference Python lives.
+ static var python: URL? {
+ let url = repoRoot.appendingPathComponent(".venv/bin/python3")
+ return FileManager.default.fileExists(atPath: url.path) ? url : nil
+ }
+
+ /// Clone the pristine cache into a fresh directory the caller may write to.
+ static func cloneCache(named name: String) throws -> URL {
+ guard let pristine else { throw CocoaError(.fileNoSuchFile) }
+ let destination = scratchRoot.appendingPathComponent(name)
+ try? FileManager.default.removeItem(at: destination)
+ try FileManager.default.createDirectory(
+ at: destination,
+ withIntermediateDirectories: true
+ )
+ let entries = try FileManager.default.contentsOfDirectory(atPath: pristine.path).sorted()
+ let result = try Shell.run(
+ executable: URL(fileURLWithPath: "/bin/cp"),
+ arguments: ["-c", "-R"]
+ + entries.map { pristine.appendingPathComponent($0).path }
+ + [destination.path]
+ )
+ guard result.status == 0 else {
+ Issue.record("cp -c failed: \(result.stderr)")
+ throw CocoaError(.fileWriteUnknown)
+ }
+ return destination
+ }
+
+ /// Discard clones, and the scratch root with them once the last one is
+ /// gone, so the run leaves the filesystem as it found it.
+ static func discard(_ clones: URL...) {
+ for clone in clones {
+ try? FileManager.default.removeItem(at: clone)
+ }
+ let remaining = (try? FileManager.default
+ .contentsOfDirectory(atPath: scratchRoot.path)) ?? []
+ if remaining.isEmpty {
+ try? FileManager.default.removeItem(at: scratchRoot)
+ }
+ }
+
+ /// Byte-compare two cache directories, file by file.
+ ///
+ /// Returns the names of files that differ, plus the names present in one
+ /// directory and not the other. Empty means the two trees are identical.
+ static func differences(between left: URL, and right: URL) throws -> [String] {
+ let leftNames = Set(try FileManager.default.contentsOfDirectory(atPath: left.path))
+ let rightNames = Set(try FileManager.default.contentsOfDirectory(atPath: right.path))
+ var differing = Array(leftNames.symmetricDifference(rightNames))
+
+ for name in leftNames.intersection(rightNames).sorted() {
+ let a = left.appendingPathComponent(name)
+ let b = right.appendingPathComponent(name)
+ // `cmp -s` streams both files; loading two 5 GB chunks into Data
+ // to compare them is not a thing this test can afford.
+ let result = try Shell.run(
+ executable: URL(fileURLWithPath: "/usr/bin/cmp"),
+ arguments: ["-s", a.path, b.path]
+ )
+ if result.status != 0 { differing.append(name) }
+ }
+ return differing.sorted()
+ }
+}
+
+// MARK: - Subprocess helper
+
+private enum Shell {
+ struct Result {
+ let status: Int32
+ let stdout: String
+ let stderr: String
+ }
+
+ @discardableResult
+ static func run(executable: URL, arguments: [String]) throws -> Result {
+ let process = Process()
+ process.executableURL = executable
+ process.arguments = arguments
+ let out = Pipe()
+ let err = Pipe()
+ process.standardOutput = out
+ process.standardError = err
+ try process.run()
+ // Drain before waiting: a full pipe buffer would deadlock the run.
+ let outData = out.fileHandleForReading.readDataToEndOfFile()
+ let errData = err.fileHandleForReading.readDataToEndOfFile()
+ process.waitUntilExit()
+ return Result(
+ status: process.terminationStatus,
+ stdout: String(decoding: outData, as: UTF8.self),
+ stderr: String(decoding: errData, as: UTF8.self)
+ )
+ }
+}
+
+// MARK: - The reference Python, driven through its own CLI
+
+private enum ReferencePython {
+ /// Addresses the reference reports writing, parsed off its own log lines:
+ ///
+ /// [+] wrote cset w0, eq at 0x1805DD644 (e8079f1a -> e0179f1a)
+ struct Run {
+ let status: Int32
+ let stdout: String
+ let writtenVMAs: [UInt64]
+ let alreadyPatched: Bool
+ }
+
+ /// Run `cfw.py patch-xpc-lwcr <directory>`, exactly as the install scripts do.
+ static func patch(directory: URL, dryRun: Bool = false) throws -> Run {
+ guard let python = LWCRFixture.python else { throw CocoaError(.fileNoSuchFile) }
+ let script = LWCRFixture.repoRoot.appendingPathComponent("scripts/patchers/cfw.py")
+ let result = try Shell.run(
+ executable: python,
+ arguments: [script.path, "patch-xpc-lwcr", directory.path]
+ + (dryRun ? ["--dry-run"] : [])
+ )
+ var addresses: [UInt64] = []
+ for line in result.stdout.split(separator: "\n") {
+ guard line.contains("[+]"), line.contains(dryRun ? "would write" : "wrote") else {
+ continue
+ }
+ // "… at 0x1805DD644 (…)" — the address is the token after " at ".
+ guard let atRange = line.range(of: " at 0x") else { continue }
+ let rest = line[atRange.upperBound...]
+ let digits = rest.prefix { $0.isHexDigit }
+ if let value = UInt64(digits, radix: 16) { addresses.append(value) }
+ }
+ return Run(
+ status: result.status,
+ stdout: result.stdout + result.stderr,
+ writtenVMAs: addresses,
+ alreadyPatched: result.stdout.contains("already patched")
+ )
+ }
+}
+
+// MARK: - Parity against the Python, on the real cache
+
+@Suite(.serialized, .enabled(if: LWCRFixture.runs, LWCRFixture.skipReason))
+struct DSCXPCLWCRParityTests {
+ @Test("Swift and the Python patch the same three sites, byte for byte")
+ func patchedClonesAreIdentical() throws {
+ _ = try #require(LWCRFixture.pristine, LWCRFixture.missing)
+ try #require(
+ LWCRFixture.python != nil,
+ "the project venv is required for the cross-check — run `make setup_venv`"
+ )
+
+ let pythonClone = try LWCRFixture.cloneCache(named: "python")
+ let swiftClone = try LWCRFixture.cloneCache(named: "swift")
+ defer { LWCRFixture.discard(pythonClone, swiftClone) }
+
+ // The two trees start out identical, or the comparison below proves
+ // nothing about the patch.
+ #expect(try LWCRFixture.differences(between: pythonClone, and: swiftClone).isEmpty)
+
+ let reference = try ReferencePython.patch(directory: pythonClone)
+ #expect(reference.status == 0, "python failed: \(reference.stdout)")
+ #expect(reference.writtenVMAs.count == 3, "python wrote \(reference.writtenVMAs.count) sites")
+
+ let outcome = try DSCXPCLWCRPatcher.apply(directory: swiftClone, log: nil)
+ #expect(outcome.status == .patched)
+ #expect(outcome.siteCount == 3, "swift wrote \(outcome.siteCount) sites")
+ #expect(outcome.records.compactMap(\.virtualAddress) == reference.writtenVMAs)
+
+ let differences = try LWCRFixture.differences(between: pythonClone, and: swiftClone)
+ #expect(differences.isEmpty, "chunks differ after patching: \(differences)")
+
+ print("[xpc_lwcr] python \(reference.writtenVMAs.count) sites, "
+ + "swift \(outcome.siteCount) sites, "
+ + "\(outcome.records.map { "0x" + String($0.virtualAddress ?? 0, radix: 16, uppercase: true) })"
+ + " — clones byte-identical")
+ }
+
+ @Test("The replacement words are exactly cset w0,eq / nop / nop")
+ func replacementWordsComeFromTheEncoders() throws {
+ _ = try #require(LWCRFixture.pristine, LWCRFixture.missing)
+ let clone = try LWCRFixture.cloneCache(named: "words")
+ defer { LWCRFixture.discard(clone) }
+
+ let outcome = try DSCXPCLWCRPatcher.apply(directory: clone, log: nil)
+ #expect(outcome.siteCount == 3)
+
+ let expectedCset = try #require(ARM64Encoder.encodeCsetW(rd: 0, condition: .eq))
+ #expect(outcome.records[0].patchedBytes == expectedCset)
+ #expect(outcome.records[1].patchedBytes == ARM64.nop)
+ #expect(outcome.records[2].patchedBytes == ARM64.nop)
+
+ // The three sites are consecutive words of one function.
+ let addresses = outcome.records.compactMap(\.virtualAddress)
+ #expect(addresses.count == 3)
+ #expect(addresses[1] == addresses[0] + 4)
+ #expect(addresses[2] == addresses[1] + 4)
+ }
+
+ @Test("A dry run reports the same three sites and writes nothing")
+ func dryRunWritesNothing() throws {
+ _ = try #require(LWCRFixture.pristine, LWCRFixture.missing)
+ try #require(LWCRFixture.python != nil)
+
+ let untouched = try LWCRFixture.cloneCache(named: "dry_reference")
+ let clone = try LWCRFixture.cloneCache(named: "dry")
+ defer { LWCRFixture.discard(untouched, clone) }
+
+ let outcome = try DSCXPCLWCRPatcher.apply(directory: clone, dryRun: true, log: nil)
+ #expect(outcome.status == .patched)
+ #expect(outcome.siteCount == 3)
+
+ let differences = try LWCRFixture.differences(between: untouched, and: clone)
+ #expect(differences.isEmpty, "a dry run modified \(differences)")
+
+ let reference = try ReferencePython.patch(directory: untouched, dryRun: true)
+ #expect(reference.writtenVMAs == outcome.records.compactMap(\.virtualAddress))
+ }
+
+ @Test("Re-running over a patched cache is a no-op, in both implementations")
+ func secondRunIsANoOp() throws {
+ _ = try #require(LWCRFixture.pristine, LWCRFixture.missing)
+ try #require(LWCRFixture.python != nil)
+
+ let pythonClone = try LWCRFixture.cloneCache(named: "python_twice")
+ let swiftClone = try LWCRFixture.cloneCache(named: "swift_twice")
+ defer { LWCRFixture.discard(pythonClone, swiftClone) }
+
+ _ = try ReferencePython.patch(directory: pythonClone)
+ _ = try DSCXPCLWCRPatcher.apply(directory: swiftClone, log: nil)
+
+ // Second pass. Neither may raise, and neither may write.
+ let second = try ReferencePython.patch(directory: pythonClone)
+ #expect(second.status == 0, "python raised on a second pass: \(second.stdout)")
+ #expect(second.alreadyPatched)
+ #expect(second.writtenVMAs.isEmpty)
+
+ let outcome = try DSCXPCLWCRPatcher.apply(directory: swiftClone, log: nil)
+ #expect(outcome.status == .alreadyPatched)
+ #expect(outcome.siteCount == 0)
+
+ let differences = try LWCRFixture.differences(between: pythonClone, and: swiftClone)
+ #expect(differences.isEmpty, "chunks differ after a second pass: \(differences)")
+ }
+
+ @Test("Every page the writes dirtied is re-attested")
+ func patchedPagesAreAttested() throws {
+ _ = try #require(LWCRFixture.pristine, LWCRFixture.missing)
+ let clone = try LWCRFixture.cloneCache(named: "attest")
+ defer { LWCRFixture.discard(clone) }
+
+ let chunks = try DSCChunkSet(directory: clone)
+ let outcome = try DSCXPCLWCRPatcher.apply(chunks: chunks, log: nil)
+ #expect(outcome.siteCount == 3)
+
+ // Re-attesting again must find every touched page already correct —
+ // which is only true if the patcher's own call covered all of them.
+ let again = try DSCCodeSignature.reattestRecordedWrites(in: chunks, log: nil)
+ #expect(again.updated.isEmpty, "a page was left stale: \(again.updated.count) slots")
+ #expect(!again.alreadyAttested.isEmpty)
+ #expect(again.skipped.isEmpty)
+ }
+
+ @Test("A missing local symbol table is not the same answer as a missing symbol")
+ func missingSymbolTableThrows() throws {
+ _ = try #require(LWCRFixture.pristine, LWCRFixture.missing)
+ let clone = try LWCRFixture.cloneCache(named: "nosymbols")
+ defer { LWCRFixture.discard(clone) }
+
+ try FileManager.default.removeItem(
+ at: clone.appendingPathComponent("dyld_shared_cache_arm64e.symbols")
+ )
+ #expect(throws: DSCError.self) {
+ try DSCXPCLWCRPatcher.apply(directory: clone, dryRun: true, log: nil)
+ }
+ }
+}
+
+// MARK: - The two shape detectors, on real instruction streams
+
+@Suite(.serialized, .enabled(if: LWCRFixture.runs, LWCRFixture.skipReason))
+struct DSCXPCLWCRShapeTests {
+ /// `_xpc_token_satisfies_lwcr` as it is disassembled out of a cache.
+ private func functionStream(in directory: URL) throws -> [Instruction] {
+ let chunks = try DSCChunkSet(directory: directory)
+ var address: UInt64?
+ for candidate in DSCXPCLWCRPatcher.symbolCandidates {
+ if let found = try chunks.resolveLocalSymbol(candidate) {
+ address = found
+ break
+ }
+ }
+ let vma = try #require(address, "\(DSCXPCLWCRPatcher.symbol) is not in this cache")
+ return try DSCXPCLWCRPatcher.disassembleFunction(
+ in: chunks,
+ at: vma,
+ disassembler: ARM64Disassembler()
+ )
+ }
+
+ @Test("The symbol resolves under its mangled spelling, at a function prologue")
+ func symbolResolvesToAFunctionStart() throws {
+ let pristine = try #require(LWCRFixture.pristine, LWCRFixture.missing)
+ let chunks = try DSCChunkSet(directory: pristine)
+
+ let mangledAddress = try chunks.resolveLocalSymbol("__xpc_token_satisfies_lwcr")
+ let mangled = try #require(
+ mangledAddress,
+ "the double-underscore spelling is the one Mach-O stores"
+ )
+ // The single-underscore source spelling is a miss, which is why the
+ // patcher tries both rather than only the obvious one.
+ let sourceSpelling = try chunks.resolveLocalSymbol(DSCXPCLWCRPatcher.symbol)
+ #expect(sourceSpelling == nil)
+
+ let stream = try DSCXPCLWCRPatcher.disassembleFunction(
+ in: chunks,
+ at: mangled,
+ disassembler: ARM64Disassembler()
+ )
+ #expect(stream.first?.mnemonic == "pacibsp")
+ #expect(stream.last?.mnemonic == "retab")
+ #expect(stream.count < DSCXPCLWCRPatcher.maxInstructions)
+ }
+
+ @Test("On a pristine stream the idiom matches and the patched shape does not")
+ func pristineStreamMatchesTheIdiomOnly() throws {
+ let pristine = try #require(LWCRFixture.pristine, LWCRFixture.missing)
+ let disassembler = ARM64Disassembler()
+ let stream = try functionStream(in: pristine)
+
+ let site = try #require(
+ DSCXPCLWCRPatcher.findConsistencyCheck(in: stream, disassembler: disassembler)
+ )
+ #expect(site.cset.mnemonic == "cset")
+ #expect(site.cset.aarch64?.conditionCode == AArch64CC_NE)
+ #expect(site.eor.mnemonic == "eor")
+ #expect(site.tbz.mnemonic == "tbz")
+ #expect(site.eor.address == site.cset.address + 4)
+ #expect(site.tbz.address == site.eor.address + 4)
+ // The xor's left operand is the matcher's return register, and its
+ // right operand is what the cset wrote — the dataflow that makes the
+ // match unambiguous.
+ #expect(DSCXPCLWCRPatcher.register(site.eor, 1, disassembler) == "w0")
+ #expect(
+ DSCXPCLWCRPatcher.register(site.eor, 2, disassembler)
+ == DSCXPCLWCRPatcher.register(site.cset, 0, disassembler)
+ )
+
+ #expect(DSCXPCLWCRPatcher.findPatchedShape(in: stream, disassembler: disassembler) == nil)
+ }
+
+ @Test("On a patched stream the patched shape matches and the idiom does not")
+ func patchedStreamMatchesThePatchedShapeOnly() throws {
+ _ = try #require(LWCRFixture.pristine, LWCRFixture.missing)
+ let clone = try LWCRFixture.cloneCache(named: "shape")
+ defer { LWCRFixture.discard(clone) }
+
+ let disassembler = ARM64Disassembler()
+ let outcome = try DSCXPCLWCRPatcher.apply(directory: clone, log: nil)
+ #expect(outcome.siteCount == 3)
+
+ let stream = try functionStream(in: clone)
+ #expect(DSCXPCLWCRPatcher.findConsistencyCheck(in: stream, disassembler: disassembler) == nil)
+
+ let already = try #require(
+ DSCXPCLWCRPatcher.findPatchedShape(in: stream, disassembler: disassembler)
+ )
+ #expect(already.mnemonic == "cset")
+ #expect(already.aarch64?.conditionCode == AArch64CC_EQ)
+ #expect(already.address == outcome.records[0].virtualAddress)
+ }
+
+ @Test("Neither detector matches a stream that stops before the check")
+ func aTruncatedStreamMatchesNothing() throws {
+ let pristine = try #require(LWCRFixture.pristine, LWCRFixture.missing)
+ let disassembler = ARM64Disassembler()
+ let stream = try functionStream(in: pristine)
+ let site = try #require(
+ DSCXPCLWCRPatcher.findConsistencyCheck(in: stream, disassembler: disassembler)
+ )
+ let csetIndex = try #require(stream.firstIndex { $0.address == site.cset.address })
+
+ // Everything before the `cset` — the prologue and the matcher call.
+ let truncated = Array(stream[..<csetIndex])
+ #expect(DSCXPCLWCRPatcher.findConsistencyCheck(in: truncated, disassembler: disassembler) == nil)
+ #expect(DSCXPCLWCRPatcher.findPatchedShape(in: truncated, disassembler: disassembler) == nil)
+
+ // And an empty stream, which is what a symbol pointing into data looks
+ // like. Both detectors index backwards, so this is the bounds check.
+ #expect(DSCXPCLWCRPatcher.findConsistencyCheck(in: [], disassembler: disassembler) == nil)
+ #expect(DSCXPCLWCRPatcher.findPatchedShape(in: [], disassembler: disassembler) == nil)
+ }
+
+ @Test("The idiom needs the cset that feeds the xor, not just any cset")
+ func aStrandedXorDoesNotMatch() throws {
+ let pristine = try #require(LWCRFixture.pristine, LWCRFixture.missing)
+ let disassembler = ARM64Disassembler()
+ let stream = try functionStream(in: pristine)
+ let site = try #require(
+ DSCXPCLWCRPatcher.findConsistencyCheck(in: stream, disassembler: disassembler)
+ )
+ let csetIndex = try #require(stream.firstIndex { $0.address == site.cset.address })
+
+ // Drop the `cset` and keep the `eor`/`tbz`: without the instruction
+ // that defines the xor's right operand there is no verdict to rewrite,
+ // and matching anyway would patch a function this does not understand.
+ var withoutCset = stream
+ withoutCset.remove(at: csetIndex)
+ #expect(
+ DSCXPCLWCRPatcher.findConsistencyCheck(in: withoutCset, disassembler: disassembler) == nil
+ )
+ }
+}
diff --git a/tests/FirmwarePatcherTests/FirmwarePatcherTests.swift b/tests/FirmwarePatcherTests/FirmwarePatcherTests.swift
index 01f54e52..d7561e70 100644
--- a/tests/FirmwarePatcherTests/FirmwarePatcherTests.swift
+++ b/tests/FirmwarePatcherTests/FirmwarePatcherTests.swift
@@ -510,7 +510,11 @@ struct FirmwarePipelineTests {
let pipeline = FirmwarePipeline(vmDirectory: tempDir, variant: .regular, verbose: false)
let found = try pipeline.findFile(in: tempDir, patterns: ["AVPBooter*.bin"], label: "AVPBooter")
- #expect(found == target)
+ // Both sides resolved: `NSTemporaryDirectory()` hands back `/var/...`
+ // and `findFile` returns what the directory scan saw, which is the
+ // realpath `/private/var/...`. Comparing them raw made this test red on
+ // every macOS that symlinks /var, which is all of them.
+ #expect(found.resolvingSymlinksInPath() == target.resolvingSymlinksInPath())
}
}