Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

feat: support iPhone19 ARM64E_X1

秋奈月d8fd4799697a
diff --git a/Documents/Guides/compatibility.md b/Documents/Guides/compatibility.md
index 81118946..f93434f7 100644
--- a/Documents/Guides/compatibility.md
+++ b/Documents/Guides/compatibility.md
@@ -48,6 +48,7 @@ See [Other iPhone models](iphone-models.md).
| --- | --- | --- | --- |
| Mac17,9 (M5 Pro) 27.0.1 | `18,1_26.6.2_23G90` (iPhone 17 Pro) | `26.4-23E5207q` | Launchpad `vm create` (2.5.1 local bundle): prepare, patch, restore, CFW, boot to the home screen at 402x874 pt @3x, `model` iPhone18,1, vphoned ping |
| Mac17,9 (M5 Pro) 27.0.1 | `18,2_27.0.1_24A446` (iPhone 17 Pro Max) | `26.4-23E5207q` | **boots** with the `kernel-boot-shared_region_size` patch (2026-10-06, bundle 2.6.0-local.0d5e6f90): `dyld cache mapped system-wide`, 0 panics, vphoned answers as 27.0.1, home screen at 440x956 pt @3x |
+| Mac17,7 (M5 Max) 26.4 | `19,2_27.0.1_24A446` (iPhone 18 Pro) | `26.4-23E5207q` | **boots** with integrated ARM64E_X1 compatibility (2026-10-17): clean offline restore, validated root seal, vphoned ping, and Settings, Safari and Calculator launch |
**iPhone18,1 and iPhone18,2 on iOS 27 need the shared-region patch**
([issue #596](https://github.com/Lakr233/vphone-cli/issues/596), 27.0 and
diff --git a/Documents/Guides/iphone-models.md b/Documents/Guides/iphone-models.md
index b7049a83..47fd0293 100644
--- a/Documents/Guides/iphone-models.md
+++ b/Documents/Guides/iphone-models.md
@@ -23,17 +23,20 @@ present that model.
| `iPhone18,1` | iPhone 17 Pro | V53AP | 1206x2622 @ 460 ppi | 402x874 |
| `iPhone18,2` | iPhone 17 Pro Max | V54AP | 1320x2868 @ 460 ppi | 440x956 |
| `iPhone18,5` | iPhone 17e | V159AP | 1170x2532 @ 460 ppi | 390x844 |
+| `iPhone19,2` | iPhone 18 Pro | V63AP | 1206x2622 @ 460 ppi | 402x874 |
The iPhone17,3 keeps the display and the fixed D47 identity it has always had;
every other model gets its own panel and the identity from its own device tree.
Each model has an IPSW of its own, so `--device` is not needed. `fw catalog`
-lists every model's releases from 26.0 to 27.0.1 (the iPhone 17e from 26.3.1),
+lists the iPhone 16/17 models' releases from 26.0 to 27.0.1 (the iPhone 17e
+from 26.3.1), and the iPhone 18 Pro's 27.0.1,
each with the cloudOS an iPhone17,3 of that release uses, and `fw catalog
--device iPhone18,1` lists one model's.
-Only the iPhone 17 Pro has been booted so far; see
-[Compatibility](compatibility.md). The rest use the same path and are listed so
-they can be tried.
+The iPhone 17 Pro, 17 Pro Max and 18 Pro have recorded boot validation; see
+[Compatibility](compatibility.md). iPhone19,2 uses ARM64E_X1. On hosts without
+native X1 support, the standard preset lowers unsupported instructions; this
+weakens PC-bound pointer authentication.
## Create one
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 7e0c2818..f7fc3aaa 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -1,5 +1,71 @@
# Patch Comparison: Regular / Development / Jailbreak / Experimental
+> **iPhone19,2 / ARM64E_X1 compatibility (validated 2026-10-17):** the tested
+> pairing is iPhone 18 Pro 27.0.1 (24A446), V63AP, with cloudOS 26.4
+> (23E5207q). Cache discovery selects `dyld_shared_cache_arm64e_x1` and its
+> matching subcaches; ordinary arm64e caches remain on their existing path.
+> MachOKit 0.54.1 supplies the X1 cache format support. The `standard` preset
+> selects the following boot-essential patches when their iOS 27 applicability
+> matches; non-X1 Mach-O inputs are unchanged.
+>
+> | Patch | Target | Final role |
+> | --- | --- | --- |
+> | `kernel-boot-arm64e_x1` | vphone600 kernel | Admit subtype 12 at grading, exec-PAC and authenticated shared-region gates |
+> | `system-dyld-boot-arm64e_x1_bootstrap` | `/usr/lib/dyld` | Reach PID 1 before runtime handling exists |
+> | `system-launchd-boot-arm64e_x1_bootstrap` | `/sbin/launchd` | Reach exception-service installation |
+> | `system-fsck-boot-arm64e_x1_bootstrap` | `/sbin/fsck` | Keep the forked checker off runtime-modified signed pages |
+> | `system-mount-boot-arm64e_x1_bootstrap` | `/sbin/mount` | Keep forked mount helpers off runtime-modified signed pages |
+> | `dyld-boot-arm64e_x1_bootstrap` | 38 shared-cache images | Lower the measured pre-handler and pre-fork closure; re-attest pages and refresh corecrypto's FIPS HMAC |
+> | `restoreramdisk-boot-apfs_sha3_hash` | RestoreRamDisk and RestoreTrustCache | Select the iOS 27 root-hash algorithm and admit the re-attested sealing tool |
+>
+> **Kernel reveal.** The analyzed image is `kernelcache.research.vphone600`,
+> XNU `12377.100.591.502.1`, UUID
+> `784F88D3-2AF5-3D4A-AB00-365607646E44`. Its symbol JSON is absent from this
+> checkout, so the `ml_grade_binary` and `exec_mach_imgact` names are XNU and
+> control-flow correlations rather than recovered symbols. The measured subtype
+> comparisons are `0xfffffe000933ceb4`, `0xfffffe00091bad94` and
+> `0xfffffe00091bb088`. Runtime patching does not embed those addresses: it
+> finds the unique subtype-2 grading tail, follows real BL callers to the
+> IMGPF_NOJOP/EBADARCH gate, then finds the shared-region gate and its subtype-2
+> success assignment. All three must resolve uniquely. Each site branches to an
+> allocated cave containing `cmp Wn,#12; ccmp Wn,#2,#6,ne; b resume`, preserving
+> subtype 2 and making subtype 12 take the same authenticated paths.
+>
+> **Instruction path.** `VPhoneArm64eX1Lowering` converts the supported
+> PAuth_LR return/authentication forms to their SP-only forms and scalar
+> ADDPT/SUBPT/MADDPT/MSUBPT to existing arithmetic encodings. This removes PC
+> binding and CPA overflow poisoning; it provides instruction compatibility,
+> not hardware-equivalent X1 security. Before installing the exception service,
+> launchd forks an isolated child that executes `PACIBSPPC` and `ADDPT`. Native
+> success leaves compatibility disabled. A trap or probe failure installs the
+> service and propagates its port through spawn before child execution.
+> Supported faults suspend the target, validate the faulting word, create a
+> private writable copy of that process's page, write one lowered instruction,
+> restore RX, flush the instruction cache and retry the same PC. PID 1 uses the
+> per-thread fallback because it hosts the service; other tasks use
+> `task_suspend` to close the thread-creation race. Unknown or unsupported
+> instructions are forwarded to the captured kernel exception destination.
+>
+> **Restore seal.** For iOS 27 with cloudOS 26.4, the restore patch resolves the
+> manifest-selected ramdisk, locates `apfs_sealvolume`'s options template from
+> its unique getopt xref and decoded copy sequence, changes hash type `1`
+> (`sha256`) to `0x106` (`sha3_256_4k`), and re-attests the modified
+> CodeDirectory page. The ordered trust-cache pass replaces exactly that
+> executable's cdhash, preserves the two metadata bytes and restores v1 sort
+> order. Discovery, signature coverage or uniqueness failures abort the patch.
+>
+> **Validation and limits.** On an M5 Max guest, the unsupported-feature path
+> completed a clean offline restore, logged `Sealing System Volume`, and the
+> first disk boot logged successful on-disk root-hash authentication. Settings,
+> Safari and Calculator launched; the instruction probe completed 20,000 calls
+> without a repeat fault or file change, the unknown-opcode case retained
+> SIGILL, and the task-suspension fix passed 240 concurrent vphoned snapshot
+> requests across ten restarts. Focused Swift/C tests, strict arm64e compilation
+> and analysis, the signer suite, the complete Debug bundle build and bundle
+> admission pass. The native fast path still requires validation on a host whose
+> virtual CPU exposes both probed X1 features. The tvOS presets block all seven
+> iPhone-specific X1 and restore patches, including for a tvOS 27 userland.
+>
> **tvOS 26.4 support (2026-10-15).** AppleTV5,3 / J42d uses a
> monolithic arm64 TVOS userland with the cloudOS 26.4 vphone600ap kernel.
> `devicetree-cfw-tv_app_architecture` copies the donor's concrete app architecture.
@@ -533,6 +599,18 @@
## Boot Chain Patches
+### Restore environment (iOS 27 + cloudOS 26.4)
+
+| # | Patch | Component | Purpose | Regular | Dev | JB |
+| --- | --- | --- | --- | :---: | :---: | :---: |
+| 1 | `restoreramdisk-boot-apfs_sha3_hash.hash_type` | `RestoreRamDisk` / `apfs_sealvolume` | Select APFS hash type `0x106` (`sha3_256_4k`) and re-attest the modified Mach-O page | Y | Y | Y |
+| 2 | `restoreramdisk-boot-apfs_sha3_hash.trustcache` | `RestoreTrustCache` | Replace the old sealing-tool cdhash with the re-attested cdhash and restore v1 entry order | Y | Y | Y |
+
+The patch is gated to an iOS 27 base paired with cloudOS 26.4. Both paths are
+resolved from `BuildManifest.plist`; discovery requires one semantic match and
+the trust-cache update requires exactly one old cdhash, so an unknown restore
+environment fails before publishing a partially patched tree.
+
### AVPBooter
| # | Patch | Purpose | Regular | Dev | JB |
@@ -1468,7 +1546,8 @@ cache rebuild.
| DeviceTree base properties | 4 | 4 | 4 | 4 |
| DeviceTree EXP identity properties | - | - | - | 8 |
| DeviceTree EXP node additions | - | - | - | 1 (`/product/camera`) |
-| Boot chain total | 46 | 58 | 117 | 132 |
+| Restore environment | 2 | 2 | 2 | 2 |
+| Boot chain total | 48 | 60 | 119 | 134 |
| CFW binary patches (base) | 4 | 5 | 6 | 6 |
| CFW EXP-only steps | - | - | - | 5 (hv_vmm DSC, camera DSC ×12, watchdogd EXP-JB-3.5, post-restore DT EXP-JB-6, build-version EXP-JB-7 opt-in) |
| CFW installed components | 6 | 7 | 9 | 9 |
diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.md
index 1655553d..a74fa9a5 100644
--- a/Research/vphoned_http_api.md
+++ b/Research/vphoned_http_api.md
@@ -323,7 +323,7 @@ request carries `"force": true`.
| Area | Methods |
| --- | --- |
| Device | `device.snapshot`, `device.info` (snapshot plus network, screen, rotation, brightness, volume, low power, Developer Mode, agent, `device_name` `{name, own_name}`: the pinned name and the guest's own ComputerName), `device.screen`, `device.network`, `device.ioreg {plane}`, `device.environment`, `device.basebin {archive?}` |
-| Display, audio | `display.brightness {value?}`, `display.rotation {orientation?}`, `display.orientation` (`{degrees, source}`: SpringBoard's interface orientation without a screen capture, for polling; capability `display_orientation`), `display.rotation_lock {locked}`, `display.auto_lock` (`{auto_lock_seconds, never, lock_screen_minimum_seconds}`: Auto-Lock and the Lock Screen timeout vphoned keeps in step with it, see below; capability `display_auto_lock`), `screen.unlock {passcode?, timeout?}` (`{locked, screen_off, was_locked, was_screen_off}`: the display on and the Lock Screen passed, see below; capability `screen_unlock`), `audio.volume {value?, category?}`, `audio.state` |
+| Display, audio | `display.brightness {value?}`, `display.rotation {orientation?}`, `display.orientation` (`{degrees, source}`: SpringBoard's interface orientation without a screen capture, for polling; `degrees` is null while SpringBoard has no answer; capability `display_orientation`), `display.rotation_lock {locked}`, `display.auto_lock` (`{auto_lock_seconds, never, lock_screen_minimum_seconds}`: Auto-Lock and the Lock Screen timeout vphoned keeps in step with it, see below; capability `display_auto_lock`), `screen.unlock {passcode?, timeout?}` (`{locked, screen_off, was_locked, was_screen_off}`: the display on and the Lock Screen passed, see below; capability `screen_unlock`), `audio.volume {value?, category?}`, `audio.state` |
| Input | `input.touch`, `input.hid`, `input.button {name}`, `input.key {name}`, `input.type {text, delay_ms?}`, `input.paste {text}`, `input.tap`, `input.double_tap`, `input.long_press`, `input.swipe`, `input.drag {points}`, `input.touch_sequence {events}` — gesture coordinates are screen points |
| UI | `ui.tree` (alias `accessibility.tree`), `ui.element_at`, `ui.tap_element`, `ui.wait`, `ui.wait_gone`, `ui.ocr {languages?, min_confidence?}`, `ui.describe`, `screen.screenshot` |
| Processes | `processes.list {filter?}`, `processes.kill {pid, signal?}` **force**, `memory.jetsam`, `memory.pressure` (only the three kernel memory sysctls, for polling) |
diff --git a/VPhone.xcworkspace/xcshareddata/swiftpm/Package.resolved b/VPhone.xcworkspace/xcshareddata/swiftpm/Package.resolved
index 936fe20e..4bf33f40 100644
--- a/VPhone.xcworkspace/xcshareddata/swiftpm/Package.resolved
+++ b/VPhone.xcworkspace/xcshareddata/swiftpm/Package.resolved
@@ -69,8 +69,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/p-x9/MachOKit.git",
"state" : {
- "revision" : "773e10797abc53914b94c2ee8c6f40f5da0b06eb",
- "version" : "0.52.2"
+ "revision" : "659d8d5adfba8f11b4a0e05c3b3c8aa59f017492",
+ "version" : "0.54.1"
}
},
{
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Device.swift b/VPhoneDaemon/Daemon/GuestAPI+Device.swift
index cc7b0c9b..e12b9814 100644
--- a/VPhoneDaemon/Daemon/GuestAPI+Device.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI+Device.swift
@@ -116,16 +116,12 @@ extension GuestAPI {
}
}
- /// The interface orientation in `display.rotation`'s degrees, cheap
- /// enough for the host to ask every second. SpringBoard is asked
- /// directly; `rotationInfo()` captures the screen, and is only the
- /// fallback when SpringBoard does not answer.
+ /// Reads SpringBoard directly; the UIScreen path can abort before display registration.
private static func interfaceOrientation() -> [String: Any] {
- if let degrees = interfaceRotationDegrees() {
- return ["degrees": degrees, "source": "springboard"]
- }
- let degrees = (rotationInfo()["degrees"] as? NSNumber)?.intValue ?? 0
- return ["degrees": degrees, "source": "screen"]
+ [
+ "degrees": interfaceRotationDegrees().map { $0 as Any } ?? NSNull(),
+ "source": "springboard",
+ ]
}
private static func brightnessState() -> [String: Any] {
diff --git a/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.pbxproj b/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.pbxproj
index efffb9d2..935dfa3c 100644
--- a/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.pbxproj
+++ b/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.pbxproj
@@ -177,7 +177,7 @@
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/zsh;
- shellScript = "set -euo pipefail\nroot=\"$(cd \"$SRCROOT/..\" && pwd)\"\n/usr/bin/env -i HOME=\"$HOME\" TMPDIR=\"${TMPDIR:-/tmp}\" PATH=\"/usr/bin:/bin:/usr/sbin:/sbin\" /usr/bin/xcodebuild -project \"$root/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj\" -scheme VPhoneSign -configuration \"$CONFIGURATION\" -destination 'generic/platform=iOS' -derivedDataPath \"$root/.build/XcodeSignGuest-$CONFIGURATION\" CODE_SIGNING_ALLOWED=NO build\n";
+ shellScript = "set -euo pipefail\nroot=\"$(cd \"$SRCROOT/..\" && pwd)\"\n# Use the device SDK and product suffix without requiring a simulator runtime.\n/usr/bin/env -i HOME=\"$HOME\" TMPDIR=\"${TMPDIR:-/tmp}\" PATH=\"/usr/bin:/bin:/usr/sbin:/sbin\" /usr/bin/xcodebuild -project \"$root/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj\" -scheme VPhoneSign -configuration \"$CONFIGURATION\" -sdk iphoneos -derivedDataPath \"$root/.build/XcodeSignGuest-$CONFIGURATION\" CODE_SIGNING_ALLOWED=NO SUPPORTS_MACCATALYST=NO EFFECTIVE_PLATFORM_NAME=-iphoneos build\n";
};
/* End PBXShellScriptBuildPhase section */
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareMachOCodeSignature.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareMachOCodeSignature.swift
index 829379e5..37124657 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareMachOCodeSignature.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareMachOCodeSignature.swift
@@ -222,7 +222,7 @@ public enum CustomFirmwareMachOCodeSignature {
guard pageSizeLog2 > 0, pageSizeLog2 < 24 else { return nil }
let pageSize = 1 << Int(pageSizeLog2)
- guard data.fits(offset, length) else { return nil }
+ guard length >= codeDirectoryHeaderSize, data.fits(offset, length) else { return nil }
guard data.fits(offset + hashOffset, codeSlotCount * hashSize) else { return nil }
return CustomFirmwareCodeDirectory(
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareArm64eX1.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareArm64eX1.swift
new file mode 100644
index 00000000..5535a7d6
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareArm64eX1.swift
@@ -0,0 +1,541 @@
+// Static ARM64E_X1 lowering for the pre-handler and fork-sensitive boot closure.
+
+import Foundation
+import MachO
+import VPhonePatchKit
+
+public enum CustomFirmwareArm64eX1 {
+ public struct Result {
+ public let records: [PatchRecord]
+ public let unvisitedCandidates: Int
+ public let unvisitedExamples: [Int]
+
+ init(records: [PatchRecord], unvisitedCandidates: Int, unvisitedExamples: [Int] = []) {
+ self.records = records; self.unvisitedCandidates = unvisitedCandidates; self.unvisitedExamples = unvisitedExamples
+ }
+ }
+
+ private static let loweredMnemonics: Set<String> = [
+ "pacibsppc", "paciasppc", "pacnbibsppc", "pacnbiasppc",
+ "autibsppc", "autiasppc", "autibsppcr", "autiasppcr",
+ "retabsppc", "retaasppc", "retabsppcr", "retaasppcr", "addpt", "subpt", "maddpt", "msubpt",
+ "autia171615", "autib171615",
+ ]
+
+ public static func lower(_ data: inout Data) throws -> Result {
+ try lower(&data, identifier: FirmwareGuestSystemPatchSet.arm64eX1DyldBootstrap)
+ }
+
+ public static func lower(_ data: inout Data, identifier: String) throws -> Result {
+ if isUniversal(data) { return try lowerUniversal(&data, identifier: identifier, reattest: false).result }
+ guard data.count >= 32, data.loadLE(UInt32.self, at: 0) == 0xFEED_FACF,
+ data.loadLE(UInt32.self, at: 4) == 0x0100_000C,
+ data.loadLE(UInt32.self, at: 8) & 0x00FF_FFFF == 12,
+ data.loadLE(UInt32.self, at: 12) != UInt32(MH_KEXT_BUNDLE)
+ else { return Result(records: [], unvisitedCandidates: 0) }
+ let segments = MachOParser.parseSegments(from: data)
+ let sections = MachOParser.parseSections(from: data).values.filter {
+ $0.size > 0 && ($0.sectionName == "__text" || $0.flags & 0x8000_0400 != 0)
+ }
+ guard !sections.isEmpty else { return Result(records: [], unvisitedCandidates: 0) }
+ var (seeds, excluded) = try entryPoints(data, segments: segments)
+ func fileOffset(_ address: UInt64, length: Int) throws -> Int {
+ guard let segment = segments.first(where: {
+ address >= $0.vmAddr && address - $0.vmAddr <= $0.fileSize &&
+ UInt64(length) <= $0.fileSize - (address - $0.vmAddr)
+ }), let offset = Int(exactly: segment.fileOffset + address - segment.vmAddr),
+ offset <= data.count, length <= data.count - offset else {
+ throw PatcherError.invalidFormat("X1 exception metadata outside Mach-O")
+ }
+ return offset
+ }
+ if let text = segments.first(where: { $0.name == "__TEXT" }) {
+ let exceptionVMAs = try exceptionEntries(sections: Array(MachOParser.parseSections(from: data).values),
+ imageBase: text.vmAddr, readMemory: { address, length in
+ let offset = try fileOffset(address, length: length)
+ return data.subdata(in: offset ..< offset + length)
+ })
+ seeds += try exceptionVMAs.map { try fileOffset($0, length: 4) }
+ }
+ guard !seeds.isEmpty else {
+ throw PatcherError.invalidFormat("X1 lowering requires function starts and executable text")
+ }
+ var ranges: [(address: Int, data: Data)] = []
+ for section in sections {
+ guard let start = Int(exactly: section.fileOffset),
+ let size = Int(exactly: section.size),
+ start <= data.count, size <= data.count - start else {
+ throw PatcherError.invalidFormat("X1 text outside Mach-O")
+ }
+ ranges.append((start, data.subdata(in: start ..< start + size)))
+ }
+ let original = data
+ let result = try planCode(ranges: ranges, seeds: seeds, excluded: excluded,
+ identifier: identifier, readMemory: { address, length in
+ guard address <= original.count, length <= original.count - address else {
+ throw PatcherError.invalidFormat("X1 switch table outside image")
+ }
+ return original.subdata(in: address ..< address + length)
+ })
+ for record in result.records { data.replaceSubrange(record.fileOffset ..< record.fileOffset + 4, with: record.patchedBytes) }
+ return result
+ }
+
+ static func planCode(ranges: [(address: Int, data: Data)], seeds: [Int], excluded: [Range<Int>], identifier: String,
+ readMemory: ((Int, Int) throws -> Data)? = nil,
+ authenticatedPointer: ((UInt64, UInt16) throws -> UInt64?)? = nil) throws -> Result {
+ let decoder = ARM64Disassembler()
+ var dataRanges = excluded
+ var candidates: [Int] = [], frameEntries: [Int] = []
+ // Recover coalesced entries from return-PAC plus an SP frame setup.
+ for range in ranges {
+ for block in stride(from: 0, to: range.data.count, by: 0x4000) {
+ let end = min(range.data.count, block + 0x4004)
+ let decoded = decoder.disassemble(range.data.subdata(in: block ..< end), at: UInt64(range.address + block))
+ for (index, item) in decoded.enumerated() where item.address < UInt64(range.address + block + 0x4000) {
+ let address = Int(item.address)
+ guard !excluded.contains(where: { $0.contains(address) }) else { continue }
+ if loweredMnemonics.contains(item.mnemonic) { candidates.append(address) }
+ if ["pacibsppc", "paciasppc", "pacnbibsppc", "pacnbiasppc", "pacibsp", "paciasp"].contains(item.mnemonic), index + 1 < decoded.count {
+ let next = decoded[index + 1], ops = next.detail?.operands ?? []
+ let savesFrame = ["stp", "str"].contains(next.mnemonic) && ops.last?.type == .memory && ops.last?.mem.base == .sp
+ let allocatesFrame = next.mnemonic == "sub" && ops.count == 3 && ops[0].reg == .sp && ops[1].reg == .sp && ops[2].type == .immediate
+ if savesFrame || allocatesFrame { frameEntries.append(address) }
+ }
+ }
+ }
+ }
+ var decodedPage: [ARM64Instruction] = [], pageAddress = -1
+ var pages: [Int: [ARM64Instruction]] = [:], pageUses: [Int: Int] = [:], tick = 0
+ func decodedInstruction(at address: Int) -> ARM64Instruction? {
+ guard !dataRanges.contains(where: { $0.contains(address) }),
+ let range = ranges.first(where: { address >= $0.address && address < $0.address + $0.data.count }) else { return nil }
+ let relative = address - range.address
+ let block = relative / 0x4000 * 0x4000
+ if pageAddress != range.address + block {
+ pageAddress = range.address + block
+ tick += 1
+ pageUses[pageAddress] = tick
+ if let cached = pages[pageAddress] {
+ decodedPage = cached
+ } else {
+ let end = min(range.data.count, block + 0x4000)
+ decodedPage = decoder.disassemble(range.data.subdata(in: block ..< end), at: UInt64(pageAddress))
+ if pages.count >= 16, let oldest = pageUses.filter({ $0.key != pageAddress }).min(by: { $0.value < $1.value })?.key {
+ pages.removeValue(forKey: oldest)
+ pageUses.removeValue(forKey: oldest)
+ }
+ pages[pageAddress] = decodedPage
+ }
+ }
+ let index = (address - pageAddress) / 4
+ guard address & 3 == 0, index < decodedPage.count,
+ decodedPage[index].address == UInt64(address) else { return nil }
+ return decodedPage[index]
+ }
+ var scheduled = Set(seeds + frameEntries)
+ var pending = scheduled.sorted(by: >), visited = Set<Int>()
+ func schedule(_ address: Int) {
+ if !visited.contains(address), scheduled.insert(address).inserted {
+ pending.append(address)
+ }
+ }
+ var records: [PatchRecord] = []
+ while let entry = pending.popLast() {
+ var offset = entry
+ while visited.insert(offset).inserted, let instruction = decodedInstruction(at: offset), instruction.isDecoded, instruction.size == 4 {
+ if let replacement = try replacement(for: instruction) {
+ let after = decoder.disassembleOne(replacement, at: instruction.address)
+ records.append(PatchRecord(patchID: identifier + ".\(offset)", component: "Mach-O", fileOffset: offset,
+ originalBytes: Data(instruction.bytes), patchedBytes: replacement,
+ beforeDisasm: "\(instruction.mnemonic) \(instruction.operandString)",
+ afterDisasm: "\(after?.mnemonic ?? "?") \(after?.operandString ?? "")",
+ description: "X1 compatibility lowering; PC PAC/CPA checks reduced"))
+ }
+ let mnemonic = instruction.mnemonic
+ if mnemonic == "br", let readMemory,
+ let table = try switchTable(at: offset, instructionAt: decodedInstruction(at:), readMemory: readMemory) {
+ dataRanges.append(table.data)
+ for target in table.targets { schedule(target) }
+ }
+ if mnemonic == "braa", let authenticatedPointer,
+ let table = try authenticatedDispatch(at: offset, instructionAt: decodedInstruction(at:),
+ pointer: authenticatedPointer) {
+ dataRanges.append(table.data)
+ for target in table.targets {
+ guard decodedInstruction(at: target)?.isDecoded == true else {
+ throw PatcherError.invalidFormat("authenticated X1 dispatch target outside executable code")
+ }
+ schedule(target)
+ }
+ }
+ if mnemonic == "b" || mnemonic == "bl" || mnemonic.hasPrefix("b.") || ["cbz", "cbnz", "tbz", "tbnz"].contains(mnemonic) {
+ if let target = instruction.detail?.operands.last, target.type == .immediate,
+ let destination = Int(exactly: target.imm) {
+ schedule(destination)
+ }
+ if mnemonic == "b" { break }
+ }
+ if instruction.isReturn || mnemonic.hasPrefix("ret") ||
+ ["br", "braa", "brab", "braaz", "brabz", "brk", "hlt", "udf"].contains(mnemonic) { break }
+ offset += 4
+ }
+ }
+ records.removeAll { record in dataRanges.contains(where: { $0.contains(record.fileOffset) }) }
+ let unvisited = candidates.filter { address in !visited.contains(address) && !dataRanges.contains(where: { $0.contains(address) }) }
+ records.sort { $0.fileOffset < $1.fileOffset }
+ return Result(records: records, unvisitedCandidates: unvisited.count, unvisitedExamples: Array(unvisited.prefix(16)))
+ }
+
+ static func exceptionEntries(sections: [MachOSectionInfo], imageBase: UInt64,
+ readMemory: (UInt64, Int) throws -> Data) throws -> [UInt64] {
+ guard let unwind = sections.first(where: { $0.sectionName == "__unwind_info" && $0.size > 0 }) else { return [] }
+ let bytes = try readMemory(unwind.address, Int(unwind.size))
+ guard bytes.count >= 28, bytes.loadLE(UInt32.self, at: 0) == 1 else {
+ throw PatcherError.invalidFormat("invalid X1 compact unwind header")
+ }
+ let index = Int(bytes.loadLE(UInt32.self, at: 20)), count = Int(bytes.loadLE(UInt32.self, at: 24))
+ guard index <= bytes.count, count <= (bytes.count - index) / 12 else {
+ throw PatcherError.invalidFormat("X1 unwind index outside section")
+ }
+ guard count > 1 else { return [] }
+ var entries: [(function: UInt64, lsda: UInt64)] = []
+ for page in 0 ..< count - 1 {
+ let start = Int(bytes.loadLE(UInt32.self, at: index + page * 12 + 8))
+ let end = Int(bytes.loadLE(UInt32.self, at: index + (page + 1) * 12 + 8))
+ guard start <= end, end <= bytes.count, (end - start) % 8 == 0 else {
+ throw PatcherError.invalidFormat("invalid X1 LSDA index range")
+ }
+ for offset in stride(from: start, to: end, by: 8) {
+ let (function, fOverflow) = imageBase.addingReportingOverflow(UInt64(bytes.loadLE(UInt32.self, at: offset)))
+ let (lsda, lOverflow) = imageBase.addingReportingOverflow(UInt64(bytes.loadLE(UInt32.self, at: offset + 4)))
+ guard !fOverflow, !lOverflow else { throw PatcherError.invalidFormat("X1 LSDA address overflow") }
+ entries.append((function, lsda))
+ }
+ }
+ guard !entries.isEmpty else { return [] }
+ let executable = sections.filter { $0.sectionName == "__text" || $0.flags & 0x8000_0400 != 0 }
+ let addresses = Set(entries.map(\.lsda)).sorted()
+ let following = Dictionary(uniqueKeysWithValues: zip(addresses, addresses.dropFirst()))
+ var result = Set<UInt64>()
+ for entry in entries {
+ guard let section = sections.first(where: {
+ $0.sectionName == "__gcc_except_tab" && entry.lsda >= $0.address && entry.lsda - $0.address < $0.size
+ }) else { throw PatcherError.invalidFormat("X1 LSDA outside exception section") }
+ let remaining = Int(section.size - (entry.lsda - section.address))
+ let next = following[entry.lsda]
+ let length = min(remaining, next.map { Int($0 - entry.lsda) } ?? remaining)
+ let lsda = try readMemory(entry.lsda, length)
+ var cursor = 0
+ func byte() throws -> UInt8 {
+ guard cursor < lsda.count else { throw PatcherError.invalidFormat("truncated X1 LSDA") }
+ defer { cursor += 1 }
+ return lsda[cursor]
+ }
+ func uleb() throws -> UInt64 {
+ var value: UInt64 = 0, shift: UInt64 = 0
+ while true {
+ let part = try byte()
+ guard shift < 64, shift < 63 || part & 0x7F <= 1 else { throw PatcherError.invalidFormat("X1 LSDA ULEB overflow") }
+ value |= UInt64(part & 0x7F) << shift
+ if part & 0x80 == 0 { return value }
+ shift += 7
+ }
+ }
+ // Apple AArch64 LSDAs use the function start and ULEB call-site offsets.
+ guard try byte() == 0xFF else { throw PatcherError.invalidFormat("unsupported X1 LSDA landing base") }
+ if try byte() != 0xFF { _ = try uleb() }
+ guard try byte() == 1 else { throw PatcherError.invalidFormat("unsupported X1 LSDA call-site encoding") }
+ let tableLength = try uleb()
+ guard tableLength <= lsda.count - cursor else { throw PatcherError.invalidFormat("X1 LSDA call-site table outside section") }
+ let end = cursor + Int(tableLength)
+ while cursor < end {
+ _ = try uleb() // protected start
+ _ = try uleb() // protected length
+ let landing = try uleb()
+ _ = try uleb() // action-table index
+ guard cursor <= end else { throw PatcherError.invalidFormat("X1 LSDA call-site entry crosses table") }
+ if landing != 0 {
+ let (target, overflow) = entry.function.addingReportingOverflow(landing)
+ guard !overflow, target & 3 == 0, executable.contains(where: {
+ target >= $0.address && target - $0.address < $0.size
+ }) else { throw PatcherError.invalidFormat("X1 exception landing outside executable section") }
+ result.insert(target)
+ }
+ }
+ }
+ return result.sorted()
+ }
+
+ private static func authenticatedDispatch(at branch: Int, instructionAt: (Int) -> ARM64Instruction?,
+ pointer: (UInt64, UInt16) throws -> UInt64?) throws -> (targets: [Int], data: Range<Int>)? {
+ guard let jump = instructionAt(branch), jump.mnemonic == "braa",
+ let j = jump.detail?.operands, j.count == 2,
+ let modifier = instructionAt(branch - 4), modifier.mnemonic == "mov",
+ let m = modifier.detail?.operands, m.count == 2, m[0].reg == j[1].reg,
+ m[1].type == .immediate, (0 ... 65535).contains(m[1].imm) else { return nil }
+ func aliases(_ lhs: ARM64Register, _ rhs: ARM64Register) -> Bool {
+ if lhs == rhs { return true }
+ return (0 ... 30).contains { (lhs == .x($0) && rhs == .w($0)) || (lhs == .w($0) && rhs == .x($0)) }
+ }
+ func writes(_ instruction: ARM64Instruction, _ register: ARM64Register) -> Bool {
+ let ops = instruction.detail?.operands ?? []
+ return ops.contains { $0.type == .register && $0.writesRegister && aliases($0.reg, register) }
+ || (instruction.detail?.writeback == true && ops.contains { $0.type == .memory && aliases($0.mem.base, register) })
+ }
+ var loadAddress = branch - 8
+ if let extra = instructionAt(loadAddress), ["mov", "ldr"].contains(extra.mnemonic),
+ !writes(extra, j[0].reg), !writes(extra, j[1].reg) {
+ loadAddress -= 4
+ }
+ guard let load = instructionAt(loadAddress), load.mnemonic == "ldr",
+ let l = load.detail?.operands, l.count == 2, l[0].reg == j[0].reg,
+ l[1].type == .memory, l[1].shift.type == .lsl, l[1].shift.amount == 3,
+ l[1].mem.disp == 0, !aliases(l[1].mem.base, l[1].mem.index) else { return nil }
+ var hasByteTag = false
+ for distance in 1 ... 4 {
+ guard let instruction = instructionAt(loadAddress - distance * 4) else { break }
+ let o = instruction.detail?.operands ?? []
+ if instruction.mnemonic == "lsr", o.count == 2, o[0].reg == l[1].mem.index,
+ o[1].type == .register, o[1].shift.type == .lsr, o[1].shift.amount == 56 {
+ hasByteTag = true
+ break
+ }
+ if writes(instruction, l[1].mem.index) || instruction.isCall || instruction.isJump || instruction.isReturn { break }
+ }
+ guard hasByteTag else { return nil }
+ var table: UInt64?
+ let base = l[1].mem.base
+ let calleeSaved = (19 ... 28).contains { base == .x($0) }
+ for distance in 1 ... 64 {
+ let address = loadAddress - distance * 4
+ guard let instruction = instructionAt(address) else { break }
+ if instruction.isReturn || ["brk", "hlt", "udf"].contains(instruction.mnemonic) { break }
+ if instruction.isCall && !calleeSaved { break }
+ guard writes(instruction, base) else { continue }
+ let o = instruction.detail?.operands ?? []
+ guard instruction.mnemonic == "add", o.count == 3, o[0].reg == base, o[1].reg == base,
+ o[2].type == .immediate, o[2].imm >= 0, o[2].shift.amount == 0,
+ let page = instructionAt(address - 4), page.mnemonic == "adrp",
+ let p = page.detail?.operands, p.count == 2, p[0].reg == base, p[1].type == .immediate else { break }
+ let (value, overflow) = p[1].imm.addingReportingOverflow(o[2].imm)
+ if !overflow { table = UInt64(exactly: value) }
+ break
+ }
+ guard let table, table & 7 == 0 else { return nil }
+ var targets: [Int] = []
+ for index in 0 ..< 256 {
+ let (entry, overflow) = table.addingReportingOverflow(UInt64(index * 8))
+ guard !overflow else { throw PatcherError.invalidFormat("X1 dispatch table overflow") }
+ guard let target = try pointer(entry, UInt16(m[1].imm)) else { break }
+ guard target & 3 == 0, let target = Int(exactly: target) else {
+ throw PatcherError.invalidFormat("invalid authenticated X1 dispatch target")
+ }
+ targets.append(target)
+ }
+ guard targets.count >= 2, let start = Int(exactly: table), start <= Int.max - targets.count * 8 else { return nil }
+ return (targets, start ..< start + targets.count * 8)
+ }
+
+ private static func switchTable(at branch: Int, instructionAt: (Int) -> ARM64Instruction?,
+ readMemory: (Int, Int) throws -> Data) throws -> (targets: [Int], data: Range<Int>)? {
+ let window = (0 ... 7).compactMap { instructionAt(branch - (7 - $0) * 4) }
+ guard window.count == 8 else { return nil }
+ let c = window.map { $0.detail?.operands ?? [] }
+ guard window[7].mnemonic == "br", c[7].count == 1,
+ window[6].mnemonic == "add", c[6].count == 3,
+ c[6][0].reg == c[7][0].reg,
+ window[5].mnemonic == "adr", c[5].count == 2,
+ c[5][0].reg == c[6][1].reg, c[5][1].type == .immediate,
+ window[4].mnemonic == "ldrsw", c[4].count == 2,
+ c[4][0].reg == c[6][2].reg, c[4][1].type == .memory,
+ c[4][1].shift.type == .lsl, c[4][1].shift.amount == 2,
+ window[3].mnemonic == "add", c[3].count == 3,
+ c[3][0].reg == c[4][1].mem.base, c[3][1].reg == c[3][0].reg,
+ c[3][2].type == .immediate, c[3][2].shift.amount == 0,
+ window[2].mnemonic == "adrp", c[2].count == 2,
+ c[2][0].reg == c[3][0].reg, c[2][1].type == .immediate,
+ window[1].mnemonic == "csel", window[1].detail?.conditionCode == .ls, c[1].count == 3,
+ c[1][0].reg == c[4][1].mem.index, c[1][1].reg == c[1][0].reg, c[1][2].reg == .xzr,
+ window[0].mnemonic == "cmp", c[0].count == 2, c[0][0].reg == c[1][0].reg,
+ c[0][1].type == .immediate, c[0][1].imm >= 0, c[0][1].imm < 4096
+ else { return nil }
+ let (tableAddress, overflow) = c[2][1].imm.addingReportingOverflow(c[3][2].imm)
+ guard !overflow, let table = Int(exactly: tableAddress), table >= 0,
+ let base = Int(exactly: c[5][1].imm) else { return nil }
+ let count = Int(c[0][1].imm) + 1
+ let bytes = try readMemory(table, count * 4)
+ guard bytes.count == count * 4 else { throw PatcherError.invalidFormat("truncated X1 switch table") }
+ var targets: [Int] = []
+ for index in 0 ..< count {
+ let (target, overflow) = base.addingReportingOverflow(Int(bytes.loadLE(Int32.self, at: index * 4)))
+ guard !overflow, target & 3 == 0, !(table ..< table + count * 4).contains(target), instructionAt(target) != nil else {
+ throw PatcherError.invalidFormat("invalid X1 switch destination at \(branch)")
+ }
+ targets.append(target)
+ }
+ return (targets, table ..< table + count * 4)
+ }
+
+ public static func lowerAndReattest(_ data: inout Data, identifier: String) throws -> (result: Result, slots: [CustomFirmwareSlotRehash]) {
+ if isUniversal(data) { return try lowerUniversal(&data, identifier: identifier, reattest: true) }
+ var patched = data
+ let result = try lower(&patched, identifier: identifier)
+ guard !result.records.isEmpty else { return (result, []) }
+ guard let directories = CustomFirmwareMachOCodeSignature.codeDirectories(in: patched), !directories.isEmpty,
+ directories.allSatisfy({ directory in
+ directory.hashType == 2 && directory.hashSize == 32 && result.records.allSatisfy { record in
+ directory.slotRange(record.fileOffset / directory.pageSize)?.contains(record.fileOffset + 3) == true
+ }
+ }) else {
+ throw PatcherError.invalidFormat("X1 instruction edits require complete SHA-256 signature coverage")
+ }
+ let slots = try CustomFirmwareMachOCodeSignature.reattest(&patched, modifiedOffsets: result.records.map(\.fileOffset))
+ data = patched
+ return (result, slots)
+ }
+
+ private static func isUniversal(_ data: Data) -> Bool {
+ data.count >= 8 && [UInt32(0xBEBA_FECA), 0xBFBA_FECA].contains(data.loadLE(UInt32.self, at: 0))
+ }
+
+ private static func lowerUniversal(_ data: inout Data, identifier: String, reattest: Bool) throws -> (result: Result, slots: [CustomFirmwareSlotRehash]) {
+ let wide = data.loadLE(UInt32.self, at: 0) == 0xBFBA_FECA
+ let stride = wide ? 32 : 20
+ let count = Int(UInt32(bigEndian: data.loadLE(UInt32.self, at: 4)))
+ guard count > 0, count <= (data.count - 8) / stride else {
+ throw PatcherError.invalidFormat("truncated X1 universal architecture table")
+ }
+ var slices: [Range<Int>] = [], selected: [Range<Int>] = []
+ for index in 0 ..< count {
+ let entry = 8 + index * stride
+ let cpu = UInt32(bigEndian: data.loadLE(UInt32.self, at: entry))
+ let subtype = UInt32(bigEndian: data.loadLE(UInt32.self, at: entry + 4))
+ let offset = wide ? UInt64(bigEndian: data.loadLE(UInt64.self, at: entry + 8))
+ : UInt64(UInt32(bigEndian: data.loadLE(UInt32.self, at: entry + 8)))
+ let size = wide ? UInt64(bigEndian: data.loadLE(UInt64.self, at: entry + 16))
+ : UInt64(UInt32(bigEndian: data.loadLE(UInt32.self, at: entry + 12)))
+ guard let start = Int(exactly: offset), let length = Int(exactly: size),
+ start >= 8 + count * stride, length >= 32, start <= data.count, length <= data.count - start else {
+ throw PatcherError.invalidFormat("X1 universal slice outside container")
+ }
+ let range = start ..< start + length
+ guard !slices.contains(where: { $0.overlaps(range) }) else {
+ throw PatcherError.invalidFormat("overlapping X1 universal slices")
+ }
+ slices.append(range)
+ guard cpu == 0x0100_000C, subtype & 0x00FF_FFFF == 12 else { continue }
+ guard data.loadLE(UInt32.self, at: start) == 0xFEED_FACF,
+ data.loadLE(UInt32.self, at: start + 4) == cpu,
+ data.loadLE(UInt32.self, at: start + 8) == subtype else {
+ throw PatcherError.invalidFormat("X1 universal architecture disagrees with slice header")
+ }
+ selected.append(range)
+ }
+ var patched = data, records: [PatchRecord] = [], slots: [CustomFirmwareSlotRehash] = [], examples: [Int] = []
+ var unvisited = 0
+ for range in selected {
+ var slice = data.subdata(in: range)
+ let result: Result
+ let hashes: [CustomFirmwareSlotRehash]
+ let id = identifier + ".slice\(range.lowerBound)"
+ if reattest {
+ (result, hashes) = try lowerAndReattest(&slice, identifier: id)
+ } else {
+ result = try lower(&slice, identifier: id)
+ hashes = []
+ }
+ let base = range.lowerBound
+ records += result.records.map {
+ PatchRecord(patchID: $0.patchID, component: $0.component, fileOffset: base + $0.fileOffset,
+ virtualAddress: $0.virtualAddress, originalBytes: $0.originalBytes, patchedBytes: $0.patchedBytes,
+ beforeDisasm: $0.beforeDisasm, afterDisasm: $0.afterDisasm, description: $0.patchDescription)
+ }
+ slots += hashes.map {
+ CustomFirmwareSlotRehash(codeDirectoryOffset: base + $0.codeDirectoryOffset, slotType: $0.slotType,
+ pageIndex: $0.pageIndex, pageStart: base + $0.pageStart, pageEnd: base + $0.pageEnd,
+ hashFileOffset: base + $0.hashFileOffset, before: $0.before, after: $0.after, pageSize: $0.pageSize)
+ }
+ unvisited += result.unvisitedCandidates
+ examples += result.unvisitedExamples.map { base + $0 }
+ patched.replaceSubrange(range, with: slice)
+ }
+ data = patched
+ return (Result(records: records.sorted { $0.fileOffset < $1.fileOffset }, unvisitedCandidates: unvisited,
+ unvisitedExamples: Array(examples.prefix(16))), slots)
+ }
+
+ public static func patch(fileAt url: URL, log: (String) -> Void = { print($0) }) throws {
+ try patch(fileAt: url, identifier: FirmwareGuestSystemPatchSet.arm64eX1DyldBootstrap, log: log)
+ }
+
+ public static func patch(fileAt url: URL, identifier: String, log: (String) -> Void = { print($0) }) throws {
+ var data = try Data(contentsOf: url)
+ let (result, slots) = try lowerAndReattest(&data, identifier: identifier)
+ guard !result.records.isEmpty else {
+ log(" [·] X1: no reachable instructions to lower (unvisited candidates: \(result.unvisitedCandidates))")
+ return
+ }
+ try data.write(to: url)
+ for record in result.records { log(record.description) }
+ log(" [+] X1: lowered \(result.records.count) instructions, re-attested \(slots.count) slots; unvisited candidates: \(result.unvisitedCandidates)")
+ }
+
+ private static func replacement(for instruction: ARM64Instruction) throws -> Data? {
+ do {
+ return try VPhoneArm64eX1Lowering.replacement(for: instruction)
+ } catch {
+ throw PatcherError.invalidFormat(String(describing: error))
+ }
+ }
+
+ private static func entryPoints(_ data: Data, segments: [MachOSegmentInfo]) throws -> ([Int], [Range<Int>]) {
+ guard let text = segments.first(where: { $0.name == "__TEXT" }) else {
+ throw PatcherError.invalidFormat("X1 image has no __TEXT")
+ }
+ let count = Int(data.loadLE(UInt32.self, at: 16))
+ var position = 32, seeds: [Int] = [], excluded: [Range<Int>] = []
+ for _ in 0 ..< count {
+ guard position <= data.count - 8 else { throw PatcherError.invalidFormat("truncated X1 load commands") }
+ let command = data.loadLE(UInt32.self, at: position), size = Int(data.loadLE(UInt32.self, at: position + 4))
+ guard size >= 8, size <= data.count - position else { throw PatcherError.invalidFormat("invalid X1 load command") }
+ if command == 0x26 || command == 0x29 {
+ guard size >= 16 else { throw PatcherError.invalidFormat("short X1 linkedit command") }
+ let start = Int(data.loadLE(UInt32.self, at: position + 8)), length = Int(data.loadLE(UInt32.self, at: position + 12))
+ guard start <= data.count, length <= data.count - start else { throw PatcherError.invalidFormat("X1 linkedit outside image") }
+ if command == 0x26 {
+ var cursor = start, address = text.vmAddr
+ while cursor < start + length {
+ var delta: UInt64 = 0, shift = 0
+ while true {
+ guard cursor < start + length, shift < 63 else { throw PatcherError.invalidFormat("invalid function-start ULEB") }
+ let byte = data[cursor]; cursor += 1
+ delta |= UInt64(byte & 0x7F) << shift
+ if byte & 0x80 == 0 { break }
+ shift += 7
+ }
+ if delta == 0 { break }
+ let (next, overflow) = address.addingReportingOverflow(delta)
+ guard !overflow else { throw PatcherError.invalidFormat("function-start overflow") }
+ address = next
+ if let offset = MachOParser.vaToFileOffset(address, segments: segments) { seeds.append(offset) }
+ }
+ } else {
+ guard length % 8 == 0 else { throw PatcherError.invalidFormat("invalid data-in-code table") }
+ for entry in stride(from: start, to: start + length, by: 8) {
+ let offset = Int(data.loadLE(UInt32.self, at: entry)), length = Int(data.loadLE(UInt16.self, at: entry + 4))
+ guard offset <= data.count, length <= data.count - offset else { throw PatcherError.invalidFormat("data-in-code outside image") }
+ excluded.append(offset ..< offset + length)
+ }
+ }
+ } else if command == 5, size >= 288, data.loadLE(UInt32.self, at: position + 8) == 6 {
+ if let entry = MachOParser.vaToFileOffset(data.loadLE(UInt64.self, at: position + 272), segments: segments) { seeds.append(entry) }
+ } else if command == 0x8000_0028, size >= 24 {
+ let entry = data.loadLE(UInt64.self, at: position + 8)
+ if entry < UInt64(data.count) { seeds.append(Int(entry)) }
+ }
+ position += size
+ }
+ return (seeds, excluded)
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift
index d82b72fc..c3e36562 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift
@@ -125,12 +125,13 @@ public final class DyldSharedCacheChunkSet {
///
/// - Parameters:
/// - directory: the directory holding `dyld_shared_cache_<arch>*`.
- /// - architecture: cache architecture suffix; `arm64e` for every device
- /// this project targets.
+ /// - architecture: explicit suffix, or nil to discover the cache.
/// - captureUndo: start capturing the original bytes of every write into
/// an undo log, retrievable with ``takeUndoLog()``. Off by default.
- public init(directory: URL, architecture: String = "arm64e", captureUndo: Bool = false) throws {
+ public init(directory: URL, architecture: String? = nil, captureUndo: Bool = false) throws {
self.directory = directory
+ let architecture = String(Self.mainCacheURL(in: directory, architecture: architecture).lastPathComponent
+ .dropFirst("dyld_shared_cache_".count))
self.architecture = architecture
undoCaptureLog = captureUndo ? DyldSharedCacheUndoLog() : nil
chunkURLs = try Self.enumerateChunks(in: directory, architecture: architecture)
@@ -162,6 +163,17 @@ public final class DyldSharedCacheChunkSet {
directory.appendingPathComponent("dyld_shared_cache_\(architecture).symbols")
}
+ /// Prefers arm64e when both cache variants exist.
+ public static func mainCacheURL(in directory: URL, architecture: String? = nil) -> URL {
+ if let architecture {
+ return directory.appendingPathComponent("dyld_shared_cache_\(architecture)")
+ }
+ let standard = directory.appendingPathComponent("dyld_shared_cache_arm64e")
+ let x1 = directory.appendingPathComponent("dyld_shared_cache_arm64e_x1")
+ return !FileManager.default.fileExists(atPath: standard.path)
+ && FileManager.default.fileExists(atPath: x1.path) ? x1 : standard
+ }
+
/// Lowest and highest address the cache covers.
public var addressRange: Range<UInt64> {
(mappings.first?.address ?? 0) ..< (mappings.map(\.endAddress).max() ?? 0)
@@ -517,7 +529,7 @@ public final class DyldSharedCacheChunkSet {
let prefix = "dyld_shared_cache_\(architecture)"
let names = try FileManager.default
.contentsOfDirectory(atPath: directory.path)
- .filter { $0.hasPrefix(prefix) }
+ .filter { $0 == prefix || $0.hasPrefix(prefix + ".") }
.filter { !$0.hasSuffix(".symbols") && !$0.hasSuffix(".map") }
// Base file first, then numerically by sub-cache index. Files whose
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheUndoLog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheUndoLog.swift
index cca3e509..a7c539b6 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheUndoLog.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheUndoLog.swift
@@ -207,10 +207,17 @@ public struct DyldSharedCacheUndoLog: Codable, Sendable, Hashable {
) throws -> [DyldSharedCacheWriteSpan] {
try validate(in: directory, patchIDs: patchIDs)
var spans: [DyldSharedCacheWriteSpan] = []
+ var openChunk: String?, openHandle: FileHandle?
+ defer { try? openHandle?.close() }
for record in records(forPatchIDs: patchIDs).reversed() {
- let url = directory.appendingPathComponent(record.chunk)
- let handle = try FileHandle(forUpdating: url)
- defer { try? handle.close() }
+ let handle: FileHandle
+ if openChunk == record.chunk, let existing = openHandle {
+ handle = existing
+ } else {
+ try? openHandle?.close()
+ handle = try FileHandle(forUpdating: directory.appendingPathComponent(record.chunk))
+ openChunk = record.chunk; openHandle = handle
+ }
try handle.seek(toOffset: UInt64(record.fileOffset))
try handle.write(contentsOf: record.original)
spans.append(DyldSharedCacheWriteSpan(vma: record.vma, length: record.original.count))
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheArm64eX1BootstrapPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheArm64eX1BootstrapPatcher.swift
new file mode 100644
index 00000000..83396bb2
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheArm64eX1BootstrapPatcher.swift
@@ -0,0 +1,390 @@
+import CryptoKit
+import Foundation
+import MachOKit
+import VPhonePatchKit
+
+public enum DyldSharedCacheArm64eX1BootstrapPatcher {
+ struct Write {
+ let address: UInt64
+ let word: UInt32
+ }
+
+ /// Cold-boot evidence for this closure is recorded in Research/0_binary_patch_comparison.md.
+ static let bootstrapImages: Set<String> = [
+ "/usr/lib/libSystem.B.dylib",
+ "/usr/lib/system/libsystem_kernel.dylib",
+ "/usr/lib/system/libsystem_platform.dylib",
+ "/usr/lib/system/libsystem_pthread.dylib",
+ "/usr/lib/system/libsystem_c.dylib",
+ "/usr/lib/system/libsystem_sanitizers.dylib",
+ "/usr/lib/system/libsystem_malloc.dylib",
+ "/usr/lib/system/libsystem_featureflags.dylib",
+ "/usr/lib/system/libcorecrypto.dylib",
+ "/usr/lib/dyld",
+ "/usr/lib/system/libdyld.dylib",
+ "/usr/lib/system/libsystem_blocks.dylib",
+ "/usr/lib/system/libdispatch.dylib",
+ "/usr/lib/libobjc.A.dylib",
+ "/usr/lib/system/libmacho.dylib",
+ "/usr/lib/system/libxpc.dylib",
+ "/usr/lib/system/libsystem_trace.dylib",
+ "/usr/lib/system/libsystem_darwin.dylib",
+ "/usr/lib/objc/libobjcMsgSend.dylib",
+ "/usr/lib/objc/libobjcMsgSend5.dylib",
+ "/usr/lib/system/libsystem_containermanager.dylib",
+ "/usr/lib/system/libsystem_sandbox.dylib",
+ "/usr/lib/libc++.1.dylib",
+ "/usr/lib/libc++abi.dylib",
+ "/usr/lib/swift/libswiftCore.dylib",
+ "/usr/lib/swift/libswift_Concurrency.dylib",
+ "/usr/lib/system/libsystem_notify.dylib",
+ "/usr/lib/system/libsystem_info.dylib",
+ "/usr/lib/system/libsystem_collections.dylib",
+ "/usr/lib/system/libsystem_coreservices.dylib",
+ "/usr/lib/system/libsystem_asl.dylib",
+ "/usr/lib/system/libsystem_configuration.dylib",
+ "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation",
+ "/System/Library/Frameworks/Foundation.framework/Foundation",
+ "/System/Library/Frameworks/Network.framework/Network",
+ "/System/Library/Frameworks/IOKit.framework/Versions/A/IOKit",
+ "/System/Library/PrivateFrameworks/APFS.framework/APFS",
+ "/usr/lib/swift/libswiftDispatch.dylib",
+ ]
+
+ public static func patch(
+ directory: URL,
+ dryRun: Bool = false,
+ captureUndo: Bool = false,
+ onUndo: (DyldSharedCacheUndoLog) -> Void = { _ in },
+ log: @escaping (String) -> Void = { print($0) },
+ ) throws {
+ let chunks = try DyldSharedCacheChunkSet(
+ directory: directory,
+ captureUndo: captureUndo || !dryRun,
+ )
+ guard chunks.mainCacheURL.lastPathComponent.hasSuffix("arm64e_x1") else {
+ log(" [·] X1 bootstrap cache: not an X1 cache")
+ return
+ }
+
+ let cache = try FullDyldCache(url: chunks.mainCacheURL)
+ guard let infos = cache.imageInfos else {
+ throw PatcherError.invalidFormat("X1 cache has no images")
+ }
+ var selected: [(address: UInt64, path: String)] = []
+ var seen = Set<UInt64>()
+ for info in infos where seen.insert(info.address).inserted {
+ guard let path = info.path(in: cache), bootstrapImages.contains(path) else { continue }
+ selected.append((info.address, path))
+ }
+ guard Set(selected.map(\.path)) == bootstrapImages else {
+ let missing = bootstrapImages.subtracting(selected.map(\.path)).sorted()
+ throw PatcherError.invalidFormat(
+ "required X1 bootstrap cache images are missing: \(missing.joined(separator: ", "))",
+ )
+ }
+ let coreCrypto = selected.first { $0.path == "/usr/lib/system/libcorecrypto.dylib" }!
+
+ var writes: [Write] = []
+ var unvisited = 0
+ for image in selected {
+ let result = try planImage(at: image.address, in: chunks)
+ unvisited += result.unvisitedCandidates
+ writes += result.records.map {
+ Write(
+ address: UInt64($0.fileOffset),
+ word: $0.patchedBytes.loadLE(UInt32.self, at: 0),
+ )
+ }
+ log(" [.] X1 bootstrap cache: \(image.path): \(result.records.count) instructions, \(result.unvisitedCandidates) unvisited")
+ }
+ writes.sort { $0.address < $1.address }
+ log(" [*] X1 bootstrap cache: \(selected.count) image(s), \(writes.count) rewrites, \(unvisited) unvisited candidates")
+ guard !dryRun else { return }
+
+ do {
+ var index = 0
+ var groups = 0
+ var pageSizes: [URL: Int] = [:]
+ while index < writes.count {
+ let first = index
+ let start = writes[index].address
+ let firstChunk = try chunks.fileRange(of: .init(vma: start, length: 4)).chunkURL
+ let pageSize: Int
+ if let known = pageSizes[firstChunk] {
+ pageSize = known
+ } else {
+ guard let directory = try DyldSharedCacheCodeSignature.readCodeDirectory(ofChunk: firstChunk) else {
+ throw PatcherError.invalidFormat("X1 bootstrap code chunk has no supported signature")
+ }
+ pageSize = directory.pageSize
+ pageSizes[firstChunk] = pageSize
+ }
+ index += 1
+ while index < writes.count {
+ let previous = writes[index - 1]
+ let next = writes[index]
+ if next.address == previous.address {
+ guard next.word == previous.word else {
+ throw PatcherError.invalidFormat("conflicting X1 bootstrap rewrites")
+ }
+ index += 1
+ continue
+ }
+ guard start / UInt64(pageSize) == next.address / UInt64(pageSize),
+ let range = try? chunks.fileRange(
+ of: .init(vma: start, length: Int(next.address + 4 - start)),
+ ),
+ range.chunkURL == firstChunk
+ else { break }
+ index += 1
+ }
+
+ let length = Int(writes[index - 1].address + 4 - start)
+ let before = try chunks.bytesAtVMA(start, length: length)
+ var after = before
+ var changed = 0
+ for write in writes[first ..< index] {
+ let offset = Int(write.address - start)
+ let replacement = ARM64.encodeU32(write.word)
+ if after.subdata(in: offset ..< offset + 4) != replacement { changed += 1 }
+ after.replaceSubrange(offset ..< offset + 4, with: replacement)
+ }
+ if before != after {
+ try chunks.write(at: start, after)
+ groups += 1
+ log(" 0x\(String(start, radix: 16)): \(changed) instruction(s) [\(FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap)]")
+ }
+ }
+ try refreshCoreCryptoIntegrity(at: coreCrypto.address, in: chunks, log: log)
+ let attestation = try DyldSharedCacheCodeSignature.reattestRecordedWrites(in: chunks, log: log)
+ guard attestation.isFullyAttested else {
+ throw PatcherError.invalidFormat(
+ "X1 bootstrap re-attestation skipped \(attestation.skipped.count) pages",
+ )
+ }
+ onUndo(chunks.takeUndoLog()!)
+ log(" [+] X1 bootstrap cache: \(writes.count) instruction rewrites in \(groups) page run(s)")
+ } catch {
+ var undo = chunks.takeUndoLog()!
+ if !undo.records.isEmpty {
+ undo.stamp(patchID: FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap)
+ let spans = try undo.restore(patchIDs: undo.patchIDs, in: directory, log: log)
+ _ = try DyldSharedCacheCodeSignature.reattest(
+ in: chunks,
+ modifiedSpans: spans,
+ log: log,
+ )
+ }
+ throw error
+ }
+ }
+
+ static func refreshCoreCryptoIntegrity(
+ at address: UInt64,
+ in chunks: DyldSharedCacheChunkSet,
+ log: (String) -> Void,
+ ) throws {
+ let prefix = try chunks.bytesAtVMA(address, length: 32)
+ guard prefix.loadLE(UInt32.self, at: 0) == 0xFEED_FACF else {
+ throw PatcherError.invalidFormat("cached corecrypto has no Mach-O header")
+ }
+ let commandBytes = Int(prefix.loadLE(UInt32.self, at: 20))
+ guard commandBytes <= 1_048_576 else {
+ throw PatcherError.invalidFormat("oversized cached corecrypto commands")
+ }
+ let header = try chunks.bytesAtVMA(address, length: 32 + commandBytes)
+ let sections = MachOParser.parseSections(from: header)
+ guard let text = sections["__TEXT,__text"], text.size > 0,
+ let expected = sections["__TEXT,__fips_hmacs"], expected.size == SHA256.byteCount,
+ let textLength = Int(exactly: text.size)
+ else {
+ throw PatcherError.invalidFormat("cached corecrypto FIPS sections are missing or malformed")
+ }
+ let code = try chunks.bytesAtVMA(text.address, length: textLength)
+ let key = SymmetricKey(data: Data(repeating: 0, count: SHA256.byteCount))
+ let digest = Data(HMAC<SHA256>.authenticationCode(for: code, using: key))
+ let stored = try chunks.bytesAtVMA(expected.address, length: SHA256.byteCount)
+ guard stored != digest else {
+ log(" [=] X1 bootstrap cache: corecrypto FIPS HMAC already matches")
+ return
+ }
+ try chunks.write(at: expected.address, digest)
+ log(" [+] X1 bootstrap cache: refreshed corecrypto FIPS HMAC")
+ }
+
+ static func planImage(
+ at address: UInt64,
+ in chunks: DyldSharedCacheChunkSet,
+ ) throws -> CustomFirmwareArm64eX1.Result {
+ let prefix = try chunks.bytesAtVMA(address, length: 32)
+ guard prefix.loadLE(UInt32.self, at: 0) == 0xFEED_FACF else {
+ throw PatcherError.invalidFormat("cache image has no Mach-O header")
+ }
+ guard prefix.loadLE(UInt32.self, at: 8) & 0x00FF_FFFF == 12 else {
+ return .init(records: [], unvisitedCandidates: 0)
+ }
+ let commandBytes = Int(prefix.loadLE(UInt32.self, at: 20))
+ guard commandBytes <= 1_048_576 else {
+ throw PatcherError.invalidFormat("oversized cache image commands")
+ }
+ let header = try chunks.bytesAtVMA(address, length: 32 + commandBytes)
+ let segments = MachOParser.parseSegments(from: header)
+ let allSections = Array(MachOParser.parseSections(from: header).values)
+ let sections = allSections.filter {
+ ($0.sectionName == "__text" || $0.flags & 0x8000_0400 != 0) && $0.size > 0
+ }
+ if sections.isEmpty { return .init(records: [], unvisitedCandidates: 0) }
+ guard let text = segments.first(where: { $0.name == "__TEXT" }),
+ let linkedit = segments.first(where: { $0.name == "__LINKEDIT" })
+ else {
+ throw PatcherError.invalidFormat("X1 cached text/linkedit missing")
+ }
+
+ func metadata(_ offset: UInt64, _ length: Int) throws -> Data {
+ guard offset >= linkedit.fileOffset,
+ UInt64(length) <= linkedit.fileSize,
+ offset - linkedit.fileOffset <= linkedit.fileSize - UInt64(length)
+ else { throw PatcherError.invalidFormat("cached X1 metadata outside linkedit") }
+ return try chunks.bytesAtVMA(
+ linkedit.vmAddr + offset - linkedit.fileOffset,
+ length: length,
+ )
+ }
+
+ var position = 32
+ var seeds: [Int] = []
+ var excluded: [Range<Int>] = []
+ for _ in 0 ..< header.loadLE(UInt32.self, at: 16) {
+ guard position + 8 <= header.count else {
+ throw PatcherError.invalidFormat("truncated cache commands")
+ }
+ let command = header.loadLE(UInt32.self, at: position)
+ let size = Int(header.loadLE(UInt32.self, at: position + 4))
+ guard size >= 8, size <= header.count - position else {
+ throw PatcherError.invalidFormat("invalid cache command")
+ }
+ if command == 0x26 || command == 0x29 {
+ guard size >= 16 else {
+ throw PatcherError.invalidFormat("short cache linkedit command")
+ }
+ let offset = UInt64(header.loadLE(UInt32.self, at: position + 8))
+ let length = Int(header.loadLE(UInt32.self, at: position + 12))
+ if length > 0 {
+ let bytes = try metadata(offset, length)
+ if command == 0x26 {
+ var cursor = 0
+ var current = text.vmAddr
+ while cursor < bytes.count {
+ var delta: UInt64 = 0
+ var shift = 0
+ while true {
+ guard cursor < bytes.count, shift < 63 else {
+ throw PatcherError.invalidFormat("invalid cached function starts")
+ }
+ let byte = bytes[cursor]
+ cursor += 1
+ delta |= UInt64(byte & 0x7F) << shift
+ if byte & 0x80 == 0 { break }
+ shift += 7
+ }
+ if delta == 0 { break }
+ let (next, overflow) = current.addingReportingOverflow(delta)
+ guard !overflow, let entry = Int(exactly: next) else {
+ throw PatcherError.invalidFormat("cached function address overflow")
+ }
+ current = next
+ seeds.append(entry)
+ }
+ } else {
+ guard bytes.count % 8 == 0 else {
+ throw PatcherError.invalidFormat("invalid cached data-in-code")
+ }
+ for entry in stride(from: 0, to: bytes.count, by: 8) {
+ let offset = UInt64(bytes.loadLE(UInt32.self, at: entry))
+ let length = Int(bytes.loadLE(UInt16.self, at: entry + 4))
+ guard let segment = segments.first(where: {
+ offset >= $0.fileOffset && offset - $0.fileOffset < $0.fileSize
+ }) else {
+ throw PatcherError.invalidFormat("cached data-in-code offset unmapped")
+ }
+ let start = Int(segment.vmAddr + offset - segment.fileOffset)
+ excluded.append(start ..< start + length)
+ }
+ }
+ }
+ }
+ position += size
+ }
+ guard !seeds.isEmpty else {
+ throw PatcherError.invalidFormat("X1 cache image has no function starts")
+ }
+ seeds += try CustomFirmwareArm64eX1.exceptionEntries(
+ sections: allSections,
+ imageBase: text.vmAddr,
+ readMemory: { try chunks.bytesAtVMA($0, length: $1) },
+ ).map { address in
+ guard let value = Int(exactly: address) else {
+ throw PatcherError.invalidFormat("X1 exception landing address overflow")
+ }
+ return value
+ }
+ let ranges = try sections.map {
+ (address: Int($0.address), data: try chunks.bytesAtVMA($0.address, length: Int($0.size)))
+ }
+ var pointerCaches: [URL: DyldCache] = [:]
+ var mainHeader: DyldCacheHeader?
+ return try CustomFirmwareArm64eX1.planCode(
+ ranges: ranges,
+ seeds: seeds,
+ excluded: excluded,
+ identifier: FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap,
+ readMemory: { address, length in
+ return try chunks.bytesAtVMA(UInt64(address), length: length)
+ },
+ authenticatedPointer: { address, diversity in
+ let range = try chunks.fileRange(of: .init(vma: address, length: 8))
+ let header: DyldCacheHeader
+ if let loaded = mainHeader {
+ header = loaded
+ } else {
+ header = try DyldCache(url: chunks.mainCacheURL).header
+ mainHeader = header
+ }
+ let cache: DyldCache
+ if let known = pointerCaches[range.chunkURL] {
+ cache = known
+ } else {
+ cache = try DyldCache(subcacheUrl: range.chunkURL, mainCacheHeader: header)
+ pointerCaches[range.chunkURL] = cache
+ }
+ guard let mapping = cache.mappingAndSlideInfos?.first(where: {
+ address >= $0.address && address - $0.address < $0.size
+ }), mapping.slideInfoVersion(in: cache) == .v5
+ else { return nil }
+ let word = try chunks.bytesAtVMA(address, length: 8).loadLE(UInt64.self, at: 0)
+ return try authenticatedTargetV5(
+ word: word,
+ base: header.sharedRegionStart,
+ diversity: diversity,
+ )
+ },
+ )
+ }
+
+ static func authenticatedTargetV5(
+ word: UInt64,
+ base: UInt64,
+ diversity: UInt16,
+ ) throws -> UInt64? {
+ guard word >> 63 == 1,
+ (word >> 34) & 0xFFFF == UInt64(diversity),
+ (word >> 50) & 3 == 0
+ else { return nil }
+ let (target, overflow) = base.addingReportingOverflow(word & ((1 << 34) - 1))
+ guard !overflow else {
+ throw PatcherError.invalidFormat("X1 authenticated pointer overflow")
+ }
+ return target
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheCameraPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheCameraPatcher.swift
index 68fee865..9ab7dfe3 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheCameraPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheCameraPatcher.swift
@@ -195,8 +195,7 @@ public enum DyldSharedCacheCameraPatcher {
/// caller passes; the Python takes it separately only because `ipsw`
/// wants a file.
/// - dryRun: report the sites and write nothing.
- /// - force: accept an entry point whose prologue is neither `pacibsp` nor
- /// the replacement. The Python's `--force`.
+ /// - force: accept an unknown prologue.
@discardableResult
public static func applyAll(
chunksDirectory: URL,
@@ -261,33 +260,13 @@ public enum DyldSharedCacheCameraPatcher {
let resolver = try DyldSharedCacheSymbolResolver(
mainCacheURL: symbolCacheURL ?? chunks.mainCacheURL,
)
- // Every symbol here is an ObjC class method, and those live only in the
- // stripped local-symbol table. Without it the six lookups would each
- // report "not found", which reads as "this build renamed them".
+ // ObjC class methods require the stripped local-symbol table.
try resolver.requireLocalSymbols()
let disassembler = ARM64Disassembler()
var sites: [Site] = []
- // Plan every family before writing any of them. Nothing in this loop
- // touches the cache.
- //
- // This used to write each site as it was classified, with one
- // re-attestation pass after the last family. Anything that threw after
- // the first write — a renamed AVF symbol, a prologue that is neither
- // `pacibsp` nor `mov w0,#3; ret` — left the NeutrinoCore sites on disk
- // with their code-signature slot hashes still describing the old bytes.
- // On `codeSigningMonitor == 2` hardware TXM checks those hashes per
- // page, so that cache SIGKILLs on the first demand-page-in of a
- // modified page: a half-patched cache that also fails to load.
- // Reproduced on two identical clones by nop-ing only the AVF entry
- // point — both patchers throw, but the old Swift left four pages of
- // `dyld_shared_cache_arm64e.15` stale where the Python left none.
- //
- // The Python avoids it by resolving both families up front and
- // re-attesting after each one. Planning everything first is stronger:
- // a failure here leaves the cache untouched rather than patched and
- // re-signed up to the failure point.
+ // Resolve and validate every site before mutating the cache.
for (index, family) in families.enumerated() {
log?("")
log?(" [\(index + 1)/\(families.count)] \(family.headline)")
@@ -388,18 +367,7 @@ public enum DyldSharedCacheCameraPatcher {
// MARK: - The prologue
- /// Decide whether an entry point may be rewritten, and whether it already was.
- ///
- /// Three shapes are acceptable, and the difference matters:
- ///
- /// * `pacibsp` — a pristine signed-prologue method. The expected case, and
- /// the only one the Python accepts without `--force`.
- /// * the replacement itself — this patcher's own output, so the run is a
- /// re-install. Reported, rewritten inertly, and re-attested, rather than
- /// raising the way three sibling DSC patchers used to on their own work.
- /// * anything at all, under `force`.
- ///
- /// - Returns: true when the entry point already held the replacement.
+ /// Accepts B-key prologues, this patcher's replacement, or `force`.
static func classifyPrologue(
_ bytes: Data,
at vma: UInt64,
@@ -411,7 +379,9 @@ public enum DyldSharedCacheCameraPatcher {
) throws -> Bool {
let decoded = disassembler.disassemble(bytes, at: vma, count: 2)
- if decoded.first?.mnemonic == "pacibsp" {
+ if let mnemonic = decoded.first?.mnemonic,
+ ["pacibsp", "pacibsppc", "pacnbibsppc"].contains(mnemonic)
+ {
return false
}
@@ -426,10 +396,11 @@ public enum DyldSharedCacheCameraPatcher {
?? "<undecodable>"
throw PatcherError.patchVerificationFailed(
"\(symbol) @ 0x\(String(vma, radix: 16, uppercase: true)): prologue is not "
- + "pacibsp (got \(head), bytes \(bytes.prefix(4).hex)); pass force to override",
+ + "an authenticated B-key stack prologue (got \(head), bytes \(bytes.prefix(4).hex)); "
+ + "pass force to override",
)
}
- log?(" [!] prologue is not pacibsp — forced")
+ log?(" [!] prologue is not an authenticated B-key stack prologue — forced")
return false
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swift
index 6fe82992..02adbd08 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swift
@@ -191,14 +191,14 @@ public enum DyldSharedCacheMaxSlidePatcher {
@discardableResult
public static func requireFitsAtSlideZero(
chunksDirectory: URL,
- architecture: String = "arm64e",
+ architecture: String? = nil,
kernelRegionSize: UInt64 = kernelSharedRegionSize,
) throws -> UInt64 {
let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory, architecture: architecture)
let header = try readHeader(
from: chunks,
at: headerVMA(of: chunks),
- chunkName: "dyld_shared_cache_\(architecture)",
+ chunkName: chunks.mainCacheURL.lastPathComponent,
)
guard header.sharedRegionSize <= kernelRegionSize else {
throw RegionOverflow(sharedRegionSize: header.sharedRegionSize, region: kernelRegionSize)
@@ -219,8 +219,7 @@ public enum DyldSharedCacheMaxSlidePatcher {
///
/// - Parameters:
/// - chunksDirectory: the directory of `dyld_shared_cache_<arch>*` chunks.
- /// - architecture: cache architecture suffix; `arm64e` on every device
- /// this project targets.
+ /// - architecture: explicit cache suffix, or nil to discover the cache.
/// - kernelRegionSize: the guest kernel's `SHARED_REGION_SIZE_ARM64`.
/// - dryRun: decide and report, but write nothing.
/// - force: clamp even when the cache already fits — the verb's `--force`,
@@ -229,7 +228,7 @@ public enum DyldSharedCacheMaxSlidePatcher {
@discardableResult
public static func patch(
chunksDirectory: URL,
- architecture: String = "arm64e",
+ architecture: String? = nil,
kernelRegionSize: UInt64 = kernelSharedRegionSize,
dryRun: Bool = false,
force: Bool = false,
@@ -237,8 +236,8 @@ public enum DyldSharedCacheMaxSlidePatcher {
onUndo: ((DyldSharedCacheUndoLog) -> Void)? = nil,
verbose: Bool = true,
) throws -> Result {
- let mainChunkName = "dyld_shared_cache_\(architecture)"
- let mainChunk = chunksDirectory.appendingPathComponent(mainChunkName)
+ let mainChunk = DyldSharedCacheChunkSet.mainCacheURL(in: chunksDirectory, architecture: architecture)
+ let mainChunkName = mainChunk.lastPathComponent
// Checked before the chunk set is built so the error names the file the
// Python's FileNotFoundError names, rather than the directory.
guard FileManager.default.fileExists(atPath: mainChunk.path) else {
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Process/KernelCustomFirmwarePatchArm64eX1.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Process/KernelCustomFirmwarePatchArm64eX1.swift
new file mode 100644
index 00000000..a9e82363
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Process/KernelCustomFirmwarePatchArm64eX1.swift
@@ -0,0 +1,188 @@
+// ARM64E_X1 admission; reveal procedure is in Research/0_binary_patch_comparison.md.
+
+import Foundation
+import VPhonePatchKit
+
+extension KernelCustomFirmwarePatcher {
+ @discardableResult
+ func patchArm64eX1Admission() -> Bool {
+ let identifier = "kernel-boot-arm64e_x1"
+ guard gate.isEnabled(identifier) else { return false }
+ guard let (start, end) = kernTextRange else { return false }
+
+ var grades: [(entry: Int, compare: Int)] = []
+ let raw = buffer.original
+ for block in stride(from: start, to: end, by: 0x4000) {
+ let scanStart = max(start, block - 16)
+ let stop = min(end, block + 0x4000 + 0x100)
+ let instructions = disasm.disassemble(raw.subdata(in: scanStart ..< stop), at: UInt64(scanStart))
+ for (index, instruction) in instructions.enumerated() where instruction.address >= UInt64(block) && instruction.address < UInt64(block + 0x4000) {
+ guard x1RegImmediate(instruction, mnemonic: "cmp", register: .w(1), immediate: 2),
+ index >= 3, index + 7 < instructions.count
+ else { continue }
+ let tail = Array(instructions[(index - 3) ... (index + 7)])
+ guard x1GradeTail(tail) else { continue }
+
+ // ml_grade_binary has no PAC prologue; anchor its entry on the per-CPU load and BL xref.
+ let compare = Int(instruction.address)
+ let prefix = disasm.disassemble(in: raw, at: max(start, compare - 0x100), count: min(0x100, compare - start) / 4)
+ let entries = prefix.filter { candidate in
+ guard candidate.mnemonic == "mrs", blIndex[Int(candidate.address)] != nil else { return false }
+ let head = disasm.disassemble(in: raw, at: Int(candidate.address), count: 3)
+ guard head.count == 3,
+ let register = head[0].detail?.operands.first?.reg,
+ let first = head[1].detail?.operands, first.count == 2,
+ first[0].type == .register, first[0].reg == register,
+ first[1].type == .memory, first[1].mem.base == register,
+ let second = head[2].detail?.operands, second.count == 2,
+ second[1].type == .memory, second[1].mem.base == register,
+ second[1].mem.disp == 8
+ else { return false }
+ return head[1].mnemonic == "ldr" && head[2].mnemonic == "ldr"
+ }
+ if entries.count == 1 { grades.append((Int(entries[0].address), compare)) }
+ }
+ }
+ guard grades.count == 1 else {
+ log(" [-] ARM64E_X1: ml_grade_binary not unique (\(grades.count))")
+ return false
+ }
+ let grade = grades[0]
+ var execSites: [(offset: Int, register: UInt32)] = []
+ for caller in blIndex[grade.entry] ?? [] {
+ let instructions = disasm.disassemble(in: raw, at: caller + 4, count: 32)
+ for index in instructions.indices where index >= 2 && index + 6 < instructions.count {
+ if let register = x1ExecPACGate(Array(instructions[(index - 2) ... (index + 6)])) {
+ execSites.append((Int(instructions[index].address), register))
+ }
+ }
+ }
+ guard execSites.count == 1 else {
+ log(" [-] ARM64E_X1: exec IMGPF_NOJOP gate not unique (\(execSites.count))")
+ return false
+ }
+
+ // The successful shared-region path retains subtype 2 for the existing auth pagers.
+ guard let shared = x1ExecSharedRegionGate(after: execSites[0].offset) else {
+ log(" [-] ARM64E_X1: exec shared-region PAC gate not unique")
+ return false
+ }
+ let sites: [(offset: Int, register: UInt32, name: String)] = [
+ (grade.compare, 1, "grade"),
+ (execSites[0].offset, execSites[0].register, "exec_ptrauth"),
+ (shared.offset, shared.register, "exec_shared_region"),
+ ]
+ guard let cave = findCodeCave(size: sites.count * 12) else {
+ log(" [-] ARM64E_X1: no executable cave")
+ return false
+ }
+ var writes: [(offset: Int, data: Data, name: String)] = []
+ for (index, site) in sites.enumerated() {
+ let trampoline = cave + index * 12
+ guard let entry = ARM64Encoder.encodeB(from: site.offset, to: trampoline),
+ let cmp = ARM64Encoder.encodeCmpWImmediate(rn: site.register, imm12: 12),
+ let ccmp = ARM64Encoder.encodeCcmpWImmediate(rn: site.register, imm5: 2, nzcv: 6, condition: .ne),
+ let resume = ARM64Encoder.encodeB(from: trampoline + 8, to: site.offset + 4)
+ else { return false }
+ // NZCV=0110 makes subtype 12 equivalent to CMP Wn,#2 with Wn=2.
+ writes.append((trampoline, cmp + ccmp + resume, site.name + ".cave"))
+ writes.append((site.offset, entry, site.name))
+ }
+ for write in writes {
+ emit(write.offset, write.data, patchID: identifier + "." + write.name,
+ virtualAddress: fileOffsetToVA(write.offset),
+ description: "ARM64E_X1 subtype 12 or legacy subtype 2 [\(write.name)]")
+ }
+ return true
+ }
+
+ private func x1RegImmediate(_ instruction: ARM64Instruction, mnemonic: String, register: ARM64Register, immediate: Int64) -> Bool {
+ guard instruction.mnemonic == mnemonic, let ops = instruction.detail?.operands, ops.count == 2 else { return false }
+ return ops[0].type == .register && ops[0].reg == register && ops[1].type == .immediate && ops[1].imm == immediate
+ }
+
+ private func x1ExecSharedRegionGate(after execCompare: Int) -> (offset: Int, register: UInt32)? {
+ let instructions = disasm.disassemble(in: buffer.original, at: execCompare + 4,
+ count: min(0x800, buffer.original.count - execCompare - 4) / 4)
+ var hits: [(Int, UInt32)] = []
+ for index in instructions.indices where index >= 2 && index + 3 < instructions.count {
+ let i = Array(instructions[(index - 2) ... (index + 3)])
+ guard i[0].mnemonic == "ldr", let load = i[0].detail?.operands, load.count == 2,
+ load[0].type == .register, load[1].type == .memory,
+ i[1].mnemonic == "and", let mask = i[1].detail?.operands, mask.count == 3,
+ mask[0].reg == load[0].reg, mask[1].reg == load[0].reg,
+ mask[2].type == .immediate, mask[2].imm == 0x0FFF_FFFF,
+ x1RegImmediate(i[2], mnemonic: "cmp", register: load[0].reg, immediate: 2),
+ let reject = x1BranchTarget(i[3], mnemonic: "b.ne"),
+ i[4].mnemonic == "ldr", let flags = i[4].detail?.operands, flags.count == 2,
+ flags[1].type == .memory, flags[1].mem.disp == 0x48,
+ x1BranchTarget(i[5], mnemonic: "tbnz") == reject,
+ let bit = i[5].detail?.operands, bit.count == 3,
+ bit[0].reg == flags[0].reg, bit[1].type == .immediate, bit[1].imm == 31
+ else { continue }
+ let failure = disasm.disassemble(in: buffer.original, at: reject, count: 1)
+ let success = disasm.disassemble(in: buffer.original, at: reject - 12, count: 1)
+ guard failure.count == 1, success.count == 1,
+ let subtypeRegister = failure[0].detail?.operands.first?.reg,
+ x1RegImmediate(failure[0], mnemonic: "mov", register: subtypeRegister, immediate: 0),
+ x1RegImmediate(success[0], mnemonic: "mov", register: subtypeRegister, immediate: 2),
+ let register = (0 ... 30).first(where: { ARM64Register.w($0) == load[0].reg })
+ else { continue }
+ hits.append((Int(i[2].address), UInt32(register)))
+ }
+ return hits.count == 1 ? hits[0] : nil
+ }
+
+ private func x1BranchTarget(_ instruction: ARM64Instruction, mnemonic: String) -> Int? {
+ guard instruction.mnemonic == mnemonic, let op = instruction.detail?.operands.last, op.type == .immediate else { return nil }
+ return Int(exactly: op.imm)
+ }
+
+ private func x1ReturnsGrade(at offset: Int, grade: Int64) -> Bool {
+ let instructions = disasm.disassemble(in: buffer.original, at: offset, count: 2)
+ return instructions.count == 2 && x1RegImmediate(instructions[0], mnemonic: "mov", register: .w(0), immediate: grade)
+ && instructions[1].mnemonic == "ret"
+ }
+
+ private func x1GradeTail(_ i: [ARM64Instruction]) -> Bool {
+ guard let all = x1BranchTarget(i[0], mnemonic: "cbz"), i[0].detail?.operands.first?.reg == .w(1),
+ x1ReturnsGrade(at: all, grade: 9),
+ x1RegImmediate(i[1], mnemonic: "cmp", register: .w(1), immediate: 1),
+ let v8 = x1BranchTarget(i[2], mnemonic: "b.eq"), x1ReturnsGrade(at: v8, grade: 10),
+ let reject = x1BranchTarget(i[4], mnemonic: "b.ne"), x1ReturnsGrade(at: reject, grade: 0),
+ x1RegImmediate(i[5], mnemonic: "tst", register: .w(2), immediate: 0x0F00_0000),
+ i[6].mnemonic == "mov", let mov = i[6].detail?.operands, mov.count == 2,
+ mov[0].type == .register, mov[1].type == .immediate, mov[1].imm == 11,
+ i[7].mnemonic == "cinc", let cinc = i[7].detail?.operands, cinc.count == 2,
+ cinc[0].reg == mov[0].reg, cinc[1].reg == mov[0].reg,
+ i[8].mnemonic == "and", let result = i[8].detail?.operands, result.count == 3,
+ result[0].reg == .w(0), result[1].reg == mov[0].reg, result[2].reg == .w(2),
+ i[9].mnemonic == "ret"
+ else { return false }
+ return true
+ }
+
+ private func x1ExecPACGate(_ i: [ARM64Instruction]) -> UInt32? {
+ guard i[0].mnemonic == "ldr", let load = i[0].detail?.operands, load.count == 2,
+ load[0].type == .register, load[1].type == .memory, load[1].mem.disp == 8,
+ i[1].mnemonic == "and", let mask = i[1].detail?.operands, mask.count == 3,
+ mask[0].reg == load[0].reg, mask[1].reg == load[0].reg,
+ mask[2].type == .immediate, mask[2].imm == 0x0FFF_FFFF,
+ x1RegImmediate(i[2], mnemonic: "cmp", register: load[0].reg, immediate: 2),
+ let disabled = x1BranchTarget(i[3], mnemonic: "b.ne"),
+ i[4].mnemonic == "and", let clear = i[4].detail?.operands, clear.count == 3,
+ clear[2].type == .immediate, clear[2].imm == 0x7FFF_FFFF,
+ let common = x1BranchTarget(i[5], mnemonic: "b"),
+ x1RegImmediate(i[6], mnemonic: "mov", register: .w(0), immediate: 86)
+ else { return nil }
+ let set = disasm.disassemble(in: buffer.original, at: disabled, count: 1)
+ let store = disasm.disassemble(in: buffer.original, at: common, count: 1)
+ guard set.count == 1, set[0].mnemonic == "orr", let ops = set[0].detail?.operands, ops.count == 3,
+ ops[0].reg == clear[0].reg, ops[1].reg == clear[1].reg,
+ ops[2].type == .immediate, UInt32(truncatingIfNeeded: ops[2].imm) == 0x8000_0000,
+ store.count == 1, store[0].mnemonic == "str", let str = store[0].detail?.operands, str.count == 2,
+ str[0].reg == clear[0].reg, str[1].type == .memory, str[1].mem.disp == 0x48
+ else { return nil }
+ return (0 ... 30).first(where: { ARM64Register.w($0) == load[0].reg }).map(UInt32.init)
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift
index b8be20c1..25df12f3 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift
@@ -82,6 +82,7 @@ public final class KernelCustomFirmwarePatcher: KernelCustomFirmwarePatcherBase,
patchIoucFailedSandbox()
patchDiskImages2ClientAbi()
patchSharedRegionSize()
+ patchArm64eX1Admission()
} else if applyParavirtUserClients {
patchParavirtUserClientsNarrow()
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareBootChainPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareBootChainPatchSet.swift
index 109ab6b0..2ed81912 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareBootChainPatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareBootChainPatchSet.swift
@@ -1,13 +1,3 @@
-// FirmwareBootChainPatchSet.swift — Manifest for the signed boot chain.
-//
-// AVPBooter, iBSS, iBEC, LLB and TXM. Almost everything here is boot-essential:
-// the chain either accepts the resealed images or the VM never reaches the
-// kernel. The two that are not — the serial labels and the boot-args string —
-// only change what the guest logs and how it is told to start.
-//
-// Identifiers are the record identifiers the patchers already emit, so a record
-// in a log and a checkbox in the UI name the same thing.
-
import Foundation
import VPhonePatchKit
@@ -17,7 +7,7 @@ public enum FirmwareBootChainPatchSet {
public static let manifest = VPhonePatchSetManifest(
identifier: identifier,
name: "Boot Chain",
- summary: "AVPBooter, iBSS, iBEC, LLB and TXM image-4 and boot-policy patches",
+ summary: "Boot images, restore-environment compatibility, and boot-policy patches",
patches: [
// MARK: AVPBooter
@@ -175,6 +165,20 @@ public enum FirmwareBootChainPatchSet {
target: .firmware(.txm),
bootEssential: true,
),
+
+ // MARK: Restore environment
+
+ VPhonePatchDeclaration(
+ identifier: RestoreRamDiskSealPatcher.patchIdentifier,
+ title: "iOS 27 APFS seal hash",
+ summary: "Makes the cloudOS 26.4 restore ramdisk calculate the iOS 27 root hash with sha3_256_4k and admits the re-attested sealing tool through its restore trust cache.",
+ target: .firmware(.restoreRamDisk),
+ applicability: VPhonePatchApplicability(
+ iOSBase: .major(27),
+ cloudOS: .release(major: 26, minor: 4),
+ ),
+ bootEssential: true,
+ ),
],
provides: ["vphone.bootchain"],
)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
index 67d6c890..accf2f3f 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
@@ -23,6 +23,11 @@ public enum FirmwareGuestSystemPatchSet {
public static let installCoordinationPersonaMarker = "/usr/lib/vphone-installcoordination-persona-lookup"
public static let gyroscope = "system-backboardd-cfw-gyroscope"
public static let attitude = "system-apps-cfw-attitude"
+ public static let arm64eX1DyldBootstrap = "system-dyld-boot-arm64e_x1_bootstrap"
+ public static let arm64eX1CacheBootstrap = "dyld-boot-arm64e_x1_bootstrap"
+ public static let arm64eX1LaunchdBootstrap = "system-launchd-boot-arm64e_x1_bootstrap"
+ public static let arm64eX1FsckBootstrap = "system-fsck-boot-arm64e_x1_bootstrap"
+ public static let arm64eX1MountBootstrap = "system-mount-boot-arm64e_x1_bootstrap"
public static let paravirtGPUIndexOffset = "system-paravirt_gpu-cfw-heap_index_offset"
public static let paravirtGPUDriverPath =
@@ -159,6 +164,47 @@ public enum FirmwareGuestSystemPatchSet {
// MARK: System Daemons
+ VPhonePatchDeclaration(
+ identifier: arm64eX1DyldBootstrap,
+ title: "ARM64E_X1 dyld bootstrap",
+ summary: "Lowers X1 instructions in dyld so launchd can install the host exception handler that translates later faults on demand.",
+ target: .guestExecutable(path: "/usr/lib/dyld"),
+ applicability: ios27,
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: arm64eX1CacheBootstrap,
+ title: "ARM64E_X1 cache bootstrap",
+ summary: "Lowers only libSystem's pre-constructor X1 code so launchd can install the global on-demand instruction handler.",
+ target: .dyldSharedCache,
+ applicability: ios27,
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: arm64eX1LaunchdBootstrap,
+ title: "ARM64E_X1 launchd bootstrap",
+ summary: "Lowers PID 1 itself so its injected on-demand instruction handler can become active for the rest of userland.",
+ target: .guestExecutable(path: "/sbin/launchd"),
+ applicability: ios27,
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: arm64eX1FsckBootstrap,
+ title: "ARM64E_X1 fsck bootstrap",
+ summary: "Lowers the boot fsck wrapper so its forked checker does not inherit runtime-modified signed pages.",
+ target: .guestExecutable(path: "/sbin/fsck"),
+ applicability: ios27,
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: arm64eX1MountBootstrap,
+ title: "ARM64E_X1 mount bootstrap",
+ summary: "Lowers the boot mount wrapper so its forked mount helpers do not inherit runtime-modified signed pages.",
+ target: .guestExecutable(path: "/sbin/mount"),
+ applicability: ios27,
+ bootEssential: true,
+ ),
+
VPhonePatchDeclaration(
identifier: "system-seputil-boot-gigalocker_uuid",
title: "seputil Gigalocker UUID",
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift
index 364290ba..6e2c572f 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift
@@ -240,6 +240,15 @@ public enum FirmwareKernelCustomFirmwarePatchSet {
// MARK: iOS 27 Userland
+ VPhonePatchDeclaration(
+ identifier: "kernel-boot-arm64e_x1",
+ title: "ARM64E_X1 admission",
+ summary: "Admits subtype-12 binaries, enables exec PAC and selects the ARM64E authenticated shared region required by the iOS 27 userland.",
+ target: .firmware(.kernelcache),
+ applicability: ios27,
+ bootEssential: true,
+ ),
+
VPhonePatchDeclaration(
identifier: "kernel-boot-di2",
title: "DiskImages2 client ABI",
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchDrift.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchDrift.swift
index b5740356..44d63318 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchDrift.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchDrift.swift
@@ -59,7 +59,7 @@ public enum FirmwarePatchDrift {
/// in boot order. AVPBooter is not among them: it never leaves the VM
/// folder, and `fw patch` records it itself.
public static let restoredComponents: [VPhoneFirmwareComponent] = [
- .iBSS, .iBEC, .llb, .txm, .kernelcache, .deviceTree,
+ .iBSS, .iBEC, .llb, .txm, .restoreRamDisk, .kernelcache, .deviceTree,
]
/// What a restore put into each component it wrote: the plan's enabled
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
index 3122cac6..c30622c8 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
@@ -54,7 +54,6 @@ public enum FirmwarePatchSetCatalog {
///
/// `dyld-exp-mis_trust_auth` is off because a userspace hook now does its
/// job: see ``misTrustAuthPatch``.
- ///
/// `kernel-cfw-paravirt_user_clients` and `kernel-cfw-display_promotion`
/// are not in this list: `standard` turns them on. See
/// ``paravirtUserClientsPatch`` and ``proMotionPatch``.
@@ -215,8 +214,10 @@ public enum FirmwarePatchSetCatalog {
/// The iOS payloads, hooks and shared-cache patches an Apple TV guest has no
/// validated port of: display, camera, audio, sensors, the GPU driver (a
- /// plain-arm64 HD cannot load it), debugserver and the environment hooks.
+ /// plain-arm64 HD cannot load it), debugserver, the environment hooks, and
+ /// the iPhone 19 ARM64E_X1 boot path.
public static let tvOSBlockedPatches: Set<String> = [
+ FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap,
"dyld-boot-iomfb_force_kern",
"dyld-boot-iomfb_swapend",
"dyld-boot-lockdown_mode",
@@ -224,22 +225,28 @@ public enum FirmwarePatchSetCatalog {
"dyld-boot-maxslide",
"dyld-boot-xpc_lwcr",
"dyld-cfw-camera",
+ "kernel-boot-arm64e_x1",
"preboot-cfw-devicetree_board_audio",
"preboot-cfw-devicetree_haptics",
"preboot-cfw-devicetree_iphone_product",
"preboot-cfw-devicetree_microphone_array",
+ RestoreRamDiskSealPatcher.patchIdentifier,
"system-apps-cfw-attitude",
"system-backboardd-cfw-gyroscope",
"system-campo-cfw-entitlements",
"system-debugserver-cfw-install",
+ FirmwareGuestSystemPatchSet.arm64eX1DyldBootstrap,
"system-diskimagesiod-cfw-is_mount_complete",
"system-extensions-boot-gpu_bundle",
+ FirmwareGuestSystemPatchSet.arm64eX1FsckBootstrap,
"system-installcoordination_proxy-cfw-persona_lookup",
"system-jetsamproperties-cfw-disable_allowed",
+ FirmwareGuestSystemPatchSet.arm64eX1LaunchdBootstrap,
"system-launchd-boot-jetsam_panic_guard_bypass",
"system-launchdaemons-boot-environment",
"system-locationd-cfw-disable_auto_cohort",
"system-mobileactivationd-boot-should_hactivate",
+ FirmwareGuestSystemPatchSet.arm64eX1MountBootstrap,
"system-paravirt_gpu-cfw-heap_index_offset",
"system-systemversion-cfw-build_version",
"system-virtiosound-cfw-hal_plugin",
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift
index b4f1e275..268eed16 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift
@@ -196,7 +196,7 @@ public final class FirmwarePipeline {
resolvedPlan = plan
let gate = plan.map { VPhonePatchGate(plan: $0) } ?? .unrestricted
- let components = buildComponentList(
+ let components = try buildComponentList(
restoreDir: restoreDir,
iOSBase: baseVersion,
plan: plan,
@@ -232,7 +232,7 @@ public final class FirmwarePipeline {
// restoreDir is unused when building the kernelcache component's
// patchers (they take the gate and versions, not files), so the VM
// directory stands in for the parameter.
- let components = buildComponentList(restoreDir: vmDirectory, iOSBase: iOSBase, plan: plan, gate: gate)
+ let components = try buildComponentList(restoreDir: vmDirectory, iOSBase: iOSBase, plan: plan, gate: gate)
guard let kernel = components.first(where: { $0.name == "kernelcache" }) else {
throw PatcherError.invalidFormat("this build has no kernelcache component to patch")
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
index 2bf9bde5..296f9fc6 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
@@ -34,7 +34,7 @@ extension FirmwarePipeline {
iOSBase: VPhoneVersion?,
plan: VPhonePatchPlan? = nil,
gate: VPhonePatchGate = .unrestricted,
- ) -> [ComponentDescriptor] {
+ ) throws -> [ComponentDescriptor] {
var components: [ComponentDescriptor] = []
// Whether the plan kept a bundled set. True when there is no plan, so a
@@ -71,6 +71,7 @@ extension FirmwarePipeline {
let baseIs18 = iOSBase?.major == 18
let baseIs27 = iOSBase?.major == 27
+ let cloudIs264 = cloudOSProductVersion?.major == 26 && cloudOSProductVersion?.minor == 4
// The Mach port guard disable. Pinned to iOS 18, whose runningboardd and
// SpringBoard trip GUARD_TYPE_MACH_PORT flavor 10 and crash-loop the UI —
@@ -211,7 +212,52 @@ extension FirmwarePipeline {
}(),
))
- // 6. Kernel — the public CFW firmware includes the former EXP
+ // 6. Restore ramdisk and trust cache
+ let sealPatch = RestoreRamDiskSealPatcher.patchIdentifier
+ let includeSealPatch = variant != .less
+ && includeBootChain
+ && isEnabled(sealPatch, fallback: baseIs27 && cloudIs264)
+ // Empty factories restore both originals when the patch is disabled.
+ let includeSealComponents = includeSealPatch || (baseIs27 && cloudIs264)
+ if includeSealComponents {
+ // Catalogue-only tests have no restore tree.
+ let manifestURL = restoreDir.appendingPathComponent("BuildManifest.plist")
+ if FileManager.default.fileExists(atPath: manifestURL.path) {
+ let ramdiskPath = try Self.manifestComponentPath("RestoreRamDisk", in: restoreDir)
+ let trustCachePath = try Self.manifestComponentPath("RestoreTrustCache", in: restoreDir)
+ let sealContext = RestoreRamDiskSealPatchContext()
+ components.append(ComponentDescriptor(
+ name: VPhoneFirmwareComponent.restoreRamDisk.rawValue,
+ inRestoreDir: true,
+ searchPatterns: [ramdiskPath],
+ patcherFactories: includeSealPatch ? [{ data, verbose in
+ let patcher = RestoreRamDiskSealPatcher(
+ data: data,
+ context: sealContext,
+ verbose: verbose,
+ )
+ patcher.gate = gate
+ return patcher
+ }] : [],
+ ))
+ components.append(ComponentDescriptor(
+ name: VPhoneFirmwareComponent.restoreTrustCache.rawValue,
+ inRestoreDir: true,
+ searchPatterns: [trustCachePath],
+ patcherFactories: includeSealPatch ? [{ data, verbose in
+ let patcher = RestoreTrustCacheSealPatcher(
+ data: data,
+ context: sealContext,
+ verbose: verbose,
+ )
+ patcher.gate = gate
+ return patcher
+ }] : [],
+ ))
+ }
+ }
+
+ // 7. Kernel — the public CFW firmware includes the former EXP
// hv_vmm rename after the base and custom-firmware patches.
components.append(ComponentDescriptor(
name: "kernelcache",
@@ -255,7 +301,7 @@ extension FirmwarePipeline {
}(),
))
- // 7. DeviceTree — JB includes the former EXP identity and camera
+ // 8. DeviceTree — JB includes the former EXP identity and camera
// properties so the guest presents a consistent iPhone17,3 identity.
// A guest that presents its board restores with this tree and boots
// its own copy (7b).
@@ -277,7 +323,7 @@ extension FirmwarePipeline {
}] : [],
))
- // 7b. The board's installed DeviceTree, which `fw prepare` split off so
+ // 8b. The board's installed DeviceTree, which `fw prepare` split off so
// it can carry the board identity through restore.
if hasGuestTree {
components.append(ComponentDescriptor(
@@ -302,7 +348,7 @@ extension FirmwarePipeline {
))
}
- // 8. Filesystem
+ // 9. Filesystem
// Not restorable: it reads BuildManifest.plist but writes cryptex images
// all over the restore tree, so putting the manifest back on its own
// would describe a tree that no longer exists. See ComponentDescriptor.
@@ -328,7 +374,7 @@ extension FirmwarePipeline {
restorable: false,
))
- // 9. Firmware Manifest - Only required when excluding the img4 signature patches.
+ // 10. Firmware Manifest - Only required when excluding the img4 signature patches.
// Not restorable, for the same reason as Filesystem: the hashes it writes
// describe files other steps produced, not the manifest's own bytes.
components.append(ComponentDescriptor(
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift
index 672bf0a6..d088b910 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift
@@ -81,6 +81,32 @@ extension FirmwarePipeline {
readProductVersion(restoreDir, manifest: "BuildManifest.plist")
}
+ static func manifestComponentPath(_ component: String, in restoreDir: URL) throws -> String {
+ let url = restoreDir.appendingPathComponent("BuildManifest.plist")
+ let data = try Data(contentsOf: url, options: .mappedIfSafe)
+ guard let root = try PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any],
+ let identities = root["BuildIdentities"] as? [[String: Any]]
+ else {
+ throw PatcherError.invalidFormat("BuildManifest.plist has no BuildIdentities")
+ }
+ let paths = Set(identities.compactMap { identity -> String? in
+ guard let manifest = identity["Manifest"] as? [String: Any],
+ let entry = manifest[component] as? [String: Any],
+ let info = entry["Info"] as? [String: Any]
+ else { return nil }
+ return info["Path"] as? String
+ })
+ guard paths.count == 1, let path = paths.first else {
+ throw PatcherError.invalidFormat(
+ "BuildManifest.plist names \(paths.count) distinct \(component) paths, expected one",
+ )
+ }
+ guard CustomFirmwareDaemons.isPlainRelativePath(path) else {
+ throw PatcherError.invalidFormat("BuildManifest.plist has unsafe \(component) path: \(path)")
+ }
+ return path
+ }
+
/// Dotted `ProductVersion` >= major.minor, compared numerically. nil is false.
static func productVersionAtLeast(_ version: String?, _ major: Int, _ minor: Int) -> Bool {
guard let parts = version?.split(separator: ".").compactMap({ Int($0) }),
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Restore/RestoreRamDiskSealPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Restore/RestoreRamDiskSealPatcher.swift
new file mode 100644
index 00000000..72d0faba
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Restore/RestoreRamDiskSealPatcher.swift
@@ -0,0 +1,470 @@
+// iOS 27 sha3_256_4k root-hash compatibility for the cloudOS restore ramdisk.
+
+import CryptoKit
+import Foundation
+import VPhonePatchKit
+
+// MARK: - Shared State
+
+final class RestoreRamDiskSealPatchContext {
+ var originalCDHash: Data?
+ var patchedCDHash: Data?
+}
+
+// MARK: - Restore Ramdisk
+
+final class RestoreRamDiskSealPatcher: BufferedPatcher {
+ static let patchIdentifier = "restoreramdisk-boot-apfs_sha3_hash"
+ static let sealVolumePath = "System/Library/Filesystems/apfs.fs/apfs_sealvolume"
+ static let sha256Type: UInt32 = 1
+ static let sha3_256_4KType: UInt32 = 0x106
+
+ let component = VPhoneFirmwareComponent.restoreRamDisk.rawValue
+ let verbose: Bool
+ var gate: VPhonePatchGate = .unrestricted
+
+ private let originalData: Data
+ private let context: RestoreRamDiskSealPatchContext
+ private var resultData: Data?
+ private var records: [PatchRecord]?
+
+ init(data: Data, context: RestoreRamDiskSealPatchContext, verbose: Bool = true) {
+ originalData = data.startIndex == 0 ? data : Data(data)
+ self.context = context
+ self.verbose = verbose
+ }
+
+ func findAll() throws -> [PatchRecord] {
+ if let records { return records }
+ guard gateAllows(Self.patchIdentifier + ".hash_type") else {
+ records = []
+ return []
+ }
+
+ let temporary = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vphone-seal-\(UUID().uuidString)", isDirectory: true)
+ let image = temporary.appendingPathComponent("RestoreRamDisk.dmg")
+ let mount = temporary.appendingPathComponent("mount", isDirectory: true)
+ try FileManager.default.createDirectory(at: mount, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: temporary) }
+ try originalData.write(to: image)
+
+ let attachment = try Self.attach(image: image, at: mount)
+ var attached = true
+ defer {
+ if attached {
+ try? Self.detach(attachment.device)
+ }
+ }
+
+ let executable = attachment.mount.appendingPathComponent(Self.sealVolumePath)
+ guard FileManager.default.fileExists(atPath: executable.path) else {
+ throw PatcherError.fileNotFound("\(component): \(Self.sealVolumePath)")
+ }
+
+ var binary = try Data(contentsOf: executable, options: .mappedIfSafe)
+ let fieldOffset = try Self.locateHashTypeField(in: binary)
+ let oldValue = binary.loadLE(UInt32.self, at: fieldOffset)
+ guard oldValue == Self.sha256Type else {
+ throw PatcherError.patchVerificationFailed(
+ "apfs_sealvolume hash type at 0x\(String(fieldOffset, radix: 16)) is "
+ + "0x\(String(oldValue, radix: 16)), expected sha256 (1)",
+ )
+ }
+
+ let originalCDHash = try Self.primaryCDHash(of: binary)
+ let replacement = Self.littleEndian(Self.sha3_256_4KType)
+ binary.replaceSubrange(fieldOffset ..< fieldOffset + 4, with: replacement)
+ let rehashes = try CustomFirmwareMachOCodeSignature.reattest(
+ &binary,
+ modifiedOffsets: [fieldOffset],
+ )
+ guard !rehashes.isEmpty else {
+ throw PatcherError.patchVerificationFailed(
+ "apfs_sealvolume hash-type field is outside every SHA-256 CodeDirectory page",
+ )
+ }
+ let patchedCDHash = try Self.primaryCDHash(of: binary)
+ guard patchedCDHash != originalCDHash else {
+ throw PatcherError.patchVerificationFailed("apfs_sealvolume cdhash did not change")
+ }
+
+ // Preserve the inode and mode inside the restore ramdisk.
+ let handle = try FileHandle(forWritingTo: executable)
+ try handle.seek(toOffset: 0)
+ try handle.write(contentsOf: binary)
+ try handle.truncate(atOffset: UInt64(binary.count))
+ try handle.close()
+
+ try Self.detach(attachment.device)
+ attached = false
+ resultData = try Data(contentsOf: image, options: .mappedIfSafe)
+ context.originalCDHash = originalCDHash
+ context.patchedCDHash = patchedCDHash
+
+ let record = PatchRecord(
+ patchID: Self.patchIdentifier + ".hash_type",
+ component: component,
+ fileOffset: fieldOffset,
+ originalBytes: Self.littleEndian(Self.sha256Type),
+ patchedBytes: replacement,
+ beforeDisasm: "hash type 1 (sha256)",
+ afterDisasm: "hash type 0x106 (sha3_256_4k)",
+ description: "Use iOS 27's sha3_256_4k algorithm for the APFS root hash",
+ )
+ records = [record]
+
+ if verbose {
+ print(" apfs_sealvolume cdhash: \(originalCDHash.hex) → \(patchedCDHash.hex)")
+ }
+ return [record]
+ }
+
+ @discardableResult
+ func apply() throws -> Int {
+ try findAll().count
+ }
+
+ var patchedData: Data {
+ resultData ?? originalData
+ }
+
+ // MARK: Mach-O Discovery
+
+ static func locateHashTypeField(in binary: Data) throws -> Int {
+ let sections = MachOParser.parseSections(from: binary)
+ let segments = MachOParser.parseSegments(from: binary)
+ guard let text = sections["__TEXT,__text"],
+ let cstrings = sections["__TEXT,__cstring"],
+ let constants = sections["__DATA_CONST,__const"]
+ else {
+ throw PatcherError.invalidFormat("apfs_sealvolume is missing text, cstring, or data-const sections")
+ }
+
+ try requireCString("sha256", in: binary, section: cstrings)
+ try requireCString("sha3_256_4k", in: binary, section: cstrings)
+ let optionsOffset = try uniqueCStringOffset(
+ "cynfhvds:o:pH:F:t:TM:R:V:I:D:PU:u:SfrE:XxLam",
+ in: binary,
+ section: cstrings,
+ )
+ let optionsVMA = cstrings.address + UInt64(optionsOffset - Int(cstrings.fileOffset))
+ let optionReferences = findADRPADDReferences(
+ to: optionsVMA,
+ in: binary,
+ text: text,
+ )
+ guard optionReferences.count == 1, let optionsReference = optionReferences.first else {
+ throw PatcherError.patchVerificationFailed(
+ "apfs_sealvolume getopt anchor has \(optionReferences.count) ADRP+ADD references, expected one",
+ )
+ }
+
+ let disassembler = ARM64Disassembler()
+ let floor = max(Int(text.fileOffset), optionsReference - 0x180)
+ var candidates: [Int] = []
+ var offset = floor - (floor % 4)
+ while offset + 32 <= optionsReference {
+ let address = text.address + UInt64(offset - Int(text.fileOffset))
+ let instructions = disassembler.disassemble(in: binary, at: offset, count: 8, address: address)
+ if let targetVMA = copiedTemplateTarget(instructions),
+ targetVMA >= constants.address,
+ targetVMA + 96 <= constants.address + constants.size,
+ let targetOffset = MachOParser.vaToFileOffset(targetVMA, segments: segments),
+ targetOffset + 28 <= binary.count
+ {
+ let value = binary.loadLE(UInt32.self, at: targetOffset + 24)
+ if value == sha256Type || value == sha3_256_4KType {
+ candidates.append(targetOffset + 24)
+ }
+ }
+ offset += 4
+ }
+
+ let unique = Array(Set(candidates)).sorted()
+ guard unique.count == 1, let field = unique.first else {
+ throw PatcherError.patchVerificationFailed(
+ "apfs_sealvolume options template has \(unique.count) hash-type candidates, expected one",
+ )
+ }
+ return field
+ }
+
+ private static func copiedTemplateTarget(_ instructions: [ARM64Instruction]) -> UInt64? {
+ guard instructions.count == 8,
+ instructions[0].mnemonic == "adrp",
+ instructions[1].mnemonic == "add",
+ let adrp = instructions[0].detail?.operands,
+ adrp.count == 2,
+ adrp[0].type == .register, adrp[0].reg == .x(8),
+ adrp[1].type == .immediate, adrp[1].imm >= 0,
+ let add = instructions[1].detail?.operands,
+ add.count == 3,
+ add[0].type == .register, add[0].reg == .x(8),
+ add[1].type == .register, add[1].reg == .x(8),
+ add[2].type == .immediate, add[2].imm >= 0
+ else { return nil }
+
+ for pair in 0 ..< 3 {
+ let load = instructions[2 + pair * 2]
+ let store = instructions[3 + pair * 2]
+ guard load.mnemonic == "ldp",
+ store.mnemonic == "stp",
+ load.detail?.operands.last?.type == .memory,
+ load.detail?.operands.last?.mem.base == .x(8),
+ store.detail?.operands.last?.type == .memory,
+ store.detail?.operands.last?.mem.base == .x(20)
+ else { return nil }
+ }
+ return UInt64(adrp[1].imm) + UInt64(add[2].imm)
+ }
+
+ private static func findADRPADDReferences(
+ to targetVMA: UInt64,
+ in binary: Data,
+ text: MachOSectionInfo,
+ ) -> [Int] {
+ guard let start = Int(exactly: text.fileOffset),
+ let textSize = Int(exactly: text.size),
+ start < binary.count else { return [] }
+ let size = min(textSize, binary.count - start)
+ guard size > 0 else { return [] }
+ let instructions = ARM64Disassembler().disassemble(
+ Data(binary[start ..< start + size]),
+ at: text.address,
+ )
+ var pending: [ARM64Register: (index: Int, page: UInt64)] = [:]
+ var references: [Int] = []
+ for (index, instruction) in instructions.enumerated() {
+ guard let operands = instruction.detail?.operands else { continue }
+ if instruction.mnemonic == "adrp",
+ operands.count == 2,
+ operands[0].type == .register,
+ operands[1].type == .immediate,
+ operands[1].imm >= 0
+ {
+ pending[operands[0].reg] = (index, UInt64(operands[1].imm))
+ continue
+ }
+ guard instruction.mnemonic == "add",
+ operands.count == 3,
+ operands[0].type == .register,
+ operands[1].type == .register,
+ operands[0].reg == operands[1].reg,
+ operands[2].type == .immediate,
+ operands[2].imm >= 0,
+ let base = pending[operands[1].reg],
+ index - base.index <= 8,
+ base.page + UInt64(operands[2].imm) == targetVMA
+ else { continue }
+ references.append(start + Int(instruction.address - text.address) - (index - base.index) * 4)
+ }
+ return references
+ }
+
+ private static func requireCString(
+ _ string: String,
+ in data: Data,
+ section: MachOSectionInfo,
+ ) throws {
+ _ = try uniqueCStringOffset(string, in: data, section: section)
+ }
+
+ private static func uniqueCStringOffset(
+ _ string: String,
+ in data: Data,
+ section: MachOSectionInfo,
+ ) throws -> Int {
+ var pattern = Data(string.utf8)
+ pattern.append(0)
+ guard let lower = Int(exactly: section.fileOffset),
+ let size = Int(exactly: section.size),
+ lower <= data.count, size <= data.count - lower else {
+ throw PatcherError.invalidFormat("apfs_sealvolume cstring section lies outside the file")
+ }
+ let upper = lower + size
+ var matches: [Int] = []
+ var cursor = lower
+ while cursor + pattern.count <= upper,
+ let range = data.range(of: pattern, in: cursor ..< upper)
+ {
+ matches.append(range.lowerBound)
+ cursor = range.lowerBound + 1
+ }
+ guard matches.count == 1, let match = matches.first else {
+ throw PatcherError.patchVerificationFailed(
+ "apfs_sealvolume cstring '\(string)' occurs \(matches.count) times, expected one",
+ )
+ }
+ return match
+ }
+
+ static func primaryCDHash(of binary: Data) throws -> Data {
+ guard let directories = CustomFirmwareMachOCodeSignature.codeDirectories(in: binary),
+ let directory = directories.first(where: {
+ $0.slotType == 0 && $0.hashType == CustomFirmwareMachOCodeSignature.hashTypeSHA256
+ })
+ else {
+ throw PatcherError.invalidFormat("apfs_sealvolume has no primary SHA-256 CodeDirectory")
+ }
+ return Data(SHA256.hash(data: binary[directory.offset ..< directory.offset + directory.length])).prefix(20)
+ }
+
+ private static func littleEndian(_ value: UInt32) -> Data {
+ withUnsafeBytes(of: value.littleEndian) { Data($0) }
+ }
+
+ // MARK: Disk Image I/O
+
+ private static func attach(image: URL, at mount: URL) throws -> (device: String, mount: URL) {
+ let output = try run(
+ "/usr/bin/hdiutil",
+ ["attach", "-plist", "-readwrite", "-owners", "off", "-nobrowse", "-mountpoint", mount.path, image.path],
+ )
+ guard let plist = try PropertyListSerialization.propertyList(from: output, format: nil) as? [String: Any],
+ let entities = plist["system-entities"] as? [[String: Any]],
+ let root = entities.first?["dev-entry"] as? String,
+ let mountedPath = entities.compactMap({ $0["mount-point"] as? String }).first
+ else {
+ throw PatcherError.invalidFormat("hdiutil did not report the restore ramdisk mount")
+ }
+ return (root, URL(fileURLWithPath: mountedPath, isDirectory: true))
+ }
+
+ private static func detach(_ device: String) throws {
+ _ = try run("/usr/bin/hdiutil", ["detach", device])
+ }
+
+ private static func run(_ executable: String, _ arguments: [String]) throws -> Data {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: executable)
+ process.arguments = arguments
+ let standardOutput = Pipe()
+ let standardError = Pipe()
+ process.standardOutput = standardOutput
+ process.standardError = standardError
+ try process.run()
+ process.waitUntilExit()
+ let output = standardOutput.fileHandleForReading.readDataToEndOfFile()
+ let error = standardError.fileHandleForReading.readDataToEndOfFile()
+ guard process.terminationStatus == 0 else {
+ let message = String(data: error, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ throw PatcherError.patchVerificationFailed(
+ "\((executable as NSString).lastPathComponent) exited \(process.terminationStatus): \(message)",
+ )
+ }
+ return output
+ }
+}
+
+// MARK: - Restore Trust Cache
+
+final class RestoreTrustCacheSealPatcher: BufferedPatcher {
+ static let entrySize = 22
+ static let headerSize = 24
+
+ let component = VPhoneFirmwareComponent.restoreTrustCache.rawValue
+ let verbose: Bool
+ var gate: VPhonePatchGate = .unrestricted
+
+ private let originalData: Data
+ private let context: RestoreRamDiskSealPatchContext
+ private var resultData: Data?
+ private var records: [PatchRecord]?
+
+ init(data: Data, context: RestoreRamDiskSealPatchContext, verbose: Bool = true) {
+ originalData = data.startIndex == 0 ? data : Data(data)
+ self.context = context
+ self.verbose = verbose
+ }
+
+ func findAll() throws -> [PatchRecord] {
+ if let records { return records }
+ let patchID = RestoreRamDiskSealPatcher.patchIdentifier + ".trustcache"
+ guard gateAllows(patchID) else {
+ records = []
+ return []
+ }
+ guard let oldHash = context.originalCDHash, let newHash = context.patchedCDHash else {
+ throw PatcherError.patchVerificationFailed(
+ "RestoreTrustCache ran before the RestoreRamDisk cdhash was available",
+ )
+ }
+ let replaced = try Self.replacingCDHash(in: originalData, from: oldHash, to: newHash)
+ resultData = replaced.data
+ let changed = replaced.changedRange
+ let record = PatchRecord(
+ patchID: patchID,
+ component: component,
+ fileOffset: changed.lowerBound,
+ originalBytes: Data(originalData[changed]),
+ patchedBytes: Data(replaced.data[changed]),
+ beforeDisasm: oldHash.hex,
+ afterDisasm: newHash.hex,
+ description: "Trust the re-attested apfs_sealvolume used for iOS 27 sealing",
+ )
+ records = [record]
+ if verbose {
+ print(" RestoreTrustCache cdhash: \(oldHash.hex) → \(newHash.hex)")
+ }
+ return [record]
+ }
+
+ @discardableResult
+ func apply() throws -> Int {
+ try findAll().count
+ }
+
+ var patchedData: Data {
+ resultData ?? originalData
+ }
+
+ static func replacingCDHash(
+ in data: Data,
+ from oldHash: Data,
+ to newHash: Data,
+ ) throws -> (data: Data, changedRange: Range<Int>) {
+ guard oldHash.count == 20, newHash.count == 20 else {
+ throw PatcherError.invalidFormat("trust-cache cdhashes must be 20 bytes")
+ }
+ guard oldHash != newHash else {
+ throw PatcherError.invalidFormat("trust-cache replacement cdhash is unchanged")
+ }
+ guard data.count >= headerSize, data.loadLE(UInt32.self, at: 0) == 1 else {
+ throw PatcherError.invalidFormat("RestoreTrustCache is not a v1 trust cache")
+ }
+ let count = Int(data.loadLE(UInt32.self, at: 20))
+ guard headerSize + count * entrySize == data.count else {
+ throw PatcherError.invalidFormat(
+ "RestoreTrustCache size \(data.count) does not match its \(count) v1 entries",
+ )
+ }
+
+ var entries: [Data] = []
+ var matchCount = 0
+ for index in 0 ..< count {
+ let offset = headerSize + index * entrySize
+ var entry = Data(data[offset ..< offset + entrySize])
+ if entry.prefix(20) == oldHash {
+ matchCount += 1
+ entry.replaceSubrange(0 ..< 20, with: newHash)
+ }
+ entries.append(entry)
+ }
+ guard matchCount == 1 else {
+ throw PatcherError.patchVerificationFailed(
+ "apfs_sealvolume cdhash occurs \(matchCount) times in RestoreTrustCache, expected one",
+ )
+ }
+ entries.sort { $0.lexicographicallyPrecedes($1) }
+
+ var rebuilt = Data(data.prefix(headerSize))
+ for entry in entries { rebuilt.append(entry) }
+ guard let firstDifference = data.indices.first(where: { data[$0] != rebuilt[$0] }),
+ let lastDifference = data.indices.last(where: { data[$0] != rebuilt[$0] })
+ else {
+ throw PatcherError.patchVerificationFailed("trust-cache replacement changed no bytes")
+ }
+ return (rebuilt, firstDifference ..< lastDifference + 1)
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift
index 2280849d..68fe3e93 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift
@@ -491,7 +491,56 @@ struct ARM64EncoderKeystoneParityTests {
),
]
- static let allCases: [ARM64EncodingCase] = asmCallSiteCases + operandCoverageCases
+ // Frozen from Keystone 0.9.2 ks_asm outside the repository.
+ static let x1ComparisonCases: [ARM64EncodingCase] = [
+ .init(source: "cmp w1, #12", keystone: 0x7100_303F, encoded: ARM64Encoder.encodeCmpWImmediate(rn: 1, imm12: 12), origin: "X1 grade"),
+ .init(source: "cmp w8, #12", keystone: 0x7100_311F, encoded: ARM64Encoder.encodeCmpWImmediate(rn: 8, imm12: 12), origin: "X1 exec"),
+ .init(source: "cmp w0, #0", keystone: 0x7100_001F, encoded: ARM64Encoder.encodeCmpWImmediate(rn: 0, imm12: 0), origin: "minimum immediate"),
+ .init(source: "cmp w30, #4095", keystone: 0x713F_FFDF, encoded: ARM64Encoder.encodeCmpWImmediate(rn: 30, imm12: 4095), origin: "maximum immediate"),
+ .init(source: "cmp wsp, #2", keystone: 0x7100_0BFF, encoded: ARM64Encoder.encodeCmpWImmediate(rn: 31, imm12: 2), origin: "WSP register"),
+ .init(source: "ccmp w1, #2, #6, ne", keystone: 0x7A42_1826, encoded: ARM64Encoder.encodeCcmpWImmediate(rn: 1, imm5: 2, nzcv: 6, condition: .ne), origin: "X1 grade"),
+ .init(source: "ccmp w8, #2, #6, ne", keystone: 0x7A42_1906, encoded: ARM64Encoder.encodeCcmpWImmediate(rn: 8, imm5: 2, nzcv: 6, condition: .ne), origin: "X1 exec"),
+ .init(source: "ccmp w0, #0, #0, eq", keystone: 0x7A40_0800, encoded: ARM64Encoder.encodeCcmpWImmediate(rn: 0, imm5: 0, nzcv: 0, condition: .eq), origin: "minimum fields"),
+ .init(source: "ccmp wzr, #31, #15, le", keystone: 0x7A5F_DBEF, encoded: ARM64Encoder.encodeCcmpWImmediate(rn: 31, imm5: 31, nzcv: 15, condition: .le), origin: "maximum fields"),
+ ]
+
+ static let x1LoweringCases: [ARM64EncodingCase] = [
+ .init(source: "madd x0, x1, x2, x3", keystone: 0x9B02_0C20, encoded: ARM64Encoder.encodeMaddSubX(subtract: false, rd: 0, rn: 1, rm: 2, ra: 3), origin: "lower MADDPT"),
+ .init(source: "msub x30, x29, x28, x27", keystone: 0x9B1C_EFBE, encoded: ARM64Encoder.encodeMaddSubX(subtract: true, rd: 30, rn: 29, rm: 28, ra: 27), origin: "lower MSUBPT"),
+ .init(source: "mul xzr, x0, xzr", keystone: 0x9B1F_7C1F, encoded: ARM64Encoder.encodeMaddSubX(subtract: false, rd: 31, rn: 0, rm: 31, ra: 31), origin: "Keystone madd xzr,x0,xzr,xzr; XZR alias"),
+ .init(source: "add x9, x8, x11, lsl #2", keystone: 0x8B0B_0909, encoded: ARM64Encoder.encodeAddSubXShifted(subtract: false, rd: 9, rn: 8, rm: 11, shift: 2), origin: "lower ADDPT"),
+ .init(source: "sub x3, x3, x4", keystone: 0xCB04_0063, encoded: ARM64Encoder.encodeAddSubXShifted(subtract: true, rd: 3, rn: 3, rm: 4), origin: "lower SUBPT"),
+ .init(source: "add x30, x29, xzr, lsl #7", keystone: 0x8B1F_1FBE, encoded: ARM64Encoder.encodeAddSubXShifted(subtract: false, rd: 30, rn: 29, rm: 31, shift: 7), origin: "XZR and shift"),
+ .init(source: "sub x0, x30, x1, lsl #63", keystone: 0xCB01_FFC0, encoded: ARM64Encoder.encodeAddSubXShifted(subtract: true, rd: 0, rn: 30, rm: 1, shift: 63), origin: "maximum shift"),
+ .init(source: "add sp, sp, x2, lsl #4", keystone: 0x8B22_73FF, encoded: ARM64Encoder.encodeAddSubXExtended(subtract: false, rd: 31, rn: 31, rm: 2, shift: 4), origin: "SP and maximum extension shift"),
+ .init(source: "sub sp, x1, x2", keystone: 0xCB22_603F, encoded: ARM64Encoder.encodeAddSubXExtended(subtract: true, rd: 31, rn: 1, rm: 2), origin: "SP destination"),
+ .init(source: "add x0, sp, xzr, lsl #3", keystone: 0x8B3F_6FE0, encoded: ARM64Encoder.encodeAddSubXExtended(subtract: false, rd: 0, rn: 31, rm: 31, shift: 3), origin: "SP and XZR differ"),
+ .init(source: "paciasp", keystone: 0xD503_233F, encoded: ARM64.paciasp, origin: "Keystone hint #25"),
+ .init(source: "autiasp", keystone: 0xD503_23BF, encoded: ARM64.autiasp, origin: "Keystone hint #29"),
+ .init(source: "autibsp", keystone: 0xD503_23FF, encoded: ARM64.autibsp, origin: "Keystone hint #31"),
+ .init(source: "autia1716", keystone: 0xD503_219F, encoded: ARM64.autia1716, origin: "Keystone hint #12"),
+ .init(source: "autib1716", keystone: 0xD503_21DF, encoded: ARM64.autib1716, origin: "Keystone hint #14"),
+ ]
+
+ static let allCases: [ARM64EncodingCase] = asmCallSiteCases + operandCoverageCases + x1ComparisonCases + x1LoweringCases
+
+ @Test func `new X1 encoders refuse unencodable operands`() {
+ #expect(ARM64Encoder.encodeMaddSubX(subtract: false, rd: 32, rn: 0, rm: 0, ra: 0) == nil)
+ #expect(ARM64Encoder.encodeMaddSubX(subtract: false, rd: 0, rn: 32, rm: 0, ra: 0) == nil)
+ #expect(ARM64Encoder.encodeMaddSubX(subtract: false, rd: 0, rn: 0, rm: 32, ra: 0) == nil)
+ #expect(ARM64Encoder.encodeMaddSubX(subtract: false, rd: 0, rn: 0, rm: 0, ra: 32) == nil)
+ #expect(ARM64Encoder.encodeAddSubXShifted(subtract: false, rd: 32, rn: 0, rm: 0) == nil)
+ #expect(ARM64Encoder.encodeAddSubXShifted(subtract: false, rd: 0, rn: 32, rm: 0) == nil)
+ #expect(ARM64Encoder.encodeAddSubXShifted(subtract: false, rd: 0, rn: 0, rm: 32) == nil)
+ #expect(ARM64Encoder.encodeAddSubXShifted(subtract: false, rd: 0, rn: 0, rm: 0, shift: 64) == nil)
+ #expect(ARM64Encoder.encodeAddSubXExtended(subtract: false, rd: 0, rn: 0, rm: 0, shift: 5) == nil)
+ #expect(ARM64Encoder.encodeAddSubXExtended(subtract: false, rd: 32, rn: 0, rm: 0) == nil)
+ #expect(ARM64Encoder.encodeCmpWImmediate(rn: 32, imm12: 2) == nil)
+ #expect(ARM64Encoder.encodeCmpWImmediate(rn: 0, imm12: 4096) == nil)
+ #expect(ARM64Encoder.encodeCcmpWImmediate(rn: 32, imm5: 2, nzcv: 6, condition: .ne) == nil)
+ #expect(ARM64Encoder.encodeCcmpWImmediate(rn: 0, imm5: 32, nzcv: 6, condition: .ne) == nil)
+ #expect(ARM64Encoder.encodeCcmpWImmediate(rn: 0, imm5: 2, nzcv: 16, condition: .ne) == nil)
+ }
// MARK: Parity
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/FirmwarePatcherTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/FirmwarePatcherTests.swift
index 848f3bca..aa769bb5 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/FirmwarePatcherTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/FirmwarePatcherTests.swift
@@ -583,7 +583,7 @@ struct FirmwarePipelineTests {
@Test func `public JB includes the former EXP device tree patchers, not the hv_vmm rename`() throws {
let root = URL(fileURLWithPath: NSTemporaryDirectory())
let pipeline = FirmwarePipeline(vmDirectory: root, variant: .jb, verbose: false)
- let components = pipeline.buildComponentList(
+ let components = try pipeline.buildComponentList(
restoreDir: root,
iOSBase: VPhoneVersion("27.0"),
)
@@ -617,7 +617,7 @@ struct FirmwarePipelineTests {
preset: standard ? FirmwarePatchSetCatalog.standardPreset : nil,
)
let plan = try pipeline.resolvePlan(iOSBase: version, cloudOS: VPhoneVersion("26.4"))
- let components = pipeline.buildComponentList(
+ let components = try pipeline.buildComponentList(
restoreDir: root,
iOSBase: version,
plan: plan,
@@ -650,7 +650,7 @@ struct FirmwarePipelineTests {
blockedPatches: blocked,
)
let plan = try pipeline.resolvePlan(iOSBase: version, cloudOS: VPhoneVersion("26.4"))
- let components = pipeline.buildComponentList(
+ let components = try pipeline.buildComponentList(
restoreDir: root,
iOSBase: version,
plan: plan,
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareArm64eX1Tests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareArm64eX1Tests.swift
new file mode 100644
index 00000000..05c26312
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareArm64eX1Tests.swift
@@ -0,0 +1,327 @@
+import CryptoKit
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+import VPhonePatchKit
+
+@Suite("ARM64E_X1 lowering")
+struct CustomFirmwareArm64eX1Tests {
+ // Instruction fixtures come from Apple clang 21 or Keystone 0.9.2.
+ static let pac: UInt32 = 0xDAC1_A7FE
+ static let add: UInt32 = 0x9A0B_2909 // addpt x9,x8,x11,lsl #2
+ static let sub: UInt32 = 0xDA04_2063 // subpt x3,x3,x4
+ static let auth: UInt32 = 0xF3A0_007F
+ static let ret: UInt32 = 0x5520_009F
+
+ static func fixture(_ code: [UInt32]) -> Data {
+ var data = Data()
+ func word(_ v: UInt32) { data += ARM64.encodeU32(v) }
+ func quad(_ v: UInt64) { withUnsafeBytes(of: v.littleEndian) { data.append(contentsOf: $0) } }
+ func name(_ s: String) { data += Data(s.utf8) + Data(repeating: 0, count: 16 - s.utf8.count) }
+ word(0xFEED_FACF); word(0x0100_000C); word(0x8000_000C); word(2)
+ word(2); word(168); word(0); word(0)
+ word(0x19); word(152); name("__TEXT")
+ quad(0); quad(0x1000); quad(0); quad(0x400)
+ word(5); word(5); word(1); word(0)
+ name("__text"); name("__TEXT"); quad(0x200); quad(UInt64(code.count * 4)); word(0x200)
+ word(2); word(0); word(0); word(0x8000_0400); word(0); word(0); word(0)
+ word(0x26); word(16); word(0x300); word(3)
+ data += Data(repeating: 0, count: 0x200 - data.count)
+ for v in code { word(v) }
+ data += Data(repeating: 0, count: 0x300 - data.count)
+ data += Data([0x80, 0x04, 0]) // LC_FUNCTION_STARTS: 0x200, terminator
+ return data
+ }
+
+ static func signedFixture(hashType: UInt8 = 2, codeLimit: Int = 0x400) -> (Data, Int) {
+ var image = fixture([pac, ret])
+ let identity = Data("com.apple.fsck\0".utf8)
+ let entitlements = Data("<plist><dict><key>platform-application</key><true/></dict></plist>".utf8)
+ func be(_ value: UInt32) -> Data { withUnsafeBytes(of: value.bigEndian) { Data($0) } }
+ let hashOffset = 44 + identity.count, directoryLength = hashOffset + 32
+ let signatureLength = 28 + directoryLength + 8 + entitlements.count
+ image.replaceSubrange(16 ..< 24, with: ARM64.encodeU32(3) + ARM64.encodeU32(184))
+ image.replaceSubrange(200 ..< 216, with: ARM64.encodeU32(0x1D) + ARM64.encodeU32(16)
+ + ARM64.encodeU32(0x400) + ARM64.encodeU32(UInt32(signatureLength)))
+ image += Data(count: 0x400 - image.count)
+ var directory = be(0xFADE_0C02) + be(UInt32(directoryLength)) + be(0x20001) + be(0x10002)
+ directory += be(UInt32(hashOffset)) + be(44) + be(0) + be(1) + be(UInt32(codeLimit))
+ directory += Data([32, hashType, 0, 12]) + be(0) + identity
+ directory += Data(SHA256.hash(data: image.prefix(codeLimit)))
+ image += be(0xFADE_0CC0) + be(UInt32(signatureLength)) + be(2)
+ + be(0) + be(28) + be(5) + be(UInt32(28 + directoryLength))
+ image += directory + be(0xFADE_7171) + be(UInt32(8 + entitlements.count)) + entitlements
+ return (image, 0x400 + 28 + hashOffset)
+ }
+
+ @Test func `signed program lowering changes only instructions and their code slot hashes`() throws {
+ var (image, hashOffset) = Self.signedFixture()
+ var expected = image
+ expected.replaceSubrange(0x200 ..< 0x208, with: ARM64.pacibsp + ARM64.retab)
+ expected.replaceSubrange(hashOffset ..< hashOffset + 32, with: Data(SHA256.hash(data: expected.prefix(0x400))))
+ let (result, slots) = try CustomFirmwareArm64eX1.lowerAndReattest(&image, identifier: "test-x1")
+ #expect(result.records.count == 2)
+ #expect(slots.count == 1)
+ #expect(image == expected)
+ }
+
+ @Test func `missing unsupported or incomplete signing coverage refuses without changing bytes`() throws {
+ for source in [Self.fixture([Self.pac, Self.ret]), Self.signedFixture(hashType: 1).0,
+ Self.signedFixture(codeLimit: 0x200).0] {
+ var image = source
+ #expect(throws: (any Error).self) {
+ try CustomFirmwareArm64eX1.lowerAndReattest(&image, identifier: "test-x1")
+ }
+ #expect(image == source)
+ }
+ }
+
+ static func universal(_ first: Data, _ second: Data, wide: Bool = false) -> Data {
+ func be<T: FixedWidthInteger>(_ value: T) -> Data { withUnsafeBytes(of: value.bigEndian) { Data($0) } }
+ var data = be(UInt32(wide ? 0xCAFE_BABF : 0xCAFE_BABE)) + be(UInt32(2))
+ for (offset, slice) in [(0x1000, first), (0x2000, second)] {
+ data += be(slice.loadLE(UInt32.self, at: 4)) + be(slice.loadLE(UInt32.self, at: 8))
+ if wide {
+ data += be(UInt64(offset)) + be(UInt64(slice.count)) + be(UInt32(12)) + be(UInt32(0))
+ } else {
+ data += be(UInt32(offset)) + be(UInt32(slice.count)) + be(UInt32(12))
+ }
+ }
+ data += Data(count: 0x1000 - data.count)
+ data += first + Data(count: 0x1000 - first.count) + second
+ return data
+ }
+
+ @Test func `universal lowering preserves other architectures and attests slice relative pages`() throws {
+ var (other, hashOffset) = Self.signedFixture()
+ other.replaceSubrange(8 ..< 12, with: ARM64.encodeU32(0x8000_0002))
+ other.replaceSubrange(hashOffset ..< hashOffset + 32, with: Data(SHA256.hash(data: other.prefix(0x400))))
+ let x1 = Self.signedFixture().0
+ var expected = x1
+ let (thin, hashes) = try CustomFirmwareArm64eX1.lowerAndReattest(&expected, identifier: "thin")
+ for wide in [false, true] {
+ var image = Self.universal(other, x1, wide: wide)
+ let original = image
+ let (result, slots) = try CustomFirmwareArm64eX1.lowerAndReattest(&image, identifier: "fat")
+ #expect(image.count == original.count)
+ #expect(image.prefix(0x2000) == original.prefix(0x2000))
+ #expect(image.subdata(in: 0x2000 ..< image.count) == expected)
+ #expect(result.records.map(\.fileOffset) == thin.records.map { 0x2000 + $0.fileOffset })
+ #expect(slots.map(\.hashFileOffset) == hashes.map { 0x2000 + $0.hashFileOffset })
+ #expect(try CustomFirmwareArm64eX1.lowerAndReattest(&image, identifier: "fat").result.records.isEmpty)
+ }
+ }
+
+ @Test func `invalid universal layouts and later signing failures leave the container unchanged`() throws {
+ let signed = Self.signedFixture().0
+ let valid = Self.universal(signed, signed)
+ var overlap = valid, outside = valid, mismatch = valid
+ func be(_ value: UInt32) -> Data { withUnsafeBytes(of: value.bigEndian) { Data($0) } }
+ overlap.replaceSubrange(36 ..< 40, with: be(0x1000))
+ outside.replaceSubrange(36 ..< 40, with: be(UInt32.max))
+ mismatch.replaceSubrange(0x2008 ..< 0x200C, with: ARM64.encodeU32(0x8000_0002))
+ for source in [overlap, outside, mismatch, Self.universal(signed, Self.fixture([Self.pac, Self.ret]))] {
+ var image = source
+ #expect(throws: (any Error).self) { try CustomFirmwareArm64eX1.lowerAndReattest(&image, identifier: "fat") }
+ #expect(image == source)
+ }
+ }
+
+ @Test func `lowers supported PAC and pointer arithmetic forms without changing operands`() throws {
+ var image = Self.fixture([
+ Self.pac, Self.add, Self.sub, Self.auth,
+ 0x9A02_33FF, // addpt sp,sp,x2,lsl #4
+ 0x9B62_0C20, 0x9B7C_EFBE, // maddpt and msubpt
+ 0xDAC1_BBFE, 0xDAC1_BFFE, // autia171615 and autib171615
+ Self.ret,
+ ])
+ let result = try CustomFirmwareArm64eX1.lower(&image)
+ #expect(result.records.count == 10)
+ #expect(result.unvisitedCandidates == 0)
+ let decoded = ARM64Disassembler().disassemble(in: image, at: 0x200, count: 10)
+ #expect(decoded.map(\.mnemonic) == [
+ "pacibsp", "add", "sub", "autibsp", "add",
+ "madd", "msub", "autia1716", "autib1716", "retab",
+ ])
+ #expect(decoded[1].detail?.operands[0].reg == .x(9))
+ #expect(decoded[1].detail?.operands[1].reg == .x(8))
+ #expect(decoded[1].detail?.operands[2].reg == .x(11))
+ #expect(decoded[1].detail?.operands[2].shift.type == .lsl)
+ #expect(decoded[1].detail?.operands[2].shift.amount == 2)
+ let stackAdd = try #require(ARM64Encoder.encodeAddSubXExtended(
+ subtract: false, rd: 31, rn: 31, rm: 2, shift: 4,
+ ))
+ #expect(image[0x210 ..< 0x214] == stackAdd)
+ #expect(image.loadLE(UInt32.self, at: 0x214) == 0x9B02_0C20)
+ #expect(image.loadLE(UInt32.self, at: 0x218) == 0x9B1C_EFBE)
+ #expect(image.loadLE(UInt32.self, at: 0x21C) == 0xD503_219F)
+ #expect(image.loadLE(UInt32.self, at: 0x220) == 0xD503_21DF)
+ let again = try CustomFirmwareArm64eX1.lower(&image)
+ #expect(again.records.isEmpty)
+ }
+
+ @Test func `does not rewrite literal pools skipped by a direct branch`() throws {
+ let branch = try #require(ARM64Encoder.encodeB(from: 0x204, to: 0x210))
+ let branchWord = branch.loadLE(UInt32.self, at: 0)
+ var image = Self.fixture([Self.pac, branchWord, Self.pac, Self.add, Self.add, Self.ret])
+ let original = image
+ let result = try CustomFirmwareArm64eX1.lower(&image)
+ #expect(result.records.map(\.fileOffset) == [0x200, 0x210, 0x214])
+ #expect(image[0x208 ..< 0x210] == original[0x208 ..< 0x210])
+ #expect(result.unvisitedCandidates == 2)
+ }
+
+ @Test func `follows a bounded hardened switch and never rewrites its table`() throws {
+ let page = try #require(ARM64Encoder.encodeADRP(rd: 17, pc: 0x208, target: 0x280))
+ let low = try #require(ARM64Encoder.encodeAddImm12(rd: 17, rn: 17, imm12: 0x280))
+ let code: [UInt32] = [0xF100_061F, 0x9A9F_9210, page.loadLE(UInt32.self, at: 0), low.loadLE(UInt32.self, at: 0),
+ 0xB8B0_7A30, 0x1000_0011, 0x8B10_0230, 0xD61F_0200,
+ Self.add, ARM64.retU32, Self.sub, ARM64.retU32]
+ var image = Self.fixture(code)
+ image.replaceSubrange(0x280 ..< 0x288, with: ARM64.encodeU32(0xC) + ARM64.encodeU32(0x14))
+ let original = image
+ let result = try CustomFirmwareArm64eX1.lower(&image)
+ #expect(result.records.map(\.fileOffset) == [0x220, 0x228])
+ #expect(result.unvisitedCandidates == 0)
+ #expect(image[0x280 ..< 0x288] == original[0x280 ..< 0x288])
+
+ var invalid = original
+ invalid.replaceSubrange(0x284 ..< 0x288, with: ARM64.encodeU32(0x7FFF_0000))
+ let before = invalid
+ #expect(throws: (any Error).self) { try CustomFirmwareArm64eX1.lower(&invalid) }
+ #expect(invalid == before)
+ }
+
+ @Test func `authenticated bytecode dispatch discovers label bodies and rejects invalid targets`() throws {
+ let page = try #require(ARM64Encoder.encodeADRP(rd: 9, pc: 0x204, target: 0x280))
+ let low = try #require(ARM64Encoder.encodeAddImm12(rd: 9, rn: 9, imm12: 0x280))
+ let words: [UInt32] = [0xD378_FF08, page.loadLE(UInt32.self, at: 0), low.loadLE(UInt32.self, at: 0),
+ 0xF868_7929, 0xD282_6B11, 0xD71F_0931,
+ Self.pac, Self.add, Self.ret, Self.sub, Self.ret, Self.add]
+ let bytes = words.reduce(into: Data()) { $0 += ARM64.encodeU32($1) }
+ func plan(badTarget: Bool = false) throws -> CustomFirmwareArm64eX1.Result {
+ try CustomFirmwareArm64eX1.planCode(ranges: [(address: 0x200, data: bytes)], seeds: [0x200],
+ excluded: [], identifier: "test-x1", authenticatedPointer: { address, diversity in
+ #expect(diversity == 0x1358)
+ switch address {
+ case 0x280: return badTarget ? 0x400 : 0x218
+ case 0x288: return 0x224
+ default: return nil
+ }
+ })
+ }
+ let result = try plan()
+ #expect(result.records.map(\.fileOffset) == [0x218, 0x21C, 0x220, 0x224, 0x228])
+ #expect(result.unvisitedCandidates == 1) // skipped instruction-shaped literal
+ #expect(throws: (any Error).self) { try plan(badTarget: true) }
+ }
+
+ @Test func `already lowered PAC frames still reveal coalesced function entries`() throws {
+ let words: [UInt32] = [ARM64.retU32, ARM64.pacibsp.loadLE(UInt32.self, at: 0),
+ 0xA9BF_7BFD, Self.add, Self.ret]
+ let bytes = words.reduce(into: Data()) { $0 += ARM64.encodeU32($1) }
+ let result = try CustomFirmwareArm64eX1.planCode(ranges: [(address: 0x200, data: bytes)],
+ seeds: [0x200], excluded: [], identifier: "test-x1")
+ #expect(result.records.map(\.fileOffset) == [0x20C, 0x210])
+ #expect(result.unvisitedCandidates == 0)
+ }
+
+ @Test func `hoisted authenticated tables reject overwritten bases and indexes`() throws {
+ let page = try #require(ARM64Encoder.encodeADRP(rd: 23, pc: 0x200, target: 0x280))
+ let low = try #require(ARM64Encoder.encodeAddImm12(rd: 23, rn: 23, imm12: 0x280))
+ let nop = ARM64.nop.loadLE(UInt32.self, at: 0)
+ for (baseWrite, indexWrite, interleaved, accepted) in [(nop, nop, UInt32(0xAA1A_03FC), true),
+ (nop, nop, UInt32(0xF940_07FB), true), // LDR X27,[SP,#8]
+ (UInt32(0x2A1F_03F7), nop, UInt32(0xAA1A_03FC), false), // W23 aliases X23
+ (UInt32(0xF840_86E0), nop, UInt32(0xAA1A_03FC), false), // LDR X0,[X23],#8
+ (nop, UInt32(0x2A1F_03E8), UInt32(0xAA1A_03FC), false)] { // W8 aliases X8
+ let words = [page.loadLE(UInt32.self, at: 0), low.loadLE(UInt32.self, at: 0),
+ baseWrite, 0xD378_FF08, indexWrite, 0xF868_7AE9, interleaved,
+ 0xD282_6B11, 0xD71F_0931, Self.add, Self.ret, Self.sub, Self.ret, Self.add]
+ let bytes = words.reduce(into: Data()) { $0 += ARM64.encodeU32($1) }
+ var pointerReads = 0
+ let result = try CustomFirmwareArm64eX1.planCode(ranges: [(address: 0x200, data: bytes)],
+ seeds: [0x200], excluded: [], identifier: "test-x1", authenticatedPointer: { address, diversity in
+ pointerReads += 1
+ #expect(diversity == 0x1358)
+ switch address {
+ case 0x280: return 0x224
+ case 0x288: return 0x22C
+ default: return nil
+ }
+ })
+ #expect(result.records.map(\.fileOffset) == (accepted ? [0x224, 0x228, 0x22C, 0x230] : []))
+ #expect(pointerReads == (accepted ? 3 : 0))
+ #expect(result.unvisitedCandidates == (accepted ? 1 : 5))
+ }
+ }
+
+ @Test func `invalid discovery or operands refuse the whole plan before writing`() {
+ var missingEntries = Self.fixture([Self.pac, Self.ret])
+ missingEntries[0x300] = 0
+ for source in [
+ Self.fixture([Self.pac, 0x9A02_3FFF, Self.ret]), // SP shift 7 has no one-instruction equivalent
+ missingEntries,
+ ] {
+ var image = source
+ #expect(throws: (any Error).self) { try CustomFirmwareArm64eX1.lower(&image) }
+ #expect(image == source)
+ }
+ }
+
+ @Test func `non-target and empty images remain unchanged`() throws {
+ var otherArchitecture = Self.fixture([Self.pac, Self.ret])
+ otherArchitecture.replaceSubrange(8 ..< 12, with: ARM64.encodeU32(2))
+ var kernelExtension = Self.fixture([Self.pac, Self.ret])
+ kernelExtension.replaceSubrange(12 ..< 16, with: ARM64.encodeU32(11)) // MH_KEXT_BUNDLE
+ for source in [otherArchitecture, kernelExtension, Self.fixture([])] {
+ var image = source
+ let (result, slots) = try CustomFirmwareArm64eX1.lowerAndReattest(&image, identifier: "test-x1")
+ #expect(result.records.isEmpty)
+ #expect(slots.isEmpty)
+ #expect(image == source)
+ }
+ }
+
+ @Test func `includes instruction sections such as authenticated stubs`() throws {
+ var image = Self.fixture([Self.pac, Self.ret])
+ image.replaceSubrange(104 ..< 120, with: Data("__auth_stubs".utf8) + Data(repeating: 0, count: 4))
+ let result = try CustomFirmwareArm64eX1.lower(&image)
+ #expect(result.records.count == 2)
+ #expect(MachOParser.parseSections(from: image)["__TEXT,__auth_stubs"]?.flags == 0x8000_0400)
+ }
+
+ @Test func `exception metadata seeds cleanup code while skipped literals stay unchanged`() throws {
+ let base: UInt64 = 0x1_0000_0000
+ let unwind = [UInt32(1), 0, 0, 0, 0, 28, 2,
+ 0x2000, 0, 52, 0x2040, 0, 60, 0x2000, 0x4000]
+ .reduce(into: Data()) { $0 += ARM64.encodeU32($1) }
+ var lsda = Data([0xFF, 0xFF, 1, 4, 0, 4, 0x10, 0])
+ let sections = [
+ MachOSectionInfo(segmentName: "__TEXT", sectionName: "__text", address: base + 0x2000,
+ size: 0x40, fileOffset: 0x2000),
+ MachOSectionInfo(segmentName: "__TEXT", sectionName: "__unwind_info", address: base + 0x3000,
+ size: UInt64(unwind.count), fileOffset: 0x3000),
+ MachOSectionInfo(segmentName: "__TEXT", sectionName: "__gcc_except_tab", address: base + 0x4000,
+ size: UInt64(lsda.count), fileOffset: 0x4000),
+ ]
+ func entries() throws -> [UInt64] {
+ try CustomFirmwareArm64eX1.exceptionEntries(sections: sections, imageBase: base, readMemory: { address, length in
+ let source = address == base + 0x3000 ? unwind : lsda
+ return source.subdata(in: 0 ..< min(length, source.count))
+ })
+ }
+ let landing = try entries()
+ #expect(landing == [base + 0x2010])
+ let code = [Self.pac, Self.ret, Self.pac, Self.add, Self.sub, Self.ret]
+ .reduce(into: Data()) { $0 += ARM64.encodeU32($1) }
+ let result = try CustomFirmwareArm64eX1.planCode(ranges: [(Int(base + 0x2000), code)],
+ seeds: [Int(base + 0x2000)] + landing.map(Int.init), excluded: [], identifier: "test")
+ #expect(result.records.map(\.fileOffset) == [0x2000, 0x2004, 0x2010, 0x2014].map { Int(base) + $0 })
+ #expect(result.unvisitedCandidates == 2)
+ lsda[3] = 5
+ #expect(throws: (any Error).self) { try entries() }
+ lsda[3] = 4; lsda[6] = 0x70
+ #expect(throws: (any Error).self) { try entries() }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheArm64eX1BootstrapTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheArm64eX1BootstrapTests.swift
new file mode 100644
index 00000000..68bf622e
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheArm64eX1BootstrapTests.swift
@@ -0,0 +1,115 @@
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+import VPhonePatchKit
+
+@Suite("X1 shared-cache bootstrap")
+struct DyldSharedCacheArm64eX1BootstrapTests {
+ @Test func `V5 authenticated pointers retain key discriminator and cache base`() throws {
+ let word: UInt64 = 0x8010_4D60_01C6_C73C
+ #expect(try DyldSharedCacheArm64eX1BootstrapPatcher.authenticatedTargetV5(
+ word: word,
+ base: 0x1_8000_0000,
+ diversity: 0x1358,
+ ) == 0x1_81C6_C73C)
+ for invalid in [word ^ (1 << 63), word | (1 << 50), word | (1 << 51)] {
+ #expect(try DyldSharedCacheArm64eX1BootstrapPatcher.authenticatedTargetV5(
+ word: invalid,
+ base: 0x1_8000_0000,
+ diversity: 0x1358,
+ ) == nil)
+ }
+ #expect(try DyldSharedCacheArm64eX1BootstrapPatcher.authenticatedTargetV5(
+ word: word,
+ base: 0,
+ diversity: 0x1359,
+ ) == nil)
+ #expect(throws: (any Error).self) {
+ try DyldSharedCacheArm64eX1BootstrapPatcher.authenticatedTargetV5(
+ word: word,
+ base: UInt64.max,
+ diversity: 0x1358,
+ )
+ }
+ }
+
+ @Test func `cached metadata produces VM-addressed bootstrap writes`() throws {
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let base: UInt64 = 0x1_8000_0000
+ let imageAddress = base + 0x1000
+ var cache = Data(repeating: 0, count: 0x5000)
+ func put32(_ value: UInt32, _ offset: Int) {
+ cache.replaceSubrange(offset ..< offset + 4, with: ARM64.encodeU32(value))
+ }
+ func put64(_ value: UInt64, _ offset: Int) {
+ withUnsafeBytes(of: value.littleEndian) {
+ cache.replaceSubrange(offset ..< offset + 8, with: $0)
+ }
+ }
+ cache.replaceSubrange(0 ..< 15, with: Data("dyld_v1arm64ex1".utf8))
+ put32(0x200, 0x10)
+ put32(1, 0x14)
+ put64(base, 0x200)
+ put64(0x5000, 0x208)
+ put64(0, 0x210)
+ put32(5, 0x218)
+ put32(5, 0x21C)
+
+ let code: [UInt32] = [
+ 0xDAC1_A7FE, 0x9A0B_2909, 0xDA04_2063, 0xF3A0_007F, 0x5520_009F,
+ ]
+ var image = CustomFirmwareArm64eX1Tests.fixture(code)
+ func word(_ value: UInt32, _ offset: Int) {
+ image.replaceSubrange(offset ..< offset + 4, with: ARM64.encodeU32(value))
+ }
+ func quad(_ value: UInt64, _ offset: Int) {
+ withUnsafeBytes(of: value.littleEndian) {
+ image.replaceSubrange(offset ..< offset + 8, with: $0)
+ }
+ }
+ word(3, 16)
+ word(240, 20)
+ quad(imageAddress, 56)
+ quad(0x1000, 64)
+ quad(0x1000, 72)
+ quad(0x1000, 80)
+ quad(imageAddress + 0x200, 136)
+ word(0x1200, 152)
+ word(0x3300, 192)
+ word(0x19, 200)
+ word(72, 204)
+ image.replaceSubrange(
+ 208 ..< 224,
+ with: Data("__LINKEDIT".utf8) + Data(repeating: 0, count: 6),
+ )
+ quad(base + 0x3000, 224)
+ quad(0x1000, 232)
+ quad(0x3000, 240)
+ quad(0x1000, 248)
+ cache.replaceSubrange(0x1000 ..< 0x1110, with: image[0 ..< 272])
+ cache.replaceSubrange(0x1200 ..< 0x1214, with: image[0x200 ..< 0x214])
+ cache.replaceSubrange(0x3300 ..< 0x3303, with: Data([0x80, 0x04, 0]))
+ let url = directory.appendingPathComponent("dyld_shared_cache_arm64e_x1")
+ try cache.write(to: url)
+
+ let chunks = try DyldSharedCacheChunkSet(directory: directory)
+ let plan = try DyldSharedCacheArm64eX1BootstrapPatcher.planImage(
+ at: imageAddress,
+ in: chunks,
+ )
+ #expect(plan.records.count == 5)
+ #expect(plan.records.first?.fileOffset == Int(imageAddress + 0x200))
+ #expect(plan.records.first?.patchedBytes == ARM64.pacibsp)
+ #expect(plan.records.last?.patchedBytes == ARM64.retab)
+ #expect(try Data(contentsOf: url) == cache)
+
+ put32(0x9000, 0x1000 + 192)
+ try cache.write(to: url)
+ #expect(throws: (any Error).self) {
+ try DyldSharedCacheArm64eX1BootstrapPatcher.planImage(at: imageAddress, in: chunks)
+ }
+ #expect(try Data(contentsOf: url) == cache)
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheCameraPatcherTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheCameraPatcherTests.swift
index 46106561..bf8d7a63 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheCameraPatcherTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheCameraPatcherTests.swift
@@ -606,6 +606,9 @@ struct DyldSharedCacheCameraPatcherBehaviourTests {
let pristinePrologue = try classify(ARM64.pacibsp + ARM64.nop)
#expect(pristinePrologue == false)
+ let x1Prologue = ARM64.encodeU32(CustomFirmwareArm64eX1Tests.pac) + ARM64.nop
+ #expect(try classify(x1Prologue) == false)
+
// The replacement itself — already patched.
let ownOutput = try classify(replacement)
#expect(ownOutput == true)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMaxSlidePatcherTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMaxSlidePatcherTests.swift
index 8291a84a..ec9283dd 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMaxSlidePatcherTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMaxSlidePatcherTests.swift
@@ -933,17 +933,49 @@ struct DyldSharedCacheRegionCheckTests {
private func withCache(
regionSize: UInt64,
maxSlide: UInt64 = 0x2000_0000,
+ magic: String = "dyld_v1 arm64e",
_ body: (URL) throws -> Void,
) throws {
let directory = FileManager.default.temporaryDirectory
.appendingPathComponent("vphone-dsc-region-\(UUID().uuidString)")
defer { try? FileManager.default.removeItem(at: directory) }
try DyldSharedCacheMaxSlideGateTests.writeCache(
- into: directory, regionSize: regionSize, maxSlide: maxSlide,
+ into: directory, regionSize: regionSize, maxSlide: maxSlide, magic: magic,
)
try body(directory)
}
+ @Test
+ func `An x1 cache uses its own header symbols and subcaches`() throws {
+ try withCache(regionSize: 0x1_7D50_8000, magic: "dyld_v1arm64ex1") { directory in
+ let main = directory.appendingPathComponent(MaxSlideFixture.mainChunkName)
+ let x1 = directory.appendingPathComponent("dyld_shared_cache_arm64e_x1")
+ try FileManager.default.moveItem(at: main, to: x1)
+ try Data().write(to: x1.appendingPathExtension("symbols"))
+ try Data().write(to: x1.appendingPathExtension("01"))
+ let chunks = try DyldSharedCacheChunkSet(directory: directory)
+ #expect(chunks.mainCacheURL == x1)
+ #expect(chunks.localSymbolsURL == x1.appendingPathExtension("symbols"))
+ #expect(chunks.chunkURLs.map(\.lastPathComponent) == [x1.lastPathComponent, x1.lastPathComponent + ".01"])
+ #expect(try DyldSharedCacheMaxSlidePatcher.requireFitsAtSlideZero(chunksDirectory: directory) == 0x1_7D50_8000)
+ let result = try DyldSharedCacheMaxSlidePatcher.patch(chunksDirectory: directory, dryRun: true, verbose: false)
+ #expect(result.sharedRegionSize == 0x1_7D50_8000)
+ #expect(DyldSharedCacheChunkSet.mainCacheURL(in: directory, architecture: "arm64e") == main)
+ }
+ }
+
+ @Test
+ func `A regular cache never includes x1 chunks from the same directory`() throws {
+ try withCache(regionSize: 0x1_7D50_8000) { directory in
+ let x1 = directory.appendingPathComponent("dyld_shared_cache_arm64e_x1")
+ try Data().write(to: x1)
+ try Data().write(to: x1.appendingPathExtension("01"))
+ let chunks = try DyldSharedCacheChunkSet(directory: directory)
+ #expect(chunks.chunkURLs.map(\.lastPathComponent) == [MaxSlideFixture.mainChunkName])
+ #expect(chunks.mainCacheURL.lastPathComponent == MaxSlideFixture.mainChunkName)
+ }
+ }
+
@Test
func `An iPhone18,2 27.0.1 cache overruns the region even at slide 0`() throws {
try withCache(regionSize: 0x1_8580_4000) { directory in
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelCustomFirmwarePatchArm64eX1Tests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelCustomFirmwarePatchArm64eX1Tests.swift
new file mode 100644
index 00000000..f325c3d1
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelCustomFirmwarePatchArm64eX1Tests.swift
@@ -0,0 +1,111 @@
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+import VPhonePatchKit
+
+@Suite("kernel-boot-arm64e_x1")
+struct KernelCustomFirmwarePatchArm64eX1Tests {
+ // vphone600 UUID 784F88D3-2AF5-3D4A-AB00-365607646E44 instruction fixtures.
+ static let grade = Data(base64Encoded: "iNA41QjNQPkICUC5qQGAUh8FAHEpAZ8aHwQIcigBiBqJAYBSCUCgch8ACWsAAgBUiQGAUgkgoHIfAAlroQMAVB8JAHEgAgBUHwUAcSEDAFQoAYBSPwAAcQgBnxpJAYBSPwQAcSABiBrAA1/WPwQAcQECAFQIBQBRHwkAcaIBAFQAAYBSwANf1sEBADQ/BABxQAEAVD8IAHHBAABUXwwIcmgBgFIIFYgaAH2CCsADX9YAAIBSwANf1kABgFLAA1/WIAGAUsADX9Y=")!
+ static let exec = Data(base64Encoded: "MQgGlOkDAKoJAgA0CAdAuYkBgFIJQKByHwEJayABAFSJAYBSCSCgch8BCWshAQBUCAtAuQhtABIfCQBxoQAAVIh6ABIEAAAUwAqAUjABABSIAgEyaEoAuQ==")!
+ static let shared = Data(base64Encoded: "qM5FuQhtABIfCQBxYQMAVGhKQLkoA/g36JNDOSgXGDdgmkH5AB0AtLbN65f5AwCqwC//8ABAMJEfIAPVwC//8ADAMJEhBwCRAgCQUgMAgNIAS+2X+AMAqmGaQfkiBwCRvLbrl2hKQLkaMQxTWQCAUvgBALUEAAAUGQCAUmhKQLkaMQxT")!
+
+ static func fixture(duplicateExec: Bool = false, cave: Bool = true) throws -> (KernelCustomFirmwarePatcher, Int, Int) {
+ var block = grade + Data(repeating: 0xD4, count: 32)
+ let execRelative = block.count
+ block += exec
+ if duplicateExec { block += Data(repeating: 0xD4, count: 32) + exec }
+ block += Data(repeating: 0xD4, count: 0x300 - block.count)
+ block += shared
+ block += Data(repeating: 0xD4, count: 0x100)
+ if cave { block += Data(repeating: 0, count: 64) }
+ var (image, gradeOffset) = KernelCustomFirmwarePatchSharedRegionSizeTests.kernel(withBlock: Array(block))
+ let execOffset = gradeOffset + execRelative
+ image.replaceSubrange(execOffset ..< execOffset + 4, with: try #require(ARM64Encoder.encodeBL(from: execOffset, to: gradeOffset)))
+ if duplicateExec {
+ let other = execOffset + exec.count + 32
+ image.replaceSubrange(other ..< other + 4, with: try #require(ARM64Encoder.encodeBL(from: other, to: gradeOffset)))
+ }
+ let patcher = KernelCustomFirmwarePatcher(data: image, verbose: false)
+ patcher.parseMachO()
+ patcher.buildBLIndex()
+ return (patcher, gradeOffset, execOffset)
+ }
+
+ @Test func `widens only the grade and exec subtype comparisons`() throws {
+ let (patcher, grade, exec) = try Self.fixture()
+ #expect(patcher.patchArm64eX1Admission())
+ #expect(patcher.patches.count == 6)
+ let compares = [grade + 0x94, exec + 0x38, grade + 0x308]
+ let decoder = ARM64Disassembler()
+ for (offset, register) in zip(compares, [ARM64Register.w(1), .w(8), .w(8)]) {
+ let branch = try #require(decoder.disassembleOne(in: patcher.patchedData, at: offset))
+ #expect(branch.mnemonic == "b")
+ let target = try #require(branch.detail?.operands.first?.imm)
+ let trampoline = decoder.disassemble(in: patcher.patchedData, at: Int(target), count: 3)
+ #expect(trampoline.map(\.mnemonic) == ["cmp", "ccmp", "b"])
+ #expect(trampoline[0].detail?.operands.first?.reg == register)
+ #expect(trampoline[0].detail?.operands.last?.imm == 12)
+ #expect(trampoline[1].detail?.operands.first?.reg == register)
+ #expect(trampoline[1].detail?.operands[1].imm == 2)
+ #expect(trampoline[1].detail?.operands[2].imm == 6)
+ #expect(trampoline[2].detail?.operands.first?.imm == Int64(offset + 4))
+ #expect(patcher.patchedData[(offset + 4) ..< (offset + 20)] == patcher.buffer.original[(offset + 4) ..< (offset + 20)])
+ }
+ let written = Set(patcher.patches.flatMap { $0.fileOffset ..< $0.fileOffset + $0.patchedBytes.count })
+ for position in patcher.patchedData.indices where !written.contains(position) {
+ #expect(patcher.patchedData[position] == patcher.buffer.original[position])
+ }
+ }
+
+ @Test func `ambiguous exec and missing cave leave the entire kernel unchanged`() throws {
+ for (duplicate, cave) in [(true, true), (false, false)] {
+ let (patcher, _, _) = try Self.fixture(duplicateExec: duplicate, cave: cave)
+ #expect(!patcher.patchArm64eX1Admission())
+ #expect(patcher.patches.isEmpty)
+ #expect(patcher.patchedData == patcher.buffer.original)
+ }
+ }
+
+ @Test func `rejects changed PAC ABI and flags paths before writing`() throws {
+ let (original, grade, exec) = try Self.fixture()
+ for offset in [grade + 0x9C, exec + 0x54, grade + 0x36C] {
+ var image = original.buffer.original
+ image.replaceSubrange(offset ..< offset + 4, with: ARM64.nop)
+ let patcher = KernelCustomFirmwarePatcher(data: image, verbose: false)
+ patcher.parseMachO()
+ patcher.buildBLIndex()
+ #expect(!patcher.patchArm64eX1Admission())
+ #expect(patcher.patches.isEmpty)
+ #expect(patcher.patchedData == image)
+ }
+ }
+
+ @Test func `does not patch an already widened kernel again`() throws {
+ let (original, _, _) = try Self.fixture()
+ #expect(original.patchArm64eX1Admission())
+ let patcher = KernelCustomFirmwarePatcher(data: original.patchedData, verbose: false)
+ patcher.parseMachO()
+ patcher.buildBLIndex()
+ #expect(!patcher.patchArm64eX1Admission())
+ #expect(patcher.patches.isEmpty)
+ }
+
+ @Test func `standard enables the complete X1 path only for its iOS gate`() throws {
+ let identifiers = [
+ "kernel-boot-arm64e_x1",
+ FirmwareGuestSystemPatchSet.arm64eX1DyldBootstrap,
+ FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap,
+ FirmwareGuestSystemPatchSet.arm64eX1LaunchdBootstrap,
+ FirmwareGuestSystemPatchSet.arm64eX1FsckBootstrap,
+ FirmwareGuestSystemPatchSet.arm64eX1MountBootstrap,
+ ]
+ for base in ["26.4", "27.0.1", "28.0"] {
+ let standard = try VPhonePatchPlan.resolve(preset: FirmwarePatchSetCatalog.standardPreset,
+ patchSets: FirmwarePatchSetCatalog.bundled, iOSBase: VPhoneVersion(base), cloudOS: VPhoneVersion("26.4"))
+ for identifier in identifiers {
+ #expect(standard.isEnabled(identifier) == base.hasPrefix("27."))
+ }
+ }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
index 5ea20573..c579326e 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
@@ -99,6 +99,16 @@ struct FirmwareGuestPatchResolutionTests {
#expect(tv4K27.enabled.isSuperset(of: FirmwarePatchSetCatalog.tvOS27UserlandPatches))
#expect(tv4K27.isEnabled("kernel-boot-iomfb_swapend"))
#expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: tv4K27.enabled, arm64eUserland: true).isEmpty)
+ let x1Patches: Set<String> = [
+ FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap,
+ FirmwareGuestSystemPatchSet.arm64eX1DyldBootstrap,
+ FirmwareGuestSystemPatchSet.arm64eX1FsckBootstrap,
+ FirmwareGuestSystemPatchSet.arm64eX1LaunchdBootstrap,
+ FirmwareGuestSystemPatchSet.arm64eX1MountBootstrap,
+ "kernel-boot-arm64e_x1",
+ "restoreramdisk-boot-apfs_sha3_hash",
+ ]
+ #expect(tv4K27.enabled.isDisjoint(with: x1Patches))
// The HD's preset is the mirror image.
let tvHD = try plan(FirmwarePatchSetCatalog.tvOSPreset)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchDriftTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchDriftTests.swift
index 33298d7d..6d2252be 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchDriftTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchDriftTests.swift
@@ -35,6 +35,7 @@ struct FirmwarePatchDriftTests {
patch("kernel-a", .firmware(.kernelcache)),
patch("kernel-b", .firmware(.kernelcache)),
patch("txm", .firmware(.txm)),
+ patch("ramdisk", .firmware(.restoreRamDisk)),
patch("dyld", .dyldSharedCache),
patch("dt", .prebootDeviceTree),
patch("tree-node", .firmware(.deviceTree)),
@@ -49,12 +50,13 @@ struct FirmwarePatchDriftTests {
enabledPatches: ["avp", "ibss", "kernel-b", "kernel-a", "dyld"],
declarations: declarations,
)
- #expect(Set(parts.keys) == [.iBSS, .iBEC, .llb, .txm, .kernelcache, .deviceTree])
+ #expect(Set(parts.keys) == [.iBSS, .iBEC, .llb, .txm, .restoreRamDisk, .kernelcache, .deviceTree])
#expect(parts[.iBSS] == ["ibss"])
#expect(parts[.kernelcache] == ["kernel-a", "kernel-b"])
// Off in the plan, or declaring nothing: recorded empty, not unknown.
#expect(parts[.llb] == [])
#expect(parts[.iBEC] == [])
+ #expect(parts[.restoreRamDisk] == [])
#expect(parts[.deviceTree] == [])
// AVPBooter never leaves the VM folder, and guest patches are written
// by cfw install, not by a restore.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/PatchSetLoaderTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/PatchSetLoaderTests.swift
index 4abb4158..8bf25c42 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/PatchSetLoaderTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/PatchSetLoaderTests.swift
@@ -459,7 +459,7 @@ struct PatchSetPlanIntegrationTests {
#expect(plan.includesPatchSet(ExamplePatchSet.identifier))
#expect(!pipeline.loadedPatchSets.isEmpty)
- let components = pipeline.buildComponentList(
+ let components = try pipeline.buildComponentList(
restoreDir: directory,
iOSBase: VPhoneVersion("27.0"),
plan: plan,
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Pipeline/FirmwarePipelineOriginalsTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Pipeline/FirmwarePipelineOriginalsTests.swift
index c2afddff..89f80cd9 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Pipeline/FirmwarePipelineOriginalsTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Pipeline/FirmwarePipelineOriginalsTests.swift
@@ -222,10 +222,10 @@ struct FirmwarePipelineOriginalsTests {
#expect(pipeline.originalURL(for: vm.stashURL) == nil)
}
- @Test func `only the two whole-tree components opt out of keeping an original`() {
+ @Test func `only the two whole-tree components opt out of keeping an original`() throws {
let root = URL(fileURLWithPath: NSTemporaryDirectory())
let pipeline = FirmwarePipeline(vmDirectory: root, variant: .less, verbose: false)
- let components = pipeline.buildComponentList(restoreDir: root, iOSBase: VPhoneVersion("26.6.2"))
+ let components = try pipeline.buildComponentList(restoreDir: root, iOSBase: VPhoneVersion("26.6.2"))
let notRestorable = components.filter { !$0.restorable }.map(\.name).sorted()
#expect(notRestorable == ["Filesystem", "Manifest"])
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Restore/RestoreRamDiskSealPatcherTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Restore/RestoreRamDiskSealPatcherTests.swift
new file mode 100644
index 00000000..4b0c4c1b
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Restore/RestoreRamDiskSealPatcherTests.swift
@@ -0,0 +1,65 @@
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+
+@Suite("Restore ramdisk APFS seal compatibility")
+struct RestoreRamDiskSealPatcherTests {
+ @Test
+ func `v1 trust cache replacement stays sorted and preserves metadata`() throws {
+ let oldHash = Data(repeating: 0x20, count: 20)
+ let newHash = Data(repeating: 0x05, count: 20)
+ let low = Data(repeating: 0x10, count: 20)
+ let high = Data(repeating: 0x30, count: 20)
+
+ var cache = Data()
+ append(UInt32(1), to: &cache)
+ cache.append(Data(repeating: 0xAB, count: 16))
+ append(UInt32(3), to: &cache)
+ cache.append(entry(low, hashType: 2, flags: 1))
+ cache.append(entry(oldHash, hashType: 2, flags: 7))
+ cache.append(entry(high, hashType: 2, flags: 3))
+
+ let result = try RestoreTrustCacheSealPatcher.replacingCDHash(
+ in: cache,
+ from: oldHash,
+ to: newHash,
+ )
+ #expect(result.changedRange == 24 ..< 24 + 44)
+ #expect(result.data.prefix(24) == cache.prefix(24))
+ #expect(cache[result.changedRange] != result.data[result.changedRange])
+
+ let entries = (0 ..< 3).map { index in
+ Data(result.data[24 + index * 22 ..< 24 + (index + 1) * 22])
+ }
+ #expect(entries.map { Data($0.prefix(20)) } == [newHash, low, high])
+ #expect(entries[0].suffix(2) == Data([2, 7]))
+ #expect(entries[1].suffix(2) == Data([2, 1]))
+ #expect(entries[2].suffix(2) == Data([2, 3]))
+ }
+
+ @Test
+ func `v1 trust cache requires exactly one old cdhash`() throws {
+ let oldHash = Data(repeating: 0x20, count: 20)
+ let newHash = Data(repeating: 0x21, count: 20)
+ var cache = Data()
+ append(UInt32(1), to: &cache)
+ cache.append(Data(repeating: 0, count: 16))
+ append(UInt32(1), to: &cache)
+ cache.append(entry(Data(repeating: 0x10, count: 20), hashType: 2, flags: 0))
+
+ #expect(throws: (any Error).self) {
+ try RestoreTrustCacheSealPatcher.replacingCDHash(in: cache, from: oldHash, to: newHash)
+ }
+ }
+
+ private func entry(_ hash: Data, hashType: UInt8, flags: UInt8) -> Data {
+ var result = hash
+ result.append(hashType)
+ result.append(flags)
+ return result
+ }
+
+ private func append(_ value: UInt32, to data: inout Data) {
+ withUnsafeBytes(of: value.littleEndian) { data.append(contentsOf: $0) }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj/project.pbxproj b/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj/project.pbxproj
index 905bea19..5319d3dc 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj/project.pbxproj
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj/project.pbxproj
@@ -1020,7 +1020,7 @@
repositoryURL = "https://github.com/p-x9/MachOKit.git";
requirement = {
kind = upToNextMajorVersion;
- minimumVersion = 0.52.2;
+ minimumVersion = 0.54.1;
};
};
BB0000000000000000000174 /* XCRemoteSwiftPackageReference "swift-argument-parser" */ = {
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
index 004aa9ff..4da56e43 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
@@ -42,8 +42,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/p-x9/MachOKit.git",
"state" : {
- "revision" : "773e10797abc53914b94c2ee8c6f40f5da0b06eb",
- "version" : "0.52.2"
+ "revision" : "659d8d5adfba8f11b4a0e05c3b3c8aa59f017492",
+ "version" : "0.54.1"
}
},
{
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift
index a0172704..0ad180e7 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift
@@ -51,7 +51,7 @@ struct DyldSharedCacheUndoOptions: ParsableArguments {
/// chunk, not 0777: it lives inside the guest System volume, whose modes
/// stay unchanged (AGENTS.md).
func persist(_ captured: DyldSharedCacheUndoLog, dryRun: Bool) throws {
- guard let undoLog, captures, !dryRun else { return }
+ guard let undoLog, captures, !dryRun, !captured.records.isEmpty else { return }
let url = URL(fileURLWithPath: undoLog)
let existing = (try? Data(contentsOf: url)).flatMap { try? DyldSharedCacheUndoLog.decode($0) }
guard let merged = DyldSharedCacheUndoLog.updated(
@@ -61,7 +61,7 @@ struct DyldSharedCacheUndoOptions: ParsableArguments {
// Match the cache chunk's owner and mode rather than widening it: the
// directory name is the cache directory, so its main chunk is the
// reference for what a file here should be owned and permissioned as.
- let mainChunk = url.deletingLastPathComponent().appendingPathComponent("dyld_shared_cache_arm64e")
+ let mainChunk = DyldSharedCacheChunkSet.mainCacheURL(in: url.deletingLastPathComponent())
var metadata = stat()
if lstat(mainChunk.path, &metadata) == 0 {
chmod(url.path, metadata.st_mode & 0o7777)
@@ -75,6 +75,7 @@ enum VPhoneCustomFirmwareDyldSharedCacheVerbs {
static var all: [ParsableCommand.Type] {
[
VPhoneCustomFirmwarePatchSettingsSoftwareUpdateCommand.self,
+ VPhoneCustomFirmwarePatchArm64eX1BootstrapCacheCommand.self,
VPhoneCustomFirmwareDyldSharedCacheRevertCommand.self,
VPhoneCustomFirmwarePatchHypervisorVirtualMachineDyldSharedCacheCommand.self,
VPhoneCustomFirmwarePatchIOMFBSwapEndCommand.self,
@@ -117,6 +118,29 @@ enum VPhoneCustomFirmwareDyldSharedCacheVerbs {
}
}
+struct VPhoneCustomFirmwarePatchArm64eX1BootstrapCacheCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "patch-arm64e-x1-bootstrap-cache",
+ abstract: "Lower the cache code needed before launchd installs on-demand X1 handling",
+ )
+
+ @Argument(transform: URL.init(fileURLWithPath:)) var directory: URL
+ @Flag(name: .customLong("dry-run")) var dryRun = false
+ @OptionGroup var undo: DyldSharedCacheUndoOptions
+
+ func run() throws {
+ var captured = DyldSharedCacheUndoLog()
+ try DyldSharedCacheArm64eX1BootstrapPatcher.patch(
+ directory: directory,
+ dryRun: dryRun,
+ captureUndo: undo.captures,
+ onUndo: { captured.merge($0) },
+ log: VPhoneCustomFirmwareDyldSharedCacheVerbs.stdout,
+ )
+ try undo.persist(captured, dryRun: dryRun)
+ }
+}
+
// MARK: - patch-hv-vmm-dsc
struct VPhoneCustomFirmwarePatchHypervisorVirtualMachineDyldSharedCacheCommand: ParsableCommand {
@@ -548,14 +572,13 @@ struct VPhoneCustomFirmwarePatchCameraDyldSharedCacheCommand: ParsableCommand {
return, which is what makes the app launch-survivable.
<dsc_header> is the unsuffixed `dyld_shared_cache_arm64e` file — the one
- the symbols resolve against, not a chunk. The Python takes it as a
- separate argument because `ipsw dyld symaddr` wants a file; it is passed
- through for the same reason.
+ whose local-symbol table resolves the entry points, not a subcache.
--force accepts an entry point whose prologue is neither the expected
- `pacibsp` nor the replacement already in place, which is otherwise
- refused rather than overwritten blind. Modified pages are re-attested;
- an already-patched cache is a no-op.
+ authenticated B-key stack form nor the replacement already in place,
+ which is otherwise refused rather than overwritten blind. Both legacy
+ `pacibsp` and the X1 PC-bound form are expected. Modified pages are
+ re-attested; an already-patched cache is a no-op.
""",
)
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
index af610b96..0ba13a5c 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
@@ -671,9 +671,12 @@ struct VPhoneCustomFirmwareInstaller {
try work.directory.setMode("Disk.img", disk.mode & 0o777)
try work.directory.rename("Disk.img", to: "Disk.img", in: bundleDirectory)
}
- if changed {
- recordKernelcacheReceipt(enabled: enabledKernelPatches, in: bundleDirectory, owner: invokingUser.map { ($0.uid, $0.gid) })
- }
+ // Record the selected identifiers even when the bytes were already present.
+ recordKernelcacheReceipt(
+ enabled: enabledKernelPatches,
+ in: bundleDirectory,
+ owner: invokingUser.map { ($0.uid, $0.gid) },
+ )
print("[+] Guest kernel updated; start the VM to boot the re-patched kernelcache")
}
@@ -1171,6 +1174,19 @@ struct VPhoneCustomFirmwareInstaller {
}
let version = try productVersion(system: system)
+ if version.hasPrefix("27.") || priorGuest.contains(FirmwareGuestSystemPatchSet.arm64eX1DyldBootstrap) {
+ machO(FirmwareGuestSystemPatchSet.arm64eX1DyldBootstrap, path: "usr/lib/dyld",
+ verbs: ["patch-arm64e-x1"], preserveEntitlements: true)
+ }
+ if version.hasPrefix("27.") || priorGuest.contains(FirmwareGuestSystemPatchSet.arm64eX1FsckBootstrap) {
+ machO(FirmwareGuestSystemPatchSet.arm64eX1FsckBootstrap, path: "sbin/fsck",
+ verbs: ["patch-arm64e-x1"], preserveEntitlements: true)
+ }
+ if version.hasPrefix("27.") || priorGuest.contains(FirmwareGuestSystemPatchSet.arm64eX1MountBootstrap) {
+ machO(FirmwareGuestSystemPatchSet.arm64eX1MountBootstrap, path: "sbin/mount",
+ verbs: ["patch-arm64e-x1"], preserveEntitlements: true)
+ }
+
// 0. A cache whose span alone overruns the guest kernel's shared region
// maps at no slide, and the guest panics on first boot. Refuse before
// the redeploy and the cache patches. A header this check cannot read
@@ -1258,6 +1274,7 @@ struct VPhoneCustomFirmwareInstaller {
var dyld: [(id: String, verb: String, args: [String])] = []
if version.hasPrefix("27.") {
dyld += [
+ (FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap, "patch-arm64e-x1-bootstrap-cache", [dsc]),
("dyld-boot-iomfb_force_kern", "patch-iomfb-force-kern", [dsc]),
("dyld-boot-maxslide", "patch-dsc-maxslide", [dsc]),
("dyld-boot-lsd_embedded_reg", "patch-lsd-embedded-reg", [dsc]),
@@ -1271,7 +1288,7 @@ struct VPhoneCustomFirmwareInstaller {
(FirmwareGuestSystemPatchSet.settingsSoftwareUpdate, "patch-settings-software-update", [dsc]),
(FirmwarePatchSetCatalog.misTrustAuthPatch, "patch-mis-trust-auth", [dsc]),
("dyld-exp-hv_vmm", "patch-hv-vmm-dsc", [dsc]),
- ("dyld-cfw-camera", "patch-camera-dsc", [dsc, (dsc as NSString).appendingPathComponent("dyld_shared_cache_arm64e")]),
+ ("dyld-cfw-camera", "patch-camera-dsc", [dsc, DyldSharedCacheChunkSet.mainCacheURL(in: URL(fileURLWithPath: dsc)).path]),
]
applyDyldPatches(
dyld, dsc: dsc, cacheRelative: cacheRelative, system: system, plan: plan, priorGuest: priorGuest,
@@ -1528,7 +1545,32 @@ struct VPhoneCustomFirmwareInstaller {
}
}
- machO("system-launchd-boot-jetsam_panic_guard_bypass", path: "sbin/launchd", verbs: ["patch-launchd-jetsam"], preserveEntitlements: true, injectedDylibPath: "/vh")
+ let launchdJetsam = "system-launchd-boot-jetsam_panic_guard_bypass"
+ let launchdX1 = FirmwareGuestSystemPatchSet.arm64eX1LaunchdBootstrap
+ isolate([launchdJetsam, launchdX1]) {
+ let enabled = [launchdJetsam, launchdX1].filter(on)
+ if !enabled.isEmpty {
+ var verbs: [String] = []
+ if enabled.contains(launchdJetsam) { verbs.append("patch-launchd-jetsam") }
+ if enabled.contains(launchdX1) { verbs.append("patch-arm64e-x1") }
+ try patchMachO(
+ system: system,
+ work: work,
+ path: "sbin/launchd",
+ verbs: verbs,
+ preserveEntitlements: true,
+ injectedDylibPath: "/vh",
+ )
+ live.formUnion(enabled)
+ } else if try revertMachO(system: system, work: work, path: "sbin/launchd") {
+ print(" [+] launchd patches: restored sbin/launchd from backup")
+ } else {
+ for identifier in [launchdJetsam, launchdX1] where priorGuest.contains(identifier) {
+ print(" [!] \(identifier): off now but no backup to revert; leaving launchd patched (not revertible)")
+ live.insert(identifier)
+ }
+ }
+ }
isolate([]) { try restoreMISFixTargets(system: system) }
@@ -1584,11 +1626,11 @@ struct VPhoneCustomFirmwareInstaller {
return live
}
- /// Live dyld patches whose verb runs again on every install. Each is cheap
- /// and idempotent, and its earlier implementation left records identical to
- /// the current one's, so `hasOutdatedImplementation` cannot single it out:
- /// `dyld-boot-maxslide` once left page 0's slot stale, and a re-run repairs it.
- private static let dyldPatchesRerunWhenLive: Set<String> = ["dyld-boot-maxslide"]
+ /// Idempotent dyld patches whose receipts cannot identify stale implementations.
+ private static let dyldPatchesRerunWhenLive: Set<String> = [
+ "dyld-boot-maxslide",
+ FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap,
+ ]
/// Apply the enabled dyld cache patches whose state differs from what was
/// live before, and revert the disabled ones from the undo log the earlier
@@ -2687,6 +2729,13 @@ struct VPhoneCustomFirmwareInstaller {
let staged = work.file(name)
try work.directory.removeItem(name)
try system.copyFile(from: backup, to: name, in: work.directory)
+ // Preserve the original CodeDirectory identifier unless explicitly overridden.
+ let signingIdentifier: String?
+ if let identifier {
+ signingIdentifier = identifier
+ } else {
+ signingIdentifier = try VPhoneSigner.identifier(ofFileAt: staged)
+ }
let entitlements =
preserveEntitlements
? try VPhoneSigner.entitlements(ofFileAt: staged).first(where: { !$0.isEmpty })
@@ -2705,7 +2754,12 @@ struct VPhoneCustomFirmwareInstaller {
// bundle-shipped guest dylibs all carry the flag; match them.
try VPhoneSigner.sign(
fileAt: staged,
- options: .init(identifier: identifier, entitlements: entitlements, mergesExisting: true, style: .appleAdHoc),
+ options: .init(
+ identifier: signingIdentifier,
+ entitlements: entitlements,
+ mergesExisting: true,
+ style: .appleAdHoc,
+ ),
)
try system.replaceFile(path, fromFileAt: staged, mode: 0o755, owner: Self.guestOwner)
}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift
index 318f310d..99a6fec2 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift
@@ -42,6 +42,32 @@ import VPhonePatchKit
/// Where these verbs send patcher progress: stdout, like the Python.
private let machOVerbLog: @Sendable (String) -> Void = { print($0) }
+struct VPhoneCustomFirmwarePatchArm64eX1Command: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "patch-arm64e-x1",
+ abstract: "Lower X1 instructions in a boot-critical executable",
+ discussion: "Supports dyld, launchd, fsck and mount. Later userland instructions are handled on demand. Re-attests modified code pages.",
+ )
+ @Argument(transform: URL.init(fileURLWithPath:)) var binary: URL
+ func run() throws {
+ try requireUntruncatedMachO(at: binary)
+ let identifier: String
+ switch binary.lastPathComponent {
+ case "dyld": identifier = FirmwareGuestSystemPatchSet.arm64eX1DyldBootstrap
+ case "launchd": identifier = FirmwareGuestSystemPatchSet.arm64eX1LaunchdBootstrap
+ case "fsck": identifier = FirmwareGuestSystemPatchSet.arm64eX1FsckBootstrap
+ case "mount": identifier = FirmwareGuestSystemPatchSet.arm64eX1MountBootstrap
+ default:
+ throw ValidationError("X1 static lowering is limited to the measured boot roots: dyld, launchd, fsck and mount")
+ }
+ try CustomFirmwareArm64eX1.patch(
+ fileAt: binary,
+ identifier: identifier,
+ log: machOVerbLog,
+ )
+ }
+}
+
// MARK: - Truncation guard
/// Refuse a file whose Mach-O header promises more than the file holds.
@@ -553,6 +579,7 @@ enum VPhoneCustomFirmwareMachOVerbs {
VPhoneCustomFirmwarePatchLaunchdCacheLoaderCommand.self,
VPhoneCustomFirmwarePatchMobileactivationdCommand.self,
VPhoneCustomFirmwarePatchLaunchdJetsamCommand.self,
+ VPhoneCustomFirmwarePatchArm64eX1Command.self,
VPhoneCustomFirmwarePatchWatchdogdCommand.self,
VPhoneCustomFirmwarePatchDiskimagesiodCommand.self,
VPhoneCustomFirmwarePatchVirtualAudioCommand.self,
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Constants.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Constants.swift
index 0501a7ce..1c757702 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Constants.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Constants.swift
@@ -26,6 +26,14 @@ public enum ARM64 {
/// PACIBSP — sign LR with B key using SP (hint #27)
public static let pacibsp = encodeU32(0xD503_237F)
+ /// Keystone-verified pointer-authentication aliases.
+ public static let paciasp = encodeU32(0xD503_233F)
+ public static let autiasp = encodeU32(0xD503_23BF)
+ public static let autibsp = encodeU32(0xD503_23FF)
+
+ public static let autia1716 = encodeU32(0xD503_219F)
+ public static let autib1716 = encodeU32(0xD503_21DF)
+
// MARK: MOV Variants
/// MOV X0, #0 (MOVZ X0, #0)
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Disassembler.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Disassembler.swift
index 81460c80..bbd8f956 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Disassembler.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Disassembler.swift
@@ -96,7 +96,7 @@ extension ARM64Instruction {
groups = withUnsafeBytes(of: rawDetail.groups) { buffer in
Array(buffer.prefix(Int(rawDetail.groups_count)))
}
- detail = ARM64InstructionDetail(rawDetail.aarch64)
+ detail = ARM64InstructionDetail(rawDetail.aarch64, writeback: rawDetail.writeback)
}
self.init(
@@ -115,7 +115,7 @@ extension ARM64Instruction {
}
extension ARM64InstructionDetail {
- init(_ raw: cs_aarch64) {
+ init(_ raw: cs_aarch64, writeback: Bool) {
let operands = withUnsafeBytes(of: raw.operands) { buffer in
let pointer = buffer.baseAddress!.assumingMemoryBound(to: cs_aarch64_op.self)
let capacity = buffer.count / MemoryLayout<cs_aarch64_op>.stride
@@ -127,6 +127,7 @@ extension ARM64InstructionDetail {
postIndex: raw.post_index,
operands: operands,
)
+ self.writeback = writeback
}
}
@@ -147,7 +148,9 @@ extension ARM64Operand {
index: ARM64Register(rawValue: raw.mem.index.rawValue),
disp: raw.mem.disp,
),
+ shift: ARM64OperandShift(type: ARM64ShiftType(rawValue: raw.shift.type.rawValue) ?? .unsupported, amount: raw.shift.value),
)
+ self.writesRegister = raw.access.rawValue & CS_AC_WRITE.rawValue != 0
}
}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
index a67d731d..1028df7b 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
@@ -19,7 +19,7 @@ import Foundation
/// ARM64 condition codes, `cond` in bits [15:12] of the conditional-select family.
///
/// Only the 14 invertible conditions exist here. `AL` (0b1110) and `NV` (0b1111)
-/// are each other's inverse and are rejected by CSET, which is the only consumer.
+/// are each other's inverse and are rejected by CSET.
public enum ARM64Condition: UInt32, Sendable, CaseIterable {
case eq = 0b0000 // equal — Z == 1
case ne = 0b0001 // not equal
@@ -47,6 +47,40 @@ public enum ARM64Condition: UInt32, Sendable, CaseIterable {
}
public enum ARM64Encoder {
+ // MARK: - Register arithmetic
+
+ /// MADD/MSUB X-register form; register 31 is XZR.
+ public static func encodeMaddSubX(subtract: Bool, rd: UInt32, rn: UInt32, rm: UInt32, ra: UInt32) -> Data? {
+ guard rd < 32, rn < 32, rm < 32, ra < 32 else { return nil }
+ return ARM64.encodeU32((subtract ? 0x9B00_8000 : 0x9B00_0000) | (rm << 16) | (ra << 10) | (rn << 5) | rd)
+ }
+
+ /// Shifted ADD/SUB X-register form; register 31 is XZR.
+ public static func encodeAddSubXShifted(subtract: Bool, rd: UInt32, rn: UInt32, rm: UInt32, shift: UInt32 = 0) -> Data? {
+ guard rd < 32, rn < 32, rm < 32, shift < 64 else { return nil }
+ return ARM64.encodeU32((subtract ? 0xCB00_0000 : 0x8B00_0000) | (rm << 16) | (shift << 10) | (rn << 5) | rd)
+ }
+
+ /// UXTX ADD/SUB form; Rd/Rn 31 are SP and Rm 31 is XZR.
+ public static func encodeAddSubXExtended(subtract: Bool, rd: UInt32, rn: UInt32, rm: UInt32, shift: UInt32 = 0) -> Data? {
+ guard rd < 32, rn < 32, rm < 32, shift <= 4 else { return nil }
+ return ARM64.encodeU32((subtract ? 0xCB20_6000 : 0x8B20_6000) | (rm << 16) | (shift << 10) | (rn << 5) | rd)
+ }
+
+ // MARK: - Comparisons
+
+ /// CMP Wn,#imm12; register 31 is WSP.
+ public static func encodeCmpWImmediate(rn: UInt32, imm12: UInt32) -> Data? {
+ guard rn < 32, imm12 < 4096 else { return nil }
+ return ARM64.encodeU32(0x7100_001F | (imm12 << 10) | (rn << 5))
+ }
+
+ /// CCMP Wn,#imm5,#nzcv,cond; register 31 is WZR.
+ public static func encodeCcmpWImmediate(rn: UInt32, imm5: UInt32, nzcv: UInt32, condition: ARM64Condition) -> Data? {
+ guard rn < 32, imm5 < 32, nzcv < 16 else { return nil }
+ return ARM64.encodeU32(0x7A40_0800 | (imm5 << 16) | (condition.rawValue << 12) | (rn << 5) | nzcv)
+ }
+
// MARK: - Branch Encoding
/// Encode unconditional B (branch) instruction.
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Instruction.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Instruction.swift
index 3851e945..200a5a52 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Instruction.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Instruction.swift
@@ -59,6 +59,7 @@ public struct ARM64InstructionDetail: Sendable {
public let updatesFlags: Bool
public let postIndex: Bool
public let operands: [ARM64Operand]
+ public internal(set) var writeback = false
public init(conditionCode: ARM64Condition?, updatesFlags: Bool, postIndex: Bool, operands: [ARM64Operand]) {
self.conditionCode = conditionCode
@@ -83,12 +84,35 @@ public struct ARM64Operand: Sendable {
public let imm: Int64
/// Meaningful when `type` is `.memory`.
public let mem: ARM64MemoryOperand
+ public let shift: ARM64OperandShift
+ public internal(set) var writesRegister = false
+ // Keep the original initializer's symbol for already-built patch bundles.
public init(type: ARM64OperandType, reg: ARM64Register, imm: Int64, mem: ARM64MemoryOperand) {
+ self.init(type: type, reg: reg, imm: imm, mem: mem, shift: .init(type: .none, amount: 0))
+ }
+
+ public init(type: ARM64OperandType, reg: ARM64Register, imm: Int64, mem: ARM64MemoryOperand, shift: ARM64OperandShift) {
self.type = type
self.reg = reg
self.imm = imm
self.mem = mem
+ self.shift = shift
+ }
+}
+
+public enum ARM64ShiftType: UInt32, Sendable {
+ case none = 0, lsl = 1, msl = 2, lsr = 3, asr = 4, ror = 5
+ case unsupported = 0xFFFF_FFFF
+}
+
+public struct ARM64OperandShift: Sendable {
+ public let type: ARM64ShiftType
+ public let amount: UInt32
+
+ public init(type: ARM64ShiftType, amount: UInt32) {
+ self.type = type
+ self.amount = amount
}
}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/VPhoneArm64eX1Lowering.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/VPhoneArm64eX1Lowering.swift
new file mode 100644
index 00000000..3e3ee852
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/VPhoneArm64eX1Lowering.swift
@@ -0,0 +1,51 @@
+import Foundation
+
+public enum VPhoneArm64eX1Lowering {
+ public struct Failure: Error, CustomStringConvertible {
+ public let description: String
+ init(_ description: String) { self.description = description }
+ }
+
+ public static func replacement(for instruction: ARM64Instruction) throws -> Data? {
+ let name = instruction.mnemonic
+ let ops = instruction.detail?.operands ?? []
+ switch name {
+ case "pacibsppc", "pacnbibsppc": return ARM64.pacibsp
+ case "paciasppc", "pacnbiasppc": return ARM64.paciasp
+ case "retabsppc", "retabsppcr": return ARM64.retab
+ case "retaasppc", "retaasppcr": return ARM64.retaa
+ case "autibsppc", "autibsppcr": return ARM64.autibsp
+ case "autiasppc", "autiasppcr": return ARM64.autiasp
+ case "autia171615": return ARM64.autia1716
+ case "autib171615": return ARM64.autib1716
+ case "addpt", "subpt":
+ guard ops.count == 3, ops.allSatisfy({ $0.type == .register }),
+ let rd = register(ops[0].reg, allowSP: true),
+ let rn = register(ops[1].reg, allowSP: true),
+ let rm = register(ops[2].reg, allowSP: false),
+ [.none, .lsl].contains(ops[2].shift.type), ops[2].shift.amount <= 7
+ else { throw Failure("unsupported scalar \(name) operands at \(instruction.address)") }
+ let shift = ops[2].shift.amount
+ let replacement = rd == 31 || rn == 31
+ ? ARM64Encoder.encodeAddSubXExtended(subtract: name == "subpt", rd: rd, rn: rn, rm: rm, shift: shift)
+ : ARM64Encoder.encodeAddSubXShifted(subtract: name == "subpt", rd: rd, rn: rn, rm: rm, shift: shift)
+ guard let replacement else { throw Failure("unencodable \(name) at \(instruction.address)") }
+ return replacement
+ case "maddpt", "msubpt":
+ guard ops.count == 4, ops.allSatisfy({ $0.type == .register }),
+ let rd = register(ops[0].reg, allowSP: false), let rn = register(ops[1].reg, allowSP: false),
+ let rm = register(ops[2].reg, allowSP: false), let ra = register(ops[3].reg, allowSP: false),
+ let replacement = ARM64Encoder.encodeMaddSubX(subtract: name == "msubpt", rd: rd, rn: rn, rm: rm, ra: ra)
+ else { throw Failure("unsupported scalar \(name) at \(instruction.address)") }
+ return replacement
+ case "madpt", "mlapt", "pacib171615", "pacia171615":
+ throw Failure("X1 compatibility does not lower \(name) at \(instruction.address)")
+ default: return nil
+ }
+ }
+
+ private static func register(_ register: ARM64Register, allowSP: Bool) -> UInt32? {
+ if allowSP && register == .sp || !allowSP && register == .xzr { return 31 }
+ return (0 ... 30).first(where: { ARM64Register.x($0) == register }).map(UInt32.init)
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/Binary/MachOParser.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/Binary/MachOParser.swift
index 407edea5..5b4460b4 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/Binary/MachOParser.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/Binary/MachOParser.swift
@@ -28,13 +28,19 @@ public struct MachOSectionInfo: Sendable {
public let address: UInt64
public let size: UInt64
public let fileOffset: UInt32
+ public let flags: UInt32
public init(segmentName: String, sectionName: String, address: UInt64, size: UInt64, fileOffset: UInt32) {
+ self.init(segmentName: segmentName, sectionName: sectionName, address: address, size: size, fileOffset: fileOffset, flags: 0)
+ }
+
+ public init(segmentName: String, sectionName: String, address: UInt64, size: UInt64, fileOffset: UInt32, flags: UInt32) {
self.segmentName = segmentName
self.sectionName = sectionName
self.address = address
self.size = size
self.fileOffset = fileOffset
+ self.flags = flags
}
}
@@ -142,6 +148,7 @@ public enum MachOParser {
address: addr,
size: size,
fileOffset: fileOff,
+ flags: data.loadLE(UInt32.self, at: sectOff + 64),
)
sectOff += section64Size
}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchTarget.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchTarget.swift
index 28fbb6a5..4e9646f3 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchTarget.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchTarget.swift
@@ -13,6 +13,8 @@ public enum VPhoneFirmwareComponent: String, Sendable, Hashable, Codable, CaseIt
case iBEC
case llb = "LLB"
case txm = "TXM"
+ case restoreRamDisk = "RestoreRamDisk"
+ case restoreTrustCache = "RestoreTrustCache"
case kernelcache
case deviceTree = "DeviceTree"
case filesystem = "Filesystem"
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhoneVersion.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhoneVersion.swift
index c1b73024..2aaa35db 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhoneVersion.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhoneVersion.swift
@@ -38,7 +38,7 @@ public struct VPhoneVersion: Sendable, Hashable, Comparable, CustomStringConvert
/// The PatchKit API this framework is. Raised when a public symbol is added, so
/// a set that needs the new symbol refuses to load on an older bundle.
- public static let currentPatchKit = VPhoneVersion(major: 1, minor: 0)
+ public static let currentPatchKit = VPhoneVersion(major: 1, minor: 1)
public static func < (lhs: Self, rhs: Self) -> Bool {
(lhs.major, lhs.minor, lhs.patch) < (rhs.major, rhs.minor, rhs.patch)
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneSign/MachO/VPhoneCodeSignature.swift b/VPhoneExecutable/VPhoneCommand/VPhoneSign/MachO/VPhoneCodeSignature.swift
index 4bef172e..66925cad 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneSign/MachO/VPhoneCodeSignature.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneSign/MachO/VPhoneCodeSignature.swift
@@ -269,6 +269,64 @@ struct VPhoneCodeSignature {
// MARK: Reading one back
+ static func identifier(in blob: Data) throws -> String? {
+ guard blob.count >= 12 else {
+ throw VPhoneSignError.malformed("the embedded signature is shorter than its header")
+ }
+ let magic: UInt32 = blob.bigEndianValue(at: 0)
+ guard magic == 0xFADE_0CC0 else {
+ throw VPhoneSignError.malformed(
+ "the embedded signature has magic 0x\(String(magic, radix: 16))",
+ )
+ }
+ let length = Int(blob.bigEndianValue(at: 4) as UInt32)
+ guard length >= 12, length <= blob.count else {
+ throw VPhoneSignError.malformed("the embedded signature length \(length) is out of bounds")
+ }
+ let count = Int(blob.bigEndianValue(at: 8) as UInt32)
+ guard count <= (length - 12) / 8 else {
+ throw VPhoneSignError.malformed("the embedded signature index does not fit")
+ }
+
+ var primaryOffset: Int?
+ for index in 0 ..< count {
+ let entry = 12 + index * 8
+ guard blob.bigEndianValue(at: entry) as UInt32 == 0 else { continue }
+ guard primaryOffset == nil else {
+ throw VPhoneSignError.malformed("the embedded signature has more than one primary CodeDirectory")
+ }
+ primaryOffset = Int(blob.bigEndianValue(at: entry + 4) as UInt32)
+ }
+ guard let primaryOffset else { return nil }
+ guard primaryOffset >= 12 + count * 8, primaryOffset <= length - 8 else {
+ throw VPhoneSignError.malformed("the primary CodeDirectory offset is out of bounds")
+ }
+ let directoryMagic: UInt32 = blob.bigEndianValue(at: primaryOffset)
+ guard directoryMagic == 0xFADE_0C02 else {
+ throw VPhoneSignError.malformed(
+ "the primary CodeDirectory has magic 0x\(String(directoryMagic, radix: 16))",
+ )
+ }
+ let directoryLength = Int(blob.bigEndianValue(at: primaryOffset + 4) as UInt32)
+ guard directoryLength >= 24, directoryLength <= length - primaryOffset else {
+ throw VPhoneSignError.malformed("the primary CodeDirectory length is out of bounds")
+ }
+ let identifierOffset = Int(blob.bigEndianValue(at: primaryOffset + 20) as UInt32)
+ guard identifierOffset >= 24, identifierOffset < directoryLength else {
+ throw VPhoneSignError.malformed("the primary CodeDirectory identifier offset is out of bounds")
+ }
+ let identifierStart = primaryOffset + identifierOffset
+ let identifierLimit = primaryOffset + directoryLength
+ guard let identifierEnd = blob[identifierStart ..< identifierLimit].firstIndex(of: 0) else {
+ throw VPhoneSignError.malformed("the primary CodeDirectory identifier is not terminated")
+ }
+ let bytes = blob.subdata(in: identifierStart ..< identifierEnd)
+ guard !bytes.isEmpty, let identifier = String(data: bytes, encoding: .utf8) else {
+ throw VPhoneSignError.malformed("the primary CodeDirectory identifier is not valid UTF-8")
+ }
+ return identifier
+ }
+
/// The entitlements XML a signature carries, as ldid reads it: the last
/// blob in slot 5, and nothing where there is none.
static func entitlementsXML(in blob: Data) -> Data? {
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneSign/MachO/VPhoneMachOImage.swift b/VPhoneExecutable/VPhoneCommand/VPhoneSign/MachO/VPhoneMachOImage.swift
index 86843bf1..ef75e53f 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneSign/MachO/VPhoneMachOImage.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneSign/MachO/VPhoneMachOImage.swift
@@ -286,6 +286,15 @@ struct VPhoneMachOImage {
return VPhoneCodeSignature.entitlementsXML(in: blob)
}
+ func embeddedIdentifier() throws -> String? {
+ guard let signature else { return nil }
+ let blob = image.subdata(in: signature.dataOffset ..< signature.dataOffset + signature.dataSize)
+ guard let identifier = try VPhoneCodeSignature.identifier(in: blob) else {
+ throw VPhoneSignError.malformed("the embedded signature has no primary CodeDirectory")
+ }
+ return identifier
+ }
+
/// How far ldid lets the code reach: the end of the string table, or the
/// start of the signature it is replacing.
func codeEnd() throws -> Int {
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneSign/Signing/VPhoneSigner.swift b/VPhoneExecutable/VPhoneCommand/VPhoneSign/Signing/VPhoneSigner.swift
index 3493a1d4..d37add53 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneSign/Signing/VPhoneSigner.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneSign/Signing/VPhoneSigner.swift
@@ -195,7 +195,20 @@ public enum VPhoneSigner {
return signature
}
- // MARK: Reading entitlements back
+ // MARK: Reading signatures back
+
+ public static func identifier(ofFileAt url: URL) throws -> String? {
+ try identifier(in: Data(contentsOf: url, options: .mappedIfSafe))
+ }
+
+ public static func identifier(in data: Data) throws -> String? {
+ let identifiers = try VPhoneMachOFile(data: data).slices.compactMap { try $0.embeddedIdentifier() }
+ guard let identifier = identifiers.first else { return nil }
+ guard identifiers.allSatisfy({ $0 == identifier }) else {
+ throw VPhoneSignError.malformed("the slices have different CodeDirectory identifiers")
+ }
+ return identifier
+ }
/// What `ldid -e` prints: the entitlements of each slice that carries
/// any, in slice order, exactly as the signature stores them. A slice
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneSignTests/VPhoneSignParityTests.swift b/VPhoneExecutable/VPhoneCommand/VPhoneSignTests/VPhoneSignParityTests.swift
index 05863710..1635a4c3 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneSignTests/VPhoneSignParityTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneSignTests/VPhoneSignParityTests.swift
@@ -228,6 +228,34 @@ struct VPhoneSignParityTests {
}
}
+ @Test
+ func `an existing identifier survives staging and re-signing`() throws {
+ let directory = try VPhoneSignFixtures.temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let file = try VPhoneSignFixtures.copy(
+ VPhoneSignFixtures.url("hello-arm64"),
+ into: directory,
+ as: "fsck",
+ )
+ try VPhoneSigner.sign(
+ fileAt: file,
+ options: .init(identifier: "com.apple.fsck", style: .appleAdHoc),
+ )
+
+ let existingIdentifier = try VPhoneSigner.identifier(ofFileAt: file)
+ let identifier = try #require(existingIdentifier)
+ #expect(identifier == "com.apple.fsck")
+ try VPhoneSigner.sign(
+ fileAt: file,
+ options: .init(identifier: identifier, mergesExisting: true, style: .appleAdHoc),
+ )
+
+ for (index, slice) in try VPhoneSignBlobs(fileAt: file).slices.enumerated() {
+ let blob = try #require(slice[0], "slice \(index) has no CodeDirectory")
+ #expect(VPhoneSignBlobs.identifier(ofCodeDirectory: blob) == "com.apple.fsck", "slice \(index)")
+ }
+ }
+
/// Signing twice must land on the same bytes, or a rebuild of the CFW
/// would produce a different image every time.
@Test
diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
index 963f4739..51eb5fbc 100755
--- a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
+++ b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
@@ -32,10 +32,13 @@ build_project -project "$root/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcode
-destination 'platform=macOS,arch=arm64' \
-derivedDataPath "$root/.build/XcodeCommand" CODE_SIGNING_ALLOWED=NO build
+# Select the device SDK and product suffix explicitly so SwiftPM paths stay iOS
+# even when Xcode only offers host destinations without a simulator runtime.
build_project -project "$root/VPhoneDaemon/VPhoneDaemon.xcodeproj" \
-scheme vphoned -configuration "$configuration" \
- -destination 'generic/platform=iOS' \
- -derivedDataPath "$root/.build/XcodeDaemon" CODE_SIGNING_ALLOWED=NO build
+ -sdk iphoneos \
+ -derivedDataPath "$root/.build/XcodeDaemon" CODE_SIGNING_ALLOWED=NO \
+ SUPPORTS_MACCATALYST=NO EFFECTIVE_PLATFORM_NAME=-iphoneos build
build_project -project "$root/VPhoneExecutable/VPhoneEscalator/VPhoneEscalator.xcodeproj" \
-scheme VPhoneEscalator -configuration "$configuration" \
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
index f4af5bbb..ff580466 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
@@ -84,23 +84,30 @@
<string>dyld-exp-mis_trust_auth</string>
<string>system-preferences-exp-root_rows</string>
<string>dyld-exp-settings_software_update_row</string>
+ <string>dyld-boot-arm64e_x1_bootstrap</string>
<string>dyld-boot-iomfb_swapend</string>
<string>dyld-cfw-camera</string>
+ <string>kernel-boot-arm64e_x1</string>
<string>preboot-cfw-devicetree_board_audio</string>
<string>preboot-cfw-devicetree_haptics</string>
<string>preboot-cfw-devicetree_iphone_product</string>
<string>preboot-cfw-devicetree_microphone_array</string>
+ <string>restoreramdisk-boot-apfs_sha3_hash</string>
<string>system-apps-cfw-attitude</string>
<string>system-backboardd-cfw-gyroscope</string>
<string>system-campo-cfw-entitlements</string>
<string>system-debugserver-cfw-install</string>
+ <string>system-dyld-boot-arm64e_x1_bootstrap</string>
<string>system-diskimagesiod-cfw-is_mount_complete</string>
+ <string>system-fsck-boot-arm64e_x1_bootstrap</string>
<string>system-installcoordination_proxy-cfw-persona_lookup</string>
<string>system-jetsamproperties-cfw-disable_allowed</string>
+ <string>system-launchd-boot-arm64e_x1_bootstrap</string>
<string>system-launchd-boot-jetsam_panic_guard_bypass</string>
<string>system-launchdaemons-boot-environment</string>
<string>system-locationd-cfw-disable_auto_cohort</string>
<string>system-mobileactivationd-boot-should_hactivate</string>
+ <string>system-mount-boot-arm64e_x1_bootstrap</string>
<string>system-paravirt_gpu-cfw-heap_index_offset</string>
<string>system-systemversion-cfw-build_version</string>
<string>system-virtiosound-cfw-hal_plugin</string>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
index 937e4669..1c09901d 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
@@ -84,6 +84,7 @@
<string>dyld-exp-mis_trust_auth</string>
<string>system-preferences-exp-root_rows</string>
<string>dyld-exp-settings_software_update_row</string>
+ <string>dyld-boot-arm64e_x1_bootstrap</string>
<string>dyld-boot-iomfb_force_kern</string>
<string>dyld-boot-iomfb_swapend</string>
<string>dyld-boot-lockdown_mode</string>
@@ -91,22 +92,28 @@
<string>dyld-boot-maxslide</string>
<string>dyld-boot-xpc_lwcr</string>
<string>dyld-cfw-camera</string>
+ <string>kernel-boot-arm64e_x1</string>
<string>preboot-cfw-devicetree_board_audio</string>
<string>preboot-cfw-devicetree_haptics</string>
<string>preboot-cfw-devicetree_iphone_product</string>
<string>preboot-cfw-devicetree_microphone_array</string>
+ <string>restoreramdisk-boot-apfs_sha3_hash</string>
<string>system-apps-cfw-attitude</string>
<string>system-backboardd-cfw-gyroscope</string>
<string>system-campo-cfw-entitlements</string>
<string>system-debugserver-cfw-install</string>
+ <string>system-dyld-boot-arm64e_x1_bootstrap</string>
<string>system-diskimagesiod-cfw-is_mount_complete</string>
<string>system-extensions-boot-gpu_bundle</string>
+ <string>system-fsck-boot-arm64e_x1_bootstrap</string>
<string>system-installcoordination_proxy-cfw-persona_lookup</string>
<string>system-jetsamproperties-cfw-disable_allowed</string>
+ <string>system-launchd-boot-arm64e_x1_bootstrap</string>
<string>system-launchd-boot-jetsam_panic_guard_bypass</string>
<string>system-launchdaemons-boot-environment</string>
<string>system-locationd-cfw-disable_auto_cohort</string>
<string>system-mobileactivationd-boot-should_hactivate</string>
+ <string>system-mount-boot-arm64e_x1_bootstrap</string>
<string>system-paravirt_gpu-cfw-heap_index_offset</string>
<string>system-systemversion-cfw-build_version</string>
<string>system-virtiosound-cfw-hal_plugin</string>
diff --git a/VPhoneGuestComponents/LaunchHook/VPhoneMachMessage.c b/VPhoneGuestComponents/LaunchHook/VPhoneMachMessage.c
new file mode 100644
index 00000000..9cce990b
--- /dev/null
+++ b/VPhoneGuestComponents/LaunchHook/VPhoneMachMessage.c
@@ -0,0 +1,37 @@
+#include "VPhoneMachMessage.h"
+#include <stdint.h>
+
+typedef uint64_t vp_mach_msg_option64_t;
+
+extern mach_msg_return_t mach_msg2_internal(void *data,
+ vp_mach_msg_option64_t options, uint64_t bits_and_send_size,
+ uint64_t remote_and_local_port, uint64_t voucher_and_id,
+ uint64_t descriptor_count_and_receive_name,
+ uint64_t receive_size_and_priority, uint64_t timeout);
+
+enum {
+ VP_MACH64_SEND_KOBJECT_CALL = 0x0000000200000000ULL,
+};
+
+static uint64_t vp_pair(uint32_t low, uint32_t high) {
+ return (uint64_t)high << 32 | low;
+}
+
+mach_msg_return_t vp_mach_msg_kobject(mach_msg_header_t *message,
+ mach_msg_option_t options, mach_msg_size_t send_size,
+ mach_msg_size_t receive_size, mach_port_name_t receive_name,
+ mach_msg_timeout_t timeout, mach_port_name_t notify) {
+ uint32_t descriptors = 0;
+ if ((options & MACH_SEND_MSG) &&
+ (message->msgh_bits & MACH_MSGH_BITS_COMPLEX)) {
+ descriptors = ((mach_msg_base_t *)message)->body.msgh_descriptor_count;
+ }
+ uint32_t priority = (options & MACH_SEND_MSG) ? notify : 0;
+ return mach_msg2_internal(message,
+ (vp_mach_msg_option64_t)options | VP_MACH64_SEND_KOBJECT_CALL,
+ vp_pair(message->msgh_bits, send_size),
+ vp_pair(message->msgh_remote_port, message->msgh_local_port),
+ vp_pair(message->msgh_voucher_port, message->msgh_id),
+ vp_pair(descriptors, receive_name),
+ vp_pair(receive_size, priority), timeout);
+}
diff --git a/VPhoneGuestComponents/LaunchHook/VPhoneMachMessage.h b/VPhoneGuestComponents/LaunchHook/VPhoneMachMessage.h
new file mode 100644
index 00000000..ab86c12e
--- /dev/null
+++ b/VPhoneGuestComponents/LaunchHook/VPhoneMachMessage.h
@@ -0,0 +1,12 @@
+#ifndef VPHONE_MACH_MESSAGE_H
+#define VPHONE_MACH_MESSAGE_H
+
+#include <mach/message.h>
+
+/// Sends MIG requests through the kernel-kobject IPC path.
+mach_msg_return_t vp_mach_msg_kobject(mach_msg_header_t *message,
+ mach_msg_option_t options, mach_msg_size_t send_size,
+ mach_msg_size_t receive_size, mach_port_name_t receive_name,
+ mach_msg_timeout_t timeout, mach_port_name_t notify);
+
+#endif
diff --git a/VPhoneGuestComponents/LaunchHook/VPhoneX1Exception.c b/VPhoneGuestComponents/LaunchHook/VPhoneX1Exception.c
new file mode 100644
index 00000000..ac0cbd9d
--- /dev/null
+++ b/VPhoneGuestComponents/LaunchHook/VPhoneX1Exception.c
@@ -0,0 +1,341 @@
+#include "VPhoneX1Exception.h"
+#include "VPhoneX1Lowering.h"
+#include "mach_exc.h"
+#include "mach_excServer.h"
+
+#include <mach-o/loader.h>
+#include <mach-o/dyld.h>
+#include <mach/arm/thread_status.h>
+#include <mach/host_special_ports.h>
+#include <mach/mach.h>
+#include <errno.h>
+#include <pthread.h>
+#include <setjmp.h>
+#include <signal.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+extern const struct mach_header *_NSGetMachExecuteHeader(void);
+
+static mach_port_t vp_original_exception_port = MACH_PORT_NULL;
+static mach_port_t vp_exception_port = MACH_PORT_NULL;
+static sigjmp_buf vp_probe_jump;
+
+__attribute__((naked, noinline, used))
+static void vp_probe_pauth_lr(void) {
+ // Preserve LR because the probe has no matching X1 authentication.
+ __asm__ volatile(
+ "mov x9, x30\n"
+ ".long 0xDAC1A7FE\n" // PACIBSPPC
+ "mov x30, x9\n"
+ "ret\n"
+ );
+}
+
+__attribute__((naked, noinline, used))
+static uintptr_t vp_probe_cpa(uintptr_t unused, uintptr_t base,
+ uintptr_t offset) {
+ __asm__ volatile(
+ ".long 0x9A022020\n" // ADDPT x0, x1, x2
+ "ret\n"
+ );
+}
+
+typedef struct {
+ bool task_suspended;
+ thread_act_array_t threads;
+ mach_msg_type_number_t count;
+ unsigned char *suspended;
+} VPStoppedTarget;
+
+static bool vp_suspend_target(mach_port_t task, mach_port_t faulting_thread,
+ VPStoppedTarget *stopped) {
+ memset(stopped, 0, sizeof(*stopped));
+
+ // task_suspend closes the thread-creation race while execute is removed.
+ if (task != mach_task_self()) {
+ if (task_suspend(task) != KERN_SUCCESS) return false;
+ stopped->task_suspended = true;
+ return true;
+ }
+
+ // launchd cannot task_suspend itself while serving the exception.
+ if (task_threads(task, &stopped->threads, &stopped->count) != KERN_SUCCESS)
+ return false;
+ stopped->suspended = calloc(stopped->count, sizeof(*stopped->suspended));
+ if (stopped->suspended == NULL) return false;
+
+ mach_port_t server_thread = mach_thread_self();
+ bool complete = true;
+ for (mach_msg_type_number_t index = 0; index < stopped->count; index++) {
+ mach_port_t candidate = stopped->threads[index];
+ if (candidate == faulting_thread || candidate == server_thread) continue;
+ if (thread_suspend(candidate) == KERN_SUCCESS)
+ stopped->suspended[index] = 1;
+ else
+ complete = false;
+ }
+ mach_port_deallocate(mach_task_self(), server_thread);
+ return complete;
+}
+
+static void vp_resume_target(mach_port_t task, VPStoppedTarget *stopped) {
+ if (stopped->task_suspended) (void)task_resume(task);
+ if (stopped->threads != NULL) {
+ for (mach_msg_type_number_t index = 0; index < stopped->count; index++) {
+ if (stopped->suspended != NULL && stopped->suspended[index])
+ thread_resume(stopped->threads[index]);
+ mach_port_deallocate(mach_task_self(), stopped->threads[index]);
+ }
+ vm_deallocate(mach_task_self(), (vm_address_t)stopped->threads,
+ stopped->count * sizeof(*stopped->threads));
+ }
+ free(stopped->suspended);
+ memset(stopped, 0, sizeof(*stopped));
+}
+
+static bool vp_is_x1_launchd(void) {
+ const struct mach_header *header = _NSGetMachExecuteHeader();
+ uint32_t subtype = (uint32_t)header->cpusubtype & ~CPU_SUBTYPE_MASK;
+ return header->cputype == CPU_TYPE_ARM64 && subtype == 12;
+}
+
+static bool vp_patch_fault(mach_port_t thread, mach_port_t task,
+ const mach_exception_data_t code, mach_msg_type_number_t code_count) {
+ if (code_count != 2) return false;
+
+ arm_thread_state64_t state;
+ mach_msg_type_number_t state_count = ARM_THREAD_STATE64_COUNT;
+ if (thread_get_state(thread, ARM_THREAD_STATE64, (thread_state_t)&state,
+ &state_count) != KERN_SUCCESS) return false;
+ // The remote thread owns the PC signature; inspect a stripped copy.
+ arm_thread_state64_ptrauth_strip(state);
+ vm_address_t pc = (vm_address_t)arm_thread_state64_get_pc(state);
+ if ((pc & 3) != 0) return false;
+
+ uint32_t fault_word = (uint32_t)code[1];
+ uint32_t replacement;
+ if (!vp_x1_lower_instruction(fault_word, &replacement)) return false;
+
+ uint32_t current = 0;
+ vm_size_t read = 0;
+ kern_return_t result = vm_read_overwrite(task, pc, sizeof(current),
+ (vm_address_t)&current, &read);
+ if (result != KERN_SUCCESS || read != sizeof(current) ||
+ (current != fault_word && current != replacement)) {
+ return false;
+ }
+ if (current == replacement) {
+ return true;
+ }
+
+ // Stop peer threads while the private page is writable and non-executable.
+ VPStoppedTarget stopped;
+ if (!vp_suspend_target(task, thread, &stopped)) {
+ vp_resume_target(task, &stopped);
+ return false;
+ }
+ vm_size_t page_size = vm_page_size;
+ vm_address_t page = pc & ~(page_size - 1);
+ result = vm_protect(task, page, page_size, false,
+ VM_PROT_COPY | VM_PROT_READ | VM_PROT_WRITE);
+ if (result == KERN_SUCCESS) {
+ result = vm_write(task, pc, (vm_offset_t)&replacement,
+ (mach_msg_type_number_t)sizeof(replacement));
+ }
+ kern_return_t protected = vm_protect(task, page, page_size, false,
+ VM_PROT_READ | VM_PROT_EXECUTE);
+ if (result == KERN_SUCCESS && protected == KERN_SUCCESS) {
+ vm_machine_attribute_val_t cache = MATTR_VAL_CACHE_FLUSH;
+ result = vm_machine_attribute(task, page, page_size, MATTR_CACHE, &cache);
+ } else if (result == KERN_SUCCESS) {
+ result = protected;
+ }
+ vp_resume_target(task, &stopped);
+ return result == KERN_SUCCESS;
+}
+
+static kern_return_t vp_forward(mach_port_t thread, mach_port_t task,
+ exception_type_t exception, mach_exception_data_t code,
+ mach_msg_type_number_t code_count) {
+ if (vp_original_exception_port == MACH_PORT_NULL) return KERN_FAILURE;
+ return mach_exception_raise(vp_original_exception_port, thread, task,
+ exception, code, code_count);
+}
+
+kern_return_t catch_mach_exception_raise(mach_port_t port, mach_port_t thread,
+ mach_port_t task, exception_type_t exception, mach_exception_data_t code,
+ mach_msg_type_number_t code_count) {
+ (void)port;
+ kern_return_t result = KERN_FAILURE;
+ if (exception == EXC_BAD_INSTRUCTION &&
+ vp_patch_fault(thread, task, code, code_count)) {
+ result = KERN_SUCCESS;
+ } else {
+ result = vp_forward(thread, task, exception, code, code_count);
+ }
+ // mach_msg_server destroys moved rights only when the callback fails.
+ if (result == KERN_SUCCESS) {
+ mach_port_deallocate(mach_task_self(), thread);
+ mach_port_deallocate(mach_task_self(), task);
+ }
+ return result;
+}
+
+kern_return_t catch_mach_exception_raise_state(mach_port_t port,
+ exception_type_t exception, const mach_exception_data_t code,
+ mach_msg_type_number_t code_count, int *flavor,
+ const thread_state_t old_state, mach_msg_type_number_t old_count,
+ thread_state_t new_state, mach_msg_type_number_t *new_count) {
+ (void)port; (void)exception; (void)code; (void)code_count; (void)flavor;
+ (void)old_state; (void)old_count; (void)new_state; (void)new_count;
+ return KERN_FAILURE;
+}
+
+kern_return_t catch_mach_exception_raise_state_identity(mach_port_t port,
+ mach_port_t thread, mach_port_t task, exception_type_t exception,
+ mach_exception_data_t code, mach_msg_type_number_t code_count, int *flavor,
+ thread_state_t old_state, mach_msg_type_number_t old_count,
+ thread_state_t new_state, mach_msg_type_number_t *new_count) {
+ (void)port; (void)thread; (void)task; (void)exception; (void)code;
+ (void)code_count; (void)flavor; (void)old_state; (void)old_count;
+ (void)new_state; (void)new_count;
+ return KERN_FAILURE;
+}
+
+static void *vp_exception_server(void *opaque) {
+ mach_port_t port = (mach_port_t)(uintptr_t)opaque;
+ (void)mach_msg_server(mach_exc_server, 8192, port, 0);
+ return NULL;
+}
+
+static void vp_probe_sigill(int signal) {
+ (void)signal;
+ siglongjmp(vp_probe_jump, 1);
+}
+
+static bool vp_probe_native_x1(void) {
+ // Probe in a child; any setup or wait failure selects compatibility.
+ int result_pipe[2];
+ if (pipe(result_pipe) != 0) return false;
+ pid_t child = fork();
+ if (child < 0) {
+ close(result_pipe[0]);
+ close(result_pipe[1]);
+ return false;
+ }
+ if (child == 0) {
+ close(result_pipe[0]);
+ struct sigaction action = {0};
+ action.sa_handler = vp_probe_sigill;
+ sigemptyset(&action.sa_mask);
+ if (sigaction(SIGILL, &action, NULL) != 0) _exit(2);
+ int trapped = sigsetjmp(vp_probe_jump, 1);
+ unsigned char supported = 0;
+ if (trapped == 0) {
+ uintptr_t marker = 0;
+ vp_probe_pauth_lr();
+ (void)vp_probe_cpa(0, (uintptr_t)&marker, 0);
+ supported = 1;
+ }
+ (void)write(result_pipe[1], &supported, sizeof(supported));
+ _exit(supported ? 0 : 1);
+ }
+
+ close(result_pipe[1]);
+ unsigned char supported = 0;
+ ssize_t bytes;
+ do {
+ bytes = read(result_pipe[0], &supported, sizeof(supported));
+ } while (bytes < 0 && errno == EINTR);
+ close(result_pipe[0]);
+
+ int status = 0;
+ pid_t waited;
+ do {
+ waited = waitpid(child, &status, 0);
+ } while (waited < 0 && errno == EINTR);
+ bool reaped = waited == child || (waited < 0 && errno == ECHILD);
+ return bytes == sizeof(supported) && supported == 1 && reaped;
+}
+
+static void vp_dispose_exception_service(void) {
+ mach_port_t port = vp_exception_port;
+ vp_exception_port = MACH_PORT_NULL;
+ if (port != MACH_PORT_NULL) {
+ // Allocation and send-right insertion can fail independently.
+ (void)mach_port_mod_refs(
+ mach_task_self(), port, MACH_PORT_RIGHT_SEND, -1);
+ (void)mach_port_mod_refs(
+ mach_task_self(), port, MACH_PORT_RIGHT_RECEIVE, -1);
+ }
+ if (vp_original_exception_port != MACH_PORT_NULL) {
+ mach_port_deallocate(mach_task_self(), vp_original_exception_port);
+ vp_original_exception_port = MACH_PORT_NULL;
+ }
+}
+
+void vp_x1_exception_install(void) {
+ if (getpid() != 1 || !vp_is_x1_launchd()) return;
+ if (vp_probe_native_x1()) return;
+
+ mach_port_t host = mach_host_self();
+ mach_port_t privileged = MACH_PORT_NULL;
+ if (host_get_special_port(host, HOST_LOCAL_NODE, HOST_PRIV_PORT,
+ &privileged) != KERN_SUCCESS) return;
+
+ exception_mask_t masks[EXC_TYPES_COUNT];
+ mach_port_t ports[EXC_TYPES_COUNT];
+ exception_behavior_t behaviors[EXC_TYPES_COUNT];
+ thread_state_flavor_t flavors[EXC_TYPES_COUNT];
+ mach_msg_type_number_t count = EXC_TYPES_COUNT;
+ kern_return_t result = host_get_exception_ports(privileged,
+ EXC_MASK_BAD_INSTRUCTION, masks, &count, ports, behaviors, flavors);
+ if (result != KERN_SUCCESS || count != 1 ||
+ (masks[0] & EXC_MASK_BAD_INSTRUCTION) == 0 ||
+ behaviors[0] != (exception_behavior_t)(
+ EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES)) {
+ if (result == KERN_SUCCESS) {
+ for (mach_msg_type_number_t i = 0; i < count; i++) {
+ if (ports[i] != MACH_PORT_NULL)
+ mach_port_deallocate(mach_task_self(), ports[i]);
+ }
+ }
+ mach_port_deallocate(mach_task_self(), privileged);
+ mach_port_deallocate(mach_task_self(), host);
+ return;
+ }
+
+ vp_original_exception_port = ports[0];
+ result = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE,
+ &vp_exception_port);
+ if (result == KERN_SUCCESS) {
+ result = mach_port_insert_right(mach_task_self(), vp_exception_port,
+ vp_exception_port, MACH_MSG_TYPE_MAKE_SEND);
+ }
+ pthread_t server;
+ if (result == KERN_SUCCESS) {
+ result = pthread_create(&server, NULL, vp_exception_server,
+ (void *)(uintptr_t)vp_exception_port);
+ if (result == 0) {
+ pthread_detach(server);
+ }
+ }
+ if (result == KERN_SUCCESS) {
+ // Spawn hooks propagate this action; unsupported faults are forwarded.
+ result = task_set_exception_ports(
+ mach_task_self(),
+ EXC_MASK_BAD_INSTRUCTION,
+ vp_exception_port,
+ EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES,
+ 0
+ );
+ }
+ if (result != KERN_SUCCESS) vp_dispose_exception_service();
+ mach_port_deallocate(mach_task_self(), privileged);
+ mach_port_deallocate(mach_task_self(), host);
+}
diff --git a/VPhoneGuestComponents/LaunchHook/VPhoneX1Exception.h b/VPhoneGuestComponents/LaunchHook/VPhoneX1Exception.h
new file mode 100644
index 00000000..d5c872b1
--- /dev/null
+++ b/VPhoneGuestComponents/LaunchHook/VPhoneX1Exception.h
@@ -0,0 +1,8 @@
+#ifndef VPHONE_X1_EXCEPTION_H
+#define VPHONE_X1_EXCEPTION_H
+
+#include <mach/port.h>
+
+void vp_x1_exception_install(void);
+
+#endif
diff --git a/VPhoneGuestComponents/LaunchHook/VPhoneX1Lowering.c b/VPhoneGuestComponents/LaunchHook/VPhoneX1Lowering.c
new file mode 100644
index 00000000..dc750c34
--- /dev/null
+++ b/VPhoneGuestComponents/LaunchHook/VPhoneX1Lowering.c
@@ -0,0 +1,122 @@
+#include "VPhoneX1Lowering.h"
+#include <stddef.h>
+
+enum {
+ VP_PACIASP = 0xD503233F,
+ VP_PACIBSP = 0xD503237F,
+ VP_AUTIASP = 0xD50323BF,
+ VP_AUTIBSP = 0xD50323FF,
+ VP_RETAA = 0xD65F0BFF,
+ VP_RETAB = 0xD65F0FFF,
+ VP_AUTIA1716 = 0xD503219F,
+ VP_AUTIB1716 = 0xD50321DF,
+};
+
+static bool vp_fixed_pac(uint32_t instruction, uint32_t *replacement) {
+ switch (instruction) {
+ case 0xDAC1A3FE: // PACIASPPC
+ case 0xDAC183FE: // PACNBIASPPC
+ *replacement = VP_PACIASP;
+ return true;
+ case 0xDAC1A7FE: // PACIBSPPC
+ case 0xDAC187FE: // PACNBIBSPPC
+ *replacement = VP_PACIBSP;
+ return true;
+ case 0xDAC1BBFE: // AUTIA171615
+ *replacement = VP_AUTIA1716;
+ return true;
+ case 0xDAC1BFFE: // AUTIB171615
+ *replacement = VP_AUTIB1716;
+ return true;
+ default:
+ return false;
+ }
+}
+
+static bool vp_pc_pac(uint32_t instruction, uint32_t *replacement) {
+ switch (instruction & 0xFFE0001F) {
+ case 0xF380001F: // AUTIASPPCi
+ *replacement = VP_AUTIASP;
+ return true;
+ case 0xF3A0001F: // AUTIBSPPCi
+ *replacement = VP_AUTIBSP;
+ return true;
+ case 0x5500001F: // RETAASPPCi
+ *replacement = VP_RETAA;
+ return true;
+ case 0x5520001F: // RETABSPPCi
+ *replacement = VP_RETAB;
+ return true;
+ default:
+ break;
+ }
+ switch (instruction & 0xFFFFFC1F) {
+ case 0xDAC1901E: // AUTIASPPCr
+ *replacement = VP_AUTIASP;
+ return true;
+ case 0xDAC1941E: // AUTIBSPPCr
+ *replacement = VP_AUTIBSP;
+ return true;
+ default:
+ break;
+ }
+ switch (instruction & 0xFFFFFFE0) {
+ case 0xD65F0BE0: // RETAASPPCr
+ *replacement = VP_RETAA;
+ return true;
+ case 0xD65F0FE0: // RETABSPPCr
+ *replacement = VP_RETAB;
+ return true;
+ default:
+ return false;
+ }
+}
+
+static bool vp_checked_add_sub(uint32_t instruction, uint32_t *replacement) {
+ uint32_t fixed = instruction & 0xFFE0E000;
+ bool subtract;
+ if (fixed == 0x9A002000) {
+ subtract = false;
+ } else if (fixed == 0xDA002000) {
+ subtract = true;
+ } else {
+ return false;
+ }
+
+ uint32_t rd = instruction & 31;
+ uint32_t rn = (instruction >> 5) & 31;
+ uint32_t shift = (instruction >> 10) & 7;
+ uint32_t rm = (instruction >> 16) & 31;
+ if (rd == 31 || rn == 31) {
+ if (shift > 4) return false;
+ *replacement = (subtract ? 0xCB206000 : 0x8B206000) |
+ (rm << 16) | (shift << 10) | (rn << 5) | rd;
+ } else {
+ *replacement = (subtract ? 0xCB000000 : 0x8B000000) |
+ (rm << 16) | (shift << 10) | (rn << 5) | rd;
+ }
+ return true;
+}
+
+static bool vp_checked_madd_sub(uint32_t instruction, uint32_t *replacement) {
+ uint32_t fixed = instruction & 0xFFE08000;
+ bool subtract;
+ if (fixed == 0x9B600000) {
+ subtract = false;
+ } else if (fixed == 0x9B608000) {
+ subtract = true;
+ } else {
+ return false;
+ }
+ uint32_t fields = instruction & 0x001F7FFF;
+ *replacement = (subtract ? 0x9B008000 : 0x9B000000) | fields;
+ return true;
+}
+
+bool vp_x1_lower_instruction(uint32_t instruction, uint32_t *replacement) {
+ if (replacement == NULL) return false;
+ return vp_fixed_pac(instruction, replacement) ||
+ vp_pc_pac(instruction, replacement) ||
+ vp_checked_add_sub(instruction, replacement) ||
+ vp_checked_madd_sub(instruction, replacement);
+}
diff --git a/VPhoneGuestComponents/LaunchHook/VPhoneX1Lowering.h b/VPhoneGuestComponents/LaunchHook/VPhoneX1Lowering.h
new file mode 100644
index 00000000..fc682c17
--- /dev/null
+++ b/VPhoneGuestComponents/LaunchHook/VPhoneX1Lowering.h
@@ -0,0 +1,9 @@
+#ifndef VPHONE_X1_LOWERING_H
+#define VPHONE_X1_LOWERING_H
+
+#include <stdbool.h>
+#include <stdint.h>
+
+bool vp_x1_lower_instruction(uint32_t instruction, uint32_t *replacement);
+
+#endif
diff --git a/VPhoneGuestComponents/LaunchHook/launchdhook-vphone.c b/VPhoneGuestComponents/LaunchHook/launchdhook-vphone.c
index d563462f..9aa9fd94 100644
--- a/VPhoneGuestComponents/LaunchHook/launchdhook-vphone.c
+++ b/VPhoneGuestComponents/LaunchHook/launchdhook-vphone.c
@@ -1,6 +1,8 @@
#include "../Shared/InjectionEnvironment.h"
#include "../Shared/JetsamLimits.h"
#include "../Shared/RootHideLoaderLinks.h"
+#include "../Shared/VPhoneX1Spawn.h"
+#include "VPhoneX1Exception.h"
#include <fcntl.h>
#include <stdint.h>
#include <limits.h>
@@ -74,10 +76,7 @@ static int vpFindJBRoot(char root[PATH_MAX]) {
return 0;
}
-typedef int (*VPSpawnFunction)(pid_t *restrict, const char *restrict, const posix_spawn_file_actions_t *restrict,
- const posix_spawnattr_t *restrict, char *const[restrict], char *const[restrict]);
-
-static int vpSpawnWith(VPSpawnFunction spawn, pid_t *restrict pid, const char *restrict path,
+static int vpSpawnWith(VPX1SpawnFunction spawn, pid_t *restrict pid, const char *restrict path,
const posix_spawn_file_actions_t *restrict actions, const posix_spawnattr_t *restrict attributes,
char *const argv[restrict], char *const envp[restrict]) {
if (!vpBootRoot[0] && vpFindJBRoot(vpBootRoot))
@@ -100,7 +99,15 @@ static int vpSpawnWith(VPSpawnFunction spawn, pid_t *restrict pid, const char *r
const VPInsertedLibraries libraries = vpInsertedLibrariesFor(path);
VPInjectionEnvironment injected = vpInsertHooksFor(envp, vpBootRoot, &libraries);
VPJetsamLimits limits = vpRaiseJetsamLimits(vpBootRoot, path, attributes, envp);
- int status = spawn(pid, path, actions, attributes, argv, injected.values ? injected.values : envp);
+ int status = vpSpawnWithInheritedX1Port(
+ spawn,
+ pid,
+ path,
+ actions,
+ attributes,
+ argv,
+ injected.values ? injected.values : envp
+ );
vpRestoreJetsamLimits(&limits);
if (bootstrapProgram || appProgram || libraries.count || strcmp(path, "/usr/libexec/xpcproxy") == 0) {
char event[128];
@@ -214,6 +221,7 @@ static int vpSandboxCheckByAuditToken(vp_audit_token_t token, const char *operat
}
__attribute__((constructor)) static void vpLaunchHookInit(void) {
+ vp_x1_exception_install();
if (getpid() != 1)
return;
// The firmware panic-guard patch does not remove a limit already on PID 1.
@@ -230,6 +238,7 @@ __attribute__((used, section("__DATA,__interpose"))) static const struct {
} vpInterpose[] = {
{(const void *)vpSpawn, (const void *)posix_spawn},
{(const void *)vpSpawnP, (const void *)posix_spawnp},
+ {(const void *)vpSetSpawnExceptionPortsPreservingX1, (const void *)posix_spawnattr_setexceptionports_np},
{(const void *)vpMemoryStatus, (const void *)memorystatus_control},
{(const void *)vpSandboxCheckByAuditToken, (const void *)sandbox_check_by_audit_token},
};
diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefile
index 8a3d8cbb..6e9a0029 100644
--- a/VPhoneGuestComponents/Makefile
+++ b/VPhoneGuestComponents/Makefile
@@ -5,6 +5,9 @@ OUT := $(abspath ../.build/siblings)
STAGE := $(OUT)/stage
ARCHIVE := $(OUT)/siblings.tar
CLANG := xcrun --sdk iphoneos clang
+MACOS_SDK := $(shell xcrun --sdk macosx --show-sdk-path)
+MACH_EXC_DEFS := $(MACOS_SDK)/usr/include/mach/mach_exc.defs
+LAUNCHHOOK_GENERATED := $(OUT)/generated/launchhook
GUEST_C_FLAGS := -arch arm64e -miphoneos-version-min=26.0 -Os
COMMON_FLAGS := $(GUEST_C_FLAGS) -fobjc-arc
@@ -35,10 +38,10 @@ VCAMCAPTURED_INPUTS := $(call find_headers,$(VCAM_HEADER_DIRS)) \
$(call find_folders,$(VCAM_HEADER_DIRS))
VCAMCAPTURED_INCLUDE_FLAGS := $(addprefix -I,$(call find_folders,VCamCaptured) $(VCAM_SHARED_DIRS))
LAUNCHHOOK := $(STAGE)/launchhook/launchdhook-vphone.dylib
-LAUNCHHOOK_SOURCES := $(wildcard LaunchHook/*.c) Shared/RootHideLoaderLinks.c
+LAUNCHHOOK_SOURCES := $(wildcard LaunchHook/*.c) Shared/RootHideLoaderLinks.c Shared/VPhoneX1Spawn.c
LAUNCHHOOK_INCLUDES := $(wildcard LaunchHook/*.h LaunchHook/*.inc Shared/*.h)
SYSTEMHOOK := $(STAGE)/systemhook/SystemHook-vphone.dylib
-SYSTEMHOOK_SOURCES := $(wildcard SystemHook/*.c) $(wildcard FlutterRemapFix/*.c) Shared/RootHideLoaderLinks.c
+SYSTEMHOOK_SOURCES := $(wildcard SystemHook/*.c) $(wildcard FlutterRemapFix/*.c) Shared/RootHideLoaderLinks.c Shared/VPhoneX1Spawn.c
SYSTEMHOOK_INCLUDES := $(wildcard SystemHook/*.h SystemHook/*.inc FlutterRemapFix/*.h Shared/*.h)
# libmis is not a framework and has no header; the iPhoneOS SDK does ship
# libmis.tbd, so the interposed symbols bind two-level like any other import
@@ -129,7 +132,7 @@ GPU_PROVENANCE := $(STAGE)/gpu/README.md
# Directory timestamps also catch files removed from the wildcard inputs.
-.PHONY: all gpu package test-loader-links test-injection-environment test-devicename test-vcam-dataplane test-virtiosound clean
+.PHONY: all gpu package test-loader-links test-injection-environment test-devicename test-vcam-dataplane test-virtiosound test-x1-lowering clean
all: $(ARTIFACTS) $(PLISTS) $(GPU_PROVENANCE)
@@ -153,6 +156,12 @@ test-injection-environment:
-o $(OUT)/InjectionEnvironmentTests Tests/InjectionEnvironmentTests.c
@$(OUT)/InjectionEnvironmentTests
+test-x1-lowering:
+ @mkdir -p $(OUT)
+ xcrun --sdk macosx clang -Wall -Wextra -Werror -ILaunchHook \
+ -o $(OUT)/X1LoweringTests Tests/X1LoweringTests.c LaunchHook/VPhoneX1Lowering.c
+ @$(OUT)/X1LoweringTests
+
# Host proof harness for libdevicename's name decoding, configd publication
# rewrite and lockdownd rename decision.
test-devicename:
@@ -217,10 +226,22 @@ $(VCAMCAPTURED): $(VCAMCAPTURED_SOURCES) $(VCAMCAPTURED_INPUTS) | $(STAGE)/vcamc
-framework CoreGraphics
@codesign --force --sign - $@
-$(LAUNCHHOOK): $(LAUNCHHOOK_SOURCES) $(LAUNCHHOOK_INCLUDES) LaunchHook Shared | $(STAGE)/launchhook
+$(LAUNCHHOOK): $(LAUNCHHOOK_SOURCES) $(LAUNCHHOOK_INCLUDES) LaunchHook Shared $(MACH_EXC_DEFS) | $(STAGE)/launchhook
+ @mkdir -p $(LAUNCHHOOK_GENERATED)
+ xcrun --sdk macosx mig -arch arm64 -isysroot $(MACOS_SDK) \
+ -server $(LAUNCHHOOK_GENERATED)/mach_excServer.c \
+ -sheader $(LAUNCHHOOK_GENERATED)/mach_excServer.h \
+ -user $(LAUNCHHOOK_GENERATED)/mach_excUser.c \
+ -header $(LAUNCHHOOK_GENERATED)/mach_exc.h $(MACH_EXC_DEFS)
+ /usr/bin/sed -i '' 's/msg_result = mach_msg(/msg_result = vp_mach_msg_kobject(/g' \
+ $(LAUNCHHOOK_GENERATED)/mach_excUser.c
+ @/usr/bin/grep -q 'msg_result = vp_mach_msg_kobject(' $(LAUNCHHOOK_GENERATED)/mach_excUser.c
+ @! /usr/bin/grep -q 'msg_result = mach_msg(' $(LAUNCHHOOK_GENERATED)/mach_excUser.c
$(CLANG) $(GUEST_C_FLAGS) -dynamiclib \
+ -I$(LAUNCHHOOK_GENERATED) -ILaunchHook -include VPhoneMachMessage.h \
-install_name /usr/lib/launchdhook-vphone.dylib \
- -o $@ $(LAUNCHHOOK_SOURCES) -Wl,-not_for_dyld_shared_cache
+ -o $@ $(LAUNCHHOOK_SOURCES) $(LAUNCHHOOK_GENERATED)/mach_excServer.c \
+ $(LAUNCHHOOK_GENERATED)/mach_excUser.c -Wl,-not_for_dyld_shared_cache
@codesign --force --sign - $@
$(SYSTEMHOOK): $(SYSTEMHOOK_SOURCES) $(SYSTEMHOOK_INCLUDES) SystemHook Shared | $(STAGE)/systemhook
diff --git a/VPhoneGuestComponents/Shared/VPhoneX1Spawn.c b/VPhoneGuestComponents/Shared/VPhoneX1Spawn.c
new file mode 100644
index 00000000..aa417211
--- /dev/null
+++ b/VPhoneGuestComponents/Shared/VPhoneX1Spawn.c
@@ -0,0 +1,114 @@
+#include "VPhoneX1Spawn.h"
+
+#include <mach/mach.h>
+#include <pthread.h>
+#include <stdbool.h>
+
+static pthread_once_t vpX1PortOnce = PTHREAD_ONCE_INIT;
+static mach_port_t vpX1Port = MACH_PORT_NULL;
+
+static void vpFindInheritedX1Port(void) {
+ exception_mask_t masks[EXC_TYPES_COUNT];
+ mach_port_t ports[EXC_TYPES_COUNT];
+ exception_behavior_t behaviors[EXC_TYPES_COUNT];
+ thread_state_flavor_t flavors[EXC_TYPES_COUNT];
+ mach_msg_type_number_t count = EXC_TYPES_COUNT;
+ kern_return_t result = task_get_exception_ports(
+ mach_task_self(),
+ EXC_MASK_BAD_INSTRUCTION,
+ masks,
+ &count,
+ ports,
+ behaviors,
+ flavors
+ );
+ if (result != KERN_SUCCESS) return;
+
+ for (mach_msg_type_number_t index = 0; index < count; index++) {
+ bool isX1Action = (masks[index] & EXC_MASK_BAD_INSTRUCTION) != 0 &&
+ ports[index] != MACH_PORT_NULL &&
+ behaviors[index] == (exception_behavior_t)(
+ EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES) &&
+ flavors[index] == 0;
+ if (isX1Action) {
+ // Retain the inherited send right for this process.
+ vpX1Port = ports[index];
+ } else if (ports[index] != MACH_PORT_NULL) {
+ mach_port_deallocate(mach_task_self(), ports[index]);
+ }
+ }
+}
+
+static mach_port_t vpInheritedX1Port(void) {
+ pthread_once(&vpX1PortOnce, vpFindInheritedX1Port);
+ return vpX1Port;
+}
+
+int vpSetSpawnExceptionPortsPreservingX1(
+ posix_spawnattr_t *attributes,
+ exception_mask_t mask,
+ mach_port_t port,
+ exception_behavior_t behavior,
+ thread_state_flavor_t flavor
+) {
+ mach_port_t x1Port = vpInheritedX1Port();
+ if (x1Port == MACH_PORT_NULL || (mask & EXC_MASK_BAD_INSTRUCTION) == 0) {
+ return posix_spawnattr_setexceptionports_np(
+ attributes, mask, port, behavior, flavor
+ );
+ }
+
+ exception_mask_t remaining = mask & ~EXC_MASK_BAD_INSTRUCTION;
+ if (remaining != 0) {
+ int status = posix_spawnattr_setexceptionports_np(
+ attributes, remaining, port, behavior, flavor
+ );
+ if (status != 0) return status;
+ }
+ return posix_spawnattr_setexceptionports_np(
+ attributes,
+ EXC_MASK_BAD_INSTRUCTION,
+ x1Port,
+ EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES,
+ 0
+ );
+}
+
+int vpSpawnWithInheritedX1Port(
+ VPX1SpawnFunction spawn,
+ pid_t *restrict pid,
+ const char *restrict path,
+ const posix_spawn_file_actions_t *restrict actions,
+ const posix_spawnattr_t *restrict attributes,
+ char *const argv[restrict],
+ char *const envp[restrict]
+) {
+ mach_port_t port = vpInheritedX1Port();
+ if (port == MACH_PORT_NULL)
+ return spawn(pid, path, actions, attributes, argv, envp);
+
+ posix_spawnattr_t localAttributes = NULL;
+ posix_spawnattr_t *childAttributes;
+ bool ownsAttributes = attributes == NULL;
+ if (ownsAttributes) {
+ if (posix_spawnattr_init(&localAttributes) != 0)
+ return spawn(pid, path, actions, attributes, argv, envp);
+ childAttributes = &localAttributes;
+ } else {
+ childAttributes = (posix_spawnattr_t *)(void *)attributes;
+ }
+ int configured = posix_spawnattr_setexceptionports_np(
+ childAttributes,
+ EXC_MASK_BAD_INSTRUCTION,
+ port,
+ EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES,
+ 0
+ );
+ if (configured != 0) {
+ if (ownsAttributes) posix_spawnattr_destroy(&localAttributes);
+ return spawn(pid, path, actions, attributes, argv, envp);
+ }
+ int status = spawn(pid, path, actions, childAttributes, argv, envp);
+ if (ownsAttributes) posix_spawnattr_destroy(&localAttributes);
+ return status;
+}
diff --git a/VPhoneGuestComponents/Shared/VPhoneX1Spawn.h b/VPhoneGuestComponents/Shared/VPhoneX1Spawn.h
new file mode 100644
index 00000000..1136782b
--- /dev/null
+++ b/VPhoneGuestComponents/Shared/VPhoneX1Spawn.h
@@ -0,0 +1,34 @@
+#ifndef VPHONE_X1_SPAWN_H
+#define VPHONE_X1_SPAWN_H
+
+#include <mach/mach.h>
+#include <spawn.h>
+
+typedef int (*VPX1SpawnFunction)(
+ pid_t *restrict,
+ const char *restrict,
+ const posix_spawn_file_actions_t *restrict,
+ const posix_spawnattr_t *restrict,
+ char *const[restrict],
+ char *const[restrict]
+);
+
+int vpSpawnWithInheritedX1Port(
+ VPX1SpawnFunction spawn,
+ pid_t *restrict pid,
+ const char *restrict path,
+ const posix_spawn_file_actions_t *restrict actions,
+ const posix_spawnattr_t *restrict attributes,
+ char *const argv[restrict],
+ char *const envp[restrict]
+);
+
+int vpSetSpawnExceptionPortsPreservingX1(
+ posix_spawnattr_t *attributes,
+ exception_mask_t mask,
+ mach_port_t port,
+ exception_behavior_t behavior,
+ thread_state_flavor_t flavor
+);
+
+#endif
diff --git a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
index c371ff3b..71fdc213 100644
--- a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
+++ b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
@@ -2,6 +2,7 @@
#include "../Shared/AttitudeProcess.h"
#include "../Shared/JetsamLimits.h"
#include "../Shared/RootHideLoaderLinks.h"
+#include "../Shared/VPhoneX1Spawn.h"
#include <crt_externs.h>
#include <dlfcn.h>
#include <errno.h>
@@ -124,7 +125,10 @@ static int vpSpawnP(pid_t *restrict pid, const char *restrict path, const posix_
char *const envp[restrict]) {
VPInjectionEnvironment injected = vpPrepareChild(path, envp, "");
VPJetsamLimits limits = vpRaiseJetsamLimits(getenv("VPHONE_JB_ROOT"), path, attributes, envp);
- int status = posix_spawnp(pid, path, actions, attributes, argv, injected.values ? injected.values : envp);
+ int status = vpSpawnWithInheritedX1Port(
+ posix_spawnp, pid, path, actions, attributes, argv,
+ injected.values ? injected.values : envp
+ );
vpRestoreJetsamLimits(&limits);
vpFreeEnvironment(&injected);
return status;
@@ -135,7 +139,10 @@ static int vpSpawn(pid_t *restrict pid, const char *restrict path, const posix_s
char *const envp[restrict]) {
VPInjectionEnvironment injected = vpPrepareChild(path, envp, "");
VPJetsamLimits limits = vpRaiseJetsamLimits(getenv("VPHONE_JB_ROOT"), path, attributes, envp);
- int status = posix_spawn(pid, path, actions, attributes, argv, injected.values ? injected.values : envp);
+ int status = vpSpawnWithInheritedX1Port(
+ posix_spawn, pid, path, actions, attributes, argv,
+ injected.values ? injected.values : envp
+ );
vpRestoreJetsamLimits(&limits);
vpFreeEnvironment(&injected);
return status;
@@ -283,5 +290,6 @@ __attribute__((used, section("__DATA,__interpose"))) static const struct {
} vpInterpose[] = {
{(const void *)vpSpawnP, (const void *)posix_spawnp},
{(const void *)vpSpawn, (const void *)posix_spawn},
+ {(const void *)vpSetSpawnExceptionPortsPreservingX1, (const void *)posix_spawnattr_setexceptionports_np},
{(const void *)vpExecve, (const void *)execve},
};
diff --git a/VPhoneGuestComponents/Tests/X1LoweringTests.c b/VPhoneGuestComponents/Tests/X1LoweringTests.c
new file mode 100644
index 00000000..c70d522f
--- /dev/null
+++ b/VPhoneGuestComponents/Tests/X1LoweringTests.c
@@ -0,0 +1,57 @@
+#include "../LaunchHook/VPhoneX1Lowering.h"
+#include <assert.h>
+#include <stdint.h>
+#include <stdio.h>
+
+static void expect(uint32_t input, uint32_t expected) {
+ uint32_t output = 0;
+ assert(vp_x1_lower_instruction(input, &output));
+ assert(output == expected);
+}
+
+static void reject(uint32_t input) {
+ uint32_t output = 0xAAAAAAAA;
+ assert(!vp_x1_lower_instruction(input, &output));
+ assert(output == 0xAAAAAAAA);
+}
+
+int main(void) {
+ expect(0xDAC1A7FE, 0xD503237F); // PACIBSPPC -> PACIBSP
+ expect(0xDAC187FE, 0xD503237F); // PACNBIBSPPC -> PACIBSP
+ expect(0xDAC1A3FE, 0xD503233F); // PACIASPPC -> PACIASP
+ expect(0xDAC183FE, 0xD503233F); // PACNBIASPPC -> PACIASP
+ expect(0xF3A0009F, 0xD50323FF); // AUTIBSPPCi -> AUTIBSP
+ expect(0xF3BFFFFF, 0xD50323FF); // AUTIBSPPCi, maximum distance -> AUTIBSP
+ expect(0xDAC1947E, 0xD50323FF); // AUTIBSPPCr -> AUTIBSP
+ expect(0xF38000DF, 0xD50323BF); // AUTIASPPCi -> AUTIASP
+ expect(0xF39FFFFF, 0xD50323BF); // AUTIASPPCi, maximum distance -> AUTIASP
+ expect(0xDAC1909E, 0xD50323BF); // AUTIASPPCr -> AUTIASP
+ expect(0x5520011F, 0xD65F0FFF); // RETABSPPCi -> RETAB
+ expect(0x5520053F, 0xD65F0FFF); // fsck cold-boot RETABSPPCi -> RETAB
+ expect(0x55200B1F, 0xD65F0FFF); // fsck later RETABSPPCi -> RETAB
+ expect(0x553FFFFF, 0xD65F0FFF); // RETABSPPCi, maximum distance -> RETAB
+ expect(0xD65F0FE5, 0xD65F0FFF); // RETABSPPCr -> RETAB
+ expect(0x5500015F, 0xD65F0BFF); // RETAASPPCi -> RETAA
+ expect(0x551FFFFF, 0xD65F0BFF); // RETAASPPCi, maximum distance -> RETAA
+ expect(0xD65F0BE6, 0xD65F0BFF); // RETAASPPCr -> RETAA
+ expect(0xDAC1BBFE, 0xD503219F); // AUTIA171615 -> AUTIA1716
+ expect(0xDAC1BFFE, 0xD50321DF); // AUTIB171615 -> AUTIB1716
+
+ expect(0x9A022020, 0x8B020020); // ADDPT x0,x1,x2
+ reject(0x9A043FE3); // SP plus shift 7 has no ordinary equivalent
+ expect(0x9A0630BF, 0x8B2670BF); // ADDPT sp,x5,x6,lsl #4
+ expect(0xDA092D07, 0xCB090D07); // SUBPT x7,x8,x9,lsl #3
+ expect(0xDA0A27FF, 0xCB2A67FF); // SUBPT sp,sp,x10,lsl #1
+ expect(0x9B620C20, 0x9B020C20); // MADDPT x0,x1,x2,x3
+ expect(0x9B661CA4, 0x9B061CA4); // MADDPT x4,x5,x6,x7
+ expect(0x9B6AAD28, 0x9B0AAD28); // MSUBPT x8,x9,x10,x11
+ expect(0x9B6EBDAC, 0x9B0EBDAC); // MSUBPT x12,x13,x14,x15
+
+ reject(0xDAC18BFE); // PACIA171615 deliberately unsupported
+ reject(0xDAC18FFE); // PACIB171615 deliberately unsupported
+ reject(0x00000000); // UDF and every unrelated instruction are forwarded
+ reject(0xD503201F); // NOP
+ assert(!vp_x1_lower_instruction(0xDAC1A7FE, NULL));
+ puts("X1LoweringTests: PASS");
+ return 0;
+}
diff --git a/VPhoneKit/VPhoneCoreKit/Firmware/VPhoneFirmwareCatalog.swift b/VPhoneKit/VPhoneCoreKit/Firmware/VPhoneFirmwareCatalog.swift
index 9223523b..68bf4710 100644
--- a/VPhoneKit/VPhoneCoreKit/Firmware/VPhoneFirmwareCatalog.swift
+++ b/VPhoneKit/VPhoneCoreKit/Firmware/VPhoneFirmwareCatalog.swift
@@ -310,6 +310,9 @@ public enum VPhoneFirmwareCatalog {
("27.0", "https://updates.cdn-apple.com/2026FallFCS/dff48a54-47d4-4a76-909e-21ac46b95468/iPhone18,5_27.0_24A437_Restore.ipsw"),
("27.0.1", "https://updates.cdn-apple.com/2026FallFCS/dad095d6-083a-4ff2-a2be-29503e316461/iPhone18,5_27.0.1_24A446_Restore.ipsw"),
]),
+ (devices: ["iPhone19,2"], releases: [
+ ("27.0.1", "https://updates.cdn-apple.com/2026FallFCS/8cd333d4-1025-4e89-99a2-1373d2b5bfcb/iPhone19,2_27.0.1_24A446_Restore.ipsw"),
+ ]),
]
/// iPadOS releases, one entry per iPad IPSW, oldest first. Each IPSW also
diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestDevice.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestDevice.swift
index f0f3b2ed..e10c2e05 100644
--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestDevice.swift
+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestDevice.swift
@@ -110,6 +110,8 @@ public struct VPhoneGuestDevice: Sendable, Equatable {
public static let iPhone18_4 = iPhone("iPhone18,4", "d23ap", "iPhone Air", width: 1260, height: 2736)
/// iPhone 17e: 1170x2532, 390x844 points.
public static let iPhone18_5 = iPhone("iPhone18,5", "v159ap", "iPhone 17e", width: 1170, height: 2532)
+ /// iPhone 18 Pro (V63AP): 1206x2622, 402x874 points.
+ public static let iPhone19_2 = iPhone("iPhone19,2", "v63ap", "iPhone 18 Pro", width: 1206, height: 2622)
private static func iPad(
_ productType: String,
@@ -188,6 +190,7 @@ public struct VPhoneGuestDevice: Sendable, Equatable {
iPhone17_3,
iPhone17_4, iPhone17_1, iPhone17_2, iPhone17_5,
iPhone18_3, iPhone18_4, iPhone18_1, iPhone18_2, iPhone18_5,
+ iPhone19_2,
iPad16_1,
iPad15_7,
iPad15_3, iPad15_5,
diff --git a/VPhoneKit/VPhoneCoreKitTests/Firmware/FirmwareCatalogReportTests.swift b/VPhoneKit/VPhoneCoreKitTests/Firmware/FirmwareCatalogReportTests.swift
index 8db3fc09..530d2340 100644
--- a/VPhoneKit/VPhoneCoreKitTests/Firmware/FirmwareCatalogReportTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/Firmware/FirmwareCatalogReportTests.swift
@@ -109,7 +109,12 @@ struct FirmwareCatalogReportTests {
@Test func `other i phones have pairings of their own`() {
for guest in VPhoneGuestDevice.known where guest.family == .iPhone && guest.presentsBoard {
let pairings = VPhoneFirmwareCatalog.pairings(for: guest.productType)
- #expect(pairings.map(\.iosName).first == (guest.productType == "iPhone18,5" ? "iOS 26.3.1" : "iOS 26.0"))
+ let firstRelease = switch guest.productType {
+ case "iPhone18,5": "iOS 26.3.1"
+ case "iPhone19,2": "iOS 27.0.1"
+ default: "iOS 26.0"
+ }
+ #expect(pairings.map(\.iosName).first == firstRelease)
#expect(pairings.map(\.iosName).last == "iOS 27.0.1")
for p in pairings {
#expect(p.device == guest.productType)
diff --git a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/GuestDeviceTests.swift b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/GuestDeviceTests.swift
index edf08b00..172e52e0 100644
--- a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/GuestDeviceTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/GuestDeviceTests.swift
@@ -137,4 +137,20 @@ struct GuestDeviceTests {
#expect(VPhoneGuestDevice.iPhone18_1.deviceClass == "v53ap")
#expect(VPhoneGuestDevice.iPhone18_1.screen == .init(width: 1206, height: 2622, pixelsPerInch: 460, scale: 3.0))
}
+
+ @Test
+ func `iPhone 18 Pro preserves its V63 identity and display in the VM`() throws {
+ let device = try #require(VPhoneGuestDevice.detect(buildManifest: ["SupportedProductTypes": ["iPhone19,2"]]))
+ #expect(device == .iPhone19_2)
+ #expect(device.deviceClass == "v63ap")
+ #expect(device.boardDeviceTreePath == "Firmware/all_flash/DeviceTree.v63ap.im4p")
+ let manifest = VPhoneVirtualMachineManifest.newVM().updating(guestDevice: device)
+ let decoded = try PropertyListDecoder().decode(
+ VPhoneVirtualMachineManifest.self,
+ from: PropertyListEncoder().encode(manifest),
+ )
+ #expect(decoded.guestProductType == "iPhone19,2")
+ #expect(decoded.guestDevice == device)
+ #expect(decoded.screenConfig == .init(width: 1206, height: 2622, pixelsPerInch: 460, scale: 3.0))
+ }
}