Run a virtual iPhone on an Apple Silicon Mac.
Swift
[kernel-jb] retarget hooks broken by cloudOS 26.5 kernel drift
Gilbod34c023e55d5
diff --git a/Makefile b/Makefileindex 1cfc8d0a..e8309876 100644--- a/Makefile+++ b/Makefile@@ -108,6 +108,10 @@ help:@echo " make fw_patch_jb Patch boot chain with Swift pipeline (dev + JB extensions)"@echo " make fw_patch_exp Patch boot chain with Swift pipeline (JB + EXP experimental)"@echo ""+ @echo "Testing:"+ @echo " make test_jb_patches Run all JB kernel patches (incl. Sandbox) over every supported cloudOS kernel"+ @echo " Options: QUICK=1 Only the local/newest kernel (fast dev loop)"+ @echo ""@echo "Restore:"@echo " make restore_get_shsh Dump SHSH response from Apple"@echo " make restore Restore to device (pymobiledevice3 backend)"@@ -360,6 +364,16 @@ fw_patch_jb: patcher_buildfw_patch_exp: patcher_build"$(CURDIR)/$(PATCHER_BINARY)" patch-firmware --vm-directory "$(VM_DIR_ABS)" --variant exp+.PHONY: test_jb_patches++# Run the full JB kernel patch layer (every hook, incl. all Sandbox ops hooks)+# over EVERY cloudOS kernel the README supports — correctness + backward-compat.+# Downloads each version's kernelcache on demand (cached under /tmp/vphone_kjb_versions).+# Options: QUICK=1 Only the local/newest kernel (fast dev loop)+test_jb_patches: patcher_build+ zsh "$(CURDIR)/tests/test_jb_kernel_patches.sh" --no-build \+ $(if $(filter 1 true yes YES TRUE,$(QUICK)),--quick,)+# ═══════════════════════════════════════════════════════════════════# Restore# ═══════════════════════════════════════════════════════════════════diff --git a/docs/26.5_jb_hook_fixes.md b/docs/26.5_jb_hook_fixes.mdnew file mode 100644index 00000000..c1445d73--- /dev/null+++ b/docs/26.5_jb_hook_fixes.md@@ -0,0 +1,219 @@+# Jailbreak Kernel Hooks — cloudOS 26.5 Fixes++_Last updated: 2026-06-16_++## What this is++The jailbreak (`jb`/`exp`) firmware variants apply a set of small kernel edits ("hooks")+that switch off specific security checks so the jailbreak can do its job. Each hook+finds its spot in the kernel by looking for a recognizable code pattern — **not** by a+fixed address — because Apple's kernel layout shifts with every release.++When we moved to **cloudOS 26.5**, Apple recompiled the kernel and several of those+patterns changed shape. Nine hooks could no longer find their spot, so they **silently+did nothing**. The build still reported "success" (it only fails if *zero* patches+apply), so the breakage only showed up at runtime — starting with `sudo` not working.++This document lists each broken hook, why it matters, and how we re-anchored it so it+works on 26.5 **and** older releases.++## The guiding principle for every fix++We never hardcode an address. For each hook we picked an anchor that is **stable across+versions**:++- a **string** the kernel still contains (e.g. a panic message),+- a **standard constant** that Apple won't change (an error code, a privilege ID, a+ protection bit), or+- a **relationship** between functions (who calls whom).++…and then we require the match to be **unique** — if the pattern ever becomes+ambiguous, the hook refuses to patch rather than guess wrong. The result is the same+patch lands on 26.5 and on the earlier kernels we derived the originals from.++---++## The hooks++### 1. `sudo` / setuid (cred-label on exec)+- **The hook:** re-applies "run as root" when a setuid binary is launched.+- **Why it's needed:** the jailbreak's files live on a partition mounted "no setuid," so+ without this hook `sudo` and every root helper run as a normal user.+- **What broke & the fix:** the hook located a helper function by an exact instruction+ sequence whose last instruction's offset changed (an internal struct field moved). We+ now match the stable part of that sequence and accept *any* value for the field that+ moved, instead of pinning the old one.+- **Symptom if missing:** `sudo` fails with "effective uid is not 0 … nosuid".++### 2. Process security policy+- **The hook:** forces the "are you allowed to inspect/control this other process?" check+ to always say yes.+- **Why it's needed:** jailbreak tools enumerate, inspect, and manage other processes;+ the stock check denies that across different users.+- **What broke & the fix:** the old code found the check via a switch-table size number+ that changed, and on 26.5 it accidentally matched the wrong function. We now find it by+ the one thing that's unique to it: it asks for the **"query other users' processes"+ privilege**, a fixed ID Apple keeps stable. Only this function uses it.+- **Symptom if missing:** process listing/inspection tools get "permission denied."++### 3. `proc_pidinfo` pid-0 guards+- **The hook:** removes two early checks that block asking about the kernel/PID 0.+- **Why it's needed:** some kernel-introspection tooling queries PID 0.+- **What broke & the fix:** this code got folded into a much larger function, so the old+ "look at the start of the function" approach missed it. We now search for the exact+ little guard sequence (it ends right before the kernel's `EINVAL` default and a switch),+ which is unique kernel-wide — so we no longer need to find the enclosing function at all.+- **Symptom if missing:** introspecting the kernel task returns "permission denied."++### 4. Task conversion+- **The hook:** lets you obtain another process's control handle.+- **Why it's needed:** this is the foundation for injecting into, debugging, or+ controlling other apps (`task_for_pid`-style operations).+- **What broke & the fix:** the compiler swapped the order of the two values in a+ comparison, so the old pattern didn't match. The fix accepts the comparison in **either+ order**. Everything else about the pattern is unchanged.+- **Symptom if missing:** in the *harder* cases — Developer Mode off, or targeting Apple's+ own system processes — getting a handle is rejected. Everyday use (a root, entitled tool+ with Developer Mode on attaching to a regular app) still works without this hook, which+ is why tools like frida-server kept running. See "How much did the broken hooks actually+ matter?" below.++### 5. Secure boot-root policy+- **The hook:** forces the "is this boot filesystem approved?" answer to success.+- **Why it's needed:** lets the device boot from a custom/ramdisk root instead of only an+ Apple-approved one.+- **What broke & the fix:** Apple inserted extra code that pushed the surrounding+ landmarks out of the window the old matcher searched. We re-anchored on the actual+ decision: the single spot that picks between "success" and the **"not privileged" error+ code** (a fixed IOKit constant). That's unambiguous and doesn't depend on the+ surrounding code.+- **Symptom if missing:** a custom root gets torn down during boot.++### 6. Mount policy+- **The hook:** removes two gates that block the mounts the jailbreak needs.+- **Why it's needed:** the jailbreak has to remount the system read-write and mount its+ own bootstrap; the stock policy rejects this.+- **What broke & the fix:** one gate was unchanged; the other was recompiled — two+ instructions got merged into one and the branch direction flipped. We now match the+ underlying check (a load of a status byte followed by a test of the same role bit)+ regardless of how it's spelled, and clear that byte.+- **Symptom if missing:** the jailbreak can't set up its filesystem (`/var/jb`), which can+ stall first-boot setup entirely.++### 7. Persona validation (process spawn)+- **The hook:** removes two rejections in the path that launches a process under a+ different identity ("persona").+- **Why it's needed:** jailbreak components launch helpers under specific identities.+- **What broke & the fix:** a trailing landmark the old matcher relied on was recompiled.+ We re-anchored on the two sibling "reject if empty" checks themselves (they both jump to+ the same rejection), which is the actual gate and is stable.+- **Symptom if missing:** launching a process with a custom persona is rejected.++### 8. Writable + executable memory (W^X)+- **The hook:** lets a memory region be both writable and executable (RWX).+- **Why it's needed:** required for JIT, runtime code generation, and many hooking+ frameworks that write code then run it.+- **What broke & the fix:** this one is compiled two different ways depending on the+ release. On 26.1/26.3 there's an explicit "skip the downgrade" branch; on 26.5 the+ downgrade became a runtime mask that strips one permission bit. We handle **both**: on+ the older shape we make the skip-branch unconditional; on the newer shape we widen the+ mask to keep **all** requested bits. The widen is strictly more permissive — it can only+ allow what was being blocked, never break a case that already worked. (This dual-shape+ handling was added specifically so the fix is backward-compatible — see below.)+- **Symptom if missing:** code that needs a *single* page that is writable and executable+ at the same time (some in-process JITs) fails. Tools that write code while a page is+ writable and then flip it to execute-only — like frida's out-of-process injection — are+ **not** affected, because that's still allowed under W^X.++### 9. Kernel-call syscall (`kcall10`)+- **The hook:** turns an unused syscall into a "call a kernel function from userspace"+ helper the jailbreak uses to drive the kernel.+- **Why it's needed:** it's the jailbreak's convenient bridge for kernel operations.+- **What broke & the fix:** finding the syscall table relied on locating an unimplemented+ "not supported" stub, but on 26.5 that stub looks different. We now find the table by+ its **shape** — the long run of fixed-size syscall entries that all point into kernel+ code — which doesn't depend on any one stub. The table is unmistakable (hundreds of+ entries; nothing else looks like it).+- **Symptom if missing:** the jailbreak loses its kernel-call bridge.++---++## How much did the broken hooks actually matter?++Short version: **the device still booted and most jailbreak tooling kept working.** The+broken hooks did not brick the jailbreak — which is exactly why the problem was easy to+miss. These hooks are *conditional* gates (they only block in specific situations), not+master on/off switches, and well-built tools are already designed to live within iOS's+restrictions.++A concrete example: **frida-server kept working** even with several of these hooks missing.+- Frida injects from *outside* the target process and never needs a page that is writable+ and executable at the same time — it writes code while a page is writable, then flips it+ to read+execute. So it never needed the W^X hook (#8). (Frida even has a built-in+ fallback for when simultaneous write+execute isn't allowed, which is the normal iOS case.)+- Frida's way of grabbing another process (`task_for_pid`) only trips the task-conversion+ hook (#4) in narrow cases — Developer Mode off, or targeting Apple's own system+ processes. Its normal use (running as root, with the right entitlement, Developer Mode+ on, attaching to a regular app) goes straight through.+- What frida and similar tools actually rely on is the **code-signing / AMFI relaxation** —+ and those hooks were applying correctly the whole time.++So the realistic impact of the breakage was **targeted malfunctions, not a dead+jailbreak**:+- **`sudo` / setuid was broken** (the symptom that kicked this off) — a hard, obvious failure.+- **A Sileo bug** — see below.+- Reduced robustness for the harder cases these hooks exist to cover (Developer Mode off,+ acting on Apple platform binaries, anything that genuinely needs a single+ write+execute page, etc.).++The lesson for testing: **"it boots and most things work" is not evidence the hooks are+fine.** A few of them can silently do nothing while the device looks completely healthy —+which is the whole reason the cross-version patch check (and, ideally, an on-device+functional check) matter.++### A Sileo bug also got fixed+Restoring the hooks also fixed a bug in **Sileo** (the jailbreak's package manager) that+was present on the affected build — it started working again once the full hook set was+back. We have **not** isolated *which* hook was responsible (it wasn't deliberately tracked+down). Worth pinning down if it recurs. Given what Sileo does — it runs as root, spawns+`apt`/`dpkg` and package maintainer scripts, and renders package pages — the most likely+candidates are the **process-spawn / persona** hook (#7), the **setuid** hook (#1), or the+**process-info** hooks (#2 / #3). Treat that as a lead, not a conclusion.++---++## How we verified it++- One test covers everything: **`make test_jb_patches`** (script: `tests/test_jb_kernel_patches.sh`)+ runs the whole JB kernel patch layer — every hook, including all the Sandbox ops hooks —+ over **every** cloudOS version the README lists as supported (26.1 / 26.3 / 26.4, and the+ current 26.5), and requires each kernel to apply with **0 failures** and emit every+ expected patch. (`QUICK=1` limits it to the local/newest kernel for a fast dev loop.)+ Result: **every version passes, 0 failures.**+- This cross-version run caught a real regression — the first W^X fix only worked on 26.5;+ we then made it handle both the old and new code shapes (see hook #8). On the oldest+ kernel (26.1) the generic anchors even land on the exact same locations the original+ hand-written patches used, which is strong evidence the new logic is correct.+- Every patched location was cross-checked against the actual kernel (via an IDA+ database) to confirm we're editing the right instruction.+- The full app builds and signs cleanly (`make build`).++## What still needs a human++These checks ran in "dry-run" mode (we confirm the right edits would be made). The final+confirmation — building real firmware and checking on a device — has **not** been run+here:++1. `make fw_prepare && make fw_patch_jb` — build the jailbreak firmware end-to-end and+ confirm the jailbreak layer reports 0 failures.+2. On the booted jailbroken device, run `sudo id` and confirm it returns `uid=0`.+3. Open **Sileo** and install/remove a package — confirm the previously-seen Sileo bug is+ gone (and, if you can, note which behavior changed so we can finally attribute it to a+ specific hook).++## Where to look in the code++- The hooks live in `sources/FirmwarePatcher/Kernel/JBPatches/` (one file per hook) with+ shared helpers in `sources/FirmwarePatcher/Kernel/KernelJBPatcherBase.swift`.+- Deeper, per-hook reverse-engineering notes are in `research/kernel_patch_jb/` and the+ patch inventory is `research/0_binary_patch_comparison.md`.diff --git a/research/0_binary_patch_comparison.md b/research/0_binary_patch_comparison.mdindex a6c54eea..0f444530 100644--- a/research/0_binary_patch_comparison.md+++ b/research/0_binary_patch_comparison.md@@ -130,7 +130,7 @@| JB-06 | B | `patch_post_validation_additional` | `_postValidation` (additional) | Disable SHA256-only hash-type reject | Y || JB-07 | C | `patch_syscallmask_apply_to_proc` | syscallmask apply wrapper (`_proc_apply_syscall_masks` path) | Faithful upstream C22: mutate installed Unix/Mach/KOBJ masks to all-ones via structural cave, then continue into setter; distinct from `NULL`-mask alternative | Y || JB-08 | A | `patch_task_conversion_eval_internal` | `_task_conversion_eval_internal` | Allow task conversion | Y |-| JB-09 | A | `patch_sandbox_hooks_extended` | Sandbox MACF ops (extended) | Stub remaining 30+ sandbox hooks (incl. IOKit 201..210) | Y |+| JB-09 | A | `patch_sandbox_hooks_extended` | Sandbox MACF ops (extended) | Stub remaining 30+ sandbox hooks (incl. IOKit 201..210)| Y || JB-10 | A | `patch_iouc_failed_macf` | IOUC MACF shared gate | A5-v2: patch only the post-`mac_iokit_check_open` deny gate (`CBZ W0, allow` -> `B allow`) and keep the rest of the IOUserClient open path intact | Y || JB-11 | B | `patch_proc_security_policy` | `_proc_security_policy` | Bypass security policy | Y || JB-12 | B | `patch_proc_pidinfo` | `_proc_pidinfo` | Allow pid 0 info | Y |@@ -826,3 +826,80 @@ cache rebuild.- removed ad-hoc `git clone` source fetching from `scripts/setup_tools.sh` and `scripts/setup_libimobiledevice.sh`.- added pinned git-submodule sources under `scripts/repos/` for: `trustcache`, `insert_dylib`, `libplist`, `libimobiledevice-glue`, `libusbmuxd`, `libtatsu`, `libimobiledevice`, `libirecovery`, `idevicerestore`.- setup scripts now initialize required submodules via `git submodule update --init --recursive <path>` and stage build copies under local tool build directories.+- 2026-06-15 cloudOS 26.5 (23F77) JB retargeting — P0 (sudo/setuid):+ - **JB-04 `patch_hook_cred_label_update_execve` (P0, sudo/setuid) — FIXED.**+ Root cause: `findVfsContextCurrentByShape()` pinned a 5-word prologue ending+ in `ldr x1, [x0, #0x3E0]`; the uthread offset drifted to `#0x3F0` on 26.5+ (`0x3E8` on macOS 26.5.1 KDK), so the exact match returned 0 hits.+ Fix: resolve `vfs_context_current` generically — symbol first, else the stable+ 4-word prologue prefix (`pacibsp; stp x29,x30,[sp,#-0x10]!; mov x29,sp;+ mrs x0,tpidr_el1`) followed by *any* `ldr x1,[x0,#imm]` (imm left unpinned);+ uniqueness still required. Reveal: on the decompressed kernelcache the prefix+ matches 5 sites, exactly one followed by an `ldr x1,[x0,#imm]` →+ `vfs_context_current` @ va `0x8D7F39C` (foff `0x1D7B39C`). Validated via+ `make test_jb_patches`: both `jb.hook_cred_label.{ops_retarget,c23_cave}` emit.+ - Symbol oracle for the above: macOS 26.5.1 KDK (`KDK_26.5.1_25F80`) —+ `kernel.release.vmapple` + `Sandbox.kext`/`AMFI.kext` (arm64e) carry full nlist+ symbol tables for the XNU/Sandbox functions stripped from the vphone600 cache.+ - Remaining 26.5 JB failures (8) still open: `task_conversion_eval` (inlined),+ `proc_security_policy` + `proc_pidinfo` (shared `_proc_info` switch refactored,+ `cmp #0x21` bound gone), `io_secure_bsd_root` (iOS-only, absent from KDK),+ `mac_mount`, `spawn_validate_persona` (iOS-only), `vm_map_protect`,+ `kcall10`/`sysent`.+- 2026-06-16 cloudOS 26.5 (23F77) JB retargeting — the 8 remaining P1 failures, all FIXED.+ Ground truth: IDA (idasql) on the decompressed `kernelcache.research.vphone600`,+ symbolicated via the macOS KDK oracle; XNU source cross-check. Validation:+ `make test_jb_patches` → every supported cloudOS kernel applies with **0** `[-]`+ failures (84 patches each). All anchors are version-independent+ (semantic/Capstone/call-graph), no pinned offsets/indices.+ - **JB-11 `proc_security_policy` + JB-12 `proc_pidinfo` (shared root cause).**+ The `sub wN,wM,#1 ; cmp wN,#0x21` switch anchor matched TWO sites on 26.5; the+ naive first-match grabbed the wrong one (`decodeWakeReason`, lower address).+ Replaced the whole `findProcInfoAnchor` with two source-backed finders in+ `KernelJBPatcherBase.swift`: `findProcSecurityPolicy()` locates the unique+ function that loads `PRIV_GLOBAL_PROC_INFO` (1002 = `0x3EA`, a stable+ `bsd/sys/priv.h` ABI value) into `w1` ahead of `priv_check_cred` →+ `_proc_security_policy` @ va `0x927E330` (stub entry `mov x0,#0; ret`);+ `findProcInfoInternal()` = its sole caller via `blIndex` → `_proc_info_internal`+ @ `0x927B38C` (proc_pidinfo is now inlined there). proc_pidinfo NOPs the unique+ `ldr x0,[x0,#0x18]; cbz x0; bl; cbz/cbnz wN; mov w0,#0x16(EINVAL); sub wN,wM,#1`+ guard pair → `0x927BDA8` / `0x927BDB0`.+ - **JB-08 `task_conversion_eval_internal`.** Inlined; recovered via the unique+ `"…pineapple on pizza…"` panic-string function (`task_get_special_port_from_user`).+ The 26.1 matcher failed only because the compare operands swapped+ (`cmp x0,x9` vs `cmp x9,x0`). Rewrote `collectTaskConversionCandidates` to accept+ the kernel_task-vs-{X0,X1} compare in EITHER operand order. Unique hit+ `cmp x0,x9 → cmp xzr,xzr` @ va `0x8D087A8`.+ - **JB-?? `io_secure_bsd_root`.** `AppleARMPE::callPlatformFunction` (refs both+ `"SecureRoot"`+`"SecureRootName"`). The match-bit compare-context moved >0xA0 back+ (sync code inserted), breaking the old lookback. Re-anchored on the unique+ `csel Wd,wzr,Wn,<cond>` whose `Wn` is built as `kIOReturnNotPrivileged`+ (`movk Wn,#0xE000,lsl#16` — IOKit error high half). `csel w22,wzr,w9,ne →+ mov w22,#0` @ va `0x7B30E10`. Dropped the pinned `[x19,#0x11A]` field offset.+ - **JB-?? `mac_mount`.** Wrapper still uniquely identified by the twin gates among+ `mount_common` callers (`__mac_mount` @ `0x8EC04F0`). Site 1 (`tbnz wFlags,#5 →+ mov w?,#1` preboot reject) unchanged → NOP @ `0x8EC06FC`. Site 2 folded on 26.5:+ `add x?,#0x70 ; ldrb w8,[x?,#1] ; tbz w8,#6` → `ldrb w8,[x16,#0x71] ; tbnz w8,#6`.+ Re-anchored `findStateGate` on the `ldrb wN,[x,#imm] ; tbz/tbnz wN,#6` pair (the+ `#6` role bit is the stable semantic) and clear the loaded reg → `mov x8,xzr`+ @ `0x8EC072C`.+ - **JB-?? `spawn_validate_persona`** @ `0x91C0D4C` (reached from the spawn+ entitlement wrapper, intact). The trailing `mov x?,#0 ; ldr x?,[x?,#0x490] ; casa`+ corroboration lowered differently on 26.5; re-anchored `matchPersonaHelper` on the+ dual sibling reject `ldr [base,#8];cbz / ldr [base,#0xc];cbz` (same base + same+ deny target + deny `mov w?,#1`), preceded by the `[_,#0x18]` sibling guard. NOP+ both cbz → `0x91C0DF8` / `0x91C0E00`.+ - **JB-25 `vm_map_protect`** @ `0x8DCA0A8`. The 26.1 `mov #6;bics;b.ne;tbnz#22;and+ #~X` block was recompiled; the per-entry apply path now narrows protection with a+ runtime W^X mask register before `pmap_protect_options`+ (`lsr wT,wFlags,#7 ; and w3,wT,wMask`, `mov wMask,#5`). Widening the mask `#5 → #7`+ makes the AND a pass-through so the requested protection (incl. the stripped bit)+ reaches the pmap — strictly permissive (`prot&7 ⊇ prot&5`). `mov w27,#5 → mov+ w27,#7` @ `0x8DCA30C`.+ - **JB-?? `kcall10` / sysent.** `findNosys()` matched an unrelated tiny+ `mov w0,#0x4e; ret` stub; the real `_nosys` is a large handler the sysent rows+ actually point to (112/558 entries). Rewrote `findSysentTable()` to find the table+ STRUCTURALLY (no `_nosys` dependency): the longest run of valid 24-byte `sysent`+ rows (chained auth-rebase `sy_call` into __TEXT_EXEC + sane+ `sy_return_type/sy_narg/sy_arg_bytes`). Base @ foff `0x7693B0` (558 rows);+ `sysent[439]` (`SYS_kas_info`) @ foff `0x76BCD8`; cave + 3 entry writes emit.diff --git a/sources/FirmwarePatcher/ARM64/ARM64Constants.swift b/sources/FirmwarePatcher/ARM64/ARM64Constants.swiftindex 55ea5d50..18fa009e 100644--- a/sources/FirmwarePatcher/ARM64/ARM64Constants.swift+++ b/sources/FirmwarePatcher/ARM64/ARM64Constants.swift@@ -70,9 +70,6 @@ public enum ARM64 {/// CMP XZR, XZR (SUBS XZR, XZR, XZR — always sets Z flag)public static let cmpXzrXzr = encodeU32(0xEB1F_03FF)- /// MOV X8, XZR (ORR X8, XZR, XZR)- public static let movX8Xzr = encodeU32(0xAA1F_03E8)-// MARK: Common Prologue/Epilogue Patterns (verified via keystone)/// STP X29, X30, [SP, #-0x10]! (push frame)@@ -139,8 +136,6 @@ public enum ARM64 {/// mrs x0, tpidr_el1static let mrs_x0_tpidr_el1: UInt32 = 0xD538_D080- /// ldr x1, [x0, #0x3e0]- static let ldr_x1_x0_0x3e0: UInt32 = 0xF941_F001// MARK: Syscallmask C22 Cave Instructions (verified via clang/as)diff --git a/sources/FirmwarePatcher/ARM64/ARM64Disassembler.swift b/sources/FirmwarePatcher/ARM64/ARM64Disassembler.swiftindex 9dccc2bd..dff70b86 100644--- a/sources/FirmwarePatcher/ARM64/ARM64Disassembler.swift+++ b/sources/FirmwarePatcher/ARM64/ARM64Disassembler.swift@@ -54,4 +54,21 @@ public final class ARM64Disassembler: Sendable {public func registerName(_ regID: UInt32) -> String? {cs.registerName(regID)}++ /// Canonical name of the instruction's first operand when it is a register+ /// (the write target for the moves/loads/branches the patchers match), else nil.+ ///+ /// Replaces the brittle `operandString.components(separatedBy: ",")` parsing that+ /// was duplicated across the JB patch files to recover a destination register's+ /// width ("w…" vs "x…") and identity.+ public func firstRegisterName(_ insn: Instruction) -> String? {+ guard let ops = insn.aarch64?.operands, let first = ops.first,+ first.type == AARCH64_OP_REG else { return nil }+ return cs.registerName(UInt32(first.reg.rawValue))+ }++ /// True iff the instruction's first (destination) operand is the named register.+ public func writesRegister(_ insn: Instruction, named regName: String) -> Bool {+ firstRegisterName(insn) == regName+ }}diff --git a/sources/FirmwarePatcher/ARM64/ARM64Encoder.swift b/sources/FirmwarePatcher/ARM64/ARM64Encoder.swiftindex 95924486..54191201 100644--- a/sources/FirmwarePatcher/ARM64/ARM64Encoder.swift+++ b/sources/FirmwarePatcher/ARM64/ARM64Encoder.swift@@ -83,6 +83,16 @@ public enum ARM64Encoder {return ARM64.encodeU32(insn)}+ /// Encode `MOV Xd, Xm` (the ORR Xd, XZR, Xm alias). With `rm == 31` (XZR) this+ /// is the canonical "zero a 64-bit register" (`mov xd, xzr`).+ ///+ /// Format: `[31] = 1 (sf)`, `[30:24] = 0101010`, `[23:22] = 00 (shift)`,+ /// `[20:16] = Rm`, `[15:10] = 0 (imm6)`, `[9:5] = 11111 (XZR)`, `[4:0] = Rd`+ public static func encodeMovX(rd: UInt32, rm: UInt32) -> Data {+ let insn: UInt32 = 0xAA00_03E0 | ((rm & 0x1F) << 16) | (rd & 0x1F)+ return ARM64.encodeU32(insn)+ }+// MARK: - Decode Helpers/// Decode a B or BL target address from an instruction at `pc`.diff --git a/sources/FirmwarePatcher/ARM64/ARM64Inst.swift b/sources/FirmwarePatcher/ARM64/ARM64Inst.swiftnew file mode 100644index 00000000..d573fdfb--- /dev/null+++ b/sources/FirmwarePatcher/ARM64/ARM64Inst.swift@@ -0,0 +1,68 @@+// ARM64Inst.swift — Raw (UInt32) instruction decoding for the fast pattern scanners.+//+// These operate directly on a 4-byte little-endian instruction word so the kernel+// patchers can scan megabytes of __TEXT_EXEC without paying Capstone's per-instruction+// cost. They are the SINGLE SOURCE OF TRUTH for the opcode masks that were previously+// re-spelled inline in each JB patch file (KernelJBPatchTaskConversion, VmProtect,+// ProcPidinfo, HookCredLabel) and in KernelJBPatcherBase.findProcSecurityPolicy.+//+// Every mask/value is documented against the ARM64 ISA encoding and round-trip+// verified against Capstone in ARM64InstTests. When a Capstone `Instruction` is+// already in hand, prefer its typed operands (see ARM64Disassembler); these raw+// predicates exist for the hot scan loops only.++import Foundation++public enum ARM64Inst {+ // MARK: - Register / immediate field accessors++ /// Rd / Rt — destination (or transfer) register, bits [4:0].+ public static func rd(_ i: UInt32) -> UInt32 { i & 0x1F }+ /// Rn — first source / base register, bits [9:5].+ public static func rn(_ i: UInt32) -> UInt32 { (i >> 5) & 0x1F }+ /// Rm — second source register, bits [20:16].+ public static func rm(_ i: UInt32) -> UInt32 { (i >> 16) & 0x1F }+ /// MOVZ/MOVN/MOVK 16-bit immediate, bits [20:5].+ public static func movImm16(_ i: UInt32) -> UInt32 { (i >> 5) & 0xFFFF }+ /// Unsigned 12-bit immediate of an ADD/SUB (immediate), bits [21:10].+ public static func addSubImm12(_ i: UInt32) -> UInt32 { (i >> 10) & 0xFFF }++ // MARK: - Opcode predicates (mask/value verified against the ISA)++ /// ADRP (any Rd): op=1, [28:24]=10000.+ public static func isADRP(_ i: UInt32) -> Bool { (i & 0x9F00_0000) == 0x9000_0000 }++ /// LDR Xt, [Xn, #imm] — 64-bit unsigned-offset load, [31:22]=1111100101.+ public static func isLDRImm64(_ i: UInt32) -> Bool { (i & 0xFFC0_0000) == 0xF940_0000 }++ /// CMP Xn, Xm ≡ SUBS XZR, Xn, Xm (64-bit, shift=0, imm6=0); Rn/Rm left free.+ public static func isCMPReg64(_ i: UInt32) -> Bool { (i & 0xFFE0_FC1F) == 0xEB00_001F }++ /// SUB Wd, Wn, #imm — 32-bit SUB (immediate), shift=0; [31:22]=0101000100.+ public static func isSUBImm32(_ i: UInt32) -> Bool { (i & 0xFFC0_0000) == 0x5100_0000 }++ /// MOVZ Wd, #imm16 (32-bit, no shift): [31:21]=01010010100.+ public static func isMOVZW(_ i: UInt32) -> Bool { (i & 0xFFE0_0000) == 0x5280_0000 }++ /// AND Wd, Wn, Wm — 32-bit shifted-register AND (imm6=0; shift type left free,+ /// harmless at shift amount 0): [31:24]=00001010, N=0.+ public static func isANDRegW(_ i: UInt32) -> Bool { (i & 0xFF20_FC00) == 0x0A00_0000 }++ /// LSR Wd, Wn, #7 ≡ UBFM Wd, Wn, #7, #31 (immr=7, imms=0x1F).+ public static func isLSRImm7W(_ i: UInt32) -> Bool { (i & 0xFFFF_FC00) == 0x5307_7C00 }++ /// BL — branch with link, [31:26]=100101.+ public static func isBL(_ i: UInt32) -> Bool { i >> 26 == 0b100101 }++ /// B.EQ — conditional branch, [31:24]=0x54, bit4=0, cond=0000.+ public static func isBEQ(_ i: UInt32) -> Bool { (i & 0xFF00_001F) == 0x5400_0000 }++ /// CBZ Wn (sf=0): top byte 0x34.+ public static func isCBZW(_ i: UInt32) -> Bool { (i & 0xFF00_0000) == 0x3400_0000 }+ /// CBNZ Wn (sf=0): top byte 0x35.+ public static func isCBNZW(_ i: UInt32) -> Bool { (i & 0xFF00_0000) == 0x3500_0000 }+ /// CBZ or CBNZ Wn.+ public static func isCBZorCBNZW(_ i: UInt32) -> Bool { isCBZW(i) || isCBNZW(i) }+ /// CBZ Xn (sf=1): top byte 0xB4.+ public static func isCBZX(_ i: UInt32) -> Bool { (i & 0xFF00_0000) == 0xB400_0000 }+}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchHookCredLabel.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchHookCredLabel.swiftindex 305a0463..ba0980ad 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchHookCredLabel.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchHookCredLabel.swift@@ -23,14 +23,17 @@ extension KernelJBPatcher {private static let hookCredLabelIndex = 18private static let c23CaveWords = 46 // Must match Python _C23_CAVE_WORDS- // Expected shape of vfs_context_current prologue (5 words).- // Python: _VFS_CONTEXT_CURRENT_SHAPE- private static let vfsContextCurrentShape: [UInt32] = [+ // Stable prologue prefix of vfs_context_current (4 words, version-independent).+ // The function reads current_thread() from tpidr_el1, then loads the+ // uthread/uu_context pointer via `ldr x1, [x0, #uthread_off]`. Only that final+ // immediate drifts across versions (0x3E0 on 26.1, 0x3E8 on macOS 26.5.1,+ // 0x3F0 on iOS 26.5), so we match the 4 fixed words exactly and require the+ // 5th to be *any* `ldr x1, [x0, #imm]` — never pinning the version-specific offset.+ private static let vfsContextCurrentPrefix: [UInt32] = [ARM64.pacibspU32, // pacibspARM64.stpFP_LR_pre, // stp x29, x30, [sp, #-0x10]!ARM64.movFP_SP, // mov x29, spARM64.mrs_x0_tpidr_el1, // mrs x0, tpidr_el1- ARM64.ldr_x1_x0_0x3e0, // ldr x1, [x0, #0x3e0]]// MARK: - Entry Point@@ -189,34 +192,49 @@ extension KernelJBPatcher {// MARK: - vfs_context_current Finder- /// Locate vfs_context_current by its unique 5-word prologue pattern.+ /// Locate vfs_context_current generically: prefer the symbol, else match the+ /// stable 4-word prologue prefix followed by *any* `ldr x1, [x0, #imm]` (the+ /// uthread offset is version-specific and deliberately left unpinned).private func findVfsContextCurrentByShape() -> Int {let cacheKey = "c23_vfs_context_current"if let cached = jbScanCache[cacheKey] { return cached }+ // Symbol fast-path (version-independent; this research kernel is stripped here, but free + future-proof).+ if let sym = resolveSymbol("_vfs_context_current"),+ codeRanges.contains(where: { sym >= $0.start && sym < $0.end })+ {+ log(" [+] vfs_context_current body at 0x\(String(format: "%X", sym)) (symbol)")+ jbScanCache[cacheKey] = sym+ return sym+ }+guard let (ks, ke) = kernTextRange else {jbScanCache[cacheKey] = -1return -1}- let pat = Self.vfsContextCurrentShape+ let pre = Self.vfsContextCurrentPrefixvar hits: [Int] = []var off = ks- while off + pat.count * 4 <= ke {+ while off + (pre.count + 1) * 4 <= ke {var match = true- for i in 0 ..< pat.count {- if buffer.readU32(at: off + i * 4) != pat[i] {+ for i in 0 ..< pre.count {+ if buffer.readU32(at: off + i * 4) != pre[i] {match = falsebreak}}- if match { hits.append(off) }+ // 5th word must load the uthread/uu_context ptr: `ldr x1, [x0, #imm]` (imm unpinned).+ let w5 = buffer.readU32(at: off + pre.count * 4)+ if match, ARM64Inst.isLDRImm64(w5), ARM64Inst.rn(w5) == 0, ARM64Inst.rd(w5) == 1 {+ hits.append(off)+ }off += 4}let result = hits.count == 1 ? hits[0] : -1if result >= 0 {- log(" [+] vfs_context_current body at 0x\(String(format: "%X", result)) (shape match)")+ log(" [+] vfs_context_current body at 0x\(String(format: "%X", result)) (prologue shape)")} else {log(" [-] vfs_context_current shape scan ambiguous (\(hits.count) hits)")}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchKcall10.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchKcall10.swiftindex dee82cb4..48392578 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchKcall10.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchKcall10.swift@@ -33,14 +33,8 @@ extension KernelJBPatcher {func patchKcall10() -> Bool {log("\n[JB] kcall10: ABI-correct sysent[439] cave")- // 1. Find _nosys.- guard let nosysOff = resolveSymbol("_nosys") ?? findNosys() else {- log(" [-] _nosys not found")- return false- }-- // 2. Find sysent table base.- guard let sysEntOff = findSysentTable(nosysOff: nosysOff) else {+ // 1. Find sysent table base (structural; this kernel is symbol-stripped).+ guard let sysEntOff = findSysentTable() else {log(" [-] sysent table not found")return false}@@ -117,60 +111,59 @@ extension KernelJBPatcher {// MARK: - Sysent Table Finder- /// Find the real sysent table base by locating a _nosys entry then scanning backward.- private func findSysentTable(nosysOff: Int) -> Int? {- var nosysEntry = -1- var segStart = -1+ /// Find the sysent table base structurally — the longest run of valid 24-byte+ /// `struct sysent` rows in a DATA segment. No symbol or `_nosys` dependency:+ /// each row's `sy_call` is an arm64e chained auth-rebase pointer into executable+ /// memory and the `(sy_return_type, sy_narg, sy_arg_bytes)` trailer is sane, a+ /// shape that no unrelated data run reproduces for hundreds of entries. The base+ /// is wherever the longest such run begins (entries are back-to-back from there).+ private func findSysentTable() -> Int? {+ // Executable file-offset ranges that sy_call / sy_arg_munge32 point into.+ let execSegNames: Set = ["__TEXT_EXEC", "__TEXT_BOOT_EXEC"]+ var execRanges: [(Int, Int)] = []+ for seg in segments where execSegNames.contains(seg.name) && seg.fileSize > 0 {+ execRanges.append((Int(seg.fileOffset), Int(seg.fileOffset + seg.fileSize)))+ }+ if execRanges.isEmpty { execRanges = codeRanges.map { ($0.start, $0.end) } }+ func inExec(_ fo: Int) -> Bool { fo > 0 && execRanges.contains { fo >= $0.0 && fo < $0.1 } }++ func validEntry(_ o: Int) -> Bool {+ guard o + Self.sysent_entry_size <= buffer.count else { return false }+ guard inExec(decodeChainedPtr(buffer.readU64(at: o))) else { return false }+ let rt = buffer.data.loadLE(UInt32.self, at: o + 16)+ let narg = buffer.data.loadLE(UInt16.self, at: o + 20)+ let argBytes = buffer.data.loadLE(UInt16.self, at: o + 22)+ return rt <= 9 && narg <= 12 && argBytes <= 96+ }- // Scan DATA segments for an entry whose decoded pointer == nosysOff- for seg in segments {- guard seg.name.contains("DATA") else { continue }+ var bestBase = -1+ var bestLen = 0+ for seg in segments where seg.name.contains("DATA") && seg.fileSize > 0 {let sStart = Int(seg.fileOffset)- let sEnd = sStart + Int(seg.fileSize)+ let sEnd = min(sStart + Int(seg.fileSize), buffer.count)var off = sStartwhile off + Self.sysent_entry_size <= sEnd {- let val = buffer.readU64(at: off)- let decoded = decodeChainedPtr(val)- if decoded == nosysOff {- // Confirm: next entry also decodes to a code-range address- let val2 = buffer.readU64(at: off + Self.sysent_entry_size)- let dec2 = decodeChainedPtr(val2)- let inCode = dec2 > 0 && codeRanges.contains { dec2 >= $0.start && dec2 < $0.end }- if inCode {- nosysEntry = off- segStart = sStart- break+ if validEntry(off) {+ let runStart = off+ var n = 0+ while off + Self.sysent_entry_size <= sEnd, validEntry(off) {+ n += 1+ off += Self.sysent_entry_size}+ if n > bestLen { bestLen = n; bestBase = runStart }+ } else {+ off += 8 // entries are 8-byte aligned}- off += 8}- if nosysEntry >= 0 { break }- }- guard nosysEntry >= 0 else { return nil }-- log(" [*] _nosys entry found at foff 0x\(String(format: "%X", nosysEntry)), scanning backward for table start")-- // Scan backward in sysent_entry_size steps to find table base- var base = nosysEntry- var entriesBack = 0- while base - Self.sysent_entry_size >= segStart {- guard entriesBack < Self.sysent_max_entries else { break }- let prev = base - Self.sysent_entry_size- let val = buffer.readU64(at: prev)- let decoded = decodeChainedPtr(val)- guard decoded > 0 else { break }- let inCode = codeRanges.contains { decoded >= $0.start && decoded < $0.end }- guard inCode else { break }- // Check narg and arg_bytes for sanity- let narg = buffer.data.loadLE(UInt16.self, at: prev + 20)- let argBytes = buffer.data.loadLE(UInt16.self, at: prev + 22)- guard narg <= 12, argBytes <= 96 else { break }- base = prev- entriesBack += 1}- log(" [+] sysent table base at foff 0x\(String(format: "%X", base)) (\(entriesBack) entries before first _nosys)")- return base+ // The real BSD syscall table has ~550 rows; require a decisively long run.+ guard bestLen >= 256, bestBase >= 0 else {+ log(" [-] no sysent-shaped table found (longest run \(bestLen))")+ return nil+ }+ log(" [+] sysent table base at foff 0x\(String(format: "%X", bestBase)) (\(bestLen) entries)")+ return bestBase}// MARK: - Munger Finderdiff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchMacMount.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchMacMount.swiftindex 78d2aac3..cf2233ce 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchMacMount.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchMacMount.swift@@ -38,7 +38,7 @@ extension KernelJBPatcher {var candidates: [Int: (Int, Int)] = [:] // caller → (flagGate, stateGate)var off = searchStartwhile off < searchEnd {- guard let blTarget = decodeBLat(off), blTarget == mountCommon else { off += 4; continue }+ guard let blTarget = jbDecodeBL(at: off), blTarget == mountCommon else { off += 4; continue }guard let caller = findFunctionStart(off), caller != mountCommon,candidates[caller] == nilelse { off += 4; continue }@@ -57,29 +57,37 @@ extension KernelJBPatcher {let (branchOff, movOff) = candidates.values.first!let va1 = fileOffsetToVA(branchOff)let va2 = fileOffsetToVA(movOff)++ // Clear the actual register the role-state byte was loaded into (W8 on every+ // build seen, but derived from the LDRB so the patch follows the encoding).+ guard let clearBytes = encodeMovXZeroForLdrbDest(at: movOff) else {+ log(" [-] mac_mount state gate: could not encode register clear")+ return false+ }+emit(branchOff, ARM64.nop,patchID: "kernelcache_jb.mac_mount.flag_gate",virtualAddress: va1,description: "NOP [___mac_mount upstream flag gate]")- emit(movOff, ARM64.movX8Xzr,+ emit(movOff, clearBytes,patchID: "kernelcache_jb.mac_mount.state_clear",virtualAddress: va2,- description: "mov x8,xzr [___mac_mount upstream state clear]")+ description: "mov x,xzr [___mac_mount upstream state clear]")return true}// MARK: - Private helpersprivate func matchUpstreamMountWrapper(start: Int, end: Int, mountCommon: Int) -> (Int, Int)? {- // Collect all BL-to-mount_common call sites- var callSites: [Int] = []+ // Require the wrapper to actually call mount_common.+ var callsMountCommon = falsefor off in stride(from: start, to: end, by: 4) {- if decodeBLat(off) == mountCommon { callSites.append(off) }+ if jbDecodeBL(at: off) == mountCommon { callsMountCommon = true; break }}- guard !callSites.isEmpty else { return nil }+ guard callsMountCommon else { return nil }guard let flagGate = findFlagGate(start: start, end: end) else { return nil }- guard let stateGate = findStateGate(start: start, end: end, callSites: callSites) else { return nil }+ guard let stateGate = findStateGate(start: start, end: end) else { return nil }return (flagGate, stateGate)}@@ -98,9 +106,7 @@ extension KernelJBPatcher {else { off += 4; continue }// Check register is a w-register- let regName = insn.operandString.components(separatedBy: ",").first?- .trimmingCharacters(in: CharacterSet.whitespaces) ?? ""- guard regName.hasPrefix("w") else { off += 4; continue }+ guard let regName = disasm.firstRegisterName(insn), regName.hasPrefix("w") else { off += 4; continue }let target = Int(ops[2].imm)guard target >= start, target < end else { off += 4; continue }@@ -113,9 +119,7 @@ extension KernelJBPatcher {tOps[0].type == AARCH64_OP_REG,tOps[1].type == AARCH64_OP_IMM, tOps[1].imm == 1else { off += 4; continue }- let tRegName = tInsn.operandString.components(separatedBy: ",").first?- .trimmingCharacters(in: CharacterSet.whitespaces) ?? ""- guard tRegName.hasPrefix("w") else { off += 4; continue }+ guard let tRegName = disasm.firstRegisterName(tInsn), tRegName.hasPrefix("w") else { off += 4; continue }hits.append(off)off += 4@@ -123,51 +127,37 @@ extension KernelJBPatcher {return hits.count == 1 ? hits[0] : nil}- /// Find `add x?, x?, #0x70 / ldrb w8, [x?, #1] / tbz w8, #6, <near call>`- private func findStateGate(start: Int, end: Int, callSites: [Int]) -> Int? {+ /// Find the unique role-state byte gate: `ldrb wN, [xBase, #imm] ; tbz/tbnz wN, #6, <target>`.+ ///+ /// On 26.1 this read as `add x8,x16,#0x70 ; ldrb w8,[x8,#1] ; tbz w8,#6,continue`;+ /// 26.5 folds the `add #0x70` into the load (`ldrb w8,[x16,#0x71]`) and inverts the+ /// branch sense (`tbnz w8,#6,reject`). Both expose the same role-state bit-6 test on+ /// the path into mount_common, so anchor on the load+`#6` bit-test pair (the `#6`+ /// role bit is the stable semantic), not the folded `add` or the branch direction.+ /// Returns the LDRB file offset (the byte we clear to neutralize the gate).+ private func findStateGate(start: Int, end: Int) -> Int? {var hits: [Int] = []var off = start- while off + 8 < end {- let insns = disasm.disassemble(in: buffer.data, at: off, count: 3)- guard insns.count >= 3 else { off += 4; continue }- let addInsn = insns[0], ldrInsn = insns[1], tbzInsn = insns[2]-- // add xD, xS, #0x70- guard addInsn.mnemonic == "add",- let addOps = addInsn.aarch64?.operands, addOps.count == 3,- addOps[0].type == AARCH64_OP_REG,- addOps[1].type == AARCH64_OP_REG,- addOps[2].type == AARCH64_OP_IMM, addOps[2].imm == 0x70- else { off += 4; continue }- let addDst = addOps[0].reg- let addDstName = addInsn.operandString.components(separatedBy: ",").first?- .trimmingCharacters(in: CharacterSet.whitespaces) ?? ""- guard addDstName.hasPrefix("x") else { off += 4; continue }+ while off + 8 <= end {+ let insns = disasm.disassemble(in: buffer.data, at: off, count: 2)+ guard insns.count >= 2 else { off += 4; continue }+ let ldrInsn = insns[0], brInsn = insns[1]- // ldrb w8, [xDst, #1]+ // ldrb wN, [xBase, #imm]guard ldrInsn.mnemonic == "ldrb",let ldrOps = ldrInsn.aarch64?.operands, ldrOps.count >= 2,ldrOps[0].type == AARCH64_OP_REG,- ldrOps[1].type == AARCH64_OP_MEM,- ldrOps[1].mem.base == addDst,- ldrOps[1].mem.disp == 1+ ldrOps[1].type == AARCH64_OP_MEMelse { off += 4; continue }let ldrDstReg = ldrOps[0].reg- let ldrDstName = ldrInsn.operandString.components(separatedBy: ",").first?- .trimmingCharacters(in: CharacterSet.whitespaces) ?? ""- guard ldrDstName.hasPrefix("w") else { off += 4; continue }-- // tbz wLdr, #6, <target near a call>- guard tbzInsn.mnemonic == "tbz",- let tbzOps = tbzInsn.aarch64?.operands, tbzOps.count == 3,- tbzOps[0].type == AARCH64_OP_REG, tbzOps[0].reg == ldrDstReg,- tbzOps[1].type == AARCH64_OP_IMM, tbzOps[1].imm == 6,- tbzOps[2].type == AARCH64_OP_IMM+ guard let ldrDstName = disasm.firstRegisterName(ldrInsn), ldrDstName.hasPrefix("w") else { off += 4; continue }++ // tbz/tbnz wN, #6, <target> (same register the byte was loaded into)+ guard brInsn.mnemonic == "tbz" || brInsn.mnemonic == "tbnz",+ let brOps = brInsn.aarch64?.operands, brOps.count == 3,+ brOps[0].type == AARCH64_OP_REG, brOps[0].reg == ldrDstReg,+ brOps[1].type == AARCH64_OP_IMM, brOps[1].imm == 6else { off += 4; continue }- let tbzTarget = Int(tbzOps[2].imm)- guard callSites.contains(where: { tbzTarget <= $0 && $0 <= tbzTarget + 0x80 }) else {- off += 4; continue- }hits.append(Int(ldrInsn.address))off += 4@@ -175,13 +165,16 @@ extension KernelJBPatcher {return hits.count == 1 ? hits[0] : nil}- /// Decode a BL instruction at `off`, returning the target file offset or nil.- private func decodeBLat(_ off: Int) -> Int? {- guard off + 4 <= buffer.count else { return nil }- let insn = buffer.readU32(at: off)- guard insn >> 26 == 0b100101 else { return nil }- let imm26 = insn & 0x03FF_FFFF- let signedImm = Int32(bitPattern: imm26 << 6) >> 6- return off + Int(signedImm) * 4+ /// Encode `mov x<rd>, xzr` where `rd` is the destination register of the LDRB at+ /// `off` (the role-state byte load). Zeroing the loaded register neutralizes the+ /// downstream bit-6 test. Returns nil if the instruction isn't a register LDRB.+ private func encodeMovXZeroForLdrbDest(at off: Int) -> Data? {+ let insns = disasm.disassemble(in: buffer.data, at: off, count: 1)+ guard let ins = insns.first, ins.mnemonic == "ldrb",+ let name = disasm.firstRegisterName(ins),+ name.hasPrefix("w"), let rd = UInt32(name.dropFirst()), rd < 31+ else { return nil }+ // `mov xd, xzr` zeroes the loaded register, neutralizing the bit-6 test.+ return ARM64Encoder.encodeMovX(rd: rd, rm: 31)}}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchProcPidinfo.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchProcPidinfo.swiftindex 1205478f..354a66ab 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchProcPidinfo.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchProcPidinfo.swift@@ -1,59 +1,75 @@-// KernelJBPatchProcPidinfo.swift — JB: NOP the two pid-0 guards in proc_pidinfo.+// KernelJBPatchProcPidinfo.swift — JB: NOP the two early pid-0 guards in proc_pidinfo.//// Historical note: derived from the legacy Python firmware patcher during the Swift migration.//-// Reveal: shared _proc_info switch-table anchor → function prologue (first 0x80 bytes) →-// precise 4-insn pattern: ldr x0,[x0,#0x18] ; cbz x0,fail ; bl ... ; cbz/cbnz wN,fail.-// Patch: NOP the two cbz/cbnz guards (instructions at +4 and +12 of the pattern).+// Reveal (version-independent, self-contained):+// proc_pidinfo is inlined into _proc_info_internal on current kernels. The pid==0+// region-flavor permission guards sit immediately ahead of the proc_pidinfo+// `flavor` switch and form a globally-unique shape in __TEXT_EXEC:+// ldr Xd, [Xn, #imm] ; load proc field+// cbz Xd, deny ; guard A (patched -> nop)+// bl <helper>+// cbz/cbnz wN, deny ; guard B (patched -> nop)+// movz w0, #0x16 ; EINVAL default (anchors the proc_pidinfo switch)+// sub wM, wK, #1 ; flavor switch zero-base+// The `mov w0,#0x16(EINVAL) ; sub _,_,#1` trailer makes the shape unique, so we+// scan kernel text directly rather than resolving the giant inlined function+// (its prologue is not recoverable by a single backward PACIBSP walk). NOPing the+// two guards lets kernel-task / restricted-pid flavors fall through to the switch.-import Capstoneimport Foundationextension KernelJBPatcher {- /// Bypass the two early pid-0/proc-null guards in proc_pidinfo.+ /// Bypass the two early pid-0 guards in the inlined proc_pidinfo path.@discardableResultfunc patchProcPidinfo() -> Bool {log("\n[JB] _proc_pidinfo: NOP pid-0 guard (2 sites)")- guard let (procInfoFunc, _) = findProcInfoAnchor() else {- log(" [-] _proc_info function not found")+ guard let (ks, ke) = kernTextRange else {+ log(" [-] kernel __TEXT_EXEC range not found")return false}- var firstGuard: Int?- var secondGuard: Int?-- let prologueEnd = min(procInfoFunc + 0x80, buffer.count)- var off = procInfoFunc- while off + 16 <= prologueEnd {+ var matches: [Int] = [] // file offset of i0 (the `ldr` opening the guard)+ var off = ks+ while off + 24 <= ke {defer { off += 4 }- let insns = disasm.disassemble(in: buffer.data, at: off, count: 4)- guard insns.count >= 4 else { continue }- let i0 = insns[0], i1 = insns[1], i2 = insns[2], i3 = insns[3]+ // Cheap distinctive prefilter: i4 == `movz w0, #0x16` (EINVAL default).+ let i4 = buffer.readU32(at: off + 16)+ guard ARM64Inst.isMOVZW(i4), ARM64Inst.rd(i4) == 0, ARM64Inst.movImm16(i4) == 0x16 else { continue }++ // i0: ldr Xd, [Xn, #imm] (64-bit unsigned-offset load; reg/imm unpinned)+ let i0 = buffer.readU32(at: off)+ guard ARM64Inst.isLDRImm64(i0) else { continue }+ let ldrRt = ARM64Inst.rd(i0)++ // i1: cbz Xd, deny (guard A — same register the load wrote)+ let i1 = buffer.readU32(at: off + 4)+ guard ARM64Inst.isCBZX(i1), ARM64Inst.rd(i1) == ldrRt else { continue }++ // i2: bl <helper>+ let i2 = buffer.readU32(at: off + 8)+ guard ARM64Inst.isBL(i2) else { continue }++ // i3: cbz/cbnz wN, deny (guard B, 32-bit register)+ let i3 = buffer.readU32(at: off + 12)+ guard ARM64Inst.isCBZorCBNZW(i3) else { continue }- // Pattern: ldr x0, [x0, #0x18]- guard i0.mnemonic == "ldr",- i0.operandString.hasPrefix("x0, [x0, #0x18]") else { continue }- // cbz x0, <label>- guard i1.mnemonic == "cbz",- i1.operandString.hasPrefix("x0, ") else { continue }- // bl <target>- guard i2.mnemonic == "bl" else { continue }- // cbz/cbnz wN, <label>- guard i3.mnemonic == "cbz" || i3.mnemonic == "cbnz",- i3.operandString.hasPrefix("w") else { continue }+ // i5: sub wM, wK, #1 (the flavor-switch zero-base right after EINVAL)+ let i5 = buffer.readU32(at: off + 20)+ guard ARM64Inst.isSUBImm32(i5), ARM64Inst.addSubImm12(i5) == 1 else { continue }- firstGuard = off + 4 // cbz x0- secondGuard = off + 12 // cbz/cbnz wN- break+ matches.append(off)}- guard let guardA = firstGuard, let guardB = secondGuard else {- log(" [-] precise proc_pidinfo guard pair not found")+ guard matches.count == 1 else {+ log(" [-] precise proc_pidinfo guard pair not found (\(matches.count) candidates)")return false}+ let guardA = matches[0] + 4 // cbz Xd+ let guardB = matches[0] + 12 // cbz/cbnz wNemit(guardA, ARM64.nop,patchID: "jb.proc_pidinfo.nop_guard_a",virtualAddress: fileOffsetToVA(guardA),diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchProcSecurity.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchProcSecurity.swiftindex 53a5bfc9..27f0eb9c 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchProcSecurity.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchProcSecurity.swift@@ -2,9 +2,13 @@//// Historical note: derived from the legacy Python firmware patcher during the Swift migration.//-// Reveal: find _proc_info by `sub wN,wM,#1 ; cmp wN,#0x21` switch pattern,-// then identify _proc_security_policy among BL targets called 2+ times,-// with function size in [0x40, 0x200].+// Reveal (version-independent): _proc_security_policy is the shared proc-info+// authorization gate (bsd/kern/proc_info.c). It is located by its unique+// reference to PRIV_GLOBAL_PROC_INFO (1002 = 0x3EA, bsd/sys/priv.h) — the+// privilege id handed to priv_check_cred(my_cred, PRIV_GLOBAL_PROC_INFO, 0).+// See KernelJBPatcherBase.findProcSecurityPolicy(). Stubbing its entry to+// `mov x0,#0; ret` forces the gate to allow, so proc-info/proc-control paths+// used by jailbreak userland never hit cross-identity authorization denials.import Foundation@@ -14,73 +18,19 @@ extension KernelJBPatcher {func patchProcSecurityPolicy() -> Bool {log("\n[JB] _proc_security_policy: mov x0,#0; ret")- guard let (procInfoFunc, switchOff) = findProcInfoAnchor() else {- log(" [-] _proc_info function not found")+ guard let policy = findProcSecurityPolicy() else {+ log(" [-] _proc_security_policy not identified (PRIV_GLOBAL_PROC_INFO anchor)")return false}- let ksStart = codeRanges.first?.start ?? 0- let ksEnd = codeRanges.first?.end ?? buffer.count-- let procInfoEnd = findFuncEnd(procInfoFunc, maxSize: 0x4000)- log(" [+] _proc_info at 0x\(String(format: "%X", procInfoFunc)) (size 0x\(String(format: "%X", procInfoEnd - procInfoFunc)))")-- // Count BL targets after switch dispatch within _proc_info.- var blTargetCounts: [Int: Int] = [:]- for off in stride(from: switchOff, to: procInfoEnd, by: 4) {- guard off + 4 <= buffer.count else { break }- let insn = buffer.readU32(at: off)- // BL: [31:26] = 0b100101- guard insn >> 26 == 0b100101 else { continue }- let imm26 = insn & 0x03FF_FFFF- let signedImm = Int32(bitPattern: imm26 << 6) >> 6- let target = off + Int(signedImm) * 4- guard target >= ksStart, target < ksEnd else { continue }- blTargetCounts[target, default: 0] += 1- }-- guard !blTargetCounts.isEmpty else {- log(" [-] no BL targets found in _proc_info switch cases")- return false- }-- // Sort by count descending, then by address ascending (to match Python- // Counter.most_common() insertion-order tie-breaking from the forward scan).- let sorted = blTargetCounts.sorted {- if $0.value != $1.value { return $0.value > $1.value }- return $0.key < $1.key- }-- for (foff, count) in sorted {- guard count >= 2 else { break }-- let funcEnd = findFuncEnd(foff, maxSize: 0x400)- let funcSize = funcEnd - foff-- log(" [*] candidate 0x\(String(format: "%X", foff)): \(count) calls, size 0x\(String(format: "%X", funcSize))")-- if funcSize > 0x200 {- log(" [-] skipped (too large, likely utility)")- continue- }- if funcSize < 0x40 {- log(" [-] skipped (too small)")- continue- }-- log(" [+] identified _proc_security_policy at 0x\(String(format: "%X", foff)) (\(count) calls, size 0x\(String(format: "%X", funcSize)))")- emit(foff, ARM64.movX0_0,- patchID: "jb.proc_security_policy.mov_x0_0",- virtualAddress: fileOffsetToVA(foff),- description: "mov x0,#0 [_proc_security_policy]")- emit(foff + 4, ARM64.ret,- patchID: "jb.proc_security_policy.ret",- virtualAddress: fileOffsetToVA(foff + 4),- description: "ret [_proc_security_policy]")- return true- }-- log(" [-] _proc_security_policy not identified among BL targets")- return false+ emit(policy, ARM64.movX0_0,+ patchID: "jb.proc_security_policy.mov_x0_0",+ virtualAddress: fileOffsetToVA(policy),+ description: "mov x0,#0 [_proc_security_policy]")+ emit(policy + 4, ARM64.ret,+ patchID: "jb.proc_security_policy.ret",+ virtualAddress: fileOffsetToVA(policy + 4),+ description: "ret [_proc_security_policy]")+ return true}}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchSecureRoot.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchSecureRoot.swiftindex 87a06aa7..05139fd0 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchSecureRoot.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchSecureRoot.swift@@ -1,20 +1,24 @@-// KernelJBPatchSecureRoot.swift — JB: force SecureRootName policy to return success.+// KernelJBPatchSecureRoot.swift — JB: force the SecureRootName policy to return success.//// Historical note: derived from the legacy Python firmware patcher during the Swift migration.//-// Reveal: find functions referencing both "SecureRootName" and "SecureRoot" strings →-// locate the final CSEL that selects between wzr (success) and kIOReturnNotPrivileged →-// verify context: TST+LDRB at [x19,#0x11A] before, STRB+CSET+CMP w0,#0 further back.-// Patch: replace CSEL with MOV <dest>, #0.+// Reveal (version-independent):+// IOSecureBSDRoot() asks the platform expert to evaluate "SecureRootName"; on+// kIOReturnNotPrivileged it tears the root device down via mdevremoveall()+// (iokit/bsddev/IOKitBSDInit.cpp + bsd/dev/memdev.c). The decision is made in+// AppleARMPE::callPlatformFunction — the single function that references BOTH the+// "SecureRoot" and "SecureRootName" strings. Its deny/allow return is a unique+// CSEL of the form `csel Wd, wzr, Wn, <cond>` where Wn is built as+// kIOReturnNotPrivileged (0xE00002C1). kIOReturn codes carry the IOKit error+// system in their high half, so Wn is recognised by its `movk Wn, #0xE000, lsl#16`+// — a stable ABI signature, not a pinned field offset or struct layout.+// Patch: rewrite that CSEL to `mov Wd, #0` so the policy always returns success.import Capstoneimport Foundationextension KernelJBPatcher {- /// Offset of the SecureRoot match flag inside the dispatch struct.- private static let secureRootMatchOffset: Int = 0x11A-- /// Force SecureRootName policy return to success in _IOSecureBSDRoot.+ /// Force SecureRootName policy return to success in AppleARMPE::callPlatformFunction.@discardableResultfunc patchIoSecureBsdRoot() -> Bool {log("\n[JB] _IOSecureBSDRoot: force SecureRootName success")@@ -25,24 +29,33 @@ extension KernelJBPatcher {return false}+ // Collect the deny-return CSEL across every candidate function and require a+ // single global match — never patch the first-of-several.+ var sites: [(Int, String)] = []for funcStart in candidates.sorted() {let funcEnd = findFuncEnd(funcStart, maxSize: 0x1200)- guard let (off, destReg) = findSecureRootReturnSite(funcStart: funcStart, funcEnd: funcEnd) else {- continue+ if let site = findSecureRootReturnSite(funcStart: funcStart, funcEnd: funcEnd) {+ sites.append(site)}+ }- // Encode mov <destReg>, #0 (always a 32-bit W register)- guard let patchBytes = encodeMovWReg0(destReg) else { continue }-- emit(off, patchBytes,- patchID: "jb.io_secure_bsd_root.zero_return",- virtualAddress: fileOffsetToVA(off),- description: "mov \(destReg), #0 [_IOSecureBSDRoot SecureRootName allow]")- return true+ guard sites.count == 1 else {+ log(" [-] SecureRootName deny-return site not uniquely found (\(sites.count) candidates)")+ return false}- log(" [-] SecureRootName deny-return site not found")- return false+ let (off, destReg) = sites[0]+ guard destReg.hasPrefix("w"), let rd = UInt32(destReg.dropFirst()),+ let patchBytes = ARM64Encoder.encodeMovzW(rd: rd, imm16: 0)+ else {+ log(" [-] could not encode mov \(destReg), #0")+ return false+ }+ emit(off, patchBytes,+ patchID: "jb.io_secure_bsd_root.zero_return",+ virtualAddress: fileOffsetToVA(off),+ description: "mov \(destReg), #0 [_IOSecureBSDRoot SecureRootName allow]")+ return true}// MARK: - Private helpers@@ -87,9 +100,11 @@ extension KernelJBPatcher {return result}- /// Scan [funcStart, funcEnd) for the CSEL that is the SecureRootName deny/allow selector.+ /// Scan [funcStart, funcEnd) for the unique CSEL that selects between success+ /// (wzr) and kIOReturnNotPrivileged — the SecureRootName deny/allow selector./// Returns (offset, destRegName) on success.private func findSecureRootReturnSite(funcStart: Int, funcEnd: Int) -> (Int, String)? {+ var hits: [(Int, String)] = []for off in stride(from: funcStart, to: funcEnd - 4, by: 4) {let insns = disasm.disassemble(in: buffer.data, at: off, count: 1)guard let insn = insns.first, insn.mnemonic == "csel" else { continue }@@ -98,7 +113,6 @@ extension KernelJBPatcher {let destOp = detail.operands[0]let zeroSrcOp = detail.operands[1]let errSrcOp = detail.operands[2]-guard destOp.type == AARCH64_OP_REG,zeroSrcOp.type == AARCH64_OP_REG,errSrcOp.type == AARCH64_OP_REG else { continue }@@ -107,111 +121,35 @@ extension KernelJBPatcher {let zeroName = disasm.registerName(UInt32(zeroSrcOp.reg.rawValue)) ?? ""let errName = disasm.registerName(UInt32(errSrcOp.reg.rawValue)) ?? ""- // Must be: csel wX, wzr, wErr, ne+ // Allow value must be 0 (wzr); deny value is the error register.guard destName.hasPrefix("w") else { continue }guard zeroName == "wzr" || zeroName == "xzr" else { continue }- // Last operand string should contain "ne"- let opStr = insn.operandString.replacingOccurrences(of: " ", with: "")- guard opStr.hasSuffix(",ne") || opStr.hasSuffix("ne") else { continue }-- // Verify return context: TST + LDRB [x19, #0x11A] walking back.- guard hasSecureRootReturnContext(off: off, funcStart: funcStart, errRegName: errName) else { continue }- // Verify compare context: STRB + CSET + CMP w0,#0 walking back.- guard hasSecureRootCompareContext(off: off, funcStart: funcStart) else { continue }-- return (off, destName)- }- return nil- }-- /// Walk backward from `off` to verify the flag-load and error-build context.- private func hasSecureRootReturnContext(off: Int, funcStart: Int, errRegName: String) -> Bool {- var sawFlagLoad = false- var sawFlagTest = false- var sawErrBuild = false- let lookbackStart = max(funcStart, off - 0x40)-- var probe = off - 4- while probe >= lookbackStart {- defer { probe -= 4 }- let insns = disasm.disassemble(in: buffer.data, at: probe, count: 1)- guard let ins = insns.first else { continue }- let ops = ins.operandString.replacingOccurrences(of: " ", with: "")-- if !sawFlagTest, ins.mnemonic == "tst", ops.hasSuffix("#1") {- sawFlagTest = true- continue- }-- if sawFlagTest, !sawFlagLoad, ins.mnemonic == "ldrb",- ops.contains("[x19,#0x\(String(format: "%x", Self.secureRootMatchOffset))]")- {- sawFlagLoad = true- continue- }+ // Confirm the deny value is a kIOReturn code: its register is built with+ // the IOKit error-system high half (movk Wn, #0xE000, lsl #16).+ guard hasIOKitErrorBuild(before: off, funcStart: funcStart, regName: errName) else { continue }- if ins.mnemonic == "mov" || ins.mnemonic == "movk" || ins.mnemonic == "sub",- writesRegister(ins, regName: errRegName)- {- sawErrBuild = true- }+ hits.append((off, destName))}- return sawFlagLoad && sawFlagTest && sawErrBuild+ return hits.count == 1 ? hits[0] : nil}- /// Walk backward from `off` to verify the match-store + cset,eq + cmp w0,#0 context.- private func hasSecureRootCompareContext(off: Int, funcStart: Int) -> Bool {- var sawMatchStore = false- var sawCsetEq = false- var sawCmpW0Zero = false- let lookbackStart = max(funcStart, off - 0xA0)-+ /// Walk backward from `off` looking for `movk <regName>, #0xE000, lsl #16` — the+ /// high half of an IOKit return code (kIOReturn* == 0xE000xxxx).+ private func hasIOKitErrorBuild(before off: Int, funcStart: Int, regName: String) -> Bool {+ let lookbackStart = max(funcStart, off - 0x40)var probe = off - 4while probe >= lookbackStart {defer { probe -= 4 }let insns = disasm.disassemble(in: buffer.data, at: probe, count: 1)- guard let ins = insns.first else { continue }- let ops = ins.operandString.replacingOccurrences(of: " ", with: "")-- if !sawMatchStore, ins.mnemonic == "strb",- ops.contains("[x19,#0x\(String(format: "%x", Self.secureRootMatchOffset))]")- {- sawMatchStore = true- continue- }-- if sawMatchStore, !sawCsetEq, ins.mnemonic == "cset", ops.hasSuffix(",eq") {- sawCsetEq = true- continue- }-- if sawMatchStore, sawCsetEq, !sawCmpW0Zero, ins.mnemonic == "cmp",- ops.hasPrefix("w0,#0")- {- sawCmpW0Zero = true- break- }+ guard let ins = insns.first, ins.mnemonic == "movk" else { continue }+ guard disasm.writesRegister(ins, named: regName) else { continue }+ let ops = ins.operandString.replacingOccurrences(of: " ", with: "").lowercased()+ // movk Wn, #0xe000, lsl #16 → "wN,#0xe000,lsl#16"+ if ops.contains("#0xe000,lsl#16") { return true }}-- return sawMatchStore && sawCsetEq && sawCmpW0Zero- }-- /// Return true if the instruction writes to `regName` as its first operand.- private func writesRegister(_ ins: Instruction, regName: String) -> Bool {- guard let detail = ins.aarch64, !detail.operands.isEmpty else { return false }- let first = detail.operands[0]- guard first.type == AARCH64_OP_REG else { return false }- return (disasm.registerName(UInt32(first.reg.rawValue)) ?? "") == regName+ return false}- /// Encode `mov <wReg>, #0` (MOVZ Wd, #0). E.g. "w22" → MOVZ W22, #0.- private func encodeMovWReg0(_ regName: String) -> Data? {- guard regName.hasPrefix("w"), let numStr = regName.dropFirst().isEmpty ? nil : String(regName.dropFirst()),- let rd = UInt32(numStr), rd < 32 else { return nil }- // MOVZ Wd, #0 = 0x52800000 | rd- let insn: UInt32 = 0x5280_0000 | rd- return ARM64.encodeU32(insn)- }}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchSpawnPersona.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchSpawnPersona.swiftindex 33edf594..871a2d0b 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchSpawnPersona.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchSpawnPersona.swift@@ -55,7 +55,7 @@ extension KernelJBPatcher {var seen = Set<Int>()for off in stride(from: anchorStart, to: anchorEnd, by: 4) {- guard let blTarget = decodeBL(at: off), !seen.contains(blTarget) else { continue }+ guard let blTarget = jbDecodeBL(at: off), !seen.contains(blTarget) else { continue }guard jbIsInCodeRange(blTarget) else { continue }seen.insert(blTarget)let callee_end = findFuncEnd(blTarget, maxSize: 0x400)@@ -72,56 +72,57 @@ extension KernelJBPatcher {return nil}- /// Match the upstream shape:- /// ldr wA, [x0, #8]- /// cbz wA, deny- /// ldr wB, [x0, #0xc]- /// cbz wB, deny- /// mov x?, #0- /// ldr x?, [x?, #0x490]+ /// Match the upstream sibling nil-field reject shape:+ /// ldr w?, [r, #0x18] ; preceding sibling-field guard+ /// cbz w?, continue+ /// ldr wA, [base, #8]+ /// cbz wA, deny ; patched (cbz1)+ /// ldr wB, [base, #0xc] ; same base+ /// cbz wB, deny ; patched (cbz2) — same deny target as cbz1+ /// where the deny block opens with `mov w?, #1` (reject return).+ ///+ /// The 26.1 doc also keyed off a trailing `mov x?,#0 ; ldr x?,[x?,#0x490] ; casa`+ /// sequence; that lowered differently on 26.5, so the anchor is the dual-cbz pair+ /// plus the `[_,#0x18]` sibling guard — the stable, source-backed reject shape.private func matchPersonaHelper(start: Int, end: Int) -> (Int, Int)? {var hits: [(Int, Int)] = []- var off = start- while off + 0x14 < end {- let insns = disasm.disassemble(in: buffer.data, at: off, count: 6)- guard insns.count >= 6 else { off += 4; continue }- let i0 = insns[0], i1 = insns[1], i2 = insns[2]- let i3 = insns[3], i4 = insns[4], i5 = insns[5]-- // ldr wA, [base, #8]- guard isLdrMem(i0, disp: 8) else { off += 4; continue }- guard let i0ops = i0.aarch64?.operands, i0ops.count >= 2 else { off += 4; continue }+ var off = start + 8+ while off + 0x10 <= end {+ defer { off += 4 }+ let insns = disasm.disassemble(in: buffer.data, at: off, count: 4)+ guard insns.count >= 4 else { continue }+ let i0 = insns[0], i1 = insns[1], i2 = insns[2], i3 = insns[3]++ // ldr wA, [base, #8] ; cbz wA, deny+ guard isLdrMem(i0, disp: 8) else { continue }+ guard let i0ops = i0.aarch64?.operands, i0ops.count >= 2 else { continue }let loadedReg0 = i0ops[0].reglet baseReg = i0ops[1].mem.base+ guard isCbzWSameReg(i1, reg: loadedReg0) else { continue }- // cbz wA, deny- guard isCbzWSameReg(i1, reg: loadedReg0) else { off += 4; continue }-- // ldr wB, [base, #0xc]- guard isLdrMemSameBase(i2, base: baseReg, disp: 0xC) else { off += 4; continue }- guard let i2ops = i2.aarch64?.operands, i2ops.count >= 1 else { off += 4; continue }+ // ldr wB, [base, #0xc] ; cbz wB, deny (same base)+ guard isLdrMemSameBase(i2, base: baseReg, disp: 0xC) else { continue }+ guard let i2ops = i2.aarch64?.operands, i2ops.count >= 1 else { continue }let loadedReg2 = i2ops[0].reg+ guard isCbzWSameReg(i3, reg: loadedReg2) else { continue }- // cbz wB, deny (same deny target)- guard isCbzWSameReg(i3, reg: loadedReg2) else { off += 4; continue }+ // Both cbz must branch to the SAME deny target.guard let i1ops = i1.aarch64?.operands, i1ops.count == 2,let i3ops = i3.aarch64?.operands, i3ops.count == 2,i1ops[1].type == AARCH64_OP_IMM, i3ops[1].type == AARCH64_OP_IMM,i1ops[1].imm == i3ops[1].imm- else { off += 4; continue }+ else { continue }let denyTarget = Int(i1ops[1].imm)- // Deny block must look like `mov w0, #1`- guard looksLikeErrnoReturn(target: denyTarget, value: 1) else { off += 4; continue }-- // mov x?, #0- guard isMovXImmZero(i4) else { off += 4; continue }+ // Deny block must open with `mov w?, #1` (reject return).+ guard looksLikeErrnoReturn(target: denyTarget, value: 1) else { continue }- // ldr x?, [x?, #0x490]- guard isLdrMem(i5, disp: 0x490) else { off += 4; continue }+ // Preceding sibling-field guard: `ldr w?, [r, #0x18] ; cbz w?, continue`.+ let pre = disasm.disassemble(in: buffer.data, at: off - 8, count: 2)+ guard pre.count == 2, isLdrMem(pre[0], disp: 0x18),+ pre[1].mnemonic == "cbz" else { continue }hits.append((Int(i1.address), Int(i3.address)))- off += 4}return hits.count == 1 ? hits[0] : nil@@ -152,20 +153,7 @@ extension KernelJBPatcher {ops[1].type == AARCH64_OP_IMMelse { return false }// Must be a w-register- let name = insn.operandString.components(separatedBy: ",").first?- .trimmingCharacters(in: CharacterSet.whitespaces) ?? ""- return name.hasPrefix("w")- }-- private func isMovXImmZero(_ insn: Instruction) -> Bool {- guard insn.mnemonic == "mov",- let ops = insn.aarch64?.operands, ops.count == 2,- ops[0].type == AARCH64_OP_REG,- ops[1].type == AARCH64_OP_IMM, ops[1].imm == 0- else { return false }- let name = insn.operandString.components(separatedBy: ",").first?- .trimmingCharacters(in: CharacterSet.whitespaces) ?? ""- return name.hasPrefix("x")+ return disasm.firstRegisterName(insn)?.hasPrefix("w") ?? false}private func looksLikeErrnoReturn(target: Int, value: Int64) -> Bool {@@ -181,20 +169,6 @@ extension KernelJBPatcher {ops[0].type == AARCH64_OP_REG,ops[1].type == AARCH64_OP_IMM, ops[1].imm == immelse { return false }- let name = insn.operandString.components(separatedBy: ",").first?- .trimmingCharacters(in: CharacterSet.whitespaces) ?? ""- return name.hasPrefix("w")- }-- // MARK: - Instruction decode helpers-- /// Decode a BL instruction at `off`, returning the target file offset or nil.- private func decodeBL(at off: Int) -> Int? {- guard off + 4 <= buffer.count else { return nil }- let insn = buffer.readU32(at: off)- guard insn >> 26 == 0b100101 else { return nil }- let imm26 = insn & 0x03FF_FFFF- let signedImm = Int32(bitPattern: imm26 << 6) >> 6- return off + Int(signedImm) * 4+ return disasm.firstRegisterName(insn)?.hasPrefix("w") ?? false}}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchTaskConversion.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchTaskConversion.swiftindex 0b8a4f42..8b4a597f 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchTaskConversion.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchTaskConversion.swift@@ -3,18 +3,23 @@// Historical note: derived from the legacy Python firmware patcher during the Swift migration.//// Strategy (fast raw scanner):-// Locate the unique guard site in _task_conversion_eval_internal that performs:-// ADRP Xn, <global> ; [off - 8] — loads global task-conversion table-// LDR Xn, [Xn] ; [off - 4] — dereferences it-// CMP Xn, X0 ; [off + 0] — compare task pointer against X0-// B.EQ <skip1> ; [off + 4]-// CMP Xn, X1 ; [off + 8] — compare against X1-// B.EQ <skip2> ; [off + 12]-// MOV X19, X0 ; [off + 16]-// MOV X0, X1 ; [off + 20]-// BL <callee> ; [off + 24]-// CBZ/CBNZ W0, ... ; [off + 28]-// Patch: replace CMP Xn, X0 with CMP XZR, XZR so the equality check always passes.+// Locate the unique guard site in task_conversion_eval_internal+// (osfmk/kern/ipc_tt.c) that resolves caller/victim against kernel_task:+// ADRP Xk, <kernel_task> ; [off - 8] load the kernel_task global+// LDR Xk, [Xk, #imm] ; [off - 4] deref it+// CMP X0, Xk / Xk, X0 ; [off + 0] caller == kernel_task (patch site)+// B.EQ <allow> ; [off + 4]+// CMP X1, Xk / Xk, X1 ; [off + 8] victim == kernel_task+// B.EQ <skip> ; [off + 12]+// MOV X19, X0 ; [off + 16] save caller+// MOV X0, X1 ; [off + 20] victim ->+// BL task_get_platform_binary+// CBZ/CBNZ W0, ... ; [off + 28]+// Patch: replace the caller==kernel_task CMP with CMP XZR, XZR so the equality+// always holds and the routine returns KERN_SUCCESS (allow). The compare-operand+// order drifts across versions (26.1: `cmp Xk, X0`; 26.5: `cmp X0, Xk`), so both+// orderings are accepted — only the kernel_task register and the X0/X1 roles are+// pinned, never the operand position.import Foundation@@ -48,115 +53,54 @@ extension KernelJBPatcher {// MARK: - Private scannerprivate func collectTaskConversionCandidates(start: Int, end: Int) -> [Int] {- // Derived masks — no hardcoded opcode bytes:- // CMP Xn, X0 = SUBS XZR, Xn, X0 → bits [31:21]=1110_1011_000, [20:16]=X0=00000,- // [15:10]=000000, [9:5]=Rn, [4:0]=11111(XZR)- // Mask covers the fixed opcode and X0 operand; leaves Rn free.- let cmpXnX0Mask: UInt32 = 0xFFFF_FC1F- let cmpXnX0Val: UInt32 = 0xEB00_001F // cmp Xn, X0 — Rn wildcard-- // CMP Xn, X1 = SUBS XZR, Xn, X1 → Rm=X1=00001- let cmpXnX1Mask: UInt32 = 0xFFFF_FC1F- let cmpXnX1Val: UInt32 = 0xEB01_001F // cmp Xn, X1 — Rn wildcard-- // B.EQ #offset → bits[31:24]=0101_0100, bit[4]=0, bits[3:0]=0000 (EQ cond)- let beqMask: UInt32 = 0xFF00_001F- let beqVal: UInt32 = 0x5400_0000 // b.eq with any imm19-- // LDR Xd, [Xn] (unsigned offset, size=3):- // bits [31:22] fixed = 0xF94 (size=11, V=0, opc=01, class=01);- // bits [21:10] = imm12, bits [9:5] = Rn, bits [4:0] = Rt — all variable.- let ldrXUnsignedMask: UInt32 = 0xFFC0_0000 // leaves imm12, Rn, Rt free- let ldrXUnsignedVal: UInt32 = 0xF940_0000-- // ADRP: bit[31]=1, bits[28:24]=10000- let adrpMask: UInt32 = 0x9F00_0000- let adrpVal: UInt32 = 0x9000_0000-- // MOV X19, X0 = ORR X19, XZR, X0- let movX19X0: UInt32 = 0xAA00_03F3- // MOV X0, X1 = ORR X0, XZR, X1- let movX0X1: UInt32 = 0xAA01_03E0-- // BL mask- let blMask: UInt32 = 0xFC00_0000- let blVal: UInt32 = 0x9400_0000+ // True iff `cmp` compares register `reg` against the kernel_task register `k`+ // (in either operand position — the order drifts across versions).+ func comparesRegAgainst(_ cmp: UInt32, reg: UInt32, k: UInt32) -> Bool {+ (ARM64Inst.rn(cmp) == reg && ARM64Inst.rm(cmp) == k) ||+ (ARM64Inst.rn(cmp) == k && ARM64Inst.rm(cmp) == reg)+ }- // CBZ/CBNZ W (32-bit): bits[31]=0, bits[30:25]=011010 / 011011- let cbzWMask: UInt32 = 0x7F00_0000- let cbzWVal: UInt32 = 0x3400_0000 // CBZ W- let cbnzWVal: UInt32 = 0x3500_0000 // CBNZ W+ let movX19X0: UInt32 = 0xAA00_03F3 // mov x19, x0+ let movX0X1: UInt32 = 0xAA01_03E0 // mov x0, x1var out: [Int] = []-var off = start + 8- while off < end - 28 {+ while off + 32 <= end {defer { off += 4 }- // [off]: CMP Xn, X0- let i0 = buffer.readU32(at: off)- guard (i0 & cmpXnX0Mask) == cmpXnX0Val else { continue }- let cmpRn = (i0 >> 5) & 0x1F // the register being compared-- // [off - 4]: LDR Xn, [Xn] (load into cmpRn from cmpRn)- let prev = buffer.readU32(at: off - 4)- guard (prev & ldrXUnsignedMask) == ldrXUnsignedVal else { continue }- let pRt = prev & 0x1F- let pRn = (prev >> 5) & 0x1F- guard pRt == cmpRn, pRn == cmpRn else { continue }-- // [off + 4]: B.EQ- let i1 = buffer.readU32(at: off + 4)- guard (i1 & beqMask) == beqVal else { continue }-- // [off + 8]: CMP Xn, X1 (same register)- let i2 = buffer.readU32(at: off + 8)- guard (i2 & cmpXnX1Mask) == cmpXnX1Val else { continue }- guard ((i2 >> 5) & 0x1F) == cmpRn else { continue }-- // [off + 12]: B.EQ- let i3 = buffer.readU32(at: off + 12)- guard (i3 & beqMask) == beqVal else { continue }-- // Context safety: ADRP at [off - 8] for same register- let p2 = buffer.readU32(at: off - 8)- guard (p2 & adrpMask) == adrpVal else { continue }- guard (p2 & 0x1F) == cmpRn else { continue }-- // [off + 16]: MOV X19, X0+ // [off-8] ADRP Xk ; [off-4] LDR Xk, [Xk, #imm] — kernel_task load.+ let adrp = buffer.readU32(at: off - 8)+ let ldr = buffer.readU32(at: off - 4)+ guard ARM64Inst.isADRP(adrp), ARM64Inst.isLDRImm64(ldr) else { continue }+ let k = ARM64Inst.rd(ldr)+ guard ARM64Inst.rn(ldr) == k, ARM64Inst.rd(adrp) == k else { continue }++ // [off] caller(X0) == kernel_task(Xk) — the patch site.+ let c0 = buffer.readU32(at: off)+ guard ARM64Inst.isCMPReg64(c0), comparesRegAgainst(c0, reg: 0, k: k) else { continue }+ // [off+4] B.EQ allow+ let b0 = buffer.readU32(at: off + 4)+ guard ARM64Inst.isBEQ(b0) else { continue }+ // [off+8] victim(X1) == kernel_task(Xk)+ let c1 = buffer.readU32(at: off + 8)+ guard ARM64Inst.isCMPReg64(c1), comparesRegAgainst(c1, reg: 1, k: k) else { continue }+ // [off+12] B.EQ+ let b1 = buffer.readU32(at: off + 12)+ guard ARM64Inst.isBEQ(b1) else { continue }+ // [off+16] MOV X19,X0 ; [off+20] MOV X0,X1 ; [off+24] BL ; [off+28] CBZ/CBNZ W0guard buffer.readU32(at: off + 16) == movX19X0 else { continue }-- // [off + 20]: MOV X0, X1guard buffer.readU32(at: off + 20) == movX0X1 else { continue }+ guard ARM64Inst.isBL(buffer.readU32(at: off + 24)) else { continue }+ let cb = buffer.readU32(at: off + 28)+ guard ARM64Inst.isCBZorCBNZW(cb), ARM64Inst.rd(cb) == 0 else { continue } // result reg must be W0- // [off + 24]: BL- let i6 = buffer.readU32(at: off + 24)- guard (i6 & blMask) == blVal else { continue }-- // [off + 28]: CBZ or CBNZ W0- let i7 = buffer.readU32(at: off + 28)- let op7 = i7 & cbzWMask- guard op7 == cbzWVal || op7 == cbnzWVal else { continue }- guard (i7 & 0x1F) == 0 else { continue } // must be W0-- // B.EQ targets must be forward and nearby (within same function)- guard let t1 = decodeBEQTarget(insn: i1, at: off + 4) else { continue }- guard let t2 = decodeBEQTarget(insn: i3, at: off + 12) else { continue }- guard t1 > off, t2 > off else { continue }- guard (t1 - off) <= 0x200, (t2 - off) <= 0x200 else { continue }+ // Both B.EQ branches must be forward and nearby (same function body).+ guard let t0 = jbDecodeBranchTarget(at: off + 4)?.target,+ let t1 = jbDecodeBranchTarget(at: off + 12)?.target else { continue }+ guard t0 > off, t1 > off, (t0 - off) <= 0x200, (t1 - off) <= 0x200 else { continue }out.append(off)}return out}-- /// Decode a B.cond target offset from an instruction at `pc`.- private func decodeBEQTarget(insn: UInt32, at pc: Int) -> Int? {- // B.cond: bits[31:24] = 0x54, bits[23:5] = imm19, bits[4] = 0, bits[3:0] = cond- guard (insn & 0xFF00_001E) == 0x5400_0000 else { return nil }- let imm19 = (insn >> 5) & 0x7FFFF- // Sign-extend 19 bits- let signedImm = Int32(bitPattern: imm19 << 13) >> 13- return pc + Int(signedImm) * 4- }}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchTaskForPid.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchTaskForPid.swiftindex 6394dfe7..36ff2579 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchTaskForPid.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchTaskForPid.swift@@ -94,9 +94,7 @@ extension KernelJBPatcher {cbzRetOps[1].imm == failTargetelse { return nil }// x0- let retRegName = cbzRet.operandString.components(separatedBy: ",").first?- .trimmingCharacters(in: CharacterSet.whitespaces) ?? ""- guard retRegName == "x0" else { return nil }+ guard disasm.firstRegisterName(cbzRet) == "x0" else { return nil }// Look backward for ldr wPid, [x?, #8] and ldr xTaskPtr, [x?, #0x10]let scanStart = max(funcStart, off - 0x18)@@ -125,9 +123,7 @@ extension KernelJBPatcher {ops[0].type == AARCH64_OP_REG,ops[1].type == AARCH64_OP_IMM, ops[1].imm == 0else { return false }- let name = insn.operandString.components(separatedBy: ",").first?- .trimmingCharacters(in: CharacterSet.whitespaces) ?? ""- return name == dstName+ return disasm.firstRegisterName(insn) == dstName}private func isWLdrFromXImm(_ insn: Instruction, imm: Int32) -> Bool {@@ -137,9 +133,7 @@ extension KernelJBPatcher {ops[1].type == AARCH64_OP_MEM,ops[1].mem.disp == immelse { return false }- let dstName = insn.operandString.components(separatedBy: ",").first?- .trimmingCharacters(in: CharacterSet.whitespaces) ?? ""- return dstName.hasPrefix("w")+ return disasm.firstRegisterName(insn)?.hasPrefix("w") ?? false}private func isXLdrFromXImm(_ insn: Instruction, imm: Int32) -> Bool {@@ -149,8 +143,6 @@ extension KernelJBPatcher {ops[1].type == AARCH64_OP_MEM,ops[1].mem.disp == immelse { return false }- let dstName = insn.operandString.components(separatedBy: ",").first?- .trimmingCharacters(in: CharacterSet.whitespaces) ?? ""- return dstName.hasPrefix("x")+ return disasm.firstRegisterName(insn)?.hasPrefix("x") ?? false}}diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchVmFault.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchVmFault.swiftindex 3dab2103..261c48f9 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchVmFault.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchVmFault.swift@@ -82,8 +82,7 @@ extension KernelJBPatcher {ops[1].mem.base != AARCH64_REG_INVALID,ops[1].mem.disp == 0x28{- let dstName = insn.operandString.components(separatedBy: ",").first?.trimmingCharacters(in: .whitespaces) ?? ""- if dstName.hasPrefix("w") {+ if disasm.firstRegisterName(insn)?.hasPrefix("w") ?? false {flagRegs.insert(ops[0].reg.rawValue)}}@@ -115,8 +114,7 @@ extension KernelJBPatcher {movOps[0].type == AARCH64_OP_REG,movOps[1].type == AARCH64_OP_IMM, movOps[1].imm == 0else { off += 4; continue }- let movDstName = movInsn.operandString.components(separatedBy: ",").first?.trimmingCharacters(in: .whitespaces) ?? ""- guard movDstName.hasPrefix("w") else { off += 4; continue }+ guard disasm.firstRegisterName(movInsn)?.hasPrefix("w") ?? false else { off += 4; continue }// Check unconditional Blet bInsns = disasm.disassemble(in: buffer.data, at: off + 8, count: 1)diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchVmProtect.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchVmProtect.swiftindex b490ce62..5c3f4c00 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchVmProtect.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchVmProtect.swift@@ -1,29 +1,37 @@-// KernelJBPatchVmProtect.swift — JB kernel patch: VM map protect bypass+// KernelJBPatchVmProtect.swift — JB kernel patch: VM map protect W^X bypass//// Historical note: derived from the legacy Python firmware patcher during the Swift migration.+//+// Goal: let vm_map_protect apply write+execute (RWX). The downgrade that blocks this+// is compiled two different ways across releases, so we try both shapes and apply+// whichever uniquely matches (same patch either way):+//+// Shape A (26.1 / 26.3): an explicit skip-branch around the strip block —+// mov wMask, #6+// bics wzr, wMask, wProt ; (~prot & 6) == 0 ? (both bits requested)+// b.ne skip ; <- rewrite to unconditional `b skip`+// tbnz wEntryFlags, #22, skip+// ... and wProt, wProt, #~bit ; the downgrade we want to skip+//+// Shape B (26.5): the per-entry apply path narrows the protection with a runtime+// W^X mask register before pmap_protect_options —+// lsr wT, wEntryFlags, #7 ; extract the 3-bit protection field+// and w3, wT, wMask ; wMask = #5 (the W^X strip)+// ...+// mov wMask, #5 ; <- widen to #7 so the AND is a pass-through+// Widening the mask keeps ALL requested permission bits; it is strictly more+// permissive (`prot & 7` ⊇ `prot & 5`), so no working mapping regresses.import Capstoneimport Foundationextension KernelJBPatcher {- /// Skip the vm_map_protect write-downgrade gate.- ///- /// Source-backed anchor: recover the function from the in-kernel- /// `vm_map_protect(` panic string, then find the unique local block matching:- ///- /// mov wMask, #6- /// bics wzr, wMask, wProt- /// b.ne skip- /// tbnz wEntryFlags, #22, skip- /// ...- /// and wProt, wProt, #~VM_PROT_WRITE- ///- /// Rewriting `b.ne` to unconditional `b` always skips the downgrade block.+ /// Bypass the vm_map_protect W^X downgrade so write+execute protections are honored.@discardableResultfunc patchVmMapProtect() -> Bool {- log("\n[JB] _vm_map_protect: skip write-downgrade gate")+ log("\n[JB] _vm_map_protect: bypass W^X downgrade")- // Find function via "vm_map_protect(" string+ // Recover the function from the in-kernel "vm_map_protect(" panic string.guard let strOff = buffer.findString("vm_map_protect(") else {log(" [-] kernel-text 'vm_map_protect(' anchor not found")return false@@ -35,29 +43,40 @@ extension KernelJBPatcher {}let funcEnd = findFuncEnd(funcStart, maxSize: 0x2000)- guard let gate = findWriteDowngradeGate(start: funcStart, end: funcEnd) else {- log(" [-] vm_map_protect write-downgrade gate not found")- return false+ // Shape A: explicit skip branch (26.1 / 26.3). Rewrite `b.ne skip` -> `b skip`.+ if let (brOff, target) = findWriteDowngradeGate(start: funcStart, end: funcEnd) {+ guard let bBytes = encodeB(from: brOff, to: target) else {+ log(" [-] branch rewrite out of range")+ return false+ }+ let delta = target - brOff+ emit(brOff, bBytes,+ patchID: "kernelcache_jb.vm_map_protect",+ virtualAddress: fileOffsetToVA(brOff),+ description: "b #0x\(String(format: "%X", delta)) [_vm_map_protect skip W^X downgrade]")+ return true}- let (brOff, target) = gate- guard let bBytes = encodeB(from: brOff, to: target) else {- log(" [-] branch rewrite out of range")- return false+ // Shape B: runtime W^X mask register (26.5). Widen the mask constant #5 -> #7.+ if let (movOff, maskReg) = findWxMaskMov(start: funcStart, end: funcEnd) {+ guard let maskBytes = ARM64Encoder.encodeMovzW(rd: maskReg, imm16: 7) else {+ log(" [-] could not encode widened W^X mask")+ return false+ }+ emit(movOff, maskBytes,+ patchID: "kernelcache_jb.vm_map_protect",+ virtualAddress: fileOffsetToVA(movOff),+ description: "mov w\(maskReg),#7 [_vm_map_protect widen W^X mask, allow W+X]")+ return true}- let va = fileOffsetToVA(brOff)- let delta = target - brOff- emit(brOff, bBytes,- patchID: "kernelcache_jb.vm_map_protect",- virtualAddress: va,- description: "b #0x\(String(format: "%X", delta)) [_vm_map_protect]")- return true+ log(" [-] vm_map_protect write-downgrade gate not found")+ return false}- // MARK: - Private helpers+ // MARK: - Shape A (26.1 / 26.3): explicit skip-branch gate- /// Find the `b.ne` instruction address and its target in the write-downgrade block.+ /// Find the `b.ne` that skips the write-downgrade block, and its target.private func findWriteDowngradeGate(start: Int, end: Int) -> (brOff: Int, target: Int)? {let wZrReg: aarch64_reg = AARCH64_REG_WZR@@ -101,22 +120,20 @@ extension KernelJBPatcher {tbnzOps[2].type == AARCH64_OP_IMM, Int(tbnzOps[2].imm) == skipTargetelse { off += 4; continue }- // Verify there's an `and wProt, wProt, #~2` between tbnz+4 and target+ // Verify there's an `and wProt, wProt, #~bit` between tbnz+4 and target.let searchStart = Int(tbnzInsn.address) + 4let searchEnd = min(skipTarget, end)guard findWriteClearBetween(start: searchStart, end: searchEnd, protReg: protReg) != nilelse { off += 4; continue }- // bneInsn.address is a virtual-like address (== file offset here)- let bneFileOff = Int(bneInsn.address)- hits.append((bneFileOff, skipTarget))+ hits.append((Int(bneInsn.address), skipTarget))off += 4}return hits.count == 1 ? hits[0] : nil}- /// Scan [start, end) for `and wProt, wProt, #imm` where imm clears bit 1 (VM_PROT_WRITE).+ /// Scan [start, end) for `and wProt, wProt, #imm` that strips one of the low protection bits.private func findWriteClearBetween(start: Int, end: Int, protReg: aarch64_reg) -> Int? {var off = startwhile off < end {@@ -129,7 +146,7 @@ extension KernelJBPatcher {ops[2].type == AARCH64_OP_IMM{let imm = UInt32(bitPattern: Int32(truncatingIfNeeded: ops[2].imm)) & 0xFFFF_FFFF- // Clears bit 1 (VM_PROT_WRITE=2), keeps bit 0 (VM_PROT_READ=1)+ // Keeps two of the three low protection bits, clears the middle one.if (imm & 0x7) == 0x3 {return off}@@ -138,4 +155,42 @@ extension KernelJBPatcher {}return nil}++ // MARK: - Shape B (26.5): runtime W^X mask register++ /// Locate the `mov wMask, #5` that defines the W^X protection mask, identified by+ /// the unique `lsr wT, _, #7 ; and wD, wT, wMask` pair that narrows the protection+ /// before pmap_protect_options. Returns (movFileOffset, maskRegIndex).+ private func findWxMaskMov(start: Int, end: Int) -> (Int, UInt32)? {+ var candidates: [(Int, UInt32)] = []+ var off = start+ while off + 8 <= end {+ defer { off += 4 }+ let lsr = buffer.readU32(at: off)+ guard ARM64Inst.isLSRImm7W(lsr) else { continue }+ let wt = ARM64Inst.rd(lsr)+ let and = buffer.readU32(at: off + 4)+ guard ARM64Inst.isANDRegW(and), ARM64Inst.rn(and) == wt else { continue }+ let maskReg = ARM64Inst.rm(and)++ // Find the (unique) `movz wMask, #5` writer in this function.+ var movOff = -1+ var p = start+ while p + 4 <= end {+ let insn = buffer.readU32(at: p)+ if ARM64Inst.isMOVZW(insn), ARM64Inst.rd(insn) == maskReg, ARM64Inst.movImm16(insn) == 5 {+ if movOff >= 0 { movOff = -2; break } // ambiguous writer+ movOff = p+ }+ p += 4+ }+ // Dedup by writer offset: several `lsr;and` pairs may reference the same+ // `mov wMask,#5` writer — that is still a single mask, not an ambiguous one.+ if movOff >= 0, !candidates.contains(where: { $0.0 == movOff }) {+ candidates.append((movOff, maskReg))+ }+ }++ return candidates.count == 1 ? candidates[0] : nil+ }}diff --git a/sources/FirmwarePatcher/Kernel/KernelJBPatcherBase.swift b/sources/FirmwarePatcher/Kernel/KernelJBPatcherBase.swiftindex 045cb440..ccfff118 100644--- a/sources/FirmwarePatcher/Kernel/KernelJBPatcherBase.swift+++ b/sources/FirmwarePatcher/Kernel/KernelJBPatcherBase.swift@@ -16,9 +16,8 @@ public class KernelJBPatcherBase: KernelPatcherBase {/// Symbol name → file offset map, built from nlist64 entries.var symbols: [String: Int] = [:]- /// Cached proc_info anchor (func_start, switch_off).- private var procInfoAnchor: (Int, Int)?- private var procInfoAnchorScanned = false+ /// Cached _proc_security_policy file offset (-1 = scanned, not found).+ private var procSecurityPolicyOff: Int?/// JB scan cache for expensive searches.var jbScanCache: [String: Int] = [:]@@ -260,91 +259,45 @@ public class KernelJBPatcherBase: KernelPatcherBase {return (funcStart, funcEnd, refs)}- /// Find `_nosys`: a tiny function returning ENOSYS (errno 78 = 0x4e).- ///- /// Pattern A: `mov w0, #0x4e ; ret`- /// Pattern B: `pacibsp ; mov w0, #0x4e ; ret` (ARM64e wrapper)+ // MARK: - proc_info Family Anchors (B6/B7)++ /// Find `_proc_security_policy` by its unique reference to `PRIV_GLOBAL_PROC_INFO`.///- /// Reads from `buffer.original` (Python: `_rd32(self.raw, off)`).- /// Mirrors Python `_find_nosys()`.- func findNosys() -> Int? {- let movW0_4e: UInt32 = 0x5280_09C0 // MOVZ W0, #0x4e- let retVal: UInt32 = ARM64.retU32- let pacibsp: UInt32 = ARM64.pacibspU32+ /// Source: `bsd/kern/proc_info.c` — `proc_security_policy()` is the shared+ /// proc-info authorization gate. Its only distinctive constant is the privilege+ /// id passed to `priv_check_cred(my_cred, PRIV_GLOBAL_PROC_INFO, 0)`.+ /// `PRIV_GLOBAL_PROC_INFO` is `1002` (`0x3EA`) in `bsd/sys/priv.h`, a stable ABI+ /// value, so the function is located generically as the unique routine that+ /// loads `0x3EA` into `w1` immediately ahead of a `BL` (the priv-check call) —+ /// no offsets, no preassembled bytes, no version-pinned switch literal.+ func findProcSecurityPolicy() -> Int? {+ if let cached = procSecurityPolicyOff { return cached >= 0 ? cached : nil }let raw = buffer.original++ var funcs = Set<Int>()for (start, end) in codeRanges {var off = start- while off + 8 <= end {- let v0 = raw.loadLE(UInt32.self, at: off)- let v1 = raw.loadLE(UInt32.self, at: off + 4)- if v0 == movW0_4e, v1 == retVal { return off }- if v0 == pacibsp, v1 == movW0_4e, off + 12 <= end {- let v2 = raw.loadLE(UInt32.self, at: off + 8)- if v2 == retVal { return off }- }- off += 4+ let limit = min(end, raw.count) - 4+ while off <= limit {+ defer { off += 4 }+ let insn = raw.loadLE(UInt32.self, at: off)+ // movz w1, #0x3EA (Rd=w1, imm16=PRIV_GLOBAL_PROC_INFO)+ guard ARM64Inst.isMOVZW(insn), ARM64Inst.rd(insn) == 1,+ ARM64Inst.movImm16(insn) == 0x3EA else { continue }+ // Require a BL within the next two instructions (priv_check_cred call).+ let blA = off + 4 <= limit ? raw.loadLE(UInt32.self, at: off + 4) : 0+ let blB = off + 8 <= limit ? raw.loadLE(UInt32.self, at: off + 8) : 0+ guard ARM64Inst.isBL(blA) || ARM64Inst.isBL(blB) else { continue }+ if let fn = findFunctionStart(off) { funcs.insert(fn) }}}- return nil- }-- // MARK: - Proc Info Anchor-- /// Find the `_proc_info` switch anchor as (func_start, switch_off). Cached.- ///- /// Shared by B6/B7 patches. Expensive on stripped kernels so result is memoised.- ///- /// Anchor pattern:- /// `sub wN, wM, #1` — zero-base the command index- /// `cmp wN, #0x21` — bounds-check against the switch table size- ///- /// Search order: direct symbol → full kern_text scan.- /// Mirrors Python `_find_proc_info_anchor()`.- func findProcInfoAnchor() -> (Int, Int)? {- if procInfoAnchorScanned { return procInfoAnchor }- procInfoAnchorScanned = true-- // Fast path: symbol table hit- if let funcOff = resolveSymbol("_proc_info") {- let searchEnd = min(funcOff + 0x800, buffer.count)- let switchOff = scanProcInfoSwitchPattern(start: funcOff, end: searchEnd)- procInfoAnchor = (funcOff, switchOff ?? funcOff)- return procInfoAnchor- }- // Slow path: scan __TEXT_EXEC- guard let (ks, ke) = kernTextRange else { return nil }- guard let switchOff = scanProcInfoSwitchPattern(start: ks, end: ke) else { return nil }- let funcStart = findFunctionStart(switchOff) ?? switchOff- procInfoAnchor = (funcStart, switchOff)- return procInfoAnchor- }-- /// Raw scanner for `sub wN, wM, #1 ; cmp wN, #0x21`. Result is memoised in `jbScanCache`.- private func scanProcInfoSwitchPattern(start: Int, end: Int) -> Int? {- let cacheKey = "proc_info_switch_\(start)_\(end)"- if let cached = jbScanCache[cacheKey] { return cached >= 0 ? cached : nil }- let raw = buffer.original- let limit = min(end - 8, raw.count - 8)- var off = max(start, 0)- while off <= limit {- let i0 = raw.loadLE(UInt32.self, at: off)- // SUB (immediate) 32-bit: [31:24]==0x51, sh[22]==0, imm12[21:10]==1- guard (i0 & 0xFF00_0000) == 0x5100_0000 else { off += 4; continue }- guard (i0 >> 22) & 1 == 0 else { off += 4; continue }- guard (i0 >> 10) & 0xFFF == 1 else { off += 4; continue }- let subRd = i0 & 0x1F- let i1 = raw.loadLE(UInt32.self, at: off + 4)- // CMP wN, #imm ≡ SUBS WZR, wN, #imm: [31:24]==0x71, rd==31, sh==0, imm12==0x21- guard (i1 & 0xFF00_001F) == 0x7100_001F else { off += 4; continue }- guard (i1 >> 22) & 1 == 0 else { off += 4; continue }- guard (i1 >> 10) & 0xFFF == 0x21 else { off += 4; continue }- guard (i1 >> 5) & 0x1F == subRd else { off += 4; continue }- jbScanCache[cacheKey] = off- return off+ let result = funcs.count == 1 ? funcs.first! : -1+ procSecurityPolicyOff = result+ if verbose, result >= 0 {+ print(" [+] _proc_security_policy at 0x\(String(format: "%X", result)) (PRIV_GLOBAL_PROC_INFO anchor)")}- jbScanCache[cacheKey] = -1- return nil+ return result >= 0 ? result : nil}// MARK: - Convenience Propertiesdiff --git a/sources/vphone-cli/VPhoneCLI.swift b/sources/vphone-cli/VPhoneCLI.swiftindex 362be521..c24c04af 100644--- a/sources/vphone-cli/VPhoneCLI.swift+++ b/sources/vphone-cli/VPhoneCLI.swift@@ -199,6 +199,12 @@ struct PatchComponentCLI: ParsableCommand {enum ComponentOption: String, CaseIterable, ExpressibleByArgument {case txmcase kernelBase = "kernel-base"+ // TESTING/DIAGNOSTICS ONLY — not part of any production flow.+ // Production JB patching runs through `patch-firmware --variant jb`; this+ // standalone option exists so `tests/test_jb_kernel_patches.sh` can run the+ // JB kernel layer over a single kernelcache and dump records via --records-out.+ // (txm / kernel-base, by contrast, are also used by scripts/ramdisk_build.py.)+ case kernelJB = "kernel-jb"}static let configuration = CommandConfiguration(@@ -226,10 +232,17 @@ struct PatchComponentCLI: ParsableCommand {@Flag(name: .customLong("quiet"), help: "Suppress per-patch progress output.")var quiet: Bool = false+ @Option(+ name: .customLong("records-out"),+ help: "Optional path to write emitted PatchRecord JSON (for fast-loop validation)."+ )+ var recordsOut: String?+mutating func run() throws {let payload = try IM4PHandler.load(contentsOf: input).payloadlet count: Intlet patchedData: Data+ var records: [PatchRecord] = []switch component {case .txm:@@ -241,12 +254,33 @@ struct PatchComponentCLI: ParsableCommand {let patcher = KernelPatcher(data: payload, verbose: !quiet)count = try patcher.apply()patchedData = patcher.buffer.data+ records = patcher.patches++ case .kernelJB:+ // Mirrors the pipeline's jb kernel layer. In FirmwarePipeline each kernel+ // patcher runs on the *original* payload independently, so running+ // KernelJBPatcher standalone faithfully reproduces JB hook behavior+ // without the base patcher or the rest of the boot chain.+ let patcher = KernelJBPatcher(data: payload, verbose: !quiet)+ count = try patcher.apply()+ patchedData = patcher.buffer.data+ records = patcher.patches}let outputDir = output.deletingLastPathComponent()try FileManager.default.createDirectory(at: outputDir, withIntermediateDirectories: true)try patchedData.write(to: output)+ if let recordsOut {+ let url = URL(fileURLWithPath: recordsOut)+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]+ try encoder.encode(records).write(to: url)+ if !quiet {+ print("[patch-component] wrote \(records.count) patch records to \(url.path)")+ }+ }+if !quiet {print("[patch-component] applied \(count) patches for \(component.rawValue)")print("[patch-component] wrote patched payload to \(output.path)")diff --git a/tests/FirmwarePatcherTests/FirmwarePatcherTests.swift b/tests/FirmwarePatcherTests/FirmwarePatcherTests.swiftindex 90b6cee9..c68f98b2 100644--- a/tests/FirmwarePatcherTests/FirmwarePatcherTests.swift+++ b/tests/FirmwarePatcherTests/FirmwarePatcherTests.swift@@ -141,6 +141,124 @@ struct ARM64EncoderTests {let insn = try disasm.disassembleOne(#require(data), at: 0)#expect(insn?.mnemonic == "add")}++ @Test func encodeMovXFromZR() {+ // `mov x8, xzr` — the mac_mount state-clear encoding (ORR X8, XZR, XZR).+ let bytes = ARM64Encoder.encodeMovX(rd: 8, rm: 31)+ let insn = disasm.disassembleOne(bytes, at: 0)+ #expect(insn != nil)+ #expect(insn?.mnemonic == "mov" || insn?.mnemonic == "orr")+ // Byte-for-byte equal to the legacy hand-encoded constant 0xAA1F03E8.+ #expect(bytes == withUnsafeBytes(of: UInt32(0xAA1F_03E8).littleEndian) { Data($0) })+ }++ @Test func encodeMovXIsRegisterMove() {+ // `mov x0, x20` matches the project's preverified ARM64.movX0X20 constant.+ #expect(ARM64Encoder.encodeMovX(rd: 0, rm: 20) == ARM64.movX0X20)+ }+}++/// Round-trip coverage for the shared raw-instruction predicates in `ARM64Inst`,+/// the single source of truth for the JB pattern scanners. Each predicate is+/// cross-checked against Capstone's decode of the same word so the masks cannot+/// silently drift from the ISA.+struct ARM64InstTests {+ let disasm = ARM64Disassembler()++ private func mnemonic(of word: UInt32) -> String? {+ let data = withUnsafeBytes(of: word.littleEndian) { Data($0) }+ return disasm.disassembleOne(data, at: 0)?.mnemonic+ }++ @Test func fieldAccessors() {+ // ldr x1, [x0, #0x3e0] → Rt=1, Rn=0+ let ldr: UInt32 = 0xF941_F001+ #expect(ARM64Inst.rd(ldr) == 1)+ #expect(ARM64Inst.rn(ldr) == 0)+ // cmp x0, x1 (SUBS XZR, X0, X1) → Rn=0, Rm=1+ let cmp: UInt32 = 0xEB01_001F+ #expect(ARM64Inst.rn(cmp) == 0)+ #expect(ARM64Inst.rm(cmp) == 1)+ // movz w0, #0x16 → imm16=0x16+ let movz: UInt32 = 0x5280_02C0+ #expect(ARM64Inst.movImm16(movz) == 0x16)+ // sub w2, w3, #1 → imm12=1+ let sub: UInt32 = 0x5100_0462+ #expect(ARM64Inst.addSubImm12(sub) == 1)+ }++ @Test func adrp() {+ let w: UInt32 = 0x9000_0000 // adrp x0, ...+ #expect(mnemonic(of: w) == "adrp")+ #expect(ARM64Inst.isADRP(w))+ #expect(!ARM64Inst.isADRP(0xF941_F001)) // an ldr is not adrp+ }++ @Test func ldrImm64() {+ let w: UInt32 = 0xF941_F001 // ldr x1, [x0, #0x3e0]+ #expect(mnemonic(of: w) == "ldr")+ #expect(ARM64Inst.isLDRImm64(w))+ #expect(!ARM64Inst.isLDRImm64(0x9000_0000))+ }++ @Test func cmpReg64() {+ let w: UInt32 = 0xEB01_001F // cmp x0, x1+ #expect(mnemonic(of: w) == "cmp")+ #expect(ARM64Inst.isCMPReg64(w))+ // operand order is irrelevant: cmp x1, x0+ #expect(ARM64Inst.isCMPReg64(0xEB00_003F))+ #expect(!ARM64Inst.isCMPReg64(0x5100_0462)) // sub-imm is not cmp-reg+ }++ @Test func subImm32() {+ let w: UInt32 = 0x5100_0462 // sub w2, w3, #1+ #expect(mnemonic(of: w) == "sub")+ #expect(ARM64Inst.isSUBImm32(w))+ #expect(!ARM64Inst.isSUBImm32(0x5280_02C0)) // movz is not sub+ }++ @Test func movzW() {+ let w: UInt32 = 0x5280_02C0 // movz w0, #0x16+ let m = mnemonic(of: w)+ #expect(m == "mov" || m == "movz")+ #expect(ARM64Inst.isMOVZW(w))+ #expect(ARM64Inst.rd(w) == 0)+ #expect(!ARM64Inst.isMOVZW(0xF941_F001))+ }++ @Test func andRegW() {+ let w: UInt32 = 0x0A05_0083 // and w3, w4, w5+ #expect(mnemonic(of: w) == "and")+ #expect(ARM64Inst.isANDRegW(w))+ #expect(!ARM64Inst.isANDRegW(0x5280_02C0))+ }++ @Test func lsrImm7W() {+ let w: UInt32 = 0x5307_7C20 // lsr w0, w1, #7+ let m = mnemonic(of: w)+ #expect(m == "lsr" || m == "ubfm")+ #expect(ARM64Inst.isLSRImm7W(w))+ #expect(!ARM64Inst.isLSRImm7W(0x0A05_0083))+ }++ @Test func branchPredicates() {+ let bl = ARM64Encoder.encodeBL(from: 0x1000, to: 0x2000)!+ .withUnsafeBytes { $0.load(as: UInt32.self) }+ #expect(ARM64Inst.isBL(bl))+ // b.eq vs b.ne (cond field)+ #expect(ARM64Inst.isBEQ(0x5400_0020)) // b.eq #4+ #expect(!ARM64Inst.isBEQ(0x5400_0021)) // b.ne #4+ }++ @Test func compareAndBranch() {+ #expect(ARM64Inst.isCBZW(0x3400_0020)) // cbz w0, #4+ #expect(!ARM64Inst.isCBZW(0x3500_0020)) // that is cbnz+ #expect(ARM64Inst.isCBNZW(0x3500_0020))+ #expect(ARM64Inst.isCBZorCBNZW(0x3400_0020))+ #expect(ARM64Inst.isCBZorCBNZW(0x3500_0020))+ #expect(ARM64Inst.isCBZX(0xB400_0020)) // cbz x0, #4 (64-bit)+ #expect(!ARM64Inst.isCBZX(0x3400_0020)) // 32-bit cbz is not the X form+ }}struct BinaryBufferTests {diff --git a/tests/test_jb_kernel_patches.sh b/tests/test_jb_kernel_patches.shnew file mode 100755index 00000000..a1b89dcf--- /dev/null+++ b/tests/test_jb_kernel_patches.sh@@ -0,0 +1,227 @@+#!/usr/bin/env zsh+# test_jb_kernel_patches.sh — the single test for the JB kernel patch layer.+#+# Runs the WHOLE `kernel-jb` patcher (every JB hook, including all the Sandbox+# MACF ops hooks) over each cloudOS kernel the README lists as supported, and+# requires that every version applies with 0 failures and emits every expected+# patch. This is both the correctness check and the backward-compatibility gate+# (we develop against the newest kernel but must not regress older ones).+#+# The kernel we patch (`kernelcache.research.vphone600`) ships inside the cloudOS+# (PCC) firmware, so "kernel versions" == the cloudOS builds in the README's+# "Tested Environments" table. For each build we resolve its PCC "OS" asset URL+# from `ipsw dl pcc --info`, pull ONLY `kernelcache.research.vphone600` via remote+# extraction (~14 MB, not the full IPSW), run `patch-component --component+# kernel-jb`, and validate. Anything cached under the work dir is reused.+#+# tests/test_jb_kernel_patches.sh # all supported cloudOS builds+# tests/test_jb_kernel_patches.sh --quick # only the local/newest kernel (fast dev loop)+# tests/test_jb_kernel_patches.sh 23B85 23D128 # only these builds+# tests/test_jb_kernel_patches.sh --no-build # skip rebuilding the patcher+# BUILDS="23B85 23D128 23E5207q" tests/test_jb_kernel_patches.sh+#+# Exit code: 0 iff EVERY tested kernel applies all expected patches with 0 failures.+set -euo pipefail++HERE=${0:a:h}+ROOT=${HERE:h} # tests/ lives at the repo root+cd "$ROOT"++WORK=${WORK:-/tmp/vphone_kjb_versions}+BIN=".build/debug/vphone-cli"+README="$ROOT/README.md"+PCC_INFO="$WORK/pcc_info.txt" # cached `ipsw dl pcc --info` dump+mkdir -p "$WORK"++# Patch IDs that MUST emit on every supported kernel: the P0 sudo hook plus the+# eight routines retargeted for 26.5. If any is missing, that hook silently+# skipped. (The 0-failure gate below additionally catches every OTHER routine —+# including all the Sandbox ops hooks — since the pipeline counts a routine that+# emits nothing as a failure.)+REQUIRED_IDS=(+ jb.hook_cred_label.c23_cave+ task_conversion_eval+ jb.proc_security_policy.mov_x0_0+ jb.proc_pidinfo.nop_guard_a+ jb.io_secure_bsd_root.zero_return+ kernelcache_jb.mac_mount.flag_gate+ kernelcache_jb.spawn_validate_persona.cbz1+ kernelcache_jb.vm_map_protect+ jb.kcall10.sy_call+)++NO_BUILD=0+QUICK=0+ARG_BUILDS=()+for a in "$@"; do+ case "$a" in+ --no-build) NO_BUILD=1 ;;+ --quick) QUICK=1 ;;+ -*) echo "unknown option: $a" >&2; exit 2 ;;+ *) ARG_BUILDS+=("$a") ;;+ esac+done++command -v ipsw >/dev/null 2>&1 || { echo "[-] 'ipsw' CLI not found (brew install blacktop/tap/ipsw)"; exit 2; }++# --- 1. Determine which cloudOS builds to test -------------------------------+# Priority: --quick (local kernel) > CLI args > $BUILDS env > README cloudOS column.+typeset -a BUILD_LIST+if (( QUICK )); then+ BUILD_LIST=(local)+elif (( ${#ARG_BUILDS} )); then+ BUILD_LIST=("${ARG_BUILDS[@]}")+elif [[ -n "${BUILDS:-}" ]]; then+ BUILD_LIST=(${=BUILDS})+else+ # cloudOS column entries look like `26.4-23E5207q` (version-dash-build); the+ # iPhone column uses `17,3_26.5_23F77` (commas/underscores), so filter those out.+ BUILD_LIST=($(python3 - "$README" <<'PY'+import re, sys+seen=[]+insec=False+for line in open(sys.argv[1], encoding="utf-8"):+ if line.startswith("## Tested Environments"): insec=True; continue+ if insec and line.startswith("## "): break+ if not insec: continue+ for tok in re.findall(r"`([^`]+)`", line):+ m=re.fullmatch(r"\d+\.\d[\d.]*-([0-9A-Za-z]+)", tok) # 26.4-23E5207q+ if m and m.group(1) not in seen:+ seen.append(m.group(1))+print("\n".join(seen))+PY+))+fi+[[ ${#BUILD_LIST} -gt 0 ]] || { echo "[-] no cloudOS builds resolved"; exit 2; }+echo "kernel builds to test: ${BUILD_LIST[*]}"++# --- 2. Build the patcher ----------------------------------------------------+if (( ! NO_BUILD )); then+ echo "==> building patcher ..."+ if ! make patcher_build > "$WORK/build.log" 2>&1; then+ echo "[-] patcher build failed:"; tail -20 "$WORK/build.log"; exit 1+ fi+fi+[[ -x "$BIN" ]] || { echo "[-] $BIN missing (run without --no-build)"; exit 1; }++# --- 3. Cache the PCC release index (build -> OS asset URL) ------------------+ensure_pcc_info() {+ [[ -s "$PCC_INFO" ]] && return 0+ echo "==> fetching PCC release index (ipsw dl pcc --info) ..."+ if ! ipsw dl pcc --info > "$PCC_INFO" 2>&1; then+ echo "[-] 'ipsw dl pcc --info' failed:"; tail -5 "$PCC_INFO"; return 1+ fi+}++# Resolve one cloudOS build -> its PCC "OS" asset URL (only releases that still+# carry the vphone600 firmware). Empty output => not found.+resolve_url() {+ local build="$1"+ PCC_INFO="$PCC_INFO" python3 - "$build" <<'PY'+import os, re, sys+build = sys.argv[1]+raw = open(os.environ["PCC_INFO"], encoding="utf-8", errors="replace").read()+clean = re.sub(r"\x1b\[[0-9;]*m", "", raw)++blocks, cur = [], None+for line in clean.splitlines():+ if re.match(r"^\d+\)\s+[0-9a-f]{16,}", line):+ cur = {"vphone": False, "url": None, "builds": set()}+ blocks.append(cur)+ continue+ if cur is None:+ continue+ if "\U0001F4F1 VPHONE" in line: # 📱 VPHONE = vphone firmware present+ cur["vphone"] = True+ u = re.search(r"(https://updates\.cdn-apple\.com/private-cloud-compute/[0-9a-f]+)", line)+ if u and cur["url"] is None:+ cur["url"] = u.group(1)+ cur["builds"].update(re.findall(r"\b(2[0-9][A-Z][0-9A-Za-z]+)\b", line))++for b in blocks:+ if b["vphone"] and b["url"] and build in b["builds"]:+ print(b["url"])+ break+PY+}++# --- 4. Obtain kernelcache.research.vphone600 for a build -------------------+# "local" => reuse the pristine kernelcache already extracted under ipsws/.+# Otherwise reuse an already-extracted copy in the work dir; else remote-extract.+get_kernelcache() {+ local build="$1"+ if [[ "$build" == local ]]; then+ ls ipsws/*/kernelcache.research.vphone600 2>/dev/null | grep -v Restore | head -1+ return+ fi+ local dir="$WORK/$build" kc+ kc=$(find "$dir" -name 'kernelcache.research.vphone600' -type f 2>/dev/null | head -1)+ if [[ -n "$kc" && -f "$kc" ]]; then echo "$kc"; return 0; fi++ ensure_pcc_info || { echo ""; return 1; }+ local url; url=$(resolve_url "$build")+ [[ -n "$url" ]] || { echo ""; return 1; }+ mkdir -p "$dir"+ if ! ipsw extract --kernel --remote "$url" --output "$dir" >> "$WORK/$build.extract.log" 2>&1; then+ echo "" ; return 1+ fi+ find "$dir" -name 'kernelcache.research.vphone600' -type f 2>/dev/null | head -1+}++# --- 5. Run the patcher + validate one kernelcache --------------------------+typeset -A RESULT+overall=0+for build in "${BUILD_LIST[@]}"; do+ echo ""+ echo "──────────── kernel $build ────────────"+ kc=$(get_kernelcache "$build") || true+ if [[ -z "$kc" || ! -f "$kc" ]]; then+ echo " [-] could not obtain kernelcache (no vphone release / download failed)"+ RESULT[$build]="NO-KERNEL"; overall=1; continue+ fi+ echo " kernel: $kc"++ out="$WORK/$build"; mkdir -p "$out"+ if ! "$BIN" patch-component --component kernel-jb \+ --input "$kc" --output "$out/kc.patched.bin" --records-out "$out/records.json" \+ > "$out/run.log" 2>&1; then+ echo " [-] patcher crashed:"; tail -8 "$out/run.log" | sed 's/^/ /'+ RESULT[$build]="CRASH"; overall=1; continue+ fi++ applied=$(grep -oE "applied [0-9]+ patches" "$out/run.log" | grep -oE "[0-9]+" | head -1 || echo "?")+ fails=$(grep -cE "\[-\]" "$out/run.log" || true)+ sandbox=$(grep -oE 'sandbox_ext_[0-9]+' "$out/records.json" 2>/dev/null | sort -u | wc -l | tr -d ' ')++ # Every required patch ID must have emitted.+ missing=()+ for id in "${REQUIRED_IDS[@]}"; do+ grep -q "\"$id\"" "$out/records.json" 2>/dev/null || missing+=("$id")+ done++ echo " applied: $applied failures: $fails sandbox hooks: $sandbox"+ if (( fails == 0 )) && (( ${#missing} == 0 )) && (( sandbox >= 1 )); then+ echo " ✅ PASS"+ RESULT[$build]="PASS ($applied applied, $sandbox sandbox)"+ else+ echo " ❌ FAIL"+ (( fails > 0 )) && { echo " failures:"; grep -E "\[-\]" "$out/run.log" | sed 's/^/ /'; }+ (( ${#missing} )) && echo " missing patch IDs: ${missing[*]}"+ (( sandbox < 1 )) && echo " no sandbox hooks emitted"+ RESULT[$build]="FAIL"; overall=1+ fi+done++# --- 6. Summary matrix -------------------------------------------------------+echo ""+echo "════════════════ summary ════════════════"+for build in "${BUILD_LIST[@]}"; do+ printf " %-12s %s\n" "$build" "${RESULT[$build]:-?}"+done+echo ""+if (( overall == 0 )); then+ echo "ALL KERNELS PASS — every JB hook (incl. Sandbox) applies, backward-compatible."+else+ echo "ONE OR MORE KERNELS FAILED — see above."+fi+exit $overall