Run a virtual iPhone on an Apple Silicon Mac.
Swift
feat(jb): match the vm_map_protect W^X gate in its fused 26.4 form
Lakr05b4181df910
diff --git a/research/0_binary_patch_comparison.md b/research/0_binary_patch_comparison.mdindex dfc2110b..a6ee6708 100644--- a/research/0_binary_patch_comparison.md+++ b/research/0_binary_patch_comparison.md@@ -156,7 +156,7 @@| JB-23 | B | `patch_thid_should_crash` | `_thid_should_crash` | Prevent GUARD_TYPE_MACH_PORT crash | Y || JB-23b| B | `patchThreadSetStateEntitlementFlag` | `thread_set_state_from_user` / inlined `act_set_state_from_user` flags materialization | **Frida Stalker existing-thread support (opt-in `--frida`).** Stalker updates an existing thread's core registers via `thread_set_state_from_user`, which passes `flags = TSSF_TRANSLATE_TO_USER \| TSSF_CHECK_ENTITLEMENT` (0x201) into `thread_set_state_internal`; the inlined `thread_set_state_allowed()` then demands `com.apple.private.thread-set-state` (which the target lacks) → `GUARD_TYPE_MACH_PORT / THREAD_SET_STATE`. Rather than NOP the entitlement check, clear TSSF_CHECK_ENTITLEMENT (bit 9) in the flags the user setters pass: rewrite `mov w6, #0x201` → `mov w6, #0x1`. This preserves TSSF_TRANSLATE_TO_USER (user-pointer translation) and leaves the independent `TH_IN_MACH_EXCEPTION` guard enforced — it only stops user-initiated `thread_set_state` from being entitlement-gated. Anchor: entitlement-string xref cluster → the single containing function (thread_set_state_internal); then its direct `b`/`bl` callers that set `w6` (the 7th-arg = flags, a calling-convention anchor, not an allocation guess) to 0x201. Both setters (`thread_set_state_from_user` + inlined `act_set_state_from_user`) are patched. No offsets/VAs/registers/bytes hardcoded; replacement from the Keystone-backed `ARM64Encoder.encodeMovzW`, Capstone-verified. Kernels without the shape are skipped (fail-open no-op). Verified on the `c0ecdb4b` 26.4 kernel (UUID `BCD06230-CCBE-8E48-50FF-D9C166D83CD5`): exactly two records at file-off `0x1D95720`/`0x1D9594C`. | `--frida` || JB-24 | B | `patch_vm_fault_enter_prepare` | `_vm_fault_enter_prepare` | Force `cs_bypass` fast path in runtime fault validation | Y |-| JB-25 | B | `patch_vm_map_protect` | `_vm_map_protect` | Skip upstream write-downgrade gate. Shape A (26.1–26.4) active; **Shape B (26.5) disabled 2026-07-05** — widened the `~VM_PROT_WRITE` COW strip (vm_map.c:6202) instead of the RWX gate (vm_map.c:5997), breaking COW and crashing the debugger (SPTM `VIOLATION_ILLEGAL_MAP`). Retired on 26.5+: SPTM code-mod (debugger + Substrate tweaks) uses write-then-flip via `vm_protect(VM_PROT_COPY)` → `XNU_USER_DEBUG`, so no RWX patch is needed. **OBSERVED (2026-09-22, cloudOS 26.4 `c0ecdb4b…`, jb):** Shape A did not match on this base either, so with Shape B disabled the patch applies nothing and logs `[-] vm_map_protect write-downgrade gate not found` — which `make test_fw_patches` is built to fail on. Left as-is deliberately: whether a 26.4 base still needs the RWX bypass is a semantics question, not a pattern-matching one, and the boot validated without it. Note the source disagrees with itself about the covered range — `KernelJBPatchVmProtect.swift` headers say "Shape A (26.1 / 26.3)" at lines 9 and 75 but "Shape A stays for 26.1-26.4" at line 69, and this row says 26.1–26.4. One of the three is wrong; resolving that is the prerequisite for deciding whether the `[-]` should become a gated skip. | Y/N |+| JB-25 | B | `patch_vm_map_protect` | `_vm_map_protect` | Skip upstream write-downgrade gate. Shape A (26.1–26.4) active; **Shape B (26.5) disabled 2026-07-05** — widened the `~VM_PROT_WRITE` COW strip (vm_map.c:6202) instead of the RWX gate (vm_map.c:5997), breaking COW and crashing the debugger (SPTM `VIOLATION_ILLEGAL_MAP`). Retired on 26.5+: SPTM code-mod (debugger + Substrate tweaks) uses write-then-flip via `vm_protect(VM_PROT_COPY)` → `XNU_USER_DEBUG`, so no RWX patch is needed. **SHAPE C ADDED (2026-09-22, cloudOS 26.4 `c0ecdb4b…`, jb):** the patch logged `[-] vm_map_protect write-downgrade gate not found` on this base, which `make test_fw_patches` is built to fail on. Two independent causes, both confirmed by disassembling the 26.4 research kernelcache. **(1) The gate is compiled differently.** Where 26.1/26.3 emit a flag-setting `bics` plus a separate `tbnz wFlags,#22,skip`, 26.4 folds the two conditions into a conditional compare and leaves one branch: `and wFlags,wFlags,#0x400000` / `mov wMask,#6` / `bic wMask,wMask,wProt` / `cmp wMask,#0` / `ccmp wFlags,#0,#0,eq` / `b.ne skip`, with `and wProt,wProt,#0xfffffffb` (clear `VM_PROT_EXECUTE`, keep R|W) inside the guarded block. Same mask `#6`, same entry bit 22, same downgrade — rewriting that single `b.ne` to an unconditional `b` bypasses both conditions at once, exactly as Shape A's rewrite does (there the `tbnz` becomes dead). Observed at VA `0xFFFFFE0008DCAEA0` → `0xFFFFFE0008DCAED0` (file `0x1DC6EA0`). **(2) The search window stopped short.** `findFuncEnd` ends at the next `pacibsp`; on 26.4 the block holding the `"vm_map_protect("` panic string ends at its own prologue `0x6B8` bytes *before* the gate, so the window derived from the string anchor never reached it. **Reveal procedure for Shape C:** the signature is its own anchor rather than a byte window — across the whole `com.apple.kernel __TEXT_EXEC` (8.4 MB) even the bare `mov wMask,#6 ; bic wMask,wMask,wProt` prefix occurs **exactly once**, and the matcher additionally requires the bit-22 mask before it and the execute-clearing `and` inside the guarded block, then demands a unique hit across all code ranges. Widening by an offset was rejected as an offset-shaped anchor. **Backward compatibility:** Shape A is untouched and still tried first, so 26.1/26.3 take precisely the path they always took and Shape C is unreachable there. **Validation status: matcher verified, not yet booted.** Confirmed on `17,3_27.0_24A435` + cloudOS 26.4 that Shape C finds the unique site and emits `b.ne → b` with the surrounding instructions byte-intact; this has NOT yet been booted on-device, and the prior Shape B attempt is the reason that matters (it broke COW and crashed the debugger with SPTM `VIOLATION_ILLEGAL_MAP`). Boot and exercise a debugger/tweak write before trusting it. Note the source also disagreed with itself about the covered range — headers said "Shape A (26.1 / 26.3)", line 69 said "26.1-26.4"; on 26.4 the answer is neither, it is Shape C. | Y/N || JB-25c| B | `patchVmMapDeleteImmutableCode` | `_vm_map_delete` permanent-entry immutable-code exception (vm_map.c:8855) | **Frida Stalker repeated-`VM_PROT_COPY` fix (opt-in `--frida`).** Stalker's write-then-flip leaves a CSM-associated permanent entry at current `RW` / max `RWX`; XNU's "debugger may undo executable mappings" exception tests `entry->protection & VM_PROT_EXECUTE` (current, bit 9), which is clear, so the entry stays permanent and the next fixed overwrite returns `KERN_PROTECTION_FAILURE`. Retarget the execute test to the packed `max_protection` bit (bit 9 → bit 13; `protection:3`@7..9, `max_protection:4`@11..14 in the `[entry,#0x38]` flags word). Semantic matcher: packed-flags load + `vme_permanent` (bit 19) + the inlined `developer_mode_state()` byte-bit-0 read + the current-X test bound to the immutable-code cluster (Shape A: shares the remove-flags fallback target; Shape B: branches to the permanent-continuation target). The remove-flags bit is matched structurally (a test of a non-entry register), not by source constant (VM_MAP_REMOVE_* bit numbers drift across XNU versions). The later CSM current-X `#9` test in the same window is deliberately excluded (different branch target). Exactly two gates or fail closed; branch bytes from the Keystone-backed `ARM64Encoder.encodeTestBitBranch`, Capstone round-trip verified (sense/bit/target). Verified on the `c0ecdb4b` 26.4 kernel: two records at file-off `0x1DBE14C` (`tbz w8,#9→#0xd`) and `0x1DBE828` (`tbnz w8,#9→#0xd`). | `--frida` || JB-26 | B | `patch_iomfb_swapend_variable_size` | IOMFB userclient method-5 (SwapEnd) `__DATA_CONST` dispatch entry (`checkStructureInputSize`) | **iOS-27 VZ-view fix, kernel half — paired with DSC force-kern (DSC-patch item 11).** The 26.4 userclient's method-5 dispatch entry hard-checks `checkStructureInputSize == 0x588`; forced-kern iOS 27 sends its native `0x6e0`. Rewrite the size field to `kIOUCVariableStructureSize (0xFFFFFFFF)` so `IOUserClient::externalMethod` accepts 27's struct and reaches the handler. Anchor (structural): the sole `__DATA_CONST` entry `{ptr(ptrauth, top-byte≥0x80), scalarIn=0, structIn=0x588, scalarOut=0, structOut=0}` (verified unique; decompressed file-off 0x9c7228). No-op-in-effect for version-matched 26.x (sends 0x588). Re-enabled 2026-07-15 (was disabled when 27 present-path was still unknown). | Y || JB-27 | B | `patch_iomfb_swapend_handler_size` | method-5 handler internal size gate (`cmp w2,#0x588 ; b.ne <err>`) | Companion to JB-26: beyond the dispatch-table check the handler re-checks the struct size (`cmp w2,#0x588 ; b.ne <kIOReturnBadArgument>`; verified unique at decompressed file-off 0x16ae22c; success path forwards the raw struct ptr to a `vtable+0x590` paravirt swap method). Retarget the `cmp` immediate to `0x6e0` so forced-kern iOS 27's native SwapEnd reaches real swap processing (27's IOMFBSwapRec prefix matches 26.x → handler reads valid fields). Semantic anchor (`cmp w2,#imm` word + following `b.ne` decode). Enabled together with JB-26 + DSC force-kern for iOS 27. | Y |diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/Memory/KernelJBPatchVmProtect.swift b/sources/FirmwarePatcher/Kernel/JBPatches/Memory/KernelJBPatchVmProtect.swiftindex 116434d9..6404b0d7 100644--- a/sources/FirmwarePatcher/Kernel/JBPatches/Memory/KernelJBPatchVmProtect.swift+++ b/sources/FirmwarePatcher/Kernel/JBPatches/Memory/KernelJBPatchVmProtect.swift@@ -13,6 +13,20 @@// tbnz wEntryFlags, #22, skip// ... and wProt, wProt, #~bit ; the downgrade we want to skip//+// Shape C (26.4): the same decision, emitted with the two conditions fused. The+// compiler drops the flag-setting `bics` and the separate `tbnz` in favour of a+// conditional compare, leaving one branch to rewrite instead of two —+// and wFlags, wFlags, #(1 << 22) ; isolate the same entry bit the tbnz tested+// mov wMask, #6+// bic wMask, wMask, wProt ; plain bic; the compare is separate+// cmp wMask, #0 ; (~prot & 6) == 0 ?+// ccmp wFlags, #0, #0, eq ; ... and the entry flag clear ?+// b.ne skip ; <- rewrite to unconditional `b skip`+// ... and wProt, wProt, #~VM_PROT_EXECUTE+// Rewriting that single `b.ne` bypasses both conditions at once, which is exactly+// what Shape A's rewrite achieves (there the `tbnz` becomes dead code). Same bit,+// same downgrade, same patch.+//// 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@@ -45,19 +59,22 @@ extension KernelJBPatcher {// 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 = ARM64Encoder.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+ return emitSkipBranch(brOff: brOff, target: target, shape: "A")+ }++ // Shape C: the same gate with the two conditions fused into a ccmp (26.4).+ // Tried only after Shape A, so a kernel that still emits the explicit+ // `bics`/`tbnz` pair keeps taking exactly the path it always took.+ //+ // Deliberately NOT scoped to [funcStart, funcEnd]: on 26.4 the panic string+ // sits in a cold block that ends at its own `pacibsp` 0x6B8 bytes before the+ // gate, so the window findFuncEnd derives from the string stops short of it.+ // Widening that window by a byte count would be an offset-shaped anchor.+ // Instead the signature carries its own anchor — on this kernel even the+ // `mov wMask,#6 ; bic wMask,wMask,wProt` prefix occurs exactly once in 8.4 MB+ // of kernel text — and uniqueness across the whole code range is required.+ if let (brOff, target) = findFusedWriteDowngradeGate() {+ return emitSkipBranch(brOff: brOff, target: target, shape: "C")}// Shape B (26.5 mask-widen) disabled: findWxMaskMov hit vm_map.c:6202@@ -72,6 +89,131 @@ extension KernelJBPatcher {return false}+ /// Rewrite the gate's conditional branch to an unconditional one to its own target.+ private func emitSkipBranch(brOff: Int, target: Int, shape: String) -> Bool {+ guard let bBytes = ARM64Encoder.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, shape \(shape)]"+ )+ return true+ }++ // MARK: - Shape C (26.4): conditions fused into a conditional compare++ /// Find the single `b.ne` that skips the downgrade when the compiler folded the+ /// entry-flag test into a `ccmp`, and its target. Scans every known code range+ /// and returns a result only when the signature occurs exactly once.+ private func findFusedWriteDowngradeGate() -> (brOff: Int, target: Int)? {+ // The entry bit the explicit shape tested with `tbnz wFlags, #22`.+ let entryFlagBit: Int64 = 1 << 22++ var hits: [(Int, Int)] = []+ for range in codeRanges {+ scanRange(range.start, range.end, entryFlagBit, &hits)+ }+ return hits.count == 1 ? hits[0] : nil+ }++ private func scanRange(+ _ start: Int, _ end: Int, _ entryFlagBit: Int64, _ hits: inout [(Int, Int)]+ ) {+ var off = start+ while off + 0x18 < end {+ defer { off += 4 }+ let insns = disasm.disassemble(in: buffer.data, at: off, count: 5)+ guard insns.count >= 5 else { continue }+ let movMask = insns[0], bicInsn = insns[1]+ let cmpInsn = insns[2], ccmpInsn = insns[3], bneInsn = insns[4]++ // mov wMask, #6+ guard movMask.mnemonic == "mov",+ let movOps = movMask.aarch64?.operands, movOps.count == 2,+ movOps[0].type == AARCH64_OP_REG,+ movOps[1].type == AARCH64_OP_IMM, movOps[1].imm == 6+ else { continue }+ let maskReg = movOps[0].reg++ // bic wMask, wMask, wProt — the non-flag-setting form.+ guard bicInsn.mnemonic == "bic",+ let bicOps = bicInsn.aarch64?.operands, bicOps.count == 3,+ bicOps[0].type == AARCH64_OP_REG, bicOps[0].reg == maskReg,+ bicOps[1].type == AARCH64_OP_REG, bicOps[1].reg == maskReg,+ bicOps[2].type == AARCH64_OP_REG+ else { continue }+ let protReg = bicOps[2].reg++ // cmp wMask, #0+ guard cmpInsn.mnemonic == "cmp",+ let cmpOps = cmpInsn.aarch64?.operands, cmpOps.count == 2,+ cmpOps[0].type == AARCH64_OP_REG, cmpOps[0].reg == maskReg,+ cmpOps[1].type == AARCH64_OP_IMM, cmpOps[1].imm == 0+ else { continue }++ // ccmp wFlags, #0, #nzcv, eq — the `eq` is what makes this the second+ // half of the same decision rather than an unrelated fused compare.+ guard ccmpInsn.mnemonic == "ccmp",+ let ccmpDetail = ccmpInsn.aarch64,+ ccmpDetail.conditionCode == AArch64CC_EQ,+ ccmpDetail.operands.count >= 2,+ ccmpDetail.operands[0].type == AARCH64_OP_REG,+ ccmpDetail.operands[1].type == AARCH64_OP_IMM,+ ccmpDetail.operands[1].imm == 0+ else { continue }+ let flagsReg = ccmpDetail.operands[0].reg++ // b.ne <skip>, forward.+ guard bneInsn.mnemonic == "b.ne",+ let bneOps = bneInsn.aarch64?.operands, bneOps.count == 1,+ bneOps[0].type == AARCH64_OP_IMM+ else { continue }+ let skipTarget = Int(bneOps[0].imm)+ guard skipTarget > Int(bneInsn.address) else { continue }++ // The flags register must have been masked down to the same entry bit the+ // explicit shape tested, so this stays anchored on that flag and cannot+ // drift onto an unrelated fused compare.+ guard findEntryFlagMask(+ before: off, limit: start, reg: flagsReg, bit: entryFlagBit+ ) != nil else { continue }++ // And the block it guards must be the downgrade.+ let searchStart = Int(bneInsn.address) + 4+ let searchEnd = min(skipTarget, end)+ guard findWriteClearBetween(start: searchStart, end: searchEnd, protReg: protReg) != nil+ else { continue }++ hits.append((Int(bneInsn.address), skipTarget))+ }+ }++ /// Scan backwards for `and wFlags, wFlags, #bit` that isolates the entry flag.+ private func findEntryFlagMask(before: Int, limit: Int, reg: aarch64_reg, bit: Int64) -> Int? {+ var off = before - 4+ let floor = max(limit, before - 0x20)+ while off >= floor {+ let insns = disasm.disassemble(in: buffer.data, at: off, count: 1)+ if let insn = insns.first, insn.mnemonic == "and",+ let ops = insn.aarch64?.operands, ops.count == 3,+ ops[0].type == AARCH64_OP_REG, ops[0].reg == reg,+ ops[1].type == AARCH64_OP_REG, ops[1].reg == reg,+ ops[2].type == AARCH64_OP_IMM, ops[2].imm == bit+ {+ return off+ }+ off -= 4+ }+ return nil+ }+// MARK: - Shape A (26.1 / 26.3): explicit skip-branch gate/// Find the `b.ne` that skips the write-downgrade block, and its target.