Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Aim the EXC_GUARD patch at thread_guard_violation on cloudOS 26.x kernels

rothilion2669850c98148d
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 98f60b9e..d6441aff 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -5086,6 +5086,56 @@ oldest base and one of the three with 15 donor kexts, and 18.5 (22F76) on
cloudOS 18.5 passed the same checks. The other four recipes resolve every
donor import but have not been booted yet.
+### 2026-11-04 — `kernel-boot-thread_guard_violation` on iOS 18.6.2 / cloudOS 26.1
+
+iPhone17,3 iOS 18.6.2 (22G100) pairs with cloudOS 26.1 (23B85), so the guest
+boots the 26.1 `kernelcache.research.vphone600` while its iOS 18 base turns
+`kernel-boot-thread_guard_violation` on. The 2026-10-24 shape then picked the
+wrong function: in 26.1 `set_exception_behavior_violation` (foff `0xB04178`)
+the guard call, `thread_guard_violation(current_thread(), code, subcode, true)`,
+is the seventh instruction after its `mrs x0, tpidr_el1` (the code is built in
+between), and the only BL within six instructions of an `mrs x0, tpidr_el1` is
+`send_set_exception_telemetry`'s `get_threadtask(current_thread())` (foff
+`0xB76068`, 588 callers). `RET` there returns the thread as its own task. The
+first page fault of boot (a `memmove` into an unmapped buffer while OSKext saves
+kext mutable segments, ESR `0x96000046`) calls `counter_inc(&task->faults)`
+through it, faults on the garbage counter, and recurses in `vm_fault` until
+`sleh_invalid_stack` raises `Invalid kernel stack pointer (probable overflow).`
+That panic is taken on SP1, so its debugger trap (`0xe7ffdeff` in
+`DebuggerTrapWithState`) panics again: the serial console only ever shows
+"Nested panic … Unexpected debugger trap while SP1 selected", with entry 1
+never printed (upstream #715). CPU1–3 are never started.
+
+Reveal procedure: the frame-pointer chain of CPU0 in the post-panic spin, read
+over the kernel GDB stub (`vm launch --kernel-debug-port`, lldb `gdb-remote`),
+walked to its oldest frame; exception frames are the records whose return
+address is not preceded by a call, and their `arm_saved_state` sits 0x10 above
+the record (pc `+0x108`, far `+0x118`).
+
+The fix keeps both existing rules and adds one in front: of the BLs within ten
+instructions after `mrs x0, tpidr_el1`, the one whose argument setup contains
+`movk xN, #imm, lsl #48` with `imm >> 13 == GUARD_TYPE_MACH_PORT`
+(`EXC_GUARD_ENCODE_TYPE`, bits 61–63 of the code) wins. When no call carries the
+type, the six-instruction rule applies exactly as before; the 18.6 kernel
+should keep `0xA21D34` either way, but that kernel was not re-run here (the
+18.6 test case is the synthetic shape described above, not its words). On 26.1
+the patch now lands on `thread_guard_violation` at
+foff `0xB4FFCC` (`0xfffffe0007b53fcc`: `get_threadtask()` against `kernel_task`,
+`code`/`subcode` into `thread+0x390/0x398`, fatal bit in `thread+0x4d2`, then
+`ldset #0x1000` = `AST_GUARD` on `thread+0x404`).
+
+The patch is still needed there. With it blocked, the 26.1 kernel boots and
+vphoned connects, but SpringBoard and runningboardd crash-loop on
+`EXC_GUARD`/`GUARD_TYPE_MACH_PORT` "Unknown flavor 67" and "flavor 10" from
+`mach_msg` (77 reports within minutes, Apple logo only). With the corrected
+target the guest reaches the Hello screen and
+`[control] connected to vphoned HTTP API (iOS 18.6.2)`.
+
+Validation: `KernelExcGuardTests` carries 26.1's
+`set_exception_behavior_violation` word for word and the 18.6 shape; with
+`VPHONE_VP600_KERNEL` set, the real-kernel test checks that the patched
+function raises `AST_GUARD`. Booted on 18.6.2 / cloudOS 26.1 (standard preset).
+
### 2026-10-24 — `standard` on the iOS 18 research board kernels
Checked on iOS 18.6 (22G86) on cloudOS 18.6 (22G86), VM restored with
@@ -5110,7 +5160,9 @@ allocation return garbage, so `kmem_init`'s first `vm_map_enter` failed with
`thread_guard_violation(current_thread(), …)`; the patch now takes the callee of
the BL after `mrs x0, tpidr_el1` in the window's callees when exactly one exists
(18.6 `0xA21D34`, which compares `get_threadtask()` with `kernel_task` first).
-The 26.x kernels match neither shape, as before.
+The 26.x kernels match neither shape, as before — except that an iOS 18 base on
+a 26.x kernel (18.6.2 on cloudOS 26.1) does match the second one, wrongly; see
+2026-11-04 below.
| Patch | 26.x shape | iOS 18 shape (18.6) |
| --- | --- | --- |
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchExcGuard.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchExcGuard.swift
index c0ff4868..d23e0ae4 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchExcGuard.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchExcGuard.swift
@@ -61,7 +61,18 @@ extension KernelPatcher {
// `ldrb ; cmp #1 ; b.ne`, not a TBZ, and the shape below then settles on
// a zone allocator called from the same window; turning that into RET
// made vm_map_enter fail in kmem_init.
+ //
+ // An iOS 18 base can also run on a cloudOS 26.x kernel (18.6.2 on
+ // 26.1). There set_exception_behavior_violation keeps both calls apart:
+ // the guard call, whose code is built between the MRS and the BL
+ // (seven instructions), and send_set_exception_telemetry's
+ // get_threadtask(current_thread()), whose BL directly follows its own
+ // MRS. Only the second fits the six-instruction window, and turning
+ // get_threadtask into RET makes the first page fault of boot recurse in
+ // vm_fault until the kernel stack overflows. The guard call is the one
+ // whose arguments carry the EXC_GUARD type, so that call wins.
var currentThreadCallees = Set<Int>()
+ var guardCodeCallees = Set<Int>()
for off in stride(from: scanStart, to: scanEnd, by: 4) {
guard let target = decodeBL(at: off), target > 0, target + 0x80 <= buffer.count,
buffer.readU32(at: target) == ARM64.pacibspU32
@@ -70,16 +81,23 @@ extension KernelPatcher {
for (index, insn) in insns.enumerated() where insn.mnemonic == "mrs" {
// A system register has no register-operand identity to compare.
guard insn.operandString.lowercased() == "x0, tpidr_el1" else { continue }
- if let call = insns.dropFirst(index + 1).prefix(6).first(where: { $0.mnemonic == "bl" }),
- let callee = decodeBL(at: Int(call.address)),
- callee > 0, callee + 4 <= buffer.count,
- buffer.readU32(at: callee) == ARM64.pacibspU32
- {
+ let following = insns.dropFirst(index + 1).prefix(10)
+ guard let call = following.first(where: { $0.mnemonic == "bl" }),
+ let callee = decodeBL(at: Int(call.address)),
+ callee > 0, callee + 4 <= buffer.count,
+ buffer.readU32(at: callee) == ARM64.pacibspU32
+ else { continue }
+ let argumentSetup = following.prefix(while: { $0.address < call.address })
+ if argumentSetup.contains(where: Self.setsMachPortGuardType) {
+ guardCodeCallees.insert(callee)
+ }
+ if argumentSetup.count < 6 {
currentThreadCallees.insert(callee)
}
}
}
- if currentThreadCallees.count == 1, let inner = currentThreadCallees.first {
+ let guardCallees = guardCodeCallees.isEmpty ? currentThreadCallees : guardCodeCallees
+ if guardCallees.count == 1, let inner = guardCallees.first {
log(" [*] thread_guard_violation at foff 0x\(String(format: "%X", inner)) (called on the current thread)")
emit(
inner,
@@ -140,4 +158,18 @@ extension KernelPatcher {
log(" [-] thread_guard_violation not found via anchor chain")
return false
}
+
+ /// `movk xN, #imm, lsl #48` whose top bits are GUARD_TYPE_MACH_PORT.
+ ///
+ /// EXC_GUARD_ENCODE_TYPE puts the guard type in bits 61-63 of the code,
+ /// bits 13-15 of the top halfword. Matching the type exactly keeps the
+ /// pointer-authentication discriminators blended in with the same
+ /// `movk ..., lsl #48` (0xd507 and the like) out.
+ static func setsMachPortGuardType(_ insn: ARM64Instruction) -> Bool {
+ guard insn.mnemonic == "movk", let ops = insn.detail?.operands, ops.count == 2,
+ ops[0].type == .register, ops[1].type == .immediate,
+ ops[1].shift.type == .lsl, ops[1].shift.amount == 48
+ else { return false }
+ return ops[1].imm >> 13 == 0x1 // GUARD_TYPE_MACH_PORT
+ }
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelExcGuardTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelExcGuardTests.swift
new file mode 100644
index 00000000..7b3ea415
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelExcGuardTests.swift
@@ -0,0 +1,216 @@
+// KernelExcGuardTests.swift — Which callee kernel-boot-thread_guard_violation patches.
+//
+// set_exception_behavior_violation below is the cloudOS 26.1 (23B85)
+// kernelcache.research.vphone600 function byte for byte (foff 0xB04178), the
+// kernel's own words, with only its BLs re-encoded for the synthetic layout.
+// That kernel boots iOS 18.6.2, so the iOS 18 gate applies the patch to it. It
+// raises the guard on the current thread seven instructions after
+// `mrs x0, tpidr_el1`, and later calls get_threadtask(current_thread()) for
+// send_set_exception_telemetry right after a second `mrs x0, tpidr_el1`.
+
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+import VPhonePatchKit
+
+@Suite("kernel-boot-thread_guard_violation")
+struct KernelExcGuardTests {
+ // MARK: - Synthetic kernel
+
+ static let anchor = "com.apple.security.only-one-exception-port"
+
+ /// Offsets inside `__TEXT_EXEC`.
+ static let callerOffset = 0x000
+ static let violationOffset = 0x100
+ static let guardOffset = 0x300 // thread_guard_violation
+ static let taskOffset = 0x400 // get_threadtask
+ static let otherOffset = 0x500
+
+ enum Callee { case guardViolation, threadTask, other }
+
+ /// cloudOS 26.1 set_exception_behavior_violation; BL words are placeholders.
+ static let violation26: [(UInt32, Callee?)] = [
+ (0xD503_237F, nil), // pacibsp
+ (0xA9BC_5FF8, nil), // stp x24, x23, [sp, #-0x40]!
+ (0xA901_57F6, nil), // stp x22, x21, [sp, #0x10]
+ (0xA902_4FF4, nil), // stp x20, x19, [sp, #0x20]
+ (0xA903_7BFD, nil), // stp x29, x30, [sp, #0x30]
+ (0x9100_C3FD, nil), // add x29, sp, #0x30
+ (0xAA00_03F4, nil), // mov x20, x0
+ (0xD0FF_DBD7, nil), // adrp x23, thid_should_crash@page
+ (0x396D_42E8, nil), // ldrb w8, [x23, #0xb50]
+ (0x2A01_03F3, nil), // mov w19, w1
+ (0x3600_0128, nil), // tbz w8, #0, +0x24
+ (0xD538_D080, nil), // mrs x0, tpidr_el1
+ (0x2A02_03E8, nil), // mov w8, w2
+ (0xD2C0_00C9, nil), // mov x9, #0x600000000
+ (0xF2E4_0009, nil), // movk x9, #0x2000, lsl #48
+ (0xAA09_0101, nil), // orr x1, x8, x9
+ (0xAA13_03E2, nil), // mov x2, x19
+ (0x5280_0023, nil), // mov w3, #1
+ (0, .guardViolation), // bl thread_guard_violation
+ (0x9000_E488, nil), // adrp x8, ...
+ (0xF941_7101, nil), // ldr x1, [x8, #0x2e0]
+ (0x5280_0600, nil), // mov w0, #0x30
+ (0x5290_0082, nil), // mov w2, #0x8004
+ (0, .other), // bl kalloc_type
+ (0xAA00_03F5, nil), // mov x21, x0
+ (0xF940_0816, nil), // ldr x22, [x0, #0x10]
+ (0xD538_D080, nil), // mrs x0, tpidr_el1
+ (0, .threadTask), // bl get_threadtask
+ (0xAA16_03E1, nil), // mov x1, x22
+ (0x5280_0222, nil), // mov w2, #0x11
+ (0, .other), // bl strlcpy
+ (0xD65F_0FFF, nil), // retab
+ ]
+
+ /// The iOS 18 research kernel shape: the guard call follows its MRS.
+ static let violation18: [(UInt32, Callee?)] = [
+ (0xD503_237F, nil), // pacibsp
+ (0xD538_D080, nil), // mrs x0, tpidr_el1
+ (0xAA13_03E1, nil), // mov x1, x19
+ (0xAA14_03E2, nil), // mov x2, x20
+ (0x5280_0023, nil), // mov w3, #1
+ (0, .guardViolation), // bl thread_guard_violation
+ (0xD65F_0FFF, nil), // retab
+ ]
+
+ /// A minimal arm64 kernel with one `__TEXT_EXEC` segment: a caller that
+ /// loads the anchor string and calls `violation`, the violation function,
+ /// and three callees that only return. The anchor string sits after the
+ /// segment.
+ static func kernel(violation: [(UInt32, Callee?)]) -> (data: Data, textStart: Int) {
+ let textStart = 0x1000
+ let textSize = 0x1000
+ let stringOffset = textStart + textSize + 0x100
+ var bytes = [UInt8](repeating: 0, count: stringOffset + 0x100)
+
+ func put(_ data: Data?, at offset: Int) {
+ guard let data else { return }
+ bytes.replaceSubrange(offset ..< offset + data.count, with: data)
+ }
+ func put(_ word: UInt32, at offset: Int) {
+ withUnsafeBytes(of: word.littleEndian) { bytes.replaceSubrange(offset ..< offset + 4, with: $0) }
+ }
+
+ // Mach-O header and LC_SEGMENT_64 __TEXT_EXEC.
+ var header = Data()
+ func append32(_ value: UInt32) { withUnsafeBytes(of: value.littleEndian) { header.append(contentsOf: $0) } }
+ func append64(_ value: UInt64) { withUnsafeBytes(of: value.littleEndian) { header.append(contentsOf: $0) } }
+ append32(0xFEED_FACF)
+ append32(0x0100_000C)
+ append32(2)
+ append32(2)
+ append32(1)
+ append32(72)
+ append32(0)
+ append32(0)
+ append32(0x19)
+ append32(72)
+ var segname = Data("__TEXT_EXEC".utf8)
+ segname.append(contentsOf: [UInt8](repeating: 0, count: 16 - segname.count))
+ header.append(segname)
+ append64(0xFFFF_FE00_0700_4000 + UInt64(textStart))
+ append64(UInt64(textSize))
+ append64(UInt64(textStart))
+ append64(UInt64(textSize))
+ append32(5)
+ append32(5)
+ append32(0)
+ append32(0)
+ put(header, at: 0)
+
+ // Caller: adrp/add of the anchor, then a BL to the violation function.
+ let caller = textStart + callerOffset
+ put(ARM64.pacibspU32, at: caller)
+ put(ARM64Encoder.encodeADRP(rd: 8, pc: UInt64(caller + 4), target: UInt64(stringOffset)), at: caller + 4)
+ put(ARM64Encoder.encodeAddImm12(rd: 8, rn: 8, imm12: UInt32(stringOffset & 0xFFF)), at: caller + 8)
+ put(ARM64Encoder.encodeBL(from: caller + 12, to: textStart + violationOffset), at: caller + 12)
+ put(ARM64.retabU32, at: caller + 16)
+
+ // The violation function.
+ for (index, (word, callee)) in violation.enumerated() {
+ let offset = textStart + violationOffset + 4 * index
+ switch callee {
+ case nil: put(word, at: offset)
+ case .guardViolation: put(ARM64Encoder.encodeBL(from: offset, to: textStart + guardOffset), at: offset)
+ case .threadTask: put(ARM64Encoder.encodeBL(from: offset, to: textStart + taskOffset), at: offset)
+ case .other: put(ARM64Encoder.encodeBL(from: offset, to: textStart + otherOffset), at: offset)
+ }
+ }
+
+ // Callees that only return.
+ for offset in [guardOffset, taskOffset, otherOffset] {
+ put(ARM64.pacibspU32, at: textStart + offset)
+ put(ARM64.retabU32, at: textStart + offset + 4)
+ }
+
+ bytes.replaceSubrange(stringOffset ..< stringOffset + anchor.utf8.count, with: Array(anchor.utf8))
+ return (Data(bytes), textStart)
+ }
+
+ static func patcher(_ data: Data) -> KernelPatcher {
+ let patcher = KernelPatcher(data: data, verbose: false)
+ patcher.parseMachO()
+ patcher.buildADRPIndex()
+ patcher.buildBLIndex()
+ return patcher
+ }
+
+ // MARK: - The locator
+
+ @Test func `patches the guard call, not get_threadtask, on the cloudOS 26.1 shape`() throws {
+ let (data, textStart) = Self.kernel(violation: Self.violation26)
+ let patcher = Self.patcher(data)
+
+ #expect(patcher.patchExcGuardBehavior())
+ #expect(patcher.patches.count == 1)
+ let patch = try #require(patcher.patches.first)
+ #expect(patch.patchID == "kernel-boot-thread_guard_violation")
+ #expect(patch.fileOffset == textStart + Self.guardOffset)
+ #expect(patch.patchedBytes == ARM64.ret)
+ }
+
+ @Test func `keeps the iOS 18 kernel shape`() throws {
+ let (data, textStart) = Self.kernel(violation: Self.violation18)
+ let patcher = Self.patcher(data)
+
+ #expect(patcher.patchExcGuardBehavior())
+ let patch = try #require(patcher.patches.first)
+ #expect(patch.fileOffset == textStart + Self.guardOffset)
+ }
+
+ @Test func `the guard type is matched exactly`() {
+ let disasm = ARM64Disassembler()
+ func decode(_ word: UInt32) -> ARM64Instruction? {
+ withUnsafeBytes(of: word.littleEndian) { disasm.disassembleOne(Data($0), at: 0) }
+ }
+ #expect(decode(0xF2E4_0009).map(KernelPatcher.setsMachPortGuardType) == true) // movk x9, #0x2000, lsl #48
+ #expect(decode(0xF2FA_A0F1).map(KernelPatcher.setsMachPortGuardType) == false) // movk x17, #0xd507, lsl #48
+ #expect(decode(0xF2C4_0009).map(KernelPatcher.setsMachPortGuardType) == false) // movk x9, #0x2000, lsl #32
+ }
+
+ // MARK: - The real kernel
+
+ /// Gated on `VPHONE_VP600_KERNEL`, a machine-local kernelcache.*.vphone600
+ /// (IM4P or raw). The patched function must be the one that raises
+ /// AST_GUARD (0x1000) on the thread, as thread_guard_violation does.
+ @Test(.enabled(
+ if: ProcessInfo.processInfo.environment["VPHONE_VP600_KERNEL"] != nil,
+ "VPHONE_VP600_KERNEL is not set; point it at a kernelcache.*.vphone600 to run",
+ ))
+ func `patches thread_guard_violation in a real vphone600 kernel`() throws {
+ let path = try #require(ProcessInfo.processInfo.environment["VPHONE_VP600_KERNEL"])
+ let (payload, _) = try IM4PHandler.load(contentsOf: URL(fileURLWithPath: path))
+ let patcher = Self.patcher(payload)
+
+ #expect(patcher.patchExcGuardBehavior())
+ let patch = try #require(patcher.patches.first { $0.patchID == "kernel-boot-thread_guard_violation" })
+ let body = ARM64Disassembler().disassemble(in: payload, at: patch.fileOffset, count: 64)
+ let setsASTGuard = body.contains { insn in
+ guard insn.mnemonic == "mov", let ops = insn.detail?.operands, ops.count == 2 else { return false }
+ return ops[1].type == .immediate && ops[1].imm == 0x1000
+ } && body.contains { $0.mnemonic.hasPrefix("ldset") }
+ #expect(setsASTGuard)
+ }
+}