Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

refactor: split oversized files along their real seams

Lakr2141120e85b2
diff --git a/sources/FirmwarePatcher/DeviceTree/DeviceTreeNodeAdditions.swift b/sources/FirmwarePatcher/DeviceTree/DeviceTreeNodeAdditions.swift
new file mode 100644
index 00000000..77bc6d79
--- /dev/null
+++ b/sources/FirmwarePatcher/DeviceTree/DeviceTreeNodeAdditions.swift
@@ -0,0 +1,333 @@
+// DeviceTreeNodeAdditions.swift — DeviceTree child-node additions.
+//
+// Nodes a real iPhone17,3 (D47AP) carries but vphone600 does not, added
+// so the userland answer surface matches the spoofed identity. Gated
+// behind `includeIdentityPatches` (the `.exp` variant only).
+//
+// Historical note: derived from the legacy Python firmware patcher during the Swift migration.
+
+import Foundation
+
+extension DeviceTreePatcher {
+ /// Experimental child-node additions. Adds nodes that exist on real
+ /// iPhone17,3 but not on vphone600 — so the userland answer surface
+ /// matches the spoofed identity. Gated by `includeIdentityPatches`
+ /// (EXP variant only).
+ ///
+ /// `/device-tree/product/camera` is required for
+ /// `MGGetBoolAnswer("still-camera")` to return YES — without it,
+ /// SpringBoard's SBAppTags filter hides `Camera.app`'s icon and
+ /// blocks launch. The d47ap DT carries this node with 64 capability
+ /// properties; the subset here is the minimum that backs the
+ /// `cameraCapability` / `aggregateCameraCapability` /
+ /// `autoFocusCameraCapability` getters in libMobileGestalt and the
+ /// `still-camera` answer the SBAppTags consumer hits.
+ static let experimentalNodeAdditions: [AddChildNodePatch] = [
+ // Replicates the full `/product/camera` property set carried by the
+ // iPhone17,3 D47AP DT (62 props in the reference build, all integers
+ // or zero-length placeholders). The minimal 11-property version
+ // wasn't enough — `PurpleBuddy` and other first-boot consumers
+ // re-evaluate camera capability via `MGGetBoolAnswer` reading
+ // additional DT properties (front-flash-capability,
+ // live-photo-capture, rear-cam-superwide-capability, etc.) and
+ // hide the Camera icon if any return nil/absent.
+ //
+ // Values copied byte-for-byte from
+ // `ipsws/iPhone17,3_26.5_23F77_Restore_extracted/Firmware/all_flash/DeviceTree.d47ap.im4p`
+ // post-LZFSE-decompression. Sorted alphabetically for diff stability.
+ // The `"<"` / `"d"` / `"x"` values that ipsw dtree shows are 4-byte
+ // little-endian ints whose first byte happens to print:
+ // "<" = 0x3C = 60 (60 fps cap)
+ // "d" = 0x64 = 100 (100-ms burst duration)
+ // "x" = 0x78 = 120 (120 fps slomo cap)
+ // `<nil>` properties are 0-length placeholders (the name exists but
+ // there's no value blob); MGGetBoolAnswer treats those as YES too.
+ AddChildNodePatch(
+ parentPath: ["device-tree", "product"],
+ nodeName: "camera",
+ properties: [
+ .init(name: "aggregate-cam-photo-zoom", length: 4, flags: 0, value: .integer(0x7d0)),
+ .init(name: "aggregate-cam-video-zoom", length: 4, flags: 0, value: .integer(0x4b0)),
+ .init(name: "aggregate-camera", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "auto-focus", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "auto-low-light-video", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "camera-hdr-version", length: 4, flags: 0, value: .integer(3)),
+ .init(name: "camera-ui-version", length: 4, flags: 0, value: .integer(2)),
+ .init(name: "deferred-processing", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "flash", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "front-auto-focus", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "front-auto-hdr", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "front-burst", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "front-burst-image-duration", length: 4, flags: 0, value: .integer(100)),
+ .init(name: "front-flash-capability", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "front-hdr", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "front-hdr-on", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "front-low-light-photo", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "front-max-burst-length", length: 4, flags: 0, value: .integer(600)),
+ .init(name: "front-max-slomo-video-fps-1080p", length: 4, flags: 0, value: .integer(120)),
+ .init(name: "front-max-slomo-video-fps-720p", length: 4, flags: 0, value: .integer(120)),
+ .init(name: "front-max-video-fps-1080p", length: 4, flags: 0, value: .integer(60)),
+ .init(name: "front-max-video-fps-4k", length: 4, flags: 0, value: .integer(60)),
+ .init(name: "front-max-video-fps-720p", length: 4, flags: 0, value: .integer(60)),
+ .init(name: "front-max-video-zoom", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "front-slowmo", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "front-stage-light-portrait", length: 0, flags: 0, value: .bytes(Data())),
+ .init(name: "front-variable-frame-rate", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "live-effects", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "live-photo-auto", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "live-photo-capture", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "moment-capture", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "p3-color-space-video-recording", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "panorama", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "pearl-camera", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "photo-capture-on-touch-down", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "photos-live-video-rendering", length: 0, flags: 0, value: .bytes(Data())),
+ .init(name: "pipelined-stillimage-capability", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "portrait-lighting-strength", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "post-effects", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "rear-auto-hdr", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "rear-burst", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "rear-burst-image-duration", length: 4, flags: 0, value: .integer(100)),
+ .init(name: "rear-cam-sup-wide-af-capability", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "rear-cam-superwide-capability", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "rear-hdr", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "rear-hdr-on", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "rear-low-light-photo", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "rear-max-burst-length", length: 4, flags: 0, value: .integer(600)),
+ .init(name: "rear-max-slomo-video-fps-1080p", length: 4, flags: 0, value: .integer(240)),
+ .init(name: "rear-max-slomo-video-fps-720p", length: 4, flags: 0, value: .integer(240)),
+ .init(name: "rear-max-video-fps-1080p", length: 4, flags: 0, value: .integer(60)),
+ .init(name: "rear-max-video-fps-4k", length: 4, flags: 0, value: .integer(60)),
+ .init(name: "rear-max-video-fps-720p", length: 4, flags: 0, value: .integer(60)),
+ .init(name: "rear-max-video-frame_rate", length: 4, flags: 0, value: .integer(60)),
+ .init(name: "rear-max-video-zoom", length: 4, flags: 0, value: .integer(3)),
+ .init(name: "rear-slowmo", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "rear-stage-light-portrait", length: 0, flags: 0, value: .bytes(Data())),
+ .init(name: "rear-variable-frame-rate", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "spatial-over-capture", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "stage-light-portrait-preview", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "video-cap", length: 4, flags: 0, value: .integer(2)),
+ .init(name: "video-stills", length: 4, flags: 0, value: .integer(1)),
+ ],
+ patchID: "devicetree.product.camera_node",
+ description: "Add /product/camera node with full iPhone17,3 D47AP property set (62 props)"
+ ),
+
+ // ── /product/facetime (Tier C — front-camera video-call config) ──
+ // d47ap carries this 11-property node (excluding AAPL,phandle).
+ // FaceTime reads bitrate-{2g,3g,lte,wifi}, decoding/encoding
+ // codec parameters, pref-decoding, and tnr-mode-{back,front}
+ // (temporal noise reduction) at app launch. Values byte-for-byte
+ // from the d47ap DT.
+ AddChildNodePatch(
+ parentPath: ["device-tree", "product"],
+ nodeName: "facetime",
+ properties: [
+ .init(name: "bitrate-2g", length: 4, flags: 0, value: .integer(100)),
+ .init(name: "bitrate-3g", length: 4, flags: 0, value: .integer(228)),
+ .init(name: "bitrate-lte", length: 4, flags: 0, value: .integer(228)),
+ .init(name: "bitrate-wifi", length: 4, flags: 0, value: .integer(2000)),
+ .init(name: "decoding", length: 48, flags: 0, value: .bytes(Data([
+ 0x40, 0x01, 0x00, 0x00, 0x0f, 0x00, 0xf0, 0x00,
+ 0x40, 0x01, 0x00, 0x00, 0x1e, 0x00, 0xf0, 0x00,
+ 0xe0, 0x01, 0x00, 0x00, 0x0f, 0x00, 0x70, 0x01,
+ 0xe0, 0x01, 0x00, 0x00, 0x1e, 0x00, 0x70, 0x01,
+ 0x80, 0x02, 0x00, 0x00, 0x1e, 0x00, 0xe0, 0x01,
+ 0x00, 0x04, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x03,
+ ]))),
+ .init(name: "encoding", length: 56, flags: 0, value: .bytes(Data([
+ 0x40, 0x01, 0x00, 0x00, 0x0f, 0x00, 0xf0, 0x00,
+ 0x40, 0x01, 0x00, 0x00, 0x1e, 0x00, 0xf0, 0x00,
+ 0xe0, 0x01, 0x00, 0x00, 0x0f, 0x00, 0x70, 0x01,
+ 0xe0, 0x01, 0x00, 0x00, 0x1e, 0x00, 0x70, 0x01,
+ 0x80, 0x02, 0x00, 0x00, 0x1e, 0x00, 0xe0, 0x01,
+ 0x00, 0x04, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x03,
+ 0x00, 0x05, 0x00, 0x00, 0x1e, 0x00, 0xd0, 0x02,
+ ]))),
+ .init(name: "pref-decoding", length: 8, flags: 0, value: .integer(0x0300_001e_0000_0400)),
+ .init(name: "tnr-mode-back", length: 4, flags: 0, value: .integer(10)),
+ .init(name: "tnr-mode-front", length: 4, flags: 0, value: .integer(10)),
+ ],
+ patchID: "devicetree.product.facetime_node",
+ description: "Add /product/facetime node with full iPhone17,3 D47AP property set (9 props)"
+ ),
+
+ // ── /product/audio (Tier C — audio + spatial-capture flags) ──
+ // d47ap carries this 31-property node (excluding AAPL,phandle).
+ // Two camera-joint flags live here: `supports-spatial-audio-capture`
+ // and `supports-spatial-facetime` — needed for spatial-video and
+ // spatial-photo capture pipelines that combine camera + audio.
+ // The remaining 29 properties are pure audio config (mic gains,
+ // speaker cpms, voice trigger, channel layout, codec use-case
+ // formats). Calibration cstrings (`mic-trim-gains-*`,
+ // `speaker-thiele-small-*`, `speaker-trim-gains-*`) keep their
+ // syscfg-reference form — replacing them with concrete values
+ // from d47 wouldn't make the VM's actual mic/speaker hardware
+ // match, but downstream code already handles missing-syscfg
+ // gracefully.
+ AddChildNodePatch(
+ parentPath: ["device-tree", "product"],
+ nodeName: "audio",
+ properties: [
+ .init(name: "acoustic-id", length: 4, flags: 0, value: .integer(8018)),
+ .init(name: "actuator-cpms-bgd_100ms", length: 8, flags: 0, value: .integer(0x0000_0eef_0000_01f4)),
+ .init(name: "actuator-cpms-bgd_inst", length: 8, flags: 0, value: .integer(0x0000_1db0_0000_06d6)),
+ .init(name: "enabledChannels", length: 4, flags: 0, value: .integer(15)),
+ .init(name: "historyChannels", length: 4, flags: 0, value: .integer(15)),
+ .init(name: "mic-trim-gains-0", length: 12, flags: 0, value: .string("syscfg/MiGH")),
+ .init(name: "mic-trim-gains-2", length: 12, flags: 0, value: .string("syscfg/MiGB")),
+ .init(name: "mic-trim-gains-key-cnt", length: 4, flags: 0, value: .integer(2)),
+ .init(name: "speaker-cpms-bgd_100ms", length: 8, flags: 0, value: .integer(0x0000_2328_0000_04b0)),
+ .init(name: "speaker-cpms-bgd_1s", length: 8, flags: 0, value: .integer(0x0000_2328_0000_04b0)),
+ .init(name: "speaker-cpms-bgd_inst", length: 8, flags: 0, value: .integer(0x0000_2328_0000_04b0)),
+ .init(name: "speaker-thiele-small-0", length: 12, flags: 0, value: .string("syscfg/SpPH")),
+ .init(name: "speaker-thiele-small-key-cnt", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "speaker-trim-gains-0", length: 12, flags: 0, value: .string("syscfg/SpGH")),
+ .init(name: "speaker-trim-gains-key-cnt", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "stereo-sound-recording", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "supportedChannels", length: 4, flags: 0, value: .integer(15)),
+ .init(name: "supports-advanced-vp-chatflavor", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "supports-always-listening", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "supports-audio-mix", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "supports-auto-mic-mode", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "supports-barge-in", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "supports-concurrent-hp-lp-mics", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "supports-mic-modes-telephony", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "supports-spatial-audio-capture", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "supports-spatial-facetime", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "use-case-client-format", length: 96, flags: 0, value: .bytes(Data([
+ 0x61, 0x64, 0x6e, 0x73, 0x80, 0xbb, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x69, 0x72, 0x69, 0x73, 0x80, 0x3e, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x73, 0x74, 0x70, 0x6c, 0x80, 0x3e, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ ]))),
+ .init(name: "use-case-dsp-in-format", length: 160, flags: 0, value: .bytes(Data([
+ 0x64, 0x6b, 0x74, 0x6d, 0x80, 0xbb, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x61, 0x64, 0x6e, 0x73, 0x80, 0xbb, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x64, 0x76, 0x70, 0x73, 0x80, 0xbb, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x69, 0x72, 0x69, 0x73, 0x80, 0x3e, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x73, 0x74, 0x70, 0x6c, 0x80, 0x3e, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ ]))),
+ .init(name: "use-case-struct-version", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "voiceTriggerChannels", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "wireless-splitter", length: 4, flags: 0, value: .integer(1)),
+ ],
+ patchID: "devicetree.product.audio_node",
+ description: "Add /product/audio node with full iPhone17,3 D47AP property set (31 props)"
+ ),
+
+ // ── /product/iopm (Tier C — always-on technology) ────────────
+ // d47ap carries this 2-property node (excluding AAPL,phandle).
+ // `aot-mode = 13` enables Always-On Technology — drives wake
+ // policy and always-on-display behavior. POTENTIAL DISPLAY
+ // RISK: if the VM display can't service the AOT init path,
+ // this may need to be reverted in isolation. Test this batch
+ // alongside facetime + audio + Tier B; if display breaks,
+ // remove this AddChildNodePatch entry first before bisecting
+ // the rest.
+ AddChildNodePatch(
+ parentPath: ["device-tree", "product"],
+ nodeName: "iopm",
+ properties: [
+ .init(name: "aot-linger-time-ms", length: 4, flags: 0, value: .integer(0)),
+ .init(name: "aot-mode", length: 4, flags: 0, value: .integer(13)),
+ ],
+ patchID: "devicetree.product.iopm_node",
+ description: "Add /product/iopm node with aot-mode=13 + aot-linger-time-ms=0 (2 props)"
+ ),
+
+ // ── ISP / SMC camera-flag stubs (Tier F — /arm-io subtree) ──
+ // Adds minimal stub nodes carrying ONLY the camera-related
+ // properties that libMobileGestalt / SpringBoard / Camera.app
+ // userland code walks under `/arm-io/isp`, `/arm-io/ispRtb`,
+ // and `/arm-io/smc/iop-smc-nub/smc-ext-charger`.
+ //
+ // d47ap carries these as full hardware-attach nodes (65/53/14
+ // properties). We deliberately do NOT replicate the full set
+ // — they describe a real ISP / SMC chip with MMIO regions,
+ // interrupts, DART/IOMMU bindings, kext-`compatible` strings
+ // etc., and the VM has no such hardware. Stubbing only the
+ // camera-* properties + the mandatory `name` (no `compatible`,
+ // no `device_type`, no `reg`, no `interrupts`) means:
+ //
+ // - IOKit registry sees these nodes appear under `/arm-io`.
+ // - No kext (`AppleH16CamIn`, AppleSMC, etc.) finds a
+ // matching `compatible` and binds, so no driver probe
+ // can fail-and-panic on missing hardware.
+ // - Userland code that resolves these paths via
+ // `IORegistryEntryFromPath` + `IORegistryEntryGetProperty`
+ // still finds the camera-* properties on the empty stub.
+ //
+ // RISK: still untested. If an IOKit walker reports the empty
+ // node and a userland daemon (e.g. cameracaptured) takes the
+ // node's presence as "real ISP attached" and then crashes
+ // trying to talk to it, the symptom is likely a boot stall or
+ // a camera-daemon respawn loop visible in logs. Bisect by
+ // removing /arm-io/isp + /arm-io/ispRtb first if so.
+ //
+ // The three nodes are added in dependency order: each parent
+ // before its children. The patcher walks `experimentalNodeAdditions`
+ // in array order against the in-memory tree, so later entries
+ // can resolve parents added by earlier entries.
+
+ // /arm-io/smc — empty stub (parent for iop-smc-nub).
+ AddChildNodePatch(
+ parentPath: ["device-tree", "arm-io"],
+ nodeName: "smc",
+ properties: [],
+ patchID: "devicetree.arm_io.smc_stub",
+ description: "Add /arm-io/smc empty stub (parent for smc-ext-charger chain)"
+ ),
+
+ // /arm-io/smc/iop-smc-nub — empty stub (parent for smc-ext-charger).
+ AddChildNodePatch(
+ parentPath: ["device-tree", "arm-io", "smc"],
+ nodeName: "iop-smc-nub",
+ properties: [],
+ patchID: "devicetree.arm_io.smc.iop_smc_nub_stub",
+ description: "Add /arm-io/smc/iop-smc-nub empty stub (parent for smc-ext-charger)"
+ ),
+
+ // /arm-io/smc/iop-smc-nub/smc-ext-charger — carries camera-driver.
+ AddChildNodePatch(
+ parentPath: ["device-tree", "arm-io", "smc", "iop-smc-nub"],
+ nodeName: "smc-ext-charger",
+ properties: [
+ .init(name: "camera-driver", length: 14, flags: 0, value: .string("AppleH16CamIn")),
+ ],
+ patchID: "devicetree.arm_io.smc.smc_ext_charger_camera_driver",
+ description: "Add /arm-io/smc/iop-smc-nub/smc-ext-charger with camera-driver='AppleH16CamIn'"
+ ),
+
+ // /arm-io/isp — minimal stub carrying camera-front + camera-rear.
+ AddChildNodePatch(
+ parentPath: ["device-tree", "arm-io"],
+ nodeName: "isp",
+ properties: [
+ .init(name: "camera-front", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "camera-rear", length: 4, flags: 0, value: .integer(1)),
+ ],
+ patchID: "devicetree.arm_io.isp_camera_flags",
+ description: "Add /arm-io/isp stub with camera-front=1 + camera-rear=1"
+ ),
+
+ // /arm-io/ispRtb — minimal stub carrying camera-front + camera-rear.
+ AddChildNodePatch(
+ parentPath: ["device-tree", "arm-io"],
+ nodeName: "ispRtb",
+ properties: [
+ .init(name: "camera-front", length: 4, flags: 0, value: .integer(1)),
+ .init(name: "camera-rear", length: 4, flags: 0, value: .integer(1)),
+ ],
+ patchID: "devicetree.arm_io.ispRtb_camera_flags",
+ description: "Add /arm-io/ispRtb stub with camera-front=1 + camera-rear=1"
+ ),
+ ]
+}
diff --git a/sources/FirmwarePatcher/DeviceTree/DeviceTreePatchSpecs.swift b/sources/FirmwarePatcher/DeviceTree/DeviceTreePatchSpecs.swift
new file mode 100644
index 00000000..05f3ca8e
--- /dev/null
+++ b/sources/FirmwarePatcher/DeviceTree/DeviceTreePatchSpecs.swift
@@ -0,0 +1,54 @@
+// DeviceTreePatchSpecs.swift — DeviceTree patch specification types.
+//
+// The shapes the DeviceTree patch catalogue is written in: a property
+// rewrite, a brand-new child node, and the value a property holds.
+//
+// Historical note: derived from the legacy Python firmware patcher during the Swift migration.
+
+import Foundation
+
+extension DeviceTreePatcher {
+ // MARK: - Patch Definitions
+
+ /// A single property patch specification.
+ struct PropertyPatch {
+ let nodePath: [String]
+ let property: String
+ let length: Int
+ let flags: UInt16
+ let value: PropertyValue
+ let patchID: String
+ let description: String
+ }
+
+ /// A patch that adds a brand-new child node under an existing parent.
+ /// Used when iPhone17,3 carries a node that vphone600 does not — e.g.
+ /// `/device-tree/product/camera`, which `libMobileGestalt` requires to
+ /// answer `MGGetBoolAnswer("still-camera")` truthfully.
+ struct AddChildNodePatch {
+ let parentPath: [String]
+ let nodeName: String
+ /// Properties to place inside the new node. The `name` property is
+ /// added automatically from `nodeName`; do not include it here.
+ let properties: [PropertySpec]
+ let patchID: String
+ let description: String
+
+ struct PropertySpec {
+ let name: String
+ let length: Int
+ let flags: UInt16
+ let value: PropertyValue
+ }
+ }
+
+ /// The value to write into a device tree property.
+ enum PropertyValue {
+ case string(String)
+ case integer(UInt64)
+ /// Raw bytes — used when the property holds a multi-string blob
+ /// (NUL-delimited cstrings packed back-to-back, e.g. `compatible`)
+ /// where Swift String escaping of embedded NULs is awkward.
+ case bytes(Data)
+ }
+}
diff --git a/sources/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift b/sources/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift
index c4291c55..55afae18 100644
--- a/sources/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift
+++ b/sources/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift
@@ -25,633 +25,6 @@ public final class DeviceTreePatcher: Patcher {
var patches: [PatchRecord] = []
var rebuiltData: Data?
- // MARK: - Patch Definitions
-
- /// A single property patch specification.
- struct PropertyPatch {
- let nodePath: [String]
- let property: String
- let length: Int
- let flags: UInt16
- let value: PropertyValue
- let patchID: String
- let description: String
- }
-
- /// A patch that adds a brand-new child node under an existing parent.
- /// Used when iPhone17,3 carries a node that vphone600 does not — e.g.
- /// `/device-tree/product/camera`, which `libMobileGestalt` requires to
- /// answer `MGGetBoolAnswer("still-camera")` truthfully.
- struct AddChildNodePatch {
- let parentPath: [String]
- let nodeName: String
- /// Properties to place inside the new node. The `name` property is
- /// added automatically from `nodeName`; do not include it here.
- let properties: [PropertySpec]
- let patchID: String
- let description: String
-
- struct PropertySpec {
- let name: String
- let length: Int
- let flags: UInt16
- let value: PropertyValue
- }
- }
-
- /// The value to write into a device tree property.
- enum PropertyValue {
- case string(String)
- case integer(UInt64)
- /// Raw bytes — used when the property holds a multi-string blob
- /// (NUL-delimited cstrings packed back-to-back, e.g. `compatible`)
- /// where Swift String escaping of embedded NULs is awkward.
- case bytes(Data)
- }
-
- /// Multi-string `compatible` blob used by patch #3 (root `compatible`).
- ///
- /// Original layout (48 bytes):
- /// "VPHONE600AP\0" "iPhone99,11\0" "AppleVirtualPlatformARM\0"
- /// 11 + 1 11 + 1 23 + 1 = 48
- ///
- /// Patched layout (48 bytes, surgical change of the middle string only):
- /// "VPHONE600AP\0" "iPhone17,3\0" "AppleVirtualPlatformARM\0\0"
- /// 11 + 1 10 + 1 23 + 2 = 48
- ///
- /// `VPHONE600AP` stays as the FIRST entry so IOKit's platform-expert
- /// matching at boot still binds against the kext that claims it. The
- /// SECOND entry, which userland walks of the compatible list see when
- /// iterating to enumerate alternate identifiers, is flipped to
- /// `iPhone17,3`. The trailing `AppleVirtualPlatformARM` shifts one byte
- /// earlier (now starts at byte 23 instead of 24), but every consumer of
- /// `compatible` walks by NUL-terminator — none depend on a fixed byte
- /// offset within the blob — so the shift is harmless.
- static let compatibleRewrite: Data = {
- var d = Data()
- d.append(contentsOf: Array("VPHONE600AP".utf8))
- d.append(0)
- d.append(contentsOf: Array("iPhone17,3".utf8))
- d.append(0)
- d.append(contentsOf: Array("AppleVirtualPlatformARM".utf8))
- d.append(0)
- // 11+1 + 10+1 + 23+1 = 47 bytes so far; pad with one NUL to 48.
- d.append(0)
- return d
- }()
-
- /// Base device-tree property patches, applied for every variant.
- /// Matches the pre-experimental set (serial-number, home-button-type,
- /// artwork-device-subtype, island-notch-location) inherited from
- /// scripts/dtree.py PATCHES.
- static let basePropertyPatches: [PropertyPatch] = [
- PropertyPatch(
- nodePath: ["device-tree"],
- property: "serial-number",
- length: 12,
- flags: 0,
- value: .string("vphone-1337"),
- patchID: "devicetree.serial_number",
- description: "Set serial number to vphone-1337"
- ),
- PropertyPatch(
- nodePath: ["device-tree", "buttons"],
- property: "home-button-type",
- length: 4,
- flags: 0,
- value: .integer(2),
- patchID: "devicetree.home_button_type",
- description: "Set home button type to 2"
- ),
- PropertyPatch(
- nodePath: ["device-tree", "product"],
- property: "artwork-device-subtype",
- length: 4,
- flags: 0,
- value: .integer(2556),
- patchID: "devicetree.artwork_device_subtype",
- description: "Set artwork device subtype to 2556"
- ),
- PropertyPatch(
- nodePath: ["device-tree", "product"],
- property: "island-notch-location",
- length: 4,
- flags: 0,
- value: .integer(144),
- patchID: "devicetree.island_notch_location",
- description: "Set island notch location to 144"
- ),
- ]
-
- /// Experimental identity-rewrite property patches. Applied only when
- /// `includeIdentityPatches` is true — currently set only by the `.exp`
- /// firmware variant. Other variants (regular, dev, jb, less) skip these.
- ///
- /// Risk categories:
- /// - LOW (#3 compatible[1], #11 sub-product-type, #12 unique-model):
- /// read by userland identity APIs; not in the restore-signed path.
- /// - HIGHER (#2 target-sub-type, #10 fdr-product-type):
- /// same family as `target-type` (which broke restore in a prior
- /// attempt) and FDR-related. If restore fails after a build that
- /// enables these, remove just those two and retry.
- /// - MEDIUM (#6 arm-io device_type, #7 arm-io soc-generation):
- /// IOKit secondary matchers; the real iPhone17,3 DT carries these
- /// exact values so they match the genuine D47AP.
- /// - LOW-MEDIUM (#13 gestalt-variants rename): some MG-equivalent
- /// code may look up the subtree by literal node name.
- /// Patches for root `model` and root `target-type` are deliberately
- /// NOT included here — both were tried, both broke restore. They are
- /// applied post-restore by EXP-JB-6 (`cfw_patch_post_restore_dt.py`)
- /// in the EXP install pipeline.
- static let identityPropertyPatches: [PropertyPatch] = [
- // ── Identity rewrite (Tier 1b) ────────────────────────────────
- // 5 properties from the 13-entry DT inventory chosen as
- // userland-facing identity surfaces. NONE of root `model` or root
- // `target-type` are included — both already proven to break restore.
-
- // #2 — root `target-sub-type` "VPHONE600AP" -> "D47AP".
- // RISK: HIGHER. Same family as `target-type`; if restore fails
- // after enabling this, remove this entry first.
- PropertyPatch(
- nodePath: ["device-tree"],
- property: "target-sub-type",
- length: 12,
- flags: 0,
- value: .string("D47AP"),
- patchID: "devicetree.target_sub_type",
- description: "Set target-sub-type to D47AP (was VPHONE600AP)"
- ),
-
- // #3 — root `compatible` surgical mangle. Keep VPHONE600AP as first
- // entry (platform-expert binding intact), rewrite iPhone99,11 (the
- // secondary entry) to iPhone17,3, keep AppleVirtualPlatformARM as
- // third entry. See `compatibleRewrite` above for byte layout.
- // RISK: LOW. Iterators of compatible[] read by userland will pick
- // up the new identity; the kernel's platform-expert bind still
- // matches the first entry, so boot is unaffected.
- PropertyPatch(
- nodePath: ["device-tree"],
- property: "compatible",
- length: 48,
- flags: 0,
- value: .bytes(compatibleRewrite),
- patchID: "devicetree.compatible_secondary",
- description: "Surgical rewrite of compatible[1]: iPhone99,11 -> iPhone17,3"
- ),
-
- // #10 — device-tree/product/fdr-product-type "iPhone99,11" -> "iPhone17,3".
- // RISK: HIGHER. FDR = Factory Data Restore; some restore-time code
- // reads this field. If restore breaks, remove this entry.
- PropertyPatch(
- nodePath: ["device-tree", "product"],
- property: "fdr-product-type",
- length: 12,
- flags: 0,
- value: .string("iPhone17,3"),
- patchID: "devicetree.product.fdr_product_type",
- description: "Set product/fdr-product-type to iPhone17,3 (was iPhone99,11)"
- ),
-
- // #11 — device-tree/product/sub-product-type "iPhone99,11" -> "iPhone17,3".
- // RISK: LOW. Read by userland classification code; not in
- // restore-signed path.
- PropertyPatch(
- nodePath: ["device-tree", "product"],
- property: "sub-product-type",
- length: 12,
- flags: 0,
- value: .string("iPhone17,3"),
- patchID: "devicetree.product.sub_product_type",
- description: "Set product/sub-product-type to iPhone17,3 (was iPhone99,11)"
- ),
-
- // #12 — device-tree/product/unique-model "VPHONE600AP" -> "D47AP".
- // RISK: LOW. Read by libMobileGestalt and "unique device class"
- // queries; not in restore-signed path.
- PropertyPatch(
- nodePath: ["device-tree", "product"],
- property: "unique-model",
- length: 12,
- flags: 0,
- value: .string("D47AP"),
- patchID: "devicetree.product.unique_model",
- description: "Set product/unique-model to D47AP (was VPHONE600AP)"
- ),
-
- // ── Identity rewrite (Tier 1c) ────────────────────────────────
- // Three more candidates from the inventory that haven't been
- // empirically shown to break restore. Each may still affect kernel
- // boot if a kext relies on the specific value.
-
- // #6 — device-tree/arm-io/device_type "vresearch1-io" -> "t8140-io".
- // RISK: MEDIUM. device_type is a secondary IOKit matcher; many
- // kexts only use compatible[] for binding, but some require both.
- // The actual d47ap DT carries "t8140-io" here, so this is the
- // genuine iPhone17,3 value (not a fabricated one).
- PropertyPatch(
- nodePath: ["device-tree", "arm-io"],
- property: "device_type",
- length: 14,
- flags: 0,
- value: .string("t8140-io"),
- patchID: "devicetree.arm_io.device_type",
- description: "Set arm-io/device_type to t8140-io (was vresearch1-io)"
- ),
-
- // #7 — device-tree/arm-io/soc-generation "VResearch1" -> "H17".
- // RISK: MEDIUM-LOW. soc-generation is typically a capability /
- // SoC-family descriptor read by kexts to select code paths.
- // d47ap (iPhone17,3) uses "H17" so we match that exactly.
- PropertyPatch(
- nodePath: ["device-tree", "arm-io"],
- property: "soc-generation",
- length: 11,
- flags: 0,
- value: .string("H17"),
- patchID: "devicetree.arm_io.soc_generation",
- description: "Set arm-io/soc-generation to H17 (was VResearch1)"
- ),
-
- // #13 — rename node device-tree/product/vphone600-gestalt-variants
- // to "d47-gestalt-variants" by rewriting its `name` property.
- // RISK: LOW-MEDIUM. Some libMobileGestalt-equivalent code may look
- // up the subtree by literal node name. d47 doesn't have a
- // `*-gestalt-variants` node at all (its product children are
- // camera/facetime/maps/haptics/audio), so iOS handles missing
- // gestalt-variants gracefully on real iPhone 17,3 devices anyway.
- // Renaming should be at-worst-equivalent to that "missing node"
- // path. The DTNode patcher walks by current name, so the nodePath
- // here uses the OLD name; the patch rewrites the `name` property
- // inside that node to the new value.
- PropertyPatch(
- nodePath: ["device-tree", "product", "vphone600-gestalt-variants"],
- property: "name",
- length: 27,
- flags: 0,
- value: .string("d47-gestalt-variants"),
- patchID: "devicetree.product.gestalt_variants_rename",
- description: "Rename node vphone600-gestalt-variants -> d47-gestalt-variants"
- ),
-
- // ── Camera physical-offset rewrites (Tier B) ──────────────────
- // vphone600 ships these as 12-byte `'syscfg/fcof'` / `'syscfg/rcof'`
- // cstring placeholders. d47ap carries 20-byte little-endian
- // blobs describing the physical mm offset from screen center
- // for each camera. Consumed by Camera.app / ARKit / FaceTime
- // for image-centering math. Replacing the placeholder with the
- // real d47ap blob (length 12 → 20) keeps the consuming code on
- // a real number rather than reading the literal `'syscfg/...'`
- // cstring as junk geometry.
- PropertyPatch(
- nodePath: ["device-tree", "product"],
- property: "front-cam-offset-from-center",
- length: 20,
- flags: 0,
- value: .bytes(Data([
- 0x61, 0x00, 0x01, 0x00, 0x92, 0x1c, 0x00, 0x00,
- 0xd8, 0x13, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00,
- ])),
- patchID: "devicetree.product.front_cam_offset",
- description: "Set product/front-cam-offset-from-center to d47ap geometry (was syscfg/fcof)"
- ),
- PropertyPatch(
- nodePath: ["device-tree", "product"],
- property: "rear-cam-offset-from-center",
- length: 20,
- flags: 0,
- value: .bytes(Data([
- 0xed, 0xa5, 0x00, 0x00, 0xb2, 0x56, 0x00, 0x00,
- 0x59, 0x08, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00,
- ])),
- patchID: "devicetree.product.rear_cam_offset",
- description: "Set product/rear-cam-offset-from-center to d47ap geometry (was syscfg/rcof)"
- ),
- ]
-
- /// Experimental child-node additions. Adds nodes that exist on real
- /// iPhone17,3 but not on vphone600 — so the userland answer surface
- /// matches the spoofed identity. Gated by `includeIdentityPatches`
- /// (EXP variant only).
- ///
- /// `/device-tree/product/camera` is required for
- /// `MGGetBoolAnswer("still-camera")` to return YES — without it,
- /// SpringBoard's SBAppTags filter hides `Camera.app`'s icon and
- /// blocks launch. The d47ap DT carries this node with 64 capability
- /// properties; the subset here is the minimum that backs the
- /// `cameraCapability` / `aggregateCameraCapability` /
- /// `autoFocusCameraCapability` getters in libMobileGestalt and the
- /// `still-camera` answer the SBAppTags consumer hits.
- static let experimentalNodeAdditions: [AddChildNodePatch] = [
- // Replicates the full `/product/camera` property set carried by the
- // iPhone17,3 D47AP DT (62 props in the reference build, all integers
- // or zero-length placeholders). The minimal 11-property version
- // wasn't enough — `PurpleBuddy` and other first-boot consumers
- // re-evaluate camera capability via `MGGetBoolAnswer` reading
- // additional DT properties (front-flash-capability,
- // live-photo-capture, rear-cam-superwide-capability, etc.) and
- // hide the Camera icon if any return nil/absent.
- //
- // Values copied byte-for-byte from
- // `ipsws/iPhone17,3_26.5_23F77_Restore_extracted/Firmware/all_flash/DeviceTree.d47ap.im4p`
- // post-LZFSE-decompression. Sorted alphabetically for diff stability.
- // The `"<"` / `"d"` / `"x"` values that ipsw dtree shows are 4-byte
- // little-endian ints whose first byte happens to print:
- // "<" = 0x3C = 60 (60 fps cap)
- // "d" = 0x64 = 100 (100-ms burst duration)
- // "x" = 0x78 = 120 (120 fps slomo cap)
- // `<nil>` properties are 0-length placeholders (the name exists but
- // there's no value blob); MGGetBoolAnswer treats those as YES too.
- AddChildNodePatch(
- parentPath: ["device-tree", "product"],
- nodeName: "camera",
- properties: [
- .init(name: "aggregate-cam-photo-zoom", length: 4, flags: 0, value: .integer(0x7d0)),
- .init(name: "aggregate-cam-video-zoom", length: 4, flags: 0, value: .integer(0x4b0)),
- .init(name: "aggregate-camera", length: 4, flags: 0, value: .integer(1)),
- .init(name: "auto-focus", length: 4, flags: 0, value: .integer(1)),
- .init(name: "auto-low-light-video", length: 4, flags: 0, value: .integer(1)),
- .init(name: "camera-hdr-version", length: 4, flags: 0, value: .integer(3)),
- .init(name: "camera-ui-version", length: 4, flags: 0, value: .integer(2)),
- .init(name: "deferred-processing", length: 4, flags: 0, value: .integer(1)),
- .init(name: "flash", length: 4, flags: 0, value: .integer(1)),
- .init(name: "front-auto-focus", length: 4, flags: 0, value: .integer(1)),
- .init(name: "front-auto-hdr", length: 4, flags: 0, value: .integer(1)),
- .init(name: "front-burst", length: 4, flags: 0, value: .integer(1)),
- .init(name: "front-burst-image-duration", length: 4, flags: 0, value: .integer(100)),
- .init(name: "front-flash-capability", length: 4, flags: 0, value: .integer(1)),
- .init(name: "front-hdr", length: 4, flags: 0, value: .integer(1)),
- .init(name: "front-hdr-on", length: 4, flags: 0, value: .integer(1)),
- .init(name: "front-low-light-photo", length: 4, flags: 0, value: .integer(1)),
- .init(name: "front-max-burst-length", length: 4, flags: 0, value: .integer(600)),
- .init(name: "front-max-slomo-video-fps-1080p", length: 4, flags: 0, value: .integer(120)),
- .init(name: "front-max-slomo-video-fps-720p", length: 4, flags: 0, value: .integer(120)),
- .init(name: "front-max-video-fps-1080p", length: 4, flags: 0, value: .integer(60)),
- .init(name: "front-max-video-fps-4k", length: 4, flags: 0, value: .integer(60)),
- .init(name: "front-max-video-fps-720p", length: 4, flags: 0, value: .integer(60)),
- .init(name: "front-max-video-zoom", length: 4, flags: 0, value: .integer(1)),
- .init(name: "front-slowmo", length: 4, flags: 0, value: .integer(1)),
- .init(name: "front-stage-light-portrait", length: 0, flags: 0, value: .bytes(Data())),
- .init(name: "front-variable-frame-rate", length: 4, flags: 0, value: .integer(1)),
- .init(name: "live-effects", length: 4, flags: 0, value: .integer(1)),
- .init(name: "live-photo-auto", length: 4, flags: 0, value: .integer(1)),
- .init(name: "live-photo-capture", length: 4, flags: 0, value: .integer(1)),
- .init(name: "moment-capture", length: 4, flags: 0, value: .integer(1)),
- .init(name: "p3-color-space-video-recording", length: 4, flags: 0, value: .integer(1)),
- .init(name: "panorama", length: 4, flags: 0, value: .integer(1)),
- .init(name: "pearl-camera", length: 4, flags: 0, value: .integer(1)),
- .init(name: "photo-capture-on-touch-down", length: 4, flags: 0, value: .integer(1)),
- .init(name: "photos-live-video-rendering", length: 0, flags: 0, value: .bytes(Data())),
- .init(name: "pipelined-stillimage-capability", length: 4, flags: 0, value: .integer(1)),
- .init(name: "portrait-lighting-strength", length: 4, flags: 0, value: .integer(1)),
- .init(name: "post-effects", length: 4, flags: 0, value: .integer(1)),
- .init(name: "rear-auto-hdr", length: 4, flags: 0, value: .integer(1)),
- .init(name: "rear-burst", length: 4, flags: 0, value: .integer(1)),
- .init(name: "rear-burst-image-duration", length: 4, flags: 0, value: .integer(100)),
- .init(name: "rear-cam-sup-wide-af-capability", length: 4, flags: 0, value: .integer(1)),
- .init(name: "rear-cam-superwide-capability", length: 4, flags: 0, value: .integer(1)),
- .init(name: "rear-hdr", length: 4, flags: 0, value: .integer(1)),
- .init(name: "rear-hdr-on", length: 4, flags: 0, value: .integer(1)),
- .init(name: "rear-low-light-photo", length: 4, flags: 0, value: .integer(1)),
- .init(name: "rear-max-burst-length", length: 4, flags: 0, value: .integer(600)),
- .init(name: "rear-max-slomo-video-fps-1080p", length: 4, flags: 0, value: .integer(240)),
- .init(name: "rear-max-slomo-video-fps-720p", length: 4, flags: 0, value: .integer(240)),
- .init(name: "rear-max-video-fps-1080p", length: 4, flags: 0, value: .integer(60)),
- .init(name: "rear-max-video-fps-4k", length: 4, flags: 0, value: .integer(60)),
- .init(name: "rear-max-video-fps-720p", length: 4, flags: 0, value: .integer(60)),
- .init(name: "rear-max-video-frame_rate", length: 4, flags: 0, value: .integer(60)),
- .init(name: "rear-max-video-zoom", length: 4, flags: 0, value: .integer(3)),
- .init(name: "rear-slowmo", length: 4, flags: 0, value: .integer(1)),
- .init(name: "rear-stage-light-portrait", length: 0, flags: 0, value: .bytes(Data())),
- .init(name: "rear-variable-frame-rate", length: 4, flags: 0, value: .integer(1)),
- .init(name: "spatial-over-capture", length: 4, flags: 0, value: .integer(1)),
- .init(name: "stage-light-portrait-preview", length: 4, flags: 0, value: .integer(1)),
- .init(name: "video-cap", length: 4, flags: 0, value: .integer(2)),
- .init(name: "video-stills", length: 4, flags: 0, value: .integer(1)),
- ],
- patchID: "devicetree.product.camera_node",
- description: "Add /product/camera node with full iPhone17,3 D47AP property set (62 props)"
- ),
-
- // ── /product/facetime (Tier C — front-camera video-call config) ──
- // d47ap carries this 11-property node (excluding AAPL,phandle).
- // FaceTime reads bitrate-{2g,3g,lte,wifi}, decoding/encoding
- // codec parameters, pref-decoding, and tnr-mode-{back,front}
- // (temporal noise reduction) at app launch. Values byte-for-byte
- // from the d47ap DT.
- AddChildNodePatch(
- parentPath: ["device-tree", "product"],
- nodeName: "facetime",
- properties: [
- .init(name: "bitrate-2g", length: 4, flags: 0, value: .integer(100)),
- .init(name: "bitrate-3g", length: 4, flags: 0, value: .integer(228)),
- .init(name: "bitrate-lte", length: 4, flags: 0, value: .integer(228)),
- .init(name: "bitrate-wifi", length: 4, flags: 0, value: .integer(2000)),
- .init(name: "decoding", length: 48, flags: 0, value: .bytes(Data([
- 0x40, 0x01, 0x00, 0x00, 0x0f, 0x00, 0xf0, 0x00,
- 0x40, 0x01, 0x00, 0x00, 0x1e, 0x00, 0xf0, 0x00,
- 0xe0, 0x01, 0x00, 0x00, 0x0f, 0x00, 0x70, 0x01,
- 0xe0, 0x01, 0x00, 0x00, 0x1e, 0x00, 0x70, 0x01,
- 0x80, 0x02, 0x00, 0x00, 0x1e, 0x00, 0xe0, 0x01,
- 0x00, 0x04, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x03,
- ]))),
- .init(name: "encoding", length: 56, flags: 0, value: .bytes(Data([
- 0x40, 0x01, 0x00, 0x00, 0x0f, 0x00, 0xf0, 0x00,
- 0x40, 0x01, 0x00, 0x00, 0x1e, 0x00, 0xf0, 0x00,
- 0xe0, 0x01, 0x00, 0x00, 0x0f, 0x00, 0x70, 0x01,
- 0xe0, 0x01, 0x00, 0x00, 0x1e, 0x00, 0x70, 0x01,
- 0x80, 0x02, 0x00, 0x00, 0x1e, 0x00, 0xe0, 0x01,
- 0x00, 0x04, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x03,
- 0x00, 0x05, 0x00, 0x00, 0x1e, 0x00, 0xd0, 0x02,
- ]))),
- .init(name: "pref-decoding", length: 8, flags: 0, value: .integer(0x0300_001e_0000_0400)),
- .init(name: "tnr-mode-back", length: 4, flags: 0, value: .integer(10)),
- .init(name: "tnr-mode-front", length: 4, flags: 0, value: .integer(10)),
- ],
- patchID: "devicetree.product.facetime_node",
- description: "Add /product/facetime node with full iPhone17,3 D47AP property set (9 props)"
- ),
-
- // ── /product/audio (Tier C — audio + spatial-capture flags) ──
- // d47ap carries this 31-property node (excluding AAPL,phandle).
- // Two camera-joint flags live here: `supports-spatial-audio-capture`
- // and `supports-spatial-facetime` — needed for spatial-video and
- // spatial-photo capture pipelines that combine camera + audio.
- // The remaining 29 properties are pure audio config (mic gains,
- // speaker cpms, voice trigger, channel layout, codec use-case
- // formats). Calibration cstrings (`mic-trim-gains-*`,
- // `speaker-thiele-small-*`, `speaker-trim-gains-*`) keep their
- // syscfg-reference form — replacing them with concrete values
- // from d47 wouldn't make the VM's actual mic/speaker hardware
- // match, but downstream code already handles missing-syscfg
- // gracefully.
- AddChildNodePatch(
- parentPath: ["device-tree", "product"],
- nodeName: "audio",
- properties: [
- .init(name: "acoustic-id", length: 4, flags: 0, value: .integer(8018)),
- .init(name: "actuator-cpms-bgd_100ms", length: 8, flags: 0, value: .integer(0x0000_0eef_0000_01f4)),
- .init(name: "actuator-cpms-bgd_inst", length: 8, flags: 0, value: .integer(0x0000_1db0_0000_06d6)),
- .init(name: "enabledChannels", length: 4, flags: 0, value: .integer(15)),
- .init(name: "historyChannels", length: 4, flags: 0, value: .integer(15)),
- .init(name: "mic-trim-gains-0", length: 12, flags: 0, value: .string("syscfg/MiGH")),
- .init(name: "mic-trim-gains-2", length: 12, flags: 0, value: .string("syscfg/MiGB")),
- .init(name: "mic-trim-gains-key-cnt", length: 4, flags: 0, value: .integer(2)),
- .init(name: "speaker-cpms-bgd_100ms", length: 8, flags: 0, value: .integer(0x0000_2328_0000_04b0)),
- .init(name: "speaker-cpms-bgd_1s", length: 8, flags: 0, value: .integer(0x0000_2328_0000_04b0)),
- .init(name: "speaker-cpms-bgd_inst", length: 8, flags: 0, value: .integer(0x0000_2328_0000_04b0)),
- .init(name: "speaker-thiele-small-0", length: 12, flags: 0, value: .string("syscfg/SpPH")),
- .init(name: "speaker-thiele-small-key-cnt", length: 4, flags: 0, value: .integer(1)),
- .init(name: "speaker-trim-gains-0", length: 12, flags: 0, value: .string("syscfg/SpGH")),
- .init(name: "speaker-trim-gains-key-cnt", length: 4, flags: 0, value: .integer(1)),
- .init(name: "stereo-sound-recording", length: 4, flags: 0, value: .integer(1)),
- .init(name: "supportedChannels", length: 4, flags: 0, value: .integer(15)),
- .init(name: "supports-advanced-vp-chatflavor", length: 4, flags: 0, value: .integer(1)),
- .init(name: "supports-always-listening", length: 4, flags: 0, value: .integer(1)),
- .init(name: "supports-audio-mix", length: 4, flags: 0, value: .integer(1)),
- .init(name: "supports-auto-mic-mode", length: 4, flags: 0, value: .integer(1)),
- .init(name: "supports-barge-in", length: 4, flags: 0, value: .integer(1)),
- .init(name: "supports-concurrent-hp-lp-mics", length: 4, flags: 0, value: .integer(1)),
- .init(name: "supports-mic-modes-telephony", length: 4, flags: 0, value: .integer(1)),
- .init(name: "supports-spatial-audio-capture", length: 4, flags: 0, value: .integer(1)),
- .init(name: "supports-spatial-facetime", length: 4, flags: 0, value: .integer(1)),
- .init(name: "use-case-client-format", length: 96, flags: 0, value: .bytes(Data([
- 0x61, 0x64, 0x6e, 0x73, 0x80, 0xbb, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x69, 0x72, 0x69, 0x73, 0x80, 0x3e, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x73, 0x74, 0x70, 0x6c, 0x80, 0x3e, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- ]))),
- .init(name: "use-case-dsp-in-format", length: 160, flags: 0, value: .bytes(Data([
- 0x64, 0x6b, 0x74, 0x6d, 0x80, 0xbb, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x61, 0x64, 0x6e, 0x73, 0x80, 0xbb, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x64, 0x76, 0x70, 0x73, 0x80, 0xbb, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x69, 0x72, 0x69, 0x73, 0x80, 0x3e, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x73, 0x74, 0x70, 0x6c, 0x80, 0x3e, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- ]))),
- .init(name: "use-case-struct-version", length: 4, flags: 0, value: .integer(1)),
- .init(name: "voiceTriggerChannels", length: 4, flags: 0, value: .integer(1)),
- .init(name: "wireless-splitter", length: 4, flags: 0, value: .integer(1)),
- ],
- patchID: "devicetree.product.audio_node",
- description: "Add /product/audio node with full iPhone17,3 D47AP property set (31 props)"
- ),
-
- // ── /product/iopm (Tier C — always-on technology) ────────────
- // d47ap carries this 2-property node (excluding AAPL,phandle).
- // `aot-mode = 13` enables Always-On Technology — drives wake
- // policy and always-on-display behavior. POTENTIAL DISPLAY
- // RISK: if the VM display can't service the AOT init path,
- // this may need to be reverted in isolation. Test this batch
- // alongside facetime + audio + Tier B; if display breaks,
- // remove this AddChildNodePatch entry first before bisecting
- // the rest.
- AddChildNodePatch(
- parentPath: ["device-tree", "product"],
- nodeName: "iopm",
- properties: [
- .init(name: "aot-linger-time-ms", length: 4, flags: 0, value: .integer(0)),
- .init(name: "aot-mode", length: 4, flags: 0, value: .integer(13)),
- ],
- patchID: "devicetree.product.iopm_node",
- description: "Add /product/iopm node with aot-mode=13 + aot-linger-time-ms=0 (2 props)"
- ),
-
- // ── ISP / SMC camera-flag stubs (Tier F — /arm-io subtree) ──
- // Adds minimal stub nodes carrying ONLY the camera-related
- // properties that libMobileGestalt / SpringBoard / Camera.app
- // userland code walks under `/arm-io/isp`, `/arm-io/ispRtb`,
- // and `/arm-io/smc/iop-smc-nub/smc-ext-charger`.
- //
- // d47ap carries these as full hardware-attach nodes (65/53/14
- // properties). We deliberately do NOT replicate the full set
- // — they describe a real ISP / SMC chip with MMIO regions,
- // interrupts, DART/IOMMU bindings, kext-`compatible` strings
- // etc., and the VM has no such hardware. Stubbing only the
- // camera-* properties + the mandatory `name` (no `compatible`,
- // no `device_type`, no `reg`, no `interrupts`) means:
- //
- // - IOKit registry sees these nodes appear under `/arm-io`.
- // - No kext (`AppleH16CamIn`, AppleSMC, etc.) finds a
- // matching `compatible` and binds, so no driver probe
- // can fail-and-panic on missing hardware.
- // - Userland code that resolves these paths via
- // `IORegistryEntryFromPath` + `IORegistryEntryGetProperty`
- // still finds the camera-* properties on the empty stub.
- //
- // RISK: still untested. If an IOKit walker reports the empty
- // node and a userland daemon (e.g. cameracaptured) takes the
- // node's presence as "real ISP attached" and then crashes
- // trying to talk to it, the symptom is likely a boot stall or
- // a camera-daemon respawn loop visible in logs. Bisect by
- // removing /arm-io/isp + /arm-io/ispRtb first if so.
- //
- // The three nodes are added in dependency order: each parent
- // before its children. The patcher walks `experimentalNodeAdditions`
- // in array order against the in-memory tree, so later entries
- // can resolve parents added by earlier entries.
-
- // /arm-io/smc — empty stub (parent for iop-smc-nub).
- AddChildNodePatch(
- parentPath: ["device-tree", "arm-io"],
- nodeName: "smc",
- properties: [],
- patchID: "devicetree.arm_io.smc_stub",
- description: "Add /arm-io/smc empty stub (parent for smc-ext-charger chain)"
- ),
-
- // /arm-io/smc/iop-smc-nub — empty stub (parent for smc-ext-charger).
- AddChildNodePatch(
- parentPath: ["device-tree", "arm-io", "smc"],
- nodeName: "iop-smc-nub",
- properties: [],
- patchID: "devicetree.arm_io.smc.iop_smc_nub_stub",
- description: "Add /arm-io/smc/iop-smc-nub empty stub (parent for smc-ext-charger)"
- ),
-
- // /arm-io/smc/iop-smc-nub/smc-ext-charger — carries camera-driver.
- AddChildNodePatch(
- parentPath: ["device-tree", "arm-io", "smc", "iop-smc-nub"],
- nodeName: "smc-ext-charger",
- properties: [
- .init(name: "camera-driver", length: 14, flags: 0, value: .string("AppleH16CamIn")),
- ],
- patchID: "devicetree.arm_io.smc.smc_ext_charger_camera_driver",
- description: "Add /arm-io/smc/iop-smc-nub/smc-ext-charger with camera-driver='AppleH16CamIn'"
- ),
-
- // /arm-io/isp — minimal stub carrying camera-front + camera-rear.
- AddChildNodePatch(
- parentPath: ["device-tree", "arm-io"],
- nodeName: "isp",
- properties: [
- .init(name: "camera-front", length: 4, flags: 0, value: .integer(1)),
- .init(name: "camera-rear", length: 4, flags: 0, value: .integer(1)),
- ],
- patchID: "devicetree.arm_io.isp_camera_flags",
- description: "Add /arm-io/isp stub with camera-front=1 + camera-rear=1"
- ),
-
- // /arm-io/ispRtb — minimal stub carrying camera-front + camera-rear.
- AddChildNodePatch(
- parentPath: ["device-tree", "arm-io"],
- nodeName: "ispRtb",
- properties: [
- .init(name: "camera-front", length: 4, flags: 0, value: .integer(1)),
- .init(name: "camera-rear", length: 4, flags: 0, value: .integer(1)),
- ],
- patchID: "devicetree.arm_io.ispRtb_camera_flags",
- description: "Add /arm-io/ispRtb stub with camera-front=1 + camera-rear=1"
- ),
- ]
-
// MARK: - Device Tree Structures
/// A single property in a device tree node.
diff --git a/sources/FirmwarePatcher/DeviceTree/DeviceTreePropertyPatches.swift b/sources/FirmwarePatcher/DeviceTree/DeviceTreePropertyPatches.swift
new file mode 100644
index 00000000..6ec18aa9
--- /dev/null
+++ b/sources/FirmwarePatcher/DeviceTree/DeviceTreePropertyPatches.swift
@@ -0,0 +1,272 @@
+// DeviceTreePropertyPatches.swift — DeviceTree property patch catalogue.
+//
+// The property rewrites `DeviceTreePatcher` applies: the base set every
+// firmware variant receives, and the experimental identity-rewrite set
+// gated behind `includeIdentityPatches` (the `.exp` variant only).
+//
+// Historical note: derived from the legacy Python firmware patcher during the Swift migration.
+
+import Foundation
+
+extension DeviceTreePatcher {
+ /// Multi-string `compatible` blob used by patch #3 (root `compatible`).
+ ///
+ /// Original layout (48 bytes):
+ /// "VPHONE600AP\0" "iPhone99,11\0" "AppleVirtualPlatformARM\0"
+ /// 11 + 1 11 + 1 23 + 1 = 48
+ ///
+ /// Patched layout (48 bytes, surgical change of the middle string only):
+ /// "VPHONE600AP\0" "iPhone17,3\0" "AppleVirtualPlatformARM\0\0"
+ /// 11 + 1 10 + 1 23 + 2 = 48
+ ///
+ /// `VPHONE600AP` stays as the FIRST entry so IOKit's platform-expert
+ /// matching at boot still binds against the kext that claims it. The
+ /// SECOND entry, which userland walks of the compatible list see when
+ /// iterating to enumerate alternate identifiers, is flipped to
+ /// `iPhone17,3`. The trailing `AppleVirtualPlatformARM` shifts one byte
+ /// earlier (now starts at byte 23 instead of 24), but every consumer of
+ /// `compatible` walks by NUL-terminator — none depend on a fixed byte
+ /// offset within the blob — so the shift is harmless.
+ static let compatibleRewrite: Data = {
+ var d = Data()
+ d.append(contentsOf: Array("VPHONE600AP".utf8))
+ d.append(0)
+ d.append(contentsOf: Array("iPhone17,3".utf8))
+ d.append(0)
+ d.append(contentsOf: Array("AppleVirtualPlatformARM".utf8))
+ d.append(0)
+ // 11+1 + 10+1 + 23+1 = 47 bytes so far; pad with one NUL to 48.
+ d.append(0)
+ return d
+ }()
+
+ /// Base device-tree property patches, applied for every variant.
+ /// Matches the pre-experimental set (serial-number, home-button-type,
+ /// artwork-device-subtype, island-notch-location) inherited from
+ /// scripts/dtree.py PATCHES.
+ static let basePropertyPatches: [PropertyPatch] = [
+ PropertyPatch(
+ nodePath: ["device-tree"],
+ property: "serial-number",
+ length: 12,
+ flags: 0,
+ value: .string("vphone-1337"),
+ patchID: "devicetree.serial_number",
+ description: "Set serial number to vphone-1337"
+ ),
+ PropertyPatch(
+ nodePath: ["device-tree", "buttons"],
+ property: "home-button-type",
+ length: 4,
+ flags: 0,
+ value: .integer(2),
+ patchID: "devicetree.home_button_type",
+ description: "Set home button type to 2"
+ ),
+ PropertyPatch(
+ nodePath: ["device-tree", "product"],
+ property: "artwork-device-subtype",
+ length: 4,
+ flags: 0,
+ value: .integer(2556),
+ patchID: "devicetree.artwork_device_subtype",
+ description: "Set artwork device subtype to 2556"
+ ),
+ PropertyPatch(
+ nodePath: ["device-tree", "product"],
+ property: "island-notch-location",
+ length: 4,
+ flags: 0,
+ value: .integer(144),
+ patchID: "devicetree.island_notch_location",
+ description: "Set island notch location to 144"
+ ),
+ ]
+
+ /// Experimental identity-rewrite property patches. Applied only when
+ /// `includeIdentityPatches` is true — currently set only by the `.exp`
+ /// firmware variant. Other variants (regular, dev, jb, less) skip these.
+ ///
+ /// Risk categories:
+ /// - LOW (#3 compatible[1], #11 sub-product-type, #12 unique-model):
+ /// read by userland identity APIs; not in the restore-signed path.
+ /// - HIGHER (#2 target-sub-type, #10 fdr-product-type):
+ /// same family as `target-type` (which broke restore in a prior
+ /// attempt) and FDR-related. If restore fails after a build that
+ /// enables these, remove just those two and retry.
+ /// - MEDIUM (#6 arm-io device_type, #7 arm-io soc-generation):
+ /// IOKit secondary matchers; the real iPhone17,3 DT carries these
+ /// exact values so they match the genuine D47AP.
+ /// - LOW-MEDIUM (#13 gestalt-variants rename): some MG-equivalent
+ /// code may look up the subtree by literal node name.
+ /// Patches for root `model` and root `target-type` are deliberately
+ /// NOT included here — both were tried, both broke restore. They are
+ /// applied post-restore by EXP-JB-6 (`cfw_patch_post_restore_dt.py`)
+ /// in the EXP install pipeline.
+ static let identityPropertyPatches: [PropertyPatch] = [
+ // ── Identity rewrite (Tier 1b) ────────────────────────────────
+ // 5 properties from the 13-entry DT inventory chosen as
+ // userland-facing identity surfaces. NONE of root `model` or root
+ // `target-type` are included — both already proven to break restore.
+
+ // #2 — root `target-sub-type` "VPHONE600AP" -> "D47AP".
+ // RISK: HIGHER. Same family as `target-type`; if restore fails
+ // after enabling this, remove this entry first.
+ PropertyPatch(
+ nodePath: ["device-tree"],
+ property: "target-sub-type",
+ length: 12,
+ flags: 0,
+ value: .string("D47AP"),
+ patchID: "devicetree.target_sub_type",
+ description: "Set target-sub-type to D47AP (was VPHONE600AP)"
+ ),
+
+ // #3 — root `compatible` surgical mangle. Keep VPHONE600AP as first
+ // entry (platform-expert binding intact), rewrite iPhone99,11 (the
+ // secondary entry) to iPhone17,3, keep AppleVirtualPlatformARM as
+ // third entry. See `compatibleRewrite` above for byte layout.
+ // RISK: LOW. Iterators of compatible[] read by userland will pick
+ // up the new identity; the kernel's platform-expert bind still
+ // matches the first entry, so boot is unaffected.
+ PropertyPatch(
+ nodePath: ["device-tree"],
+ property: "compatible",
+ length: 48,
+ flags: 0,
+ value: .bytes(compatibleRewrite),
+ patchID: "devicetree.compatible_secondary",
+ description: "Surgical rewrite of compatible[1]: iPhone99,11 -> iPhone17,3"
+ ),
+
+ // #10 — device-tree/product/fdr-product-type "iPhone99,11" -> "iPhone17,3".
+ // RISK: HIGHER. FDR = Factory Data Restore; some restore-time code
+ // reads this field. If restore breaks, remove this entry.
+ PropertyPatch(
+ nodePath: ["device-tree", "product"],
+ property: "fdr-product-type",
+ length: 12,
+ flags: 0,
+ value: .string("iPhone17,3"),
+ patchID: "devicetree.product.fdr_product_type",
+ description: "Set product/fdr-product-type to iPhone17,3 (was iPhone99,11)"
+ ),
+
+ // #11 — device-tree/product/sub-product-type "iPhone99,11" -> "iPhone17,3".
+ // RISK: LOW. Read by userland classification code; not in
+ // restore-signed path.
+ PropertyPatch(
+ nodePath: ["device-tree", "product"],
+ property: "sub-product-type",
+ length: 12,
+ flags: 0,
+ value: .string("iPhone17,3"),
+ patchID: "devicetree.product.sub_product_type",
+ description: "Set product/sub-product-type to iPhone17,3 (was iPhone99,11)"
+ ),
+
+ // #12 — device-tree/product/unique-model "VPHONE600AP" -> "D47AP".
+ // RISK: LOW. Read by libMobileGestalt and "unique device class"
+ // queries; not in restore-signed path.
+ PropertyPatch(
+ nodePath: ["device-tree", "product"],
+ property: "unique-model",
+ length: 12,
+ flags: 0,
+ value: .string("D47AP"),
+ patchID: "devicetree.product.unique_model",
+ description: "Set product/unique-model to D47AP (was VPHONE600AP)"
+ ),
+
+ // ── Identity rewrite (Tier 1c) ────────────────────────────────
+ // Three more candidates from the inventory that haven't been
+ // empirically shown to break restore. Each may still affect kernel
+ // boot if a kext relies on the specific value.
+
+ // #6 — device-tree/arm-io/device_type "vresearch1-io" -> "t8140-io".
+ // RISK: MEDIUM. device_type is a secondary IOKit matcher; many
+ // kexts only use compatible[] for binding, but some require both.
+ // The actual d47ap DT carries "t8140-io" here, so this is the
+ // genuine iPhone17,3 value (not a fabricated one).
+ PropertyPatch(
+ nodePath: ["device-tree", "arm-io"],
+ property: "device_type",
+ length: 14,
+ flags: 0,
+ value: .string("t8140-io"),
+ patchID: "devicetree.arm_io.device_type",
+ description: "Set arm-io/device_type to t8140-io (was vresearch1-io)"
+ ),
+
+ // #7 — device-tree/arm-io/soc-generation "VResearch1" -> "H17".
+ // RISK: MEDIUM-LOW. soc-generation is typically a capability /
+ // SoC-family descriptor read by kexts to select code paths.
+ // d47ap (iPhone17,3) uses "H17" so we match that exactly.
+ PropertyPatch(
+ nodePath: ["device-tree", "arm-io"],
+ property: "soc-generation",
+ length: 11,
+ flags: 0,
+ value: .string("H17"),
+ patchID: "devicetree.arm_io.soc_generation",
+ description: "Set arm-io/soc-generation to H17 (was VResearch1)"
+ ),
+
+ // #13 — rename node device-tree/product/vphone600-gestalt-variants
+ // to "d47-gestalt-variants" by rewriting its `name` property.
+ // RISK: LOW-MEDIUM. Some libMobileGestalt-equivalent code may look
+ // up the subtree by literal node name. d47 doesn't have a
+ // `*-gestalt-variants` node at all (its product children are
+ // camera/facetime/maps/haptics/audio), so iOS handles missing
+ // gestalt-variants gracefully on real iPhone 17,3 devices anyway.
+ // Renaming should be at-worst-equivalent to that "missing node"
+ // path. The DTNode patcher walks by current name, so the nodePath
+ // here uses the OLD name; the patch rewrites the `name` property
+ // inside that node to the new value.
+ PropertyPatch(
+ nodePath: ["device-tree", "product", "vphone600-gestalt-variants"],
+ property: "name",
+ length: 27,
+ flags: 0,
+ value: .string("d47-gestalt-variants"),
+ patchID: "devicetree.product.gestalt_variants_rename",
+ description: "Rename node vphone600-gestalt-variants -> d47-gestalt-variants"
+ ),
+
+ // ── Camera physical-offset rewrites (Tier B) ──────────────────
+ // vphone600 ships these as 12-byte `'syscfg/fcof'` / `'syscfg/rcof'`
+ // cstring placeholders. d47ap carries 20-byte little-endian
+ // blobs describing the physical mm offset from screen center
+ // for each camera. Consumed by Camera.app / ARKit / FaceTime
+ // for image-centering math. Replacing the placeholder with the
+ // real d47ap blob (length 12 → 20) keeps the consuming code on
+ // a real number rather than reading the literal `'syscfg/...'`
+ // cstring as junk geometry.
+ PropertyPatch(
+ nodePath: ["device-tree", "product"],
+ property: "front-cam-offset-from-center",
+ length: 20,
+ flags: 0,
+ value: .bytes(Data([
+ 0x61, 0x00, 0x01, 0x00, 0x92, 0x1c, 0x00, 0x00,
+ 0xd8, 0x13, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00,
+ ])),
+ patchID: "devicetree.product.front_cam_offset",
+ description: "Set product/front-cam-offset-from-center to d47ap geometry (was syscfg/fcof)"
+ ),
+ PropertyPatch(
+ nodePath: ["device-tree", "product"],
+ property: "rear-cam-offset-from-center",
+ length: 20,
+ flags: 0,
+ value: .bytes(Data([
+ 0xed, 0xa5, 0x00, 0x00, 0xb2, 0x56, 0x00, 0x00,
+ 0x59, 0x08, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00,
+ ])),
+ patchID: "devicetree.product.rear_cam_offset",
+ description: "Set product/rear-cam-offset-from-center to d47ap geometry (was syscfg/rcof)"
+ ),
+ ]
+}
diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcher.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcher.swift
index c26c890b..17f22f6a 100644
--- a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcher.swift
+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcher.swift
@@ -8,33 +8,17 @@
// 4. Create mtree for resulting image
// 5. Generate digest.db and SystemVolume root_hash
// 6. Join mtree and digest.db to Ap,SystemVolumeCanonicalMetadata
+//
+// The supporting steps live beside this file: CryptexFilesystemPatcherGuestPayload.swift,
+// CryptexFilesystemPatcherSealing.swift, CryptexFilesystemPatcherManifest.swift,
+// CryptexFilesystemPatcherAEA.swift, CryptexFilesystemPatcherDiskImage.swift and
+// CryptexFilesystemPatcherProcess.swift.
import Foundation
import CryptoKit
import Img4tool
import VPhoneCore
-enum ProcessError: Error {
- case failed(Int32, String)
- case notExecutable(String)
-}
-
-extension Data {
- init?(fromHexString hex: String) {
- guard hex.count.isMultiple(of: 2) else {
- return nil
- }
-
- let chars = hex.map { $0 }
- let bytes = stride(from: 0, to: chars.count, by: 2)
- .map { String(chars[$0]) + String(chars[$0 + 1]) }
- .compactMap { UInt8($0, radix: 16) }
-
- guard hex.count / bytes.count == 2 else { return nil }
- self.init(bytes)
- }
-}
-
/// Patcher for the Filesystem payload.
public final class CryptexFilesystemPatcher: Patcher {
public let component = "Filesystem"
@@ -44,13 +28,13 @@ public final class CryptexFilesystemPatcher: Patcher {
public let noVphoned: Bool
let vphoneCliDirectory = URL(filePath: "./")
let resources = VPhoneResources.resolve()
-
+
var buildManiest: Data
var rebuiltData: Data?
var tmpDirectories: [URL] = []
-
+
// MARK: - Init
-
+
public init(buildManiest: Data, restoreDir: URL, verbose: Bool = true, noBinpack: Bool = false, noVphoned: Bool = false) {
self.buildManiest = buildManiest
self.restoreDir = restoreDir
@@ -58,15 +42,15 @@ public final class CryptexFilesystemPatcher: Patcher {
self.noBinpack = noBinpack
self.noVphoned = noVphoned
}
-
+
deinit {
for tmp in tmpDirectories {
try? FileManager.default.removeItem(at: tmp)
}
}
-
+
// MARK: - Patcher
-
+
public func findAll() throws -> [PatchRecord] {
return [PatchRecord(
patchID: "filesystem.cryptex.merge",
@@ -77,44 +61,44 @@ public final class CryptexFilesystemPatcher: Patcher {
description: "Merge the cryptex filesystems inside the OS filesystem",
)]
}
-
+
@discardableResult
public func apply() throws -> Int {
print("Merging filesystems…")
let (unencryptedImage, aeaImage) = try mergeFilesystems()
defer { try? FileManager.default.removeItem(at: unencryptedImage) }
-
+
print("Creating trustcache…")
let trustcachePath = try createTrustcache(filesystem: unencryptedImage)
-
+
print("Creating mtree…")
let didEdit = try removeSpecificSystemFiles(filesystem: unencryptedImage)
let mtreePath = try createMtree(filesystem: unencryptedImage)
-
+
print("Creating digest database and root hash…")
let (digestDbPath, rootHashPath) = try createDigestAndHash(filesystem: unencryptedImage, mtree: mtreePath, remap: didEdit)
let metadataPath = try compressCanonicalMetadata(mtree: mtreePath, digestDb: digestDbPath)
let rootHashContainer = try wrapRootHash(rootHashPath)
-
+
// update trustcache, metadata, root_hash path
let updatedManifest = try setUpdatedComponentsInManifest(filesystem: aeaImage, trustcache: trustcachePath, metadata: metadataPath, rootHash: rootHashContainer)
rebuiltData = try serializePayload(updatedManifest)
-
+
return 1
}
-
+
/// Get the patched data.
public var patchedData: Data {
rebuiltData!
}
-
+
// mergeFilesystems merges the main OS filesystem with the Cryptexes filesystems.
// It returns the path of the merged image (plain and encrypted)
func mergeFilesystems() throws -> (URL, URL) {
let osPath = try componentPath("OS")
let osDmgPath = try decryptAeaFile(self.restoreDir.appending(path: osPath))
let newDmgPath = self.restoreDir.appending(path: "new-filesystem.dmg")
-
+
print("- Converting OS image…")
let tmpDir = try createTmpDir()
let targetImagePath = tmpDir.appending(path: "disk.dmg")
@@ -122,28 +106,28 @@ public final class CryptexFilesystemPatcher: Patcher {
try convertToRawImage(input: osDmgPath, output: targetImagePath)
let (targetDevice, targetMount) = try attachImage(path: targetImagePath, forceRW: true)
defer { try? detachImage(deviceNode: targetDevice) }
-
+
print("- Merging App OS cryptex…")
try copyCryptex(targetMount: targetMount, appOS: true)
print("- Merging System OS cryptex…")
try copyCryptex(targetMount: targetMount, systemOS: true)
-
+
print("- Fixing dyld cache…")
try addDyldSymlinks(targetMount: targetMount)
-
+
let cfwInputOgPath = resources.resourceArchivesDir.appendingPathComponent("cfw_input.tar.zst")
let cfwInputPath = try createTmpDir()
_ = try runProcess("/usr/bin/tar", [
"--zstd", "-xf", cfwInputOgPath.path, "-C", cfwInputPath.path
])
-
+
print("- Fixing GPU driver…")
try addGpuDriver(targetMount: targetMount, cfwInput: cfwInputPath)
-
+
print("- Patching mobile activation…")
try patchMobileActivation(targetMount: targetMount, cfwInput: cfwInputPath)
-
+
if !noVphoned {
print("- Adding vphoned…")
try addVphoned(targetMount: targetMount, cfwInput: cfwInputPath)
@@ -157,7 +141,7 @@ public final class CryptexFilesystemPatcher: Patcher {
try patchLaunchdCacheLoader(targetMount: targetMount, cfwInput: cfwInputPath)
}
}
-
+
print("- Finalizing merged image…")
try shrinkImage(dmg: targetImagePath)
try convertToUDRWImage(input: targetImagePath, output: newDmgPath)
@@ -172,391 +156,12 @@ public final class CryptexFilesystemPatcher: Patcher {
try FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: finalDestination.path)
return (newDmgPath, finalDestination)
}
-
- func patchLaunchdCacheLoader(targetMount: String, cfwInput: URL) throws {
- let target = URL.init(filePath: targetMount)
- let launchdCacheLoaderPath = target.appending(path: "/usr/libexec/launchd_cache_loader")
- let pythonPath = try resources.pythonExecutable()
- let patcherPath = resources.cfwPy
- _ = try runProcess(pythonPath.path, [
- patcherPath.path, "patch-launchd-cache-loader",
- launchdCacheLoaderPath.path
- ])
- _ = try runProcess("/bin/chmod", ["0755", launchdCacheLoaderPath.path])
-
- let signingCertificatePath = cfwInput.appending(path: "cfw_input/signcert.p12")
- _ = try runProcess("/opt/homebrew/bin/ldid", [
- "-S", "-M", "-K\(signingCertificatePath.path)",
- "-Icom.apple.launchd_cache_loader",
- launchdCacheLoaderPath.path
- ])
- }
-
- func injectLaunchDaemons(targetMount: String, cfwInput: URL, vphoned: Bool = true, cfw: Bool = true) throws {
- let target = URL.init(filePath: targetMount)
- let scriptDir = resources.scriptsDir
-
- let tmpDir = try createTmpDir()
- let launchdPath = tmpDir.appending(path: "launchd.plist")
- let launchDaemonsPath = tmpDir.appending(path: "launchDaemons")
- let launchdOgPath = target.appending(path: "/System/Library/xpc/launchd.plist")
- try FileManager.default.createDirectory(at: launchDaemonsPath, withIntermediateDirectories: false)
- try FileManager.default.moveItem(at: launchdOgPath, to: launchdPath)
-
- if vphoned {
- let vphonedSrc = scriptDir.appendingPathComponent("vphoned")
- let vphonedLaunchdPlist = vphonedSrc.appending(path: "vphoned.plist")
- try FileManager.default.copyItem(at: vphonedLaunchdPlist,
- to: target.appending(path: "System/Library/LaunchDaemons/vphoned.plist"))
- try FileManager.default.copyItem(at: vphonedLaunchdPlist, to: launchDaemonsPath.appending(path: vphonedLaunchdPlist.lastPathComponent))
- }
- if cfw {
- let launchDaemonsDir = cfwInput.appending(path: "cfw_input/jb/LaunchDaemons")
- let launchDaemons = try FileManager.default.contentsOfDirectory(atPath: launchDaemonsDir.path)
- for filename in launchDaemons {
- let launchDaemonUrl = launchDaemonsDir.appending(component: filename)
- let filename = launchDaemonUrl.lastPathComponent
- let fsTarget = target.appending(path: "System/Library/LaunchDaemons/\(filename)")
- try FileManager.default.copyItem(at: launchDaemonUrl, to: fsTarget)
- try FileManager.default.copyItem(at: launchDaemonUrl, to: launchDaemonsPath.appending(path: filename))
- }
- }
-
- let pythonPath = try resources.pythonExecutable()
- _ = try runProcess(pythonPath.path, [
- resources.cfwPy.path, "inject-daemons",
- launchdPath.path, launchDaemonsPath.path
- ])
- try FileManager.default.moveItem(at: launchdPath, to: launchdOgPath)
- _ = try runProcess("/bin/chmod", ["0644", launchdOgPath.path])
- }
-
- func addExtraServices(targetMount: String, cfwInput: URL) throws {
- _ = try runProcess("/usr/bin/tar", [
- "--preserve-permissions",
- "-xf", cfwInput.appending(path: "cfw_input/jb/iosbinpack64.tar").path,
- "-C", targetMount
- ])
- }
-
- func addVphoned(targetMount: String, cfwInput: URL) throws {
- let target = URL.init(filePath: targetMount)
- let scriptDir = resources.scriptsDir
- let vphonedSrc = scriptDir.appendingPathComponent("vphoned")
- // vphonedSrc (bundled source) is read-only inside a packaged .app, so the
- // compiled binary must land in a writable temp dir, not next to the source.
- let buildDir = try createTmpDir()
- let vphonedBin = buildDir.appendingPathComponent("vphoned")
-
- try buildVphoned(vphonedSrc: vphonedSrc, vphonedBin: vphonedBin)
- defer { try? FileManager.default.removeItem(at: vphonedBin) }
-
- // Sign
- let targetBin = target.appending(path: "/usr/bin/vphoned")
- try FileManager.default.copyItem(at: vphonedBin, to: targetBin)
- let signingCertificatePath = cfwInput.appending(path: "cfw_input/signcert.p12")
- _ = try runProcess("/opt/homebrew/bin/ldid", [
- "-S\(vphonedSrc.appendingPathComponent("entitlements.plist").path)",
- "-M", "-K\(signingCertificatePath.path)",
- targetBin.path
- ])
- _ = try runProcess("/bin/chmod", ["0755", targetBin.path])
- }
-
- func buildVphoned(vphonedSrc: URL, vphonedBin: URL) throws {
- let srcURLs = try FileManager.default.contentsOfDirectory(
- at: vphonedSrc,
- includingPropertiesForKeys: [.contentModificationDateKey],
- options: [.skipsHiddenFiles]
- ).filter { $0.pathExtension == "m" }
-
- var args = [
- "-sdk", "iphoneos", "clang",
- "-arch", "arm64",
- "-Os",
- "-fobjc-arc",
- "-I\(vphonedSrc.path)",
- "-I\(vphonedSrc.appendingPathComponent("vendor/libarchive").path)",
- "-DLESS=1",
- "-o", vphonedBin.path
- ]
- args.append(contentsOf: srcURLs.map { $0.path })
- args.append(contentsOf: [
- "-larchive",
- "-lsqlite3",
- "-framework", "Foundation",
- "-framework", "Security",
- "-framework", "CoreServices"
- ])
-
- _ = try runProcess("/usr/bin/xcrun", args)
- }
-
- func addGpuDriver(targetMount: String, cfwInput: URL) throws {
- let target = URL.init(filePath: targetMount)
-
- let gpuTarPath = cfwInput.appending(path: "cfw_input/custom/AppleParavirtGPUMetalIOGPUFamily.tar")
- _ = try runProcess("/usr/bin/tar", [
- "--preserve-permissions",
- "-xf", gpuTarPath.path,
- "-C", target.path
- ])
-
- let bundle = target.appending(path: "/System/Library/Extensions/AppleParavirtGPUMetalIOGPUFamily.bundle")
- // Clean macOS resource fork files (._* files from tar xattrs)
- _ = try? runProcess("/usr/bin/find", [bundle.path, "-name", "._*", "-delete"])
- _ = try runProcess("/usr/sbin/chown", ["-R", "0:0", bundle.path])
- for path in [
- bundle.path,
- bundle.appending(path: "/libAppleParavirtCompilerPluginIOGPUFamily.dylib").path,
- bundle.appending(path: "/AppleParavirtGPUMetalIOGPUFamily").path,
- bundle.appending(path: "/_CodeSignature").path,
- ] {
- _ = try runProcess("/bin/chmod", ["0755", path])
- }
- for path in [
- bundle.appending(path: "/_CodeSignature/CodeResources").path,
- bundle.appending(path: "/Info.plist").path
- ] {
- _ = try runProcess("/bin/chmod", ["0644", path])
- }
- }
-
- func patchMobileActivation(targetMount: String, cfwInput: URL) throws {
- let target = URL.init(filePath: targetMount)
- let mobileActivationdPath = target.appending(path: "/usr/libexec/mobileactivationd")
- let pythonPath = try resources.pythonExecutable()
- _ = try runProcess(pythonPath.path, [
- resources.cfwPy.path, "patch-mobileactivationd",
- mobileActivationdPath.path
- ])
- _ = try runProcess("/bin/chmod", ["0755", mobileActivationdPath.path])
-
- let signingCertificatePath = cfwInput.appending(path: "cfw_input/signcert.p12")
- _ = try runProcess("/opt/homebrew/bin/ldid", [
- "-S", "-M", "-K\(signingCertificatePath.path)",
- mobileActivationdPath.path
- ])
- }
-
- func addDyldSymlinks(targetMount: String) throws {
- let target = URL.init(filePath: targetMount)
- _ = try runProcess("/bin/ln", [
- "-sf", "../../../System/Cryptexes/OS/System/Library/Caches/com.apple.dyld",
- target.appending(path: "/System/Library/Caches/com.apple.dyld").path
- ])
- _ = try runProcess("/bin/ln", [
- "-sf", "../../../../System/Cryptexes/OS/System/DriverKit/System/Library/dyld",
- target.appending(path: "/System/DriverKit/System/Library/dyld").path
- ])
- }
-
- func wrapRootHash(_ rootHashPath: URL) throws -> URL {
- let tmpDir = try createTmpDir()
- let im4pPath = tmpDir.appending(path: "metadata.root_hash")
- _ = try runProcess("/opt/homebrew/bin/ipsw", [
- "img4", "im4p", "create",
- "--type", "isys", "--version", "0",
- "-o", im4pPath.path,
- rootHashPath.path
- ])
- return im4pPath
- }
-
- func wrapTrustcache(_ trustcache: URL) throws -> URL {
- let tmpDir = try createTmpDir()
- let im4pPath = tmpDir.appending(path: "new.filesystem")
- _ = try runProcess("/opt/homebrew/bin/ipsw", [
- "img4", "im4p", "create",
- "--type", "trst", "--version", "1",
- "-o", im4pPath.path,
- trustcache.path
- ])
- return im4pPath
- }
-
- func compressCanonicalMetadata(mtree: URL, digestDb: URL) throws -> URL {
- let tmpDir = try createTmpDir()
- let targetMtree = tmpDir.appending(path: mtree.lastPathComponent)
- try FileManager.default.copyItem(at: mtree, to: targetMtree)
- let targetDigestDb = tmpDir.appending(path: digestDb.lastPathComponent)
- try FileManager.default.copyItem(at: digestDb, to: targetDigestDb)
-
- let archivePath = tmpDir.appending(path: "payload.aar")
- _ = try runProcess("/usr/bin/aa", [
- "archive",
- "-d", tmpDir.path,
- "-o", archivePath.path
- ])
-
- let im4pPath = tmpDir.appending(path: "metadata.mtree")
- _ = try runProcess("/opt/homebrew/bin/ipsw", [
- "img4", "im4p", "create",
- "--type", "msys", "--version", "0",
- "-o", im4pPath.path,
- archivePath.path
- ])
- return im4pPath
- }
-
- private func identifyApfsSealvolume() throws -> URL {
- let iosVersion = try getProductVersion()
- // VPHONE_SEAL_DIR (set by the CLI's `fw prepare`/`fw patch`) must agree with
- // wherever fw_prepare.sh's download_apfs_sealvolume() wrote the file; unset
- // (dev Makefile flow) falls back to the historical repo-relative `.tools/`.
- let sealDir = ProcessInfo.processInfo.environment["VPHONE_SEAL_DIR"].map { URL(fileURLWithPath: $0) }
- ?? self.vphoneCliDirectory.appending(path: ".tools")
- let path = sealDir.appendingPathComponent("apfs_sealvolume_\(iosVersion)")
- guard FileManager.default.fileExists(atPath: path.path) else {
- throw FirmwareManifest.ManifestError.fileNotFound(path.path)
- }
- guard FileManager.default.isExecutableFile(atPath: path.path) else {
- throw ProcessError.notExecutable(path.path)
- }
- return path
- }
-
- func createDigestAndHash(filesystem: URL, mtree: URL, remap: Bool) throws -> (URL, URL) {
- let (device, mount) = try attachImage(path: filesystem)
- defer { try? detachImage(deviceNode: device) }
-
- let tmpDir = try createTmpDir()
- let digestDbPath = tmpDir.appending(path: "digest.db")
- let rootHashPath = tmpDir.appending(path: "root_hash")
- let mtreeRemapPath = tmpDir.appending(path: "mtree_remap.xml")
- let sealLogPath = tmpDir.appending(path: "seal.log")
-
- // We want to get the nanosecond timestamp of the last modification before the mtree collection.
- // We know that we remove directories in /private/var in removeSpecificSystemFiles last.
- // Therefore, we parse the modification time of /private/var.
- let modificationTime = try parsePrivateVarTime(mtree: mtree)
- let remapContent = """
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
- <plist version="1.0">
- <dict>
- \(remap ? """
- <key>MODIFICATION</key>
- <integer>\(modificationTime)</integer>
- """ : "")
- </dict>
- </plist>
- """
- print("Modification time: \(remap ? modificationTime : "none")")
- FileManager.default.createFile(atPath: mtreeRemapPath.path, contents: remapContent.data(using: .utf8))
-
- try unmount(mount: mount)
- let sealvolume = try identifyApfsSealvolume()
- FileManager.default.createFile(atPath: sealLogPath.path, contents: nil)
- _ = try runProcess(sealvolume.path, [
- "-R", mtreeRemapPath.path,
- "-U", digestDbPath.path, // Save digest records
- "-M", rootHashPath.path, // Save root hash
- device
- ], output: sealLogPath)
- return (digestDbPath, rootHashPath)
- }
-
- func parsePrivateVarTime(mtree: URL) throws -> String {
- guard let mtreeData = FileManager.default.contents(atPath: mtree.path),
- let text = String(data: mtreeData, encoding: .utf8) else {
- throw FirmwareManifest.ManifestError.fileNotFound(mtree.path)
- }
- let lines = text.split(whereSeparator: \.isNewline).map(String.init)
-
- // Find the section header for /private/var
- guard let sectionIndex = lines.firstIndex(of: "# ./private/var") else {
- throw FirmwareManifest.ManifestError.fileNotFound("/private/var")
- }
-
- // Look at the lines after that header until the next section header
- for line in lines[(sectionIndex + 1)...] {
- // Stop if we hit the next section
- if line.hasPrefix("# ./") {
- break
- }
-
- // The metadata line for /private/var starts with "var "
- guard line.hasPrefix("var ") else { continue }
-
- // Extract time=...
- guard let match = line.range(of: #"time=([0-9]+(?:\.[0-9]+)?)"#,
- options: .regularExpression) else {
- throw FirmwareManifest.ManifestError.fileNotFound("modification time for /private/var in \(mtree.path)")
- }
-
- let matchedText = String(line[match])
- return matchedText
- .replacingOccurrences(of: "time=", with: "")
- .replacingOccurrences(of: ".", with: "")
- }
-
- throw FirmwareManifest.ManifestError.fileNotFound("the /private/var entry in \(mtree.path)")
- }
-
- func createMtree(filesystem: URL) throws -> URL {
- let (device, mount) = try attachImage(path: filesystem, readonly: true)
- defer { try? detachImage(deviceNode: device) }
-
- let tmpDir = try createTmpDir()
- let mtreeFile = tmpDir.appending(path: "mtree.txt")
- FileManager.default.createFile(atPath: mtreeFile.path, contents: nil)
- _ = try runProcess("/usr/sbin/mtree", [
- "-c",
- "-p", mount,
- ], output: mtreeFile)
- return mtreeFile
- }
-
- func removeSpecificSystemFiles(filesystem: URL) throws -> Bool {
- let (device, mount) = try attachImage(path: filesystem, forceRW: true)
- defer { try? detachImage(deviceNode: device) }
-
- let removedPaths = [
- "/private/var/MobileAsset/PreinstalledAssets",
- "/private/var/MobileAsset/PreinstalledAssetsV2",
- "/private/var/staged_system_apps",
- ]
- var didEdit = false
- for path in removedPaths {
- if FileManager.default.fileExists(atPath: mount.appending(path)) {
- try FileManager.default.removeItem(atPath: mount.appending(path))
- didEdit = true
- }
- }
- return didEdit
- }
-
- func createTrustcache(filesystem: URL) throws -> URL {
- let (device, mount) = try attachImage(path: filesystem, readonly: true)
- defer { try? detachImage(deviceNode: device) }
-
- let oldTrustcache = try componentPath("StaticTrustCache")
- let oldTrustcachePath = self.restoreDir.appending(path: oldTrustcache)
- let newTrustcachePath = self.restoreDir.appending(path: "Firmware/new.trustcache")
- let tmpDir = try createTmpDir()
-
- let tcContainer = tmpDir.appending(path: "new.trustcache")
- _ = try runProcess("/System/Library/SecurityResearch/usr/bin/cryptexctl", [
- "generate-trust-cache", "--type", "static",
- "--base-trust-cache", oldTrustcachePath.path,
- "--output-file", tcContainer.path,
- mount
- ])
-
- if FileManager.default.fileExists(atPath: newTrustcachePath.path) {
- try FileManager.default.removeItem(at: newTrustcachePath)
- }
- try FileManager.default.moveItem(at: tcContainer, to: newTrustcachePath)
- return newTrustcachePath
- }
-
func copyCryptex(targetMount: String, appOS: Bool = false, systemOS: Bool = false) throws {
guard (appOS || systemOS) && !(appOS && systemOS) else {
throw FirmwarePatcher.PatcherError.patchVerificationFailed("Can patch only one at a time")
}
-
+
let osPath = if appOS {
self.restoreDir.appending(path: try componentPath("Cryptex1,AppOS"))
} else {
@@ -564,137 +169,13 @@ public final class CryptexFilesystemPatcher: Patcher {
}
let (osDevice, osMount) = try attachImage(path: osPath, readonly: true)
defer { try? detachImage(deviceNode: osDevice) }
-
+
let destination = URL.init(filePath: targetMount).appending(path: appOS ? "/System/Cryptexes/App" : "/System/Cryptexes/OS")
try FileManager.default.removeItem(at: destination)
try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: false)
try copyImageContents(source: URL.init(filePath: osMount), destination: destination)
}
-
- func serializePayload(_ buildManifest: PlistDict) throws -> Data {
- return try PropertyListSerialization.data(
- fromPropertyList: buildManifest,
- format: .xml,
- options: 0
- )
- }
-
- func setUpdatedComponentsInManifest(filesystem: URL, trustcache: URL, metadata: URL, rootHash: URL) throws -> PlistDict {
- var root = try parsePlist(data: buildManiest)
- guard var buildIdentities = root["BuildIdentities"] as? [Any],
- buildIdentities.count > 0,
- var buildIdentity = buildIdentities.first! as? PlistDict else {
- throw FirmwareManifest.ManifestError.missingKey("Component in BuildManifest")
- }
- var identityManifest = try getChildPlistDict(parent: buildIdentity, key: "Manifest")
-
- // We assume that the filesystem is already placed in the restore directory.
- identityManifest = try updateManifestComponentPath(identityManifest: identityManifest, component: "OS", at: filesystem)
-
- let newTrustcachePath = self.restoreDir.appending(path: "Firmware").appending(path: trustcache.lastPathComponent)
- if trustcache != newTrustcachePath && FileManager.default.fileExists(atPath: newTrustcachePath.path) {
- try FileManager.default.removeItem(at: newTrustcachePath)
- }
- try FileManager.default.moveItem(at: trustcache, to: newTrustcachePath)
- identityManifest = try updateManifestComponentPath(identityManifest: identityManifest, component: "StaticTrustCache", at: newTrustcachePath)
-
- let newMetadataPath = self.restoreDir.appending(path: "Firmware").appending(path: metadata.lastPathComponent)
- if metadata != newMetadataPath && FileManager.default.fileExists(atPath: newMetadataPath.path) {
- try FileManager.default.removeItem(at: newMetadataPath)
- }
- try FileManager.default.moveItem(at: metadata, to: newMetadataPath)
- identityManifest = try updateManifestComponentPath(identityManifest: identityManifest, component: "Ap,SystemVolumeCanonicalMetadata", at: newMetadataPath)
-
- let newRootHashPath = self.restoreDir.appending(path: "Firmware").appending(path: rootHash.lastPathComponent)
- if rootHash != newRootHashPath && FileManager.default.fileExists(atPath: newRootHashPath.path) {
- try FileManager.default.removeItem(at: newRootHashPath)
- }
- try FileManager.default.moveItem(at: rootHash, to: newRootHashPath)
- identityManifest = try updateManifestComponentPath(identityManifest: identityManifest, component: "SystemVolume", at: newRootHashPath)
-
- buildIdentity["Manifest"] = identityManifest
- buildIdentities[0] = buildIdentity
- root["BuildIdentities"] = buildIdentities
- return root
- }
-
- func updateManifestComponentPath(identityManifest: PlistDict, component: String, at: URL) throws -> PlistDict {
- var identityManifest = identityManifest
- let pathSuffix = relativePath(from: at, base: self.restoreDir.appendingPathComponent("", isDirectory: true))
- var comp = try getChildPlistDict(parent: identityManifest, key: component)
- var info = try getChildPlistDict(parent: comp, key: "Info")
- info["Path"] = pathSuffix
- comp["Info"] = info
- identityManifest[component] = comp
- return identityManifest
- }
-
- func relativePath(from child: URL, base: URL) -> String? {
- let basePath = base.standardizedFileURL.pathComponents
- let childPath = child.standardizedFileURL.pathComponents
-
- guard childPath.starts(with: basePath) else { return nil }
- let remaining = childPath.dropFirst(basePath.count)
- return remaining.joined(separator: "/")
- }
-
- func getProductVersion() throws -> String {
- let root = try parsePlist(data: buildManiest)
- guard let productVersion = root["ProductVersion"] as? String else {
- throw FirmwareManifest.ManifestError.missingKey("ProductVersion in BuildManifest")
- }
- return productVersion
- }
-
- func componentPath(_ component: String) throws -> String {
- let path = self.restoreDir.appending(path: "iPhone-BuildManifest.plist")
- let manifest = try getBuildIdentityManifest(path: path)
- return try getComponentPath(component: component, buildManifest: manifest)
- }
-
- func getComponentPath(component: String, buildManifest: PlistDict) throws -> String {
- let comp = try getChildPlistDict(parent: buildManifest, key: component)
- let info = try getChildPlistDict(parent: comp, key: "Info")
- guard let path = info["Path"] as? String else {
- throw FirmwareManifest.ManifestError.missingKey("component path")
- }
- return path
- }
-
- func getBuildIdentityManifest(path: URL) throws -> PlistDict {
- let data = try Data.init(contentsOf: path)
- return try getBuildIdentityManifest(data: data)
- }
-
- func getBuildIdentityManifest(data: Data) throws -> PlistDict {
- let buildManifest = try parsePlist(data: data)
- guard let buildIdentities = buildManifest["BuildIdentities"] as? [Any],
- buildIdentities.count > 0,
- let buildIdentity = buildIdentities.first! as? PlistDict else {
- throw FirmwareManifest.ManifestError.missingKey("Component in BuildManifest")
- }
- return try getChildPlistDict(parent: buildIdentity, key: "Manifest")
- }
-
- func parsePlist(data: Data) throws -> PlistDict {
- guard let buildManifest = try PropertyListSerialization.propertyList(
- from: data,
- options: [],
- format: nil
- ) as? PlistDict else {
- throw FirmwareManifest.ManifestError.invalidPlist("")
- }
- return buildManifest
- }
-
- func getChildPlistDict(parent: PlistDict, key: String) throws -> PlistDict {
- guard let value = parent[key] as? PlistDict else {
- throw FirmwareManifest.ManifestError.missingKey(key)
- }
- return value
- }
-
func createTmpDir() throws -> URL {
let tmpDir = FileManager.default.temporaryDirectory
.appending(path: "vphone-\(UUID.init().uuidString)")
@@ -702,307 +183,4 @@ public final class CryptexFilesystemPatcher: Patcher {
self.tmpDirectories.append(tmpDir)
return tmpDir
}
-
- func copyImageContents(source: URL, destination: URL) throws {
- // Copy everything from source volume root into destination volume root.
- let sourceRoot = source.appendingPathComponent("", isDirectory: true)
- let sourcePath = sourceRoot.path
- let destinationRoot = destination.appendingPathComponent("", isDirectory: true)
-
- // We delete the files first as we want to replace symlinks with actual files.
- let keys: [URLResourceKey] = [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey]
- guard let enumerator = FileManager.default.enumerator(at: sourceRoot, includingPropertiesForKeys: keys) else {
- throw FirmwareManifest.ManifestError.fileNotFound(
- "Unable to read \(sourceRoot.path). Check that the image is still mounted, then try again."
- )
- }
- for case let fileURL as URL in enumerator {
- guard fileURL.path.hasPrefix(sourcePath) else { continue }
-
- let values = try fileURL.resourceValues(forKeys: Set(keys))
- var suffix = String(fileURL.path.dropFirst(sourcePath.count))
- if suffix.hasPrefix("/") {
- suffix.removeFirst()
- }
-
- let destinationPath = destinationRoot.appendingPathComponent(suffix)
- guard let ok = try? destinationPath.checkResourceIsReachable(), ok else {
- // try FileManager.default.copyItem(at: fileURL, to: destinationPath)
- let result = copyfile(fileURL.path, destinationPath.path, nil, copyfile_flags_t(COPYFILE_SECURITY | COPYFILE_DATA))
- if result < 0 {
- print("Unable to copy \(destinationPath.path). Check permissions and free space, then try again.")
- }
- continue
- }
-
- let vals = try destinationPath.resourceValues(forKeys: Set(keys))
- if values.isDirectory != vals.isDirectory ||
- values.isRegularFile != vals.isRegularFile ||
- values.isSymbolicLink != vals.isSymbolicLink {
- try FileManager.default.removeItem(at: destinationPath)
- // try FileManager.default.copyItem(at: fileURL, to: destinationPath)
- let result = copyfile(fileURL.path, destinationPath.path, nil, copyfile_flags_t(COPYFILE_SECURITY | COPYFILE_DATA))
- if result < 0 {
- print("Unable to copy \(destinationPath.path). Check permissions and free space, then try again.")
- }
- }
- }
- }
-
- func getAeaKey(_ path: URL, metadata: [String: String]) throws -> String {
- if let key = metadata["encryption_key"] {
- let key = String(key.dropFirst(4))
- if let unwrapped = Data(fromHexString: key),
- let encoded = String(data: unwrapped, encoding: .utf8),
- let data = Data(fromHexString: encoded) {
- return "base64:\(data.base64EncodedString())"
- }
- return key
- }
-
- return try runProcess("/opt/homebrew/bin/ipsw", [
- "fw", "aea",
- "--no-color",
- "--key",
- path.path,
- ]).trimmingCharacters(in: ["\n"])
- }
-
- func encryptAeaFile(_ path: URL, output: URL, key: String, metadata: [String: String]) throws {
- var arguments = [
- "encrypt", "-i", path.path, "-o", output.path,
- "-profile", "1", "-key-value", key,
- ]
- for (metaKey, metaValue) in metadata {
- arguments.append("-auth-data-key")
- arguments.append(metaKey)
- arguments.append("-auth-data-value")
- arguments.append(metaValue)
- }
- _ = try runProcess("/usr/bin/aea", arguments)
- }
-
- func decryptAeaFile(_ path: URL) throws -> URL {
- let tmpDir = try createTmpDir()
- let outputPath = tmpDir.appending(path: path.appendingPathExtension("dmg").lastPathComponent)
- _ = try runProcess("/opt/homebrew/bin/ipsw", [
- "fw", "aea",
- "-o", outputPath.path,
- path.path,
- ])
- return outputPath.appending(path: path.lastPathComponent.dropLast(4))
- }
-
- func getAeaMetadata(_ path: URL) throws -> [String: String] {
- let output = try runProcess("/opt/homebrew/bin/ipsw", [
- "fw", "aea",
- "--no-color",
- "--info",
- path.path,
- ])
- let lines = output.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline).map(String.init)
-
- var result: [String: String] = [:]
- var currentKey: String?
- var bodyLines: [String] = []
-
- func flushCurrentSection() {
- guard let key = currentKey else { return }
- result[key] = parseSectionBody(bodyLines)
- }
-
- for rawLine in lines {
- let trimmed = rawLine.trimmingCharacters(in: .whitespaces)
-
- if let key = parseSectionHeader(trimmed) {
- flushCurrentSection()
- currentKey = key
- bodyLines = []
- } else {
- // Ignore banner lines before the first section
- if currentKey != nil {
- bodyLines.append(rawLine)
- }
- }
- }
-
- flushCurrentSection()
- return result
- }
-
- private func parseSectionHeader(_ line: String) -> String? {
- // Matches both:
- // [com.apple.wkms.url]:
- // [saksKey]:
- guard line.hasPrefix("[") else { return nil }
- guard let end = line.firstIndex(of: "]") else { return nil }
-
- let key = String(line[line.index(after: line.startIndex)..<end])
- return key.isEmpty ? nil : key
- }
-
- private func parseSectionBody(_ bodyLines: [String]) -> String {
- let nonEmpty = bodyLines.filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty }
-
- // If the section contains hex dump lines, parse and concatenate them.
- let hexBytes = nonEmpty.flatMap { parseHexDumpLine($0) }
- if !hexBytes.isEmpty {
- let b64Encoded = Data(hexBytes).base64EncodedString()
- return "hex:\(Data(b64Encoded.utf8).hex)"
- }
-
- // Otherwise treat it as plain text / JSON / whatever the section contains.
- let text = bodyLines.joined(separator: "\n")
- .trimmingCharacters(in: .whitespacesAndNewlines)
-
- return "hex:\(Data(text.utf8).hex)"
- }
-
- private func parseHexDumpLine(_ line: String) -> [UInt8] {
- // Example:
- // 0000000000000000: 0a 8d 03 0a 2f c7 ... |....|
- guard let colonIndex = line.firstIndex(of: ":") else { return [] }
-
- let afterColon = line[line.index(after: colonIndex)...]
- let beforeAscii = afterColon.split(separator: "|", maxSplits: 1, omittingEmptySubsequences: false).first ?? afterColon
-
- let tokens = beforeAscii.split(whereSeparator: \.isWhitespace)
- var bytes: [UInt8] = []
- bytes.reserveCapacity(tokens.count)
-
- for token in tokens {
- guard token.count == 2, let b = UInt8(token, radix: 16) else {
- return [] // not a hexdump line
- }
- bytes.append(b)
- }
-
- return bytes
- }
-
- func convertToRawImage(input: URL, output: URL) throws {
- _ = try runProcess("/usr/sbin/diskutil", [
- "image", "create", "from",
- "--format", "RAW", input.path,
- output.path
- ])
-
- // Resize to max
- let maxsize = try runProcess("/bin/sh", [
- "-c", "diskutil image resize --plist \"\(output.path)\" | plutil -extract max raw -o - -"
- ]).trimmingCharacters(in: ["\n"])
- _ = try runProcess("/usr/sbin/diskutil", [
- "image", "resize", "--size", maxsize, output.path
- ])
- }
-
- func convertToUDRWImage(input: URL, output: URL) throws {
- if FileManager.default.fileExists(atPath: output.path) {
- try FileManager.default.removeItem(at: output)
- }
- _ = try runProcess("/usr/bin/hdiutil", [
- "convert",
- input.path,
- "-format", "UDRW",
- "-o", output.path
- ])
- }
-
- func shrinkImage(dmg: URL) throws {
- _ = try runProcess("/usr/sbin/diskutil", [
- "image",
- "resize",
- "--size", "min",
- dmg.path
- ])
- }
-
- func unmount(mount: String) throws {
- _ = try runProcess("/usr/sbin/diskutil", ["unmount", mount])
- }
-
- // attachImage returns the device and mount point
- func attachImage(path: URL, readonly: Bool = false, forceRW: Bool = false) throws -> (String, String) {
- let process = Process()
- process.executableURL = URL(fileURLWithPath: "/usr/bin/hdiutil")
- process.arguments = if readonly {[
- "attach",
- "-readonly",
- "-plist",
- path.path,
- ]} else {[
- "attach",
- "-plist",
- path.path,
- ]}
-
- let pipe = Pipe()
- process.standardOutput = pipe
- process.standardError = pipe
-
- try process.run()
- process.waitUntilExit()
-
- let data = pipe.fileHandleForReading.readDataToEndOfFile()
- guard process.terminationStatus == 0 else {
- let output = String(data: data, encoding: .utf8) ?? ""
- throw ProcessError.failed(process.terminationStatus, output)
- }
-
- let root = try parsePlist(data: data)
- guard let entries = root["system-entities"] as? [Any] else {
- throw FirmwareManifest.ManifestError.missingKey("system-entities")
- }
- for entry in entries {
- guard let entry = entry as? PlistDict,
- let volumeKind = entry["volume-kind"] as? String,
- volumeKind == "apfs" || volumeKind == "hfs" else {
- continue
- }
- let device = entry["dev-entry"] as? String ?? ""
- let mountPoint = entry["mount-point"] as? String ?? ""
-
- if forceRW {
- _ = try runProcess("/sbin/mount", ["-u", "-w", device, mountPoint])
- }
- return (device, mountPoint)
- }
- throw FirmwareManifest.ManifestError.missingKey("dev-entry or mount-point")
- }
-
- func detachImage(deviceNode: String) throws {
- _ = try runProcess("/usr/bin/hdiutil", ["detach", deviceNode])
- }
-
- func runProcess(_ launchPath: String, _ arguments: [String], sudo: Bool = false, output: URL? = nil) throws -> String {
- let process = Process()
- if sudo {
- let whoami = try runProcess("/usr/bin/whoami", [])
- if !whoami.contains("root") {
- print("This step requires root. Run the command again with sudo.")
- exit(42)
- }
- }
- process.executableURL = URL(fileURLWithPath: launchPath)
- process.arguments = arguments
-
- let outPipe = Pipe()
- if let output {
- let outFile = try FileHandle.init(forWritingTo: output)
- process.standardOutput = outFile
- process.standardError = outFile
- } else {
- process.standardOutput = outPipe
- process.standardError = outPipe
- }
-
- try process.run()
- process.waitUntilExit()
-
- let output = output == nil ? String(data: outPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) : nil
- guard process.terminationStatus == 0 else {
- throw ProcessError.failed(process.terminationStatus, output ?? "")
- }
- return output ?? ""
- }
}
diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherAEA.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherAEA.swift
new file mode 100644
index 00000000..6f3659bb
--- /dev/null
+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherAEA.swift
@@ -0,0 +1,156 @@
+// CryptexFilesystemPatcherAEA.swift — Apple Encrypted Archive handling for the OS image.
+//
+// Split out of CryptexFilesystemPatcher.swift. Reading an .aea file's key and auth metadata,
+// decrypting it into a plain dmg, re-encrypting the rebuilt image, and the hex-dump parsing
+// that turns `ipsw fw aea --info` output back into auth-data key/value pairs.
+
+import Foundation
+
+extension Data {
+ init?(fromHexString hex: String) {
+ guard hex.count.isMultiple(of: 2) else {
+ return nil
+ }
+
+ let chars = hex.map { $0 }
+ let bytes = stride(from: 0, to: chars.count, by: 2)
+ .map { String(chars[$0]) + String(chars[$0 + 1]) }
+ .compactMap { UInt8($0, radix: 16) }
+
+ guard hex.count / bytes.count == 2 else { return nil }
+ self.init(bytes)
+ }
+}
+
+extension CryptexFilesystemPatcher {
+ func getAeaKey(_ path: URL, metadata: [String: String]) throws -> String {
+ if let key = metadata["encryption_key"] {
+ let key = String(key.dropFirst(4))
+ if let unwrapped = Data(fromHexString: key),
+ let encoded = String(data: unwrapped, encoding: .utf8),
+ let data = Data(fromHexString: encoded) {
+ return "base64:\(data.base64EncodedString())"
+ }
+ return key
+ }
+
+ return try runProcess("/opt/homebrew/bin/ipsw", [
+ "fw", "aea",
+ "--no-color",
+ "--key",
+ path.path,
+ ]).trimmingCharacters(in: ["\n"])
+ }
+
+ func encryptAeaFile(_ path: URL, output: URL, key: String, metadata: [String: String]) throws {
+ var arguments = [
+ "encrypt", "-i", path.path, "-o", output.path,
+ "-profile", "1", "-key-value", key,
+ ]
+ for (metaKey, metaValue) in metadata {
+ arguments.append("-auth-data-key")
+ arguments.append(metaKey)
+ arguments.append("-auth-data-value")
+ arguments.append(metaValue)
+ }
+ _ = try runProcess("/usr/bin/aea", arguments)
+ }
+
+ func decryptAeaFile(_ path: URL) throws -> URL {
+ let tmpDir = try createTmpDir()
+ let outputPath = tmpDir.appending(path: path.appendingPathExtension("dmg").lastPathComponent)
+ _ = try runProcess("/opt/homebrew/bin/ipsw", [
+ "fw", "aea",
+ "-o", outputPath.path,
+ path.path,
+ ])
+ return outputPath.appending(path: path.lastPathComponent.dropLast(4))
+ }
+
+ func getAeaMetadata(_ path: URL) throws -> [String: String] {
+ let output = try runProcess("/opt/homebrew/bin/ipsw", [
+ "fw", "aea",
+ "--no-color",
+ "--info",
+ path.path,
+ ])
+ let lines = output.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline).map(String.init)
+
+ var result: [String: String] = [:]
+ var currentKey: String?
+ var bodyLines: [String] = []
+
+ func flushCurrentSection() {
+ guard let key = currentKey else { return }
+ result[key] = parseSectionBody(bodyLines)
+ }
+
+ for rawLine in lines {
+ let trimmed = rawLine.trimmingCharacters(in: .whitespaces)
+
+ if let key = parseSectionHeader(trimmed) {
+ flushCurrentSection()
+ currentKey = key
+ bodyLines = []
+ } else {
+ // Ignore banner lines before the first section
+ if currentKey != nil {
+ bodyLines.append(rawLine)
+ }
+ }
+ }
+
+ flushCurrentSection()
+ return result
+ }
+
+ private func parseSectionHeader(_ line: String) -> String? {
+ // Matches both:
+ // [com.apple.wkms.url]:
+ // [saksKey]:
+ guard line.hasPrefix("[") else { return nil }
+ guard let end = line.firstIndex(of: "]") else { return nil }
+
+ let key = String(line[line.index(after: line.startIndex)..<end])
+ return key.isEmpty ? nil : key
+ }
+
+ private func parseSectionBody(_ bodyLines: [String]) -> String {
+ let nonEmpty = bodyLines.filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty }
+
+ // If the section contains hex dump lines, parse and concatenate them.
+ let hexBytes = nonEmpty.flatMap { parseHexDumpLine($0) }
+ if !hexBytes.isEmpty {
+ let b64Encoded = Data(hexBytes).base64EncodedString()
+ return "hex:\(Data(b64Encoded.utf8).hex)"
+ }
+
+ // Otherwise treat it as plain text / JSON / whatever the section contains.
+ let text = bodyLines.joined(separator: "\n")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+
+ return "hex:\(Data(text.utf8).hex)"
+ }
+
+ private func parseHexDumpLine(_ line: String) -> [UInt8] {
+ // Example:
+ // 0000000000000000: 0a 8d 03 0a 2f c7 ... |....|
+ guard let colonIndex = line.firstIndex(of: ":") else { return [] }
+
+ let afterColon = line[line.index(after: colonIndex)...]
+ let beforeAscii = afterColon.split(separator: "|", maxSplits: 1, omittingEmptySubsequences: false).first ?? afterColon
+
+ let tokens = beforeAscii.split(whereSeparator: \.isWhitespace)
+ var bytes: [UInt8] = []
+ bytes.reserveCapacity(tokens.count)
+
+ for token in tokens {
+ guard token.count == 2, let b = UInt8(token, radix: 16) else {
+ return [] // not a hexdump line
+ }
+ bytes.append(b)
+ }
+
+ return bytes
+ }
+}
diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherDiskImage.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherDiskImage.swift
new file mode 100644
index 00000000..11174b70
--- /dev/null
+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherDiskImage.swift
@@ -0,0 +1,149 @@
+// CryptexFilesystemPatcherDiskImage.swift — Disk image attach, convert and copy helpers.
+//
+// Split out of CryptexFilesystemPatcher.swift. The hdiutil/diskutil layer: attaching and
+// detaching images, converting between RAW and UDRW, resizing, unmounting, and the
+// copyfile-based volume copy used to merge a cryptex into the target volume.
+
+import Foundation
+
+extension CryptexFilesystemPatcher {
+ func copyImageContents(source: URL, destination: URL) throws {
+ // Copy everything from source volume root into destination volume root.
+ let sourceRoot = source.appendingPathComponent("", isDirectory: true)
+ let sourcePath = sourceRoot.path
+ let destinationRoot = destination.appendingPathComponent("", isDirectory: true)
+
+ // We delete the files first as we want to replace symlinks with actual files.
+ let keys: [URLResourceKey] = [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey]
+ guard let enumerator = FileManager.default.enumerator(at: sourceRoot, includingPropertiesForKeys: keys) else {
+ throw FirmwareManifest.ManifestError.fileNotFound(
+ "Unable to read \(sourceRoot.path). Check that the image is still mounted, then try again."
+ )
+ }
+ for case let fileURL as URL in enumerator {
+ guard fileURL.path.hasPrefix(sourcePath) else { continue }
+
+ let values = try fileURL.resourceValues(forKeys: Set(keys))
+ var suffix = String(fileURL.path.dropFirst(sourcePath.count))
+ if suffix.hasPrefix("/") {
+ suffix.removeFirst()
+ }
+
+ let destinationPath = destinationRoot.appendingPathComponent(suffix)
+ guard let ok = try? destinationPath.checkResourceIsReachable(), ok else {
+ // try FileManager.default.copyItem(at: fileURL, to: destinationPath)
+ let result = copyfile(fileURL.path, destinationPath.path, nil, copyfile_flags_t(COPYFILE_SECURITY | COPYFILE_DATA))
+ if result < 0 {
+ print("Unable to copy \(destinationPath.path). Check permissions and free space, then try again.")
+ }
+ continue
+ }
+
+ let vals = try destinationPath.resourceValues(forKeys: Set(keys))
+ if values.isDirectory != vals.isDirectory ||
+ values.isRegularFile != vals.isRegularFile ||
+ values.isSymbolicLink != vals.isSymbolicLink {
+ try FileManager.default.removeItem(at: destinationPath)
+ // try FileManager.default.copyItem(at: fileURL, to: destinationPath)
+ let result = copyfile(fileURL.path, destinationPath.path, nil, copyfile_flags_t(COPYFILE_SECURITY | COPYFILE_DATA))
+ if result < 0 {
+ print("Unable to copy \(destinationPath.path). Check permissions and free space, then try again.")
+ }
+ }
+ }
+ }
+
+ func convertToRawImage(input: URL, output: URL) throws {
+ _ = try runProcess("/usr/sbin/diskutil", [
+ "image", "create", "from",
+ "--format", "RAW", input.path,
+ output.path
+ ])
+
+ // Resize to max
+ let maxsize = try runProcess("/bin/sh", [
+ "-c", "diskutil image resize --plist \"\(output.path)\" | plutil -extract max raw -o - -"
+ ]).trimmingCharacters(in: ["\n"])
+ _ = try runProcess("/usr/sbin/diskutil", [
+ "image", "resize", "--size", maxsize, output.path
+ ])
+ }
+
+ func convertToUDRWImage(input: URL, output: URL) throws {
+ if FileManager.default.fileExists(atPath: output.path) {
+ try FileManager.default.removeItem(at: output)
+ }
+ _ = try runProcess("/usr/bin/hdiutil", [
+ "convert",
+ input.path,
+ "-format", "UDRW",
+ "-o", output.path
+ ])
+ }
+
+ func shrinkImage(dmg: URL) throws {
+ _ = try runProcess("/usr/sbin/diskutil", [
+ "image",
+ "resize",
+ "--size", "min",
+ dmg.path
+ ])
+ }
+
+ func unmount(mount: String) throws {
+ _ = try runProcess("/usr/sbin/diskutil", ["unmount", mount])
+ }
+
+ // attachImage returns the device and mount point
+ func attachImage(path: URL, readonly: Bool = false, forceRW: Bool = false) throws -> (String, String) {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/usr/bin/hdiutil")
+ process.arguments = if readonly {[
+ "attach",
+ "-readonly",
+ "-plist",
+ path.path,
+ ]} else {[
+ "attach",
+ "-plist",
+ path.path,
+ ]}
+
+ let pipe = Pipe()
+ process.standardOutput = pipe
+ process.standardError = pipe
+
+ try process.run()
+ process.waitUntilExit()
+
+ let data = pipe.fileHandleForReading.readDataToEndOfFile()
+ guard process.terminationStatus == 0 else {
+ let output = String(data: data, encoding: .utf8) ?? ""
+ throw ProcessError.failed(process.terminationStatus, output)
+ }
+
+ let root = try parsePlist(data: data)
+ guard let entries = root["system-entities"] as? [Any] else {
+ throw FirmwareManifest.ManifestError.missingKey("system-entities")
+ }
+ for entry in entries {
+ guard let entry = entry as? PlistDict,
+ let volumeKind = entry["volume-kind"] as? String,
+ volumeKind == "apfs" || volumeKind == "hfs" else {
+ continue
+ }
+ let device = entry["dev-entry"] as? String ?? ""
+ let mountPoint = entry["mount-point"] as? String ?? ""
+
+ if forceRW {
+ _ = try runProcess("/sbin/mount", ["-u", "-w", device, mountPoint])
+ }
+ return (device, mountPoint)
+ }
+ throw FirmwareManifest.ManifestError.missingKey("dev-entry or mount-point")
+ }
+
+ func detachImage(deviceNode: String) throws {
+ _ = try runProcess("/usr/bin/hdiutil", ["detach", deviceNode])
+ }
+}
diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift
new file mode 100644
index 00000000..562e09d5
--- /dev/null
+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift
@@ -0,0 +1,188 @@
+// CryptexFilesystemPatcherGuestPayload.swift — Guest payload injection into the merged volume.
+//
+// Split out of CryptexFilesystemPatcher.swift. These are the steps that write files into the
+// mounted target volume: dyld symlinks, GPU driver bundle, the mobileactivationd and
+// launchd_cache_loader patches, vphoned, the binpack, and the LaunchDaemons that start them.
+
+import Foundation
+import VPhoneCore
+
+extension CryptexFilesystemPatcher {
+ func patchLaunchdCacheLoader(targetMount: String, cfwInput: URL) throws {
+ let target = URL.init(filePath: targetMount)
+ let launchdCacheLoaderPath = target.appending(path: "/usr/libexec/launchd_cache_loader")
+ let pythonPath = try resources.pythonExecutable()
+ let patcherPath = resources.cfwPy
+ _ = try runProcess(pythonPath.path, [
+ patcherPath.path, "patch-launchd-cache-loader",
+ launchdCacheLoaderPath.path
+ ])
+ _ = try runProcess("/bin/chmod", ["0755", launchdCacheLoaderPath.path])
+
+ let signingCertificatePath = cfwInput.appending(path: "cfw_input/signcert.p12")
+ _ = try runProcess("/opt/homebrew/bin/ldid", [
+ "-S", "-M", "-K\(signingCertificatePath.path)",
+ "-Icom.apple.launchd_cache_loader",
+ launchdCacheLoaderPath.path
+ ])
+ }
+
+ func injectLaunchDaemons(targetMount: String, cfwInput: URL, vphoned: Bool = true, cfw: Bool = true) throws {
+ let target = URL.init(filePath: targetMount)
+ let scriptDir = resources.scriptsDir
+
+ let tmpDir = try createTmpDir()
+ let launchdPath = tmpDir.appending(path: "launchd.plist")
+ let launchDaemonsPath = tmpDir.appending(path: "launchDaemons")
+ let launchdOgPath = target.appending(path: "/System/Library/xpc/launchd.plist")
+ try FileManager.default.createDirectory(at: launchDaemonsPath, withIntermediateDirectories: false)
+ try FileManager.default.moveItem(at: launchdOgPath, to: launchdPath)
+
+ if vphoned {
+ let vphonedSrc = scriptDir.appendingPathComponent("vphoned")
+ let vphonedLaunchdPlist = vphonedSrc.appending(path: "vphoned.plist")
+ try FileManager.default.copyItem(at: vphonedLaunchdPlist,
+ to: target.appending(path: "System/Library/LaunchDaemons/vphoned.plist"))
+ try FileManager.default.copyItem(at: vphonedLaunchdPlist, to: launchDaemonsPath.appending(path: vphonedLaunchdPlist.lastPathComponent))
+ }
+ if cfw {
+ let launchDaemonsDir = cfwInput.appending(path: "cfw_input/jb/LaunchDaemons")
+ let launchDaemons = try FileManager.default.contentsOfDirectory(atPath: launchDaemonsDir.path)
+ for filename in launchDaemons {
+ let launchDaemonUrl = launchDaemonsDir.appending(component: filename)
+ let filename = launchDaemonUrl.lastPathComponent
+ let fsTarget = target.appending(path: "System/Library/LaunchDaemons/\(filename)")
+ try FileManager.default.copyItem(at: launchDaemonUrl, to: fsTarget)
+ try FileManager.default.copyItem(at: launchDaemonUrl, to: launchDaemonsPath.appending(path: filename))
+ }
+ }
+
+ let pythonPath = try resources.pythonExecutable()
+ _ = try runProcess(pythonPath.path, [
+ resources.cfwPy.path, "inject-daemons",
+ launchdPath.path, launchDaemonsPath.path
+ ])
+ try FileManager.default.moveItem(at: launchdPath, to: launchdOgPath)
+ _ = try runProcess("/bin/chmod", ["0644", launchdOgPath.path])
+ }
+
+ func addExtraServices(targetMount: String, cfwInput: URL) throws {
+ _ = try runProcess("/usr/bin/tar", [
+ "--preserve-permissions",
+ "-xf", cfwInput.appending(path: "cfw_input/jb/iosbinpack64.tar").path,
+ "-C", targetMount
+ ])
+ }
+
+ func addVphoned(targetMount: String, cfwInput: URL) throws {
+ let target = URL.init(filePath: targetMount)
+ let scriptDir = resources.scriptsDir
+ let vphonedSrc = scriptDir.appendingPathComponent("vphoned")
+ // vphonedSrc (bundled source) is read-only inside a packaged .app, so the
+ // compiled binary must land in a writable temp dir, not next to the source.
+ let buildDir = try createTmpDir()
+ let vphonedBin = buildDir.appendingPathComponent("vphoned")
+
+ try buildVphoned(vphonedSrc: vphonedSrc, vphonedBin: vphonedBin)
+ defer { try? FileManager.default.removeItem(at: vphonedBin) }
+
+ // Sign
+ let targetBin = target.appending(path: "/usr/bin/vphoned")
+ try FileManager.default.copyItem(at: vphonedBin, to: targetBin)
+ let signingCertificatePath = cfwInput.appending(path: "cfw_input/signcert.p12")
+ _ = try runProcess("/opt/homebrew/bin/ldid", [
+ "-S\(vphonedSrc.appendingPathComponent("entitlements.plist").path)",
+ "-M", "-K\(signingCertificatePath.path)",
+ targetBin.path
+ ])
+ _ = try runProcess("/bin/chmod", ["0755", targetBin.path])
+ }
+
+ func buildVphoned(vphonedSrc: URL, vphonedBin: URL) throws {
+ let srcURLs = try FileManager.default.contentsOfDirectory(
+ at: vphonedSrc,
+ includingPropertiesForKeys: [.contentModificationDateKey],
+ options: [.skipsHiddenFiles]
+ ).filter { $0.pathExtension == "m" }
+
+ var args = [
+ "-sdk", "iphoneos", "clang",
+ "-arch", "arm64",
+ "-Os",
+ "-fobjc-arc",
+ "-I\(vphonedSrc.path)",
+ "-I\(vphonedSrc.appendingPathComponent("vendor/libarchive").path)",
+ "-DLESS=1",
+ "-o", vphonedBin.path
+ ]
+ args.append(contentsOf: srcURLs.map { $0.path })
+ args.append(contentsOf: [
+ "-larchive",
+ "-lsqlite3",
+ "-framework", "Foundation",
+ "-framework", "Security",
+ "-framework", "CoreServices"
+ ])
+
+ _ = try runProcess("/usr/bin/xcrun", args)
+ }
+
+ func addGpuDriver(targetMount: String, cfwInput: URL) throws {
+ let target = URL.init(filePath: targetMount)
+
+ let gpuTarPath = cfwInput.appending(path: "cfw_input/custom/AppleParavirtGPUMetalIOGPUFamily.tar")
+ _ = try runProcess("/usr/bin/tar", [
+ "--preserve-permissions",
+ "-xf", gpuTarPath.path,
+ "-C", target.path
+ ])
+
+ let bundle = target.appending(path: "/System/Library/Extensions/AppleParavirtGPUMetalIOGPUFamily.bundle")
+ // Clean macOS resource fork files (._* files from tar xattrs)
+ _ = try? runProcess("/usr/bin/find", [bundle.path, "-name", "._*", "-delete"])
+ _ = try runProcess("/usr/sbin/chown", ["-R", "0:0", bundle.path])
+ for path in [
+ bundle.path,
+ bundle.appending(path: "/libAppleParavirtCompilerPluginIOGPUFamily.dylib").path,
+ bundle.appending(path: "/AppleParavirtGPUMetalIOGPUFamily").path,
+ bundle.appending(path: "/_CodeSignature").path,
+ ] {
+ _ = try runProcess("/bin/chmod", ["0755", path])
+ }
+ for path in [
+ bundle.appending(path: "/_CodeSignature/CodeResources").path,
+ bundle.appending(path: "/Info.plist").path
+ ] {
+ _ = try runProcess("/bin/chmod", ["0644", path])
+ }
+ }
+
+ func patchMobileActivation(targetMount: String, cfwInput: URL) throws {
+ let target = URL.init(filePath: targetMount)
+ let mobileActivationdPath = target.appending(path: "/usr/libexec/mobileactivationd")
+ let pythonPath = try resources.pythonExecutable()
+ _ = try runProcess(pythonPath.path, [
+ resources.cfwPy.path, "patch-mobileactivationd",
+ mobileActivationdPath.path
+ ])
+ _ = try runProcess("/bin/chmod", ["0755", mobileActivationdPath.path])
+
+ let signingCertificatePath = cfwInput.appending(path: "cfw_input/signcert.p12")
+ _ = try runProcess("/opt/homebrew/bin/ldid", [
+ "-S", "-M", "-K\(signingCertificatePath.path)",
+ mobileActivationdPath.path
+ ])
+ }
+
+ func addDyldSymlinks(targetMount: String) throws {
+ let target = URL.init(filePath: targetMount)
+ _ = try runProcess("/bin/ln", [
+ "-sf", "../../../System/Cryptexes/OS/System/Library/Caches/com.apple.dyld",
+ target.appending(path: "/System/Library/Caches/com.apple.dyld").path
+ ])
+ _ = try runProcess("/bin/ln", [
+ "-sf", "../../../../System/Cryptexes/OS/System/DriverKit/System/Library/dyld",
+ target.appending(path: "/System/DriverKit/System/Library/dyld").path
+ ])
+ }
+}
diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherManifest.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherManifest.swift
new file mode 100644
index 00000000..ab425271
--- /dev/null
+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherManifest.swift
@@ -0,0 +1,133 @@
+// CryptexFilesystemPatcherManifest.swift — BuildManifest reading and rewriting.
+//
+// Split out of CryptexFilesystemPatcher.swift. Plist parsing helpers, component path lookup,
+// and the rewrite that points OS, StaticTrustCache, Ap,SystemVolumeCanonicalMetadata and
+// SystemVolume at the freshly built payloads.
+
+import Foundation
+
+extension CryptexFilesystemPatcher {
+ func serializePayload(_ buildManifest: PlistDict) throws -> Data {
+ return try PropertyListSerialization.data(
+ fromPropertyList: buildManifest,
+ format: .xml,
+ options: 0
+ )
+ }
+
+ func setUpdatedComponentsInManifest(filesystem: URL, trustcache: URL, metadata: URL, rootHash: URL) throws -> PlistDict {
+ var root = try parsePlist(data: buildManiest)
+ guard var buildIdentities = root["BuildIdentities"] as? [Any],
+ buildIdentities.count > 0,
+ var buildIdentity = buildIdentities.first! as? PlistDict else {
+ throw FirmwareManifest.ManifestError.missingKey("Component in BuildManifest")
+ }
+ var identityManifest = try getChildPlistDict(parent: buildIdentity, key: "Manifest")
+
+ // We assume that the filesystem is already placed in the restore directory.
+ identityManifest = try updateManifestComponentPath(identityManifest: identityManifest, component: "OS", at: filesystem)
+
+ let newTrustcachePath = self.restoreDir.appending(path: "Firmware").appending(path: trustcache.lastPathComponent)
+ if trustcache != newTrustcachePath && FileManager.default.fileExists(atPath: newTrustcachePath.path) {
+ try FileManager.default.removeItem(at: newTrustcachePath)
+ }
+ try FileManager.default.moveItem(at: trustcache, to: newTrustcachePath)
+ identityManifest = try updateManifestComponentPath(identityManifest: identityManifest, component: "StaticTrustCache", at: newTrustcachePath)
+
+ let newMetadataPath = self.restoreDir.appending(path: "Firmware").appending(path: metadata.lastPathComponent)
+ if metadata != newMetadataPath && FileManager.default.fileExists(atPath: newMetadataPath.path) {
+ try FileManager.default.removeItem(at: newMetadataPath)
+ }
+ try FileManager.default.moveItem(at: metadata, to: newMetadataPath)
+ identityManifest = try updateManifestComponentPath(identityManifest: identityManifest, component: "Ap,SystemVolumeCanonicalMetadata", at: newMetadataPath)
+
+ let newRootHashPath = self.restoreDir.appending(path: "Firmware").appending(path: rootHash.lastPathComponent)
+ if rootHash != newRootHashPath && FileManager.default.fileExists(atPath: newRootHashPath.path) {
+ try FileManager.default.removeItem(at: newRootHashPath)
+ }
+ try FileManager.default.moveItem(at: rootHash, to: newRootHashPath)
+ identityManifest = try updateManifestComponentPath(identityManifest: identityManifest, component: "SystemVolume", at: newRootHashPath)
+
+ buildIdentity["Manifest"] = identityManifest
+ buildIdentities[0] = buildIdentity
+ root["BuildIdentities"] = buildIdentities
+ return root
+ }
+
+ func updateManifestComponentPath(identityManifest: PlistDict, component: String, at: URL) throws -> PlistDict {
+ var identityManifest = identityManifest
+ let pathSuffix = relativePath(from: at, base: self.restoreDir.appendingPathComponent("", isDirectory: true))
+ var comp = try getChildPlistDict(parent: identityManifest, key: component)
+ var info = try getChildPlistDict(parent: comp, key: "Info")
+ info["Path"] = pathSuffix
+ comp["Info"] = info
+ identityManifest[component] = comp
+ return identityManifest
+ }
+
+ func relativePath(from child: URL, base: URL) -> String? {
+ let basePath = base.standardizedFileURL.pathComponents
+ let childPath = child.standardizedFileURL.pathComponents
+
+ guard childPath.starts(with: basePath) else { return nil }
+
+ let remaining = childPath.dropFirst(basePath.count)
+ return remaining.joined(separator: "/")
+ }
+
+ func getProductVersion() throws -> String {
+ let root = try parsePlist(data: buildManiest)
+ guard let productVersion = root["ProductVersion"] as? String else {
+ throw FirmwareManifest.ManifestError.missingKey("ProductVersion in BuildManifest")
+ }
+ return productVersion
+ }
+
+ func componentPath(_ component: String) throws -> String {
+ let path = self.restoreDir.appending(path: "iPhone-BuildManifest.plist")
+ let manifest = try getBuildIdentityManifest(path: path)
+ return try getComponentPath(component: component, buildManifest: manifest)
+ }
+
+ func getComponentPath(component: String, buildManifest: PlistDict) throws -> String {
+ let comp = try getChildPlistDict(parent: buildManifest, key: component)
+ let info = try getChildPlistDict(parent: comp, key: "Info")
+ guard let path = info["Path"] as? String else {
+ throw FirmwareManifest.ManifestError.missingKey("component path")
+ }
+ return path
+ }
+
+ func getBuildIdentityManifest(path: URL) throws -> PlistDict {
+ let data = try Data.init(contentsOf: path)
+ return try getBuildIdentityManifest(data: data)
+ }
+
+ func getBuildIdentityManifest(data: Data) throws -> PlistDict {
+ let buildManifest = try parsePlist(data: data)
+ guard let buildIdentities = buildManifest["BuildIdentities"] as? [Any],
+ buildIdentities.count > 0,
+ let buildIdentity = buildIdentities.first! as? PlistDict else {
+ throw FirmwareManifest.ManifestError.missingKey("Component in BuildManifest")
+ }
+ return try getChildPlistDict(parent: buildIdentity, key: "Manifest")
+ }
+
+ func parsePlist(data: Data) throws -> PlistDict {
+ guard let buildManifest = try PropertyListSerialization.propertyList(
+ from: data,
+ options: [],
+ format: nil
+ ) as? PlistDict else {
+ throw FirmwareManifest.ManifestError.invalidPlist("")
+ }
+ return buildManifest
+ }
+
+ func getChildPlistDict(parent: PlistDict, key: String) throws -> PlistDict {
+ guard let value = parent[key] as? PlistDict else {
+ throw FirmwareManifest.ManifestError.missingKey(key)
+ }
+ return value
+ }
+}
diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherProcess.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherProcess.swift
new file mode 100644
index 00000000..fafa512c
--- /dev/null
+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherProcess.swift
@@ -0,0 +1,46 @@
+// CryptexFilesystemPatcherProcess.swift — Subprocess execution for the filesystem patcher.
+//
+// Split out of CryptexFilesystemPatcher.swift. Every external tool the merge drives — hdiutil,
+// diskutil, tar, ldid, ipsw, aa, cryptexctl, apfs_sealvolume — runs through runProcess, and
+// ProcessError is what it throws.
+
+import Foundation
+
+enum ProcessError: Error {
+ case failed(Int32, String)
+ case notExecutable(String)
+}
+
+extension CryptexFilesystemPatcher {
+ func runProcess(_ launchPath: String, _ arguments: [String], sudo: Bool = false, output: URL? = nil) throws -> String {
+ let process = Process()
+ if sudo {
+ let whoami = try runProcess("/usr/bin/whoami", [])
+ if !whoami.contains("root") {
+ print("This step requires root. Run the command again with sudo.")
+ exit(42)
+ }
+ }
+ process.executableURL = URL(fileURLWithPath: launchPath)
+ process.arguments = arguments
+
+ let outPipe = Pipe()
+ if let output {
+ let outFile = try FileHandle.init(forWritingTo: output)
+ process.standardOutput = outFile
+ process.standardError = outFile
+ } else {
+ process.standardOutput = outPipe
+ process.standardError = outPipe
+ }
+
+ try process.run()
+ process.waitUntilExit()
+
+ let output = output == nil ? String(data: outPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) : nil
+ guard process.terminationStatus == 0 else {
+ throw ProcessError.failed(process.terminationStatus, output ?? "")
+ }
+ return output ?? ""
+ }
+}
diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherSealing.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherSealing.swift
new file mode 100644
index 00000000..93ca7e1c
--- /dev/null
+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherSealing.swift
@@ -0,0 +1,210 @@
+// CryptexFilesystemPatcherSealing.swift — Trust cache, mtree and SystemVolume seal generation.
+//
+// Split out of CryptexFilesystemPatcher.swift. Everything that turns the merged image into a
+// sealed system volume: the static trust cache, the mtree, the digest database and root hash
+// produced by apfs_sealvolume, and the Ap,SystemVolumeCanonicalMetadata container.
+
+import Foundation
+
+extension CryptexFilesystemPatcher {
+ func wrapRootHash(_ rootHashPath: URL) throws -> URL {
+ let tmpDir = try createTmpDir()
+ let im4pPath = tmpDir.appending(path: "metadata.root_hash")
+ _ = try runProcess("/opt/homebrew/bin/ipsw", [
+ "img4", "im4p", "create",
+ "--type", "isys", "--version", "0",
+ "-o", im4pPath.path,
+ rootHashPath.path
+ ])
+ return im4pPath
+ }
+
+ func wrapTrustcache(_ trustcache: URL) throws -> URL {
+ let tmpDir = try createTmpDir()
+ let im4pPath = tmpDir.appending(path: "new.filesystem")
+ _ = try runProcess("/opt/homebrew/bin/ipsw", [
+ "img4", "im4p", "create",
+ "--type", "trst", "--version", "1",
+ "-o", im4pPath.path,
+ trustcache.path
+ ])
+ return im4pPath
+ }
+
+ func compressCanonicalMetadata(mtree: URL, digestDb: URL) throws -> URL {
+ let tmpDir = try createTmpDir()
+ let targetMtree = tmpDir.appending(path: mtree.lastPathComponent)
+ try FileManager.default.copyItem(at: mtree, to: targetMtree)
+ let targetDigestDb = tmpDir.appending(path: digestDb.lastPathComponent)
+ try FileManager.default.copyItem(at: digestDb, to: targetDigestDb)
+
+ let archivePath = tmpDir.appending(path: "payload.aar")
+ _ = try runProcess("/usr/bin/aa", [
+ "archive",
+ "-d", tmpDir.path,
+ "-o", archivePath.path
+ ])
+
+ let im4pPath = tmpDir.appending(path: "metadata.mtree")
+ _ = try runProcess("/opt/homebrew/bin/ipsw", [
+ "img4", "im4p", "create",
+ "--type", "msys", "--version", "0",
+ "-o", im4pPath.path,
+ archivePath.path
+ ])
+ return im4pPath
+ }
+
+ private func identifyApfsSealvolume() throws -> URL {
+ let iosVersion = try getProductVersion()
+ // VPHONE_SEAL_DIR (set by the CLI's `fw prepare`/`fw patch`) must agree with
+ // wherever fw_prepare.sh's download_apfs_sealvolume() wrote the file; unset
+ // (dev Makefile flow) falls back to the historical repo-relative `.tools/`.
+ let sealDir = ProcessInfo.processInfo.environment["VPHONE_SEAL_DIR"].map { URL(fileURLWithPath: $0) }
+ ?? self.vphoneCliDirectory.appending(path: ".tools")
+ let path = sealDir.appendingPathComponent("apfs_sealvolume_\(iosVersion)")
+ guard FileManager.default.fileExists(atPath: path.path) else {
+ throw FirmwareManifest.ManifestError.fileNotFound(path.path)
+ }
+ guard FileManager.default.isExecutableFile(atPath: path.path) else {
+ throw ProcessError.notExecutable(path.path)
+ }
+ return path
+ }
+
+ func createDigestAndHash(filesystem: URL, mtree: URL, remap: Bool) throws -> (URL, URL) {
+ let (device, mount) = try attachImage(path: filesystem)
+ defer { try? detachImage(deviceNode: device) }
+
+ let tmpDir = try createTmpDir()
+ let digestDbPath = tmpDir.appending(path: "digest.db")
+ let rootHashPath = tmpDir.appending(path: "root_hash")
+ let mtreeRemapPath = tmpDir.appending(path: "mtree_remap.xml")
+ let sealLogPath = tmpDir.appending(path: "seal.log")
+
+ // We want to get the nanosecond timestamp of the last modification before the mtree collection.
+ // We know that we remove directories in /private/var in removeSpecificSystemFiles last.
+ // Therefore, we parse the modification time of /private/var.
+ let modificationTime = try parsePrivateVarTime(mtree: mtree)
+ let remapContent = """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+ <plist version="1.0">
+ <dict>
+ \(remap ? """
+ <key>MODIFICATION</key>
+ <integer>\(modificationTime)</integer>
+ """ : "")
+ </dict>
+ </plist>
+ """
+ print("Modification time: \(remap ? modificationTime : "none")")
+ FileManager.default.createFile(atPath: mtreeRemapPath.path, contents: remapContent.data(using: .utf8))
+
+ try unmount(mount: mount)
+ let sealvolume = try identifyApfsSealvolume()
+ FileManager.default.createFile(atPath: sealLogPath.path, contents: nil)
+ _ = try runProcess(sealvolume.path, [
+ "-R", mtreeRemapPath.path,
+ "-U", digestDbPath.path, // Save digest records
+ "-M", rootHashPath.path, // Save root hash
+ device
+ ], output: sealLogPath)
+ return (digestDbPath, rootHashPath)
+ }
+
+ func parsePrivateVarTime(mtree: URL) throws -> String {
+ guard let mtreeData = FileManager.default.contents(atPath: mtree.path),
+ let text = String(data: mtreeData, encoding: .utf8) else {
+ throw FirmwareManifest.ManifestError.fileNotFound(mtree.path)
+ }
+ let lines = text.split(whereSeparator: \.isNewline).map(String.init)
+
+ // Find the section header for /private/var
+ guard let sectionIndex = lines.firstIndex(of: "# ./private/var") else {
+ throw FirmwareManifest.ManifestError.fileNotFound("/private/var")
+ }
+
+ // Look at the lines after that header until the next section header
+ for line in lines[(sectionIndex + 1)...] {
+ // Stop if we hit the next section
+ if line.hasPrefix("# ./") {
+ break
+ }
+
+ // The metadata line for /private/var starts with "var "
+ guard line.hasPrefix("var ") else { continue }
+
+ // Extract time=...
+ guard let match = line.range(of: #"time=([0-9]+(?:\.[0-9]+)?)"#,
+ options: .regularExpression) else {
+ throw FirmwareManifest.ManifestError.fileNotFound("modification time for /private/var in \(mtree.path)")
+ }
+
+ let matchedText = String(line[match])
+ return matchedText
+ .replacingOccurrences(of: "time=", with: "")
+ .replacingOccurrences(of: ".", with: "")
+ }
+
+ throw FirmwareManifest.ManifestError.fileNotFound("the /private/var entry in \(mtree.path)")
+ }
+
+ func createMtree(filesystem: URL) throws -> URL {
+ let (device, mount) = try attachImage(path: filesystem, readonly: true)
+ defer { try? detachImage(deviceNode: device) }
+
+ let tmpDir = try createTmpDir()
+ let mtreeFile = tmpDir.appending(path: "mtree.txt")
+ FileManager.default.createFile(atPath: mtreeFile.path, contents: nil)
+ _ = try runProcess("/usr/sbin/mtree", [
+ "-c",
+ "-p", mount,
+ ], output: mtreeFile)
+ return mtreeFile
+ }
+
+ func removeSpecificSystemFiles(filesystem: URL) throws -> Bool {
+ let (device, mount) = try attachImage(path: filesystem, forceRW: true)
+ defer { try? detachImage(deviceNode: device) }
+
+ let removedPaths = [
+ "/private/var/MobileAsset/PreinstalledAssets",
+ "/private/var/MobileAsset/PreinstalledAssetsV2",
+ "/private/var/staged_system_apps",
+ ]
+ var didEdit = false
+ for path in removedPaths {
+ if FileManager.default.fileExists(atPath: mount.appending(path)) {
+ try FileManager.default.removeItem(atPath: mount.appending(path))
+ didEdit = true
+ }
+ }
+ return didEdit
+ }
+
+ func createTrustcache(filesystem: URL) throws -> URL {
+ let (device, mount) = try attachImage(path: filesystem, readonly: true)
+ defer { try? detachImage(deviceNode: device) }
+
+ let oldTrustcache = try componentPath("StaticTrustCache")
+ let oldTrustcachePath = self.restoreDir.appending(path: oldTrustcache)
+ let newTrustcachePath = self.restoreDir.appending(path: "Firmware/new.trustcache")
+ let tmpDir = try createTmpDir()
+
+ let tcContainer = tmpDir.appending(path: "new.trustcache")
+ _ = try runProcess("/System/Library/SecurityResearch/usr/bin/cryptexctl", [
+ "generate-trust-cache", "--type", "static",
+ "--base-trust-cache", oldTrustcachePath.path,
+ "--output-file", tcContainer.path,
+ mount
+ ])
+
+ if FileManager.default.fileExists(atPath: newTrustcachePath.path) {
+ try FileManager.default.removeItem(at: newTrustcachePath)
+ }
+ try FileManager.default.moveItem(at: tcContainer, to: newTrustcachePath)
+
+ return newTrustcachePath
+ }
+}
diff --git a/sources/FirmwarePatcher/IBoot/IBootPatcher.swift b/sources/FirmwarePatcher/IBoot/IBootPatcher.swift
index 820f52d2..f458046d 100644
--- a/sources/FirmwarePatcher/IBoot/IBootPatcher.swift
+++ b/sources/FirmwarePatcher/IBoot/IBootPatcher.swift
@@ -7,6 +7,8 @@
// ibss — serial labels + image4 callback
// ibec — serial labels + image4 callback + boot-args + bootx precondition (if present)
// llb — serial labels + image4 callback + boot-args + rootfs bypass (5 patches) + panic bypass
+//
+// Each patch method is defined as an extension in its own file under IBoot/Patches/.
import Capstone
import Foundation
@@ -189,587 +191,4 @@ public class IBootPatcher: Patcher {
}
return results
}
-
- // MARK: - 1. Serial Labels
-
- /// Find the two long '====...' banner runs and write the mode label into each.
- /// Python: `patch_serial_labels()`
- func patchSerialLabels() {
- let labelStr = switch mode {
- case .ibss: "Loaded iBSS"
- case .ibec: "Loaded iBEC"
- case .llb: "Loaded LLB"
- }
- guard let labelBytes = labelStr.data(using: .ascii) else { return }
-
- // Collect all runs of '=' (>=20 chars) — same logic as Python.
- let raw = buffer.original
- var eqRuns: [Int] = []
- var i = raw.startIndex
-
- while i < raw.endIndex {
- if raw[i] == UInt8(ascii: "=") {
- let start = i
- while i < raw.endIndex, raw[i] == UInt8(ascii: "=") {
- i = raw.index(after: i)
- }
- let runLen = raw.distance(from: start, to: i)
- if runLen >= 20 {
- eqRuns.append(raw.distance(from: raw.startIndex, to: start))
- }
- } else {
- i = raw.index(after: i)
- }
- }
-
- if eqRuns.count < 2 {
- var labelCount = 0
- var searchStart = raw.startIndex
- while let range = raw.range(of: labelBytes, in: searchStart ..< raw.endIndex) {
- labelCount += 1
- searchStart = range.upperBound
- }
- if labelCount >= 2 {
- if verbose { print(" [*] serial labels: already present, skipping") }
- return
- }
- if verbose { print(" [-] serial labels: <2 banner runs found") }
- return
- }
-
- for runStart in eqRuns.prefix(2) {
- let writeOff = runStart + 1 // Python: run_start + 1
- emitString(writeOff, labelBytes, id: "\(component).serial_label", description: "serial label")
- }
- }
-
- // MARK: - 2. image4_validate_property_callback
-
- /// Find the b.ne + mov x0, x22 pattern with a preceding cmp.
- /// Patch: b.ne → NOP, mov x0, x22 → mov x0, #0.
- /// Python: `patch_image4_callback()`
- func patchImage4Callback() {
- var candidates: [(addr: Int, hasNeg1: Bool)] = []
-
- for insns in chunkedDisasm() {
- let count = insns.count
- guard count >= 2 else { continue }
- for i in 0 ..< count - 1 {
- let a = insns[i]
- let b = insns[i + 1]
-
- // Must be: b.ne followed immediately by mov x0, x22
- guard a.mnemonic == "b.ne" else { continue }
- guard b.mnemonic == "mov", b.operandString == "x0, x22" else { continue }
-
- let addr = Int(a.address)
-
- // There must be a cmp within the 8 preceding instructions
- let lookback = max(0, i - 8)
- let hasCmp = insns[lookback ..< i].contains { $0.mnemonic == "cmp" }
- guard hasCmp else { continue }
-
- // Check if a movn w22 / mov w22, #-1 appears within 64 insns before (prefer this candidate)
- let far = max(0, i - 64)
- let hasNeg1 = insns[far ..< i].contains { insn in
- if insn.mnemonic == "movn", insn.operandString.hasPrefix("w22,") {
- return true
- }
- if insn.mnemonic == "mov", insn.operandString.contains("w22"),
- insn.operandString.contains("#-1") || insn.operandString.contains("#0xffffffff")
- {
- return true
- }
- return false
- }
-
- candidates.append((addr: addr, hasNeg1: hasNeg1))
- }
- }
-
- if candidates.isEmpty {
- if verbose { print(" [-] image4 callback: pattern not found") }
- return
- }
-
- // Prefer the candidate that has a movn w22 (error return path)
- let off: Int = if let preferred = candidates.first(where: { $0.hasNeg1 }) {
- preferred.addr
- } else {
- candidates.last!.addr
- }
-
- emit(off, ARM64.nop, id: "\(component).image4_callback_bne", description: "image4 callback: b.ne → nop")
- emit(off + 4, ARM64.movX0_0, id: "\(component).image4_callback_mov", description: "image4 callback: mov x0,x22 → mov x0,#0")
- }
-
- // MARK: - 3. Boot-Args (iBEC / LLB)
-
- /// Effective boot-args string, with any `extraBootArgs` inserted before `%s`.
- private var effectiveBootArgs: String {
- extraBootArgs.isEmpty
- ? IBootPatcher.bootArgs
- : "serial=3 -v debug=0x2014e \(extraBootArgs) %s"
- }
-
- /// Redirect ADRP+ADD x2 to a custom boot-args string.
- /// Python: `patch_boot_args()`
- func patchBootArgs(newArgs: String? = nil) {
- let newArgs = newArgs ?? effectiveBootArgs
- guard let newArgsData = newArgs.data(using: .ascii) else { return }
-
- guard let fmtOff = findBootArgsFmt() else {
- if verbose { print(" [-] boot-args: format string not found") }
- return
- }
-
- guard let (adrpOff, addOff) = findBootArgsAdrp(fmtOff: fmtOff) else {
- if verbose { print(" [-] boot-args: ADRP+ADD x2 not found") }
- return
- }
-
- guard let newOff = findStringSlot(length: newArgsData.count) else {
- if verbose { print(" [-] boot-args: no NUL slot") }
- return
- }
-
- // Write the string itself
- emitString(newOff, newArgsData, id: "\(component).boot_args_string", description: "boot-args string")
-
- // Re-encode ADRP x2 → new page
- guard let newAdrp = ARM64Encoder.encodeADRP(rd: 2, pc: UInt64(adrpOff), target: UInt64(newOff)) else {
- if verbose { print(" [-] boot-args: ADRP encoding out of range") }
- return
- }
- emit(adrpOff, newAdrp, id: "\(component).boot_args_adrp", description: "boot-args: adrp x2 → new string page")
-
- // Re-encode ADD x2, x2, #offset
- let imm12 = UInt32(newOff & 0xFFF)
- guard let newAdd = ARM64Encoder.encodeAddImm12(rd: 2, rn: 2, imm12: imm12) else {
- if verbose { print(" [-] boot-args: ADD encoding out of range") }
- return
- }
- emit(addOff, newAdd, id: "\(component).boot_args_add", description: "boot-args: add x2 → new string offset")
- }
-
- /// Find the standalone "%s" format string near "rd=md0" or "BootArgs".
- /// Python: `_find_boot_args_fmt()`
- private func findBootArgsFmt() -> Int? {
- let raw = buffer.original
-
- // Find the anchor string
- var anchor: Int? = raw.range(of: Data("rd=md0".utf8)).map { raw.distance(from: raw.startIndex, to: $0.lowerBound) }
- if anchor == nil {
- anchor = raw.range(of: Data("BootArgs".utf8)).map { raw.distance(from: raw.startIndex, to: $0.lowerBound) }
- }
- guard let anchorOff = anchor else { return nil }
-
- // Search for "%s" within 0x40 bytes of the anchor
- let searchEnd = anchorOff + 0x40
- let pctS = Data([UInt8(ascii: "%"), UInt8(ascii: "s")])
-
- var off = anchorOff
- while off < searchEnd {
- guard let range = raw.range(of: pctS, in: off ..< min(searchEnd, raw.count)) else { return nil }
- let found = raw.distance(from: raw.startIndex, to: range.lowerBound)
- if found >= off + raw.count { return nil }
-
- // Must have NUL before and NUL after (isolated "%s\0")
- if found > 0, raw[found - 1] == 0, found + 2 < raw.count, raw[found + 2] == 0 {
- return found
- }
- off = found + 1
- }
- return nil
- }
-
- /// Find ADRP+ADD x2 pointing to the format string at fmtOff.
- /// Python: `_find_boot_args_adrp()`
- private func findBootArgsAdrp(fmtOff: Int) -> (Int, Int)? {
- for insns in chunkedDisasm() {
- let count = insns.count
- guard count >= 2 else { continue }
- for i in 0 ..< count - 1 {
- let a = insns[i]
- let b = insns[i + 1]
-
- guard a.mnemonic == "adrp", b.mnemonic == "add" else { continue }
-
- // First operand of ADRP must be x2
- guard a.operandString.hasPrefix("x2,") else { continue }
-
- guard let aDetail = a.aarch64, let bDetail = b.aarch64 else { continue }
- guard aDetail.operands.count >= 2, bDetail.operands.count >= 3 else { continue }
-
- // ADRP Rd must equal ADD Rn (same register)
- guard aDetail.operands[0].reg == bDetail.operands[1].reg else { continue }
-
- // ADRP page imm + ADD imm12 must equal fmt_off
- let pageImm = aDetail.operands[1].imm // already page-aligned VA
- let addImm = bDetail.operands[2].imm
- if Int(pageImm + addImm) == fmtOff {
- return (Int(a.address), Int(b.address))
- }
- }
- }
- return nil
- }
-
- /// Find a run of NUL bytes ≥ 64 bytes long to write the new string into.
- /// Python: `_find_string_slot()`
- private func findStringSlot(length: Int, searchStart: Int = 0x14000) -> Int? {
- let raw = buffer.original
- var off = searchStart
- while off < raw.count {
- if raw[off] == 0 {
- let runStart = off
- while off < raw.count, raw[off] == 0 {
- off += 1
- }
- let runLen = off - runStart
- if runLen >= 64 {
- // Align write pointer to 16 bytes (Python: (run_start + 8 + 15) & ~15)
- let writeOff = (runStart + 8 + 15) & ~15
- if writeOff + length <= off {
- return writeOff
- }
- }
- } else {
- off += 1
- }
- }
- return nil
- }
-
- // MARK: - 4. Rootfs Bypass (LLB only)
-
- /// Apply all five rootfs bypass patches.
- /// Python: `patch_rootfs_bypass()`
- func patchRootfssBypass() {
- // 4a: cbz/cbnz before error code 0x3B7 → unconditional b
- patchCbzBeforeError(errorCode: 0x3B7, description: "rootfs: skip sig check (0x3B7)")
- // 4b: NOP b.hs after cmp x8, #0x400
- patchBhsAfterCmp0x400()
- // 4c: cbz/cbnz before error code 0x3C2 → unconditional b
- patchCbzBeforeError(errorCode: 0x3C2, description: "rootfs: skip sig verify (0x3C2)")
- // 4d: NOP cbz x8 null check (ldr x8, [xN, #0x78])
- patchNullCheck0x78()
- // 4e: cbz/cbnz before error code 0x110 → unconditional b
- patchCbzBeforeError(errorCode: 0x110, description: "rootfs: skip size verify (0x110)")
- }
-
- /// Find unique `mov w8, #<errorCode>` and convert the cbz/cbnz 4 bytes before
- /// it into an unconditional branch to the same target.
- /// Python: `_patch_cbz_before_error()`
- private func patchCbzBeforeError(errorCode: UInt32, description: String) {
- let pattern = encodedMovW8(errorCode)
- let locs = buffer.findAll(pattern)
-
- guard locs.count == 1 else {
- if verbose {
- print(" [-] \(description): expected 1 'mov w8, #0x\(String(errorCode, radix: 16))', found \(locs.count)")
- }
- return
- }
-
- let errOff = locs[0]
- let cbzOff = errOff - 4
-
- guard let insn = disasm.disassembleOne(in: buffer.original, at: cbzOff) else {
- if verbose { print(" [-] \(description): no instruction at 0x\(String(format: "%X", cbzOff))") }
- return
- }
- guard insn.mnemonic == "cbz" || insn.mnemonic == "cbnz" else {
- if verbose { print(" [-] \(description): expected cbz/cbnz at 0x\(String(format: "%X", cbzOff)), got \(insn.mnemonic)") }
- return
- }
-
- // Extract branch target from the operand string (last operand is the immediate)
- guard let detail = insn.aarch64, detail.operands.count >= 2 else { return }
- let target = Int(detail.operands[1].imm)
-
- guard let bInsn = ARM64Encoder.encodeB(from: cbzOff, to: target) else {
- if verbose { print(" [-] \(description): B encoding out of range") }
- return
- }
-
- emit(cbzOff, bInsn, id: "\(component).rootfs_cbz_0x\(String(errorCode, radix: 16))", description: description)
- }
-
- /// NOP the `b.hs` of the unique `cmp x8,#0x400 ; b.hs` rootfs size gate.
- /// Anchoring on the cmp+b.hs pair disambiguates 26.4's three `cmp x8,#0x400`
- /// (the other two are followed by `b.hi`); 26.1/26.3 have just the one.
- /// Python: `_patch_bhs_after_cmp_0x400()`
- private func patchBhsAfterCmp0x400() {
- var bhsSites: [Int] = []
- for insns in chunkedDisasm() {
- for insn in insns where insn.mnemonic == "cmp" && insn.operandString == "x8, #0x400" {
- let bhsOff = Int(insn.address) + 4
- guard let next = disasm.disassembleOne(in: buffer.original, at: bhsOff),
- next.mnemonic == "b.hs" else { continue }
- if !bhsSites.contains(bhsOff) { bhsSites.append(bhsOff) }
- }
- }
-
- guard bhsSites.count == 1 else {
- if verbose { print(" [-] rootfs b.hs: expected 1 'cmp x8,#0x400 ; b.hs' pair, found \(bhsSites.count)") }
- return
- }
-
- emit(bhsSites[0], ARM64.nop, id: "\(component).rootfs_bhs_0x400", description: "rootfs: NOP b.hs size check (0x400)")
- }
-
- /// Find `ldr xR, [xN, #0x78]; cbz xR` preceding the unique `mov w8, #0x110`
- /// and NOP the cbz.
- /// Python: `_patch_null_check_0x78()`
- private func patchNullCheck0x78() {
- let pattern = encodedMovW8(0x110)
- let locs = buffer.findAll(pattern)
-
- guard locs.count == 1 else {
- if verbose { print(" [-] rootfs null check: expected 1 'mov w8, #0x110', found \(locs.count)") }
- return
- }
-
- let errOff = locs[0]
-
- // Walk backwards from errOff to find ldr x?, [xN, #0x78]; cbz x?
- let scanStart = max(errOff - 0x300, 0)
- var scan = errOff - 4
- while scan >= scanStart {
- guard let i1 = disasm.disassembleOne(in: buffer.original, at: scan),
- let i2 = disasm.disassembleOne(in: buffer.original, at: scan + 4)
- else {
- scan -= 4
- continue
- }
-
- if i1.mnemonic == "ldr",
- i1.operandString.contains("#0x78"),
- i2.mnemonic == "cbz",
- i2.operandString.hasPrefix("x")
- {
- emit(scan + 4, ARM64.nop, id: "\(component).rootfs_null_check_0x78",
- description: "rootfs: NOP cbz x8 null check (#0x78)")
- return
- }
- scan -= 4
- }
-
- if verbose { print(" [-] rootfs null check: ldr+cbz #0x78 pattern not found") }
- }
-
- // MARK: - 5. Panic Bypass (LLB only)
-
- /// Find `mov w8, #0x328; movk w8, #0x40, lsl #16; ...; bl X; cbnz w0`
- /// and NOP the cbnz.
- /// Python: `patch_panic_bypass()`
- func patchPanicBypass() {
- let mov328 = encodedMovW8(0x328)
- let locs = buffer.findAll(mov328)
-
- for loc in locs {
- // Verify movk w8, #0x40, lsl #16 follows
- guard let nextInsn = disasm.disassembleOne(in: buffer.original, at: loc + 4) else { continue }
- guard nextInsn.mnemonic == "movk",
- nextInsn.operandString.contains("w8"),
- nextInsn.operandString.contains("#0x40"),
- nextInsn.operandString.contains("lsl #16") else { continue }
-
- // Walk forward (up to 7 instructions past the movk) to find bl; cbnz w0
- var step = loc + 8
- while step < loc + 32 {
- guard let i = disasm.disassembleOne(in: buffer.original, at: step) else {
- step += 4
- continue
- }
- if i.mnemonic == "bl" {
- if let ni = disasm.disassembleOne(in: buffer.original, at: step + 4),
- ni.mnemonic == "cbnz"
- {
- emit(step + 4, ARM64.nop,
- id: "\(component).panic_bypass",
- description: "panic bypass: NOP cbnz w0")
- return
- }
- break // bl found but no cbnz — keep scanning other mov candidates
- }
- step += 4
- }
- }
-
- if verbose { print(" [-] panic bypass: pattern not found") }
- }
-
- // MARK: - 6. Bootx-handoff precondition (modern iBoot, all stages)
-
- /// NOP the conditional branch gating the modern iBoot bootx-handoff
- /// panic.
- ///
- /// Gate signature (Capstone-decoded):
- ///
- /// BL <bit_getter> ; tiny 4-insn `return bit_N([global])` fn
- /// TBZ w0, #0, <panic_block> ; patch target — NOP'd
- /// ...
- /// <panic_block>:
- /// BL <hash_getter> ; 5-insn 4×MOV/MOVK+RET source-hash fn
- /// MOV w?, #<lineno> ; source line (any value)
- /// BL <log_func> ; panic/log dispatcher
- ///
- /// `<bit_getter>` is `ADRP; LDRB; UBFX Wd, Wn, #?, #1; RET` — a
- /// "return one bit of one byte at a global address" function (rare in
- /// iBoot). The combination of "TBZ w0, #0 → panic" where the preceding
- /// instruction is BL to such a function, and the TBZ target is a
- /// hash-getter/MOVZ-line/BL-log triple, is the distinctive shape.
- ///
- /// Refuses to patch on ambiguity (multiple matches).
- func patchBootxPrecondition() {
- let hashGetters = enumerateHashGetters()
- let bitGetters = enumerateBitGetters()
-
- guard !hashGetters.isEmpty, !bitGetters.isEmpty else {
- if verbose {
- print(" [-] bootx precondition: hash-getter or bit-getter pattern absent")
- }
- return
- }
-
- let panicBlocks = enumeratePanicBlocks(hashGetters: hashGetters)
- if panicBlocks.isEmpty {
- if verbose { print(" [-] bootx precondition: no panic-shaped call blocks") }
- return
- }
-
- var gates = Set<Int>()
- for insns in chunkedDisasm() {
- guard insns.count >= 2 else { continue }
- for i in 1 ..< insns.count {
- let tbz = insns[i]
- let prev = insns[i - 1]
- guard tbz.mnemonic == "tbz" else { continue }
- guard
- let tbzDet = tbz.aarch64,
- tbzDet.operands.count >= 3,
- tbzDet.operands[0].type == AARCH64_OP_REG,
- tbzDet.operands[0].reg.rawValue == AARCH64_REG_W0.rawValue,
- tbzDet.operands[1].type == AARCH64_OP_IMM,
- tbzDet.operands[1].imm == 0,
- tbzDet.operands[2].type == AARCH64_OP_IMM
- else { continue }
- let target = Int(tbzDet.operands[2].imm)
- guard panicBlocks.contains(target) else { continue }
-
- guard prev.mnemonic == "bl" else { continue }
- guard
- let prevDet = prev.aarch64,
- prevDet.operands.count >= 1,
- prevDet.operands[0].type == AARCH64_OP_IMM
- else { continue }
- let blTarget = Int(prevDet.operands[0].imm)
- guard bitGetters.contains(blTarget) else { continue }
-
- gates.insert(Int(tbz.address))
- }
- }
-
- if gates.isEmpty {
- // 26.4+ construct; genuinely absent on previous iBoot versions.
- if verbose { print(" [.] bootx precondition: construct not present (pre-26.4 iBoot) — skipping") }
- return
- }
- if gates.count > 1 {
- if verbose {
- print(" [-] bootx precondition: ambiguous (\(gates.count) candidates)")
- for g in gates.sorted() { print(String(format: " 0x%X", g)) }
- }
- return
- }
- let gate = gates.first!
- emit(gate, ARM64.nop, id: "\(component).bootx_precondition",
- description: "bootx precondition: NOP gate TBZ")
- }
-
- /// Enumerate 5-insn `MOVZ + 3×MOVK + RET` functions assembling a 64-bit
- /// constant into a single X register (used by iBoot's panic/log calls
- /// to load the source-file hash). Returns the file offsets at which
- /// each such function starts.
- private func enumerateHashGetters() -> Set<Int> {
- var out = Set<Int>()
- for insns in chunkedDisasm() {
- guard insns.count >= 5 else { continue }
- for i in 0 ..< (insns.count - 4) {
- guard insns[i].mnemonic == "mov" || insns[i].mnemonic == "movz" else { continue }
- guard insns[i + 1].mnemonic == "movk" else { continue }
- guard insns[i + 2].mnemonic == "movk" else { continue }
- guard insns[i + 3].mnemonic == "movk" else { continue }
- guard insns[i + 4].mnemonic == "ret" else { continue }
- // All four MOV/MOVK destinations must be the same register.
- var regs = Set<UInt32>()
- var ok = true
- for k in 0 ..< 4 {
- guard
- let det = insns[i + k].aarch64,
- det.operands.count >= 1,
- det.operands[0].type == AARCH64_OP_REG
- else { ok = false; break }
- regs.insert(det.operands[0].reg.rawValue)
- }
- guard ok, regs.count == 1 else { continue }
- out.insert(Int(insns[i].address))
- }
- }
- return out
- }
-
- /// Enumerate 4-insn `ADRP + LDRB + UBFX (width=1) + RET` functions —
- /// the "return one bit of one byte global" shape used as the
- /// precondition feature-check. Any bit position is accepted; only the
- /// width-1 extract is enforced.
- private func enumerateBitGetters() -> Set<Int> {
- var out = Set<Int>()
- for insns in chunkedDisasm() {
- guard insns.count >= 4 else { continue }
- for i in 0 ..< (insns.count - 3) {
- let mnems = [
- insns[i].mnemonic, insns[i + 1].mnemonic,
- insns[i + 2].mnemonic, insns[i + 3].mnemonic,
- ]
- guard mnems == ["adrp", "ldrb", "ubfx", "ret"] else { continue }
- guard
- let det = insns[i + 2].aarch64,
- det.operands.count >= 4,
- det.operands[3].type == AARCH64_OP_IMM,
- det.operands[3].imm == 1
- else { continue }
- out.insert(Int(insns[i].address))
- }
- }
- return out
- }
-
- /// Enumerate "panic block" call sites: 3-insn sequence of
- /// `BL <hash_getter>; MOV W?, #<imm>; BL <anything>`. Returns the file
- /// offset of the first BL in each such triple.
- private func enumeratePanicBlocks(hashGetters: Set<Int>) -> Set<Int> {
- var out = Set<Int>()
- for insns in chunkedDisasm() {
- guard insns.count >= 3 else { continue }
- for i in 0 ..< (insns.count - 2) {
- guard
- insns[i].mnemonic == "bl",
- (insns[i + 1].mnemonic == "mov" || insns[i + 1].mnemonic == "movz"),
- insns[i + 2].mnemonic == "bl"
- else { continue }
- guard
- let det = insns[i].aarch64,
- det.operands.count >= 1,
- det.operands[0].type == AARCH64_OP_IMM
- else { continue }
- let blTarget = Int(det.operands[0].imm)
- guard hashGetters.contains(blTarget) else { continue }
- out.insert(Int(insns[i].address))
- }
- }
- return out
- }
}
diff --git a/sources/FirmwarePatcher/IBoot/Patches/IBootPatchBootArgs.swift b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchBootArgs.swift
new file mode 100644
index 00000000..be6b97e9
--- /dev/null
+++ b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchBootArgs.swift
@@ -0,0 +1,146 @@
+// IBootPatchBootArgs.swift — custom boot-args redirection (iBEC / LLB).
+//
+// Part of IBootPatcher; see IBootPatcher.swift for the patch schedule by mode.
+
+import Capstone
+import Foundation
+
+extension IBootPatcher {
+ // MARK: - 3. Boot-Args (iBEC / LLB)
+
+ /// Effective boot-args string, with any `extraBootArgs` inserted before `%s`.
+ private var effectiveBootArgs: String {
+ extraBootArgs.isEmpty
+ ? IBootPatcher.bootArgs
+ : "serial=3 -v debug=0x2014e \(extraBootArgs) %s"
+ }
+
+ /// Redirect ADRP+ADD x2 to a custom boot-args string.
+ /// Python: `patch_boot_args()`
+ func patchBootArgs(newArgs: String? = nil) {
+ let newArgs = newArgs ?? effectiveBootArgs
+ guard let newArgsData = newArgs.data(using: .ascii) else { return }
+
+ guard let fmtOff = findBootArgsFmt() else {
+ if verbose { print(" [-] boot-args: format string not found") }
+ return
+ }
+
+ guard let (adrpOff, addOff) = findBootArgsAdrp(fmtOff: fmtOff) else {
+ if verbose { print(" [-] boot-args: ADRP+ADD x2 not found") }
+ return
+ }
+
+ guard let newOff = findStringSlot(length: newArgsData.count) else {
+ if verbose { print(" [-] boot-args: no NUL slot") }
+ return
+ }
+
+ // Write the string itself
+ emitString(newOff, newArgsData, id: "\(component).boot_args_string", description: "boot-args string")
+
+ // Re-encode ADRP x2 → new page
+ guard let newAdrp = ARM64Encoder.encodeADRP(rd: 2, pc: UInt64(adrpOff), target: UInt64(newOff)) else {
+ if verbose { print(" [-] boot-args: ADRP encoding out of range") }
+ return
+ }
+ emit(adrpOff, newAdrp, id: "\(component).boot_args_adrp", description: "boot-args: adrp x2 → new string page")
+
+ // Re-encode ADD x2, x2, #offset
+ let imm12 = UInt32(newOff & 0xFFF)
+ guard let newAdd = ARM64Encoder.encodeAddImm12(rd: 2, rn: 2, imm12: imm12) else {
+ if verbose { print(" [-] boot-args: ADD encoding out of range") }
+ return
+ }
+ emit(addOff, newAdd, id: "\(component).boot_args_add", description: "boot-args: add x2 → new string offset")
+ }
+
+ /// Find the standalone "%s" format string near "rd=md0" or "BootArgs".
+ /// Python: `_find_boot_args_fmt()`
+ private func findBootArgsFmt() -> Int? {
+ let raw = buffer.original
+
+ // Find the anchor string
+ var anchor: Int? = raw.range(of: Data("rd=md0".utf8)).map { raw.distance(from: raw.startIndex, to: $0.lowerBound) }
+ if anchor == nil {
+ anchor = raw.range(of: Data("BootArgs".utf8)).map { raw.distance(from: raw.startIndex, to: $0.lowerBound) }
+ }
+ guard let anchorOff = anchor else { return nil }
+
+ // Search for "%s" within 0x40 bytes of the anchor
+ let searchEnd = anchorOff + 0x40
+ let pctS = Data([UInt8(ascii: "%"), UInt8(ascii: "s")])
+
+ var off = anchorOff
+ while off < searchEnd {
+ guard let range = raw.range(of: pctS, in: off ..< min(searchEnd, raw.count)) else { return nil }
+ let found = raw.distance(from: raw.startIndex, to: range.lowerBound)
+ if found >= off + raw.count { return nil }
+
+ // Must have NUL before and NUL after (isolated "%s\0")
+ if found > 0, raw[found - 1] == 0, found + 2 < raw.count, raw[found + 2] == 0 {
+ return found
+ }
+ off = found + 1
+ }
+ return nil
+ }
+
+ /// Find ADRP+ADD x2 pointing to the format string at fmtOff.
+ /// Python: `_find_boot_args_adrp()`
+ private func findBootArgsAdrp(fmtOff: Int) -> (Int, Int)? {
+ for insns in chunkedDisasm() {
+ let count = insns.count
+ guard count >= 2 else { continue }
+ for i in 0 ..< count - 1 {
+ let a = insns[i]
+ let b = insns[i + 1]
+
+ guard a.mnemonic == "adrp", b.mnemonic == "add" else { continue }
+
+ // First operand of ADRP must be x2
+ guard a.operandString.hasPrefix("x2,") else { continue }
+
+ guard let aDetail = a.aarch64, let bDetail = b.aarch64 else { continue }
+ guard aDetail.operands.count >= 2, bDetail.operands.count >= 3 else { continue }
+
+ // ADRP Rd must equal ADD Rn (same register)
+ guard aDetail.operands[0].reg == bDetail.operands[1].reg else { continue }
+
+ // ADRP page imm + ADD imm12 must equal fmt_off
+ let pageImm = aDetail.operands[1].imm // already page-aligned VA
+ let addImm = bDetail.operands[2].imm
+ if Int(pageImm + addImm) == fmtOff {
+ return (Int(a.address), Int(b.address))
+ }
+ }
+ }
+ return nil
+ }
+
+ /// Find a run of NUL bytes ≥ 64 bytes long to write the new string into.
+ /// Python: `_find_string_slot()`
+ private func findStringSlot(length: Int, searchStart: Int = 0x14000) -> Int? {
+ let raw = buffer.original
+ var off = searchStart
+ while off < raw.count {
+ if raw[off] == 0 {
+ let runStart = off
+ while off < raw.count, raw[off] == 0 {
+ off += 1
+ }
+ let runLen = off - runStart
+ if runLen >= 64 {
+ // Align write pointer to 16 bytes (Python: (run_start + 8 + 15) & ~15)
+ let writeOff = (runStart + 8 + 15) & ~15
+ if writeOff + length <= off {
+ return writeOff
+ }
+ }
+ } else {
+ off += 1
+ }
+ }
+ return nil
+ }
+}
diff --git a/sources/FirmwarePatcher/IBoot/Patches/IBootPatchBootxPrecondition.swift b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchBootxPrecondition.swift
new file mode 100644
index 00000000..ec73e8cd
--- /dev/null
+++ b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchBootxPrecondition.swift
@@ -0,0 +1,180 @@
+// IBootPatchBootxPrecondition.swift — modern iBoot bootx-handoff precondition bypass.
+//
+// Part of IBootPatcher; see IBootPatcher.swift for the patch schedule by mode.
+
+import Capstone
+import Foundation
+
+extension IBootPatcher {
+ // MARK: - 6. Bootx-handoff precondition (modern iBoot, all stages)
+
+ /// NOP the conditional branch gating the modern iBoot bootx-handoff
+ /// panic.
+ ///
+ /// Gate signature (Capstone-decoded):
+ ///
+ /// BL <bit_getter> ; tiny 4-insn `return bit_N([global])` fn
+ /// TBZ w0, #0, <panic_block> ; patch target — NOP'd
+ /// ...
+ /// <panic_block>:
+ /// BL <hash_getter> ; 5-insn 4×MOV/MOVK+RET source-hash fn
+ /// MOV w?, #<lineno> ; source line (any value)
+ /// BL <log_func> ; panic/log dispatcher
+ ///
+ /// `<bit_getter>` is `ADRP; LDRB; UBFX Wd, Wn, #?, #1; RET` — a
+ /// "return one bit of one byte at a global address" function (rare in
+ /// iBoot). The combination of "TBZ w0, #0 → panic" where the preceding
+ /// instruction is BL to such a function, and the TBZ target is a
+ /// hash-getter/MOVZ-line/BL-log triple, is the distinctive shape.
+ ///
+ /// Refuses to patch on ambiguity (multiple matches).
+ func patchBootxPrecondition() {
+ let hashGetters = enumerateHashGetters()
+ let bitGetters = enumerateBitGetters()
+
+ guard !hashGetters.isEmpty, !bitGetters.isEmpty else {
+ if verbose {
+ print(" [-] bootx precondition: hash-getter or bit-getter pattern absent")
+ }
+ return
+ }
+
+ let panicBlocks = enumeratePanicBlocks(hashGetters: hashGetters)
+ if panicBlocks.isEmpty {
+ if verbose { print(" [-] bootx precondition: no panic-shaped call blocks") }
+ return
+ }
+
+ var gates = Set<Int>()
+ for insns in chunkedDisasm() {
+ guard insns.count >= 2 else { continue }
+ for i in 1 ..< insns.count {
+ let tbz = insns[i]
+ let prev = insns[i - 1]
+ guard tbz.mnemonic == "tbz" else { continue }
+ guard
+ let tbzDet = tbz.aarch64,
+ tbzDet.operands.count >= 3,
+ tbzDet.operands[0].type == AARCH64_OP_REG,
+ tbzDet.operands[0].reg.rawValue == AARCH64_REG_W0.rawValue,
+ tbzDet.operands[1].type == AARCH64_OP_IMM,
+ tbzDet.operands[1].imm == 0,
+ tbzDet.operands[2].type == AARCH64_OP_IMM
+ else { continue }
+ let target = Int(tbzDet.operands[2].imm)
+ guard panicBlocks.contains(target) else { continue }
+
+ guard prev.mnemonic == "bl" else { continue }
+ guard
+ let prevDet = prev.aarch64,
+ prevDet.operands.count >= 1,
+ prevDet.operands[0].type == AARCH64_OP_IMM
+ else { continue }
+ let blTarget = Int(prevDet.operands[0].imm)
+ guard bitGetters.contains(blTarget) else { continue }
+
+ gates.insert(Int(tbz.address))
+ }
+ }
+
+ if gates.isEmpty {
+ // 26.4+ construct; genuinely absent on previous iBoot versions.
+ if verbose { print(" [.] bootx precondition: construct not present (pre-26.4 iBoot) — skipping") }
+ return
+ }
+ if gates.count > 1 {
+ if verbose {
+ print(" [-] bootx precondition: ambiguous (\(gates.count) candidates)")
+ for g in gates.sorted() { print(String(format: " 0x%X", g)) }
+ }
+ return
+ }
+ let gate = gates.first!
+ emit(gate, ARM64.nop, id: "\(component).bootx_precondition",
+ description: "bootx precondition: NOP gate TBZ")
+ }
+
+ /// Enumerate 5-insn `MOVZ + 3×MOVK + RET` functions assembling a 64-bit
+ /// constant into a single X register (used by iBoot's panic/log calls
+ /// to load the source-file hash). Returns the file offsets at which
+ /// each such function starts.
+ private func enumerateHashGetters() -> Set<Int> {
+ var out = Set<Int>()
+ for insns in chunkedDisasm() {
+ guard insns.count >= 5 else { continue }
+ for i in 0 ..< (insns.count - 4) {
+ guard insns[i].mnemonic == "mov" || insns[i].mnemonic == "movz" else { continue }
+ guard insns[i + 1].mnemonic == "movk" else { continue }
+ guard insns[i + 2].mnemonic == "movk" else { continue }
+ guard insns[i + 3].mnemonic == "movk" else { continue }
+ guard insns[i + 4].mnemonic == "ret" else { continue }
+ // All four MOV/MOVK destinations must be the same register.
+ var regs = Set<UInt32>()
+ var ok = true
+ for k in 0 ..< 4 {
+ guard
+ let det = insns[i + k].aarch64,
+ det.operands.count >= 1,
+ det.operands[0].type == AARCH64_OP_REG
+ else { ok = false; break }
+ regs.insert(det.operands[0].reg.rawValue)
+ }
+ guard ok, regs.count == 1 else { continue }
+ out.insert(Int(insns[i].address))
+ }
+ }
+ return out
+ }
+
+ /// Enumerate 4-insn `ADRP + LDRB + UBFX (width=1) + RET` functions —
+ /// the "return one bit of one byte global" shape used as the
+ /// precondition feature-check. Any bit position is accepted; only the
+ /// width-1 extract is enforced.
+ private func enumerateBitGetters() -> Set<Int> {
+ var out = Set<Int>()
+ for insns in chunkedDisasm() {
+ guard insns.count >= 4 else { continue }
+ for i in 0 ..< (insns.count - 3) {
+ let mnems = [
+ insns[i].mnemonic, insns[i + 1].mnemonic,
+ insns[i + 2].mnemonic, insns[i + 3].mnemonic,
+ ]
+ guard mnems == ["adrp", "ldrb", "ubfx", "ret"] else { continue }
+ guard
+ let det = insns[i + 2].aarch64,
+ det.operands.count >= 4,
+ det.operands[3].type == AARCH64_OP_IMM,
+ det.operands[3].imm == 1
+ else { continue }
+ out.insert(Int(insns[i].address))
+ }
+ }
+ return out
+ }
+
+ /// Enumerate "panic block" call sites: 3-insn sequence of
+ /// `BL <hash_getter>; MOV W?, #<imm>; BL <anything>`. Returns the file
+ /// offset of the first BL in each such triple.
+ private func enumeratePanicBlocks(hashGetters: Set<Int>) -> Set<Int> {
+ var out = Set<Int>()
+ for insns in chunkedDisasm() {
+ guard insns.count >= 3 else { continue }
+ for i in 0 ..< (insns.count - 2) {
+ guard
+ insns[i].mnemonic == "bl",
+ (insns[i + 1].mnemonic == "mov" || insns[i + 1].mnemonic == "movz"),
+ insns[i + 2].mnemonic == "bl"
+ else { continue }
+ guard
+ let det = insns[i].aarch64,
+ det.operands.count >= 1,
+ det.operands[0].type == AARCH64_OP_IMM
+ else { continue }
+ let blTarget = Int(det.operands[0].imm)
+ guard hashGetters.contains(blTarget) else { continue }
+ out.insert(Int(insns[i].address))
+ }
+ }
+ return out
+ }
+}
diff --git a/sources/FirmwarePatcher/IBoot/Patches/IBootPatchImage4Callback.swift b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchImage4Callback.swift
new file mode 100644
index 00000000..998da501
--- /dev/null
+++ b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchImage4Callback.swift
@@ -0,0 +1,68 @@
+// IBootPatchImage4Callback.swift — image4_validate_property_callback bypass.
+//
+// Part of IBootPatcher; see IBootPatcher.swift for the patch schedule by mode.
+
+import Capstone
+import Foundation
+
+extension IBootPatcher {
+ // MARK: - 2. image4_validate_property_callback
+
+ /// Find the b.ne + mov x0, x22 pattern with a preceding cmp.
+ /// Patch: b.ne → NOP, mov x0, x22 → mov x0, #0.
+ /// Python: `patch_image4_callback()`
+ func patchImage4Callback() {
+ var candidates: [(addr: Int, hasNeg1: Bool)] = []
+
+ for insns in chunkedDisasm() {
+ let count = insns.count
+ guard count >= 2 else { continue }
+ for i in 0 ..< count - 1 {
+ let a = insns[i]
+ let b = insns[i + 1]
+
+ // Must be: b.ne followed immediately by mov x0, x22
+ guard a.mnemonic == "b.ne" else { continue }
+ guard b.mnemonic == "mov", b.operandString == "x0, x22" else { continue }
+
+ let addr = Int(a.address)
+
+ // There must be a cmp within the 8 preceding instructions
+ let lookback = max(0, i - 8)
+ let hasCmp = insns[lookback ..< i].contains { $0.mnemonic == "cmp" }
+ guard hasCmp else { continue }
+
+ // Check if a movn w22 / mov w22, #-1 appears within 64 insns before (prefer this candidate)
+ let far = max(0, i - 64)
+ let hasNeg1 = insns[far ..< i].contains { insn in
+ if insn.mnemonic == "movn", insn.operandString.hasPrefix("w22,") {
+ return true
+ }
+ if insn.mnemonic == "mov", insn.operandString.contains("w22"),
+ insn.operandString.contains("#-1") || insn.operandString.contains("#0xffffffff")
+ {
+ return true
+ }
+ return false
+ }
+
+ candidates.append((addr: addr, hasNeg1: hasNeg1))
+ }
+ }
+
+ if candidates.isEmpty {
+ if verbose { print(" [-] image4 callback: pattern not found") }
+ return
+ }
+
+ // Prefer the candidate that has a movn w22 (error return path)
+ let off: Int = if let preferred = candidates.first(where: { $0.hasNeg1 }) {
+ preferred.addr
+ } else {
+ candidates.last!.addr
+ }
+
+ emit(off, ARM64.nop, id: "\(component).image4_callback_bne", description: "image4 callback: b.ne → nop")
+ emit(off + 4, ARM64.movX0_0, id: "\(component).image4_callback_mov", description: "image4 callback: mov x0,x22 → mov x0,#0")
+ }
+}
diff --git a/sources/FirmwarePatcher/IBoot/Patches/IBootPatchPanicBypass.swift b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchPanicBypass.swift
new file mode 100644
index 00000000..21194ee6
--- /dev/null
+++ b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchPanicBypass.swift
@@ -0,0 +1,50 @@
+// IBootPatchPanicBypass.swift — LLB panic-path bypass.
+//
+// Part of IBootPatcher; see IBootPatcher.swift for the patch schedule by mode.
+
+import Capstone
+import Foundation
+
+extension IBootPatcher {
+ // MARK: - 5. Panic Bypass (LLB only)
+
+ /// Find `mov w8, #0x328; movk w8, #0x40, lsl #16; ...; bl X; cbnz w0`
+ /// and NOP the cbnz.
+ /// Python: `patch_panic_bypass()`
+ func patchPanicBypass() {
+ let mov328 = encodedMovW8(0x328)
+ let locs = buffer.findAll(mov328)
+
+ for loc in locs {
+ // Verify movk w8, #0x40, lsl #16 follows
+ guard let nextInsn = disasm.disassembleOne(in: buffer.original, at: loc + 4) else { continue }
+ guard nextInsn.mnemonic == "movk",
+ nextInsn.operandString.contains("w8"),
+ nextInsn.operandString.contains("#0x40"),
+ nextInsn.operandString.contains("lsl #16") else { continue }
+
+ // Walk forward (up to 7 instructions past the movk) to find bl; cbnz w0
+ var step = loc + 8
+ while step < loc + 32 {
+ guard let i = disasm.disassembleOne(in: buffer.original, at: step) else {
+ step += 4
+ continue
+ }
+ if i.mnemonic == "bl" {
+ if let ni = disasm.disassembleOne(in: buffer.original, at: step + 4),
+ ni.mnemonic == "cbnz"
+ {
+ emit(step + 4, ARM64.nop,
+ id: "\(component).panic_bypass",
+ description: "panic bypass: NOP cbnz w0")
+ return
+ }
+ break // bl found but no cbnz — keep scanning other mov candidates
+ }
+ step += 4
+ }
+ }
+
+ if verbose { print(" [-] panic bypass: pattern not found") }
+ }
+}
diff --git a/sources/FirmwarePatcher/IBoot/Patches/IBootPatchRootfsBypass.swift b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchRootfsBypass.swift
new file mode 100644
index 00000000..a797fce3
--- /dev/null
+++ b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchRootfsBypass.swift
@@ -0,0 +1,126 @@
+// IBootPatchRootfsBypass.swift — LLB rootfs signature/size verification bypass.
+//
+// Part of IBootPatcher; see IBootPatcher.swift for the patch schedule by mode.
+
+import Capstone
+import Foundation
+
+extension IBootPatcher {
+ // MARK: - 4. Rootfs Bypass (LLB only)
+
+ /// Apply all five rootfs bypass patches.
+ /// Python: `patch_rootfs_bypass()`
+ func patchRootfssBypass() {
+ // 4a: cbz/cbnz before error code 0x3B7 → unconditional b
+ patchCbzBeforeError(errorCode: 0x3B7, description: "rootfs: skip sig check (0x3B7)")
+ // 4b: NOP b.hs after cmp x8, #0x400
+ patchBhsAfterCmp0x400()
+ // 4c: cbz/cbnz before error code 0x3C2 → unconditional b
+ patchCbzBeforeError(errorCode: 0x3C2, description: "rootfs: skip sig verify (0x3C2)")
+ // 4d: NOP cbz x8 null check (ldr x8, [xN, #0x78])
+ patchNullCheck0x78()
+ // 4e: cbz/cbnz before error code 0x110 → unconditional b
+ patchCbzBeforeError(errorCode: 0x110, description: "rootfs: skip size verify (0x110)")
+ }
+
+ /// Find unique `mov w8, #<errorCode>` and convert the cbz/cbnz 4 bytes before
+ /// it into an unconditional branch to the same target.
+ /// Python: `_patch_cbz_before_error()`
+ private func patchCbzBeforeError(errorCode: UInt32, description: String) {
+ let pattern = encodedMovW8(errorCode)
+ let locs = buffer.findAll(pattern)
+
+ guard locs.count == 1 else {
+ if verbose {
+ print(" [-] \(description): expected 1 'mov w8, #0x\(String(errorCode, radix: 16))', found \(locs.count)")
+ }
+ return
+ }
+
+ let errOff = locs[0]
+ let cbzOff = errOff - 4
+
+ guard let insn = disasm.disassembleOne(in: buffer.original, at: cbzOff) else {
+ if verbose { print(" [-] \(description): no instruction at 0x\(String(format: "%X", cbzOff))") }
+ return
+ }
+ guard insn.mnemonic == "cbz" || insn.mnemonic == "cbnz" else {
+ if verbose { print(" [-] \(description): expected cbz/cbnz at 0x\(String(format: "%X", cbzOff)), got \(insn.mnemonic)") }
+ return
+ }
+
+ // Extract branch target from the operand string (last operand is the immediate)
+ guard let detail = insn.aarch64, detail.operands.count >= 2 else { return }
+ let target = Int(detail.operands[1].imm)
+
+ guard let bInsn = ARM64Encoder.encodeB(from: cbzOff, to: target) else {
+ if verbose { print(" [-] \(description): B encoding out of range") }
+ return
+ }
+
+ emit(cbzOff, bInsn, id: "\(component).rootfs_cbz_0x\(String(errorCode, radix: 16))", description: description)
+ }
+
+ /// NOP the `b.hs` of the unique `cmp x8,#0x400 ; b.hs` rootfs size gate.
+ /// Anchoring on the cmp+b.hs pair disambiguates 26.4's three `cmp x8,#0x400`
+ /// (the other two are followed by `b.hi`); 26.1/26.3 have just the one.
+ /// Python: `_patch_bhs_after_cmp_0x400()`
+ private func patchBhsAfterCmp0x400() {
+ var bhsSites: [Int] = []
+ for insns in chunkedDisasm() {
+ for insn in insns where insn.mnemonic == "cmp" && insn.operandString == "x8, #0x400" {
+ let bhsOff = Int(insn.address) + 4
+ guard let next = disasm.disassembleOne(in: buffer.original, at: bhsOff),
+ next.mnemonic == "b.hs" else { continue }
+ if !bhsSites.contains(bhsOff) { bhsSites.append(bhsOff) }
+ }
+ }
+
+ guard bhsSites.count == 1 else {
+ if verbose { print(" [-] rootfs b.hs: expected 1 'cmp x8,#0x400 ; b.hs' pair, found \(bhsSites.count)") }
+ return
+ }
+
+ emit(bhsSites[0], ARM64.nop, id: "\(component).rootfs_bhs_0x400", description: "rootfs: NOP b.hs size check (0x400)")
+ }
+
+ /// Find `ldr xR, [xN, #0x78]; cbz xR` preceding the unique `mov w8, #0x110`
+ /// and NOP the cbz.
+ /// Python: `_patch_null_check_0x78()`
+ private func patchNullCheck0x78() {
+ let pattern = encodedMovW8(0x110)
+ let locs = buffer.findAll(pattern)
+
+ guard locs.count == 1 else {
+ if verbose { print(" [-] rootfs null check: expected 1 'mov w8, #0x110', found \(locs.count)") }
+ return
+ }
+
+ let errOff = locs[0]
+
+ // Walk backwards from errOff to find ldr x?, [xN, #0x78]; cbz x?
+ let scanStart = max(errOff - 0x300, 0)
+ var scan = errOff - 4
+ while scan >= scanStart {
+ guard let i1 = disasm.disassembleOne(in: buffer.original, at: scan),
+ let i2 = disasm.disassembleOne(in: buffer.original, at: scan + 4)
+ else {
+ scan -= 4
+ continue
+ }
+
+ if i1.mnemonic == "ldr",
+ i1.operandString.contains("#0x78"),
+ i2.mnemonic == "cbz",
+ i2.operandString.hasPrefix("x")
+ {
+ emit(scan + 4, ARM64.nop, id: "\(component).rootfs_null_check_0x78",
+ description: "rootfs: NOP cbz x8 null check (#0x78)")
+ return
+ }
+ scan -= 4
+ }
+
+ if verbose { print(" [-] rootfs null check: ldr+cbz #0x78 pattern not found") }
+ }
+}
diff --git a/sources/FirmwarePatcher/IBoot/Patches/IBootPatchSerialLabels.swift b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchSerialLabels.swift
new file mode 100644
index 00000000..787a4e68
--- /dev/null
+++ b/sources/FirmwarePatcher/IBoot/Patches/IBootPatchSerialLabels.swift
@@ -0,0 +1,60 @@
+// IBootPatchSerialLabels.swift — iBoot serial banner label patch.
+//
+// Part of IBootPatcher; see IBootPatcher.swift for the patch schedule by mode.
+
+import Foundation
+
+extension IBootPatcher {
+ // MARK: - 1. Serial Labels
+
+ /// Find the two long '====...' banner runs and write the mode label into each.
+ /// Python: `patch_serial_labels()`
+ func patchSerialLabels() {
+ let labelStr = switch mode {
+ case .ibss: "Loaded iBSS"
+ case .ibec: "Loaded iBEC"
+ case .llb: "Loaded LLB"
+ }
+ guard let labelBytes = labelStr.data(using: .ascii) else { return }
+
+ // Collect all runs of '=' (>=20 chars) — same logic as Python.
+ let raw = buffer.original
+ var eqRuns: [Int] = []
+ var i = raw.startIndex
+
+ while i < raw.endIndex {
+ if raw[i] == UInt8(ascii: "=") {
+ let start = i
+ while i < raw.endIndex, raw[i] == UInt8(ascii: "=") {
+ i = raw.index(after: i)
+ }
+ let runLen = raw.distance(from: start, to: i)
+ if runLen >= 20 {
+ eqRuns.append(raw.distance(from: raw.startIndex, to: start))
+ }
+ } else {
+ i = raw.index(after: i)
+ }
+ }
+
+ if eqRuns.count < 2 {
+ var labelCount = 0
+ var searchStart = raw.startIndex
+ while let range = raw.range(of: labelBytes, in: searchStart ..< raw.endIndex) {
+ labelCount += 1
+ searchStart = range.upperBound
+ }
+ if labelCount >= 2 {
+ if verbose { print(" [*] serial labels: already present, skipping") }
+ return
+ }
+ if verbose { print(" [-] serial labels: <2 banner runs found") }
+ return
+ }
+
+ for runStart in eqRuns.prefix(2) {
+ let writeOff = runStart + 1 // Python: run_start + 1
+ emitString(writeOff, labelBytes, id: "\(component).serial_label", description: "serial label")
+ }
+ }
+}
diff --git a/sources/FirmwarePatcher/Pipeline/FirmwarePipeline.swift b/sources/FirmwarePatcher/Pipeline/FirmwarePipeline.swift
index 8e83a4d5..998b7b1c 100644
--- a/sources/FirmwarePatcher/Pipeline/FirmwarePipeline.swift
+++ b/sources/FirmwarePatcher/Pipeline/FirmwarePipeline.swift
@@ -11,6 +11,9 @@
// .exp — JB + experimental: KernelEXPPatcher (hv_vmm rename) +
// DeviceTreePatcher identity properties (D47AP/iPhone17,3).
// Other variants are NOT affected by experimental patches.
+//
+// The component catalogue lives in FirmwarePipelineComponents.swift and the
+// Restore-directory/firmware-file lookup in FirmwarePipelineDiscovery.swift.
import Darwin
import Foundation
@@ -206,372 +209,6 @@ public final class FirmwarePipeline {
return (currentData, componentRecords)
}
- // MARK: - Component List Builder
-
- /// Build the ordered component list based on the variant.
- ///
- /// - Parameters:
- /// - restoreDir: The `*Restore*` directory `patchAll()` resolved, captured by value
- /// into the patcher factory closures below.
- /// - iosBaseIs18: True when the iPhone base is iOS 18.x (read from
- /// `iPhone-BuildManifest.plist`). Gates the skywalk-netagent boot-arg workaround
- /// (18.x-specific mDNSResponder crash-loop).
- /// - iosBaseIs27: True when the iPhone base is iOS 27.x. Gates the iOS-27-only JB
- /// kernel patches (`KernelJBPatcher.applyIOS27`); false for 18.x/26.x so those
- /// bases are byte-identical to pre-branch.
- /// - cloudOSIsFridaCapable: True when the cloudOS kernel is 26.4+; gates the opt-in
- /// Frida kernel patches.
- func buildComponentList(
- restoreDir: URL,
- iosBaseIs18: Bool,
- iosBaseIs27: Bool,
- cloudOSIsFridaCapable: Bool
- ) -> [ComponentDescriptor] {
- var components: [ComponentDescriptor] = []
-
- // Captured by value into the patcher factory closures below (avoids
- // capturing self). Always on for iOS 18 bases: 18.6.2's runningboardd/
- // SpringBoard trips GUARD_TYPE_MACH_PORT flavor 10, crash-looping the
- // UI, and the VM won't boot without this patch there. Otherwise off by
- // default and opt-in via `forceExcGuard` (--force-exc-guard):
- // some third-party apps shipping crash-reporting/RASP SDKs call
- // task_swap_exception_ports(), which the research kernel can enforce
- // as a fatal EXC_GUARD/GUARD_TYPE_MACH_PORT/KOBJECT_REPLY_PORT_SEMANTICS
- // violation (see upstream issue #291 / PR #297) — but this isn't
- // required for the VM itself to boot on 26.x, so it stays opt-in
- // rather than always-on for regular/jb/exp.
- let applyExcGuard = iosBaseIs18 || forceExcGuard
-
- // Same capture-by-value; true only for iOS 27 bases. Gates the iOS-27-only
- // JB kernel patches so 18.x/26.x bases apply none of them.
- let applyIOS27 = iosBaseIs27
-
- // Opt-in Frida Stalker kernel relaxations (--frida), gated to cloudOS 26.4+.
- let applyFrida = enableFrida && cloudOSIsFridaCapable
-
- // iOS 18 bases: disable the skywalk flowswitch netagents via boot-arg so
- // Network.framework uses the BSD path (the 26.1-kernel skywalk
- // channel-create traps in the 18.x Network.framework and crash-loops
- // mDNSResponder → no DNS). Empty on 26.x bases (stock boot-args).
- let extraBootArgs = iosBaseIs18 ? "if_attach_nx=0x3" : ""
-
- // 1. AVPBooter — always present, lives in VM root.
- // Patched for every non-less variant (regular/dev/jb/exp).
- components.append(ComponentDescriptor(
- name: "AVPBooter",
- inRestoreDir: false,
- searchPatterns: ["AVPBooter*.bin"],
- patcherFactories: {
- if variant != .less {
- return [
- { data, verbose in
- AVPBooterPatcher(data: data, verbose: verbose)
- },
- ]
- }
- return []
- }()
- ))
-
- // 2. iBSS — JB and EXP variants run the base iBSS patcher, then the nonce-skip extension.
- components.append(ComponentDescriptor(
- name: "iBSS",
- inRestoreDir: true,
- searchPatterns: ["Firmware/dfu/iBSS.vresearch101.RELEASE.im4p"],
- patcherFactories: {
- return switch variant {
- case .less:
- []
- case .regular, .dev:
- [{ data, verbose in
- IBootPatcher(data: data, mode: .ibss, verbose: verbose)
- }]
- case .jb, .exp:
- [
- { data, verbose in
- IBootPatcher(data: data, mode: .ibss, verbose: verbose)
- },
- { data, verbose in
- IBootJBPatcher(data: data, mode: .ibss, verbose: verbose)
- },
- ]
- }
- }()
- ))
-
- // 3. iBEC - Not required by the less variant, still added for the serial logs.
- components.append(ComponentDescriptor(
- name: "iBEC",
- inRestoreDir: true,
- searchPatterns: ["Firmware/dfu/iBEC.vresearch101.RELEASE.im4p"],
- patcherFactories: [{ data, verbose in
- let p = IBootPatcher(data: data, mode: .ibec, verbose: verbose)
- p.extraBootArgs = extraBootArgs
- return p
- }]
- ))
-
- // 4. LLB - Not required by the less variant, still added for the serial logs.
- components.append(ComponentDescriptor(
- name: "LLB",
- inRestoreDir: true,
- searchPatterns: ["Firmware/all_flash/LLB.vresearch101.RELEASE.im4p"],
- patcherFactories: [{ data, verbose in
- let p = IBootPatcher(data: data, mode: .llb, verbose: verbose)
- p.extraBootArgs = extraBootArgs
- return p
- }]
- ))
-
- // 5. TXM — dev/jb/exp variants use TXMDevPatcher (adds entitlements, debugger, dev-mode)
- components.append(ComponentDescriptor(
- name: "TXM",
- inRestoreDir: true,
- searchPatterns: ["Firmware/txm.iphoneos.research.im4p"],
- patcherFactories: {
- return switch variant {
- case .less:
- []
- case .regular:
- [{ data, verbose in
- TXMPatcher(data: data, verbose: verbose)
- }]
- case .dev, .jb, .exp:
- [{ data, verbose in
- TXMDevPatcher(data: data, verbose: verbose)
- }]
- }
- }()
- ))
-
- // 6. Kernel — JB variant runs base kernel patches first, then JB extensions.
- // EXP variant runs base + JB + experimental extensions (hv_vmm rename).
- components.append(ComponentDescriptor(
- name: "kernelcache",
- inRestoreDir: true,
- searchPatterns: ["kernelcache.research.vphone600"],
- patcherFactories: {
- return switch variant {
- case .less:
- []
- case .regular:
- [{ data, verbose in
- KernelPatcher(data: data, verbose: verbose, isDev: false, applyExcGuard: applyExcGuard)
- }]
- case .dev:
- [{ data, verbose in
- KernelPatcher(data: data, verbose: verbose, isDev: true)
- }]
- case .jb:
- [
- { data, verbose in
- KernelPatcher(data: data, verbose: verbose, isDev: false, applyExcGuard: applyExcGuard)
- },
- { data, verbose in
- let p = KernelJBPatcher(data: data, verbose: verbose)
- p.applyIOS27 = applyIOS27
- p.applyFrida = applyFrida
- return p
- },
- ]
- case .exp:
- [
- { data, verbose in
- KernelPatcher(data: data, verbose: verbose, isDev: false, applyExcGuard: applyExcGuard)
- },
- { data, verbose in
- let p = KernelJBPatcher(data: data, verbose: verbose)
- p.applyIOS27 = applyIOS27
- p.applyFrida = applyFrida
- return p
- },
- { data, verbose in
- KernelEXPPatcher(data: data, verbose: verbose)
- },
- ]
- }
- }()
- ))
-
- // 7. DeviceTree — base property patches for every variant. EXP additionally
- // applies the 8 identity-rewrite properties (Tier 1b + 1c) that flip the
- // device's userland-visible identity toward D47AP / iPhone17,3.
- let dtIncludeIdentity = variant == .exp
- components.append(ComponentDescriptor(
- name: "DeviceTree",
- inRestoreDir: true,
- searchPatterns: ["Firmware/all_flash/DeviceTree.vphone600ap.im4p"],
- patcherFactories: [{ data, verbose in
- DeviceTreePatcher(
- data: data,
- verbose: verbose,
- includeIdentityPatches: dtIncludeIdentity
- )
- }]
- ))
-
- // 8. Filesystem
- components.append(ComponentDescriptor(
- name: "Filesystem",
- inRestoreDir: true,
- searchPatterns: ["BuildManifest.plist"],
- patcherFactories: {
- return switch variant {
- case .less:
- [{ data, verbose in
- CryptexFilesystemPatcher(buildManiest: data, restoreDir: restoreDir, verbose: verbose, noBinpack: self.noBinpack, noVphoned: self.noVphoned)
- }]
- case .regular, .dev, .jb, .exp:
- []
- }
- }()
- ))
-
- // 9. Firmware Manifest - Only required when excluding the img4 signature patches.
- components.append(ComponentDescriptor(
- name: "Manifest",
- inRestoreDir: true,
- searchPatterns: ["BuildManifest.plist"],
- patcherFactories: {
- return switch variant {
- case .less:
- [{ data, verbose in
- ManifestHashPatcher(data: data, restoreDir: restoreDir, verbose: verbose)
- }]
- case .regular, .dev, .jb, .exp:
- []
- }
- }()
- ))
-
- return components
- }
-
- // MARK: - File Discovery
-
- /// Find the `*Restore*` subdirectory inside the VM directory.
- /// Mirrors Python `find_restore_dir`.
- func findRestoreDirectory() throws -> URL {
- let fm = FileManager.default
- let contents = try fm.contentsOfDirectory(
- at: vmDirectory,
- includingPropertiesForKeys: [.isDirectoryKey, .contentModificationDateKey]
- )
- .filter { (try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true }
- .filter { $0.lastPathComponent.contains("Restore") }
- .sorted(by: compareRestoreDirectories)
-
- guard let restoreDir = contents.first else {
- throw PatcherError.fileNotFound("Restore directory in \(vmDirectory.path). Run make fw_prepare first.")
- }
- return restoreDir
- }
-
- /// `ProductVersion` from a manifest in `restoreDir`, or nil if absent/unreadable.
- static func readProductVersion(_ restoreDir: URL, manifest: String) -> String? {
- let url = restoreDir.appendingPathComponent(manifest)
- guard let data = try? Data(contentsOf: url),
- let plist = try? PropertyListSerialization.propertyList(from: data, format: nil),
- let dict = plist as? [String: Any],
- let version = dict["ProductVersion"] as? String
- else { return nil }
- return version
- }
-
- /// iPhone base version (`iPhone-BuildManifest.plist`, preserved by fw_prepare).
- static func readBaseProductVersion(_ restoreDir: URL) -> String? {
- readProductVersion(restoreDir, manifest: "iPhone-BuildManifest.plist")
- }
-
- /// cloudOS/kernel version (the live `BuildManifest.plist`).
- static func readCloudOSProductVersion(_ restoreDir: URL) -> String? {
- readProductVersion(restoreDir, manifest: "BuildManifest.plist")
- }
-
- /// 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) }),
- let vMajor = parts.first else { return false }
- return vMajor != major ? vMajor > major : (parts.count > 1 ? parts[1] : 0) >= minor
- }
-
- private func compareRestoreDirectories(_ lhs: URL, _ rhs: URL) -> Bool {
- let leftName = lhs.lastPathComponent
- let rightName = rhs.lastPathComponent
-
- if let left = parseRestoreDirectoryName(leftName),
- let right = parseRestoreDirectoryName(rightName)
- {
- if left.version != right.version {
- return left.version.lexicographicallyPrecedes(right.version, by: >)
- }
- if left.build != right.build {
- return left.build.compare(right.build, options: .numeric) == .orderedDescending
- }
- }
-
- let leftDate = (try? lhs.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast
- let rightDate = (try? rhs.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast
- if leftDate != rightDate {
- return leftDate > rightDate
- }
- return leftName > rightName
- }
-
- private func parseRestoreDirectoryName(_ name: String) -> (version: [Int], build: String)? {
- let pattern = #"_([0-9]+(?:\.[0-9]+)*)_([0-9A-Za-z]+)_Restore$"#
- guard let regex = try? NSRegularExpression(pattern: pattern) else { return nil }
- let range = NSRange(name.startIndex..., in: name)
- guard let match = regex.firstMatch(in: name, range: range),
- match.numberOfRanges == 3,
- let versionRange = Range(match.range(at: 1), in: name),
- let buildRange = Range(match.range(at: 2), in: name)
- else { return nil }
-
- let version = name[versionRange]
- .split(separator: ".")
- .compactMap { Int($0) }
- let build = String(name[buildRange])
- guard !version.isEmpty else { return nil }
- return (version, build)
- }
-
- /// Find a firmware file by trying glob-style patterns under `baseDir`.
- /// Mirrors Python `find_file`.
- func findFile(in baseDir: URL, patterns: [String], label: String) throws -> URL {
- let fm = FileManager.default
- for pattern in patterns {
- if pattern.contains("*") || pattern.contains("?") || pattern.contains("[") {
- var matches: [URL] = []
- if !pattern.contains("/") {
- let urls = try fm.contentsOfDirectory(at: baseDir, includingPropertiesForKeys: [.isRegularFileKey])
- for url in urls where fnmatch(pattern, url.lastPathComponent, 0) == 0 {
- matches.append(url)
- }
- } else {
- let enumerator = fm.enumerator(at: baseDir, includingPropertiesForKeys: [.isRegularFileKey])
- while let url = enumerator?.nextObject() as? URL {
- guard url.path.hasPrefix(baseDir.path + "/") else { continue }
- let rel = String(url.path.dropFirst(baseDir.path.count + 1))
- if fnmatch(pattern, rel, 0) == 0 {
- matches.append(url)
- }
- }
- }
- if let first = matches.sorted(by: { $0.path < $1.path }).first {
- return first
- }
- } else {
- let candidate = baseDir.appendingPathComponent(pattern)
- if fm.fileExists(atPath: candidate.path) {
- return candidate
- }
- }
- }
- let searched = patterns.map { baseDir.appendingPathComponent($0).path }.joined(separator: "\n ")
- throw PatcherError.fileNotFound("\(label). Looked in:\n \(searched)")
- }
-
// MARK: - Data Extraction
/// Extract the patched data from a patcher's internal buffer.
diff --git a/sources/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift b/sources/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
new file mode 100644
index 00000000..8edd3708
--- /dev/null
+++ b/sources/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
@@ -0,0 +1,252 @@
+// FirmwarePipelineComponents.swift — Ordered boot-chain component list per variant.
+//
+// Owns the catalogue half of the pipeline: which firmware components are patched,
+// in which order, where their files are searched for, and which patchers run over
+// each one for the selected ``FirmwarePipeline/Variant``.
+//
+// Split out of FirmwarePipeline.swift; the execution loop stays there.
+
+import Foundation
+
+extension FirmwarePipeline {
+ // MARK: - Component List Builder
+
+ /// Build the ordered component list based on the variant.
+ ///
+ /// - Parameters:
+ /// - restoreDir: The `*Restore*` directory `patchAll()` resolved, captured by value
+ /// into the patcher factory closures below.
+ /// - iosBaseIs18: True when the iPhone base is iOS 18.x (read from
+ /// `iPhone-BuildManifest.plist`). Gates the skywalk-netagent boot-arg workaround
+ /// (18.x-specific mDNSResponder crash-loop).
+ /// - iosBaseIs27: True when the iPhone base is iOS 27.x. Gates the iOS-27-only JB
+ /// kernel patches (`KernelJBPatcher.applyIOS27`); false for 18.x/26.x so those
+ /// bases are byte-identical to pre-branch.
+ /// - cloudOSIsFridaCapable: True when the cloudOS kernel is 26.4+; gates the opt-in
+ /// Frida kernel patches.
+ func buildComponentList(
+ restoreDir: URL,
+ iosBaseIs18: Bool,
+ iosBaseIs27: Bool,
+ cloudOSIsFridaCapable: Bool
+ ) -> [ComponentDescriptor] {
+ var components: [ComponentDescriptor] = []
+
+ // Captured by value into the patcher factory closures below (avoids
+ // capturing self). Always on for iOS 18 bases: 18.6.2's runningboardd/
+ // SpringBoard trips GUARD_TYPE_MACH_PORT flavor 10, crash-looping the
+ // UI, and the VM won't boot without this patch there. Otherwise off by
+ // default and opt-in via `forceExcGuard` (--force-exc-guard):
+ // some third-party apps shipping crash-reporting/RASP SDKs call
+ // task_swap_exception_ports(), which the research kernel can enforce
+ // as a fatal EXC_GUARD/GUARD_TYPE_MACH_PORT/KOBJECT_REPLY_PORT_SEMANTICS
+ // violation (see upstream issue #291 / PR #297) — but this isn't
+ // required for the VM itself to boot on 26.x, so it stays opt-in
+ // rather than always-on for regular/jb/exp.
+ let applyExcGuard = iosBaseIs18 || forceExcGuard
+
+ // Same capture-by-value; true only for iOS 27 bases. Gates the iOS-27-only
+ // JB kernel patches so 18.x/26.x bases apply none of them.
+ let applyIOS27 = iosBaseIs27
+
+ // Opt-in Frida Stalker kernel relaxations (--frida), gated to cloudOS 26.4+.
+ let applyFrida = enableFrida && cloudOSIsFridaCapable
+
+ // iOS 18 bases: disable the skywalk flowswitch netagents via boot-arg so
+ // Network.framework uses the BSD path (the 26.1-kernel skywalk
+ // channel-create traps in the 18.x Network.framework and crash-loops
+ // mDNSResponder → no DNS). Empty on 26.x bases (stock boot-args).
+ let extraBootArgs = iosBaseIs18 ? "if_attach_nx=0x3" : ""
+
+ // 1. AVPBooter — always present, lives in VM root.
+ // Patched for every non-less variant (regular/dev/jb/exp).
+ components.append(ComponentDescriptor(
+ name: "AVPBooter",
+ inRestoreDir: false,
+ searchPatterns: ["AVPBooter*.bin"],
+ patcherFactories: {
+ if variant != .less {
+ return [
+ { data, verbose in
+ AVPBooterPatcher(data: data, verbose: verbose)
+ },
+ ]
+ }
+ return []
+ }()
+ ))
+
+ // 2. iBSS — JB and EXP variants run the base iBSS patcher, then the nonce-skip extension.
+ components.append(ComponentDescriptor(
+ name: "iBSS",
+ inRestoreDir: true,
+ searchPatterns: ["Firmware/dfu/iBSS.vresearch101.RELEASE.im4p"],
+ patcherFactories: {
+ return switch variant {
+ case .less:
+ []
+ case .regular, .dev:
+ [{ data, verbose in
+ IBootPatcher(data: data, mode: .ibss, verbose: verbose)
+ }]
+ case .jb, .exp:
+ [
+ { data, verbose in
+ IBootPatcher(data: data, mode: .ibss, verbose: verbose)
+ },
+ { data, verbose in
+ IBootJBPatcher(data: data, mode: .ibss, verbose: verbose)
+ },
+ ]
+ }
+ }()
+ ))
+
+ // 3. iBEC - Not required by the less variant, still added for the serial logs.
+ components.append(ComponentDescriptor(
+ name: "iBEC",
+ inRestoreDir: true,
+ searchPatterns: ["Firmware/dfu/iBEC.vresearch101.RELEASE.im4p"],
+ patcherFactories: [{ data, verbose in
+ let p = IBootPatcher(data: data, mode: .ibec, verbose: verbose)
+ p.extraBootArgs = extraBootArgs
+ return p
+ }]
+ ))
+
+ // 4. LLB - Not required by the less variant, still added for the serial logs.
+ components.append(ComponentDescriptor(
+ name: "LLB",
+ inRestoreDir: true,
+ searchPatterns: ["Firmware/all_flash/LLB.vresearch101.RELEASE.im4p"],
+ patcherFactories: [{ data, verbose in
+ let p = IBootPatcher(data: data, mode: .llb, verbose: verbose)
+ p.extraBootArgs = extraBootArgs
+ return p
+ }]
+ ))
+
+ // 5. TXM — dev/jb/exp variants use TXMDevPatcher (adds entitlements, debugger, dev-mode)
+ components.append(ComponentDescriptor(
+ name: "TXM",
+ inRestoreDir: true,
+ searchPatterns: ["Firmware/txm.iphoneos.research.im4p"],
+ patcherFactories: {
+ return switch variant {
+ case .less:
+ []
+ case .regular:
+ [{ data, verbose in
+ TXMPatcher(data: data, verbose: verbose)
+ }]
+ case .dev, .jb, .exp:
+ [{ data, verbose in
+ TXMDevPatcher(data: data, verbose: verbose)
+ }]
+ }
+ }()
+ ))
+
+ // 6. Kernel — JB variant runs base kernel patches first, then JB extensions.
+ // EXP variant runs base + JB + experimental extensions (hv_vmm rename).
+ components.append(ComponentDescriptor(
+ name: "kernelcache",
+ inRestoreDir: true,
+ searchPatterns: ["kernelcache.research.vphone600"],
+ patcherFactories: {
+ return switch variant {
+ case .less:
+ []
+ case .regular:
+ [{ data, verbose in
+ KernelPatcher(data: data, verbose: verbose, isDev: false, applyExcGuard: applyExcGuard)
+ }]
+ case .dev:
+ [{ data, verbose in
+ KernelPatcher(data: data, verbose: verbose, isDev: true)
+ }]
+ case .jb:
+ [
+ { data, verbose in
+ KernelPatcher(data: data, verbose: verbose, isDev: false, applyExcGuard: applyExcGuard)
+ },
+ { data, verbose in
+ let p = KernelJBPatcher(data: data, verbose: verbose)
+ p.applyIOS27 = applyIOS27
+ p.applyFrida = applyFrida
+ return p
+ },
+ ]
+ case .exp:
+ [
+ { data, verbose in
+ KernelPatcher(data: data, verbose: verbose, isDev: false, applyExcGuard: applyExcGuard)
+ },
+ { data, verbose in
+ let p = KernelJBPatcher(data: data, verbose: verbose)
+ p.applyIOS27 = applyIOS27
+ p.applyFrida = applyFrida
+ return p
+ },
+ { data, verbose in
+ KernelEXPPatcher(data: data, verbose: verbose)
+ },
+ ]
+ }
+ }()
+ ))
+
+ // 7. DeviceTree — base property patches for every variant. EXP additionally
+ // applies the 8 identity-rewrite properties (Tier 1b + 1c) that flip the
+ // device's userland-visible identity toward D47AP / iPhone17,3.
+ let dtIncludeIdentity = variant == .exp
+ components.append(ComponentDescriptor(
+ name: "DeviceTree",
+ inRestoreDir: true,
+ searchPatterns: ["Firmware/all_flash/DeviceTree.vphone600ap.im4p"],
+ patcherFactories: [{ data, verbose in
+ DeviceTreePatcher(
+ data: data,
+ verbose: verbose,
+ includeIdentityPatches: dtIncludeIdentity
+ )
+ }]
+ ))
+
+ // 8. Filesystem
+ components.append(ComponentDescriptor(
+ name: "Filesystem",
+ inRestoreDir: true,
+ searchPatterns: ["BuildManifest.plist"],
+ patcherFactories: {
+ return switch variant {
+ case .less:
+ [{ data, verbose in
+ CryptexFilesystemPatcher(buildManiest: data, restoreDir: restoreDir, verbose: verbose, noBinpack: self.noBinpack, noVphoned: self.noVphoned)
+ }]
+ case .regular, .dev, .jb, .exp:
+ []
+ }
+ }()
+ ))
+
+ // 9. Firmware Manifest - Only required when excluding the img4 signature patches.
+ components.append(ComponentDescriptor(
+ name: "Manifest",
+ inRestoreDir: true,
+ searchPatterns: ["BuildManifest.plist"],
+ patcherFactories: {
+ return switch variant {
+ case .less:
+ [{ data, verbose in
+ ManifestHashPatcher(data: data, restoreDir: restoreDir, verbose: verbose)
+ }]
+ case .regular, .dev, .jb, .exp:
+ []
+ }
+ }()
+ ))
+
+ return components
+ }
+}
diff --git a/sources/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift b/sources/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift
new file mode 100644
index 00000000..9f32fb71
--- /dev/null
+++ b/sources/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift
@@ -0,0 +1,140 @@
+// FirmwarePipelineDiscovery.swift — Locating the Restore directory, firmware files
+// and manifest versions.
+//
+// Owns the filesystem half of the pipeline: picking the newest `*Restore*` directory,
+// reading `ProductVersion` out of the base and cloudOS manifests, and resolving a
+// component's glob patterns to a concrete file URL.
+//
+// Split out of FirmwarePipeline.swift. `compareRestoreDirectories` and
+// `parseRestoreDirectoryName` stay `private` and live here with their only caller,
+// so nothing was widened by the move.
+
+import Darwin
+import Foundation
+
+extension FirmwarePipeline {
+ // MARK: - File Discovery
+
+ /// Find the `*Restore*` subdirectory inside the VM directory.
+ /// Mirrors Python `find_restore_dir`.
+ func findRestoreDirectory() throws -> URL {
+ let fm = FileManager.default
+ let contents = try fm.contentsOfDirectory(
+ at: vmDirectory,
+ includingPropertiesForKeys: [.isDirectoryKey, .contentModificationDateKey]
+ )
+ .filter { (try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true }
+ .filter { $0.lastPathComponent.contains("Restore") }
+ .sorted(by: compareRestoreDirectories)
+
+ guard let restoreDir = contents.first else {
+ throw PatcherError.fileNotFound("Restore directory in \(vmDirectory.path). Run make fw_prepare first.")
+ }
+ return restoreDir
+ }
+
+ /// `ProductVersion` from a manifest in `restoreDir`, or nil if absent/unreadable.
+ static func readProductVersion(_ restoreDir: URL, manifest: String) -> String? {
+ let url = restoreDir.appendingPathComponent(manifest)
+ guard let data = try? Data(contentsOf: url),
+ let plist = try? PropertyListSerialization.propertyList(from: data, format: nil),
+ let dict = plist as? [String: Any],
+ let version = dict["ProductVersion"] as? String
+ else { return nil }
+ return version
+ }
+
+ /// iPhone base version (`iPhone-BuildManifest.plist`, preserved by fw_prepare).
+ static func readBaseProductVersion(_ restoreDir: URL) -> String? {
+ readProductVersion(restoreDir, manifest: "iPhone-BuildManifest.plist")
+ }
+
+ /// cloudOS/kernel version (the live `BuildManifest.plist`).
+ static func readCloudOSProductVersion(_ restoreDir: URL) -> String? {
+ readProductVersion(restoreDir, manifest: "BuildManifest.plist")
+ }
+
+ /// 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) }),
+ let vMajor = parts.first else { return false }
+ return vMajor != major ? vMajor > major : (parts.count > 1 ? parts[1] : 0) >= minor
+ }
+
+ private func compareRestoreDirectories(_ lhs: URL, _ rhs: URL) -> Bool {
+ let leftName = lhs.lastPathComponent
+ let rightName = rhs.lastPathComponent
+
+ if let left = parseRestoreDirectoryName(leftName),
+ let right = parseRestoreDirectoryName(rightName)
+ {
+ if left.version != right.version {
+ return left.version.lexicographicallyPrecedes(right.version, by: >)
+ }
+ if left.build != right.build {
+ return left.build.compare(right.build, options: .numeric) == .orderedDescending
+ }
+ }
+
+ let leftDate = (try? lhs.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast
+ let rightDate = (try? rhs.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast
+ if leftDate != rightDate {
+ return leftDate > rightDate
+ }
+ return leftName > rightName
+ }
+
+ private func parseRestoreDirectoryName(_ name: String) -> (version: [Int], build: String)? {
+ let pattern = #"_([0-9]+(?:\.[0-9]+)*)_([0-9A-Za-z]+)_Restore$"#
+ guard let regex = try? NSRegularExpression(pattern: pattern) else { return nil }
+ let range = NSRange(name.startIndex..., in: name)
+ guard let match = regex.firstMatch(in: name, range: range),
+ match.numberOfRanges == 3,
+ let versionRange = Range(match.range(at: 1), in: name),
+ let buildRange = Range(match.range(at: 2), in: name)
+ else { return nil }
+
+ let version = name[versionRange]
+ .split(separator: ".")
+ .compactMap { Int($0) }
+ let build = String(name[buildRange])
+ guard !version.isEmpty else { return nil }
+ return (version, build)
+ }
+
+ /// Find a firmware file by trying glob-style patterns under `baseDir`.
+ /// Mirrors Python `find_file`.
+ func findFile(in baseDir: URL, patterns: [String], label: String) throws -> URL {
+ let fm = FileManager.default
+ for pattern in patterns {
+ if pattern.contains("*") || pattern.contains("?") || pattern.contains("[") {
+ var matches: [URL] = []
+ if !pattern.contains("/") {
+ let urls = try fm.contentsOfDirectory(at: baseDir, includingPropertiesForKeys: [.isRegularFileKey])
+ for url in urls where fnmatch(pattern, url.lastPathComponent, 0) == 0 {
+ matches.append(url)
+ }
+ } else {
+ let enumerator = fm.enumerator(at: baseDir, includingPropertiesForKeys: [.isRegularFileKey])
+ while let url = enumerator?.nextObject() as? URL {
+ guard url.path.hasPrefix(baseDir.path + "/") else { continue }
+ let rel = String(url.path.dropFirst(baseDir.path.count + 1))
+ if fnmatch(pattern, rel, 0) == 0 {
+ matches.append(url)
+ }
+ }
+ }
+ if let first = matches.sorted(by: { $0.path < $1.path }).first {
+ return first
+ }
+ } else {
+ let candidate = baseDir.appendingPathComponent(pattern)
+ if fm.fileExists(atPath: candidate.path) {
+ return candidate
+ }
+ }
+ }
+ let searched = patterns.map { baseDir.appendingPathComponent($0).path }.joined(separator: "\n ")
+ throw PatcherError.fileNotFound("\(label). Looked in:\n \(searched)")
+ }
+}
diff --git a/sources/vphone-cli/VPhoneControl.swift b/sources/vphone-cli/VPhoneControl.swift
index 3e030712..63ddd8cb 100644
--- a/sources/vphone-cli/VPhoneControl.swift
+++ b/sources/vphone-cli/VPhoneControl.swift
@@ -492,37 +492,6 @@ class VPhoneControl {
return "Installed \(localURL.lastPathComponent) through the built-in IPA installer."
}
- // MARK: - Keychain Operations
-
- struct KeychainResult {
- let items: [[String: Any]]
- let diagnostics: [String]
- }
-
- func listKeychainItems() async throws -> KeychainResult {
- let req: [String: Any] = ["t": "keychain_list"]
- let (resp, _) = try await sendRequest(req)
- guard let items = resp["items"] as? [[String: Any]] else {
- throw ControlError.protocolError("missing items in keychain response")
- }
- let diag = resp["diag"] as? [String] ?? []
- return KeychainResult(items: items, diagnostics: diag)
- }
-
- func addKeychainItem(
- account: String = "vphone-test", service: String = "vphone", password: String = "testpass123"
- ) async throws {
- let req: [String: Any] = [
- "t": "keychain_add", "account": account, "service": service, "password": password,
- ]
- let (resp, _) = try await sendRequest(req)
- let ok = resp["ok"] as? Bool ?? false
- if !ok {
- let msg = resp["msg"] as? String ?? "unknown error"
- throw ControlError.protocolError("keychain_add: \(msg)")
- }
- }
-
// MARK: - Clipboard
struct ClipboardContent {
@@ -590,100 +559,6 @@ class VPhoneControl {
}
}
- // MARK: - App Management
-
- struct AppInfo {
- let bundleId: String
- let name: String
- let version: String
- let type: String
- let state: String
- let pid: Int
- let path: String
- }
-
- func appList(filter: String = "all") async throws -> [AppInfo] {
- let (resp, _) = try await sendRequest(["t": "app_list", "filter": filter])
- guard let apps = resp["apps"] as? [[String: Any]] else {
- throw ControlError.protocolError("missing apps in response")
- }
- return apps.map { app in
- AppInfo(
- bundleId: app["bundle_id"] as? String ?? "",
- name: app["name"] as? String ?? "",
- version: app["version"] as? String ?? "",
- type: app["type"] as? String ?? "",
- state: app["state"] as? String ?? "",
- pid: app["pid"] as? Int ?? 0,
- path: app["path"] as? String ?? ""
- )
- }
- }
-
- func appLaunch(bundleId: String, url: String? = nil) async throws -> Int {
- var req: [String: Any] = ["t": "app_launch", "bundle_id": bundleId]
- if let url { req["url"] = url }
- let (resp, _) = try await sendRequest(req)
- return resp["pid"] as? Int ?? 0
- }
-
- func appTerminate(bundleId: String) async throws {
- _ = try await sendRequest(["t": "app_terminate", "bundle_id": bundleId])
- }
-
- func appForeground() async throws -> (bundleId: String, name: String, pid: Int) {
- let (resp, _) = try await sendRequest(["t": "app_foreground"])
- return (
- bundleId: resp["bundle_id"] as? String ?? "",
- name: resp["name"] as? String ?? "",
- pid: resp["pid"] as? Int ?? 0
- )
- }
-
- // MARK: - URL
-
- func openURL(_ url: String) async throws {
- let (resp, _) = try await sendRequest(["t": "open_url", "url": url])
- let ok = resp["ok"] as? Bool ?? false
- if !ok {
- let msg = resp["msg"] as? String ?? "failed to open URL"
- throw ControlError.guestError(msg)
- }
- }
-
- // MARK: - Settings
-
- func settingsGet(domain: String, key: String? = nil) async throws -> Any? {
- var req: [String: Any] = ["t": "settings_get", "domain": domain]
- if let key { req["key"] = key }
- let (resp, _) = try await sendRequest(req)
- return resp["value"]
- }
-
- func settingsSet(domain: String, key: String, value: Any, type: String? = nil) async throws {
- var req: [String: Any] = ["t": "settings_set", "domain": domain, "key": key, "value": value]
- if let type { req["type"] = type }
- _ = try await sendRequest(req)
- }
-
- func lowPowerMode(enabled: Bool) async throws {
- let (resp, _) = try await sendRequest(["t": "low_power_mode", "enabled": enabled])
- let ok = resp["ok"] as? Bool ?? false
- if !ok {
- throw ControlError.guestError("low_power_mode: failed to set state on guest")
- }
- }
-
- // MARK: - Accessibility
-
- func accessibilityTree(depth: Int = -1) async throws -> [String: Any] {
- guard guestCaps.contains("accessibility_tree") else {
- throw ControlError.unsupportedCapability("accessibility_tree")
- }
- let (resp, _) = try await sendRequest(["t": "accessibility_tree", "depth": depth])
- return resp
- }
-
// MARK: - Location
func sendLocation(
diff --git a/sources/vphone-cli/VPhoneControlApps.swift b/sources/vphone-cli/VPhoneControlApps.swift
new file mode 100644
index 00000000..ccfbb947
--- /dev/null
+++ b/sources/vphone-cli/VPhoneControlApps.swift
@@ -0,0 +1,53 @@
+import Foundation
+
+extension VPhoneControl {
+ // MARK: - App Management
+
+ struct AppInfo {
+ let bundleId: String
+ let name: String
+ let version: String
+ let type: String
+ let state: String
+ let pid: Int
+ let path: String
+ }
+
+ func appList(filter: String = "all") async throws -> [AppInfo] {
+ let (resp, _) = try await sendRequest(["t": "app_list", "filter": filter])
+ guard let apps = resp["apps"] as? [[String: Any]] else {
+ throw ControlError.protocolError("missing apps in response")
+ }
+ return apps.map { app in
+ AppInfo(
+ bundleId: app["bundle_id"] as? String ?? "",
+ name: app["name"] as? String ?? "",
+ version: app["version"] as? String ?? "",
+ type: app["type"] as? String ?? "",
+ state: app["state"] as? String ?? "",
+ pid: app["pid"] as? Int ?? 0,
+ path: app["path"] as? String ?? ""
+ )
+ }
+ }
+
+ func appLaunch(bundleId: String, url: String? = nil) async throws -> Int {
+ var req: [String: Any] = ["t": "app_launch", "bundle_id": bundleId]
+ if let url { req["url"] = url }
+ let (resp, _) = try await sendRequest(req)
+ return resp["pid"] as? Int ?? 0
+ }
+
+ func appTerminate(bundleId: String) async throws {
+ _ = try await sendRequest(["t": "app_terminate", "bundle_id": bundleId])
+ }
+
+ func appForeground() async throws -> (bundleId: String, name: String, pid: Int) {
+ let (resp, _) = try await sendRequest(["t": "app_foreground"])
+ return (
+ bundleId: resp["bundle_id"] as? String ?? "",
+ name: resp["name"] as? String ?? "",
+ pid: resp["pid"] as? Int ?? 0
+ )
+ }
+}
diff --git a/sources/vphone-cli/VPhoneControlKeychain.swift b/sources/vphone-cli/VPhoneControlKeychain.swift
new file mode 100644
index 00000000..ba3900b6
--- /dev/null
+++ b/sources/vphone-cli/VPhoneControlKeychain.swift
@@ -0,0 +1,34 @@
+import Foundation
+
+extension VPhoneControl {
+ // MARK: - Keychain Operations
+
+ struct KeychainResult {
+ let items: [[String: Any]]
+ let diagnostics: [String]
+ }
+
+ func listKeychainItems() async throws -> KeychainResult {
+ let req: [String: Any] = ["t": "keychain_list"]
+ let (resp, _) = try await sendRequest(req)
+ guard let items = resp["items"] as? [[String: Any]] else {
+ throw ControlError.protocolError("missing items in keychain response")
+ }
+ let diag = resp["diag"] as? [String] ?? []
+ return KeychainResult(items: items, diagnostics: diag)
+ }
+
+ func addKeychainItem(
+ account: String = "vphone-test", service: String = "vphone", password: String = "testpass123"
+ ) async throws {
+ let req: [String: Any] = [
+ "t": "keychain_add", "account": account, "service": service, "password": password,
+ ]
+ let (resp, _) = try await sendRequest(req)
+ let ok = resp["ok"] as? Bool ?? false
+ if !ok {
+ let msg = resp["msg"] as? String ?? "unknown error"
+ throw ControlError.protocolError("keychain_add: \(msg)")
+ }
+ }
+}
diff --git a/sources/vphone-cli/VPhoneControlSystem.swift b/sources/vphone-cli/VPhoneControlSystem.swift
new file mode 100644
index 00000000..d0b06e93
--- /dev/null
+++ b/sources/vphone-cli/VPhoneControlSystem.swift
@@ -0,0 +1,47 @@
+import Foundation
+
+extension VPhoneControl {
+ // MARK: - URL
+
+ func openURL(_ url: String) async throws {
+ let (resp, _) = try await sendRequest(["t": "open_url", "url": url])
+ let ok = resp["ok"] as? Bool ?? false
+ if !ok {
+ let msg = resp["msg"] as? String ?? "failed to open URL"
+ throw ControlError.guestError(msg)
+ }
+ }
+
+ // MARK: - Settings
+
+ func settingsGet(domain: String, key: String? = nil) async throws -> Any? {
+ var req: [String: Any] = ["t": "settings_get", "domain": domain]
+ if let key { req["key"] = key }
+ let (resp, _) = try await sendRequest(req)
+ return resp["value"]
+ }
+
+ func settingsSet(domain: String, key: String, value: Any, type: String? = nil) async throws {
+ var req: [String: Any] = ["t": "settings_set", "domain": domain, "key": key, "value": value]
+ if let type { req["type"] = type }
+ _ = try await sendRequest(req)
+ }
+
+ func lowPowerMode(enabled: Bool) async throws {
+ let (resp, _) = try await sendRequest(["t": "low_power_mode", "enabled": enabled])
+ let ok = resp["ok"] as? Bool ?? false
+ if !ok {
+ throw ControlError.guestError("low_power_mode: failed to set state on guest")
+ }
+ }
+
+ // MARK: - Accessibility
+
+ func accessibilityTree(depth: Int = -1) async throws -> [String: Any] {
+ guard guestCaps.contains("accessibility_tree") else {
+ throw ControlError.unsupportedCapability("accessibility_tree")
+ }
+ let (resp, _) = try await sendRequest(["t": "accessibility_tree", "depth": depth])
+ return resp
+ }
+}
diff --git a/sources/vphone-cli/VPhoneCreateOptions.swift b/sources/vphone-cli/VPhoneCreateOptions.swift
new file mode 100644
index 00000000..3667b214
--- /dev/null
+++ b/sources/vphone-cli/VPhoneCreateOptions.swift
@@ -0,0 +1,57 @@
+import VPhoneCore
+
+// MARK: - Create Options
+
+extension VPhoneCreateOrchestrator {
+ public struct Options {
+ public var name: String
+ public var variant: String
+ public var iphoneSource: String?
+ public var cloudosSource: String?
+ public var sudoPassword: String?
+ public var spoofBuild: String?
+ public var forceDSCMaxSlide: Bool
+ public var enableFrida: Bool
+ public var rootPopup: Bool
+ public var interactive: Bool
+ public var cpuCount: UInt
+ public var memoryMB: UInt64
+ public var diskSizeGB: UInt64
+ public var verbosity: VPhoneVerbosity
+ public var keepArtifacts: Bool
+
+ public init(
+ name: String,
+ variant: String,
+ iphoneSource: String? = nil,
+ cloudosSource: String? = nil,
+ sudoPassword: String? = nil,
+ spoofBuild: String? = nil,
+ forceDSCMaxSlide: Bool = false,
+ enableFrida: Bool = false,
+ rootPopup: Bool = false,
+ interactive: Bool = false,
+ cpuCount: UInt = 8,
+ memoryMB: UInt64 = 8192,
+ diskSizeGB: UInt64 = 64,
+ verbosity: VPhoneVerbosity = .quiet,
+ keepArtifacts: Bool = false
+ ) {
+ self.name = name
+ self.variant = variant
+ self.iphoneSource = iphoneSource
+ self.cloudosSource = cloudosSource
+ self.sudoPassword = sudoPassword
+ self.spoofBuild = spoofBuild
+ self.forceDSCMaxSlide = forceDSCMaxSlide
+ self.enableFrida = enableFrida
+ self.rootPopup = rootPopup
+ self.interactive = interactive
+ self.cpuCount = cpuCount
+ self.memoryMB = memoryMB
+ self.diskSizeGB = diskSizeGB
+ self.verbosity = verbosity
+ self.keepArtifacts = keepArtifacts
+ }
+ }
+}
diff --git a/sources/vphone-cli/VPhoneCreateOrchestrator.swift b/sources/vphone-cli/VPhoneCreateOrchestrator.swift
index 31ada9d3..0fac2e1a 100644
--- a/sources/vphone-cli/VPhoneCreateOrchestrator.swift
+++ b/sources/vphone-cli/VPhoneCreateOrchestrator.swift
@@ -92,58 +92,6 @@ extension VPhoneCreateError: LocalizedError {
/// `VPhoneBootPatterns`, where `VPhoneCoreTests` (which depends only on
/// VPhoneCore) can reach them.
public struct VPhoneCreateOrchestrator {
- public struct Options {
- public var name: String
- public var variant: String
- public var iphoneSource: String?
- public var cloudosSource: String?
- public var sudoPassword: String?
- public var spoofBuild: String?
- public var forceDSCMaxSlide: Bool
- public var enableFrida: Bool
- public var rootPopup: Bool
- public var interactive: Bool
- public var cpuCount: UInt
- public var memoryMB: UInt64
- public var diskSizeGB: UInt64
- public var verbosity: VPhoneVerbosity
- public var keepArtifacts: Bool
-
- public init(
- name: String,
- variant: String,
- iphoneSource: String? = nil,
- cloudosSource: String? = nil,
- sudoPassword: String? = nil,
- spoofBuild: String? = nil,
- forceDSCMaxSlide: Bool = false,
- enableFrida: Bool = false,
- rootPopup: Bool = false,
- interactive: Bool = false,
- cpuCount: UInt = 8,
- memoryMB: UInt64 = 8192,
- diskSizeGB: UInt64 = 64,
- verbosity: VPhoneVerbosity = .quiet,
- keepArtifacts: Bool = false
- ) {
- self.name = name
- self.variant = variant
- self.iphoneSource = iphoneSource
- self.cloudosSource = cloudosSource
- self.sudoPassword = sudoPassword
- self.spoofBuild = spoofBuild
- self.forceDSCMaxSlide = forceDSCMaxSlide
- self.enableFrida = enableFrida
- self.rootPopup = rootPopup
- self.interactive = interactive
- self.cpuCount = cpuCount
- self.memoryMB = memoryMB
- self.diskSizeGB = diskSizeGB
- self.verbosity = verbosity
- self.keepArtifacts = keepArtifacts
- }
- }
-
private let library: VPhoneLibrary
private let resources: VPhoneResources
private let selfExecutable: URL