Run a virtual iPhone on an Apple Silicon Mac.
Swift
cfw: jb: Fix iOS 27 daemon crash-loop (libxpc LWCR self-check abort)
zqxwce0827e0ad539e
diff --git a/research/0_binary_patch_comparison.md b/research/0_binary_patch_comparison.mdindex 13594e1c..75569c9f 100644--- a/research/0_binary_patch_comparison.md+++ b/research/0_binary_patch_comparison.md@@ -188,6 +188,7 @@ do NOT execute these).| 12 | NOP `-[_LSDModifyClient clientIsEntitledForEmbeddedRegistrationOperations]` entitlement gate + per-page re-attest — **iOS 27.0** | DSC `CoreServices` (LaunchServices) | **iOS-27 app-registration fix.** lsd gates `-[_LSDModifyClient performPostInstallationRegistration:operationUUID:reply:]` (and the containerized/rebuild registration paths) behind `clientIsEntitledForEmbeddedRegistrationOperations`, which does `xpc_connection_copy_entitlement_value` on the XPC peer for any of `com.apple.private.coreservices.lsaw` / `com.apple.private.installcoordinationd.daemon` / `com.apple.private.coreservices.can-register-install-results`. A client without one gets `NSOSStatusErrorDomain -54` (permErr, `LSDModifyService.mm:1639`), so `registerApplicationDictionary:` / `registerContainerizedApplicationWithInfoDictionaries:` fail and no app can (re)register — blocking vphoned's installer, TrollStore, and uicache/Sileo alike. The entitlement route is a dead end even for a launchd platform daemon (vphoned) whose validated csblob (`csops CS_OPS_ENTITLEMENTS_BLOB`) contains all three: LS registration is proxied, so the XPC peer lsd inspects is not the registering process. Fix: NOP the final `cbz w0, <not_entitled>` (the conditional branch whose fall-through sets the `mov w<reg>,#1` result) so the method always returns YES. Fully dynamic: method resolved via the DSC's own `.symbols` in-image local-symbol table (ipsw `symaddr -a`/`a2s` time out on this cache), gate located by control-flow shape in Capstone, NOP from Keystone `asm("nop")`, modified 16 KiB page re-attested (`cfw_dsc_codesign.py`; TXM enforces per-page). The resulting CDHash change is accepted by the JB always-true AMFI cdhash-trust patch. Install gate: **`27.*`** (hard-gated in `cfw_install.sh` as of 2026-07-20 — an 18.x/26.x base does not apply it). The patcher additionally self-gates (`patch-lsd-embedded-reg`): no-op on pre-iOS-27 userlands where the method is absent. **Pairs with vphoned's `vp_register_path` containerized-registration fallback** (`registerContainerizedApplicationWithInfoDictionaries:...:registrationError:`, treating a nil `registrationError` as success since it returns NO even when it registers). Also paired with **`/cores/vpregister`** (built + deployed by `cfw_install_jb.sh` / `cfw_install_exp.sh`, invoked by `vphone_jb_setup.sh` at first boot — 27-gated by DEPLOYMENT: `cfw_install_jb.sh`/`cfw_install_exp.sh` copy `/cores/vpregister` only when the mounted rootfs `SystemVersion.plist` is `27.*`, and the setup script's `[ -x /cores/vpregister ]` presence check is the runtime gate. Do NOT gate the invocation on a guest `sw_vers` check — the hybrid guest does not reliably report the 27 userland version at first boot, which silently skipped registration): it registers JB app bundles (Sileo) via the same containerized API, because `uicache -a`'s `registerApplicationDictionary:` is a deprecated no-op on iOS 27 (lsd logs *"you cannot use ... to register applications anymore. These interfaces have been deprecated for years."*). **VALIDATED (2026-07-17, `17,3_27.0_24A5380h` + cloudOS 26.4, JB): -54 gone; Sileo registers (`uicache -l` 0→1) via `vpregister`; vphoned installs+registers a test IPA (`com.vphone.vptest`) to `/var/containers/Bundle/Application/` end-to-end. Clean boot (re-attest correct; no CoreServices page rejection).** See `scripts/patchers/cfw_patch_lsd_embedded_reg.py` and `scripts/vphoned/vpregister.m`. | Y | Y | Y || 13 | `mov x0,#1; ret` on `-[DIDiskArb isMountCompleteWithExpectedCount:diskTracker:]` — **iOS 27.0** | `diskimagesiod` | **iOS-27 DDI (`/System/Developer`) auto-mount — mount-gate.** After the personalized DDI attaches (kernel side: JB-28 + JB-09), MobileStorageMounter waits on diskimagesiod's `-[DIDiskArb waitForDAMountWithExpectedCount:diskTracker:]` before it does the real (nobrowse) mount at `/System/Developer`. That wait loops until `isMountComplete` (= `callbackReached \|\| (appearedDiskCount>=expectedCount && mountedDiskCount>=mountableDiskCount)`) is YES; on the 26.4-kernel / 27-userland hybrid it never becomes true (not all of the DMG's IOMedia "appear" to diskimagesiod's DiskArbitration session, and diskarbitrationd never auto-mounts the volume), so the wait hangs and pmd3 times out. diskimagesiod itself does NOT mount the DDI (its `-[DIDiskArb mountWithDeviceName:...]` is dead code) — it only gates MobileStorageMounter. Forcing `isMountComplete` → YES lets the wait return so MobileStorageMounter proceeds. IMP resolved via LC_SYMTAB or ObjC metadata (selector → `__objc_selrefs` → `__TEXT,__objc_methlist` relative method list → IMP); prologue overwritten `mov x0,#1 ; ret` (safe — the method returns to the caller's unsigned LR without pushing a frame). **Gated to 27.\*** in `cfw_install.sh` (same `$IOS_VERSION` as the DSC patches): on a version-matched userland the native wait completes correctly and forcing it early could race the real mount, so it is NOT applied there. Embedded sandbox profile + private DA/apfs entitlements preserved on re-sign (`ldid_sign_ent`). **Validated on `c0ecdb4b` 26.4 + 27.0 userland: `pmd3 mounter auto-mount` → rc=0, DDI at `/System/Developer`, idempotent across fresh boots.** See `scripts/patchers/cfw_patch_diskimagesiod.py`. | Y | Y | Y || 14 | Merge backboard/frontboard launch mach-services into `com.apple.security.exception.mach-lookup.global-name` + `ldid_sign_ent` re-sign — **iOS 27.0** | `/Applications/Campo.app/Campo` | **iOS-27 Campo (wallpaper renderer) crash-loop fix — sandbox half.** Campo declares `com.apple.private.sandbox.profile:embedded = temporary-sandbox` + `no-container`, so it runs under the `temporary-sandbox` profile. On the 26.4 vphone600 kernel that builtin profile predates iOS 27 and DENIES the `mach-lookup` of the backboard/frontboard launch services, so `BKSDisplayServicesStart` (looks up `com.apple.backboard.display.services`) and then `+[BKSHIDEventDeliveryManager sharedInstance]` (HID) fail, log *"backboardd isn't running -- or we couldn't talk to it"*, and `brk #0` ~34 ms after launch → continuous crash-loop, no wallpaper (launchd eventually throttles it off). **JB-02d is NOT sufficient here:** it stops the exec-time container-manager-upcall autobox *KILL*, but Campo is still placed in `temporary-sandbox` (its own declared profile — confirmed the JB-02d `b`-flip is present in the running kernel yet Campo still traps), and that profile still denies the lookups. Fix: append the needed services to Campo's OWN `com.apple.security.exception.mach-lookup.global-name` array — the Apple-sanctioned escape hatch, which `temporary-sandbox` honors (Campo already ships ~20 such exceptions; these launch services simply aren't among them because 27's profile allows them directly). Services added (backboard names exact, from `com.apple.backboardd.plist` MachServices): `com.apple.backboard.display.services`, `com.apple.iohideventsystem`, `com.apple.CARenderServer`, `com.apple.backboard.hid.services`, `com.apple.backboard.hid-services.xpc`, `com.apple.backboard.TouchDeliveryPolicyServer`, `com.apple.backboard.system-app-server`, `com.apple.backboard.watchdog`, `com.apple.backboard.oswatchdog`, `com.apple.backboard.altsysapp`, `com.apple.AttentionAwareness`, `PurpleSystemEventPort`, `PurpleWorkspacePort`, `com.apple.frontboard.systemappservices`, `com.apple.frontboard.workspace`, `com.apple.frontboardservices.systemappmanager`, `com.apple.frontboard.watchdog`. Merge is done by the external helper `scripts/patchers/campo_mach_lookup_exceptions.py` (Python `plistlib`, not `plutil` — the entitlement key contains dots that `plutil` keypaths would mis-split; idempotent, preserves the existing array); re-signed with the JB `signcert.p12` via `ldid_sign_ent` (AMFI enforcement is relaxed on the research VM, so the re-signed cdhash loads and the entitlements are honored). Applied at host-mount build time in `cfw_install_jb.sh` / `cfw_install_exp.sh` step **[JB-3b]**, **hard-gated to `27.*`** via the mounted rootfs `SystemVersion.plist` `ProductVersion` (same gate as the vpregister/DSC patches) — skipped entirely on 26.x/18.x, which don't need it and where `Campo.app` also exists. **VALIDATED on-device (2026-07-21, `17,3_27.0_24A5390f` + cloudOS 26.4, JB): Campo launches and stays up (stable pid, no BKSDisplayServicesStart/BKSHIDEventDeliveryManager trap, no crash-loop); first-cut display-only exception advanced the trap from display→HID, confirming the mechanism, then the full service set cleared it.** See `scripts/cfw_install_jb.sh` / `scripts/cfw_install_exp.sh` step JB-3b and the merge helper `scripts/patchers/campo_mach_lookup_exceptions.py`. | - | - | Y |+| 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: `_xpc_token_satisfies_lwcr` resolved via the DSC's own `.symbols` in-image local-symbol table, 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`. | Y | Y | Y |### Installed Componentsdiff --git a/scripts/cfw_install.sh b/scripts/cfw_install.shindex d319ee12..f0fedbcf 100755--- a/scripts/cfw_install.sh+++ b/scripts/cfw_install.sh@@ -349,6 +349,11 @@ esac# the iOS-27 vpregister first-boot tool can register JB apps (uicache's# registerApplicationDictionary is a no-op stub on 27). Not needed on 26.x/18.x,# where uicache registers apps normally.+# - xpc LWCR self-check: iOS 27's libxpc brk-aborts when its Lightweight Code+# Requirement matcher returns the contradictory (matched=0, error_code=MATCH) pair+# that our JB code-signing environment produces. That crash-loops every daemon which+# pins an entitlement peer-requirement (intelligencetasksd/searchpartyd/transparencyd/+# bluetoothd/...). Absent on 26.x/18.x libxpc (self-gating patcher no-ops there).DSC_DIR="$MNT1/System/Cryptexes/OS/System/Library/Caches/com.apple.dyld"case "$IOS_VERSION" in27.*)@@ -357,6 +362,8 @@ case "$IOS_VERSION" in"$PYTHON3" "$SCRIPT_DIR/patchers/cfw.py" patch-dsc-maxslide "$DSC_DIR"echo " [*] Patching lsd embedded-registration gate (iOS 27 app registration)...""$PYTHON3" "$SCRIPT_DIR/patchers/cfw.py" patch-lsd-embedded-reg "$DSC_DIR"+ echo " [*] Patching libxpc LWCR self-check (iOS 27 daemon crash-loop)..."+ "$PYTHON3" "$SCRIPT_DIR/patchers/cfw.py" patch-xpc-lwcr "$DSC_DIR"fi;;esacdiff --git a/scripts/patchers/cfw.py b/scripts/patchers/cfw.pyindex 5e678e89..ae08e052 100755--- a/scripts/patchers/cfw.py+++ b/scripts/patchers/cfw.py@@ -57,6 +57,15 @@ Commands:otherwise demands from the XPC peer. Unblocks vphoned/TrollStore/uicache appinstalls. Self-gating (no-op on pre-iOS-27 userlands where the method is absent).+ patch-xpc-lwcr <chunks_dir> [--dry-run]+ Stop libxpc's Lightweight Code Requirement self-check (_xpc_token_satisfies_lwcr)+ from brk-aborting on our JB. iOS 27's LWCR matcher returns the contradictory+ (matched=0, error_code=MATCH) pair under our code-signing environment; the+ assertion crash-loops every daemon that pins an entitlement peer-requirement+ (intelligencetasksd/searchpartyd/transparencyd/bluetoothd/...). Derives `matched`+ from error_code + drops the abort (cset w0,eq; nop; nop) and re-attests the page.+ Self-gating (no-op on pre-iOS-27 userlands where the symbol is absent).+patch-camera-dsc <chunks_dir> <dsc_header> [--dry-run] [--force]Apply the 10-patch set to the DSC chunks that makes Camera.applaunch-survivable on a vphone VM: synthesises a single@@ -116,6 +125,7 @@ if __name__ == "__main__":from patchers.cfw_patch_iomfb_force_kern import patch_iomfb_force_kernfrom patchers.cfw_patch_dsc_maxslide import patch_dsc_maxslidefrom patchers.cfw_patch_lsd_embedded_reg import patch_lsd_embedded_reg+ from patchers.cfw_patch_xpc_lwcr import patch_xpc_lwcrfrom patchers.cfw_patch_camera_dsc import apply_all_camera_patchesfrom patchers.cfw_patch_watchdogd import patch_watchdogdfrom patchers.cfw_patch_diskimagesiod import patch_diskimagesiod@@ -130,6 +140,7 @@ else:from .cfw_patch_iomfb_force_kern import patch_iomfb_force_kernfrom .cfw_patch_dsc_maxslide import patch_dsc_maxslidefrom .cfw_patch_lsd_embedded_reg import patch_lsd_embedded_reg+ from .cfw_patch_xpc_lwcr import patch_xpc_lwcrfrom .cfw_patch_camera_dsc import apply_all_camera_patchesfrom .cfw_patch_watchdogd import patch_watchdogdfrom .cfw_patch_diskimagesiod import patch_diskimagesiod@@ -232,6 +243,14 @@ def main():patch_lsd_embedded_reg(sys.argv[2], dry_run=dry_run)sys.exit(0)+ elif cmd == "patch-xpc-lwcr":+ if len(sys.argv) < 3:+ print("Usage: patch_cfw.py patch-xpc-lwcr <chunks_dir> [--dry-run]")+ sys.exit(1)+ dry_run = "--dry-run" in sys.argv[3:]+ patch_xpc_lwcr(sys.argv[2], dry_run=dry_run)+ sys.exit(0)+elif cmd == "patch-camera-dsc":if len(sys.argv) < 4:print("Usage: patch_cfw.py patch-camera-dsc <chunks_dir> <dsc_header> [--dry-run] [--force]")@@ -300,7 +319,7 @@ def main():print(f"Unknown command: {cmd}")print("Commands: cryptex-paths, patch-seputil, patch-launchd-cache-loader, patch-camera-dsc,")print(" patch-mobileactivationd, patch-launchd-jetsam,")- print(" patch-hv-vmm-dsc, patch-iomfb-swapend, patch-iomfb-force-kern, patch-dsc-maxslide, patch-lsd-embedded-reg, patch-watchdogd,")+ print(" patch-hv-vmm-dsc, patch-iomfb-swapend, patch-iomfb-force-kern, patch-dsc-maxslide, patch-lsd-embedded-reg, patch-xpc-lwcr, patch-watchdogd,")print(" patch-diskimagesiod, inject-daemons, patch-dropbear-plist, inject-dylib")sys.exit(1)diff --git a/scripts/patchers/cfw_patch_xpc_lwcr.py b/scripts/patchers/cfw_patch_xpc_lwcr.pynew file mode 100644index 00000000..815b7592--- /dev/null+++ b/scripts/patchers/cfw_patch_xpc_lwcr.py@@ -0,0 +1,213 @@+"""Patch libxpc so the Lightweight Code Requirement (LWCR) self-check can't+abort on our JB.++iOS 27 introduced XPC "lightweight code requirements": a server pins a code+requirement on its listener (via `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 and a `match_result.error_code` — and then hard-asserts they+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> ; abort (brk #1) when they disagree++On stock iOS the two always agree. On our JB the matcher's code-signing query+writes error_code = MATCH(0) but then returns a failure status, yielding the+forbidden combination (matched=0, error_code=0). libxpc `brk #1`-aborts, so+every daemon that pins an entitlement peer-requirement at startup+(intelligencetasksd, searchpartyd, transparencyd, bluetoothd, ...) crash-loops+— which in turn churns the SpringBoard/backboardd group into resprings.++Fix: make `matched` consistent with `error_code` by construction and drop the+abort. Derive the return from error_code (the matcher's own verdict) and NOP+the xor + the conditional branch:++ 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 is preserved (error_code drives it, exactly as stock does when+the two agree); only the internally-contradictory case is resolved — toward+"satisfied" when error_code says MATCH — instead of aborting.++Nothing is hardcoded: `_xpc_token_satisfies_lwcr` is resolved from the DSC's+own local-symbol table, disassembled with Capstone, and the check located by+control-flow shape (the `cset wC,ne; eor wE,w0,wC; tbz wE,#0` idiom).+Replacements come from Keystone. The modified 16 KiB page is re-attested (TXM+enforces per-page); the CDHash change is accepted by the JB's always-true AMFI+cdhash-trust patch.+"""++import os+import struct++from capstone.arm64_const import ARM64_OP_REG, ARM64_OP_IMM++try:+ from .cfw_asm import asm, _cs+ from .cfw_dsc_chunks import DSCChunks+ from .cfw_dsc_codesign import reattest_modified_pages+except ImportError: # direct self-test / standalone execution+ from cfw_asm import asm, _cs+ from cfw_dsc_chunks import DSCChunks+ from cfw_dsc_codesign import reattest_modified_pages+++SYMBOL = "_xpc_token_satisfies_lwcr"+++def _resolve_local_symbol(chunks_dir, name):+ """Resolve a symbol to its vmaddr via the DSC's own `.symbols` local-symbol+ table (in-image; no repo-exported dumps)."""+ sym = os.path.join(chunks_dir, "dyld_shared_cache_arm64e.symbols")+ with open(sym, "rb") as f:+ hdr = f.read(0x100)+ if hdr[:15] != b"dyld_v1 arm64e":+ raise RuntimeError(f"unexpected .symbols magic in {sym}")+ local_off = struct.unpack_from("<Q", hdr, 72)[0]+ f.seek(local_off)+ nlist_off, nlist_cnt, str_off, str_sz, _eo, _ec = struct.unpack("<IIIIII", f.read(24))+ f.seek(local_off + str_off)+ strings = f.read(str_sz)+ f.seek(local_off + nlist_off)+ nl = f.read(nlist_cnt * 16)+ want = name.encode()+ for i in range(nlist_cnt):+ n_strx, _t, _s, _d, n_value = struct.unpack_from("<IBBHQ", nl, i * 16)+ if n_strx >= len(strings):+ continue+ end = strings.find(b"\x00", n_strx)+ if strings[n_strx:end] == want:+ return n_value+ raise RuntimeError(f"could not resolve {name!r} in .symbols")+++def _disasm_function(chunks, vma, max_insns=160):+ buf = chunks.bytes_at_vma(vma, max_insns * 4)+ insns = []+ for insn in _cs.disasm(buf, vma):+ insns.append(insn)+ if insn.mnemonic in ("ret", "retab"):+ break+ return insns+++def _rn(insn, idx):+ ops = insn.operands+ if idx >= len(ops) or ops[idx].type != ARM64_OP_REG:+ return None+ return insn.reg_name(ops[idx].reg)+++def _find_consistency_check(insns):+ """Locate the LWCR self-consistency idiom and return the (cset, eor, tbz)+ instructions plus the error_code register.++ Shape:+ cset wC, ne+ eor wE, w0, wC+ tbz wE, #0, <abort>+ """+ for i in range(len(insns) - 1):+ eor = insns[i]+ if eor.mnemonic != "eor":+ continue+ wE, w0, wC = _rn(eor, 0), _rn(eor, 1), _rn(eor, 2)+ if w0 != "w0" or wE is None or wC is None:+ continue+ tbz = insns[i + 1]+ if tbz.mnemonic != "tbz":+ continue+ if _rn(tbz, 0) != wE:+ continue+ tops = tbz.operands+ if len(tops) < 2 or tops[1].type != ARM64_OP_IMM or tops[1].imm != 0:+ continue+ # Walk back for `cset wC, ne` feeding the eor.+ cset = None+ for j in range(i - 1, max(-1, i - 6), -1):+ cand = insns[j]+ if cand.mnemonic == "cset" and _rn(cand, 0) == wC:+ cops = cand.operands+ if len(cops) >= 2 and cops[1].type == ARM64_OP_IMM:+ # capstone renders the condition as an operand imm code;+ # use op_str to confirm it is `ne`.+ pass+ if cand.op_str.strip().endswith("ne"):+ cset = cand+ break+ if cset is None:+ continue+ return cset, eor, tbz, wC+ return None+++def patch_xpc_lwcr(chunks_dir, *, dry_run=False):+ chunks = DSCChunks(chunks_dir)+ print(f" [.] {chunks!r}")++ # Self-gating: the LWCR path only exists on iOS 27+ libxpc. On older+ # userlands the symbol is absent, so this is a no-op there.+ try:+ fn_vma = _resolve_local_symbol(chunks_dir, SYMBOL)+ except RuntimeError:+ print(f" [=] {SYMBOL} not present (pre-iOS-27 userland); nothing to patch")+ return 0+ print(f" [.] {SYMBOL} @ 0x{fn_vma:X}")++ insns = _disasm_function(chunks, fn_vma)+ found = _find_consistency_check(insns)+ if found is None:+ raise ValueError(+ f"{SYMBOL}: LWCR consistency idiom (cset wC,ne; eor wE,w0,wC; "+ f"tbz wE,#0) not found"+ )+ cset, eor, tbz, wC = found+ print(f" [.] cset @ 0x{cset.address:X}: {cset.mnemonic} {cset.op_str}")+ print(f" [.] eor @ 0x{eor.address:X}: {eor.mnemonic} {eor.op_str}")+ print(f" [.] tbz @ 0x{tbz.address:X}: {tbz.mnemonic} {tbz.op_str}")++ nop = asm("nop")+ cset_new = asm("cset w0, eq") # w0 = matched = (error_code == 0)+ edits = [+ (cset.address, cset_new, "cset w0, eq"),+ (eor.address, nop, "nop"),+ (tbz.address, nop, "nop"),+ ]++ modified = []+ for vma, new_bytes, label in edits:+ cur = chunks.bytes_at_vma(vma, 4)+ if cur == new_bytes:+ print(f" [=] already patched at 0x{vma:X} ({label})")+ continue+ action = "would write" if dry_run else "wrote"+ print(f" [+] {action} {label} at 0x{vma:X} ({cur.hex()} -> {new_bytes.hex()})")+ if not dry_run:+ chunks.write_at_vma(vma, new_bytes)+ modified.append(vma)++ if not dry_run and modified:+ print(f" [.] re-attesting modified page(s)...")+ reattest_modified_pages(chunks, modified, dry_run=False)+ for vma, new_bytes, _ in edits:+ if chunks.bytes_at_vma(vma, 4) != new_bytes:+ raise RuntimeError(f"post-write verify failed at 0x{vma:X}")+ elif dry_run:+ print(f" [.] dry-run: would re-attest page for {[hex(v) for v in modified]}")++ print(f" [+] libxpc LWCR self-check patch complete")+ return 1+++if __name__ == "__main__":+ import sys+ dry = "--apply" not in sys.argv+ args = [a for a in sys.argv[1:] if not a.startswith("--")]+ d = args[0] if args else "/private/tmp/cryptex27/System/Library/Caches/com.apple.dyld"+ patch_xpc_lwcr(d, dry_run=dry)