Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Declare every patch in a patch set and select it with a preset

Lakr30c8512c89cd
diff --git a/AGENTS.md b/AGENTS.md
index ce5be0b5..46db64ce 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -27,6 +27,7 @@ For any changes applying new patches, also update Research/0_binary_patch_compar
- If working on kernel analysis, symbolication lookups, or kernel patch reasoning, read `Skills/kernel-analysis-vphone600/SKILL.md` first.
- Use this skill as the default procedure for `vphone600` kernel work.
+- If adding or changing a patch, a patch set, or a preset, read `Skills/authoring-patch-sets/SKILL.md` first. Every patch is declared in a patch set and selected by a preset; a patch in no manifest cannot be turned off and warns on every run.
## Firmware Mode
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 4777db9d..b07ee4ec 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -1,5 +1,79 @@
# Patch Comparison: Regular / Development / Jailbreak / Experimental
+> **Patch sets and presets (2026-09-28):** every patch is now *declared*, and
+> selection happens before any byte is written. The declarations live in nine
+> bundled patch sets under `VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/`
+> (`bootchain`, `kernel.base`, `kernel.jailbreak`, `kernel.hypervisor`,
+> `kernel.frida`, `devicetree`, `guest.system`, `guest.display`,
+> `guest.identity`), listed by `FirmwarePatchSetCatalog`. A declaration's
+> identifier is the record identifier the patcher already emits, or the common
+> prefix when one patch writes several sites — so `jb.kcall10` is one selectable
+> patch covering its four records, and `sandbox_ext` covers every
+> `sandbox_ext_<index>`. 115 patches are declared in total. `vphone-cli fw patches`
+> prints them; `--json` is what the Launchpad patch editor reads.
+>
+> Two presets ship, prewritten, in
+> `VPhone.bundle/Contents/Resources/patches_presets/`. Both name all nine sets and
+> differ only in their selection: `standard` (the default, and what a VM gets
+> unless `--preset` says otherwise) blocks the two Frida Stalker relaxations;
+> `extended` blocks nothing. A VM records only the boxes its owner changed, in
+> `<vm>/PatchSelection.plist`, and `fw patch` writes what it resolved to
+> `<vm>/PatchPlan.plist` for `cfw install` to reuse.
+>
+> **Patch sets also load from outside the bundle.** A `.vphonepatchset` is a macOS
+> loadable bundle whose `Contents/Resources/Manifest.plist` is read before any of
+> its code is mapped, and whose executable exports one symbol,
+> `vphone_patch_set_principal`, returning a `VPhonePatchSetPrincipal` that hands the
+> pipeline one `BufferedPatcher` per component the plan enabled. Not
+> `NSPrincipalClass`: PatchKit is built for library evolution, so a subclass of a
+> PatchKit class is registered with the ObjC runtime only when its metadata is first
+> realized, and `Bundle.principalClass` therefore resolves to the wrong class
+> entirely. `VPhoneExecutable/VPhoneCommand/VPhonePatchSetExample` is the template
+> and is what the loader tests load.
+>
+> An external set can patch the boot chain only, and reaches a run through a preset
+> in `~/.vphone/patches_presets/` naming it by identifier *and* path — the manifest
+> at that path has to declare that identifier. `vphone-cli patchset import` copies a
+> set into `~/.vphone/patchsets` and ad hoc signs it, which is what makes a bundle
+> straight out of Xcode loadable at all: the linker signs the Mach-O but seals no
+> resources, so `codesign --verify` rejects it until one `codesign --force --sign -`
+> pass over the bundle fixes it. The signature is re-verified from disk at every
+> load. Root `cfw install` loads no external set, so nothing here is on a privileged
+> path.
+>
+> **Version gates replaced three flags.** The patches `--frida`,
+> `--force-exc-guard` and `--force-dsc-maxslide` controlled now carry a structured
+> `VPhonePatchApplicability`: `kernel.thread_guard_violation` is pinned to
+> `iOSBase: .major(18)` (whose runningboardd trips a flavor-10 Mach port guard and
+> crash-loops the UI), `dsc_maxslide.zero` to `.major(27)`, and the two
+> `kernelcache_frida.*` patches to `cloudOS: .atLeast(26, 4)`. A preset can turn a
+> patch off, and a VM can turn one on that its preset leaves off, but neither can
+> widen a version gate — so forcing the guard or the slide onto a 26.x base is no
+> longer possible. That capability was opt-in for third-party RASP SDKs and was
+> never required to boot.
+>
+> Two of the three flags are gone from the surface as well: `--force-exc-guard` no
+> longer exists, and `--frida` survives only on the `patch-component` developer
+> subcommand, not on `vm create` or `fw patch`. `--force-dsc-maxslide` is **still
+> plumbed** through `vm create`, `VPhoneVirtualMachineCreateOptions`, the Launchpad
+> helper protocol and the Launchpad new-machine sheet, where it now reaches an
+> installer branch the plan has already decided; removing that chain is outstanding
+> and touches the privileged helper's XPC signature, so it is its own change.
+>
+> The `iosBaseIs18` / `iosBaseIs27` booleans are gone from the pipeline too: it now
+> carries a parsed `VPhoneVersion` (major, minor, patch). Two things still branch
+> on the release rather than on a selection, because they change *which shapes a
+> patch looks for* rather than whether it runs: the 18.x skywalk-netagent
+> boot-arg, and `KernelJailbreakPatcher.applyIOS27`.
+>
+> **Byte-identity check (2026-09-28):** the golden corpus was re-run over cloudOS
+> 26.4 with iOS 26.1, 26.4 and 27.0 bases. `--preset standard` reproduced the
+> pre-patch-set output for all three, digest for digest, and `--preset extended`
+> reproduced the old `--frida` case exactly. No run emitted the
+> `declared by no patch set` warning, so every record the boot chain emits is
+> covered by a declaration. The one case that no longer exists is
+> `--force-exc-guard` on a 26.1 base, for the reason above.
+
> **Current product scope (September 2026):** the tables below preserve the
> historical patch comparison. The public runtime now exposes only JB. Guest
> package managers, Procursus, and first-boot package setup are outside this
diff --git a/Skills/authoring-patch-sets/SKILL.md b/Skills/authoring-patch-sets/SKILL.md
new file mode 100644
index 00000000..e2ef296d
--- /dev/null
+++ b/Skills/authoring-patch-sets/SKILL.md
@@ -0,0 +1,359 @@
+---
+name: authoring-patch-sets
+description: Declare a new firmware patch in a vphone patch set, add a patch set, or write a patch preset. Use when adding or changing a patch in FirmwarePatcher, when a patch needs a version gate, when a patch should be selectable or off by default, or when building an out-of-tree .vphonepatchset.
+---
+
+# Authoring Patch Sets
+
+Every patch this project applies is declared in a **patch set**, selected by a
+**preset**, and written only if the **gate** says so. A patch that exists in code
+but in no manifest still applies — it just cannot be turned off, and it prints a
+warning on every run. Declaring it is what makes it real.
+
+## The Three Layers
+
+| Layer | Type | Where |
+| --- | --- | --- |
+| A patch | `VPhonePatchDeclaration` | a set's `patches` array |
+| A set | `VPhonePatchSetManifest` | `FirmwarePatcher/PatchSets/*.swift`, or a `.vphonepatchset`'s `Contents/Resources/Manifest.plist` |
+| A preset | `VPhonePatchPreset` | `VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/*.plist` |
+
+The types live in `VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/`. The
+nine in-tree sets and the two shipped presets live in
+`VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/`, listed by
+`FirmwarePatchSetCatalog`.
+
+## Adding a Patch to an Existing Set
+
+1. **Write the patch as usual.** Nothing about patch code changes: same
+ `ARM64Disassembler` matching, same `ARM64Encoder` / `ARM64` constants for
+ replacement bytes, same `emit(...)`. Follow the kernel patcher guardrails in
+ `AGENTS.md`.
+
+2. **Note the record identifier your patch emits** — the `patchID:` you pass to
+ `emit`. That is what ties the patch to its declaration.
+
+3. **Declare it** in the right set, with the identifier being the record
+ identifier, or their common prefix when the patch writes several sites:
+
+ ```swift
+ VPhonePatchDeclaration(
+ identifier: "jb.my_patch",
+ title: "What it is, in three or four words",
+ summary: "What it does and why the guest needs it. One or two sentences.",
+ target: .firmware(.kernelcache),
+ applicability: VPhonePatchApplicability(iOSBase: .major(27)),
+ bootEssential: true,
+ )
+ ```
+
+4. **Build and run the golden corpus.** A record no declaration covers prints
+ `[!] <component>: <id> is declared by no patch set; applying it anyway`. Grep
+ the logs for `declared by no patch set` — it must be absent.
+
+### Identifiers Are the Contract
+
+A declaration covers its own record and any record under it, with either
+separator:
+
+- `jb.kcall10` covers `jb.kcall10.sy_call`, `jb.kcall10.sy_munge`, …
+- `llb.rootfs` covers `llb.rootfs_cbz_0x3b7`, `llb.rootfs_bhs_0x400`, …
+- `sandbox_ext` covers `sandbox_ext_267` and every other index
+- `kernel.debugger` does **not** cover `kernel.debuggerless`
+
+Both separators are supported because record identifiers predate declarations and
+spell their per-site suffix both ways. Do not rename an existing record
+identifier to tidy this up: they appear in logs, in research notes and in test
+expectations.
+
+Pick the granularity a user would want to tick. One declaration per patch method
+is usually right — a patch writing four sites that only work together is one
+checkbox, because half of it would not boot. Where sites are genuinely
+independent, declare them separately: `kernel.sandbox.*` is five declarations,
+one per MACF hook, because turning one hook off is a sensible thing to want.
+
+**Never let one declaration read as a site of another.**
+`FirmwarePatchSetCatalogTests.noAmbiguousPrefixes` fails if you do.
+
+## Version Gates
+
+`applicability` is the only correct way to say "this patch is for release X". It
+is a structured enum, never a string:
+
+```swift
+VPhonePatchApplicability(iOSBase: .major(27)) // every 27.x
+VPhonePatchApplicability(iOSBase: .release(major: 26, minor: 0)) // exactly 26.0
+VPhonePatchApplicability(cloudOS: .atLeast(major: 26, minor: 4)) // 26.4 and later
+VPhonePatchApplicability(iOSBase: .oneOf([.release(major: 26, minor: 0), .major(18)]))
+```
+
+`iOSBase` is the iPhone base whose userland is restored into the guest; `cloudOS`
+is the release supplying the kernel and boot chain. Only major and minor are
+compared, so 18.6.2 satisfies `.major(18)`.
+
+An unreadable version satisfies only `.any`. That is deliberate: a patch pinned
+to a release must not apply when nothing knows which release this is.
+
+Two rules follow, and they are the ones people get wrong:
+
+- **A version gate is not a preference.** Use it when applying the patch
+ elsewhere would patch the wrong shapes or break the guest. Do not use it to
+ express "most people want this off" — that is what a preset's block list is
+ for.
+- **A preset cannot widen a gate.** Checking a box in the UI changes the
+ selection, never the applicability. So a patch pinned to iOS 18 is unreachable
+ on 26.x, by design. If a patch genuinely needs to be available everywhere *and*
+ off by default, give it `.any` applicability and block it in `standard`.
+
+Do **not** add a boolean flag to `FirmwarePipeline` or a `--force-something` CLI
+flag for this. The patches behind `--frida`, `--force-exc-guard` and
+`--force-dsc-maxslide` are declarations now, and adding another flag is a
+regression. (`--force-dsc-maxslide` itself is still plumbed from `vm create`
+through the Launchpad helper; that chain is dead weight awaiting removal, not a
+pattern to copy.)
+
+## Boot-Essential Patches
+
+Set `bootEssential: true` when the guest does not boot without the patch. This
+does not prevent it being turned off — an external set replacing it is a
+supported case — but it makes the consequence visible: the resolver reports it in
+`droppedBootEssentials`, `fw patch` logs `[!] Boot-essential patches are off:`,
+and the Launchpad editor warns before letting it be unticked.
+
+A boot-essential declaration must have a `summary`. The test enforces it: it is
+the text someone reads before unticking a box that stops their VM booting.
+
+## Adding a New Patch Set
+
+A set is worth creating when its patches share a reason to be on or off together.
+Copy the shape of `FirmwareKernelFridaPatchSet.swift` — it is the smallest one:
+
+```swift
+public enum FirmwareMyPatchSet {
+ public static let identifier = "com.vphone.patchset.my"
+
+ public static let manifest = VPhonePatchSetManifest(
+ identifier: identifier,
+ name: "My Patches",
+ summary: "One line on what this set is for",
+ patches: [ /* declarations */ ],
+ requires: ["vphone.kernel.base"],
+ provides: ["vphone.my"],
+ conflictsWith: [],
+ after: ["vphone.kernel.base"],
+ )
+}
+```
+
+Then:
+
+1. Add the manifest to `FirmwarePatchSetCatalog.bundled`.
+2. If the set maps to a whole patcher, gate that patcher's construction in
+ `FirmwarePipelineComponents.buildComponentList` on `includesSet(...)`. **This
+ matters:** a patcher left in place while its set is out of the preset emits
+ records nothing declares, and undeclared records apply. Leaving the set out
+ has to mean leaving the patcher out.
+3. Add the set to both shipped preset plists (both name every set; presets differ
+ by their selection, not by which sets they draw on).
+4. Run the catalogue tests.
+
+### Capabilities, Requires, Conflicts, After
+
+`provides` names capabilities; a set implicitly provides its own identifier.
+`requires` must be satisfied by some set in the plan or resolution fails.
+`conflictsWith` is enforced **symmetrically** — either side naming the other is a
+conflict, so an older set need not be edited to learn about a newer rival. There
+is no `Supersedes`: a conflict is an error, not a silent winner. `after` orders
+the sets, and a cycle is an error.
+
+Two sets may not declare the same patch identifier. A set that *replaces* another
+set's patch gives its version a new identifier, and the preset blocks the
+original.
+
+## Writing a Preset
+
+Presets are prewritten and reviewed. Nothing in the tool writes one; a VM records
+only which boxes its owner changed, and those compose on top.
+
+`standard` is what every VM gets. Any other preset must be asked for with
+`--preset`. Both shipped presets name all nine sets and differ only in their
+selection:
+
+```xml
+<key>Selection</key>
+<dict>
+ <key>Kind</key>
+ <string>Block</string>
+ <key>Patches</key>
+ <array>
+ <string>kernelcache_frida.thread_set_state_entitlement_flag</string>
+ </array>
+</dict>
+```
+
+`Kind` is `All`, `Allow` or `Block` — never both lists, because a manifest able to
+carry both invites a preset where one silently wins. Use `Block` for "everything
+except"; use `Allow` only for a deliberately minimal preset, remembering that a
+patch added later will not be in it.
+
+When you add or change a preset plist, mirror it in
+`FirmwarePatchSetCatalog` — that Swift copy is what a dev build with no staged
+bundle falls back to, and `shippedPresetsMatchBuiltIns` fails if they drift.
+
+### What a VM Records
+
+`fw set-patches` writes `<vm>/PatchSelection.plist`, and is the only writer:
+
+```zsh
+vphone-cli fw set-patches lab --preset extended --block kernel.debugger
+vphone-cli fw set-patches lab # back to the preset alone
+```
+
+Each run writes the whole record, and only differences survive it — an
+identifier the preset already agrees with is dropped, so a later preset revision
+still reaches a VM whose boxes were never touched. The Launchpad's patch editor
+reads `fw patches --json` and writes through this verb rather than touching a VM
+bundle itself. Blocking a boot-essential patch is allowed; it warns on stderr.
+
+## Out-of-Tree Patch Sets
+
+**Start from `VPhoneExecutable/VPhoneCommand/VPhonePatchSetExample`.** It is a
+complete, building set — one iBEC string rewrite — and the loader tests load it,
+so it is kept working. Copy the target, change the identifier, replace the patcher.
+
+An external set is a macOS loadable bundle with the `.vphonepatchset` extension:
+
+```
+Mine.vphonepatchset/
+ Contents/
+ Info.plist CFBundleExecutable names the binary
+ MacOS/Mine exports vphone_patch_set_principal
+ Resources/Manifest.plist what the set declares
+ _CodeSignature/ written by `vphone-cli patchset import`
+```
+
+Build it against the `VPhonePatchKit.framework` the bundle ships — it is built
+with library evolution and ships its `.swiftinterface`, so an out-of-tree set
+links against the same copy `vphone-cli` loads rather than statically linking a
+second disassembler. The target needs
+`LD_RUNPATH_SEARCH_PATHS = @executable_path/../Frameworks` so the framework beside
+`vphone-cli` is the one that resolves.
+
+Three things make up the code side, and there is nothing else to implement:
+
+```swift
+// 1. The entry point. One exported C symbol, copied verbatim.
+@_cdecl("vphone_patch_set_principal")
+public func makeMyPatchSetPrincipal() -> UnsafeMutableRawPointer {
+ VPhonePatchSetPrincipal.export(MyPatchSet())
+}
+
+// 2. The principal, asked for one patcher per component the manifest declares
+// an enabled patch for. The inherited default throws for anything else, so a
+// manifest promising a component the code does not handle is a loud error.
+public final class MyPatchSet: VPhonePatchSetPrincipal {
+ public override func makePatcher(
+ for component: VPhoneFirmwareComponent,
+ data: Data,
+ context: VPhonePatchSetContext,
+ ) throws -> any BufferedPatcher {
+ guard component == .iBEC else {
+ return try super.makePatcher(for: component, data: data, context: context)
+ }
+ return MyPatcher(data: data, gate: context.gate, verbose: context.verbose)
+ }
+}
+
+// 3. A BufferedPatcher per component: `patchedData` is how the pipeline reads the
+// bytes back, and `gate` is how a per-VM checkmark reaches your patch sites.
+```
+
+Not `NSPrincipalClass`, even though that is the usual way a loadable bundle names
+its entry point. PatchKit is built for library evolution, so a subclass of
+`VPhonePatchSetPrincipal` has a resilient superclass and its metadata is realized
+at first use, not at image load; the class is therefore not registered with the
+ObjC runtime when the bundle is mapped, `NSClassFromString` cannot find it, and
+`Bundle.principalClass` silently returns whichever class *was* registered. The
+exported symbol has none of that.
+
+`context` carries what the plan resolved: `iOSBase` and `cloudOS`, the `gate`, the
+preset's `parameters`, and `verbose`. Ask the gate before you write, never after —
+a patch whose records are already in the buffer cannot be turned off.
+
+Set `MinimumPatchKitVersion` to the API version you need. A set requiring a newer
+PatchKit than the bundle has is refused with a readable error instead of failing
+in the dynamic loader.
+
+Then import it, which is also what signs it:
+
+```zsh
+vphone-cli patchset import ./Mine.vphonepatchset # copies into ~/.vphone/patchsets, ad hoc signs
+vphone-cli patchset list # and says whether it still matches the import
+```
+
+A set straight out of Xcode is *linker* ad hoc signed: the Mach-O has a signature
+but the bundle seals no resources, so `codesign --verify` rejects it. Import runs
+one `codesign --force --sign -` pass over the bundle, which is what fixes that.
+The signature is re-checked from disk at every load, so a set edited afterwards
+stops loading until it is imported again.
+
+A preset references one by identifier *and* path:
+
+```xml
+<dict>
+ <key>Kind</key><string>External</string>
+ <key>Identifier</key><string>com.example.patchset.mine</string>
+ <key>Path</key><string>/path/to/Mine.vphonepatchset</string>
+</dict>
+```
+
+Both are required: the manifest found at that path must declare that identifier,
+or replacing the file would silently change which patches a preset applies.
+
+Such a preset goes in `~/.vphone/patches_presets/`, not in the bundle: shipped
+presets live in a sealed bundle and never reference anything outside it. A user
+preset cannot claim an identifier a shipped one already has, so nothing can
+redefine `standard`.
+
+**A loaded set patches the boot chain only.** Every declared patch must target a
+firmware component; a guest-side target is refused at import, because the guest
+half of an install is the privileged step and loads no external set at all.
+
+**Security boundary.** Root `cfw install` loads bundled sets only. An external
+set reaches a privileged run only after the Launchpad helper has imported it and
+pinned its cdhash. Unsigned or invalidly signed sets are ad hoc re-signed at
+import, not at load. Do not add a path that lets root open an arbitrary file.
+
+The honest limit: a loaded set is code in the patching process. The gate is what
+makes its patches selectable, and a patcher that ignores the gate applies anyway.
+What does hold is the signature check at load and the rule above.
+
+## Checking Your Work
+
+```zsh
+# Build
+xcodebuild -workspace VPhone.xcworkspace -scheme VPhoneCommand -configuration Debug \
+ -destination 'platform=macOS,arch=arm64' -derivedDataPath .build/XcodeCommand build
+
+# What the catalogue now says
+vphone-cli fw patches # for a person
+vphone-cli fw patches --json # what the Launchpad editor reads
+
+# The model and catalogue tests
+xcodebuild -workspace VPhone.xcworkspace -scheme FirmwarePatcherTests -configuration Debug \
+ -destination 'platform=macOS,arch=arm64' -derivedDataPath .build/XcodeCommand test-without-building
+```
+
+The suites that must pass: `Version requirements`, `Patch selection`,
+`Patch declarations`, `Plan resolution`, `Patch gate`,
+`Bundled patch set catalogue`. Reference-fixture suites fail on machines without
+`ipsws/ref_extract`; that is an environment gap, not a regression.
+
+Then verify byte-identity for anything you did not intend to change. Patching the
+same firmware with the same preset must produce the same bytes, and `standard`
+must keep producing what it produced before your change unless changing that was
+the point.
+
+Finally: **for any change applying new patches, update
+`Research/0_binary_patch_comparison.md`.** That is a standing rule in `AGENTS.md`,
+and a new declaration with no research note is an incomplete change.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/ARM64/ARM64Constants.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/ARM64/ARM64Constants.swift
deleted file mode 100644
index 18fa009e..00000000
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/ARM64/ARM64Constants.swift
+++ /dev/null
@@ -1,188 +0,0 @@
-// ARM64Constants.swift — Pre-encoded ARM64 instruction constants.
-//
-// Every constant was generated by keystone-engine and verified
-// via capstone round-trip disassembly. Do NOT edit raw bytes
-// without updating the corresponding test case.
-
-import Foundation
-
-// MARK: - ARM64 Instruction Constants
-
-public enum ARM64 {
- // MARK: Fixed Instructions
-
- /// NOP — no operation
- public static let nop = encodeU32(0xD503_201F)
-
- /// RET — return from subroutine
- public static let ret = encodeU32(0xD65F_03C0)
-
- /// RETAA — return with pointer authentication (A key)
- public static let retaa = encodeU32(0xD65F_0BFF)
-
- /// RETAB — return with pointer authentication (B key)
- public static let retab = encodeU32(0xD65F_0FFF)
-
- /// PACIBSP — sign LR with B key using SP (hint #27)
- public static let pacibsp = encodeU32(0xD503_237F)
-
- // MARK: MOV Variants
-
- /// MOV X0, #0 (MOVZ X0, #0)
- public static let movX0_0 = encodeU32(0xD280_0000)
-
- /// MOV X0, #1 (MOVZ X0, #1)
- public static let movX0_1 = encodeU32(0xD280_0020)
-
- /// MOV W0, #0 (MOVZ W0, #0)
- public static let movW0_0 = encodeU32(0x5280_0000)
-
- /// MOV W0, #1 (MOVZ W0, #1)
- public static let movW0_1 = encodeU32(0x5280_0020)
-
- /// MOV X0, X20 (ORR X0, XZR, X20)
- public static let movX0X20 = encodeU32(0xAA14_03E0)
-
- /// MOV W0, #0xA1 (MOVZ W0, #0xA1)
- public static let movW0_0xA1 = encodeU32(0x5280_1420)
-
- // MARK: Compare
-
- /// CMP W0, W0 (SUBS WZR, W0, W0)
- public static let cmpW0W0 = encodeU32(0x6B00_001F)
-
- /// CMP X0, X0 (SUBS XZR, X0, X0)
- public static let cmpX0X0 = encodeU32(0xEB00_001F)
-
- // MARK: Memory
-
- /// STRB W0, [X20, #0x30]
- public static let strbW0X20_30 = encodeU32(0x3900_C280)
-
- // MARK: JB Constants
-
- /// CBZ X2, #8 (branch if X2 == 0, skip 2 instructions)
- public static let cbzX2_8 = encodeU32(0xB400_0042)
-
- /// STR X0, [X2]
- public static let strX0X2 = encodeU32(0xF900_0040)
-
- /// CMP XZR, XZR (SUBS XZR, XZR, XZR — always sets Z flag)
- public static let cmpXzrXzr = encodeU32(0xEB1F_03FF)
-
- // MARK: Common Prologue/Epilogue Patterns (verified via keystone)
-
- /// STP X29, X30, [SP, #-0x10]! (push frame)
- static let stpFP_LR_pre: UInt32 = 0xA9BF_7BFD
- /// MOV X29, SP (set frame pointer)
- static let movFP_SP: UInt32 = 0x9100_03FD
-
- // MARK: IOUC MACF Aggregator Shape
-
- /// LDR X10, [X10, #0x9E8] (mac_policy_list slot load)
- static let ldr_x10_x10_0x9e8: UInt32 = 0xF944_F54A
- /// BLRAA X10, SP (authenticated indirect call)
- static let blraa_x10: UInt32 = 0xD73F_0940
- /// BLRAB X10, SP
- static let blrab_x10: UInt32 = 0xD73F_0D40
- /// BLR X10
- static let blr_x10: UInt32 = 0xD63F_0140
-
- // MARK: C23 Cave Instructions (verified via keystone)
-
- //
- // These are the fixed instructions used in the faithful upstream C23
- // shellcode cave (vnode getattr → uid/gid/P_SUGID fixup).
- // Position-dependent BL/B instructions are NOT included here — they are
- // encoded at build time by ARM64Encoder.
-
- static let c23_cbzX3_0xA8: UInt32 = 0xB400_0543 // cbz x3, #+0xa8
- static let c23_subSP_0x400: UInt32 = 0xD110_03FF // sub sp, sp, #0x400
- static let c23_stpFP_LR: UInt32 = 0xA900_7BFD // stp x29, x30, [sp]
- static let c23_stpX0X1_0x10: UInt32 = 0xA901_07E0 // stp x0, x1, [sp, #0x10]
- static let c23_stpX2X3_0x20: UInt32 = 0xA902_0FE2 // stp x2, x3, [sp, #0x20]
- static let c23_stpX4X5_0x30: UInt32 = 0xA903_17E4 // stp x4, x5, [sp, #0x30]
- static let c23_stpX6X7_0x40: UInt32 = 0xA904_1FE6 // stp x6, x7, [sp, #0x40]
- static let c23_movX2_X0: UInt32 = 0xAA00_03E2 // mov x2, x0
- static let c23_ldrX0_sp_0x28: UInt32 = 0xF940_17E0 // ldr x0, [sp, #0x28]
- static let c23_addX1_sp_0x80: UInt32 = 0x9102_03E1 // add x1, sp, #0x80
- static let c23_movzW8_0x380: UInt32 = 0x5280_7008 // movz w8, #0x380
- static let c23_stpXZR_X8: UInt32 = 0xA900_203F // stp xzr, x8, [x1]
- static let c23_stpXZR_XZR_0x10: UInt32 = 0xA901_7C3F // stp xzr, xzr, [x1, #0x10]
- static let c23_cbnzX0_0x4c: UInt32 = 0xB500_0260 // cbnz x0, #+0x4c
- static let c23_movW2_0: UInt32 = 0x5280_0002 // mov w2, #0
- static let c23_ldrW8_sp_0xcc: UInt32 = 0xB940_CFE8 // ldr w8, [sp, #0xcc]
- static let c23_tbzW8_11_0x14: UInt32 = 0x3658_00A8 // tbz w8, #0xb, #+0x14
- static let c23_ldrW8_sp_0xc4: UInt32 = 0xB940_C7E8 // ldr w8, [sp, #0xc4]
- static let c23_ldrX0_sp_0x18: UInt32 = 0xF940_0FE0 // ldr x0, [sp, #0x18]
- static let c23_strW8_x0_0x18: UInt32 = 0xB900_1808 // str w8, [x0, #0x18]
- static let c23_movW2_1: UInt32 = 0x5280_0022 // mov w2, #1
- static let c23_tbzW8_10_0x14: UInt32 = 0x3650_00A8 // tbz w8, #0xa, #+0x14
- static let c23_ldrW8_sp_0xc8: UInt32 = 0xB940_CBE8 // ldr w8, [sp, #0xc8]
- static let c23_strW8_x0_0x28: UInt32 = 0xB900_2808 // str w8, [x0, #0x28]
- static let c23_cbzW2_0x14: UInt32 = 0x3400_00A2 // cbz w2, #+0x14
- static let c23_ldrX0_sp_0x20: UInt32 = 0xF940_13E0 // ldr x0, [sp, #0x20]
- static let c23_ldrW8_x0_0x454: UInt32 = 0xB944_5408 // ldr w8, [x0, #0x454]
- static let c23_orrW8_0x100: UInt32 = 0x3218_0108 // orr w8, w8, #0x100
- static let c23_strW8_x0_0x454: UInt32 = 0xB904_5408 // str w8, [x0, #0x454]
- static let c23_ldpX0X1_0x10: UInt32 = 0xA941_07E0 // ldp x0, x1, [sp, #0x10]
- static let c23_ldpX2X3_0x20: UInt32 = 0xA942_0FE2 // ldp x2, x3, [sp, #0x20]
- static let c23_ldpX4X5_0x30: UInt32 = 0xA943_17E4 // ldp x4, x5, [sp, #0x30]
- static let c23_ldpX6X7_0x40: UInt32 = 0xA944_1FE6 // ldp x6, x7, [sp, #0x40]
- static let c23_ldpFP_LR: UInt32 = 0xA940_7BFD // ldp x29, x30, [sp]
- static let c23_addSP_0x400: UInt32 = 0x9110_03FF // add sp, sp, #0x400
-
- // MARK: vfs_context_current Shape (verified via keystone)
-
- /// mrs x0, tpidr_el1
- static let mrs_x0_tpidr_el1: UInt32 = 0xD538_D080
-
- // MARK: Syscallmask C22 Cave Instructions (verified via clang/as)
-
- static let syscallmask_cbzX2_0x6c: UInt32 = 0xB400_0362 // cbz x2, #+0x6c
- static let syscallmask_subSP_0x40: UInt32 = 0xD101_03FF // sub sp, sp, #0x40
- static let syscallmask_stpX19X20_0x10: UInt32 = 0xA901_53F3 // stp x19, x20, [sp, #0x10]
- static let syscallmask_stpX21X22_0x20: UInt32 = 0xA902_5BF5 // stp x21, x22, [sp, #0x20]
- static let syscallmask_stpFP_LR_0x30: UInt32 = 0xA903_7BFD // stp x29, x30, [sp, #0x30]
- static let syscallmask_movX19_X0: UInt32 = 0xAA00_03F3 // mov x19, x0
- static let syscallmask_movX20_X1: UInt32 = 0xAA01_03F4 // mov x20, x1
- static let syscallmask_movX21_X2: UInt32 = 0xAA02_03F5 // mov x21, x2
- static let syscallmask_movX22_X3: UInt32 = 0xAA03_03F6 // mov x22, x3
- static let syscallmask_movX8_8: UInt32 = 0xD280_0108 // mov x8, #8
- static let syscallmask_movX0_X17: UInt32 = 0xAA11_03E0 // mov x0, x17
- static let syscallmask_movX1_X21: UInt32 = 0xAA15_03E1 // mov x1, x21
- static let syscallmask_movX2_0: UInt32 = 0xD280_0002 // mov x2, #0
- static let syscallmask_udivX4_X22_X8: UInt32 = 0x9AC8_0AC4 // udiv x4, x22, x8
- static let syscallmask_msubX10_X4_X8_X22: UInt32 = 0x9B08_D88A // msub x10, x4, x8, x22
- static let syscallmask_cbzX10_8: UInt32 = 0xB400_004A // cbz x10, #+8
- static let syscallmask_addX4_X4_1: UInt32 = 0x9100_0484 // add x4, x4, #1
- static let syscallmask_movX0_X19: UInt32 = 0xAA13_03E0 // mov x0, x19
- static let syscallmask_movX1_X20: UInt32 = 0xAA14_03E1 // mov x1, x20
- static let syscallmask_movX2_X21: UInt32 = 0xAA15_03E2 // mov x2, x21
- static let syscallmask_movX3_X22: UInt32 = 0xAA16_03E3 // mov x3, x22
- static let syscallmask_ldpX19X20_0x10: UInt32 = 0xA941_53F3 // ldp x19, x20, [sp, #0x10]
- static let syscallmask_ldpX21X22_0x20: UInt32 = 0xA942_5BF5 // ldp x21, x22, [sp, #0x20]
- static let syscallmask_ldpFP_LR_0x30: UInt32 = 0xA943_7BFD // ldp x29, x30, [sp, #0x30]
- static let syscallmask_addSP_0x40: UInt32 = 0x9101_03FF // add sp, sp, #0x40
-
- // MARK: UInt32 Values (for pattern matching)
-
- public static let nopU32: UInt32 = 0xD503_201F
- public static let retU32: UInt32 = 0xD65F_03C0
- public static let retaaU32: UInt32 = 0xD65F_0BFF
- public static let retabU32: UInt32 = 0xD65F_0FFF
- public static let pacibspU32: UInt32 = 0xD503_237F
- public static let movX0_0_U32: UInt32 = 0xD280_0000 // MOV X0, #0 (MOVZ X0, #0)
-
- /// Set of instruction uint32 values that indicate function boundaries.
- public static let funcBoundaryU32s: Set<UInt32> = [
- retU32, retaaU32, retabU32, pacibspU32,
- ]
-
- // MARK: - Helpers
-
- @inlinable
- static func encodeU32(_ value: UInt32) -> Data {
- withUnsafeBytes(of: value.littleEndian) { Data($0) }
- }
-}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/ARM64/ARM64Disassembler.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/ARM64/ARM64Disassembler.swift
deleted file mode 100644
index 026c0544..00000000
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/ARM64/ARM64Disassembler.swift
+++ /dev/null
@@ -1,71 +0,0 @@
-// ARM64Disassembler.swift — Capstone wrapper for ARM64 disassembly.
-
-import Capstone
-import Foundation
-
-public final class ARM64Disassembler: Sendable {
- private let cs: Disassembler
-
- public init() {
- // CS_ARCH_AARCH64 and CS_MODE_LITTLE_ENDIAN are the correct constants
- cs = try! Disassembler(arch: CS_ARCH_AARCH64, mode: CS_MODE_LITTLE_ENDIAN)
- cs.detail = true
- cs.skipData = true
- }
-
- /// Disassemble instructions from data starting at the given virtual address.
- ///
- /// - Parameters:
- /// - data: Raw instruction bytes.
- /// - address: Virtual address of the first byte.
- /// - count: Maximum number of instructions to disassemble (0 = all).
- /// - Returns: Array of disassembled instructions.
- public func disassemble(_ data: Data, at address: UInt64 = 0, count: Int = 0) -> [Instruction] {
- cs.disassemble(code: data, address: address, count: count)
- }
-
- /// Disassemble a single 4-byte instruction at the given address.
- public func disassembleOne(_ data: Data, at address: UInt64 = 0) -> Instruction? {
- let insns = cs.disassemble(code: data, address: address, count: 1)
- return insns.first
- }
-
- /// Disassemble a single instruction from a buffer at a file offset.
- public func disassembleOne(in buffer: Data, at offset: Int, address: UInt64? = nil) -> Instruction? {
- guard offset >= 0, offset + 4 <= buffer.count else { return nil }
- let slice = buffer[offset ..< offset + 4]
- let addr = address ?? UInt64(offset)
- return disassembleOne(Data(slice), at: addr)
- }
-
- /// Disassemble `count` instructions starting at file offset.
- public func disassemble(in buffer: Data, at offset: Int, count: Int, address: UInt64? = nil) -> [Instruction] {
- let byteCount = count * 4
- guard offset >= 0, offset + byteCount <= buffer.count else { return [] }
- let slice = buffer[offset ..< offset + byteCount]
- let addr = address ?? UInt64(offset)
- return disassemble(Data(slice), at: addr, count: count)
- }
-
- /// Return the canonical name string for an AArch64 register ID (e.g. "x0", "w1", "wzr").
- public func registerName(_ regID: UInt32) -> String? {
- cs.registerName(regID)
- }
-
- /// Canonical name of the instruction's first operand when it is a register
- /// (the write target for the moves/loads/branches the patchers match), else nil.
- ///
- /// Replaces the brittle `operandString.components(separatedBy: ",")` parsing that
- /// was duplicated across the JB patch files to recover a destination register's
- /// width ("w…" vs "x…") and identity.
- public func firstRegisterName(_ insn: Instruction) -> String? {
- guard let ops = insn.aarch64?.operands, let first = ops.first,
- first.type == AARCH64_OP_REG else { return nil }
- return cs.registerName(UInt32(first.reg.rawValue))
- }
-
- /// True iff the instruction's first (destination) operand is the named register.
- public func writesRegister(_ insn: Instruction, named regName: String) -> Bool {
- firstRegisterName(insn) == regName
- }
-}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/AVPBooter/AVPBooterPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/AVPBooter/AVPBooterPatcher.swift
index c39a0b97..3f3260c4 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/AVPBooter/AVPBooterPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/AVPBooter/AVPBooterPatcher.swift
@@ -12,12 +12,16 @@
// 5. Patch that instruction to `mov x0, #0`.
import Foundation
+import VPhonePatchKit
/// Patcher for AVPBooter DGST bypass.
-public final class AVPBooterPatcher: Patcher {
+public final class AVPBooterPatcher: BufferedPatcher {
public let component = "avpbooter"
public let verbose: Bool
+ /// Which patches the resolved preset turned on. Unrestricted by default.
+ public var gate: VPhonePatchGate = .unrestricted
+
let buffer: BinaryBuffer
let disasm = ARM64Disassembler()
var patches: [PatchRecord] = []
@@ -123,6 +127,8 @@ public final class AVPBooterPatcher: Patcher {
throw PatcherError.patchSiteNotFound("AVPBooter DGST: x0 setter not found before RET")
}
+ guard gateAllows("avpbooter.dgst_bypass") else { return }
+
let target = insns[targetIdx]
let fileOff = Int(target.address) // base address is 0, so VA == file offset
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swift
index a4476812..672a0abc 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swift
@@ -19,9 +19,10 @@ import Foundation
import Img4tool
import VPhoneArchiveKit
import VPhoneCoreKit
+import VPhonePatchKit
/// Patcher for the Filesystem payload.
-public final class CryptexFilesystemPatcher: Patcher {
+public final class CryptexFilesystemPatcher: BufferedPatcher {
public let component = "Filesystem"
public let restoreDir: URL
public let verbose: Bool
@@ -109,7 +110,7 @@ public final class CryptexFilesystemPatcher: Patcher {
rebuiltData = try serializePayload(updatedManifest)
guard attachedDevices.isEmpty else {
- throw FirmwarePatcher.PatcherError.patchVerificationFailed("The filesystem image is still attached. Detach it, then try again.")
+ throw VPhonePatchKit.PatcherError.patchVerificationFailed("The filesystem image is still attached. Detach it, then try again.")
}
return 1
@@ -157,7 +158,7 @@ public final class CryptexFilesystemPatcher: Patcher {
}
guard attachedDevices.isEmpty else {
- throw FirmwarePatcher.PatcherError.patchVerificationFailed("The filesystem image is still attached. Detach it, then try again.")
+ throw VPhonePatchKit.PatcherError.patchVerificationFailed("The filesystem image is still attached. Detach it, then try again.")
}
print("- Finalizing merged image…")
@@ -177,7 +178,7 @@ public final class CryptexFilesystemPatcher: Patcher {
func copyCryptex(targetMount: String, appOS: Bool = false, systemOS: Bool = false) throws {
guard appOS || systemOS, !(appOS && systemOS) else {
- throw FirmwarePatcher.PatcherError.patchVerificationFailed("Specify exactly one cryptex to copy: AppOS or SystemOS.")
+ throw VPhonePatchKit.PatcherError.patchVerificationFailed("Specify exactly one cryptex to copy: AppOS or SystemOS.")
}
let osPath = if appOS {
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherGuestPayload.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherGuestPayload.swift
index 66d5b3bb..6f2350c4 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherGuestPayload.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherGuestPayload.swift
@@ -6,6 +6,7 @@
import Foundation
import VPhoneCoreKit
+import VPhonePatchKit
import VPhoneSign
extension CryptexFilesystemPatcher {
@@ -92,7 +93,7 @@ extension CryptexFilesystemPatcher {
let bundle = target.appending(path: "/System/Library/Extensions/AppleParavirtGPUMetalIOGPUFamily.bundle")
let staged = VPhonePCCGPUDriver.stagedBundle(in: restoreDir)
guard FileManager.default.fileExists(atPath: staged.path) else {
- throw FirmwarePatcher.PatcherError.patchVerificationFailed(
+ throw VPhonePatchKit.PatcherError.patchVerificationFailed(
"PCC GPU driver is missing: \(staged.path). Re-run fw prepare with the PCC IPSW.",
)
}
@@ -112,7 +113,7 @@ extension CryptexFilesystemPatcher {
}
let compilerPlugin = bundle.appending(path: "libAppleParavirtCompilerPluginIOGPUFamily.dylib")
guard FileManager.default.fileExists(atPath: compilerPlugin.path) else {
- throw FirmwarePatcher.PatcherError.patchVerificationFailed(
+ throw VPhonePatchKit.PatcherError.patchVerificationFailed(
"PCC GPU compiler plugin is missing: \(compilerPlugin.path). Re-run fw prepare with a complete vphone-cli.app.",
)
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareBuildVersion.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareBuildVersion.swift
index 67d07191..95dba874 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareBuildVersion.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareBuildVersion.swift
@@ -19,6 +19,7 @@
// is told the target build and rewrites it.
import Foundation
+import VPhonePatchKit
/// Rewrites `ProductBuildVersion` in a `SystemVersion.plist`, preserving the
/// file's original plist format (XML in, XML out; binary in, binary out).
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareInjectDylib.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareInjectDylib.swift
index 714e7098..579e5002 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareInjectDylib.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareInjectDylib.swift
@@ -24,6 +24,7 @@
// policy is part of this API rather than a separate pass.
import Foundation
+import VPhonePatchKit
// MARK: - Byte Access
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareMachLookupExceptions.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareMachLookupExceptions.swift
index c13c2cbf..951c70c8 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareMachLookupExceptions.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareMachLookupExceptions.swift
@@ -16,6 +16,7 @@
// downgrade.
import Foundation
+import VPhonePatchKit
/// Merges the mach-lookup global-name exceptions Campo needs into an
/// entitlements plist, in place.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareMachOCodeSignature.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareMachOCodeSignature.swift
index b44c9875..829379e5 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareMachOCodeSignature.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareMachOCodeSignature.swift
@@ -21,6 +21,7 @@
import CryptoKit
import Foundation
+import VPhonePatchKit
// MARK: - Byte Reading
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift
index 0906c66b..891fa779 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift
@@ -29,6 +29,7 @@
import Foundation
import Img4tool
+import VPhonePatchKit
/// Rewrites the three restore-fatal identity properties in a
/// `devicetree.img4` (or bare `.im4p`), in place, preserving the container's
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CacheLoader/CustomFirmwareCacheLoader+Results.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CacheLoader/CustomFirmwareCacheLoader+Results.swift
index 39556521..e69413fe 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CacheLoader/CustomFirmwareCacheLoader+Results.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CacheLoader/CustomFirmwareCacheLoader+Results.swift
@@ -1,3 +1,5 @@
+import VPhonePatchKit
+
public extension CustomFirmwareCacheLoaderPatcher {
// MARK: - Results
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CacheLoader/CustomFirmwareCacheLoader+StringAnchor.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CacheLoader/CustomFirmwareCacheLoader+StringAnchor.swift
index 5650ec03..013ec03d 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CacheLoader/CustomFirmwareCacheLoader+StringAnchor.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CacheLoader/CustomFirmwareCacheLoader+StringAnchor.swift
@@ -1,5 +1,5 @@
-import Capstone
import Foundation
+import VPhonePatchKit
extension CustomFirmwareCacheLoaderPatcher {
// MARK: - The boot-arg string
@@ -120,21 +120,21 @@ extension CustomFirmwareCacheLoaderPatcher {
for (index, offset) in wordOffsets(of: text).enumerated() {
let vma = text.address + UInt64(offset - Int(text.fileOffset))
guard let instruction = disassembler.disassembleOne(in: data, at: offset, address: vma),
- let operands = instruction.aarch64?.operands
+ let operands = instruction.detail?.operands
else { continue }
switch instruction.mnemonic {
case "adrp":
guard operands.count >= 2,
- operands[0].type == AARCH64_OP_REG,
- operands[1].type == AARCH64_OP_IMM
+ operands[0].type == .register,
+ operands[1].type == .immediate
else { continue }
pendingADRP[UInt32(operands[0].reg.rawValue)] = (index, offset, vma, operands[1].imm)
case "add":
guard operands.count >= 3,
- operands[1].type == AARCH64_OP_REG,
- operands[2].type == AARCH64_OP_IMM,
+ operands[1].type == .register,
+ operands[2].type == .immediate,
let adrp = pendingADRP[UInt32(operands[1].reg.rawValue)],
adrp.page == targetPage,
operands[2].imm == targetPageOffset,
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CacheLoader/CustomFirmwareCacheLoader.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CacheLoader/CustomFirmwareCacheLoader.swift
index dbc27f47..418e8c49 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CacheLoader/CustomFirmwareCacheLoader.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CacheLoader/CustomFirmwareCacheLoader.swift
@@ -53,8 +53,8 @@
// pass `reattestsCodeSignature: true` or ship a binary TXM will SIGKILL on the
// first page-in of the patched page.
-import Capstone
import Foundation
+import VPhonePatchKit
/// NOPs the `launchd_unsecure_cache=` gate in `/usr/libexec/launchd_cache_loader`.
public enum CustomFirmwareCacheLoaderPatcher {
@@ -311,7 +311,7 @@ public enum CustomFirmwareCacheLoaderPatcher {
) throws -> Gate {
let disassembler = ARM64Disassembler()
let textEnd = Int(text.fileOffset) + Int(text.size)
- func decode(_ offset: Int) -> Instruction? {
+ func decode(_ offset: Int) -> ARM64Instruction? {
guard offset >= Int(text.fileOffset), offset + 4 <= textEnd else { return nil }
return disassembler.disassembleOne(
in: data,
@@ -320,7 +320,7 @@ public enum CustomFirmwareCacheLoaderPatcher {
)
}
- var call: Instruction?
+ var call: ARM64Instruction?
for step in 0 ..< maxInstructionsToCall {
guard let instruction = decode(anchor.referenceFileOffset + step * 4) else { break }
// A direct `bl` only — the string is an argument to a call, and an
@@ -372,8 +372,8 @@ public enum CustomFirmwareCacheLoaderPatcher {
)
}
- /// Conditional branches, decided on the mnemonic Capstone produced.
- static func isConditionalBranch(_ instruction: Instruction) -> Bool {
+ /// Conditional branches, decided on the decoded mnemonic.
+ static func isConditionalBranch(_ instruction: ARM64Instruction) -> Bool {
switch instruction.mnemonic {
case "cbz", "cbnz", "tbz", "tbnz": true
default: instruction.mnemonic.hasPrefix("b.")
@@ -388,10 +388,10 @@ public enum CustomFirmwareCacheLoaderPatcher {
/// branch, and NOP'ing it would be a silent miscompile of a boot-critical
/// binary — so this throws instead.
static func validate(
- gate: Instruction,
+ gate: ARM64Instruction,
in data: Data,
text: MachOSectionInfo,
- after call: Instruction?,
+ after call: ARM64Instruction?,
_ disassembler: ARM64Disassembler,
) throws {
if let target = branchTarget(of: gate) {
@@ -431,8 +431,8 @@ public enum CustomFirmwareCacheLoaderPatcher {
/// Whether some instruction between the call and the branch sets the flags
/// from x0/w0 — a `cmp`/`subs`/`ands`/`tst` reading register 0.
static func flagSetterOnResult(
- between call: Instruction,
- and gate: Instruction,
+ between call: ARM64Instruction,
+ and gate: ARM64Instruction,
in data: Data,
text: MachOSectionInfo,
_ disassembler: ARM64Disassembler,
@@ -442,11 +442,11 @@ public enum CustomFirmwareCacheLoaderPatcher {
defer { address += 4 }
let offset = Int(address - text.address) + Int(text.fileOffset)
guard let instruction = disassembler.disassembleOne(in: data, at: offset, address: address),
- instruction.aarch64?.updatesFlags == true,
- let operands = instruction.aarch64?.operands
+ instruction.detail?.updatesFlags == true,
+ let operands = instruction.detail?.operands
else { continue }
- for operand in operands where operand.type == AARCH64_OP_REG {
- let name = disassembler.registerName(UInt32(operand.reg.rawValue))
+ for operand in operands where operand.type == .register {
+ let name = operand.reg.name
if name == "x0" || name == "w0" {
return true
}
@@ -457,10 +457,10 @@ public enum CustomFirmwareCacheLoaderPatcher {
/// The absolute address a branch jumps to, read from its last immediate
/// operand, or `nil` when the instruction carries none.
- static func branchTarget(of instruction: Instruction) -> UInt64? {
- guard let operands = instruction.aarch64?.operands,
+ static func branchTarget(of instruction: ARM64Instruction) -> UInt64? {
+ guard let operands = instruction.detail?.operands,
let last = operands.last,
- last.type == AARCH64_OP_IMM,
+ last.type == .immediate,
last.imm >= 0
else { return nil }
return UInt64(last.imm)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/DiskImage/CustomFirmwareDiskImage+DynamicMetadata.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/DiskImage/CustomFirmwareDiskImage+DynamicMetadata.swift
index 1229374b..228f4247 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/DiskImage/CustomFirmwareDiskImage+DynamicMetadata.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/DiskImage/CustomFirmwareDiskImage+DynamicMetadata.swift
@@ -1,4 +1,5 @@
import Foundation
+import VPhonePatchKit
extension CustomFirmwareDiskImage {
// MARK: - ObjC metadata
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/DiskImage/CustomFirmwareDiskImage.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/DiskImage/CustomFirmwareDiskImage.swift
index 9c1d71a3..74af3287 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/DiskImage/CustomFirmwareDiskImage.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/DiskImage/CustomFirmwareDiskImage.swift
@@ -71,8 +71,8 @@
// drops the `ldid` step needs — and what makes `codesign -v` pass on the patched
// file on its own.
-import Capstone
import Foundation
+import VPhonePatchKit
/// Forces `-[DIDiskArb isMountCompleteWithExpectedCount:diskTracker:]` to
/// return YES so MobileStorageMounter stops waiting on a mount that will never
@@ -365,7 +365,7 @@ public enum CustomFirmwareDiskImage {
original,
at: virtualAddress ?? UInt64(fileOffset),
)
- guard decoded.count == length / 4, decoded.allSatisfy({ $0.id != 0 }) else { return nil }
+ guard decoded.count == length / 4, decoded.allSatisfy(\.isDecoded) else { return nil }
return site
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/Jetsam/CustomFirmwareJetsam.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/Jetsam/CustomFirmwareJetsam.swift
index 39698c1e..b941694c 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/Jetsam/CustomFirmwareJetsam.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/Jetsam/CustomFirmwareJetsam.swift
@@ -69,6 +69,7 @@
// `codesign -v`.
import Foundation
+import VPhonePatchKit
public enum CustomFirmwareJetsamPatcher {
// MARK: - Anchors
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/Jetsam/CustomFirmwareJetsamDiscovery.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/Jetsam/CustomFirmwareJetsamDiscovery.swift
index f99a4d7e..27e5aed0 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/Jetsam/CustomFirmwareJetsamDiscovery.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/Jetsam/CustomFirmwareJetsamDiscovery.swift
@@ -1,7 +1,7 @@
// CustomFirmwareJetsamDiscovery.swift — Locate the jetsam guard in launchd.
-import Capstone
import Foundation
+import VPhonePatchKit
extension CustomFirmwareJetsamPatcher {
/// `ARM64Disassembler` is stateless across calls and `Sendable`.
@@ -285,22 +285,22 @@ extension CustomFirmwareJetsamPatcher {
/// the last immediate covers all three without parsing operand text. The
/// instruction was decoded at its own file offset, so the immediate is a
/// file offset too.
- static func branchTarget(_ insn: Instruction) -> Int? {
- guard let detail = insn.aarch64 else { return nil }
- for operand in detail.operands.reversed() where operand.type == AARCH64_OP_IMM {
+ static func branchTarget(_ insn: ARM64Instruction) -> Int? {
+ guard let detail = insn.detail else { return nil }
+ for operand in detail.operands.reversed() where operand.type == .immediate {
return Int(operand.imm)
}
return nil
}
/// True when the instruction returns from the function — `ret`, `retaa`,
- /// `retab`, by Capstone's own classification rather than a mnemonic prefix.
+ /// `retab`, by the decoder's own classification rather than a mnemonic prefix.
///
/// The prefix test this replaces (`hasPrefix("ret")`) is close enough on
- /// this image and wrong in principle; the group is what Capstone decoded
- /// the instruction to mean.
- static func isReturn(_ insn: Instruction) -> Bool {
- insn.groups.contains(UInt8(CS_GRP_RET.rawValue))
+ /// this image and wrong in principle; the classification is what the
+ /// disassembler decoded the instruction to mean.
+ static func isReturn(_ insn: ARM64Instruction) -> Bool {
+ insn.isReturn
}
/// True when control leaves the block here without falling through: an
@@ -311,14 +311,14 @@ extension CustomFirmwareJetsamPatcher {
/// so the return can still be the instruction after it, which is what makes
/// a compare-and-return epilogue a return block.
///
- /// Groups again, not prefixes: `hasPrefix("br")` also swallows `brk`, which
- /// is a breakpoint (`CS_GRP_INT`) and ends nothing, and `hasPrefix("bl")`
+ /// Classification again, not prefixes: `hasPrefix("br")` also swallows
+ /// `brk`, which is a breakpoint and ends nothing, and `hasPrefix("bl")`
/// would only reach the authenticated calls by accident.
- static func leavesBlock(_ insn: Instruction) -> Bool {
- if insn.groups.contains(UInt8(CS_GRP_CALL.rawValue)) {
+ static func leavesBlock(_ insn: ARM64Instruction) -> Bool {
+ if insn.isCall {
return true
}
- return insn.groups.contains(UInt8(CS_GRP_JUMP.rawValue))
+ return insn.isJump
&& !conditionalBranchMnemonics.contains(insn.mnemonic)
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/MobileActivation/CustomFirmwareMobileActivation+Anchoring.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/MobileActivation/CustomFirmwareMobileActivation+Anchoring.swift
index 4c4d6626..d97e240a 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/MobileActivation/CustomFirmwareMobileActivation+Anchoring.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/MobileActivation/CustomFirmwareMobileActivation+Anchoring.swift
@@ -1,4 +1,5 @@
import Foundation
+import VPhonePatchKit
extension CustomFirmwareMobileActivation {
// MARK: - Anchoring
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/MobileActivation/CustomFirmwareMobileActivation.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/MobileActivation/CustomFirmwareMobileActivation.swift
index d387e72f..3fcaadda 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/MobileActivation/CustomFirmwareMobileActivation.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/MobileActivation/CustomFirmwareMobileActivation.swift
@@ -52,8 +52,8 @@
// `ldid_sign` stays a no-op-in-effect re-sign. Pass `resign: false` to get the
// Python's exact bytes.
-import Capstone
import Foundation
+import VPhonePatchKit
/// Forces `-[DeviceType should_hactivate]` to return YES, so the guest
/// self-activates instead of waiting on Apple's activation service.
@@ -296,9 +296,9 @@ public enum CustomFirmwareMobileActivation {
// MARK: - Body Shape
/// Decode the eight bytes the patch replaces.
- static func decodeBody(_ bytes: Data, at va: UInt64) throws -> [Instruction] {
+ static func decodeBody(_ bytes: Data, at va: UInt64) throws -> [ARM64Instruction] {
let decoded = ARM64Disassembler().disassemble(bytes, at: va, count: 2)
- guard decoded.count == 2, decoded.allSatisfy({ $0.id != 0 }) else {
+ guard decoded.count == 2, decoded.allSatisfy(\.isDecoded) else {
throw PatcherError.invalidFormat(
"\(method): the eight bytes at 0x\(hex(va)) (\(bytes.hex)) are not two "
+ "decodable instructions",
@@ -315,7 +315,7 @@ public enum CustomFirmwareMobileActivation {
/// is a plain function entry — rather than on `ldrb` specifically: a future
/// build may spell the getter differently, but overwriting eight bytes that
/// are *not* a function's first two words would land mid-function.
- static func isPlausibleGetterBody(_ body: [Instruction]) -> Bool {
+ static func isPlausibleGetterBody(_ body: [ARM64Instruction]) -> Bool {
guard body.count == 2 else { return false }
// A getter: `ldr…/mov… ; ret`.
if body[1].mnemonic == "ret" || body[1].mnemonic.hasPrefix("reta") {
@@ -329,7 +329,7 @@ public enum CustomFirmwareMobileActivation {
// MARK: - Helpers
- static func text(of instructions: [Instruction]) -> String {
+ static func text(of instructions: [ARM64Instruction]) -> String {
instructions
.map { $0.operandString.isEmpty ? $0.mnemonic : "\($0.mnemonic) \($0.operandString)" }
.joined(separator: "; ")
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/Sep/CustomFirmwareSeputil.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/Sep/CustomFirmwareSeputil.swift
index 8cb9557d..57ea13c7 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/Sep/CustomFirmwareSeputil.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/Sep/CustomFirmwareSeputil.swift
@@ -50,8 +50,8 @@
// binary that leaves this function verifies on its own. Pass
// `reattest: false` to reproduce the reference's bytes exactly.
-import Capstone
import Foundation
+import VPhonePatchKit
public enum CustomFirmwareSeputil {
// MARK: - Anchors
@@ -412,10 +412,10 @@ public enum CustomFirmwareSeputil {
var sites: [UInt64] = []
for (index, insn) in instructions.enumerated() {
guard insn.mnemonic == "adrp",
- let operands = insn.aarch64?.operands,
+ let operands = insn.detail?.operands,
operands.count == 2,
- operands[0].type == AARCH64_OP_REG,
- operands[1].type == AARCH64_OP_IMM,
+ operands[0].type == .register,
+ operands[1].type == .immediate,
UInt64(bitPattern: operands[1].imm) == page
else { continue }
@@ -426,12 +426,12 @@ public enum CustomFirmwareSeputil {
let candidate = instructions[cursor]
cursor += 1
guard candidate.mnemonic == "add",
- let addOperands = candidate.aarch64?.operands,
+ let addOperands = candidate.detail?.operands,
addOperands.count == 3,
- addOperands[0].type == AARCH64_OP_REG,
- addOperands[1].type == AARCH64_OP_REG,
+ addOperands[0].type == .register,
+ addOperands[1].type == .register,
addOperands[1].reg.rawValue == base,
- addOperands[2].type == AARCH64_OP_IMM,
+ addOperands[2].type == .immediate,
addOperands[2].imm == pageOffset,
!isShiftedAddImmediate(candidate)
else { continue }
@@ -444,12 +444,12 @@ public enum CustomFirmwareSeputil {
/// True when an `add` immediate carries `lsl #12`.
///
- /// The Swift Capstone wrapper does not surface an operand's shift, so the
+ /// PatchKit's decoded operands do not surface an operand's shift, so the
/// `sh` field is read off the instruction's own 32-bit encoding — still a
/// property of the decode, never of the printed operand text. Without it an
/// `add xD, xN, #imm, lsl #12` could be paired as if it computed
/// `page + imm`, which is a different address than it really forms.
- static func isShiftedAddImmediate(_ insn: Instruction) -> Bool {
+ static func isShiftedAddImmediate(_ insn: ARM64Instruction) -> Bool {
guard insn.bytes.count == 4 else { return false }
let word = UInt32(insn.bytes[0])
| UInt32(insn.bytes[1]) << 8
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/WatchDog/CustomFirmwareWatchDog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/WatchDog/CustomFirmwareWatchDog.swift
index 3fdea3ed..1b053b20 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/WatchDog/CustomFirmwareWatchDog.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/WatchDog/CustomFirmwareWatchDog.swift
@@ -90,8 +90,8 @@
// binary's cdHash; the JB kernel patch `patch_amfi_cdhash_in_trustcache`
// short-circuits AMFI's trust-cache check, and that precondition still holds.
-import Capstone
import Foundation
+import VPhonePatchKit
public enum CustomFirmwareWatchDog {
// MARK: - Anchors
@@ -383,20 +383,20 @@ public enum CustomFirmwareWatchDog {
// MARK: - Instruction helpers
/// Index of the first instruction at or after `from` that satisfies
- /// `predicate`, within `within` instructions. A word Capstone could not
- /// decode ends the window: past it the stream is no longer this function's
- /// instructions.
+ /// `predicate`, within `within` instructions. A word the disassembler could
+ /// not decode ends the window: past it the stream is no longer this
+ /// function's instructions.
static func firstIndex(
- in instructions: [Instruction],
+ in instructions: [ARM64Instruction],
from: Int,
within: Int,
- where predicate: (Instruction) -> Bool,
+ where predicate: (ARM64Instruction) -> Bool,
) -> Int? {
guard from >= 0 else { return nil }
let end = min(instructions.count, from + within)
var index = from
while index < end {
- guard instructions[index].id != 0 else { return nil }
+ guard instructions[index].isDecoded else { return nil }
if predicate(instructions[index]) {
return index
}
@@ -411,7 +411,7 @@ public enum CustomFirmwareWatchDog {
ofRegister register: UInt32,
before: Int,
notBefore: Int,
- in instructions: [Instruction],
+ in instructions: [ARM64Instruction],
) -> UInt64? {
var index = before - 1
while index >= notBefore {
@@ -426,9 +426,9 @@ public enum CustomFirmwareWatchDog {
return nil
}
- /// True for `mov wN, #1` in any encoding Capstone aliases to it (MOVZ, and
- /// the ORR-immediate form) — the shape this patch writes.
- static func isMoveOfOne(_ instruction: Instruction) -> Bool {
+ /// True for `mov wN, #1` in any encoding the disassembler aliases to it
+ /// (MOVZ, and the ORR-immediate form) — the shape this patch writes.
+ static func isMoveOfOne(_ instruction: ARM64Instruction) -> Bool {
guard instruction.mnemonic == "mov",
let register = registerName(instruction, 0), register.hasPrefix("w"),
let value = immediate(instruction, 1)
@@ -437,7 +437,7 @@ public enum CustomFirmwareWatchDog {
}
/// The instruction's raw little-endian word, for the branch decoder.
- static func word(of instruction: Instruction) -> UInt32 {
+ static func word(of instruction: ARM64Instruction) -> UInt32 {
var value: UInt32 = 0
for byte in instruction.bytes.prefix(4).reversed() {
value = (value << 8) | UInt32(byte)
@@ -445,30 +445,30 @@ public enum CustomFirmwareWatchDog {
return value
}
- static func registerName(_ instruction: Instruction, _ index: Int) -> String? {
- guard let operands = instruction.aarch64?.operands, index < operands.count,
- operands[index].type == AARCH64_OP_REG
+ static func registerName(_ instruction: ARM64Instruction, _ index: Int) -> String? {
+ guard let operands = instruction.detail?.operands, index < operands.count,
+ operands[index].type == .register
else { return nil }
- return sharedDisassembler.registerName(UInt32(operands[index].reg.rawValue))
+ return operands[index].reg.name
}
- static func registerNumber(_ instruction: Instruction, _ index: Int) -> UInt32? {
- guard let operands = instruction.aarch64?.operands, index < operands.count,
- operands[index].type == AARCH64_OP_REG
+ static func registerNumber(_ instruction: ARM64Instruction, _ index: Int) -> UInt32? {
+ guard let operands = instruction.detail?.operands, index < operands.count,
+ operands[index].type == .register
else { return nil }
return UInt32(operands[index].reg.rawValue)
}
- static func immediate(_ instruction: Instruction, _ index: Int) -> Int64? {
- guard let operands = instruction.aarch64?.operands, index < operands.count,
- operands[index].type == AARCH64_OP_IMM
+ static func immediate(_ instruction: ARM64Instruction, _ index: Int) -> Int64? {
+ guard let operands = instruction.detail?.operands, index < operands.count,
+ operands[index].type == .immediate
else { return nil }
return operands[index].imm
}
- static func memoryOperand(_ instruction: Instruction) -> aarch64_op_mem? {
- guard let operands = instruction.aarch64?.operands,
- let operand = operands.first(where: { $0.type == AARCH64_OP_MEM })
+ static func memoryOperand(_ instruction: ARM64Instruction) -> ARM64MemoryOperand? {
+ guard let operands = instruction.detail?.operands,
+ let operand = operands.first(where: { $0.type == .memory })
else { return nil }
return operand.mem
}
@@ -481,10 +481,6 @@ public enum CustomFirmwareWatchDog {
return number
}
- /// Capstone handle used only for register-name lookups, which need no
- /// per-call state.
- static let sharedDisassembler = ARM64Disassembler()
-
// MARK: - Addresses
static func fileOffset(of address: UInt64, in text: MachOSectionInfo) -> Int {
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/WatchDog/CustomFirmwareWatchDogDiscovery.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/WatchDog/CustomFirmwareWatchDogDiscovery.swift
index b9392d6d..967d9caf 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/WatchDog/CustomFirmwareWatchDogDiscovery.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/WatchDog/CustomFirmwareWatchDogDiscovery.swift
@@ -1,7 +1,7 @@
// CustomFirmwareWatchDogDiscovery.swift — Locate watchdogd VM-presence cache sites.
-import Capstone
import Foundation
+import VPhonePatchKit
extension CustomFirmwareWatchDog {
// MARK: - Site discovery
@@ -42,10 +42,10 @@ extension CustomFirmwareWatchDog {
var sites: [Site] = []
for (index, instruction) in instructions.enumerated() {
- // Capstone runs with `skipData` on, so a word it cannot decode
- // arrives as a data pseudo-instruction rather than ending the
+ // The disassembler runs with skip-data on, so a word it cannot
+ // decode arrives as a data pseudo-instruction rather than ending the
// stream. Register state across such a word means nothing.
- guard instruction.id != 0 else {
+ guard instruction.isDecoded else {
pages.removeAll()
continue
}
@@ -99,7 +99,7 @@ extension CustomFirmwareWatchDog {
/// pointer. Returns `nil` when any layer of the anchor fails, which is how
/// the three unrelated `sysctlbyname` calls in watchdogd are rejected.
static func matchSite(
- instructions: [Instruction],
+ instructions: [ARM64Instruction],
addIndex: Int,
pointerRegister: String,
literalVMA: UInt64,
@@ -151,7 +151,7 @@ extension CustomFirmwareWatchDog {
where: { instruction in
switch state {
case .pristine:
- instruction.mnemonic == "cset" && instruction.aarch64?.conditionCode == AArch64CC_NE
+ instruction.mnemonic == "cset" && instruction.detail?.conditionCode == .ne
case .patched:
isMoveOfOne(instruction)
}
@@ -210,7 +210,7 @@ extension CustomFirmwareWatchDog {
inRegister pointer: String,
from addIndex: Int,
toCallAt callIndex: Int,
- in instructions: [Instruction],
+ in instructions: [ARM64Instruction],
) -> Bool {
if pointer == argumentRegister {
return true
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/WatchDog/CustomFirmwareWatchDogSymbolTargets.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/WatchDog/CustomFirmwareWatchDogSymbolTargets.swift
index da3e42f4..f16bd8b2 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/WatchDog/CustomFirmwareWatchDogSymbolTargets.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/WatchDog/CustomFirmwareWatchDogSymbolTargets.swift
@@ -1,6 +1,7 @@
// CustomFirmwareWatchDogSymbolTargets.swift — Resolve watchdogd branch targets.
import Foundation
+import VPhonePatchKit
// MARK: - Symbol targets
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift
index 28015b5b..2892b089 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift
@@ -9,12 +9,16 @@
// 3. Serialize the modified tree back to flat binary.
import Foundation
+import VPhonePatchKit
/// Patcher for DeviceTree payloads.
-public final class DeviceTreePatcher: Patcher {
+public final class DeviceTreePatcher: BufferedPatcher {
public let component = "devicetree"
public let verbose: Bool
+ /// Which patches the resolved preset turned on. Unrestricted by default.
+ public var gate: VPhonePatchGate = .unrestricted
+
/// Whether to apply the 8 identity-rewrite property patches (Tier 1b + 1c)
/// that flip device identity towards iPhone17,3 / D47AP. Enabled for
/// public JB and the historical internal EXP variant.
@@ -300,6 +304,11 @@ public final class DeviceTreePatcher: Patcher {
patchesToApply.append(contentsOf: Self.identityPropertyPatches)
}
for patch in patchesToApply {
+ // Before the property is rewritten, not after: the tree is serialised
+ // from these nodes, so a skipped record with a mutated node would
+ // still change the output.
+ guard gateAllows(patch.patchID) else { continue }
+
let node = try resolveNode(root, path: patch.nodePath)
let prop = try findProperty(node, name: patch.property)
@@ -354,6 +363,8 @@ public final class DeviceTreePatcher: Patcher {
/// parent — keeps the patch idempotent so re-runs against an
/// already-patched DT don't double-add.
private func applyNodeAddition(root: DTNode, patch: AddChildNodePatch) throws {
+ guard gateAllows(patch.patchID) else { return }
+
let parent = try resolveNode(root, path: patch.parentPath)
for existing in parent.children {
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift
index e8694fec..987205cd 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift
@@ -33,6 +33,7 @@
// one file, which on this cache accepts every seam the Python accepts.
import Foundation
+import VPhonePatchKit
/// A half-open span of virtual addresses that was written, or is about to be.
///
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheCodeSignature.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheCodeSignature.swift
index 8938aa66..0b700c29 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheCodeSignature.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheCodeSignature.swift
@@ -47,6 +47,7 @@
import CryptoKit
import Foundation
+import VPhonePatchKit
/// The `CS_CodeDirectory` of one chunk, reduced to what re-signing needs.
public struct DyldSharedCacheChunkCodeDirectory: Sendable {
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheError.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheError.swift
index a043684f..a80bef6c 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheError.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheError.swift
@@ -1,6 +1,7 @@
// DyldSharedCacheError.swift — Errors raised by the dyld shared cache foundation layer.
import Foundation
+import VPhonePatchKit
/// Failures specific to reading and writing a chunked dyld shared cache.
///
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheLocalSymbolTable.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheLocalSymbolTable.swift
index af1a4fbb..97124e21 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheLocalSymbolTable.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheLocalSymbolTable.swift
@@ -27,6 +27,7 @@
// };
import Foundation
+import VPhonePatchKit
/// Reader over `dyld_shared_cache_<arch>.symbols`.
public struct DyldSharedCacheLocalSymbolTable: Sendable {
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheCameraPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheCameraPatcher.swift
index bd8833cb..453133ed 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheCameraPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheCameraPatcher.swift
@@ -69,8 +69,8 @@
// `--avf-only` is `applyAVFAuthorizationOnly`: the composition mode for a chunk
// pulled off a device that already carries the NeutrinoCore patches.
-import Capstone
import Foundation
+import VPhonePatchKit
/// The camera-related patches applied to the SystemOS cryptex's shared cache.
public enum DyldSharedCacheCameraPatcher {
@@ -428,19 +428,19 @@ public enum DyldSharedCacheCameraPatcher {
/// method already return that constant", and a byte comparison would answer
/// a narrower one that only happens to coincide. `movz` is accepted
/// alongside its `mov` alias so the answer does not depend on which of the
- /// two Capstone prints.
+ /// two the disassembler prints.
static func isReturnConstantShape(
- _ decoded: [Instruction],
+ _ decoded: [ARM64Instruction],
returning value: UInt16,
disassembler: ARM64Disassembler,
) -> Bool {
guard decoded.count == 2,
decoded[1].mnemonic == "ret",
decoded[0].mnemonic == "mov" || decoded[0].mnemonic == "movz",
- let operands = decoded[0].aarch64?.operands,
+ let operands = decoded[0].detail?.operands,
operands.count == 2,
- operands[0].type == AARCH64_OP_REG,
- operands[1].type == AARCH64_OP_IMM,
+ operands[0].type == .register,
+ operands[1].type == .immediate,
disassembler.firstRegisterName(decoded[0]) == "w0"
else { return false }
return operands[1].imm == Int64(value)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher+MachOStringSites.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher+MachOStringSites.swift
index 0669911e..2efa15b6 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher+MachOStringSites.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher+MachOStringSites.swift
@@ -1,4 +1,5 @@
import Foundation
+import VPhonePatchKit
public extension DyldSharedCacheHypervisorVirtualMachinePatcher {
/// One occurrence of the pristine cstring in a standalone Mach-O.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher.swift
index e6d66514..8a70308c 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher.swift
@@ -72,6 +72,7 @@
// write itself, so it is the page that changed by construction.
import Foundation
+import VPhonePatchKit
/// The user-mode `kern.hv_vmm_present` cstring mangle, over a chunked dyld
/// shared cache and over standalone Mach-Os.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBForceKernPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBForceKernPatcher.swift
index ace03eed..30c75370 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBForceKernPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBForceKernPatcher.swift
@@ -59,8 +59,8 @@
// written, so that check happens while the cache is still untouched. On the
// success path the bytes are identical.
-import Capstone
import Foundation
+import VPhonePatchKit
/// Retargets IOMobileFramebuffer's public swap trampolines at their `_kern_`
/// implementations, inside a chunked dyld shared cache.
@@ -333,18 +333,18 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {
/// True iff the four instructions are
/// `cbz x0, … ; ldr xN, [x0, #imm] ; cbz xN, … ; braaz xN`.
///
- /// Matched on typed Capstone operands rather than on the operand text: the
+ /// Matched on typed decoded operands rather than on the operand text: the
/// base register of the load, the register the fp lands in and the register
/// the tail-call branches through are compared as register identities, so
/// `x1` cannot match the `x10` that a prefix test on the printed string
/// would accept.
- public static func isDispatchTrampoline(_ instructions: [Instruction]) -> Bool {
+ public static func isDispatchTrampoline(_ instructions: [ARM64Instruction]) -> Bool {
guard instructions.count >= 4 else { return false }
let (check, load, guardBranch, tailCall) =
(instructions[0], instructions[1], instructions[2], instructions[3])
// cbz x0, <fail> — the connection pointer.
- guard check.mnemonic == "cbz", register(check, at: 0) == AARCH64_REG_X0 else {
+ guard check.mnemonic == "cbz", register(check, at: 0) == .x(0) else {
return false
}
@@ -353,8 +353,8 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {
guard load.mnemonic == "ldr",
let scratch = register(load, at: 0),
let memory = memory(load),
- memory.base == AARCH64_REG_X0,
- memory.index == AARCH64_REG_INVALID,
+ memory.base == .x(0),
+ memory.index == .invalid,
memory.disp != 0
else { return false }
@@ -428,23 +428,23 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {
// MARK: - Typed operand access
- private static func register(_ instruction: Instruction, at index: Int) -> aarch64_reg? {
- guard let operands = instruction.aarch64?.operands, index < operands.count,
- operands[index].type == AARCH64_OP_REG
+ private static func register(_ instruction: ARM64Instruction, at index: Int) -> ARM64Register? {
+ guard let operands = instruction.detail?.operands, index < operands.count,
+ operands[index].type == .register
else { return nil }
return operands[index].reg
}
- private static func immediate(_ instruction: Instruction, at index: Int) -> Int64? {
- guard let operands = instruction.aarch64?.operands, index < operands.count,
- operands[index].type == AARCH64_OP_IMM
+ private static func immediate(_ instruction: ARM64Instruction, at index: Int) -> Int64? {
+ guard let operands = instruction.detail?.operands, index < operands.count,
+ operands[index].type == .immediate
else { return nil }
return operands[index].imm
}
- private static func memory(_ instruction: Instruction) -> aarch64_op_mem? {
- guard let operands = instruction.aarch64?.operands,
- let operand = operands.first(where: { $0.type == AARCH64_OP_MEM })
+ private static func memory(_ instruction: ARM64Instruction) -> ARM64MemoryOperand? {
+ guard let operands = instruction.detail?.operands,
+ let operand = operands.first(where: { $0.type == .memory })
else { return nil }
return operand.mem
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBSwapEndPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBSwapEndPatcher.swift
index 3c5ca2ce..036e64e4 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBSwapEndPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBSwapEndPatcher.swift
@@ -51,8 +51,8 @@
// reads the cache's export tries and its `.symbols` side file directly — same
// addresses, no Go tool on the patch path.
-import Capstone
import Foundation
+import VPhonePatchKit
/// What one run of the SwapEnd size patch did.
public struct DyldSharedCacheIOMFBSwapEndPatch: Sendable {
@@ -257,7 +257,7 @@ public enum DyldSharedCacheIOMFBSwapEndPatcher {
/// The `mov w3, #imm` found inside the external-method call set-up, with the
/// index it sits at — the index is what the tests assert the shape on.
struct SizeSite {
- let instruction: Instruction
+ let instruction: ARM64Instruction
let index: Int
}
@@ -270,7 +270,7 @@ public enum DyldSharedCacheIOMFBSwapEndPatcher {
/// operand — register identity and immediate value — never on the rendered
/// operand string.
static func findSizeInstruction(
- in instructions: [Instruction],
+ in instructions: [ARM64Instruction],
disassembler: ARM64Disassembler,
) -> SizeSite? {
// selector, size, the zeroed argument registers, then the call.
@@ -308,18 +308,18 @@ public enum DyldSharedCacheIOMFBSwapEndPatcher {
/// `(register, immediate)` when `instruction` is `mov <reg>, #<imm>`, else
/// `nil`.
///
- /// The register name comes from Capstone's own register table rather than
+ /// The register name comes from the decoder's own register table rather than
/// from splitting `operandString`, so `w3` and `w13` cannot be confused and
- /// a change in how Capstone renders an operand cannot move the site.
+ /// a change in how an operand renders cannot move the site.
static func movRegisterImmediate(
- _ instruction: Instruction,
+ _ instruction: ARM64Instruction,
disassembler: ARM64Disassembler,
) -> (register: String, immediate: Int64)? {
guard instruction.mnemonic == "mov" else { return nil }
- guard let operands = instruction.aarch64?.operands, operands.count == 2,
- operands[0].type == AARCH64_OP_REG,
- operands[1].type == AARCH64_OP_IMM,
- let name = disassembler.registerName(UInt32(operands[0].reg.rawValue))
+ guard let operands = instruction.detail?.operands, operands.count == 2,
+ operands[0].type == .register,
+ operands[1].type == .immediate,
+ let name = operands[0].reg.name
else { return nil }
return (name, operands[1].imm)
}
@@ -335,13 +335,13 @@ public enum DyldSharedCacheIOMFBSwapEndPatcher {
at vma: UInt64,
maximumInstructions: Int,
disassembler: ARM64Disassembler,
- ) throws -> [Instruction] {
+ ) throws -> [ARM64Instruction] {
let code = try chunks.readAtVMA(
vma,
length: maximumInstructions * 4,
allowShort: true,
)
- var result: [Instruction] = []
+ var result: [ARM64Instruction] = []
for instruction in disassembler.disassemble(code, at: vma, count: maximumInstructions) {
result.append(instruction)
if instruction.mnemonic == "ret" || instruction.mnemonic == "retab" {
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLSDEmbeddedRegPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLSDEmbeddedRegPatcher.swift
index c80731b5..fd976d8f 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLSDEmbeddedRegPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLSDEmbeddedRegPatcher.swift
@@ -43,8 +43,8 @@
// page is re-attested (TXM enforces per-page); the CDHash change that follows
// is accepted by the JB's always-true AMFI cdhash-trust patch.
-import Capstone
import Foundation
+import VPhonePatchKit
/// Forces `-[_LSDModifyClient clientIsEntitledForEmbeddedRegistrationOperations]`
/// to return YES, by NOP'ing the branch that skips its YES result.
@@ -248,22 +248,21 @@ public enum DyldSharedCacheLSDEmbeddedRegPatcher {
static func disassembleFunction(
in chunks: DyldSharedCacheChunkSet,
at vma: UInt64,
- ) throws -> [Instruction] {
+ ) throws -> [ARM64Instruction] {
let buffer = try chunks.readAtVMA(
vma,
length: maxInstructions * 4,
allowShort: true,
)
let decoded = ARM64Disassembler().disassemble(buffer, at: vma)
- var result: [Instruction] = []
+ var result: [ARM64Instruction] = []
for instruction in decoded {
- // The shared disassembler has `skipData` on, so a word Capstone
- // cannot decode arrives as a data pseudo-instruction (id 0) rather
- // than ending the stream. The Python's `cs.disasm` stops there, and
- // so does this: past an undecodable word the window is no longer
- // this function's instructions, and matching a "gate" in it would
- // be matching noise.
- guard instruction.id != 0 else { break }
+ // The shared disassembler has skip-data on, so a word it cannot
+ // decode arrives as a data pseudo-instruction rather than ending the
+ // stream. The Python's `cs.disasm` stops there, and so does this:
+ // past an undecodable word the window is no longer this function's
+ // instructions, and matching a "gate" in it would be matching noise.
+ guard instruction.isDecoded else { break }
result.append(instruction)
if instruction.mnemonic == "ret" || instruction.mnemonic == "retab" {
break
@@ -279,7 +278,7 @@ public enum DyldSharedCacheLSDEmbeddedRegPatcher {
/// output, so a second run over an already-patched cache recognises the
/// idempotent state instead of failing to find a branch that is no longer
/// there — which is exactly how a re-run of `cfw install` used to die.
- static func findGate(in instructions: [Instruction]) -> Gate? {
+ static func findGate(in instructions: [ARM64Instruction]) -> Gate? {
let disassembler = ARM64Disassembler()
guard instructions.count >= 2 else { return nil }
@@ -313,14 +312,14 @@ public enum DyldSharedCacheLSDEmbeddedRegPatcher {
/// Matched on decoded operand types — register destination, immediate
/// source — rather than on operand text.
static func movRegisterImmediate(
- _ instruction: Instruction,
+ _ instruction: ARM64Instruction,
_ disassembler: ARM64Disassembler,
) -> (register: String, immediate: Int64)? {
guard instruction.mnemonic == "mov",
- let operands = instruction.aarch64?.operands,
+ let operands = instruction.detail?.operands,
operands.count == 2,
- operands[0].type == AARCH64_OP_REG,
- operands[1].type == AARCH64_OP_IMM,
+ operands[0].type == .register,
+ operands[1].type == .immediate,
let register = disassembler.firstRegisterName(instruction)
else { return nil }
return (register, operands[1].imm)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLockdownModePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLockdownModePatcher.swift
index 7440d575..e5e337a0 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLockdownModePatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLockdownModePatcher.swift
@@ -35,8 +35,8 @@
// and the `PatchRecord` description, never a patched byte, and nothing here
// matches on operand text.
-import Capstone
import Foundation
+import VPhonePatchKit
public enum DyldSharedCacheLockdownModePatcher {
// MARK: - Anchors
@@ -260,11 +260,11 @@ public enum DyldSharedCacheLockdownModePatcher {
/// A wrong patch that passes its own signature check is worse than a
/// failed install. `DyldSharedCacheLSDEmbeddedRegPatcher.disassembleFunction` breaks on
/// the same condition for the same reason.
- static func disassembleBlock(in chunks: DyldSharedCacheChunkSet, at vma: UInt64) throws -> [Instruction] {
+ static func disassembleBlock(in chunks: DyldSharedCacheChunkSet, at vma: UInt64) throws -> [ARM64Instruction] {
let window = try chunks.readAtVMA(vma, length: maxInstructions * 4, allowShort: true)
- var decoded: [Instruction] = []
+ var decoded: [ARM64Instruction] = []
for insn in disassembler.disassemble(window, at: vma, count: maxInstructions) {
- guard insn.id != 0 else { break }
+ guard insn.isDecoded else { break }
decoded.append(insn)
if insn.mnemonic == "ret" || insn.mnemonic == "retab" {
break
@@ -282,7 +282,7 @@ public enum DyldSharedCacheLockdownModePatcher {
/// fails instead of reporting a no-op. The `bl` + `cmn wR, #1` anchor is
/// unchanged, so widening the slot does not weaken where a match can land,
/// and re-writing a NOP over a NOP is inert.
- static func findErrorGate(_ instructions: [Instruction]) -> Instruction? {
+ static func findErrorGate(_ instructions: [ARM64Instruction]) -> ARM64Instruction? {
guard instructions.count >= 2 else { return nil }
var sawCall = false
for index in 0 ..< (instructions.count - 1) {
@@ -304,10 +304,10 @@ public enum DyldSharedCacheLockdownModePatcher {
///
/// Semantic, not textual: the `#1` of `cmn w0, #1` is read off the decode,
/// so a build that prints it as `#0x1` matches just the same.
- static func immediate(of insn: Instruction, at index: Int) -> Int64? {
- guard let operands = insn.aarch64?.operands,
+ static func immediate(of insn: ARM64Instruction, at index: Int) -> Int64? {
+ guard let operands = insn.detail?.operands,
index < operands.count,
- operands[index].type == AARCH64_OP_IMM
+ operands[index].type == .immediate
else { return nil }
return operands[index].imm
}
@@ -315,7 +315,7 @@ public enum DyldSharedCacheLockdownModePatcher {
// MARK: - Reporting
private static func record(
- for gate: Instruction,
+ for gate: ARM64Instruction,
original: Data,
replacement: Data,
in chunks: DyldSharedCacheChunkSet,
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swift
index e8f39f94..c831c1b4 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swift
@@ -64,6 +64,7 @@
// layout is refused rather than written into blind.
import Foundation
+import VPhonePatchKit
/// Zeroes `dyld_cache_header.maxSlide` when the cache would otherwise overflow
/// the kernel's fixed shared region.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheXPCLWCRPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheXPCLWCRPatcher.swift
index 007cf833..ba227660 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheXPCLWCRPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheXPCLWCRPatcher.swift
@@ -49,8 +49,8 @@
// cache per 16 KiB page; the resulting cdHash change is accepted by the JB's
// always-true AMFI cdhash-trust patch.
-import Capstone
import Foundation
+import VPhonePatchKit
/// Patches `_xpc_token_satisfies_lwcr` in the shared cache's libxpc.
public enum DyldSharedCacheXPCLWCRPatcher {
@@ -253,9 +253,9 @@ public enum DyldSharedCacheXPCLWCRPatcher {
/// The three instructions the patch rewrites.
struct ConsistencyCheck {
- let cset: Instruction
- let eor: Instruction
- let tbz: Instruction
+ let cset: ARM64Instruction
+ let eor: ARM64Instruction
+ let tbz: ARM64Instruction
}
/// Locate the LWCR self-consistency idiom.
@@ -269,7 +269,7 @@ public enum DyldSharedCacheXPCLWCRPatcher {
/// `cset` and the `tbz` are common shapes on their own, and the register
/// dataflow between the three is what makes the match unambiguous.
static func findConsistencyCheck(
- in instructions: [Instruction],
+ in instructions: [ARM64Instruction],
disassembler: ARM64Disassembler,
) -> ConsistencyCheck? {
guard instructions.count >= 2 else { return nil }
@@ -290,14 +290,14 @@ public enum DyldSharedCacheXPCLWCRPatcher {
else { continue }
// The `cset wC, ne` feeding the xor, within a short window back.
- var cset: Instruction?
+ var cset: ARM64Instruction?
var back = index - 1
while back >= 0, back >= index - 5 {
let candidate = instructions[back]
if candidate.mnemonic == "cset", register(candidate, 0, disassembler) == source {
- // The condition is read off Capstone's decode, not the
- // printed operand text.
- if candidate.aarch64?.conditionCode == AArch64CC_NE {
+ // The condition is read off the decode, not the printed
+ // operand text.
+ if candidate.detail?.conditionCode == .ne {
cset = candidate
}
break
@@ -323,15 +323,15 @@ public enum DyldSharedCacheXPCLWCRPatcher {
/// that search looks for the very instructions this patch replaced. On an
/// already-patched cache the idiom is gone by construction.
static func findPatchedShape(
- in instructions: [Instruction],
+ in instructions: [ARM64Instruction],
disassembler: ARM64Disassembler,
- ) -> Instruction? {
+ ) -> ARM64Instruction? {
guard instructions.count >= 3 else { return nil }
for index in 0 ..< (instructions.count - 2) {
let cset = instructions[index]
guard cset.mnemonic == "cset",
register(cset, 0, disassembler) == "w0",
- cset.aarch64?.conditionCode == AArch64CC_EQ,
+ cset.detail?.conditionCode == .eq,
instructions[index + 1].mnemonic == "nop",
instructions[index + 2].mnemonic == "nop"
else { continue }
@@ -345,7 +345,7 @@ public enum DyldSharedCacheXPCLWCRPatcher {
back -= 1
continue
}
- let operands = candidate.aarch64?.operands ?? []
+ let operands = candidate.detail?.operands ?? []
if operands.count == 2, let value = immediate(candidate, 1), value == 0 {
return cset
}
@@ -367,9 +367,9 @@ public enum DyldSharedCacheXPCLWCRPatcher {
in chunks: DyldSharedCacheChunkSet,
at vma: UInt64,
disassembler: ARM64Disassembler,
- ) throws -> [Instruction] {
+ ) throws -> [ARM64Instruction] {
let window = try chunks.readAtVMA(vma, length: maxInstructions * 4, allowShort: true)
- var result: [Instruction] = []
+ var result: [ARM64Instruction] = []
for insn in disassembler.disassemble(window, at: vma) {
result.append(insn)
if insn.mnemonic == "ret" || insn.mnemonic == "retab" {
@@ -383,21 +383,21 @@ public enum DyldSharedCacheXPCLWCRPatcher {
/// Canonical name of operand `index` when it is a register, else `nil`.
static func register(
- _ insn: Instruction,
+ _ insn: ARM64Instruction,
_ index: Int,
_ disassembler: ARM64Disassembler,
) -> String? {
- guard let operands = insn.aarch64?.operands, index < operands.count else { return nil }
+ guard let operands = insn.detail?.operands, index < operands.count else { return nil }
let operand = operands[index]
- guard operand.type == AARCH64_OP_REG else { return nil }
- return disassembler.registerName(UInt32(operand.reg.rawValue))
+ guard operand.type == .register else { return nil }
+ return operand.reg.name
}
/// Value of operand `index` when it is an immediate, else `nil`.
- static func immediate(_ insn: Instruction, _ index: Int) -> Int64? {
- guard let operands = insn.aarch64?.operands, index < operands.count else { return nil }
+ static func immediate(_ insn: ARM64Instruction, _ index: Int) -> Int64? {
+ guard let operands = insn.detail?.operands, index < operands.count else { return nil }
let operand = operands[index]
- guard operand.type == AARCH64_OP_IMM else { return nil }
+ guard operand.type == .immediate else { return nil }
return operand.imm
}
@@ -431,7 +431,7 @@ public enum DyldSharedCacheXPCLWCRPatcher {
)
}
- private static func text(_ insn: Instruction) -> String {
+ private static func text(_ insn: ARM64Instruction) -> String {
insn.operandString.isEmpty ? insn.mnemonic : "\(insn.mnemonic) \(insn.operandString)"
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/BasePatches/IBootPatchBootArgs.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/BasePatches/IBootPatchBootArgs.swift
index 76fc0c9f..17d3be4b 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/BasePatches/IBootPatchBootArgs.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/BasePatches/IBootPatchBootArgs.swift
@@ -2,8 +2,8 @@
//
// Part of IBootPatcher; see IBootPatcher.swift for the patch schedule by mode.
-import Capstone
import Foundation
+import VPhonePatchKit
extension IBootPatcher {
// MARK: - 3. Boot-Args (iBEC / LLB)
@@ -114,7 +114,7 @@ extension IBootPatcher {
// 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 let aDetail = a.detail, let bDetail = b.detail else { continue }
guard aDetail.operands.count >= 2, bDetail.operands.count >= 3 else { continue }
// ADRP Rd must equal ADD Rn (same register)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/BasePatches/IBootPatchBootxPrecondition.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/BasePatches/IBootPatchBootxPrecondition.swift
index b5f96c12..cbd182d1 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/BasePatches/IBootPatchBootxPrecondition.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/BasePatches/IBootPatchBootxPrecondition.swift
@@ -2,8 +2,8 @@
//
// Part of IBootPatcher; see IBootPatcher.swift for the patch schedule by mode.
-import Capstone
import Foundation
+import VPhonePatchKit
extension IBootPatcher {
// MARK: - 6. Bootx-handoff precondition (modern iBoot, all stages)
@@ -55,22 +55,22 @@ extension IBootPatcher {
let prev = insns[i - 1]
guard tbz.mnemonic == "tbz" else { continue }
guard
- let tbzDet = tbz.aarch64,
+ let tbzDet = tbz.detail,
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[0].type == .register,
+ tbzDet.operands[0].reg == .w(0),
+ tbzDet.operands[1].type == .immediate,
tbzDet.operands[1].imm == 0,
- tbzDet.operands[2].type == AARCH64_OP_IMM
+ tbzDet.operands[2].type == .immediate
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,
+ let prevDet = prev.detail,
prevDet.operands.count >= 1,
- prevDet.operands[0].type == AARCH64_OP_IMM
+ prevDet.operands[0].type == .immediate
else { continue }
let blTarget = Int(prevDet.operands[0].imm)
guard bitGetters.contains(blTarget) else { continue }
@@ -123,9 +123,9 @@ extension IBootPatcher {
var ok = true
for k in 0 ..< 4 {
guard
- let det = insns[i + k].aarch64,
+ let det = insns[i + k].detail,
det.operands.count >= 1,
- det.operands[0].type == AARCH64_OP_REG
+ det.operands[0].type == .register
else { ok = false; break }
regs.insert(det.operands[0].reg.rawValue)
}
@@ -151,9 +151,9 @@ extension IBootPatcher {
]
guard mnems == ["adrp", "ldrb", "ubfx", "ret"] else { continue }
guard
- let det = insns[i + 2].aarch64,
+ let det = insns[i + 2].detail,
det.operands.count >= 4,
- det.operands[3].type == AARCH64_OP_IMM,
+ det.operands[3].type == .immediate,
det.operands[3].imm == 1
else { continue }
out.insert(Int(insns[i].address))
@@ -176,9 +176,9 @@ extension IBootPatcher {
insns[i + 2].mnemonic == "bl"
else { continue }
guard
- let det = insns[i].aarch64,
+ let det = insns[i].detail,
det.operands.count >= 1,
- det.operands[0].type == AARCH64_OP_IMM
+ det.operands[0].type == .immediate
else { continue }
let blTarget = Int(det.operands[0].imm)
guard hashGetters.contains(blTarget) else { continue }
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/BasePatches/IBootPatchImage4Callback.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/BasePatches/IBootPatchImage4Callback.swift
index 6c5ce5e2..043df9ab 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/BasePatches/IBootPatchImage4Callback.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/BasePatches/IBootPatchImage4Callback.swift
@@ -2,8 +2,8 @@
//
// Part of IBootPatcher; see IBootPatcher.swift for the patch schedule by mode.
-import Capstone
import Foundation
+import VPhonePatchKit
extension IBootPatcher {
// MARK: - 2. image4_validate_property_callback
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/BasePatches/IBootPatchPanicBypass.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/BasePatches/IBootPatchPanicBypass.swift
index d3fb6f50..b39dd0e3 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/BasePatches/IBootPatchPanicBypass.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/BasePatches/IBootPatchPanicBypass.swift
@@ -2,8 +2,8 @@
//
// Part of IBootPatcher; see IBootPatcher.swift for the patch schedule by mode.
-import Capstone
import Foundation
+import VPhonePatchKit
extension IBootPatcher {
// MARK: - 5. Panic Bypass (LLB only)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/BasePatches/IBootPatchRootfsBypass.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/BasePatches/IBootPatchRootfsBypass.swift
index f32ec4d3..0541dc24 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/BasePatches/IBootPatchRootfsBypass.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/BasePatches/IBootPatchRootfsBypass.swift
@@ -2,8 +2,8 @@
//
// Part of IBootPatcher; see IBootPatcher.swift for the patch schedule by mode.
-import Capstone
import Foundation
+import VPhonePatchKit
extension IBootPatcher {
// MARK: - 4. Rootfs Bypass (LLB only)
@@ -54,7 +54,7 @@ extension IBootPatcher {
}
// Extract branch target from the operand string (last operand is the immediate)
- guard let detail = insn.aarch64, detail.operands.count >= 2 else { return }
+ guard let detail = insn.detail, detail.operands.count >= 2 else { return }
let target = Int(detail.operands[1].imm)
guard let bInsn = ARM64Encoder.encodeB(from: cbzOff, to: target) else {
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/IBootJailbreakPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/IBootJailbreakPatcher.swift
index 72e404a8..8431303d 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/IBootJailbreakPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/IBootJailbreakPatcher.swift
@@ -2,8 +2,8 @@
//
// Historical note: derived from the legacy Python firmware patcher during the Swift migration.
-import Capstone
import Foundation
+import VPhonePatchKit
/// JB-variant patcher for iBoot images.
///
@@ -76,11 +76,11 @@ public final class IBootJailbreakPatcher: IBootPatcher {
// i0 operands: [0]=reg (w0), [1]=bit (0), [2]=target address
guard
- let detail0 = i0.aarch64,
+ let detail0 = i0.detail,
detail0.operands.count >= 3,
- detail0.operands[0].type == AARCH64_OP_REG,
- detail0.operands[0].reg.rawValue == AARCH64_REG_W0.rawValue,
- detail0.operands[1].type == AARCH64_OP_IMM,
+ detail0.operands[0].type == .register,
+ detail0.operands[0].reg == .w(0),
+ detail0.operands[1].type == .immediate,
detail0.operands[1].imm == 0
else {
scan += 4
@@ -170,13 +170,13 @@ public final class IBootJailbreakPatcher: IBootPatcher {
guard
a.mnemonic == "adrp",
b.mnemonic == "add",
- let detA = a.aarch64,
- let detB = b.aarch64,
+ let detA = a.detail,
+ let detB = b.detail,
detA.operands.count >= 2,
detB.operands.count >= 3,
- detA.operands[0].reg.rawValue == detB.operands[1].reg.rawValue,
- detA.operands[1].type == AARCH64_OP_IMM,
- detB.operands[2].type == AARCH64_OP_IMM
+ detA.operands[0].reg == detB.operands[1].reg,
+ detA.operands[1].type == .immediate,
+ detB.operands[2].type == .immediate
else {
off += 4
continue
@@ -220,14 +220,14 @@ public final class IBootJailbreakPatcher: IBootPatcher {
guard
a.mnemonic == "adrp",
b.mnemonic == "add",
- let detA = a.aarch64,
- let detB = b.aarch64,
+ let detA = a.detail,
+ let detB = b.detail,
detA.operands.count >= 2,
detB.operands.count >= 3,
// Destination register of ADRP must match source register of ADD
- detA.operands[0].reg.rawValue == detB.operands[1].reg.rawValue,
- detA.operands[1].type == AARCH64_OP_IMM,
- detB.operands[2].type == AARCH64_OP_IMM
+ detA.operands[0].reg == detB.operands[1].reg,
+ detA.operands[1].type == .immediate,
+ detB.operands[2].type == .immediate
else {
off += 4
continue
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/IBootPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/IBootPatcher.swift
index 4d19ac7d..d0a6863f 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/IBootPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/IBoot/IBootPatcher.swift
@@ -10,11 +10,11 @@
//
// Each patch method is defined as an extension in its own file under IBoot/Patches/.
-import Capstone
import Foundation
+import VPhonePatchKit
/// Patcher for iBoot components (iBSS, iBEC, LLB).
-public class IBootPatcher: Patcher {
+public class IBootPatcher: BufferedPatcher {
// MARK: - Types
public enum Mode: String, Sendable {
@@ -37,6 +37,9 @@ public class IBootPatcher: Patcher {
public let component: String
public let verbose: Bool
+ /// Which patches the resolved preset turned on. Unrestricted by default.
+ public var gate: VPhonePatchGate = .unrestricted
+
/// Extra boot-args token(s) inserted before the trailing `%s` in the
/// patched boot-args (ibec/llb). Used to add `if_attach_nx=0x3` on iOS 18
/// bases (disables the skywalk flowswitch netagents so Network.framework
@@ -105,6 +108,8 @@ public class IBootPatcher: Patcher {
/// Record a code patch (disassembles before/after for logging).
func emit(_ offset: Int, _ patchBytes: Data, id: String, description: String) {
+ guard gateAllows(id) else { return }
+
let originalBytes = buffer.readBytes(at: offset, count: patchBytes.count)
let beforeInsn = disasm.disassembleOne(in: buffer.original, at: offset)
@@ -131,6 +136,8 @@ public class IBootPatcher: Patcher {
/// Record a string/data patch (not disassemblable).
func emitString(_ offset: Int, _ data: Data, id: String, description: String) {
+ guard gateAllows(id) else { return }
+
let originalBytes = buffer.readBytes(at: offset, count: data.count)
let txt = String(data: data, encoding: .ascii) ?? data.hex
@@ -177,9 +184,9 @@ public class IBootPatcher: Patcher {
/// Yield chunks of disassembled instructions over the whole binary.
/// Mirrors Python `_chunked_disasm()` with CHUNK_SIZE=0x2000, OVERLAP=0x100.
- func chunkedDisasm() -> [[Instruction]] {
+ func chunkedDisasm() -> [[ARM64Instruction]] {
let size = buffer.original.count
- var results: [[Instruction]] = []
+ var results: [[ARM64Instruction]] = []
var off = 0
while off < size {
let end = min(off + IBootPatcher.chunkSize, size)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/APFS/KernelPatchApfsGraft.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/APFS/KernelPatchApfsGraft.swift
index f0c4dfb6..e83126bc 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/APFS/KernelPatchApfsGraft.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/APFS/KernelPatchApfsGraft.swift
@@ -6,6 +6,7 @@
// Historical note: derived from the legacy Python firmware patcher during the Swift migration.
import Foundation
+import VPhonePatchKit
extension KernelPatcher {
// MARK: - Patch 12: _apfs_graft
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/APFS/KernelPatchApfsMount.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/APFS/KernelPatchApfsMount.swift
index 6070bc4f..e1a75109 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/APFS/KernelPatchApfsMount.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/APFS/KernelPatchApfsMount.swift
@@ -3,8 +3,8 @@
// Historical note: derived from the legacy Python firmware patcher during the Swift migration.
// scripts/patchers/kernel_patch_apfs_graft.py (patch_handle_fsioc_graft)
-import Capstone
import Foundation
+import VPhonePatchKit
extension KernelPatcher {
// MARK: - Private Helpers
@@ -89,7 +89,7 @@ extension KernelPatcher {
while scan + 4 <= scanEnd {
guard let insn = disasm.disassembleOne(in: buffer.data, at: scan),
insn.mnemonic == "cmp",
- let detail = insn.aarch64,
+ let detail = insn.detail,
detail.operands.count >= 2
else {
scan += 4; continue
@@ -97,11 +97,11 @@ extension KernelPatcher {
let ops = detail.operands
// Both operands must be registers.
- guard ops[0].type == AARCH64_OP_REG, ops[1].type == AARCH64_OP_REG else {
+ guard ops[0].type == .register, ops[1].type == .register else {
scan += 4; continue
}
// First operand must be x0 (return value from BL current_thread).
- guard ops[0].reg == AARCH64_REG_X0 else {
+ guard ops[0].reg == .x(0) else {
scan += 4; continue
}
// Skip CMP x0, x0 (already patched or trivially true).
@@ -174,10 +174,10 @@ extension KernelPatcher {
guard nextOff + 4 <= buffer.count,
let nextInsn = disasm.disassembleOne(in: buffer.data, at: nextOff),
nextInsn.mnemonic == "tbnz",
- let detail = nextInsn.aarch64,
+ let detail = nextInsn.detail,
!detail.operands.isEmpty,
- detail.operands[0].type == AARCH64_OP_REG,
- detail.operands[0].reg == AARCH64_REG_W0
+ detail.operands[0].type == .register,
+ detail.operands[0].reg == .w(0)
else {
scan += 4; continue
}
@@ -314,21 +314,21 @@ extension KernelPatcher {
while scan + 4 <= funcEnd {
guard let insn = disasm.disassembleOne(in: buffer.data, at: scan),
insn.mnemonic == "cbz" || insn.mnemonic == "cbnz",
- let detail = insn.aarch64,
+ let detail = insn.detail,
detail.operands.count >= 2
else {
scan += 4; continue
}
let ops = detail.operands
- guard ops[0].type == AARCH64_OP_REG,
- ops[1].type == AARCH64_OP_IMM
+ guard ops[0].type == .register,
+ ops[1].type == .immediate
else {
scan += 4; continue
}
let reg = ops[0].reg
- guard reg == AARCH64_REG_X0 || reg == AARCH64_REG_W0 else {
+ guard reg == .x(0) || reg == .w(0) else {
scan += 4; continue
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/APFS/KernelPatchApfsSeal.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/APFS/KernelPatchApfsSeal.swift
index aac65fc9..c884e3ae 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/APFS/KernelPatchApfsSeal.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/APFS/KernelPatchApfsSeal.swift
@@ -11,8 +11,8 @@
// branch whose target lands in [adrp_off - 0x40, bl_off + 4].
// 4. NOP that conditional branch.
-import Capstone
import Foundation
+import VPhonePatchKit
extension KernelPatcher {
@discardableResult
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/APFS/KernelPatchApfsSnapshot.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/APFS/KernelPatchApfsSnapshot.swift
index c34f4678..e1dee3f2 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/APFS/KernelPatchApfsSnapshot.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/APFS/KernelPatchApfsSnapshot.swift
@@ -10,8 +10,8 @@
// tbz/tbnz <reg>, #5, <target> instruction.
// 3. NOP it.
-import Capstone
import Foundation
+import VPhonePatchKit
extension KernelPatcher {
@discardableResult
@@ -47,10 +47,10 @@ extension KernelPatcher {
// Check: tbz/tbnz <reg>, #5, <target>
// Operands: [0] = register, [1] = bit number (IMM), [2] = branch target (IMM)
guard
- let detail = insn.aarch64,
+ let detail = insn.detail,
detail.operands.count >= 2,
- detail.operands[0].type == AARCH64_OP_REG,
- detail.operands[1].type == AARCH64_OP_IMM,
+ detail.operands[0].type == .register,
+ detail.operands[1].type == .immediate,
detail.operands[1].imm == 5
else {
scan += 4
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchDebugger.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchDebugger.swift
index 5ba40a7c..993dacee 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchDebugger.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchDebugger.swift
@@ -6,6 +6,7 @@
// Historical note: derived from the legacy Python firmware patcher during the Swift migration.
import Foundation
+import VPhonePatchKit
extension KernelPatcher {
/// Patches 6-7: stub _PE_i_can_has_debugger with mov x0,#1; ret.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchDyldPolicy.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchDyldPolicy.swift
index 40724555..1c080634 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchDyldPolicy.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchDyldPolicy.swift
@@ -8,6 +8,7 @@
// Historical note: derived from the legacy Python firmware patcher during the Swift migration.
import Foundation
+import VPhonePatchKit
extension KernelPatcher {
/// Patches 10–11: Replace two BL calls in _check_dyld_policy_internal with mov w0,#1.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchExcGuard.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchExcGuard.swift
index c5e03f96..51e4f5eb 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchExcGuard.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchExcGuard.swift
@@ -21,8 +21,8 @@
// 4. → in that target, find BL to thread_guard_violation()
// 5. → patch thread_guard_violation prologue to RET
-import Capstone
import Foundation
+import VPhonePatchKit
extension KernelPatcher {
/// Disable Mach port guard violation enforcement (EXC_GUARD).
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchLaunchConstraints.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchLaunchConstraints.swift
index b0c4164f..b119d6d3 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchLaunchConstraints.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchLaunchConstraints.swift
@@ -16,6 +16,7 @@
// Historical note: derived from the legacy Python firmware patcher during the Swift migration.
import Foundation
+import VPhonePatchKit
extension KernelPatcher {
// MARK: - Patches 4–5: _proc_check_launch_constraints
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchPostValidation.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchPostValidation.swift
index 6e445a61..4d8bae80 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchPostValidation.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchPostValidation.swift
@@ -11,8 +11,8 @@
// BL targets in code range → callee with `cmp w0,#imm ; b.ne` preceded by BL →
// replace CMP with `cmp w0,w0`.
-import Capstone
import Foundation
+import VPhonePatchKit
extension KernelPatcher {
// MARK: - Patch 8: NOP TBNZ after TXM CodeSignature error log
@@ -123,11 +123,11 @@ extension KernelPatcher {
let i0 = insns[0], i1 = insns[1]
guard i0.mnemonic == "cmp", i1.mnemonic == "b.ne" else { continue }
- guard let detail0 = i0.aarch64, detail0.operands.count >= 2 else { continue }
+ guard let detail0 = i0.detail, detail0.operands.count >= 2 else { continue }
let op0 = detail0.operands[0]
let op1 = detail0.operands[1]
- guard op0.type == AARCH64_OP_REG, op0.reg == AARCH64_REG_W0 else { continue }
- guard op1.type == AARCH64_OP_IMM else { continue }
+ guard op0.type == .register, op0.reg == .w(0) else { continue }
+ guard op1.type == .immediate else { continue }
// Must be preceded by a BL within 2 instructions (4 or 8 bytes back).
var hasBlBefore = false
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchSandbox.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchSandbox.swift
index 23e80606..7334e0ae 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchSandbox.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchSandbox.swift
@@ -21,6 +21,7 @@
// vnode_check_rename → index 120
import Foundation
+import VPhonePatchKit
extension KernelPatcher {
// MARK: - Public Entry Point
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Startup/KernelPatchBsdInit.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Startup/KernelPatchBsdInit.swift
index b726d26e..77ba88bc 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Startup/KernelPatchBsdInit.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Startup/KernelPatchBsdInit.swift
@@ -7,8 +7,8 @@
// recover bsd_init → locate rootvp panic block → find the unique in-function BL
// → cbnz w0/x0 panic → bl imageboot_needed site → patch the branch gate only.
-import Capstone
import Foundation
+import VPhonePatchKit
// MARK: - Conditional branch mnemonics (ARM64)
@@ -139,7 +139,7 @@ extension KernelPatcher {
///
/// Capstone renders the target as a hex literal (e.g., `#0x1abc`).
/// We parse the last whitespace-separated token and strip the leading `#`.
- private func decodeBranchTargetFromInsn(_ insn: Instruction) -> Int? {
+ private func decodeBranchTargetFromInsn(_ insn: ARM64Instruction) -> Int? {
// operandString examples:
// "w0, #0xf7798c" (cbz / cbnz)
// "#0xf7798c" (b.eq / b.ne / etc.)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/ExperimentalPatches/KernelExperimentalPatchHvVmmRename.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/ExperimentalPatches/KernelExperimentalPatchHvVmmRename.swift
index 3ce05dd3..1892be47 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/ExperimentalPatches/KernelExperimentalPatchHvVmmRename.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/ExperimentalPatches/KernelExperimentalPatchHvVmmRename.swift
@@ -75,6 +75,7 @@
// is already 'X' the patcher skips that occurrence.
import Foundation
+import VPhonePatchKit
extension KernelExperimentalPatcher {
/// Apply Part A (OID rename) + Part B (kernel-internal caller
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchAmfiExecve.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchAmfiExecve.swift
index 3362c7e2..75f4e536 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchAmfiExecve.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchAmfiExecve.swift
@@ -12,6 +12,7 @@
// from patchAmfiExecveKillPath() in the orchestrator.
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
// MARK: - AMFI execve kill-path bypass (disabled)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchAmfiTrustcache.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchAmfiTrustcache.swift
index 816331c7..3e536882 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchAmfiTrustcache.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchAmfiTrustcache.swift
@@ -16,6 +16,7 @@
// the always-allow stub: mov x0,#1 / cbz x2,+8 / str x0,[x2] / ret.
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
/// AMFI trustcache gate bypass: rewrite AMFIIsCDHashInTrustCache to always return 1.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchCredLabel.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchCredLabel.swift
index 9fae7dd7..fffcb838 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchCredLabel.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchCredLabel.swift
@@ -15,6 +15,7 @@
// RELAX_SETMASK = 0x0000000C (CS_GET_TASK_ALLOW | CS_INSTALLER)
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
// MARK: - Constants
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchHookCredLabel.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchHookCredLabel.swift
index 4505c481..c7f2ef86 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchHookCredLabel.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchHookCredLabel.swift
@@ -14,8 +14,8 @@
// The ops[18] entry is an auth-rebase chained pointer. We re-encode it
// preserving PAC metadata but changing the target to our cave address.
-import Capstone
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
// MARK: - Constants
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchLoadDylinker.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchLoadDylinker.swift
index fcb44ad9..a1d2a829 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchLoadDylinker.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchLoadDylinker.swift
@@ -7,6 +7,7 @@
// Patch: replace BL with unconditional B to <allow>, skipping the policy check.
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
/// Bypass the load_dylinker policy gate in the dyld path.
@@ -67,7 +68,7 @@ extension KernelJailbreakPatcher {
guard let i1 = insns1.first, i1.mnemonic == "cbz" else { continue }
guard i1.operandString.hasPrefix("w0, ") else { continue }
- guard let detail1 = i1.aarch64, detail1.operands.count >= 2 else { continue }
+ guard let detail1 = i1.detail, detail1.operands.count >= 2 else { continue }
let allowTarget = Int(detail1.operands.last!.imm)
// Selector: deny path sets w0 = 2 immediately after CBZ.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchPostValidation.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchPostValidation.swift
index b69a8882..81a8f7f5 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchPostValidation.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/CodeSigning/KernelJailbreakPatchPostValidation.swift
@@ -6,8 +6,8 @@
// BL targets in AMFI text → callee with `cmp w0,#imm ; b.ne` preceded by a BL.
// Patch: replace `cmp w0,#imm` with `cmp w0,w0` so the compare always sets Z=1.
-import Capstone
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
/// Patch: rewrite the SHA256-only reject compare in AMFI's post-validation path.
@@ -58,19 +58,19 @@ extension KernelJailbreakPatcher {
// Must be: cmp w0, #imm followed by b.ne
guard i0.mnemonic == "cmp", i1.mnemonic == "b.ne" else { continue }
- guard let detail0 = i0.aarch64, detail0.operands.count >= 2 else { continue }
+ guard let detail0 = i0.detail, detail0.operands.count >= 2 else { continue }
let op0 = detail0.operands[0]
let op1 = detail0.operands[1]
- guard op0.type == AARCH64_OP_REG, op0.reg == AARCH64_REG_W0 else { continue }
+ guard op0.type == .register, op0.reg == .w(0) else { continue }
- let isImmediate = op1.type == AARCH64_OP_IMM
+ let isImmediate = op1.type == .immediate
// `cmp w0, w0` in this slot is this patch's own result. The
// base layer's postValidation patch reveals the same site
// the same way — same string anchor, same `cmp w0,#imm ;
// b.ne` shape, a narrower BL window — and rewrites it
// before this runs, so the immediate is already gone by
// then and searching only for one finds nothing at all.
- let isAlreadyPatched = op1.type == AARCH64_OP_REG && op1.reg == AARCH64_REG_W0
+ let isAlreadyPatched = op1.type == .register && op1.reg == .w(0)
guard isImmediate || isAlreadyPatched else { continue }
// Must be preceded by a BL within 3 instructions.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Drivers/KernelJailbreakPatchIomfbSwap.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Drivers/KernelJailbreakPatchIomfbSwap.swift
index c74f77b7..cf6ba7d4 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Drivers/KernelJailbreakPatchIomfbSwap.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Drivers/KernelJailbreakPatchIomfbSwap.swift
@@ -27,6 +27,7 @@
// handler reads (26.5=0x588, 27=0x6e0 both do).
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
private static let swapEndExpectedSize: UInt32 = 0x588 // 26.4 kernel's native SwapEnd struct size
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Drivers/KernelJailbreakPatchNvram.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Drivers/KernelJailbreakPatchNvram.swift
index decfacea..2d4ca43a 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Drivers/KernelJailbreakPatchNvram.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Drivers/KernelJailbreakPatchNvram.swift
@@ -3,6 +3,7 @@
// Historical note: derived from the legacy Python firmware patcher during the Swift migration.
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
/// NOP the verifyPermission gate in the `krn.` key-prefix path.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Frida/KernelJailbreakPatchThreadSetState.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Frida/KernelJailbreakPatchThreadSetState.swift
index 6e690dd3..77daa56a 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Frida/KernelJailbreakPatchThreadSetState.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Frida/KernelJailbreakPatchThreadSetState.swift
@@ -1,12 +1,15 @@
-// KernelJailbreakPatchThreadSetState.swift — optional Frida Stalker support (--frida).
+// KernelJailbreakPatchThreadSetState.swift — optional Frida Stalker support.
+//
+// Declared as `kernelcache_frida.thread_set_state_entitlement_flag`, off in
+// `standard`.
//
// Frida follows an existing thread via thread_set_state_from_user, whose flags
// carry TSSF_CHECK_ENTITLEMENT and trip GUARD_TYPE_MACH_PORT. Clear that bit in the
// user setters (`mov w6,#0x201` → `mov w6,#0x1`) rather than the check itself.
// Reveal + validation: Research/KernelJailbreakPatches/patch_thread_set_state.md.
-import Capstone
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
private static let tssEntitlement = "com.apple.private.thread-set-state"
@@ -63,8 +66,8 @@ extension KernelJailbreakPatcher {
let bytes = ARM64Encoder.encodeMovzW(rd: rd, imm16: Self.tssFlagsCleared),
let check = disasm.disassembleOne(bytes, at: UInt64(setterOff)),
check.mnemonic == "mov" || check.mnemonic == "movz",
- let ops = check.aarch64?.operands, ops.count == 2,
- ops[1].type == AARCH64_OP_IMM, ops[1].imm == Int64(Self.tssFlagsCleared)
+ let ops = check.detail?.operands, ops.count == 2,
+ ops[1].type == .immediate, ops[1].imm == Int64(Self.tssFlagsCleared)
else {
log(" [-] failed to assemble/verify cleared flags at 0x\(String(format: "%X", setterOff))")
return false
@@ -83,9 +86,9 @@ extension KernelJailbreakPatcher {
// MARK: - Helpers
/// Direct B/BL target (disassembly runs in file-offset space).
- private func branchTargetFileOffset(_ insn: Instruction) -> Int? {
- guard let ops = insn.aarch64?.operands, ops.count == 1,
- ops[0].type == AARCH64_OP_IMM
+ private func branchTargetFileOffset(_ insn: ARM64Instruction) -> Int? {
+ guard let ops = insn.detail?.operands, ops.count == 1,
+ ops[0].type == .immediate
else { return nil }
return Int(ops[0].imm)
}
@@ -99,8 +102,8 @@ extension KernelJailbreakPatcher {
defer { off -= 4; steps += 1 }
guard let insn = disasAt(off) else { continue }
guard insn.mnemonic == "mov" || insn.mnemonic == "movz" else { continue }
- guard let ops = insn.aarch64?.operands, ops.count == 2,
- ops[0].type == AARCH64_OP_REG, ops[1].type == AARCH64_OP_IMM,
+ guard let ops = insn.detail?.operands, ops.count == 2,
+ ops[0].type == .register, ops[1].type == .immediate,
disasm.firstRegisterName(insn) == "w6"
else { continue }
return ops[1].imm == Self.tssFlagsFromUser ? off : nil
@@ -108,7 +111,7 @@ extension KernelJailbreakPatcher {
return nil
}
- private func wRegisterNumber(_ insn: Instruction) -> UInt32? {
+ private func wRegisterNumber(_ insn: ARM64Instruction) -> UInt32? {
guard let name = disasm.firstRegisterName(insn), name.hasPrefix("w"),
let value = UInt32(name.dropFirst()), value < 32
else { return nil }
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Frida/KernelJailbreakPatchVmMapDelete.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Frida/KernelJailbreakPatchVmMapDelete.swift
index d983ad3e..6f0728f7 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Frida/KernelJailbreakPatchVmMapDelete.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Frida/KernelJailbreakPatchVmMapDelete.swift
@@ -1,4 +1,6 @@
-// KernelJailbreakPatchVmMapDelete.swift — optional Frida Stalker support (--frida).
+// KernelJailbreakPatchVmMapDelete.swift — optional Frida Stalker support.
+//
+// Declared as `kernelcache_frida.vm_map_delete_immutable_code`, off in `standard`.
//
// Frida's write-then-flip leaves a permanent CSM mapping at current RW / max RWX;
// vm_map_delete's immutable-code exception tests current-protection EXECUTE, which
@@ -6,8 +8,8 @@
// test from current-X (packed [entry,#0x38] bit 9) to max-X (bit 13).
// Reveal + validation: Research/KernelJailbreakPatches/patch_vm_map_delete_immutable_code.md.
-import Capstone
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
private struct VmMapDeleteGate {
@@ -51,9 +53,9 @@ extension KernelJailbreakPatcher {
),
let decoded = disasm.disassembleOne(bytes, at: UInt64(gate.offset)),
decoded.mnemonic == (gate.nonzero ? "tbnz" : "tbz"),
- let ops = decoded.aarch64?.operands, ops.count == 3,
- ops[1].type == AARCH64_OP_IMM, ops[1].imm == 13,
- ops[2].type == AARCH64_OP_IMM, Int(ops[2].imm) == gate.target
+ let ops = decoded.detail?.operands, ops.count == 3,
+ ops[1].type == .immediate, ops[1].imm == 13,
+ ops[2].type == .immediate, Int(ops[2].imm) == gate.target
else {
log(" [-] failed to assemble/verify max-X gate at 0x\(String(format: "%X", gate.offset))")
return false
@@ -67,7 +69,7 @@ extension KernelJailbreakPatcher {
bytes,
patchID: "kernelcache_frida.vm_map_delete_immutable_code",
virtualAddress: fileOffsetToVA(gate.offset),
- description: "\(gate.nonzero ? "tbnz" : "tbz") entry max_protection.X [vm_map_delete immutable-code \(gate.shape), --frida]",
+ description: "\(gate.nonzero ? "tbnz" : "tbz") entry max_protection.X [vm_map_delete immutable-code \(gate.shape), frida]",
)
}
return true
@@ -156,7 +158,7 @@ extension KernelJailbreakPatcher {
// MARK: - Instruction helpers
/// The instruction's first operand as a W register number, if it is one.
- private func destRegister(_ insn: Instruction) -> UInt32? {
+ private func destRegister(_ insn: ARM64Instruction) -> UInt32? {
guard let name = disasm.firstRegisterName(insn), name.hasPrefix("w"),
let value = UInt32(name.dropFirst()), value < 32
else { return nil }
@@ -165,29 +167,29 @@ extension KernelJailbreakPatcher {
/// A `tbz`/`tbnz wReg,#bit,target` matching the given mnemonic, register, and
/// bit; returns the branch target file offset.
- private func bitBranch(_ insn: Instruction, mnemonic: String, register: UInt32, bit: Int64) -> Int? {
+ private func bitBranch(_ insn: ARM64Instruction, mnemonic: String, register: UInt32, bit: Int64) -> Int? {
guard insn.mnemonic == mnemonic,
- let ops = insn.aarch64?.operands, ops.count == 3,
- ops[0].type == AARCH64_OP_REG, destRegister(insn) == register,
- ops[1].type == AARCH64_OP_IMM, ops[1].imm == bit,
- ops[2].type == AARCH64_OP_IMM
+ let ops = insn.detail?.operands, ops.count == 3,
+ ops[0].type == .register, destRegister(insn) == register,
+ ops[1].type == .immediate, ops[1].imm == bit,
+ ops[2].type == .immediate
else { return nil }
return Int(ops[2].imm)
}
/// Any `tbz`/`tbnz wReg,#bit,target` of the given mnemonic; returns bit + target.
- private func bitBranchAnyBit(_ insn: Instruction, mnemonic: String) -> (bit: Int64, target: Int)? {
+ private func bitBranchAnyBit(_ insn: ARM64Instruction, mnemonic: String) -> (bit: Int64, target: Int)? {
guard insn.mnemonic == mnemonic,
- let ops = insn.aarch64?.operands, ops.count == 3,
- ops[0].type == AARCH64_OP_REG,
- ops[1].type == AARCH64_OP_IMM, ops[2].type == AARCH64_OP_IMM
+ let ops = insn.detail?.operands, ops.count == 3,
+ ops[0].type == .register,
+ ops[1].type == .immediate, ops[2].type == .immediate
else { return nil }
return (ops[1].imm, Int(ops[2].imm))
}
/// The inlined `developer_mode_state()`: a byte load whose bit 0 is then tested
/// (`ldrb wD,[...] ; … ; tbz/tbnz wD,#0`).
- private func developerModeGatePresent(_ insns: [Instruction]) -> Bool {
+ private func developerModeGatePresent(_ insns: [ARM64Instruction]) -> Bool {
for i in 0 ..< insns.count {
guard insns[i].mnemonic == "ldrb", let devReg = destRegister(insns[i]) else { continue }
for j in (i + 1) ..< min(insns.count, i + 4) {
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Memory/KernelJailbreakPatchPortToMap.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Memory/KernelJailbreakPatchPortToMap.swift
index 24ea93ba..706607bd 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Memory/KernelJailbreakPatchPortToMap.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Memory/KernelJailbreakPatchPortToMap.swift
@@ -7,6 +7,7 @@
// replace B.cond with unconditional B to same target.
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
/// Skip kernel-map panic in _convert_port_to_map_with_flavor.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Memory/KernelJailbreakPatchSharedRegion.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Memory/KernelJailbreakPatchSharedRegion.swift
index b8a66a21..b5877441 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Memory/KernelJailbreakPatchSharedRegion.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Memory/KernelJailbreakPatchSharedRegion.swift
@@ -2,8 +2,8 @@
//
// Historical note: derived from the legacy Python firmware patcher during the Swift migration.
-import Capstone
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
/// Force `cmp x0, x0` in the root-vs-preboot gate of
@@ -80,12 +80,12 @@ extension KernelJailbreakPatcher {
guard cmpInsn.mnemonic == "cmp", beqInsn.mnemonic == "b.eq" else { off += 4; continue }
- guard let cmpOps = cmpInsn.aarch64?.operands, cmpOps.count == 2,
- cmpOps[0].type == AARCH64_OP_REG, cmpOps[1].type == AARCH64_OP_REG
+ guard let cmpOps = cmpInsn.detail?.operands, cmpOps.count == 2,
+ cmpOps[0].type == .register, cmpOps[1].type == .register
else { off += 4; continue }
- guard let beqOps = beqInsn.aarch64?.operands, beqOps.count == 1,
- beqOps[0].type == AARCH64_OP_IMM,
+ guard let beqOps = beqInsn.detail?.operands, beqOps.count == 1,
+ beqOps[0].type == .immediate,
Int(beqOps[0].imm) > Int(beqInsn.address)
else { off += 4; continue }
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Memory/KernelJailbreakPatchVmFault.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Memory/KernelJailbreakPatchVmFault.swift
index 7d6aed3d..7b3a8921 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Memory/KernelJailbreakPatchVmFault.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Memory/KernelJailbreakPatchVmFault.swift
@@ -2,8 +2,8 @@
//
// Historical note: derived from the legacy Python firmware patcher during the Swift migration.
-import Capstone
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
/// Force the upstream cs_bypass fast-path in `_vm_fault_enter_prepare`.
@@ -79,10 +79,10 @@ extension KernelJailbreakPatcher {
let insns = disasm.disassemble(in: buffer.data, at: off, count: 1)
guard let insn = insns.first else { off += 4; continue }
if insn.mnemonic == "ldr",
- let ops = insn.aarch64?.operands, ops.count >= 2,
- ops[0].type == AARCH64_OP_REG,
- ops[1].type == AARCH64_OP_MEM,
- ops[1].mem.base != AARCH64_REG_INVALID,
+ let ops = insn.detail?.operands, ops.count >= 2,
+ ops[0].type == .register,
+ ops[1].type == .memory,
+ ops[1].mem.base != .invalid,
ops[1].mem.disp == 0x28
{
if disasm.firstRegisterName(insn)?.hasPrefix("w") ?? false {
@@ -102,20 +102,20 @@ extension KernelJailbreakPatcher {
let insns = disasm.disassemble(in: buffer.data, at: off, count: 1)
guard let gate = insns.first else { off += 4; continue }
guard gate.mnemonic == "tbz",
- let gateOps = gate.aarch64?.operands, gateOps.count == 3,
- gateOps[0].type == AARCH64_OP_REG,
+ let gateOps = gate.detail?.operands, gateOps.count == 3,
+ gateOps[0].type == .register,
flagRegs.contains(gateOps[0].reg.rawValue),
- gateOps[1].type == AARCH64_OP_IMM, gateOps[1].imm == 3,
- gateOps[2].type == AARCH64_OP_IMM
+ gateOps[1].type == .immediate, gateOps[1].imm == 3,
+ gateOps[2].type == .immediate
else { off += 4; continue }
// Check mov Wt, #0
let movInsns = disasm.disassemble(in: buffer.data, at: off + 4, count: 1)
guard let movInsn = movInsns.first,
movInsn.mnemonic == "mov",
- let movOps = movInsn.aarch64?.operands, movOps.count == 2,
- movOps[0].type == AARCH64_OP_REG,
- movOps[1].type == AARCH64_OP_IMM, movOps[1].imm == 0
+ let movOps = movInsn.detail?.operands, movOps.count == 2,
+ movOps[0].type == .register,
+ movOps[1].type == .immediate, movOps[1].imm == 0
else { off += 4; continue }
guard disasm.firstRegisterName(movInsn)?.hasPrefix("w") ?? false else { off += 4; continue }
@@ -123,8 +123,8 @@ extension KernelJailbreakPatcher {
let bInsns = disasm.disassemble(in: buffer.data, at: off + 8, count: 1)
guard let bInsn = bInsns.first,
bInsn.mnemonic == "b",
- let bOps = bInsn.aarch64?.operands, bOps.count == 1,
- bOps[0].type == AARCH64_OP_IMM
+ let bOps = bInsn.detail?.operands, bOps.count == 1,
+ bOps[0].type == .immediate
else { off += 4; continue }
hits.append(off)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Memory/KernelJailbreakPatchVmProtect.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Memory/KernelJailbreakPatchVmProtect.swift
index 37c2535f..91417bf9 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Memory/KernelJailbreakPatchVmProtect.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Memory/KernelJailbreakPatchVmProtect.swift
@@ -36,8 +36,8 @@
// Widening the mask keeps ALL requested permission bits; it is strictly more
// permissive (`prot & 7` ⊇ `prot & 5`), so no working mapping regresses.
-import Capstone
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
/// Bypass the vm_map_protect W^X downgrade so write+execute protections are honored.
@@ -136,44 +136,44 @@ extension KernelJailbreakPatcher {
// mov wMask, #6
guard movMask.mnemonic == "mov",
- let movOps = movMask.aarch64?.operands, movOps.count == 2,
- movOps[0].type == AARCH64_OP_REG,
- movOps[1].type == AARCH64_OP_IMM, movOps[1].imm == 6
+ let movOps = movMask.detail?.operands, movOps.count == 2,
+ movOps[0].type == .register,
+ movOps[1].type == .immediate, movOps[1].imm == 6
else { continue }
let maskReg = movOps[0].reg
// bic wMask, wMask, wProt — the non-flag-setting form.
guard bicInsn.mnemonic == "bic",
- let bicOps = bicInsn.aarch64?.operands, bicOps.count == 3,
- bicOps[0].type == AARCH64_OP_REG, bicOps[0].reg == maskReg,
- bicOps[1].type == AARCH64_OP_REG, bicOps[1].reg == maskReg,
- bicOps[2].type == AARCH64_OP_REG
+ let bicOps = bicInsn.detail?.operands, bicOps.count == 3,
+ bicOps[0].type == .register, bicOps[0].reg == maskReg,
+ bicOps[1].type == .register, bicOps[1].reg == maskReg,
+ bicOps[2].type == .register
else { continue }
let protReg = bicOps[2].reg
// cmp wMask, #0
guard cmpInsn.mnemonic == "cmp",
- let cmpOps = cmpInsn.aarch64?.operands, cmpOps.count == 2,
- cmpOps[0].type == AARCH64_OP_REG, cmpOps[0].reg == maskReg,
- cmpOps[1].type == AARCH64_OP_IMM, cmpOps[1].imm == 0
+ let cmpOps = cmpInsn.detail?.operands, cmpOps.count == 2,
+ cmpOps[0].type == .register, cmpOps[0].reg == maskReg,
+ cmpOps[1].type == .immediate, cmpOps[1].imm == 0
else { continue }
// ccmp wFlags, #0, #nzcv, eq — the `eq` is what makes this the second
// half of the same decision rather than an unrelated fused compare.
guard ccmpInsn.mnemonic == "ccmp",
- let ccmpDetail = ccmpInsn.aarch64,
- ccmpDetail.conditionCode == AArch64CC_EQ,
+ let ccmpDetail = ccmpInsn.detail,
+ ccmpDetail.conditionCode == .eq,
ccmpDetail.operands.count >= 2,
- ccmpDetail.operands[0].type == AARCH64_OP_REG,
- ccmpDetail.operands[1].type == AARCH64_OP_IMM,
+ ccmpDetail.operands[0].type == .register,
+ ccmpDetail.operands[1].type == .immediate,
ccmpDetail.operands[1].imm == 0
else { continue }
let flagsReg = ccmpDetail.operands[0].reg
// b.ne <skip>, forward.
guard bneInsn.mnemonic == "b.ne",
- let bneOps = bneInsn.aarch64?.operands, bneOps.count == 1,
- bneOps[0].type == AARCH64_OP_IMM
+ let bneOps = bneInsn.detail?.operands, bneOps.count == 1,
+ bneOps[0].type == .immediate
else { continue }
let skipTarget = Int(bneOps[0].imm)
guard skipTarget > Int(bneInsn.address) else { continue }
@@ -199,16 +199,16 @@ extension KernelJailbreakPatcher {
}
/// Scan backwards for `and wFlags, wFlags, #bit` that isolates the entry flag.
- private func findEntryFlagMask(before: Int, limit: Int, reg: aarch64_reg, bit: Int64) -> Int? {
+ private func findEntryFlagMask(before: Int, limit: Int, reg: ARM64Register, bit: Int64) -> Int? {
var off = before - 4
let floor = max(limit, before - 0x20)
while off >= floor {
let insns = disasm.disassemble(in: buffer.data, at: off, count: 1)
if let insn = insns.first, insn.mnemonic == "and",
- let ops = insn.aarch64?.operands, ops.count == 3,
- ops[0].type == AARCH64_OP_REG, ops[0].reg == reg,
- ops[1].type == AARCH64_OP_REG, ops[1].reg == reg,
- ops[2].type == AARCH64_OP_IMM, ops[2].imm == bit
+ let ops = insn.detail?.operands, ops.count == 3,
+ ops[0].type == .register, ops[0].reg == reg,
+ ops[1].type == .register, ops[1].reg == reg,
+ ops[2].type == .immediate, ops[2].imm == bit
{
return off
}
@@ -221,7 +221,7 @@ extension KernelJailbreakPatcher {
/// Find the `b.ne` that skips the write-downgrade block, and its target.
private func findWriteDowngradeGate(start: Int, end: Int) -> (brOff: Int, target: Int)? {
- let wZrReg: aarch64_reg = AARCH64_REG_WZR
+ let wZrReg: ARM64Register = .wzr
var hits: [(Int, Int)] = []
var off = start
@@ -232,35 +232,35 @@ extension KernelJailbreakPatcher {
// mov wMask, #6
guard movMask.mnemonic == "mov",
- let movOps = movMask.aarch64?.operands, movOps.count == 2,
- movOps[0].type == AARCH64_OP_REG,
- movOps[1].type == AARCH64_OP_IMM, movOps[1].imm == 6
+ let movOps = movMask.detail?.operands, movOps.count == 2,
+ movOps[0].type == .register,
+ movOps[1].type == .immediate, movOps[1].imm == 6
else { off += 4; continue }
let maskReg = movOps[0].reg
// bics wzr, wMask, wProt
guard bicsInsn.mnemonic == "bics",
- let bicsOps = bicsInsn.aarch64?.operands, bicsOps.count == 3,
- bicsOps[0].type == AARCH64_OP_REG, bicsOps[0].reg == wZrReg,
- bicsOps[1].type == AARCH64_OP_REG, bicsOps[1].reg == maskReg,
- bicsOps[2].type == AARCH64_OP_REG
+ let bicsOps = bicsInsn.detail?.operands, bicsOps.count == 3,
+ bicsOps[0].type == .register, bicsOps[0].reg == wZrReg,
+ bicsOps[1].type == .register, bicsOps[1].reg == maskReg,
+ bicsOps[2].type == .register
else { off += 4; continue }
let protReg = bicsOps[2].reg
// b.ne <skip>
guard bneInsn.mnemonic == "b.ne",
- let bneOps = bneInsn.aarch64?.operands, bneOps.count == 1,
- bneOps[0].type == AARCH64_OP_IMM
+ let bneOps = bneInsn.detail?.operands, bneOps.count == 1,
+ bneOps[0].type == .immediate
else { off += 4; continue }
let skipTarget = Int(bneOps[0].imm)
guard skipTarget > Int(bneInsn.address) else { off += 4; continue }
// tbnz wEntryFlags, #22, <skip>
guard tbnzInsn.mnemonic == "tbnz",
- let tbnzOps = tbnzInsn.aarch64?.operands, tbnzOps.count == 3,
- tbnzOps[0].type == AARCH64_OP_REG,
- tbnzOps[1].type == AARCH64_OP_IMM, tbnzOps[1].imm == 22,
- tbnzOps[2].type == AARCH64_OP_IMM, Int(tbnzOps[2].imm) == skipTarget
+ let tbnzOps = tbnzInsn.detail?.operands, tbnzOps.count == 3,
+ tbnzOps[0].type == .register,
+ tbnzOps[1].type == .immediate, tbnzOps[1].imm == 22,
+ tbnzOps[2].type == .immediate, Int(tbnzOps[2].imm) == skipTarget
else { off += 4; continue }
// Verify there's an `and wProt, wProt, #~bit` between tbnz+4 and target.
@@ -277,16 +277,16 @@ extension KernelJailbreakPatcher {
}
/// Scan [start, end) for `and wProt, wProt, #imm` that strips one of the low protection bits.
- private func findWriteClearBetween(start: Int, end: Int, protReg: aarch64_reg) -> Int? {
+ private func findWriteClearBetween(start: Int, end: Int, protReg: ARM64Register) -> Int? {
var off = start
while off < end {
let insns = disasm.disassemble(in: buffer.data, at: off, count: 1)
guard let insn = insns.first else { off += 4; continue }
if insn.mnemonic == "and",
- let ops = insn.aarch64?.operands, ops.count == 3,
- ops[0].type == AARCH64_OP_REG, ops[0].reg == protReg,
- ops[1].type == AARCH64_OP_REG, ops[1].reg == protReg,
- ops[2].type == AARCH64_OP_IMM
+ let ops = insn.detail?.operands, ops.count == 3,
+ ops[0].type == .register, ops[0].reg == protReg,
+ ops[1].type == .register, ops[1].reg == protReg,
+ ops[2].type == .immediate
{
let imm = UInt32(bitPattern: Int32(truncatingIfNeeded: ops[2].imm)) & 0xFFFF_FFFF
// Keeps two of the three low protection bits, clears the middle one.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchKcall10.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchKcall10.swift
index f84b60b6..6366be7a 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchKcall10.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchKcall10.swift
@@ -12,6 +12,7 @@
// The sysent entries use arm64e chained auth-rebase fixup pointers.
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
// MARK: - Constants
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchProcPidinfo.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchProcPidinfo.swift
index 84c867d6..b491d366 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchProcPidinfo.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchProcPidinfo.swift
@@ -18,6 +18,7 @@
// two guards lets kernel-task / restricted-pid flavors fall through to the switch.
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
/// Bypass the two early pid-0 guards in the inlined proc_pidinfo path.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchSpawnPersona.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchSpawnPersona.swift
index 319c2188..0cbb982b 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchSpawnPersona.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchSpawnPersona.swift
@@ -2,8 +2,8 @@
//
// Historical note: derived from the legacy Python firmware patcher during the Swift migration.
-import Capstone
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
/// NOP the upstream dual-CBZ bypass in the persona helper.
@@ -103,21 +103,21 @@ extension KernelJailbreakPatcher {
// ldr wA, [base, #8] ; cbz wA, deny
guard isLdrMem(i0, disp: 8) else { continue }
- guard let i0ops = i0.aarch64?.operands, i0ops.count >= 2 else { continue }
+ guard let i0ops = i0.detail?.operands, i0ops.count >= 2 else { continue }
let loadedReg0 = i0ops[0].reg
let baseReg = i0ops[1].mem.base
guard isCbzWSameReg(i1, reg: loadedReg0) else { continue }
// ldr wB, [base, #0xc] ; cbz wB, deny (same base)
guard isLdrMemSameBase(i2, base: baseReg, disp: 0xC) else { continue }
- guard let i2ops = i2.aarch64?.operands, i2ops.count >= 1 else { continue }
+ guard let i2ops = i2.detail?.operands, i2ops.count >= 1 else { continue }
let loadedReg2 = i2ops[0].reg
guard isCbzWSameReg(i3, reg: loadedReg2) else { continue }
// Both cbz must branch to the SAME deny target.
- guard let i1ops = i1.aarch64?.operands, i1ops.count == 2,
- let i3ops = i3.aarch64?.operands, i3ops.count == 2,
- i1ops[1].type == AARCH64_OP_IMM, i3ops[1].type == AARCH64_OP_IMM,
+ guard let i1ops = i1.detail?.operands, i1ops.count == 2,
+ let i3ops = i3.detail?.operands, i3ops.count == 2,
+ i1ops[1].type == .immediate, i3ops[1].type == .immediate,
i1ops[1].imm == i3ops[1].imm
else { continue }
let denyTarget = Int(i1ops[1].imm)
@@ -136,29 +136,29 @@ extension KernelJailbreakPatcher {
return hits.count == 1 ? hits[0] : nil
}
- private func isLdrMem(_ insn: Instruction, disp: Int32) -> Bool {
+ private func isLdrMem(_ insn: ARM64Instruction, disp: Int32) -> Bool {
guard insn.mnemonic == "ldr",
- let ops = insn.aarch64?.operands, ops.count >= 2,
- ops[0].type == AARCH64_OP_REG,
- ops[1].type == AARCH64_OP_MEM,
+ let ops = insn.detail?.operands, ops.count >= 2,
+ ops[0].type == .register,
+ ops[1].type == .memory,
ops[1].mem.disp == disp
else { return false }
return true
}
- private func isLdrMemSameBase(_ insn: Instruction, base: aarch64_reg, disp: Int32) -> Bool {
+ private func isLdrMemSameBase(_ insn: ARM64Instruction, base: ARM64Register, disp: Int32) -> Bool {
guard isLdrMem(insn, disp: disp),
- let ops = insn.aarch64?.operands, ops.count >= 2,
+ let ops = insn.detail?.operands, ops.count >= 2,
ops[1].mem.base == base
else { return false }
return true
}
- private func isCbzWSameReg(_ insn: Instruction, reg: aarch64_reg) -> Bool {
+ private func isCbzWSameReg(_ insn: ARM64Instruction, reg: ARM64Register) -> Bool {
guard insn.mnemonic == "cbz",
- let ops = insn.aarch64?.operands, ops.count == 2,
- ops[0].type == AARCH64_OP_REG, ops[0].reg == reg,
- ops[1].type == AARCH64_OP_IMM
+ let ops = insn.detail?.operands, ops.count == 2,
+ ops[0].type == .register, ops[0].reg == reg,
+ ops[1].type == .immediate
else { return false }
// Must be a w-register
return disasm.firstRegisterName(insn)?.hasPrefix("w") ?? false
@@ -171,11 +171,11 @@ extension KernelJailbreakPatcher {
return isMovWImmValue(insn, imm: value)
}
- private func isMovWImmValue(_ insn: Instruction, imm: Int64) -> Bool {
+ private func isMovWImmValue(_ insn: ARM64Instruction, imm: Int64) -> Bool {
guard insn.mnemonic == "mov",
- let ops = insn.aarch64?.operands, ops.count == 2,
- ops[0].type == AARCH64_OP_REG,
- ops[1].type == AARCH64_OP_IMM, ops[1].imm == imm
+ let ops = insn.detail?.operands, ops.count == 2,
+ ops[0].type == .register,
+ ops[1].type == .immediate, ops[1].imm == imm
else { return false }
return disasm.firstRegisterName(insn)?.hasPrefix("w") ?? false
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchSyscallmask.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchSyscallmask.swift
index 6d76229d..749bb37e 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchSyscallmask.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchSyscallmask.swift
@@ -16,6 +16,7 @@
// validation, but with an all-0xFF effective mask.
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
// MARK: - Constants
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchTaskConversion.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchTaskConversion.swift
index 901d050a..51eb6fee 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchTaskConversion.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchTaskConversion.swift
@@ -22,6 +22,7 @@
// pinned, never the operand position.
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
/// Task conversion eval bypass: patch the guard CMP to always be equal.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchTaskForPid.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchTaskForPid.swift
index a38e3953..7ddcbd15 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchTaskForPid.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchTaskForPid.swift
@@ -2,8 +2,8 @@
//
// Historical note: derived from the legacy Python firmware patcher during the Swift migration.
-import Capstone
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
/// NOP the upstream early `pid == 0` reject gate in `task_for_pid`.
@@ -73,9 +73,9 @@ extension KernelJailbreakPatcher {
// cbz wPid, fail
guard cbzPid.mnemonic == "cbz",
- let cbzPidOps = cbzPid.aarch64?.operands, cbzPidOps.count == 2,
- cbzPidOps[0].type == AARCH64_OP_REG,
- cbzPidOps[1].type == AARCH64_OP_IMM
+ let cbzPidOps = cbzPid.detail?.operands, cbzPidOps.count == 2,
+ cbzPidOps[0].type == .register,
+ cbzPidOps[1].type == .immediate
else { return nil }
let failTarget = cbzPidOps[1].imm
@@ -91,9 +91,9 @@ extension KernelJailbreakPatcher {
// cbz x0, fail (same target)
guard cbzRet.mnemonic == "cbz",
- let cbzRetOps = cbzRet.aarch64?.operands, cbzRetOps.count == 2,
- cbzRetOps[0].type == AARCH64_OP_REG,
- cbzRetOps[1].type == AARCH64_OP_IMM,
+ let cbzRetOps = cbzRet.detail?.operands, cbzRetOps.count == 2,
+ cbzRetOps[0].type == .register,
+ cbzRetOps[1].type == .immediate,
cbzRetOps[1].imm == failTarget
else { return nil }
// x0
@@ -101,8 +101,8 @@ extension KernelJailbreakPatcher {
// Look backward for ldr wPid, [x?, #8] and ldr xTaskPtr, [x?, #0x10]
let scanStart = max(funcStart, off - 0x18)
- var pidLoad: Instruction? = nil
- var taskptrLoad: Instruction? = nil
+ var pidLoad: ARM64Instruction? = nil
+ var taskptrLoad: ARM64Instruction? = nil
var prevOff = scanStart
while prevOff < off {
let prevInsns = disasm.disassemble(in: buffer.data, at: prevOff, count: 1)
@@ -117,37 +117,37 @@ extension KernelJailbreakPatcher {
}
guard let pid = pidLoad, taskptrLoad != nil else { return nil }
// pid register must match cbz operand
- guard let pidOps = pid.aarch64?.operands, !pidOps.isEmpty,
+ guard let pidOps = pid.detail?.operands, !pidOps.isEmpty,
pidOps[0].reg == cbzPidOps[0].reg
else { return nil }
return off
}
- private func isMovImmZero(_ insn: Instruction, dstName: String) -> Bool {
+ private func isMovImmZero(_ insn: ARM64Instruction, dstName: String) -> Bool {
guard insn.mnemonic == "mov",
- let ops = insn.aarch64?.operands, ops.count == 2,
- ops[0].type == AARCH64_OP_REG,
- ops[1].type == AARCH64_OP_IMM, ops[1].imm == 0
+ let ops = insn.detail?.operands, ops.count == 2,
+ ops[0].type == .register,
+ ops[1].type == .immediate, ops[1].imm == 0
else { return false }
return disasm.firstRegisterName(insn) == dstName
}
- private func isWLdrFromXImm(_ insn: Instruction, imm: Int32) -> Bool {
+ private func isWLdrFromXImm(_ insn: ARM64Instruction, imm: Int32) -> Bool {
guard insn.mnemonic == "ldr",
- let ops = insn.aarch64?.operands, ops.count >= 2,
- ops[0].type == AARCH64_OP_REG,
- ops[1].type == AARCH64_OP_MEM,
+ let ops = insn.detail?.operands, ops.count >= 2,
+ ops[0].type == .register,
+ ops[1].type == .memory,
ops[1].mem.disp == imm
else { return false }
return disasm.firstRegisterName(insn)?.hasPrefix("w") ?? false
}
- private func isXLdrFromXImm(_ insn: Instruction, imm: Int32) -> Bool {
+ private func isXLdrFromXImm(_ insn: ARM64Instruction, imm: Int32) -> Bool {
guard insn.mnemonic == "ldr",
- let ops = insn.aarch64?.operands, ops.count >= 2,
- ops[0].type == AARCH64_OP_REG,
- ops[1].type == AARCH64_OP_MEM,
+ let ops = insn.detail?.operands, ops.count >= 2,
+ ops[0].type == .register,
+ ops[1].type == .memory,
ops[1].mem.disp == imm
else { return false }
return disasm.firstRegisterName(insn)?.hasPrefix("x") ?? false
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchThidCrash.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchThidCrash.swift
index 57d61c7a..f36ba26a 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchThidCrash.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Process/KernelJailbreakPatchThidCrash.swift
@@ -3,6 +3,7 @@
// Historical note: derived from the legacy Python firmware patcher during the Swift migration.
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
/// Zero out `_thid_should_crash` via the nearby sysctl metadata.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchContainerUpcall.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchContainerUpcall.swift
index 3db782d6..6b78a420 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchContainerUpcall.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchContainerUpcall.swift
@@ -38,6 +38,7 @@
// the Keystone-backed ARM64Encoder.
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
@discardableResult
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchExecPolicyKill.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchExecPolicyKill.swift
index 055c5e9d..9052c137 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchExecPolicyKill.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchExecPolicyKill.swift
@@ -29,6 +29,7 @@
// an X register).
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
@discardableResult
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchFpfsScopedOpen.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchFpfsScopedOpen.swift
index 8d55aa78..3976a2b5 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchFpfsScopedOpen.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchFpfsScopedOpen.swift
@@ -8,6 +8,7 @@
// daemons (matched by p_comm) and returns allow for everyone else — preserving the bypass.
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
private static let vnodeCheckOpenIndex = 267
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchIoucMacf.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchIoucMacf.swift
index 93cb5409..c2a9b4eb 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchIoucMacf.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchIoucMacf.swift
@@ -16,6 +16,7 @@
// 5. Replace CBZ W0, <allow> with unconditional B <allow>.
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
/// IOUC MACF gate bypass: replace CBZ W0, <allow> with B <allow>.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchIoucSandbox.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchIoucSandbox.swift
index c6c1d631..0da978df 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchIoucSandbox.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchIoucSandbox.swift
@@ -32,6 +32,7 @@
// it → the immediately-preceding B.EQ allow target); no hardcoded offsets.
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
@discardableResult
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchMacMount.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchMacMount.swift
index 7a165c26..d91350f6 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchMacMount.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchMacMount.swift
@@ -2,8 +2,8 @@
//
// Historical note: derived from the legacy Python firmware patcher during the Swift migration.
-import Capstone
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
/// Apply the upstream twin bypasses in the mount-role wrapper.
@@ -107,10 +107,10 @@ extension KernelJailbreakPatcher {
let insns = disasm.disassemble(in: buffer.data, at: off, count: 1)
guard let insn = insns.first else { off += 4; continue }
guard insn.mnemonic == "tbnz",
- let ops = insn.aarch64?.operands, ops.count == 3,
- ops[0].type == AARCH64_OP_REG,
- ops[1].type == AARCH64_OP_IMM, ops[1].imm == 5,
- ops[2].type == AARCH64_OP_IMM
+ let ops = insn.detail?.operands, ops.count == 3,
+ ops[0].type == .register,
+ ops[1].type == .immediate, ops[1].imm == 5,
+ ops[2].type == .immediate
else { off += 4; continue }
// Check register is a w-register
@@ -123,9 +123,9 @@ extension KernelJailbreakPatcher {
let targetInsns = disasm.disassemble(in: buffer.data, at: target, count: 1)
guard let tInsn = targetInsns.first,
tInsn.mnemonic == "mov",
- let tOps = tInsn.aarch64?.operands, tOps.count == 2,
- tOps[0].type == AARCH64_OP_REG,
- tOps[1].type == AARCH64_OP_IMM, tOps[1].imm == 1
+ let tOps = tInsn.detail?.operands, tOps.count == 2,
+ tOps[0].type == .register,
+ tOps[1].type == .immediate, tOps[1].imm == 1
else { off += 4; continue }
guard let tRegName = disasm.firstRegisterName(tInsn), tRegName.hasPrefix("w") else { off += 4; continue }
@@ -153,9 +153,9 @@ extension KernelJailbreakPatcher {
// ldrb wN, [xBase, #imm]
guard ldrInsn.mnemonic == "ldrb",
- let ldrOps = ldrInsn.aarch64?.operands, ldrOps.count >= 2,
- ldrOps[0].type == AARCH64_OP_REG,
- ldrOps[1].type == AARCH64_OP_MEM
+ let ldrOps = ldrInsn.detail?.operands, ldrOps.count >= 2,
+ ldrOps[0].type == .register,
+ ldrOps[1].type == .memory
else { off += 4; continue }
let ldrDstReg = ldrOps[0].reg
guard let ldrDstName = disasm.firstRegisterName(ldrInsn),
@@ -163,9 +163,9 @@ extension KernelJailbreakPatcher {
// tbz/tbnz wN, #6, <target> (same register the byte was loaded into)
guard brInsn.mnemonic == "tbz" || brInsn.mnemonic == "tbnz",
- let brOps = brInsn.aarch64?.operands, brOps.count == 3,
- brOps[0].type == AARCH64_OP_REG, brOps[0].reg == ldrDstReg,
- brOps[1].type == AARCH64_OP_IMM, brOps[1].imm == 6
+ let brOps = brInsn.detail?.operands, brOps.count == 3,
+ brOps[0].type == .register, brOps[0].reg == ldrDstReg,
+ brOps[1].type == .immediate, brOps[1].imm == 6
else { off += 4; continue }
hits.append(Int(ldrInsn.address))
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchProcSecurity.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchProcSecurity.swift
index d149a73e..3d8652f0 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchProcSecurity.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchProcSecurity.swift
@@ -11,6 +11,7 @@
// used by jailbreak userland never hit cross-identity authorization denials.
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
/// Stub _proc_security_policy: mov x0,#0; ret.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchSandboxExtended.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchSandboxExtended.swift
index 46d336ea..d9327839 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchSandboxExtended.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchSandboxExtended.swift
@@ -13,6 +13,7 @@
// the high 32 bits (PAC/auth-rebase metadata), and emit the new value.
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
/// Extended sandbox hooks bypass: retarget ops entries to the allow stub.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchBsdInitAuth.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchBsdInitAuth.swift
index d388023b..00590b1f 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchBsdInitAuth.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchBsdInitAuth.swift
@@ -13,8 +13,8 @@
// with a BL to _imageboot_needed (or any BL) in the next 3 instructions.
// 5. NOP that cbnz.
-import Capstone
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
private static let rootvpAuthNeedle = "rootvp not authenticated after mounting"
@@ -159,10 +159,10 @@ extension KernelJailbreakPatcher {
// Must be CBNZ on w0 or x0
guard insn.mnemonic == "cbnz" else { return nil }
- guard let detail = insn.aarch64, !detail.operands.isEmpty else { return nil }
+ guard let detail = insn.detail, !detail.operands.isEmpty else { return nil }
let regOp = detail.operands[0]
- guard regOp.type == AARCH64_OP_REG,
- regOp.reg == AARCH64_REG_W0 || regOp.reg == AARCH64_REG_X0 else { return nil }
+ guard regOp.type == .register,
+ regOp.reg == .w(0) || regOp.reg == .x(0) else { return nil }
// Branch target must point into the panic block region
guard let (branchTarget, _) = jbDecodeBranchTarget(at: off),
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchDiskImages2.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchDiskImages2.swift
index 4997f005..02c065a8 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchDiskImages2.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchDiskImages2.swift
@@ -32,8 +32,8 @@
// Capstone decode, replacement bytes from the Keystone-backed ARM64/ARM64Encoder
// helpers.
-import Capstone
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
/// Apply all DiskImages2 ABI pokes. Wired into KernelJailbreakPatcher.findAll().
@@ -93,10 +93,10 @@ extension KernelJailbreakPatcher {
while off + 8 <= funcEnd {
defer { off += 4 }
guard let cmp = disasAt(off), cmp.mnemonic == "cmp",
- let ops = cmp.aarch64?.operands, ops.count == 2,
- ops[0].type == AARCH64_OP_REG,
+ let ops = cmp.detail?.operands, ops.count == 2,
+ ops[0].type == .register,
disasm.firstRegisterName(cmp)?.hasPrefix("w") ?? false,
- ops[1].type == AARCH64_OP_IMM, ops[1].imm == 9
+ ops[1].type == .immediate, ops[1].imm == 9
else { continue }
guard let nxt = disasAt(off + 4), nxt.mnemonic == "b.ne" else { continue }
hits.append(off + 4) // the b.ne
@@ -215,9 +215,9 @@ extension KernelJailbreakPatcher {
while off + 4 <= funcEnd {
defer { off += 4 }
guard let ins = disasAt(off), ins.mnemonic == mnemonic,
- let ops = ins.aarch64?.operands, ops.count == 2,
- ops[0].type == AARCH64_OP_REG,
- ops[1].type == AARCH64_OP_MEM, ops[1].mem.disp == disp
+ let ops = ins.detail?.operands, ops.count == 2,
+ ops[0].type == .register,
+ ops[1].type == .memory, ops[1].mem.disp == disp
else { continue }
if requireWDest, !(disasm.firstRegisterName(ins)?.hasPrefix("w") ?? false) {
continue
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchDounmount.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchDounmount.swift
index bfd33812..7bbe8a6d 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchDounmount.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchDounmount.swift
@@ -6,8 +6,8 @@
// call: mov x0,xN ; mov w1,#0 ; mov w2,#0 ; mov w3,#0 ; bl ; mov x0,xN ; bl ; cbz x19,...
// Patch: NOP the first BL in that sequence.
-import Capstone
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
/// NOP the upstream cleanup call in _dounmount.
@@ -80,36 +80,36 @@ extension KernelJailbreakPatcher {
}
/// Return the source register name if instruction is `mov <dst>, <src_reg>`.
- private func movRegRegDst(_ insn: Instruction, dst: String) -> String? {
+ private func movRegRegDst(_ insn: ARM64Instruction, dst: String) -> String? {
guard insn.mnemonic == "mov" else { return nil }
- guard let detail = insn.aarch64, detail.operands.count == 2 else { return nil }
+ guard let detail = insn.detail, detail.operands.count == 2 else { return nil }
let dstOp = detail.operands[0], srcOp = detail.operands[1]
- guard dstOp.type == AARCH64_OP_REG, srcOp.type == AARCH64_OP_REG else { return nil }
+ guard dstOp.type == .register, srcOp.type == .register else { return nil }
guard regName(dstOp.reg) == dst else { return nil }
return regName(srcOp.reg)
}
/// Return true if instruction is `mov <dst>, #0`.
- private func movImmZero(_ insn: Instruction, dst: String) -> Bool {
+ private func movImmZero(_ insn: ARM64Instruction, dst: String) -> Bool {
guard insn.mnemonic == "mov" else { return false }
- guard let detail = insn.aarch64, detail.operands.count == 2 else { return false }
+ guard let detail = insn.detail, detail.operands.count == 2 else { return false }
let dstOp = detail.operands[0], srcOp = detail.operands[1]
- guard dstOp.type == AARCH64_OP_REG, regName(dstOp.reg) == dst else { return false }
- guard srcOp.type == AARCH64_OP_IMM, srcOp.imm == 0 else { return false }
+ guard dstOp.type == .register, regName(dstOp.reg) == dst else { return false }
+ guard srcOp.type == .immediate, srcOp.imm == 0 else { return false }
return true
}
/// Return true if instruction is `cbz x<N>, <label>` (64-bit register).
- private func cbzUsesXreg(_ insn: Instruction) -> Bool {
+ private func cbzUsesXreg(_ insn: ARM64Instruction) -> Bool {
guard insn.mnemonic == "cbz" else { return false }
- guard let detail = insn.aarch64, detail.operands.count >= 2 else { return false }
+ guard let detail = insn.detail, detail.operands.count >= 2 else { return false }
let regOp = detail.operands[0]
- guard regOp.type == AARCH64_OP_REG else { return false }
+ guard regOp.type == .register else { return false }
return regName(regOp.reg).hasPrefix("x")
}
- /// Get the register name string for an aarch64_reg value.
- private func regName(_ reg: aarch64_reg) -> String {
- disasm.registerName(reg.rawValue) ?? "??"
+ /// Get the register name string for a decoded register operand.
+ private func regName(_ reg: ARM64Register) -> String {
+ reg.name ?? "??"
}
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchSecureRoot.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchSecureRoot.swift
index ecc7dd17..fec67602 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchSecureRoot.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchSecureRoot.swift
@@ -14,8 +14,8 @@
// — a stable ABI signature, not a pinned field offset or struct layout.
// Patch: rewrite that CSEL to `mov Wd, #0` so the policy always returns success.
-import Capstone
import Foundation
+import VPhonePatchKit
extension KernelJailbreakPatcher {
/// Force SecureRootName policy return to success in AppleARMPE::callPlatformFunction.
@@ -111,18 +111,18 @@ extension KernelJailbreakPatcher {
for off in stride(from: funcStart, to: funcEnd - 4, by: 4) {
let insns = disasm.disassemble(in: buffer.data, at: off, count: 1)
guard let insn = insns.first, insn.mnemonic == "csel" else { continue }
- guard let detail = insn.aarch64, detail.operands.count >= 3 else { continue }
+ guard let detail = insn.detail, detail.operands.count >= 3 else { continue }
let destOp = detail.operands[0]
let zeroSrcOp = detail.operands[1]
let errSrcOp = detail.operands[2]
- guard destOp.type == AARCH64_OP_REG,
- zeroSrcOp.type == AARCH64_OP_REG,
- errSrcOp.type == AARCH64_OP_REG else { continue }
+ guard destOp.type == .register,
+ zeroSrcOp.type == .register,
+ errSrcOp.type == .register else { continue }
- let destName = disasm.registerName(UInt32(destOp.reg.rawValue)) ?? ""
- let zeroName = disasm.registerName(UInt32(zeroSrcOp.reg.rawValue)) ?? ""
- let errName = disasm.registerName(UInt32(errSrcOp.reg.rawValue)) ?? ""
+ let destName = destOp.reg.name ?? ""
+ let zeroName = zeroSrcOp.reg.name ?? ""
+ let errName = errSrcOp.reg.name ?? ""
// Allow value must be 0 (wzr); deny value is the error register.
guard destName.hasPrefix("w") else { continue }
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelExperimentalPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelExperimentalPatcher.swift
index ec8f0ae0..a4fb6512 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelExperimentalPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelExperimentalPatcher.swift
@@ -9,6 +9,7 @@
// EXPPatches/KernelExperimentalPatchHvVmmRename.swift for the implementation.
import Foundation
+import VPhonePatchKit
/// Experimental kernel patcher.
///
@@ -16,7 +17,7 @@ import Foundation
/// encoders, code-cave finder, string-anchored function finders, etc.) from
/// `KernelJailbreakPatcherBase` so EXP-specific patches can use the same helpers
/// as JB ones without duplicating them.
-public final class KernelExperimentalPatcher: KernelJailbreakPatcherBase, Patcher {
+public final class KernelExperimentalPatcher: KernelJailbreakPatcherBase, BufferedPatcher {
public let component = "kernelcache_exp"
public func findAll() throws -> [PatchRecord] {
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelJailbreakPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelJailbreakPatcher.swift
index 71d442b7..a019c50f 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelJailbreakPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelJailbreakPatcher.swift
@@ -3,15 +3,17 @@
// Historical note: derived from the legacy Python firmware patcher during the Swift migration.
import Foundation
+import VPhonePatchKit
/// JB kernel patcher across 3 groups. Variant- and feature-gated methods can
/// change the emitted record count; iOS-27-only patches are gated by `applyIOS27`
-/// and Frida Stalker relaxations by `applyFrida` (opt-in `--frida`).
+/// and Frida Stalker relaxations by `applyFrida`, which the pipeline sets from the
+/// plan — the `com.vphone.patchset.kernel.frida` patches, off in `standard`.
///
/// Group A: Core gate-bypass methods
/// Group B: Pattern/string anchored methods
/// Group C: Shellcode/trampoline heavy methods
-public final class KernelJailbreakPatcher: KernelJailbreakPatcherBase, Patcher {
+public final class KernelJailbreakPatcher: KernelJailbreakPatcherBase, BufferedPatcher {
public let component = "kernelcache_jb"
/// Gates the iOS-27-only kernel patches. These target an iOS-27 userland running
@@ -23,8 +25,10 @@ public final class KernelJailbreakPatcher: KernelJailbreakPatcherBase, Patcher {
/// set (override with --target-os).
public var applyIOS27 = false
- /// Opt-in Frida Stalker kernel relaxations (exposed as `--frida`). Baseline
- /// JB/EXP firmware is byte-identical when false.
+ /// Opt-in Frida Stalker kernel relaxations. Set from the plan: `standard` blocks
+ /// both, `extended` and a per-VM checkmark turn them on, and their own
+ /// cloudOS 26.4+ gate then decides whether they land. Baseline JB/EXP firmware is
+ /// byte-identical when false.
public var applyFrida = false
public func findAll() throws -> [PatchRecord] {
@@ -73,8 +77,9 @@ public final class KernelJailbreakPatcher: KernelJailbreakPatcherBase, Patcher {
patchVmFaultEnterPrepare()
patchVmMapProtect()
- // Opt-in Frida Stalker support (--frida): existing-thread follow
- // (thread_set_state) + repeated VM_PROT_COPY overwrite (vm_map_delete).
+ // Opt-in Frida Stalker support, from the kernel.frida patch set:
+ // existing-thread follow (thread_set_state) + repeated VM_PROT_COPY
+ // overwrite (vm_map_delete).
if applyFrida {
patchThreadSetStateEntitlementFlag()
patchVmMapDeleteImmutableCode()
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelJailbreakPatcherBase.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelJailbreakPatcherBase.swift
index 0b6169c0..1e770c3e 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelJailbreakPatcherBase.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelJailbreakPatcherBase.swift
@@ -2,8 +2,8 @@
//
// Historical note: derived from the legacy Python firmware patcher during the Swift migration.
-import Capstone
import Foundation
+import VPhonePatchKit
/// Base class for JB kernel patching, extending KernelPatcherBase with:
/// - Symbol table parsing (nlist64 from LC_SYMTAB + fileset entries)
@@ -273,7 +273,7 @@ public class KernelJailbreakPatcherBase: KernelPatcherBase {
// MARK: - Disassemble Helper
/// Disassemble one instruction at file offset in the mutable buffer.
- func disasAt(_ off: Int) -> Instruction? {
+ func disasAt(_ off: Int) -> ARM64Instruction? {
guard off >= 0, off + 4 <= buffer.count else { return nil }
return disasm.disassembleOne(in: buffer.data, at: off)
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelPatcher.swift
index c81ea1d4..2208bb22 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelPatcher.swift
@@ -4,12 +4,13 @@
// Each patch method is defined as an extension in its own file under Patches/.
import Foundation
+import VPhonePatchKit
/// Regular kernel patcher for iOS prelinked kernelcaches.
///
/// Patches are applied in the same order as the Python reference implementation.
/// Each patch method is an extension in a separate file under `Kernel/Patches/`.
-public final class KernelPatcher: KernelPatcherBase, Patcher {
+public final class KernelPatcher: KernelPatcherBase, BufferedPatcher {
public let component = "kernelcache"
/// When true, includes dev-only kernel patches (e.g. EXC_GUARD disable).
@@ -18,8 +19,10 @@ public final class KernelPatcher: KernelPatcherBase, Patcher {
/// When true, apply the EXC_GUARD (Mach port guard) disable even on
/// non-dev variants. Always required on iOS 18 bases: their older
/// userland (runningboardd/SpringBoard) trips a Mach port guard
- /// "flavor 10" that crash-loops the UI. On other bases this is opt-in
- /// (see `FirmwarePipeline`'s `forceExcGuard`/`--force-exc-guard`): some
+ /// "flavor 10" that crash-loops the UI. On other bases it is off: the
+ /// `kernel.thread_guard_violation` declaration is pinned to iOS 18, and no
+ /// preset or checkmark can widen a version gate, so a 26.x or 27.x base cannot
+ /// ask for it any more. What it used to be for: some
/// third-party apps calling task_swap_exception_ports() (crash-reporting/
/// RASP SDKs) can trip a GUARD_TYPE_MACH_PORT/KOBJECT_REPLY_PORT_SEMANTICS
/// violation that the research kernel enforces fatally (upstream issue
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelPatcherBase.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelPatcherBase.swift
index 24497b11..c33a9fd3 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelPatcherBase.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelPatcherBase.swift
@@ -4,8 +4,8 @@
// kext range discovery, and the emit() system.
// Historical note: this file replaces the old Python firmware patcher implementation.
-import Capstone
import Foundation
+import VPhonePatchKit
/// Base class for kernel patchers providing shared infrastructure.
open class KernelPatcherBase {
@@ -17,9 +17,19 @@ open class KernelPatcherBase {
/// Verbose logging.
public let verbose: Bool
+ /// Which patches the resolved preset turned on. Unrestricted by default, so a
+ /// patcher built directly applies everything it finds.
+ public var gate: VPhonePatchGate = .unrestricted
+
/// Collected patch records.
public var patches: [PatchRecord] = []
+ /// The kernelcache after ``emit`` wrote every allowed site.
+ ///
+ /// ``BufferedPatcher`` is how the pipeline reads a component's result, so the
+ /// three concrete kernel patchers satisfy it from here.
+ public var patchedData: Data { buffer.data }
+
/// Base virtual address of the kernelcache __TEXT segment.
public var baseVA: UInt64 = 0
@@ -81,6 +91,10 @@ open class KernelPatcherBase {
virtualAddress: UInt64? = nil,
description: String,
) {
+ // The gate is consulted before the write, not after: a record dropped
+ // afterwards would leave the bytes patched and nothing saying so.
+ guard gate.allowsReporting(record: patchID, component: "kernelcache", verbose: verbose) else { return }
+
let originalBytes = buffer.readBytes(at: offset, count: patchBytes.count)
// Disassemble before/after
@@ -234,12 +248,12 @@ open class KernelPatcherBase {
/// Decode a conditional branch instruction, returning its target as a file offset.
/// Returns nil if the instruction is not a conditional branch.
- public func conditionalBranchTarget(insn: Instruction) -> Int? {
+ public func conditionalBranchTarget(insn: ARM64Instruction) -> Int? {
guard KernelPatcherBase.conditionalBranchMnemonics.contains(insn.mnemonic) else { return nil }
// Target is always the last IMM operand.
- guard let detail = insn.aarch64 else { return nil }
+ guard let detail = insn.detail else { return nil }
for op in detail.operands.reversed() {
- if op.type == AARCH64_OP_IMM {
+ if op.type == .immediate {
return Int(op.imm)
}
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Manifest/ManifestHashPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Manifest/ManifestHashPatcher.swift
index b458c1fd..0d60cc17 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Manifest/ManifestHashPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Manifest/ManifestHashPatcher.swift
@@ -6,9 +6,10 @@
import CryptoKit
import Foundation
import Img4tool
+import VPhonePatchKit
/// Patcher for Manifest payloads.
-public final class ManifestHashPatcher: Patcher {
+public final class ManifestHashPatcher: BufferedPatcher {
public let component = "Manifest"
public let restoreDir: URL?
public let verbose: Bool
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchInfrastructure/PatcherProtocol.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchInfrastructure/PatcherProtocol.swift
deleted file mode 100644
index 8e5464d4..00000000
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchInfrastructure/PatcherProtocol.swift
+++ /dev/null
@@ -1,28 +0,0 @@
-// PatcherProtocol.swift — Common protocol for all firmware patchers.
-
-import Foundation
-
-/// A firmware patcher that can find and apply patches to a binary buffer.
-public protocol Patcher {
- /// The component name (e.g., "kernelcache", "ibss", "txm").
- var component: String { get }
-
- /// Whether to print verbose output.
- var verbose: Bool { get }
-
- /// Find all patch sites and return patch records (dry-run mode).
- func findAll() throws -> [PatchRecord]
-
- /// Apply all patches to the buffer. Returns the number of patches applied.
- @discardableResult
- func apply() throws -> Int
-}
-
-extension Patcher {
- /// Log a message if verbose mode is enabled.
- func log(_ message: String) {
- if verbose {
- print(message)
- }
- }
-}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareBootChainPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareBootChainPatchSet.swift
new file mode 100644
index 00000000..68e64df5
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareBootChainPatchSet.swift
@@ -0,0 +1,167 @@
+// FirmwareBootChainPatchSet.swift — Manifest for the signed boot chain.
+//
+// AVPBooter, iBSS, iBEC, LLB and TXM. Almost everything here is boot-essential:
+// the chain either accepts the resealed images or the VM never reaches the
+// kernel. The two that are not — the serial labels and the boot-args string —
+// only change what the guest logs and how it is told to start.
+//
+// Identifiers are the record identifiers the patchers already emit, so a record
+// in a log and a checkbox in the UI name the same thing.
+
+import Foundation
+import VPhonePatchKit
+
+public enum FirmwareBootChainPatchSet {
+ public static let identifier = "com.vphone.patchset.bootchain"
+
+ public static let manifest = VPhonePatchSetManifest(
+ identifier: identifier,
+ name: "Boot Chain",
+ summary: "AVPBooter, iBSS, iBEC, LLB and TXM image-4 and boot-policy patches",
+ patches: [
+ // MARK: AVPBooter
+
+ VPhonePatchDeclaration(
+ identifier: "avpbooter.dgst_bypass",
+ title: "AVPBooter digest bypass",
+ summary: "Accepts the resealed boot images instead of the stock digests.",
+ target: .firmware(.avpBooter),
+ bootEssential: true,
+ ),
+
+ // MARK: iBSS
+
+ VPhonePatchDeclaration(
+ identifier: "ibss.serial_label",
+ title: "iBSS serial label",
+ summary: "Tags iBSS serial output so the boot log names its stage.",
+ target: .firmware(.iBSS),
+ ),
+ VPhonePatchDeclaration(
+ identifier: "ibss.image4_callback",
+ title: "iBSS image-4 callback",
+ summary: "Lets iBSS load the resealed next stage.",
+ target: .firmware(.iBSS),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "ibss_jb.skip_generate_nonce",
+ title: "iBSS nonce generation skip",
+ summary: "Keeps the boot nonce stable so a personalised image stays valid.",
+ target: .firmware(.iBSS),
+ bootEssential: true,
+ ),
+
+ // MARK: iBEC
+
+ VPhonePatchDeclaration(
+ identifier: "ibec.serial_label",
+ title: "iBEC serial label",
+ summary: "Tags iBEC serial output so the boot log names its stage.",
+ target: .firmware(.iBEC),
+ ),
+ VPhonePatchDeclaration(
+ identifier: "ibec.image4_callback",
+ title: "iBEC image-4 callback",
+ summary: "Lets iBEC load the resealed kernelcache.",
+ target: .firmware(.iBEC),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "ibec.boot_args",
+ title: "iBEC boot arguments",
+ summary: "Installs the research boot-args string iBEC hands the kernel.",
+ target: .firmware(.iBEC),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "ibec.bootx_precondition",
+ title: "iBEC bootx precondition",
+ summary: "Drops the precondition that would refuse a patched chain.",
+ target: .firmware(.iBEC),
+ bootEssential: true,
+ ),
+
+ // MARK: LLB
+
+ VPhonePatchDeclaration(
+ identifier: "llb.serial_label",
+ title: "LLB serial label",
+ summary: "Tags LLB serial output so the boot log names its stage.",
+ target: .firmware(.llb),
+ ),
+ VPhonePatchDeclaration(
+ identifier: "llb.image4_callback",
+ title: "LLB image-4 callback",
+ summary: "Lets LLB load the resealed next stage.",
+ target: .firmware(.llb),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "llb.boot_args",
+ title: "LLB boot arguments",
+ summary: "Installs the research boot-args string LLB passes along.",
+ target: .firmware(.llb),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "llb.rootfs",
+ title: "LLB root filesystem checks",
+ summary: "Skips the signature, size and null checks on the patched root image.",
+ target: .firmware(.llb),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "llb.panic_bypass",
+ title: "LLB panic bypass",
+ summary: "Turns LLB's image-policy panic into a continue.",
+ target: .firmware(.llb),
+ bootEssential: true,
+ ),
+
+ // MARK: TXM
+
+ VPhonePatchDeclaration(
+ identifier: "txm.trustcache_bypass",
+ title: "TXM trust cache bypass",
+ summary: "Lets TXM admit the guest's own trust cache entries.",
+ target: .firmware(.txm),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "txm_dev.get_task_allow",
+ title: "TXM get-task-allow",
+ summary: "Grants get-task-allow so a debugger can attach in the guest.",
+ target: .firmware(.txm),
+ ),
+ VPhonePatchDeclaration(
+ identifier: "txm_dev.debugger_entitlement",
+ title: "TXM debugger entitlement",
+ summary: "Grants the task_for_pid debugger entitlement.",
+ target: .firmware(.txm),
+ ),
+ VPhonePatchDeclaration(
+ identifier: "txm_dev.developer_mode_bypass",
+ title: "TXM developer mode",
+ summary: "Reports developer mode on without the enrolment dance.",
+ target: .firmware(.txm),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "txm_dev.selector24_bypass",
+ title: "TXM selector 24 bypass",
+ summary: "Lets the selector-24 code-signing query succeed.",
+ target: .firmware(.txm),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "txm_dev.sel42_29",
+ title: "TXM selector 42/29 shellcode",
+ summary: "Installs the selector-42/29 stub that admits guest signatures.",
+ target: .firmware(.txm),
+ bootEssential: true,
+ ),
+ ],
+ provides: ["vphone.bootchain"],
+ )
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swift
new file mode 100644
index 00000000..519b96b1
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swift
@@ -0,0 +1,164 @@
+// FirmwareDeviceTreePatchSet.swift — Manifest for the device tree.
+//
+// Two kinds of entry. The first four properties make the research board present
+// as a phone the guest's own UI can lay out. The rest give it the iPhone17,3
+// identity and the camera, audio and SMC nodes that identity implies, which is
+// what lets a stock app see a plausible device.
+//
+// None is boot-essential: a VM with a stock device tree boots, it just looks like
+// a research board and has no camera.
+
+import Foundation
+import VPhonePatchKit
+
+public enum FirmwareDeviceTreePatchSet {
+ public static let identifier = "com.vphone.patchset.devicetree"
+
+ private static func property(
+ _ identifier: String,
+ _ title: String,
+ _ summary: String,
+ ) -> VPhonePatchDeclaration {
+ VPhonePatchDeclaration(
+ identifier: identifier,
+ title: title,
+ summary: summary,
+ target: .firmware(.deviceTree),
+ )
+ }
+
+ public static let manifest = VPhonePatchSetManifest(
+ identifier: identifier,
+ name: "Device Tree",
+ summary: "Display geometry plus the iPhone17,3 identity, camera, audio and SMC nodes",
+ patches: [
+ // MARK: Board Presentation
+
+ property(
+ "devicetree.serial_number",
+ "Serial number",
+ "Gives the board a well-formed serial number.",
+ ),
+ property(
+ "devicetree.home_button_type",
+ "Home button type",
+ "Declares a gesture-driven device with no home button.",
+ ),
+ property(
+ "devicetree.artwork_device_subtype",
+ "Artwork device subtype",
+ "Picks the artwork subtype the guest UI lays out against.",
+ ),
+ property(
+ "devicetree.island_notch_location",
+ "Island notch location",
+ "Places the sensor cutout so status bar layout matches the display.",
+ ),
+
+ // MARK: Device Identity
+
+ property(
+ "devicetree.target_sub_type",
+ "Target sub type",
+ "Reports the iPhone17,3 target sub type.",
+ ),
+ property(
+ "devicetree.compatible_secondary",
+ "Compatible list",
+ "Adds the iPhone17,3 entry to the board's compatible list.",
+ ),
+ property(
+ "devicetree.product.fdr_product_type",
+ "FDR product type",
+ "Reports the iPhone17,3 product type to FDR.",
+ ),
+ property(
+ "devicetree.product.sub_product_type",
+ "Sub product type",
+ "Reports the iPhone17,3 sub product type.",
+ ),
+ property(
+ "devicetree.product.unique_model",
+ "Unique model code",
+ "Reports the model code a stock app reads for the device name.",
+ ),
+ property(
+ "devicetree.product.gestalt_variants_rename",
+ "Gestalt variants",
+ "Renames the gestalt variants node so the identity is consistent.",
+ ),
+ property(
+ "devicetree.arm_io.device_type",
+ "SoC device type",
+ "Reports the SoC device type the identity implies.",
+ ),
+ property(
+ "devicetree.arm_io.soc_generation",
+ "SoC generation",
+ "Reports the SoC generation the identity implies.",
+ ),
+
+ // MARK: Camera Geometry
+
+ property(
+ "devicetree.product.front_cam_offset",
+ "Front camera offset",
+ "Places the front camera where the identity's hardware has it.",
+ ),
+ property(
+ "devicetree.product.rear_cam_offset",
+ "Rear camera offset",
+ "Places the rear camera where the identity's hardware has it.",
+ ),
+
+ // MARK: Added Nodes
+
+ property(
+ "devicetree.product.camera_node",
+ "Camera node",
+ "Adds the camera node the virtual camera is published under.",
+ ),
+ property(
+ "devicetree.product.facetime_node",
+ "FaceTime node",
+ "Adds the FaceTime camera node.",
+ ),
+ property(
+ "devicetree.product.audio_node",
+ "Audio node",
+ "Adds the audio topology node so the guest has speakers.",
+ ),
+ property(
+ "devicetree.product.iopm_node",
+ "Power management node",
+ "Adds the IOPM node the power stack expects.",
+ ),
+ property(
+ "devicetree.arm_io.smc_stub",
+ "SMC stub",
+ "Adds a stub SMC so the power and thermal clients attach.",
+ ),
+ property(
+ "devicetree.arm_io.smc.iop_smc_nub_stub",
+ "SMC nub stub",
+ "Adds the SMC nub the IOP driver binds to.",
+ ),
+ property(
+ "devicetree.arm_io.smc.smc_ext_charger_camera_driver",
+ "SMC charger and camera driver",
+ "Publishes the charger and camera driver under the stub SMC.",
+ ),
+ property(
+ "devicetree.arm_io.isp_camera_flags",
+ "ISP camera flags",
+ "Sets the ISP flags the virtual camera pipeline needs.",
+ ),
+ property(
+ "devicetree.arm_io.ispRtb_camera_flags",
+ "ISP RTB camera flags",
+ "Sets the ISP round-trip buffer flags for the camera pipeline.",
+ ),
+ ],
+ provides: ["vphone.devicetree"],
+ )
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareExternalPatchSets.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareExternalPatchSets.swift
new file mode 100644
index 00000000..a787b4e5
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareExternalPatchSets.swift
@@ -0,0 +1,62 @@
+// FirmwareExternalPatchSets.swift — The `.vphonepatchset` bundles one run loaded.
+//
+// A loaded set contributes patchers to the boot-chain components its manifest
+// declares an enabled patch for, and nothing else. Two rules are worth stating
+// where they are implemented:
+//
+// * A set whose patches the plan all turned off is never asked for a patcher.
+// This is the same rule the bundled sets follow. A patcher built anyway would
+// emit records that no *enabled* declaration covers, and the gate applies an
+// undeclared record rather than dropping it (``VPhonePatchGate``), so the
+// patches would land after being switched off.
+//
+// * External patchers run after the bundled patchers of the same component. The
+// order *among* external sets follows the resolved plan, so a set that
+// declared `After` another runs after it. Nothing lets an external set run
+// before a bundled one; a set that needs to undo a bundled patch blocks it in
+// the preset instead.
+
+import Foundation
+import VPhonePatchKit
+
+final class FirmwareExternalPatchSets {
+ private struct Loaded {
+ let bundle: VPhonePatchSetBundle
+ let principal: VPhonePatchSetPrincipal
+ }
+
+ private var loaded: [String: Loaded] = [:]
+
+ var isEmpty: Bool { loaded.isEmpty }
+
+ /// Map the set's executable and keep its principal for the rest of the run.
+ ///
+ /// The caller has already validated the manifest; this is the step that starts
+ /// running the set's code.
+ func add(_ bundle: VPhonePatchSetBundle) throws {
+ loaded[bundle.manifest.identifier] = Loaded(
+ bundle: bundle,
+ principal: try bundle.loadPrincipal(),
+ )
+ }
+
+ /// Factories for `component`, in the order the plan resolved the sets.
+ func factories(
+ for component: VPhoneFirmwareComponent,
+ plan: VPhonePatchPlan,
+ context: VPhonePatchSetContext,
+ ) -> [(Data, Bool) throws -> any Patcher] {
+ guard !loaded.isEmpty else { return [] }
+ var factories: [(Data, Bool) throws -> any Patcher] = []
+ for manifest in plan.patchSets {
+ guard let entry = loaded[manifest.identifier],
+ entry.bundle.enabledComponents(in: plan).contains(component)
+ else { continue }
+ let principal = entry.principal
+ factories.append { data, _ in
+ try principal.makePatcher(for: component, data: data, context: context)
+ }
+ }
+ return factories
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestDisplayPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestDisplayPatchSet.swift
new file mode 100644
index 00000000..343b7e3e
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestDisplayPatchSet.swift
@@ -0,0 +1,45 @@
+// FirmwareGuestDisplayPatchSet.swift — Manifest for the guest display path.
+//
+// IOMFB talks to a framebuffer that does not exist on a research board. Which
+// patch is needed depends on the userland: a 27 base routes the swap through the
+// kernel, while 26.0 and 18.x only need the swap-end structure resized. The two
+// are mutually exclusive by version, so one set covers both.
+
+import Foundation
+import VPhonePatchKit
+
+public enum FirmwareGuestDisplayPatchSet {
+ public static let identifier = "com.vphone.patchset.guest.display"
+
+ public static let manifest = VPhonePatchSetManifest(
+ identifier: identifier,
+ name: "Guest Display",
+ summary: "IOMFB patches that let the guest present a frame on the virtual display",
+ patches: [
+ VPhonePatchDeclaration(
+ identifier: "iomfb_force_kern",
+ title: "IOMFB force kernel swap",
+ summary: "Routes the 27 display swap through the kernel, where the virtual framebuffer lives.",
+ target: .dyldSharedCache,
+ applicability: VPhonePatchApplicability(iOSBase: .major(27)),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "dsc.iomfb_swapend",
+ title: "IOMFB swap-end size",
+ summary: "Resizes the swap-end structure a 26.0 or 18.x userland submits.",
+ target: .dyldSharedCache,
+ applicability: VPhonePatchApplicability(
+ iOSBase: .oneOf([.release(major: 26, minor: 0), .major(18)]),
+ ),
+ bootEssential: true,
+ ),
+ ],
+ requires: ["vphone.guest.system"],
+ provides: ["vphone.guest.display"],
+ after: ["vphone.guest.system"],
+ )
+
+ /// The swap-end target size the verb is invoked with.
+ public static let swapEndTargetSize = "0x560"
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestIdentityPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestIdentityPatchSet.swift
new file mode 100644
index 00000000..f52cebb2
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestIdentityPatchSet.swift
@@ -0,0 +1,47 @@
+// FirmwareGuestIdentityPatchSet.swift — Manifest for what the guest sees of itself.
+//
+// The shared-cache half of the hypervisor concealment that the kernel set starts,
+// plus the camera symbols the virtual camera is published through. These pair with
+// `com.vphone.patchset.kernel.hypervisor` and the device tree's camera nodes: on
+// their own, each half leaves the guest inconsistent with itself.
+
+import Foundation
+import VPhonePatchKit
+
+public enum FirmwareGuestIdentityPatchSet {
+ public static let identifier = "com.vphone.patchset.guest.identity"
+
+ public static let manifest = VPhonePatchSetManifest(
+ identifier: identifier,
+ name: "Guest Identity",
+ summary: "Hypervisor concealment in the shared cache and watchdog, plus the virtual camera symbols",
+ patches: [
+ VPhonePatchDeclaration(
+ identifier: "hv_vmm_dsc",
+ title: "Shared cache hypervisor strings",
+ summary: """
+ Mangles the hv_vmm_present references in the shared cache, so a userland check \
+ finds nothing where the kernel set renamed the sysctl.
+ """,
+ target: .dyldSharedCache,
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "watchdogd.hv_vmm_cache",
+ title: "watchdogd hypervisor cache",
+ summary: "Stops watchdogd caching a positive hypervisor answer and acting on it.",
+ target: .guestExecutable(path: "/usr/libexec/watchdogd"),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "camera_dsc",
+ title: "Camera shared cache symbols",
+ summary: "Redirects the camera symbols the virtual camera publishes frames through.",
+ target: .dyldSharedCache,
+ ),
+ ],
+ requires: ["vphone.guest.system"],
+ provides: ["vphone.guest.identity"],
+ after: ["vphone.guest.system"],
+ )
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
new file mode 100644
index 00000000..a51c846e
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
@@ -0,0 +1,161 @@
+// FirmwareGuestSystemPatchSet.swift — Manifest for the mounted guest volume.
+//
+// What `cfw install` does after the restore: the shared-cache policy gates a 27
+// userland needs, the handful of system daemons that must be patched to start on
+// a research board, and the vphone payload itself.
+//
+// Unlike the boot chain, several of these are Mach-O or shared-cache edits that
+// emit no patch record — a string mangled in place, a file installed. Their
+// identifiers name the operation instead of mirroring a record, and they are
+// still the names a preset selects and the UI lists.
+
+import Foundation
+import VPhonePatchKit
+
+public enum FirmwareGuestSystemPatchSet {
+ public static let identifier = "com.vphone.patchset.guest.system"
+
+ private static let ios27 = VPhonePatchApplicability(iOSBase: .major(27))
+
+ public static let manifest = VPhonePatchSetManifest(
+ identifier: identifier,
+ name: "Guest System",
+ summary: "Shared-cache policy gates, patched system daemons and the vphone guest payload",
+ patches: [
+ // MARK: Shared Cache Policy
+
+ VPhonePatchDeclaration(
+ identifier: "dsc_maxslide.zero",
+ title: "Shared cache max slide",
+ summary: """
+ Zeroes the shared cache's maximum slide. A 27 userland otherwise computes a slide \
+ the patched cache cannot satisfy.
+ """,
+ target: .dyldSharedCache,
+ applicability: ios27,
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "lsd_embedded_reg.entitlement_gate",
+ title: "lsd registration entitlement",
+ summary: "Lets lsd register the guest's embedded app bundles.",
+ target: .dyldSharedCache,
+ applicability: ios27,
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "xpc_lwcr",
+ title: "XPC lightweight code requirements",
+ summary: "Stops XPC refusing a peer whose lightweight code requirement no longer matches.",
+ target: .dyldSharedCache,
+ applicability: ios27,
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "lockdown_mode.sysctl_error_gate",
+ title: "Lockdown mode sysctl gate",
+ summary: "Stops a failed lockdown-mode sysctl read being treated as an error.",
+ target: .dyldSharedCache,
+ applicability: ios27,
+ bootEssential: true,
+ ),
+
+ // MARK: System Daemons
+
+ VPhonePatchDeclaration(
+ identifier: "seputil.gigalocker_uuid",
+ title: "seputil Gigalocker UUID",
+ summary: "Points seputil at the renamed Gigalocker so key material resolves.",
+ target: .guestExecutable(path: "/usr/libexec/seputil"),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "diskimagesiod.is_mount_complete",
+ title: "diskimagesiod mount completion",
+ summary: "Reports the personalised developer image as mounted on a 27 userland.",
+ target: .guestExecutable(path: "/usr/libexec/diskimagesiod"),
+ applicability: ios27,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "launchd_cache_loader.unsecure_cache_gate",
+ title: "launchd cache loader gate",
+ summary: "Lets the launchd cache loader accept the patched, unsealed cache.",
+ target: .guestExecutable(path: "/usr/libexec/launchd_cache_loader"),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "mobileactivationd.should_hactivate",
+ title: "mobileactivationd activation",
+ summary: "Reports the device activated, so the guest reaches the home screen.",
+ target: .guestExecutable(path: "/usr/libexec/mobileactivationd"),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "launchd_jetsam.panic_guard_bypass",
+ title: "launchd jetsam panic guard",
+ summary: "Stops launchd panicking when jetsam reaps a process the VM needs.",
+ target: .guestExecutable(path: "/sbin/launchd"),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "guest.debugserver",
+ title: "debugserver",
+ summary: "Installs a debugserver that can attach in the guest.",
+ target: .guestFile(path: "/usr/bin/debugserver"),
+ ),
+ VPhonePatchDeclaration(
+ identifier: "campo.entitlements",
+ title: "Campo entitlements",
+ summary: "Widens Campo's entitlements so the 27 setup assistant completes.",
+ target: .guestEntitlements(path: "/System/Library/PrivateFrameworks/Campo.framework/Campo"),
+ applicability: ios27,
+ ),
+
+ // MARK: Guest Payload
+
+ VPhonePatchDeclaration(
+ identifier: "guest.gigalocker_rename",
+ title: "Gigalocker rename",
+ summary: "Renames the data volume's Gigalocker so the guest recreates it.",
+ target: .guestFile(path: "/private/var/Gigalocker"),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "guest.gpu_bundle",
+ title: "GPU driver bundle",
+ summary: "Installs the GPU bundle the virtual display needs.",
+ target: .guestFile(path: "/System/Library/Extensions"),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "guest.vphoned",
+ title: "vphoned",
+ summary: "Installs the guest daemon the host talks to over VSOCK.",
+ target: .guestFile(path: "/usr/local/bin/vphoned"),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "guest.environment",
+ title: "Guest environment",
+ summary: "Installs the launchd environment and plists the guest tools read.",
+ target: .guestFile(path: "/Library/LaunchDaemons"),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "guest.build_version",
+ title: "Reported build version",
+ summary: """
+ Rewrites the guest's SystemVersion build string. Needs a build to write: the \
+ preset's BuildVersion parameter, or the SPOOF_BUILD environment variable. With \
+ neither, this patch has nothing to do even when it is on.
+ """,
+ target: .guestFile(path: "/System/Library/CoreServices/SystemVersion.plist"),
+ ),
+ ],
+ requires: ["vphone.kernel.base"],
+ provides: ["vphone.guest.system"],
+ )
+
+ /// The preset parameter `guest.build_version` reads.
+ public static let buildVersionParameter = "BuildVersion"
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelBasePatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelBasePatchSet.swift
new file mode 100644
index 00000000..6dd11337
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelBasePatchSet.swift
@@ -0,0 +1,167 @@
+// FirmwareKernelBasePatchSet.swift — Manifest for the base kernel patches.
+//
+// What every research VM needs to mount a patched, unsealed root filesystem and
+// run unsigned code from it. `KernelJailbreakPatcher` builds on this set, so the
+// jailbreak set requires the capability declared here.
+//
+// The Mach port guard patch is the one entry with a version gate. It is required
+// on an iOS 18 base, where runningboardd trips a flavor-10 guard and crash-loops
+// the UI, and it is off elsewhere — where disabling the guard only hides
+// violations a researcher may want to see.
+
+import Foundation
+import VPhonePatchKit
+
+public enum FirmwareKernelBasePatchSet {
+ public static let identifier = "com.vphone.patchset.kernel.base"
+
+ public static let manifest = VPhonePatchSetManifest(
+ identifier: identifier,
+ name: "Kernel Base",
+ summary: "APFS, code-signing policy and sandbox patches every research VM needs",
+ patches: [
+ // MARK: APFS
+
+ VPhonePatchDeclaration(
+ identifier: "kernel.apfs_root_snapshot",
+ title: "APFS root snapshot",
+ summary: "Boots the live root volume instead of its sealed snapshot.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "kernel.apfs_seal_broken",
+ title: "APFS broken seal",
+ summary: "Accepts a root volume whose seal the patches broke.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "apfs_graft",
+ title: "APFS graft",
+ summary: "Allows grafting so the cryptex payload mounts.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "kernel.apfs_vfsop_mount",
+ title: "APFS mount entry check",
+ summary: "Drops the vfsop_mount refusal for an unsealed volume.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "kernel.apfs_mount_upgrade_checks",
+ title: "APFS mount upgrade checks",
+ summary: "Lets a read-only root be remounted writable.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "kernel.handle_fsioc_graft",
+ title: "APFS graft ioctl",
+ summary: "Lets the graft ioctl succeed from the guest.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "kernel.handle_get_dev_by_role",
+ title: "APFS device-by-role gates",
+ summary: "Resolves volume roles for the patched container layout.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+
+ // MARK: Startup
+
+ VPhonePatchDeclaration(
+ identifier: "kernel.bsd_init_rootvp",
+ title: "bsd_init root vnode",
+ summary: "Keeps bsd_init going when the root vnode is the patched image.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+
+ // MARK: Code Signing
+
+ VPhonePatchDeclaration(
+ identifier: "kernel.post_validation",
+ title: "Post-validation checks",
+ summary: "Accepts signatures the patched trust cache vouches for.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "launch_constraints",
+ title: "Launch constraints",
+ summary: "Stops launch constraints refusing a relocated system binary.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "dyld_policy",
+ title: "dyld loading policy",
+ summary: "Lets dyld load a library from outside the sealed image.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "kernel.debugger",
+ title: "Debugger check",
+ summary: "Reports the kernel as debuggable so task_for_pid works.",
+ target: .firmware(.kernelcache),
+ ),
+
+ // MARK: Sandbox MACF Hooks
+
+ VPhonePatchDeclaration(
+ identifier: "kernel.sandbox.file_check_mmap",
+ title: "Sandbox: file_check_mmap",
+ summary: "Stubs the mmap sandbox check to allow.",
+ target: .firmware(.kernelcache),
+ ),
+ VPhonePatchDeclaration(
+ identifier: "kernel.sandbox.mount_check_mount",
+ title: "Sandbox: mount_check_mount",
+ summary: "Stubs the mount sandbox check to allow.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "kernel.sandbox.mount_check_remount",
+ title: "Sandbox: mount_check_remount",
+ summary: "Stubs the remount sandbox check to allow.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "kernel.sandbox.mount_check_umount",
+ title: "Sandbox: mount_check_umount",
+ summary: "Stubs the umount sandbox check to allow.",
+ target: .firmware(.kernelcache),
+ ),
+ VPhonePatchDeclaration(
+ identifier: "kernel.sandbox.vnode_check_rename",
+ title: "Sandbox: vnode_check_rename",
+ summary: "Stubs the rename sandbox check to allow.",
+ target: .firmware(.kernelcache),
+ ),
+
+ // MARK: Mach Port Guard
+
+ VPhonePatchDeclaration(
+ identifier: "kernel.thread_guard_violation",
+ title: "Mach port guard violation",
+ summary: """
+ Turns a fatal EXC_GUARD port violation into a continue. Required on an iOS 18 \
+ base, whose runningboardd and SpringBoard trip a flavor-10 guard and crash-loop \
+ the UI.
+ """,
+ target: .firmware(.kernelcache),
+ applicability: VPhonePatchApplicability(iOSBase: .major(18)),
+ bootEssential: true,
+ ),
+ ],
+ provides: ["vphone.kernel.base"],
+ )
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelFridaPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelFridaPatchSet.swift
new file mode 100644
index 00000000..7673e332
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelFridaPatchSet.swift
@@ -0,0 +1,43 @@
+// FirmwareKernelFridaPatchSet.swift — Manifest for the Frida Stalker relaxations.
+//
+// Two kernel checks stand between Frida's Stalker and a working trace: the
+// entitlement flag thread_set_state wants, and the immutability vm_map_delete
+// enforces over code pages. Neither is needed to boot, and both widen what any
+// process in the guest can do, so this set is opt-in — no preset that a VM gets
+// by default includes it.
+//
+// Gated to cloudOS 26.4 and newer, where these shapes were verified.
+
+import Foundation
+import VPhonePatchKit
+
+public enum FirmwareKernelFridaPatchSet {
+ public static let identifier = "com.vphone.patchset.kernel.frida"
+
+ private static let fridaCapable = VPhonePatchApplicability(cloudOS: .atLeast(major: 26, minor: 4))
+
+ public static let manifest = VPhonePatchSetManifest(
+ identifier: identifier,
+ name: "Frida Stalker",
+ summary: "Kernel relaxations Frida's Stalker needs to trace and rewrite code pages",
+ patches: [
+ VPhonePatchDeclaration(
+ identifier: "kernelcache_frida.thread_set_state_entitlement_flag",
+ title: "thread_set_state entitlement",
+ summary: "Drops the entitlement flag thread_set_state checks, so Stalker can set thread state.",
+ target: .firmware(.kernelcache),
+ applicability: fridaCapable,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "kernelcache_frida.vm_map_delete_immutable_code",
+ title: "Immutable code deletion",
+ summary: "Lets vm_map_delete remove an immutable code mapping, which Stalker rewrites over.",
+ target: .firmware(.kernelcache),
+ applicability: fridaCapable,
+ ),
+ ],
+ requires: ["vphone.kernel.jailbreak"],
+ provides: ["vphone.kernel.frida"],
+ after: ["vphone.kernel.jailbreak"],
+ )
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelHypervisorPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelHypervisorPatchSet.swift
new file mode 100644
index 00000000..1e20f923
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelHypervisorPatchSet.swift
@@ -0,0 +1,38 @@
+// FirmwareKernelHypervisorPatchSet.swift — Manifest for the hv_vmm rename.
+//
+// The guest runs under a hypervisor and the research kernel says so through an
+// `hv_vmm_present` sysctl. Renaming the OID and mangling its internal caller
+// hides that from the userland checks that would otherwise refuse to run, which
+// is what lets stock apps start at all.
+//
+// Its own set because it is the one kernel change that is about hiding the
+// hypervisor rather than about jailbreaking, and a preset studying VM detection
+// wants it off without giving up the rest.
+
+import Foundation
+import VPhonePatchKit
+
+public enum FirmwareKernelHypervisorPatchSet {
+ public static let identifier = "com.vphone.patchset.kernel.hypervisor"
+
+ public static let manifest = VPhonePatchSetManifest(
+ identifier: identifier,
+ name: "Hypervisor Concealment",
+ summary: "Renames the hv_vmm_present sysctl so userland does not see the hypervisor",
+ patches: [
+ VPhonePatchDeclaration(
+ identifier: "kernelcache_exp.hv_vmm",
+ title: "hv_vmm_present sysctl",
+ summary: """
+ Renames the hv_vmm_present OID and mangles its internal caller, so a userland \
+ check for the hypervisor finds nothing.
+ """,
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ ],
+ requires: ["vphone.kernel.base"],
+ provides: ["vphone.kernel.hypervisor"],
+ after: ["vphone.kernel.jailbreak"],
+ )
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelJailbreakPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelJailbreakPatchSet.swift
new file mode 100644
index 00000000..a2c97de8
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelJailbreakPatchSet.swift
@@ -0,0 +1,271 @@
+// FirmwareKernelJailbreakPatchSet.swift — Manifest for the jailbreak kernel patches.
+//
+// The patches that make the guest a jailbroken phone rather than a research VM
+// that boots: an admitted trust cache, a writable root, task ports, and the
+// syscall surface `vphoned` and the package manager need.
+//
+// Version gates here are structural, not preference. The iOS-27 entries target a
+// 27 userland — its DiskImages2 client ABI, its container-manager upcall, its
+// IOMFB swap sizes — and applying them under a 26.x userland would patch the
+// wrong shapes. They carry `iOSBase: .major(27)` so one preset covers every base.
+
+import Foundation
+import VPhonePatchKit
+
+public enum FirmwareKernelJailbreakPatchSet {
+ public static let identifier = "com.vphone.patchset.kernel.jailbreak"
+
+ /// Only applies to an iOS 27 userland.
+ private static let ios27 = VPhonePatchApplicability(iOSBase: .major(27))
+
+ public static let manifest = VPhonePatchSetManifest(
+ identifier: identifier,
+ name: "Kernel Jailbreak",
+ summary: "Trust cache admission, writable root, task ports and the jailbreak syscall surface",
+ patches: [
+ // MARK: Trust Cache and Code Signing
+
+ VPhonePatchDeclaration(
+ identifier: "amfi_trustcache",
+ title: "AMFI trust cache",
+ summary: "Admits the guest's own trust cache so unsigned binaries run.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "jb.post_validation",
+ title: "Jailbreak post-validation",
+ summary: "Completes the base post-validation patch for unsigned pages.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "jb.cred_label_update_execve",
+ title: "Credential label on execve",
+ summary: "Grants the platform label to every binary the guest executes.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "jb.hook_cred_label",
+ title: "Credential label hook",
+ summary: "Retargets the MACF credential hook to the patched handler.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "jb.amfi_execve",
+ title: "AMFI execve kill",
+ summary: "Stops AMFI killing a process whose signature it dislikes.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "jb.load_dylinker",
+ title: "Dynamic linker policy",
+ summary: "Lets a binary name a dynamic linker outside the sealed image.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+
+ // MARK: Task and Process
+
+ VPhonePatchDeclaration(
+ identifier: "task_conversion_eval",
+ title: "Task conversion evaluation",
+ summary: "Allows converting a task port the caller would not normally get.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "kernelcache_jb.task_for_pid",
+ title: "task_for_pid",
+ summary: "Lets task_for_pid return a port for any process.",
+ target: .firmware(.kernelcache),
+ ),
+ VPhonePatchDeclaration(
+ identifier: "jb.port_to_map",
+ title: "Port to map conversion",
+ summary: "Skips the panic when a port is converted to a vm_map.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "jb.proc_pidinfo",
+ title: "proc_pidinfo guards",
+ summary: "Lets proc_pidinfo report on processes the caller does not own.",
+ target: .firmware(.kernelcache),
+ ),
+ VPhonePatchDeclaration(
+ identifier: "jb.proc_security_policy",
+ title: "Process security policy",
+ summary: "Stubs the per-process security policy check to allow.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "kernelcache_jb.spawn_validate_persona",
+ title: "Spawn persona validation",
+ summary: "Lets a process spawn under a persona it did not inherit.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "kernelcache_jb.thid_should_crash",
+ title: "Thread identity crash",
+ summary: "Stops a thread-identity mismatch killing the process.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+
+ // MARK: Memory
+
+ VPhonePatchDeclaration(
+ identifier: "kernelcache_jb.vm_map_protect",
+ title: "vm_map_protect",
+ summary: "Allows making an executable mapping writable.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "kernelcache_jb.vm_fault_enter_prepare",
+ title: "vm_fault_enter_prepare",
+ summary: "Lets a fault install an unsigned executable page.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "kernelcache_jb.shared_region_map",
+ title: "Shared region mapping",
+ summary: "Lets the patched dyld shared cache be mapped.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+
+ // MARK: Filesystem
+
+ VPhonePatchDeclaration(
+ identifier: "jb.bsd_init_auth",
+ title: "bsd_init imageboot gate",
+ summary: "Skips the imageboot authentication branch during startup.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "jb.io_secure_bsd_root",
+ title: "Secure BSD root",
+ summary: "Reports the root device as not security-locked.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "kernelcache_jb.mac_mount",
+ title: "MACF mount flags",
+ summary: "Lets the guest mount writable over a sealed path.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "jb.dounmount",
+ title: "dounmount cleanup",
+ summary: "Skips the unmount cleanup call that would undo the bind mounts.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "kernelcache_jb.nvram_verify_permission",
+ title: "NVRAM permission check",
+ summary: "Lets the guest write the NVRAM variables the jailbreak reads.",
+ target: .firmware(.kernelcache),
+ ),
+
+ // MARK: Sandbox and IOUserClient
+
+ VPhonePatchDeclaration(
+ identifier: "sandbox_ext",
+ title: "Extended sandbox hooks",
+ summary: "Retargets the remaining vnode and mount sandbox hooks to an allow stub.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "iouc_macf_gate",
+ title: "IOUserClient MACF gate",
+ summary: "Lets the guest open user clients MACF would refuse.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "iouc_sandbox_gate",
+ title: "IOUserClient sandbox gate",
+ summary: "Lets a sandboxed process open a user client, as a 27 userland expects.",
+ target: .firmware(.kernelcache),
+ applicability: ios27,
+ bootEssential: true,
+ ),
+
+ // MARK: Syscall Surface
+
+ VPhonePatchDeclaration(
+ identifier: "jb.kcall10",
+ title: "Kernel call syscall",
+ summary: "Installs the syscall the jailbreak uses to call into the kernel.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "jb.syscallmask",
+ title: "Per-process syscall mask",
+ summary: "Widens the syscall mask a process inherits.",
+ target: .firmware(.kernelcache),
+ bootEssential: true,
+ ),
+
+ // MARK: iOS 27 Userland
+
+ VPhonePatchDeclaration(
+ identifier: "di2",
+ title: "DiskImages2 client ABI",
+ summary: "Matches the DiskImages2 client ABI a 27 userland calls with.",
+ target: .firmware(.kernelcache),
+ applicability: ios27,
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "exec_security_policy_kill",
+ title: "Exec security policy kill",
+ summary: "Stops the 27 exec security policy killing the process.",
+ target: .firmware(.kernelcache),
+ applicability: ios27,
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "container_manager_upcall_force_success",
+ title: "Container manager upcall",
+ summary: "Forces the container-manager upcall to succeed.",
+ target: .firmware(.kernelcache),
+ applicability: ios27,
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "iomfb_swapend",
+ title: "IOMFB swap-end sizes",
+ summary: "Accepts the 27 display driver's swap-end structure sizes.",
+ target: .firmware(.kernelcache),
+ applicability: ios27,
+ bootEssential: true,
+ ),
+ VPhonePatchDeclaration(
+ identifier: "jb.fpfs_scoped_open",
+ title: "FileProvider scoped open",
+ summary: "Scopes the vnode-open check to FileProvider so respring does not loop.",
+ target: .firmware(.kernelcache),
+ applicability: ios27,
+ bootEssential: true,
+ ),
+ ],
+ requires: ["vphone.kernel.base"],
+ provides: ["vphone.kernel.jailbreak"],
+ after: ["vphone.kernel.base"],
+ )
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
new file mode 100644
index 00000000..ef80f414
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
@@ -0,0 +1,79 @@
+// FirmwarePatchSetCatalog.swift — The patch sets built into the bundle.
+//
+// These are the sets a preset can name as `Bundled`. They are compiled in rather
+// than loaded, so `cfw install` running as root never has to open a file to learn
+// what the bundle's own patches are — an external `.vphonepatchset` is the only
+// thing that has to be imported and pinned first.
+
+import Foundation
+import VPhonePatchKit
+
+public enum FirmwarePatchSetCatalog {
+ /// Every bundled set, in the order the pipeline would run them.
+ public static let bundled: [VPhonePatchSetManifest] = [
+ FirmwareBootChainPatchSet.manifest,
+ FirmwareKernelBasePatchSet.manifest,
+ FirmwareKernelJailbreakPatchSet.manifest,
+ FirmwareKernelHypervisorPatchSet.manifest,
+ FirmwareKernelFridaPatchSet.manifest,
+ FirmwareDeviceTreePatchSet.manifest,
+ FirmwareGuestSystemPatchSet.manifest,
+ FirmwareGuestDisplayPatchSet.manifest,
+ FirmwareGuestIdentityPatchSet.manifest,
+ ]
+
+ /// Every bundled set, as a preset references them.
+ ///
+ /// Both shipped presets name all of them. A preset picks patches with its
+ /// selection, not by leaving a set out, so the editor always sees the whole
+ /// catalogue and can turn any patch on or off.
+ public static let bundledReferences: [VPhonePatchSetReference] =
+ bundled.map { .bundled($0.identifier) }
+
+ public static func manifest(identifier: String) -> VPhonePatchSetManifest? {
+ bundled.first { $0.identifier == identifier }
+ }
+
+ /// Every declared patch across every bundled set.
+ public static var allDeclarations: [VPhonePatchDeclaration] {
+ bundled.flatMap(\.patches)
+ }
+
+ // MARK: - Built-in Presets
+
+ /// Patches that are declared but off unless someone asks for them.
+ ///
+ /// The Frida relaxations widen what any process in the guest may do and
+ /// nothing needs them to boot, so `standard` leaves them off. They stay in the
+ /// catalogue, version-gated like everything else, and a VM can check them on.
+ public static let manualOnlyPatches: Set<String> = Set(
+ FirmwareKernelFridaPatchSet.manifest.patches.map(\.identifier),
+ )
+
+ /// The preset a VM gets when nothing else is named.
+ ///
+ /// The shipped `standard.plist` must match this; `FirmwarePatchSetTests`
+ /// checks that it does. This copy is what a dev build with no staged
+ /// `patches_presets` directory falls back to, so `fw patch` works straight out
+ /// of an Xcode build.
+ public static let standardPreset = VPhonePatchPreset(
+ identifier: VPhonePatchPreset.standardIdentifier,
+ title: "Standard",
+ summary: "The patches every vphone VM needs to boot, jailbroken, with a working display and camera.",
+ patchSets: bundledReferences,
+ selection: .block(manualOnlyPatches),
+ )
+
+ /// Everything the bundle declares, including the Frida relaxations. Each
+ /// patch's own version gate still decides whether it lands.
+ public static let extendedPreset = VPhonePatchPreset(
+ identifier: "extended",
+ title: "Extended",
+ summary: "Every patch this bundle declares, including the Frida Stalker relaxations.",
+ patchSets: bundledReferences,
+ selection: .all,
+ )
+
+ /// The presets the bundle ships.
+ public static let builtInPresets: [VPhonePatchPreset] = [standardPreset, extendedPreset]
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift
index fc6ca70b..1e4f6f4f 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift
@@ -17,6 +17,7 @@
import Darwin
import Foundation
+import VPhonePatchKit
/// Orchestrates firmware patching for all boot-chain components.
///
@@ -73,7 +74,22 @@ public final class FirmwarePipeline {
/// Glob patterns used to locate the file (tried in order).
let searchPatterns: [String]
/// Factories that create patchers to run in sequence for the loaded data.
- let patcherFactories: [(Data, Bool) -> any Patcher]
+ ///
+ /// Throwing, because a loaded `.vphonepatchset` builds its patcher here: a
+ /// set that declares a patch for this component but builds no patcher for
+ /// it has to say so rather than leave the component untouched.
+ let patcherFactories: [(Data, Bool) throws -> any Patcher]
+
+ /// The same descriptor with more patchers appended after the existing ones.
+ func appending(_ factories: [(Data, Bool) throws -> any Patcher]) -> ComponentDescriptor {
+ guard !factories.isEmpty else { return self }
+ return ComponentDescriptor(
+ name: name,
+ inRestoreDir: inRestoreDir,
+ searchPatterns: searchPatterns,
+ patcherFactories: patcherFactories + factories,
+ )
+ }
}
// MARK: - Properties
@@ -82,10 +98,33 @@ public final class FirmwarePipeline {
let variant: Variant
let verbose: Bool
let noBinpack: Bool
- let forceExcGuard: Bool
- let enableFrida: Bool
let loader: any FirmwareLoader
+ /// The preset to resolve, or nil to apply every patch the variant's patchers
+ /// find. Nil is what the tests use, and what keeps a directly built pipeline
+ /// behaving as it did before presets existed.
+ let preset: VPhonePatchPreset?
+ /// The manifests `preset` resolves against.
+ let patchSets: [VPhonePatchSetManifest]
+ /// Per-VM patches to turn off on top of the preset.
+ let blockedPatches: Set<String>
+ /// Per-VM patches to turn on that the preset leaves off.
+ let allowedPatches: Set<String>
+
+ /// The `.vphonepatchset` bundles `resolvePlan` opened for this run. Empty for a
+ /// preset that names only bundled sets, which is every shipped preset.
+ let loadedPatchSets = FirmwareExternalPatchSets()
+
+ /// The plan `patchAll()` resolved, once the OS versions were known. Nil until
+ /// then, and nil for the whole run when no preset was given.
+ public private(set) var resolvedPlan: VPhonePatchPlan?
+
+ /// The iPhone base `ProductVersion` `patchAll()` read, if it found one.
+ public private(set) var baseProductVersion: VPhoneVersion?
+
+ /// The cloudOS `ProductVersion` `patchAll()` read, if it found one.
+ public private(set) var cloudOSProductVersion: VPhoneVersion?
+
// MARK: - Init
public init(
@@ -93,16 +132,20 @@ public final class FirmwarePipeline {
variant: Variant = .regular,
verbose: Bool = true,
noBinpack: Bool = false,
- forceExcGuard: Bool = false,
- enableFrida: Bool = false,
+ preset: VPhonePatchPreset? = nil,
+ patchSets: [VPhonePatchSetManifest] = FirmwarePatchSetCatalog.bundled,
+ blockedPatches: Set<String> = [],
+ allowedPatches: Set<String> = [],
loader: (any FirmwareLoader)? = nil,
) {
self.vmDirectory = vmDirectory
self.variant = variant
self.verbose = verbose
self.noBinpack = noBinpack
- self.forceExcGuard = forceExcGuard
- self.enableFrida = enableFrida
+ self.preset = preset
+ self.patchSets = patchSets
+ self.blockedPatches = blockedPatches
+ self.allowedPatches = allowedPatches
self.loader = loader ?? ContainerFirmwareLoader()
}
@@ -121,29 +164,29 @@ public final class FirmwarePipeline {
// Detect the iPhone base iOS version (from the pre-hybrid manifest that
// fw_prepare preserves — the live BuildManifest.plist reads the cloudOS
// version, not the base). iOS 18 bases need the skywalk-netagent boot-arg.
- let baseVersion = Self.readBaseProductVersion(restoreDir)
- let iosBaseIs18 = baseVersion?.hasPrefix("18.") ?? false
- let iosBaseIs27 = baseVersion?.hasPrefix("27.") ?? false
- let baseGateNote = iosBaseIs18 ? " (enabling iOS-18 netagent boot-arg)"
- : iosBaseIs27 ? " (enabling iOS-27 JB kernel patches)" : ""
- log("[*] iPhone base iOS: \(baseVersion ?? "unknown")\(baseGateNote)")
+ let baseVersion = VPhoneVersion(Self.readBaseProductVersion(restoreDir))
+ baseProductVersion = baseVersion
+ log("[*] iPhone base iOS: \(baseVersion?.description ?? "unknown")")
// Frida Stalker kernel patches only apply on cloudOS 26.4+ (where the shapes
// were validated); older kernels are left untouched. The Frida deb install is
// separate and version-independent.
- let cloudOSVersion = Self.readCloudOSProductVersion(restoreDir)
- let cloudOSIsFridaCapable = Self.productVersionAtLeast(cloudOSVersion, 26, 4)
- if enableFrida {
- log("[*] cloudOS kernel: \(cloudOSVersion ?? "unknown")"
- + (cloudOSIsFridaCapable ? " (Frida kernel patches enabled)"
- : " (< 26.4 — Frida kernel patches skipped)"))
- }
+ let cloudOSVersion = VPhoneVersion(Self.readCloudOSProductVersion(restoreDir))
+ cloudOSProductVersion = cloudOSVersion
+ log("[*] cloudOS kernel: \(cloudOSVersion?.description ?? "unknown")")
+
+ // The preset resolves here rather than in init: its version gates need the
+ // two ProductVersions that were just read, and a conflict or a misnamed
+ // patch must stop the run before a single byte is written.
+ let plan = try resolvePlan(iOSBase: baseVersion, cloudOS: cloudOSVersion)
+ resolvedPlan = plan
+ let gate = plan.map { VPhonePatchGate(plan: $0) } ?? .unrestricted
let components = buildComponentList(
restoreDir: restoreDir,
- iosBaseIs18: iosBaseIs18,
- iosBaseIs27: iosBaseIs27,
- cloudOSIsFridaCapable: cloudOSIsFridaCapable,
+ iOSBase: baseVersion,
+ plan: plan,
+ gate: gate,
)
log("[*] Patching \(components.count) boot-chain components ...")
@@ -169,10 +212,18 @@ public final class FirmwarePipeline {
rawData,
componentName: component.name,
patcherFactories: component.patcherFactories,
+ expectsPatches: expectsPatches(for: component.name, plan: plan),
)
- try loader.save(currentData, to: fileURL)
- log(" [+] saved")
+ // A component whose every patch the preset turned off is left exactly
+ // as it was found. Re-sealing an unmodified payload would rewrite a
+ // signed image for no reason.
+ if componentRecords.isEmpty {
+ log(" [=] unchanged, not rewritten")
+ } else {
+ try loader.save(currentData, to: fileURL)
+ log(" [+] saved")
+ }
allRecords.append(contentsOf: componentRecords)
}
@@ -187,17 +238,25 @@ public final class FirmwarePipeline {
func patchData(
_ rawData: Data,
componentName: String,
- patcherFactories: [(Data, Bool) -> any Patcher],
+ patcherFactories: [(Data, Bool) throws -> any Patcher],
+ expectsPatches: Bool = true,
) throws -> (Data, [PatchRecord]) {
var currentData = rawData
var componentRecords: [PatchRecord] = []
for makePatcher in patcherFactories {
- let patcher = makePatcher(currentData, verbose)
+ let patcher = try makePatcher(currentData, verbose)
let records = try patcher.findAll()
guard !records.isEmpty else {
- throw PatcherError.patchSiteNotFound("\(componentName): no patches found")
+ // A patcher that found nothing is a failure — unless the preset
+ // turned this component's patches off, in which case finding
+ // nothing is the whole point.
+ guard !expectsPatches else {
+ throw PatcherError.patchSiteNotFound("\(componentName): no patches found")
+ }
+ log(" [=] \(componentName): every patch is off in this preset")
+ continue
}
let count = try patcher.apply()
@@ -210,41 +269,83 @@ public final class FirmwarePipeline {
return (currentData, componentRecords)
}
- // MARK: - Data Extraction
+ // MARK: - Preset Resolution
- /// Extract the patched data from a patcher's internal buffer.
+ /// Resolve the preset against the versions just read, and report what it did.
///
- /// All current patchers own a ``BinaryBuffer`` whose `.data` property
- /// holds the mutated bytes after `apply()`. We use protocol-based
- /// access where possible and fall back to manual patch application.
- func extractPatchedData(from patcher: any Patcher, fallback: Data, records: [PatchRecord]) -> Data {
- // Try known patcher types that expose their buffer.
- if let avp = patcher as? AVPBooterPatcher {
- return avp.buffer.data
- }
- if let iboot = patcher as? IBootPatcher {
- return iboot.buffer.data
- }
- if let txm = patcher as? TXMPatcher {
- return txm.buffer.data
- }
- if let kp = patcher as? KernelPatcher {
- return kp.buffer.data
- }
- if let kjb = patcher as? KernelJailbreakPatcher {
- return kjb.buffer.data
+ /// Returns nil when no preset was given, which leaves every patcher
+ /// unrestricted.
+ ///
+ /// Every `.vphonepatchset` the preset names is opened here, before the plan is
+ /// resolved and so before a byte is written. Opening one means reading and
+ /// checking its manifest, then mapping its executable — in that order, so a set
+ /// that conflicts with another or needs a newer PatchKit is refused without its
+ /// code ever running.
+ ///
+ /// Internal rather than private so the tests can resolve a preset naming an
+ /// external set without a restore tree to patch.
+ func resolvePlan(iOSBase: VPhoneVersion?, cloudOS: VPhoneVersion?) throws -> VPhonePatchPlan? {
+ guard let preset else { return nil }
+
+ var available = patchSets
+ for reference in preset.patchSets {
+ guard case let .external(identifier, path) = reference else { continue }
+ let set = try VPhonePatchSetBundle.inspect(at: URL(fileURLWithPath: path))
+ try set.validate(expecting: identifier)
+ try loadedPatchSets.add(set)
+ available.append(set.manifest)
+ log("[*] External set: \(set.manifest.identifier) \(set.manifest.version)"
+ + " (\(set.manifest.patches.count) patches) from \(set.url.path)")
}
- if let kexp = patcher as? KernelExperimentalPatcher {
- return kexp.buffer.data
+
+ let plan = try VPhonePatchPlan.resolve(
+ preset: preset,
+ patchSets: available,
+ iOSBase: iOSBase,
+ cloudOS: cloudOS,
+ blocked: blockedPatches,
+ allowed: allowedPatches,
+ )
+
+ log("[*] Patch preset: \(preset.identifier)"
+ + " (\(plan.patchSets.count) sets, \(plan.enabled.count) patches on)")
+ if !plan.skippedByVersion.isEmpty {
+ log("[*] Not applicable: \(plan.skippedByVersion.count) patches for other OS versions")
}
- if let dt = patcher as? DeviceTreePatcher {
- return dt.patchedData
+ let blocked: [String] = plan.declarations
+ .filter { !plan.enabled.contains($0.identifier) && !plan.skippedByVersion.contains($0.identifier) }
+ .map(\.identifier)
+ .sorted()
+ if !blocked.isEmpty {
+ log("[*] Turned off: \(blocked.joined(separator: ", "))")
}
- if let fs = patcher as? CryptexFilesystemPatcher {
- return fs.patchedData
+ if !plan.droppedBootEssentials.isEmpty {
+ // Allowed — an external set may be replacing them — but never quiet.
+ log("[!] Boot-essential patches are off: "
+ + plan.droppedBootEssentials.joined(separator: ", "))
}
- if let mh = patcher as? ManifestHashPatcher {
- return mh.patchedData
+ return plan
+ }
+
+ /// Whether `componentName` should still produce at least one patch record.
+ private func expectsPatches(for componentName: String, plan: VPhonePatchPlan?) -> Bool {
+ guard let plan else { return true }
+ guard let component = VPhoneFirmwareComponent(rawValue: componentName) else { return true }
+ return plan.hasEnabledPatches(target: .firmware(component))
+ }
+
+ // MARK: - Data Extraction
+
+ /// Extract the patched data from a patcher's internal buffer.
+ ///
+ /// Every patcher in this project conforms to ``BufferedPatcher`` and hands its
+ /// bytes back through it. Asking through the protocol rather than downcasting
+ /// to each known type is also the only way a patcher from a loaded
+ /// `.vphonepatchset` can contribute anything: the pipeline has never heard of
+ /// its type, and bytes it could not read would be silently dropped.
+ func extractPatchedData(from patcher: any Patcher, fallback: Data, records: [PatchRecord]) -> Data {
+ if let buffered = patcher as? any BufferedPatcher {
+ return buffered.patchedData
}
// Fallback: apply records manually to a copy of the original data.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
index 18bc2b19..51d0ba19 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
@@ -7,6 +7,7 @@
// Split out of FirmwarePipeline.swift; the execution loop stays there.
import Foundation
+import VPhonePatchKit
extension FirmwarePipeline {
// MARK: - Component List Builder
@@ -16,47 +17,70 @@ extension FirmwarePipeline {
/// - 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 (`KernelJailbreakPatcher.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.
+ /// - iOSBase: The iPhone base `ProductVersion` read from `iPhone-BuildManifest.plist`,
+ /// or nil when it could not be read. Two patchers still branch on the release
+ /// itself rather than on a patch being selected: the skywalk-netagent boot-arg is
+ /// 18.x-only, and `KernelJailbreakPatcher.applyIOS27` changes the shapes a patch
+ /// method looks for rather than whether it runs.
+ /// - plan: The resolved preset, or nil when there is none. A patcher whose whole
+ /// patch set the preset left out is not built at all: its records would be
+ /// declared by nothing, and an undeclared record applies rather than being
+ /// dropped (see ``VPhonePatchGate``), so leaving the set out has to mean
+ /// leaving the patcher out.
+ /// - gate: Handed to each patcher built below, so a blocked patch is never written.
func buildComponentList(
restoreDir: URL,
- iosBaseIs18: Bool,
- iosBaseIs27: Bool,
- cloudOSIsFridaCapable: Bool,
+ iOSBase: VPhoneVersion?,
+ plan: VPhonePatchPlan? = nil,
+ gate: VPhonePatchGate = .unrestricted,
) -> [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
+ /// Whether the plan kept a bundled set. True when there is no plan, so a
+ /// directly built pipeline runs every patcher its variant names.
+ func includesSet(_ identifier: String) -> Bool {
+ plan?.includesPatchSet(identifier) ?? true
+ }
- // 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
+ let includeBootChain = includesSet(FirmwareBootChainPatchSet.identifier)
+ let includeKernelBase = includesSet(FirmwareKernelBasePatchSet.identifier)
+ let includeKernelJailbreak = includesSet(FirmwareKernelJailbreakPatchSet.identifier)
+ let includeHypervisor = includesSet(FirmwareKernelHypervisorPatchSet.identifier)
+ let includeDeviceTree = includesSet(FirmwareDeviceTreePatchSet.identifier)
- // Opt-in Frida Stalker kernel relaxations (--frida), gated to cloudOS 26.4+.
- let applyFrida = enableFrida && cloudOSIsFridaCapable
+ /// Whether the plan turned a patch on. Without a plan, fall back to the
+ /// release the patch is pinned to, which is the same answer the standard
+ /// preset gives.
+ func isEnabled(_ identifier: String, fallback: Bool) -> Bool {
+ plan?.isEnabled(identifier) ?? fallback
+ }
+
+ let baseIs18 = iOSBase?.major == 18
+ let baseIs27 = iOSBase?.major == 27
+
+ // The Mach port guard disable. Pinned to iOS 18, whose runningboardd and
+ // SpringBoard trip GUARD_TYPE_MACH_PORT flavor 10 and crash-loop the UI —
+ // the VM does not boot there without it. On 26.x and 27.x it only hides
+ // violations, so it is off unless a VM checks it on.
+ let applyExcGuard = isEnabled("kernel.thread_guard_violation", fallback: baseIs18)
+
+ // Not a selection: `applyIOS27` changes which shapes the JB patch methods
+ // look for, and which sandbox hook is left real for the fpfs trampoline.
+ // It follows the base release, and the gate decides separately whether each
+ // of those patches is written.
+ let applyIOS27 = baseIs27
+
+ // Frida Stalker relaxations, off unless the VM asked for them. Their own
+ // cloudOS 26.4+ gate decides whether they then land.
+ let applyFrida = FirmwareKernelFridaPatchSet.manifest.patches.contains {
+ isEnabled($0.identifier, fallback: false)
+ }
// 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" : ""
+ let extraBootArgs = baseIs18 ? "if_attach_nx=0x3" : ""
// 1. AVPBooter — always present, lives in VM root.
// Patched for every non-less variant (regular/dev/jb/exp).
@@ -65,10 +89,12 @@ extension FirmwarePipeline {
inRestoreDir: false,
searchPatterns: ["AVPBooter*.bin"],
patcherFactories: {
- if variant != .less {
+ if variant != .less, includeBootChain {
return [
{ data, verbose in
- AVPBooterPatcher(data: data, verbose: verbose)
+ let p = AVPBooterPatcher(data: data, verbose: verbose)
+ p.gate = gate
+ return p
},
]
}
@@ -86,18 +112,24 @@ extension FirmwarePipeline {
case .less:
[]
case .regular, .dev:
- [{ data, verbose in
- IBootPatcher(data: data, mode: .ibss, verbose: verbose)
- }]
+ includeBootChain ? [{ data, verbose in
+ let p = IBootPatcher(data: data, mode: .ibss, verbose: verbose)
+ p.gate = gate
+ return p
+ }] : []
case .jb, .exp:
- [
+ includeBootChain ? [
{ data, verbose in
- IBootPatcher(data: data, mode: .ibss, verbose: verbose)
+ let p = IBootPatcher(data: data, mode: .ibss, verbose: verbose)
+ p.gate = gate
+ return p
},
{ data, verbose in
- IBootJailbreakPatcher(data: data, mode: .ibss, verbose: verbose)
+ let p = IBootJailbreakPatcher(data: data, mode: .ibss, verbose: verbose)
+ p.gate = gate
+ return p
},
- ]
+ ] : []
}
}(),
))
@@ -107,11 +139,12 @@ extension FirmwarePipeline {
name: "iBEC",
inRestoreDir: true,
searchPatterns: ["Firmware/dfu/iBEC.vresearch101.RELEASE.im4p"],
- patcherFactories: [{ data, verbose in
+ patcherFactories: includeBootChain ? [{ data, verbose in
let p = IBootPatcher(data: data, mode: .ibec, verbose: verbose)
p.extraBootArgs = extraBootArgs
+ p.gate = gate
return p
- }],
+ }] : [],
))
// 4. LLB - Not required by the less variant, still added for the serial logs.
@@ -119,11 +152,12 @@ extension FirmwarePipeline {
name: "LLB",
inRestoreDir: true,
searchPatterns: ["Firmware/all_flash/LLB.vresearch101.RELEASE.im4p"],
- patcherFactories: [{ data, verbose in
+ patcherFactories: includeBootChain ? [{ data, verbose in
let p = IBootPatcher(data: data, mode: .llb, verbose: verbose)
p.extraBootArgs = extraBootArgs
+ p.gate = gate
return p
- }],
+ }] : [],
))
// 5. TXM — dev/jb/exp variants use TXMDevPatcher (adds entitlements, debugger, dev-mode)
@@ -136,13 +170,17 @@ extension FirmwarePipeline {
case .less:
[]
case .regular:
- [{ data, verbose in
- TXMPatcher(data: data, verbose: verbose)
- }]
+ includeBootChain ? [{ data, verbose in
+ let p = TXMPatcher(data: data, verbose: verbose)
+ p.gate = gate
+ return p
+ }] : []
case .dev, .jb, .exp:
- [{ data, verbose in
- TXMDevPatcher(data: data, verbose: verbose)
- }]
+ includeBootChain ? [{ data, verbose in
+ let p = TXMDevPatcher(data: data, verbose: verbose)
+ p.gate = gate
+ return p
+ }] : []
}
}(),
))
@@ -158,43 +196,32 @@ extension FirmwarePipeline {
case .less:
[]
case .regular:
- [{ data, verbose in
- KernelPatcher(data: data, verbose: verbose, isDev: false, applyExcGuard: applyExcGuard)
- }]
+ includeKernelBase ? [{ data, verbose in
+ let p = KernelPatcher(
+ data: data,
+ verbose: verbose,
+ isDev: false,
+ applyExcGuard: applyExcGuard,
+ )
+ p.gate = gate
+ return p
+ }] : []
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 = KernelJailbreakPatcher(data: data, verbose: verbose)
- p.applyIOS27 = applyIOS27
- p.applyFrida = applyFrida
- return p
- },
- { data, verbose in
- KernelExperimentalPatcher(data: data, verbose: verbose)
- },
- ]
- case .exp:
- [
- { data, verbose in
- KernelPatcher(data: data, verbose: verbose, isDev: false, applyExcGuard: applyExcGuard)
- },
- { data, verbose in
- let p = KernelJailbreakPatcher(data: data, verbose: verbose)
- p.applyIOS27 = applyIOS27
- p.applyFrida = applyFrida
- return p
- },
- { data, verbose in
- KernelExperimentalPatcher(data: data, verbose: verbose)
- },
- ]
+ includeKernelBase ? [{ data, verbose in
+ let p = KernelPatcher(data: data, verbose: verbose, isDev: true)
+ p.gate = gate
+ return p
+ }] : []
+ case .jb, .exp:
+ kernelJailbreakFactories(
+ applyExcGuard: applyExcGuard,
+ applyIOS27: applyIOS27,
+ applyFrida: applyFrida,
+ includeBase: includeKernelBase,
+ includeJailbreak: includeKernelJailbreak,
+ includeHypervisor: includeHypervisor,
+ gate: gate,
+ )
}
}(),
))
@@ -206,13 +233,15 @@ extension FirmwarePipeline {
name: "DeviceTree",
inRestoreDir: true,
searchPatterns: ["Firmware/all_flash/DeviceTree.vphone600ap.im4p"],
- patcherFactories: [{ data, verbose in
- DeviceTreePatcher(
+ patcherFactories: includeDeviceTree ? [{ data, verbose in
+ let p = DeviceTreePatcher(
data: data,
verbose: verbose,
includeIdentityPatches: dtIncludeIdentity,
)
- }],
+ p.gate = gate
+ return p
+ }] : [],
))
// 8. Filesystem
@@ -254,6 +283,79 @@ extension FirmwarePipeline {
}(),
))
- return components
+ return appendingExternalPatchers(to: components, plan: plan, gate: gate, iOSBase: iOSBase)
+ }
+
+ // MARK: - External Patch Sets
+
+ /// Give every loaded `.vphonepatchset` its turn on each component.
+ ///
+ /// A no-op unless the preset named an external set, which no shipped preset
+ /// does. The manifest decides which components a set is asked about, so this
+ /// never invents work for a set whose patches are off.
+ private func appendingExternalPatchers(
+ to components: [ComponentDescriptor],
+ plan: VPhonePatchPlan?,
+ gate: VPhonePatchGate,
+ iOSBase: VPhoneVersion?,
+ ) -> [ComponentDescriptor] {
+ guard let plan, !loadedPatchSets.isEmpty else { return components }
+ let context = VPhonePatchSetContext(
+ iOSBase: iOSBase,
+ cloudOS: cloudOSProductVersion,
+ gate: gate,
+ parameters: plan.parameters,
+ verbose: verbose,
+ )
+ return components.map { descriptor in
+ guard let component = VPhoneFirmwareComponent(rawValue: descriptor.name) else {
+ return descriptor
+ }
+ return descriptor.appending(
+ loadedPatchSets.factories(for: component, plan: plan, context: context),
+ )
+ }
+ }
+
+ // MARK: - Kernel Factories
+
+ /// The kernelcache patcher chain the JB and EXP variants share.
+ ///
+ /// Each patcher corresponds to one bundled patch set, and a set the preset
+ /// left out drops its patcher rather than being filtered afterwards.
+ private func kernelJailbreakFactories(
+ applyExcGuard: Bool,
+ applyIOS27: Bool,
+ applyFrida: Bool,
+ includeBase: Bool,
+ includeJailbreak: Bool,
+ includeHypervisor: Bool,
+ gate: VPhonePatchGate,
+ ) -> [(Data, Bool) throws -> any Patcher] {
+ var factories: [(Data, Bool) throws -> any Patcher] = []
+ if includeBase {
+ factories.append { data, verbose in
+ let p = KernelPatcher(data: data, verbose: verbose, isDev: false, applyExcGuard: applyExcGuard)
+ p.gate = gate
+ return p
+ }
+ }
+ if includeJailbreak {
+ factories.append { data, verbose in
+ let p = KernelJailbreakPatcher(data: data, verbose: verbose)
+ p.applyIOS27 = applyIOS27
+ p.applyFrida = applyFrida
+ p.gate = gate
+ return p
+ }
+ }
+ if includeHypervisor {
+ factories.append { data, verbose in
+ let p = KernelExperimentalPatcher(data: data, verbose: verbose)
+ p.gate = gate
+ return p
+ }
+ }
+ return factories
}
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift
index 155c10bf..533c0503 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift
@@ -11,6 +11,7 @@
import Darwin
import Foundation
+import VPhonePatchKit
extension FirmwarePipeline {
// MARK: - File Discovery
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/TXM/TXMDevPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/TXM/TXMDevPatcher.swift
index b8e4025f..0d4d2d52 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/TXM/TXMDevPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/TXM/TXMDevPatcher.swift
@@ -3,6 +3,7 @@
// Historical note: derived from the legacy Python firmware patcher during the Swift migration.
import Foundation
+import VPhonePatchKit
/// Dev-variant patcher for TXM images.
///
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/TXM/TXMPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/TXM/TXMPatcher.swift
index 1b598b8e..30b93172 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/TXM/TXMPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/TXM/TXMPatcher.swift
@@ -3,8 +3,8 @@
// Implements the trustcache bypass patch.
// Historical note: derived from the legacy Python firmware patcher during the Swift migration.
-import Capstone
import Foundation
+import VPhonePatchKit
/// Patcher for TXM trustcache bypass.
///
@@ -12,10 +12,13 @@ import Foundation
/// 1. Trustcache binary-search BL → mov x0, #0
/// (in the AMFI cert verification function identified by the
/// unique constant 0x2446 loaded into w19)
-public class TXMPatcher: Patcher {
+public class TXMPatcher: BufferedPatcher {
public let component = "txm"
public let verbose: Bool
+ /// Which patches the resolved preset turned on. Unrestricted by default.
+ public var gate: VPhonePatchGate = .unrestricted
+
let buffer: BinaryBuffer
let disasm = ARM64Disassembler()
var patches: [PatchRecord] = []
@@ -52,6 +55,8 @@ public class TXMPatcher: Patcher {
// MARK: - Emit
func emit(_ offset: Int, _ patchBytes: Data, patchID: String, description: String) {
+ guard gateAllows(patchID) else { return }
+
let originalBytes = buffer.readBytes(at: offset, count: patchBytes.count)
let beforeInsn = disasm.disassembleOne(in: buffer.original, at: offset)
@@ -145,11 +150,11 @@ extension TXMPatcher {
let i4 = insns[i + 4]
let i5 = insns[i + 5]
- guard isLdrRegFromBaseImm(i0, dest: AARCH64_REG_X1, base: AARCH64_REG_X20, disp: 0x38) else { continue }
- guard isAddImmediate(i1, dest: AARCH64_REG_X2, base: AARCH64_REG_SP, imm: 4) else { continue }
+ guard isLdrRegFromBaseImm(i0, dest: .x(1), base: .x(20), disp: 0x38) else { continue }
+ guard isAddImmediate(i1, dest: .x(2), base: .sp, imm: 4) else { continue }
guard isBLOrPatchedMovX0Zero(i2) else { continue }
guard isLdpX0X1FromX20_0x30(i3) else { continue }
- guard isAddImmediate(i4, dest: AARCH64_REG_X2, base: AARCH64_REG_SP, imm: 8) else { continue }
+ guard isAddImmediate(i4, dest: .x(2), base: .sp, imm: 8) else { continue }
guard i5.mnemonic == "bl" else { continue }
matches.append(Int(i2.address))
@@ -181,7 +186,7 @@ extension TXMPatcher {
let i2 = insns[i + 2]
let i3 = insns[i + 3]
- guard isMovImm(i0, dest: AARCH64_REG_W2, imm: 0x14) else { continue }
+ guard isMovImm(i0, dest: .w(2), imm: 0x14) else { continue }
guard isBLOrPatchedMovX0Zero(i1) else { continue }
guard isCBZW0(i2) else { continue }
guard isTBZFamilyBit31(i3) else { continue }
@@ -212,64 +217,64 @@ extension TXMPatcher {
return nil
}
- private func isMovImm(_ insn: Instruction, dest: aarch64_reg, imm: Int64) -> Bool {
+ private func isMovImm(_ insn: ARM64Instruction, dest: ARM64Register, imm: Int64) -> Bool {
guard insn.mnemonic == "mov",
- let ops = insn.aarch64?.operands, ops.count == 2,
- ops[0].type == AARCH64_OP_REG, ops[0].reg == dest,
- ops[1].type == AARCH64_OP_IMM, ops[1].imm == imm
+ let ops = insn.detail?.operands, ops.count == 2,
+ ops[0].type == .register, ops[0].reg == dest,
+ ops[1].type == .immediate, ops[1].imm == imm
else { return false }
return true
}
- private func isAddImmediate(_ insn: Instruction, dest: aarch64_reg, base: aarch64_reg, imm: Int64) -> Bool {
+ private func isAddImmediate(_ insn: ARM64Instruction, dest: ARM64Register, base: ARM64Register, imm: Int64) -> Bool {
guard insn.mnemonic == "add",
- let ops = insn.aarch64?.operands, ops.count == 3,
- ops[0].type == AARCH64_OP_REG, ops[0].reg == dest,
- ops[1].type == AARCH64_OP_REG, ops[1].reg == base,
- ops[2].type == AARCH64_OP_IMM, ops[2].imm == imm
+ let ops = insn.detail?.operands, ops.count == 3,
+ ops[0].type == .register, ops[0].reg == dest,
+ ops[1].type == .register, ops[1].reg == base,
+ ops[2].type == .immediate, ops[2].imm == imm
else { return false }
return true
}
- private func isLdrRegFromBaseImm(_ insn: Instruction, dest: aarch64_reg, base: aarch64_reg, disp: Int32) -> Bool {
+ private func isLdrRegFromBaseImm(_ insn: ARM64Instruction, dest: ARM64Register, base: ARM64Register, disp: Int32) -> Bool {
guard insn.mnemonic == "ldr",
- let ops = insn.aarch64?.operands, ops.count >= 2,
- ops[0].type == AARCH64_OP_REG, ops[0].reg == dest,
- ops[1].type == AARCH64_OP_MEM,
+ let ops = insn.detail?.operands, ops.count >= 2,
+ ops[0].type == .register, ops[0].reg == dest,
+ ops[1].type == .memory,
ops[1].mem.base == base,
ops[1].mem.disp == disp
else { return false }
return true
}
- private func isLdpX0X1FromX20_0x30(_ insn: Instruction) -> Bool {
+ private func isLdpX0X1FromX20_0x30(_ insn: ARM64Instruction) -> Bool {
guard insn.mnemonic == "ldp",
- let ops = insn.aarch64?.operands, ops.count >= 3,
- ops[0].type == AARCH64_OP_REG, ops[0].reg == AARCH64_REG_X0,
- ops[1].type == AARCH64_OP_REG, ops[1].reg == AARCH64_REG_X1,
- ops[2].type == AARCH64_OP_MEM,
- ops[2].mem.base == AARCH64_REG_X20,
+ let ops = insn.detail?.operands, ops.count >= 3,
+ ops[0].type == .register, ops[0].reg == .x(0),
+ ops[1].type == .register, ops[1].reg == .x(1),
+ ops[2].type == .memory,
+ ops[2].mem.base == .x(20),
ops[2].mem.disp == 0x30
else { return false }
return true
}
- private func isBLOrPatchedMovX0Zero(_ insn: Instruction) -> Bool {
+ private func isBLOrPatchedMovX0Zero(_ insn: ARM64Instruction) -> Bool {
insn.mnemonic == "bl" || buffer.readU32(at: Int(insn.address)) == ARM64.movX0_0_U32
}
- private func isCBZW0(_ insn: Instruction) -> Bool {
+ private func isCBZW0(_ insn: ARM64Instruction) -> Bool {
guard insn.mnemonic == "cbz",
- let ops = insn.aarch64?.operands, ops.count == 2,
- ops[0].type == AARCH64_OP_REG, ops[0].reg == AARCH64_REG_W0
+ let ops = insn.detail?.operands, ops.count == 2,
+ ops[0].type == .register, ops[0].reg == .w(0)
else { return false }
return true
}
- private func isTBZFamilyBit31(_ insn: Instruction) -> Bool {
+ private func isTBZFamilyBit31(_ insn: ARM64Instruction) -> Bool {
guard insn.mnemonic == "tbnz" || insn.mnemonic == "tbz",
- let ops = insn.aarch64?.operands, ops.count == 3,
- ops[1].type == AARCH64_OP_IMM, ops[1].imm == 0x1F
+ let ops = insn.detail?.operands, ops.count == 3,
+ ops[1].type == .immediate, ops[1].imm == 0x1F
else { return false }
return true
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift
index 2414905e..c4cf6c23 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift
@@ -21,6 +21,7 @@
@testable import FirmwarePatcher
import Foundation
import Testing
+import VPhonePatchKit
// MARK: - Case Model
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/FirmwarePatcherTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/FirmwarePatcherTests.swift
index ddbb5b60..f4e79970 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/FirmwarePatcherTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/FirmwarePatcherTests.swift
@@ -3,6 +3,7 @@
@testable import FirmwarePatcher
import Foundation
import Testing
+import VPhonePatchKit
struct ARM64ConstantTests {
let disasm = ARM64Disassembler()
@@ -527,13 +528,11 @@ struct FirmwarePipelineTests {
let pipeline = FirmwarePipeline(vmDirectory: root, variant: .jb, verbose: false)
let components = pipeline.buildComponentList(
restoreDir: root,
- iosBaseIs18: false,
- iosBaseIs27: true,
- cloudOSIsFridaCapable: true,
+ iOSBase: VPhoneVersion("27.0"),
)
let kernel = try #require(components.first { $0.name == "kernelcache" })
#expect(kernel.patcherFactories.count == 3)
- #expect(kernel.patcherFactories[2](Data(), false) is KernelExperimentalPatcher)
+ #expect(try kernel.patcherFactories[2](Data(), false) is KernelExperimentalPatcher)
let deviceTree = try #require(components.first { $0.name == "DeviceTree" })
let patcher = try #require(deviceTree.patcherFactories.first?(Data(), false) as? DeviceTreePatcher)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/MachOParserBoundsTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/MachOParserBoundsTests.swift
index 416413c4..06a9ad61 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/MachOParserBoundsTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/MachOParserBoundsTests.swift
@@ -11,6 +11,7 @@
@testable import FirmwarePatcher
import Foundation
import Testing
+import VPhonePatchKit
@Suite("MachOParser bounds")
struct MachOParserBoundsTests {
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/PatchComparisonTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/PatchComparisonTests.swift
index d841c73f..70985ee6 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/PatchComparisonTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/PatchComparisonTests.swift
@@ -20,6 +20,7 @@
@testable import FirmwarePatcher
import Foundation
import Testing
+import VPhonePatchKit
/// True when the unreproducible Python reference records are present.
private var hasReferencePatches: Bool {
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareCacheLoaderTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareCacheLoaderTests.swift
index 7a729a23..f276e689 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareCacheLoaderTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareCacheLoaderTests.swift
@@ -24,6 +24,7 @@ import CryptoKit
@testable import FirmwarePatcher
import Foundation
import Testing
+import VPhonePatchKit
// MARK: - Fixture discovery
@@ -283,8 +284,8 @@ struct CustomFirmwareCacheLoaderGateTests {
#expect(adrp.mnemonic == "adrp")
#expect(add.mnemonic == "add")
- let page = try #require(adrp.aarch64?.operands.last?.imm)
- let pageOffset = try #require(add.aarch64?.operands.last?.imm)
+ let page = try #require(adrp.detail?.operands.last?.imm)
+ let pageOffset = try #require(add.detail?.operands.last?.imm)
#expect(UInt64(page + pageOffset) == anchor.stringVMA)
// And the xref is inside __TEXT,__text, which is the only place a gate
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDaemonsTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDaemonsTests.swift
index 4787662e..23c801f3 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDaemonsTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDaemonsTests.swift
@@ -2,6 +2,7 @@ import CryptoKit
@testable import FirmwarePatcher
import Foundation
import Testing
+import VPhonePatchKit
// MARK: - Plist semantics
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDiskImageTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDiskImageTests.swift
index 8f232af2..4c928da2 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDiskImageTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDiskImageTests.swift
@@ -34,6 +34,7 @@ import CryptoKit
@testable import FirmwarePatcher
import Foundation
import Testing
+import VPhonePatchKit
// MARK: - Fixture discovery
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareJetsamTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareJetsamTests.swift
index fb1c9323..b8e7c3a3 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareJetsamTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareJetsamTests.swift
@@ -19,11 +19,11 @@
// Set `VPHONE_JETSAM_ARTIFACTS=<dir>` to keep each run's inputs and outputs for
// inspection from a shell; without it they land in a temporary directory.
-import Capstone
import CryptoKit
@testable import FirmwarePatcher
import Foundation
import Testing
+import VPhonePatchKit
// MARK: - Fixtures
@@ -473,9 +473,9 @@ struct CustomFirmwareJetsamDecodeTests {
] {
let encoded = try #require(ARM64Encoder.encodeADRP(rd: 0, pc: pc, target: target))
let insn = try #require(disassembler.disassembleOne(encoded, at: pc))
- let operands = try #require(insn.aarch64?.operands)
+ let operands = try #require(insn.detail?.operands)
#expect(insn.mnemonic == "adrp")
- #expect(operands.count >= 2 && operands[1].type == AARCH64_OP_IMM)
+ #expect(operands.count >= 2 && operands[1].type == .immediate)
let word = encoded.loadLE(UInt32.self, at: 0)
#expect(CustomFirmwareJetsamPatcher.adrpPage(word, at: pc) == UInt64(operands[1].imm))
#expect(CustomFirmwareJetsamPatcher.adrpPage(word, at: pc) == target & ~0xFFF)
@@ -503,7 +503,7 @@ struct CustomFirmwareJetsamDecodeTests {
@Test
func `block boundaries come from capstone groups`() throws {
let disassembler = ARM64Disassembler()
- func decode(_ bytes: Data) throws -> Instruction {
+ func decode(_ bytes: Data) throws -> ARM64Instruction {
try #require(disassembler.disassembleOne(bytes, at: 0))
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareMachOTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareMachOTests.swift
index 2f9b1f3e..b10b0c9d 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareMachOTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareMachOTests.swift
@@ -33,6 +33,7 @@ import CryptoKit
@testable import FirmwarePatcher
import Foundation
import Testing
+import VPhonePatchKit
// MARK: - Fixtures
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareMobileActivationTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareMobileActivationTests.swift
index 818e22f8..db403084 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareMobileActivationTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareMobileActivationTests.swift
@@ -15,11 +15,11 @@
// directory under `TMPDIR` — never inside the repository, and never inside
// `ipsws/ref_extract/`, which is the read-only reference tree.
-import Capstone
import CryptoKit
@testable import FirmwarePatcher
import Foundation
import Testing
+import VPhonePatchKit
// MARK: - Fixtures
@@ -268,9 +268,9 @@ struct CustomFirmwareMobileActivationAnchorTests {
#expect(decoded.count == 2)
#expect(decoded[0].mnemonic == "mov")
#expect(decoded[1].mnemonic == "ret")
- let operands = try #require(decoded[0].aarch64?.operands)
+ let operands = try #require(decoded[0].detail?.operands)
#expect(operands.count == 2)
- #expect(operands[1].type == AARCH64_OP_IMM)
+ #expect(operands[1].type == .immediate)
#expect(operands[1].imm == 1)
#expect(ARM64Disassembler().firstRegisterName(decoded[0]) == "x0")
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwarePlistPatchTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwarePlistPatchTests.swift
index f90fcf0f..4a05ae89 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwarePlistPatchTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwarePlistPatchTests.swift
@@ -27,6 +27,7 @@ import CryptoKit
import Foundation
import Img4tool
import Testing
+import VPhonePatchKit
// MARK: - The frozen reference
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareSeputilTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareSeputilTests.swift
index a4c0470e..ec26d817 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareSeputilTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareSeputilTests.swift
@@ -38,6 +38,7 @@ import CryptoKit
@testable import FirmwarePatcher
import Foundation
import Testing
+import VPhonePatchKit
// MARK: - Fixture discovery
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareWatchDogTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareWatchDogTests.swift
index 6bdd9f92..bb79a2b7 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareWatchDogTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareWatchDogTests.swift
@@ -18,11 +18,11 @@
// read-only reference data: every test here clones what it needs into the
// system temp directory and never writes inside it.
-import Capstone
import CryptoKit
@testable import FirmwarePatcher
import Foundation
import Testing
+import VPhonePatchKit
// MARK: - Fixtures
@@ -184,7 +184,7 @@ struct CustomFirmwareWatchDogAnchorTests {
data.subdata(in: site.valueFileOffset ..< site.valueFileOffset + 4), at: site.valueVMA,
))
#expect(value.mnemonic == "cset")
- #expect(value.aarch64?.conditionCode == AArch64CC_NE)
+ #expect(value.detail?.conditionCode == .ne)
}
}
@@ -258,7 +258,7 @@ struct CustomFirmwareWatchDogAnchorTests {
func `accepts the literal reaching X 0 through A move`() throws {
let base: UInt64 = 0x1_0000_0000
- func stream(movingInto destination: UInt32?) throws -> [Instruction] {
+ func stream(movingInto destination: UInt32?) throws -> [ARM64Instruction] {
var code = Data()
code += try #require(ARM64Encoder.encodeADRP(rd: 9, pc: base, target: base + 0x4000))
code += try #require(ARM64Encoder.encodeAddImm12(rd: 9, rn: 9, imm12: 0x453))
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheCameraPatcherTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheCameraPatcherTests.swift
index 34ce04de..51437978 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheCameraPatcherTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheCameraPatcherTests.swift
@@ -31,6 +31,7 @@ import CryptoKit
@testable import FirmwarePatcher
import Foundation
import Testing
+import VPhonePatchKit
// MARK: - The frozen reference
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheFoundationTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheFoundationTests.swift
index 66c79e2d..0fc29482 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheFoundationTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheFoundationTests.swift
@@ -31,6 +31,7 @@ import CryptoKit
@testable import FirmwarePatcher
import Foundation
import Testing
+import VPhonePatchKit
// MARK: - The frozen reference
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheHypervisorVirtualMachinePatcherTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheHypervisorVirtualMachinePatcherTests.swift
index faf3cda6..1e93658d 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheHypervisorVirtualMachinePatcherTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheHypervisorVirtualMachinePatcherTests.swift
@@ -33,6 +33,7 @@ import CryptoKit
@testable import FirmwarePatcher
import Foundation
import Testing
+import VPhonePatchKit
// MARK: - The frozen reference
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheIOMFBForceKernTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheIOMFBForceKernTests.swift
index 1daf7141..ac55bb5c 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheIOMFBForceKernTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheIOMFBForceKernTests.swift
@@ -29,6 +29,7 @@ import CryptoKit
@testable import FirmwarePatcher
import Foundation
import Testing
+import VPhonePatchKit
// MARK: - The frozen reference
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheIOMFBSwapEndTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheIOMFBSwapEndTests.swift
index 02b54011..59b2d178 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheIOMFBSwapEndTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheIOMFBSwapEndTests.swift
@@ -28,11 +28,11 @@
// builds with keystone — and run the finder over it, so the anchor's semantics
// are pinned on every machine, fixture or no fixture.
-import Capstone
import CryptoKit
@testable import FirmwarePatcher
import Foundation
import Testing
+import VPhonePatchKit
// MARK: - The frozen reference
@@ -297,7 +297,7 @@ private enum SwapEndCallSetup {
return ldr + add + selectorMove + sizeMove + zeroX4 + zeroX5 + (terminator ?? call)
}
- static func disassemble(_ code: Data, _ disassembler: ARM64Disassembler) -> [Instruction] {
+ static func disassemble(_ code: Data, _ disassembler: ARM64Disassembler) -> [ARM64Instruction] {
disassembler.disassemble(code, at: baseAddress, count: code.count / 4)
}
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheLSDEmbeddedRegTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheLSDEmbeddedRegTests.swift
index 89d1b078..435a1d41 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheLSDEmbeddedRegTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheLSDEmbeddedRegTests.swift
@@ -25,6 +25,7 @@ import CryptoKit
@testable import FirmwarePatcher
import Foundation
import Testing
+import VPhonePatchKit
// MARK: - The frozen reference
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheLockdownModePatcherTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheLockdownModePatcherTests.swift
index 25eecebb..e8b39cdf 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheLockdownModePatcherTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheLockdownModePatcherTests.swift
@@ -23,11 +23,11 @@
// working tree. Clones are made with `clonefile` under the system temp
// directory — instant and near-free on APFS — and removed again.
-import Capstone
import CryptoKit
@testable import FirmwarePatcher
import Foundation
import Testing
+import VPhonePatchKit
// MARK: - The frozen reference
@@ -420,7 +420,7 @@ struct DyldSharedCacheLockdownModeParityTests {
struct DyldSharedCacheLockdownModeGateTests {
/// The real instruction stream, and the index of the real gate in it.
private struct Stream {
- let instructions: [Instruction]
+ let instructions: [ARM64Instruction]
let gateIndex: Int
let comparisonIndex: Int
}
@@ -447,7 +447,7 @@ struct DyldSharedCacheLockdownModeGateTests {
/// documented `[21:10]` immediate field (see `ARM64Inst.addSubImm12`) is
/// rewritten, so this is derived test data rather than a hand-written
/// encoding.
- private func word(of insn: Instruction, withImmediate imm12: UInt32) -> Data {
+ private func word(of insn: ARM64Instruction, withImmediate imm12: UInt32) -> Data {
let original = insn.bytes.enumerated().reduce(UInt32(0)) { accumulated, byte in
accumulated | (UInt32(byte.element) << (8 * UInt32(byte.offset)))
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMaxSlidePatcherTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMaxSlidePatcherTests.swift
index 8ca043a6..7326ddff 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMaxSlidePatcherTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMaxSlidePatcherTests.swift
@@ -29,6 +29,7 @@ import CryptoKit
@testable import FirmwarePatcher
import Foundation
import Testing
+import VPhonePatchKit
// MARK: - The frozen reference
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheXPCLWCRPatcherTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheXPCLWCRPatcherTests.swift
index 9b48b5c3..c417a542 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheXPCLWCRPatcherTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheXPCLWCRPatcherTests.swift
@@ -20,11 +20,11 @@
// `cp -c` — APFS `clonefile`, so instant and near-free — under the system
// temporary directory, or `VPHONE_DSC_SCRATCH` when it is set.
-import Capstone
import CryptoKit
@testable import FirmwarePatcher
import Foundation
import Testing
+import VPhonePatchKit
// MARK: - The frozen reference
@@ -383,7 +383,7 @@ struct DyldSharedCacheXPCLWCRParityTests {
@Suite(.serialized, .enabled(if: LWCRFixture.runs, LWCRFixture.skipReason))
struct DyldSharedCacheXPCLWCRShapeTests {
/// `_xpc_token_satisfies_lwcr` as it is disassembled out of a cache.
- private func functionStream(in directory: URL) throws -> [Instruction] {
+ private func functionStream(in directory: URL) throws -> [ARM64Instruction] {
let chunks = try DyldSharedCacheChunkSet(directory: directory)
var address: UInt64?
for candidate in DyldSharedCacheXPCLWCRPatcher.symbolCandidates {
@@ -437,7 +437,7 @@ struct DyldSharedCacheXPCLWCRShapeTests {
DyldSharedCacheXPCLWCRPatcher.findConsistencyCheck(in: stream, disassembler: disassembler),
)
#expect(site.cset.mnemonic == "cset")
- #expect(site.cset.aarch64?.conditionCode == AArch64CC_NE)
+ #expect(site.cset.detail?.conditionCode == .ne)
#expect(site.eor.mnemonic == "eor")
#expect(site.tbz.mnemonic == "tbz")
#expect(site.eor.address == site.cset.address + 4)
@@ -477,7 +477,7 @@ struct DyldSharedCacheXPCLWCRShapeTests {
DyldSharedCacheXPCLWCRPatcher.findPatchedShape(in: stream, disassembler: disassembler),
)
#expect(already.mnemonic == "cset")
- #expect(already.aarch64?.conditionCode == AArch64CC_EQ)
+ #expect(already.detail?.conditionCode == .eq)
#expect(already.address == outcome.records[0].virtualAddress)
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
new file mode 100644
index 00000000..a317782b
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
@@ -0,0 +1,207 @@
+// FirmwarePatchSetCatalogTests.swift — The bundled catalogue, checked against itself.
+//
+// The manifests are hand-written and the patch identifiers in them have to match
+// the record identifiers the patchers emit. Nothing in the type system enforces
+// that, so these tests do: every shipped preset resolves, every declaration is
+// reachable, and the standard preset still says what the golden corpus was recorded
+// against.
+//
+// The one thing they cannot check without firmware is that each declaration
+// actually covers a record. That is what the `[!] declared by no patch set` warning
+// is for: it fires during a real `fw patch`, and the golden runs are checked for it.
+
+import FirmwarePatcher
+import Foundation
+import Testing
+import VPhonePatchKit
+
+@Suite("Bundled patch set catalogue")
+struct FirmwarePatchSetCatalogTests {
+ @Test("Every bundled set has a unique identifier and no duplicate patches")
+ func identifiersAreUnique() {
+ let setIdentifiers = FirmwarePatchSetCatalog.bundled.map(\.identifier)
+ #expect(Set(setIdentifiers).count == setIdentifiers.count)
+
+ let patchIdentifiers = FirmwarePatchSetCatalog.allDeclarations.map(\.identifier)
+ #expect(Set(patchIdentifiers).count == patchIdentifiers.count)
+ }
+
+ @Test("No patch identifier is a record-site prefix of another")
+ func noAmbiguousPrefixes() {
+ // Two declarations where one is a site of the other would make record
+ // attribution depend on the order they happen to be checked in. The
+ // resolver picks the longest, but a catalogue that needs that rule to
+ // disambiguate its own patches is a catalogue with a naming mistake.
+ let identifiers = FirmwarePatchSetCatalog.allDeclarations.map(\.identifier)
+ for outer in identifiers {
+ for inner in identifiers where inner != outer {
+ let isSite = inner.hasPrefix(outer + ".") || inner.hasPrefix(outer + "_")
+ #expect(!isSite, "\(inner) reads as a site of \(outer)")
+ }
+ }
+ }
+
+ @Test("Every patch has a title, and a summary if it is boot-essential")
+ func patchesAreDescribed() {
+ for patch in FirmwarePatchSetCatalog.allDeclarations {
+ #expect(!patch.title.isEmpty, "\(patch.identifier) has no title")
+ // The editor shows these beside a checkbox someone may untick. A
+ // boot-essential patch without an explanation is a trap.
+ if patch.bootEssential {
+ #expect(!patch.summary.isEmpty, "\(patch.identifier) is boot-essential with no summary")
+ }
+ }
+ }
+
+ @Test("Every shipped preset resolves on each supported base")
+ func presetsResolve() throws {
+ for preset in FirmwarePatchSetCatalog.builtInPresets {
+ for base in ["18.6.2", "26.0", "26.4", "27.0"] {
+ for cloud in ["26.1", "26.4"] {
+ let plan = try VPhonePatchPlan.resolve(
+ preset: preset,
+ patchSets: FirmwarePatchSetCatalog.bundled,
+ iOSBase: VPhoneVersion(base),
+ cloudOS: VPhoneVersion(cloud),
+ )
+ #expect(!plan.enabled.isEmpty)
+ // Nothing a shipped preset does should drop a boot-essential
+ // patch: these are the combinations we claim boot.
+ #expect(
+ plan.droppedBootEssentials.isEmpty,
+ "\(preset.identifier) on \(base)/\(cloud) drops \(plan.droppedBootEssentials)",
+ )
+ }
+ }
+ }
+ }
+
+ @Test("A preset resolves even when no version could be read")
+ func presetsResolveWithoutVersions() throws {
+ // `fw patch` can run against a tree whose manifests it could not parse.
+ // Resolution must still succeed; the version-gated patches simply skip.
+ let plan = try VPhonePatchPlan.resolve(
+ preset: FirmwarePatchSetCatalog.standardPreset,
+ patchSets: FirmwarePatchSetCatalog.bundled,
+ iOSBase: nil,
+ cloudOS: nil,
+ )
+ #expect(!plan.enabled.isEmpty)
+ #expect(!plan.skippedByVersion.isEmpty)
+ }
+
+ @Test("Standard leaves the Frida relaxations off, on every base")
+ func standardExcludesManualOnly() throws {
+ for base in ["18.6.2", "26.4", "27.0"] {
+ let plan = try VPhonePatchPlan.resolve(
+ preset: FirmwarePatchSetCatalog.standardPreset,
+ patchSets: FirmwarePatchSetCatalog.bundled,
+ iOSBase: VPhoneVersion(base),
+ cloudOS: VPhoneVersion("26.4"),
+ )
+ for identifier in FirmwarePatchSetCatalog.manualOnlyPatches {
+ #expect(!plan.isEnabled(identifier), "standard enabled \(identifier) on \(base)")
+ }
+ }
+ }
+
+ @Test("Extended is standard plus the Frida relaxations, and nothing else")
+ func extendedDiffersOnlyByManualOnly() throws {
+ let standard = try VPhonePatchPlan.resolve(
+ preset: FirmwarePatchSetCatalog.standardPreset,
+ patchSets: FirmwarePatchSetCatalog.bundled,
+ iOSBase: VPhoneVersion("26.4"),
+ cloudOS: VPhoneVersion("26.4"),
+ )
+ let extended = try VPhonePatchPlan.resolve(
+ preset: FirmwarePatchSetCatalog.extendedPreset,
+ patchSets: FirmwarePatchSetCatalog.bundled,
+ iOSBase: VPhoneVersion("26.4"),
+ cloudOS: VPhoneVersion("26.4"),
+ )
+ #expect(extended.enabled.subtracting(standard.enabled) == FirmwarePatchSetCatalog.manualOnlyPatches)
+ #expect(standard.enabled.subtracting(extended.enabled).isEmpty)
+ }
+
+ @Test("The two patches pinned by release are off everywhere else")
+ func versionPinnedPatchesAreOffByDefault() throws {
+ // These two were flags once (`--force-exc-guard`, `--force-dsc-maxslide`).
+ // They are now pinned to the release that needs them, so a base that does
+ // not need them never gets them from a preset.
+ let pinned = ["kernel.thread_guard_violation": 18, "dsc_maxslide.zero": 27]
+ for (identifier, requiredMajor) in pinned {
+ for base in [18, 26, 27] {
+ let plan = try VPhonePatchPlan.resolve(
+ preset: FirmwarePatchSetCatalog.extendedPreset,
+ patchSets: FirmwarePatchSetCatalog.bundled,
+ iOSBase: VPhoneVersion("\(base).0"),
+ cloudOS: VPhoneVersion("26.4"),
+ )
+ #expect(
+ plan.isEnabled(identifier) == (base == requiredMajor),
+ "\(identifier) on iOS \(base) should be \(base == requiredMajor)",
+ )
+ }
+ }
+ }
+
+ @Test("The Frida relaxations need cloudOS 26.4")
+ func fridaNeedsCapableCloudOS() throws {
+ for cloud in ["26.1", "26.4"] {
+ let plan = try VPhonePatchPlan.resolve(
+ preset: FirmwarePatchSetCatalog.extendedPreset,
+ patchSets: FirmwarePatchSetCatalog.bundled,
+ iOSBase: VPhoneVersion("26.4"),
+ cloudOS: VPhoneVersion(cloud),
+ )
+ let on = FirmwarePatchSetCatalog.manualOnlyPatches.allSatisfy { plan.isEnabled($0) }
+ #expect(on == (cloud == "26.4"))
+ }
+ }
+
+ @Test("Every set's manifest survives a plist round trip")
+ func manifestsRoundTrip() throws {
+ for manifest in FirmwarePatchSetCatalog.bundled {
+ let decoded = try VPhonePatchSetManifest.decode(manifest.encodedPlist())
+ #expect(decoded == manifest, "\(manifest.identifier) did not round trip")
+ }
+ }
+
+ @Test("Every built-in preset survives a plist round trip")
+ func presetsRoundTrip() throws {
+ for preset in FirmwarePatchSetCatalog.builtInPresets {
+ #expect(try VPhonePatchPreset.decode(preset.encodedPlist()) == preset)
+ }
+ }
+
+ @Test("The shipped preset plists match the built-in copies")
+ func shippedPresetsMatchBuiltIns() throws {
+ // The bundle reads the plists; a dev build falls back to the Swift copies.
+ // They have to agree, or a VM built from an Xcode build and a VM built from
+ // a staged bundle would get different patches.
+ let directory = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent() // PatchSets
+ .deletingLastPathComponent() // FirmwarePatcherTests
+ .deletingLastPathComponent() // VPhoneCommand
+ .deletingLastPathComponent() // VPhoneExecutable/VPhoneCommand
+ .appendingPathComponent("VPhoneVirtualization/Resources/patches_presets", isDirectory: true)
+ let shipped = try VPhonePatchPreset.readAll(fromDirectory: directory)
+ #expect(shipped.count == FirmwarePatchSetCatalog.builtInPresets.count)
+ for builtIn in FirmwarePatchSetCatalog.builtInPresets {
+ let match = shipped.first { $0.identifier == builtIn.identifier }
+ #expect(match == builtIn, "\(builtIn.identifier).plist differs from the built-in copy")
+ }
+ }
+
+ @Test("Standard comes first in a picker")
+ func standardSortsFirst() throws {
+ #expect(FirmwarePatchSetCatalog.builtInPresets.first?.isStandard == true)
+ }
+
+ @Test("No bundled set is external, so root cfw install never loads a file")
+ func bundledSetsOnly() {
+ for preset in FirmwarePatchSetCatalog.builtInPresets {
+ #expect(!preset.usesExternalPatchSets)
+ }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/PatchSetLoaderTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/PatchSetLoaderTests.swift
new file mode 100644
index 00000000..5a65d8ac
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/PatchSetLoaderTests.swift
@@ -0,0 +1,530 @@
+// PatchSetLoaderTests.swift — Loading a `.vphonepatchset` from outside the tool.
+//
+// These run against `VPhonePatchSetExample.vphonepatchset`, built beside the test
+// bundle, so they exercise the real loader against a real bundle rather than a
+// mock of one: the manifest read before any code is mapped, the signature check,
+// `dlopen` through `Bundle`, the principal class, and the patcher it hands back.
+//
+// The signature tests work on copies in a temporary directory, never on the built
+// product. A set straight out of Xcode is *linker* ad hoc signed — the Mach-O
+// carries a signature but the bundle has no sealed resources — which is exactly
+// the "arrived unsigned or invalid" case `vphone-cli patchset import` fixes, so
+// these tests reproduce that repair with the same `codesign` invocation instead of
+// asserting anything about how Xcode happened to leave the product.
+
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+import VPhonePatchKit
+
+// MARK: - Fixture
+
+/// Where the example set is, and how to get sealed and tampered copies of it.
+private enum ExamplePatchSet {
+ static let identifier = "com.vphone.patchset.example"
+ static let patchIdentifier = "example.string_rewrite"
+
+ /// The built product, beside the running `.xctest`.
+ static func url() throws -> URL {
+ let xctest = try #require(
+ Bundle.allBundles.first { $0.bundlePath.hasSuffix(".xctest") },
+ "the test bundle has to be findable to locate the products directory",
+ )
+ let products = URL(fileURLWithPath: xctest.bundlePath).deletingLastPathComponent()
+ let url = products.appendingPathComponent(
+ "VPhonePatchSetExample.\(VPhonePatchSetBundle.pathExtension)",
+ isDirectory: true,
+ )
+ guard FileManager.default.fileExists(atPath: url.path) else {
+ Issue.record("VPhonePatchSetExample is not in \(products.path)")
+ throw CocoaError(.fileNoSuchFile)
+ }
+ return url
+ }
+
+ /// A copy under `directory`, ad hoc signed the way `patchset import` signs one.
+ static func sealedCopy(into directory: URL) throws -> URL {
+ let copy = directory.appendingPathComponent(
+ "Copy.\(VPhonePatchSetBundle.pathExtension)",
+ isDirectory: true,
+ )
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ try? FileManager.default.removeItem(at: copy)
+ try FileManager.default.copyItem(at: try url(), to: copy)
+ try codesign(copy)
+ return copy
+ }
+
+ /// `codesign --force --sign -`, no `--deep`: one pass over the bundle is what
+ /// seals its resources. See `VPhonePatchSetStore.adHocSign`.
+ static func codesign(_ url: URL) throws {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/usr/bin/codesign")
+ process.arguments = ["--force", "--sign", "-", url.path]
+ process.standardOutput = FileHandle.nullDevice
+ process.standardError = FileHandle.nullDevice
+ try process.run()
+ process.waitUntilExit()
+ #expect(process.terminationStatus == 0, "codesign should seal a copy of the example")
+ }
+
+ static func temporaryDirectory() -> URL {
+ URL(fileURLWithPath: NSTemporaryDirectory())
+ .appendingPathComponent("vphone-patchset-tests-\(UUID().uuidString)", isDirectory: true)
+ }
+}
+
+// MARK: - Inspecting
+
+@Suite("Patch set bundles are read before they are loaded")
+struct PatchSetInspectionTests {
+ @Test("The manifest comes out of the bundle without loading any code")
+ func inspect() throws {
+ let set = try VPhonePatchSetBundle.inspect(at: try ExamplePatchSet.url())
+ #expect(set.manifest.identifier == ExamplePatchSet.identifier)
+ #expect(set.manifest.patches.count == 1)
+ let patch = try #require(set.manifest.patches.first)
+ #expect(patch.identifier == ExamplePatchSet.patchIdentifier)
+ #expect(patch.target == .firmware(.iBEC))
+ // Nothing is version-pinned, so the example applies to any pairing.
+ #expect(patch.applicability.matches(iOSBase: VPhoneVersion("18.6"), cloudOS: nil))
+ #expect(patch.applicability.matches(iOSBase: VPhoneVersion("27.0"), cloudOS: nil))
+ }
+
+ @Test("Anything that is not a patch set bundle is refused")
+ func notABundle() throws {
+ let plain = URL(fileURLWithPath: "/usr/bin/codesign")
+ #expect(throws: VPhonePatchSetError.notABundle(path: plain.path)) {
+ try VPhonePatchSetBundle.inspect(at: plain)
+ }
+ }
+
+ @Test("A path with the right extension but no manifest is refused")
+ func missingManifest() throws {
+ let directory = ExamplePatchSet.temporaryDirectory()
+ let empty = directory.appendingPathComponent(
+ "Empty.\(VPhonePatchSetBundle.pathExtension)",
+ isDirectory: true,
+ )
+ try FileManager.default.createDirectory(
+ at: empty.appendingPathComponent("Contents/Resources", isDirectory: true),
+ withIntermediateDirectories: true,
+ )
+ defer { try? FileManager.default.removeItem(at: directory) }
+
+ var thrown: VPhonePatchSetError?
+ do {
+ _ = try VPhonePatchSetBundle.inspect(at: empty)
+ } catch let error as VPhonePatchSetError {
+ thrown = error
+ }
+ guard case .manifestUnreadable = try #require(thrown) else {
+ Issue.record("expected manifestUnreadable, got \(String(describing: thrown))")
+ return
+ }
+ }
+}
+
+// MARK: - Validating
+
+@Suite("What a patch set has to satisfy before it is loaded")
+struct PatchSetValidationTests {
+ @Test("The identifier the preset pinned has to be the one the manifest declares")
+ func identifierMismatch() throws {
+ let set = try VPhonePatchSetBundle.inspect(at: try ExamplePatchSet.url())
+ #expect(throws: VPhonePatchSetError.identifierMismatch(
+ path: set.url.path,
+ expected: "com.example.other",
+ found: ExamplePatchSet.identifier,
+ )) {
+ // Signature off: this test is about identity, and the built product is
+ // not sealed until `patchset import` signs a copy of it.
+ try set.validate(expecting: "com.example.other", requireSignature: false)
+ }
+ }
+
+ @Test("A set built against a newer PatchKit is refused")
+ func patchKitTooOld() throws {
+ let set = try VPhonePatchSetBundle.inspect(at: try ExamplePatchSet.url())
+ let ancient = try #require(VPhoneVersion("0.1"))
+ #expect(throws: VPhonePatchSetError.patchKitTooOld(
+ patchSet: ExamplePatchSet.identifier,
+ required: set.manifest.minimumPatchKitVersion,
+ available: ancient,
+ )) {
+ try set.validate(expecting: nil, patchKitVersion: ancient, requireSignature: false)
+ }
+ // And is accepted by the framework it was actually built against.
+ #expect(set.manifest.minimumPatchKitVersion <= .currentPatchKit)
+ }
+
+ @Test("An ad hoc signed copy passes every check the loader makes")
+ func sealedCopyValidates() throws {
+ let directory = ExamplePatchSet.temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let copy = try ExamplePatchSet.sealedCopy(into: directory)
+
+ let set = try VPhonePatchSetBundle.inspect(at: copy)
+ // The full check, signature included — what `patchset import` ends with and
+ // what `resolvePlan` runs before it loads anything.
+ try set.validate(expecting: ExamplePatchSet.identifier)
+ #expect(try !set.codeDirectoryHash().isEmpty)
+ }
+
+ @Test("A set altered after signing no longer validates")
+ func tamperedCopyFails() throws {
+ let directory = ExamplePatchSet.temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let copy = try ExamplePatchSet.sealedCopy(into: directory)
+ let sealed = try VPhonePatchSetBundle.inspect(at: copy)
+ try sealed.requireValidSignature()
+
+ // Rewrite a sealed resource. This is the case the signature exists for:
+ // the manifest decides which patches the plan believes it is getting, so a
+ // manifest edited behind the plan's back has to stop the load.
+ let manifest = copy
+ .appendingPathComponent("Contents/Resources")
+ .appendingPathComponent(VPhonePatchSetManifest.resourceName)
+ var contents = try String(contentsOf: manifest, encoding: .utf8)
+ contents = contents.replacingOccurrences(
+ of: "<string>Example</string>",
+ with: "<string>Tampered</string>",
+ )
+ try contents.write(to: manifest, atomically: true, encoding: .utf8)
+
+ let altered = try VPhonePatchSetBundle.inspect(at: copy)
+ #expect(altered.manifest.name == "Tampered")
+ var thrown: (any Error)?
+ do {
+ try altered.validate(expecting: ExamplePatchSet.identifier)
+ } catch {
+ thrown = error
+ }
+ guard case .signatureInvalid = try #require(thrown as? VPhonePatchSetError) else {
+ Issue.record("expected signatureInvalid, got \(String(describing: thrown))")
+ return
+ }
+ }
+
+ @Test("A boot-chain-only set has no guest-side patch to refuse")
+ func bootChainOnly() throws {
+ let set = try VPhonePatchSetBundle.inspect(at: try ExamplePatchSet.url())
+ let guestSide = set.manifest.patches.filter { !$0.target.isBootChain }
+ #expect(guestSide.isEmpty)
+ // The refusal itself is the resolver's rule and is covered where the
+ // manifest model is tested; here the point is that the example obeys it,
+ // because a set that did not could never be imported at all.
+ }
+}
+
+// MARK: - Loading
+
+@Suite("Loading the principal class and the patcher it builds")
+struct PatchSetLoadingTests {
+ /// An iBEC-shaped buffer: the anchor, NUL terminated, inside other bytes.
+ private static func syntheticIBEC(anchor: String) -> Data {
+ var data = Data(repeating: 0x41, count: 0x40)
+ data.append(anchor.data(using: .ascii)!)
+ data.append(0)
+ data.append(Data(repeating: 0x42, count: 0x40))
+ return data
+ }
+
+ private static func context(
+ parameters: [String: String],
+ gate: VPhonePatchGate = .unrestricted,
+ ) -> VPhonePatchSetContext {
+ VPhonePatchSetContext(
+ iOSBase: VPhoneVersion("27.0"),
+ cloudOS: VPhoneVersion("26.4"),
+ gate: gate,
+ parameters: parameters,
+ verbose: false,
+ )
+ }
+
+ @Test("The exported factory loads and resolves VPhonePatchKit at runtime")
+ func loadPrincipal() throws {
+ // Two things are load-bearing here. The link: the bundle's executable names
+ // `@rpath/VPhonePatchKit.framework`, and dyld has to find the same framework
+ // this process already has — a second copy would make the cast inside
+ // `loadPrincipal` fail, because the two `VPhonePatchSetPrincipal`s would be
+ // different types. And the entry point: the set is reached through the C
+ // symbol it exports, not through `NSPrincipalClass`, which cannot work for a
+ // class whose superclass is resilient.
+ let set = try VPhonePatchSetBundle.inspect(at: try ExamplePatchSet.url())
+ let principal = try set.loadPrincipal()
+ #expect(String(describing: type(of: principal)) == "VPhoneExamplePatchSet")
+ // Loading twice hands back a second principal rather than failing: dlopen on
+ // a mapped image returns its handle.
+ #expect(String(describing: type(of: try set.loadPrincipal())) == "VPhoneExamplePatchSet")
+ }
+
+ @Test("A component the manifest never declared is a loud error")
+ func componentUnsupported() throws {
+ let set = try VPhonePatchSetBundle.inspect(at: try ExamplePatchSet.url())
+ let principal = try set.loadPrincipal()
+ var thrown: (any Error)?
+ do {
+ _ = try principal.makePatcher(
+ for: .kernelcache,
+ data: Data(),
+ context: Self.context(parameters: [:]),
+ )
+ } catch {
+ thrown = error
+ }
+ guard case let .componentUnsupported(_, component) =
+ try #require(thrown as? VPhonePatchSetError)
+ else {
+ Issue.record("expected componentUnsupported, got \(String(describing: thrown))")
+ return
+ }
+ #expect(component == VPhoneFirmwareComponent.kernelcache.rawValue)
+ }
+
+ @Test("The loaded patcher rewrites the string the preset named")
+ func patcherRewritesString() throws {
+ let set = try VPhonePatchSetBundle.inspect(at: try ExamplePatchSet.url())
+ let principal = try set.loadPrincipal()
+ let original = Self.syntheticIBEC(anchor: "VPHONE-ANCHOR")
+
+ let patcher = try principal.makePatcher(
+ for: .iBEC,
+ data: original,
+ context: Self.context(parameters: [
+ "ExampleFindString": "VPHONE-ANCHOR",
+ // One byte shorter than the anchor, so the rewrite also has to NUL
+ // pad rather than leave the tail of the old string behind.
+ "ExampleReplaceString": "vphone-patch",
+ ]),
+ )
+ let records = try patcher.findAll()
+ #expect(records.count == 1)
+ #expect(try patcher.apply() == 1)
+
+ let patched = patcher.patchedData
+ #expect(patched.count == original.count)
+ let buffer = BinaryBuffer(patched)
+ #expect(buffer.findAll(Data("VPHONE-ANCHOR".utf8)).isEmpty)
+ let sites = buffer.findAll(Data("vphone-patch".utf8))
+ #expect(sites == [try #require(records.first).fileOffset])
+ // The byte the shorter replacement freed is a NUL, not the old tail.
+ #expect(patched[try #require(sites.first) + 12] == 0)
+ }
+
+ @Test("A replacement longer than the anchor is refused rather than shifting bytes")
+ func replacementCannotGrow() throws {
+ let set = try VPhonePatchSetBundle.inspect(at: try ExamplePatchSet.url())
+ let principal = try set.loadPrincipal()
+ let patcher = try principal.makePatcher(
+ for: .iBEC,
+ data: Self.syntheticIBEC(anchor: "SHORT"),
+ context: Self.context(parameters: [
+ "ExampleFindString": "SHORT",
+ "ExampleReplaceString": "MUCH LONGER REPLACEMENT",
+ ]),
+ )
+ #expect(throws: (any Error).self) { try patcher.findAll() }
+ }
+
+ @Test("A patcher whose patch the plan turned off writes nothing")
+ func gateTurnsThePatchOff() throws {
+ let set = try VPhonePatchSetBundle.inspect(at: try ExamplePatchSet.url())
+ let principal = try set.loadPrincipal()
+ let original = Self.syntheticIBEC(anchor: "VPHONE-ANCHOR")
+ let parameters = [
+ "ExampleFindString": "VPHONE-ANCHOR",
+ "ExampleReplaceString": "vphone-patch",
+ ]
+
+ let off = try principal.makePatcher(
+ for: .iBEC,
+ data: original,
+ context: Self.context(
+ parameters: parameters,
+ gate: VPhonePatchGate(
+ declared: [ExamplePatchSet.patchIdentifier],
+ enabled: [],
+ ),
+ ),
+ )
+ #expect(try off.findAll().isEmpty)
+ #expect(try off.apply() == 0)
+ #expect(off.patchedData == original)
+
+ // Declared and enabled: the same patcher writes.
+ let on = try principal.makePatcher(
+ for: .iBEC,
+ data: original,
+ context: Self.context(
+ parameters: parameters,
+ gate: VPhonePatchGate(
+ declared: [ExamplePatchSet.patchIdentifier],
+ enabled: [ExamplePatchSet.patchIdentifier],
+ ),
+ ),
+ )
+ #expect(try on.findAll().count == 1)
+ #expect(try on.apply() == 1)
+ #expect(on.patchedData != original)
+ }
+
+ @Test("Without the preset's parameters the set patches nothing")
+ func noParametersNoPatch() throws {
+ let set = try VPhonePatchSetBundle.inspect(at: try ExamplePatchSet.url())
+ let principal = try set.loadPrincipal()
+ let original = Self.syntheticIBEC(anchor: "VPHONE-ANCHOR")
+ let patcher = try principal.makePatcher(
+ for: .iBEC,
+ data: original,
+ context: Self.context(parameters: [:]),
+ )
+ #expect(try patcher.findAll().isEmpty)
+ #expect(patcher.patchedData == original)
+ }
+}
+
+// MARK: - Plan Integration
+
+@Suite("An external set inside a resolved plan")
+struct PatchSetPlanIntegrationTests {
+ private func preset(
+ path: String,
+ selection: VPhonePatchSelection = .all,
+ ) -> VPhonePatchPreset {
+ VPhonePatchPreset(
+ identifier: "loader-test",
+ title: "Loader test",
+ patchSets: [.external(identifier: ExamplePatchSet.identifier, path: path)],
+ selection: selection,
+ parameters: ["ExampleFindString": "VPHONE-ANCHOR"],
+ )
+ }
+
+ @Test("A preset naming the set by path resolves to its manifest")
+ func resolvesExternalReference() throws {
+ let set = try VPhonePatchSetBundle.inspect(at: try ExamplePatchSet.url())
+ let plan = try VPhonePatchPlan.resolve(
+ preset: preset(path: set.url.path),
+ patchSets: [set.manifest],
+ iOSBase: VPhoneVersion("27.0"),
+ cloudOS: VPhoneVersion("26.4"),
+ )
+ #expect(plan.includesPatchSet(ExamplePatchSet.identifier))
+ #expect(plan.isEnabled(ExamplePatchSet.patchIdentifier))
+ #expect(plan.parameters["ExampleFindString"] == "VPHONE-ANCHOR")
+ // The manifest decides which components the set's code is asked about.
+ #expect(set.enabledComponents(in: plan) == [.iBEC])
+ }
+
+ @Test("A set whose every patch is off is asked for no patcher at all")
+ func allPatchesOffContributesNothing() throws {
+ let set = try VPhonePatchSetBundle.inspect(at: try ExamplePatchSet.url())
+ let plan = try VPhonePatchPlan.resolve(
+ preset: preset(
+ path: set.url.path,
+ selection: .block([ExamplePatchSet.patchIdentifier]),
+ ),
+ patchSets: [set.manifest],
+ iOSBase: VPhoneVersion("27.0"),
+ cloudOS: VPhoneVersion("26.4"),
+ )
+ #expect(!plan.isEnabled(ExamplePatchSet.patchIdentifier))
+ #expect(set.enabledComponents(in: plan).isEmpty)
+ }
+
+ @Test("The pipeline loads the set the preset names and runs it over iBEC")
+ func pipelineRunsAnExternalSet() throws {
+ // The whole path, without a restore tree: resolvePlan opens the bundle the
+ // preset names — signature required, identifier pinned — buildComponentList
+ // appends its patcher to the iBEC component, and patchData runs it.
+ //
+ // A signed copy, because this is the check the loader actually makes.
+ let directory = ExamplePatchSet.temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let copy = try ExamplePatchSet.sealedCopy(into: directory)
+
+ let pipeline = FirmwarePipeline(
+ vmDirectory: directory,
+ variant: .jb,
+ verbose: false,
+ preset: preset(path: copy.path, selection: .all),
+ patchSets: FirmwarePatchSetCatalog.bundled,
+ )
+ let plan = try #require(try pipeline.resolvePlan(
+ iOSBase: VPhoneVersion("27.0"),
+ cloudOS: VPhoneVersion("26.4"),
+ ))
+ #expect(plan.includesPatchSet(ExamplePatchSet.identifier))
+ #expect(!pipeline.loadedPatchSets.isEmpty)
+
+ let components = pipeline.buildComponentList(
+ restoreDir: directory,
+ iOSBase: VPhoneVersion("27.0"),
+ plan: plan,
+ gate: VPhonePatchGate(plan: plan),
+ )
+ let iBEC = try #require(components.first { $0.name == "iBEC" })
+ let external = try #require(
+ iBEC.patcherFactories.last,
+ "the external set's patcher has to be appended to iBEC",
+ )
+ // Last, not first: an external patcher sees the bytes the bundled boot-chain
+ // patchers already wrote.
+ let patcher = try external(Data(repeating: 0x41, count: 0x20), false)
+ #expect(String(describing: type(of: patcher)) == "VPhoneExampleStringPatcher")
+
+ // And the bytes come back out through BufferedPatcher, which is the only way
+ // the pipeline can read a patcher it has never heard of.
+ var anchored = Data(repeating: 0x41, count: 0x20)
+ anchored.append(Data("VPHONE-ANCHOR".utf8))
+ anchored.append(0)
+ let (patched, records) = try pipeline.patchData(
+ anchored,
+ componentName: "iBEC",
+ patcherFactories: [external],
+ )
+ #expect(records.map(\.patchID) == [ExamplePatchSet.patchIdentifier])
+ #expect(patched != anchored)
+ #expect(patched.count == anchored.count)
+ }
+
+ @Test("A set the preset pins but never imported stops the run")
+ func unsignedExternalSetIsRefused() throws {
+ // The built product is linker-signed with no sealed resources, which is what
+ // a set nobody imported looks like. resolvePlan has to refuse it rather than
+ // load it, and the message has to point at `patchset import`.
+ let pipeline = FirmwarePipeline(
+ vmDirectory: URL(fileURLWithPath: NSTemporaryDirectory()),
+ variant: .jb,
+ verbose: false,
+ preset: preset(path: try ExamplePatchSet.url().path),
+ patchSets: FirmwarePatchSetCatalog.bundled,
+ )
+ var thrown: (any Error)?
+ do {
+ _ = try pipeline.resolvePlan(iOSBase: VPhoneVersion("27.0"), cloudOS: VPhoneVersion("26.4"))
+ } catch {
+ thrown = error
+ }
+ let error = try #require(thrown as? VPhonePatchSetError)
+ switch error {
+ case .unsigned, .signatureInvalid:
+ #expect(pipeline.loadedPatchSets.isEmpty)
+ default:
+ Issue.record("expected a signature refusal, got \(error)")
+ }
+ }
+
+ @Test("The preset has to name the identifier the file declares")
+ func presetPinsIdentity() throws {
+ let set = try VPhonePatchSetBundle.inspect(at: try ExamplePatchSet.url())
+ // What `resolvePlan` does with a preset whose pinned identifier does not
+ // match the bundle at the path: refuse before loading, so swapping the file
+ // cannot silently change which patches apply.
+ #expect(throws: (any Error).self) {
+ try set.validate(expecting: "com.vphone.patchset.somethingelse", requireSignature: false)
+ }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/PatchSetModelTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/PatchSetModelTests.swift
new file mode 100644
index 00000000..a31f9fc4
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/PatchSetModelTests.swift
@@ -0,0 +1,546 @@
+// PatchSetModelTests.swift — The manifest, preset and resolver model.
+//
+// These tests use small hand-made manifests rather than the shipped catalogue, so
+// they pin the rules themselves: what a version gate means, what a plist round trip
+// must preserve, and which disagreements between patch sets are errors rather than
+// a silent choice. `FirmwarePatchSetCatalogTests` then checks the real catalogue
+// against those rules.
+
+import Foundation
+import Testing
+import VPhonePatchKit
+
+// MARK: - Versions
+
+@Suite("Version requirements")
+struct VPhoneVersionRequirementTests {
+ @Test("A product version splits into major, minor and patch")
+ func parsing() {
+ #expect(VPhoneVersion("27")?.major == 27)
+ #expect(VPhoneVersion("27")?.minor == 0)
+ #expect(VPhoneVersion("26.4")?.minor == 4)
+ #expect(VPhoneVersion("18.6.2")?.patch == 2)
+ // A version nothing could read is nil rather than zero, so it cannot
+ // accidentally satisfy a gate that names a real release.
+ #expect(VPhoneVersion(nil) == nil)
+ #expect(VPhoneVersion("") == nil)
+ #expect(VPhoneVersion("26.x") == nil)
+ #expect(VPhoneVersion("1.2.3.4") == nil)
+ }
+
+ @Test("Trailing zeros do not change a version")
+ func trailingZeros() {
+ #expect(VPhoneVersion("27") == VPhoneVersion("27.0"))
+ #expect(VPhoneVersion("27.0") == VPhoneVersion("27.0.0"))
+ #expect(VPhoneVersion("26.4")! < VPhoneVersion("26.4.1")!)
+ }
+
+ @Test("Each requirement matches exactly the releases it names")
+ func matching() {
+ let eighteen = VPhoneVersion("18.6.2")
+ let twentySixZero = VPhoneVersion("26.0")
+ let twentySixFour = VPhoneVersion("26.4")
+ let twentySeven = VPhoneVersion("27.0")
+
+ #expect(VPhoneVersionRequirement.any.matches(nil))
+ #expect(VPhoneVersionRequirement.major(18).matches(eighteen))
+ #expect(!VPhoneVersionRequirement.major(18).matches(twentySeven))
+
+ #expect(VPhoneVersionRequirement.release(major: 26, minor: 0).matches(twentySixZero))
+ #expect(!VPhoneVersionRequirement.release(major: 26, minor: 0).matches(twentySixFour))
+
+ #expect(VPhoneVersionRequirement.atLeast(major: 26, minor: 4).matches(twentySixFour))
+ #expect(VPhoneVersionRequirement.atLeast(major: 26, minor: 4).matches(twentySeven))
+ #expect(!VPhoneVersionRequirement.atLeast(major: 26, minor: 4).matches(twentySixZero))
+
+ let either = VPhoneVersionRequirement.oneOf([.release(major: 26, minor: 0), .major(18)])
+ #expect(either.matches(twentySixZero))
+ #expect(either.matches(eighteen))
+ #expect(!either.matches(twentySixFour))
+ }
+
+ @Test("A version gate never matches an unreadable version")
+ func unknownVersion() {
+ // The one case that must not fail open: a patch pinned to a release must
+ // not apply when nothing knows which release this is.
+ for requirement: VPhoneVersionRequirement in [
+ .major(27),
+ .release(major: 26, minor: 4),
+ .atLeast(major: 18, minor: 0),
+ .oneOf([.major(18), .major(27)]),
+ ] {
+ #expect(!requirement.matches(nil))
+ }
+ }
+
+ @Test("A requirement survives a plist round trip")
+ func coding() throws {
+ let cases: [VPhoneVersionRequirement] = [
+ .any,
+ .major(27),
+ .release(major: 26, minor: 0),
+ .atLeast(major: 26, minor: 4),
+ .oneOf([.major(18), .release(major: 26, minor: 0)]),
+ ]
+ for requirement in cases {
+ let encoder = PropertyListEncoder()
+ encoder.outputFormat = .xml
+ let data = try encoder.encode([requirement])
+ let decoded = try PropertyListDecoder().decode([VPhoneVersionRequirement].self, from: data)
+ #expect(decoded == [requirement])
+ }
+ }
+
+ @Test("An empty OneOf is refused, because it would match nothing")
+ func emptyOneOf() throws {
+ let plist = """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <plist version="1.0"><array><dict>
+ <key>Kind</key><string>OneOf</string>
+ <key>Options</key><array/>
+ </dict></array></plist>
+ """
+ #expect(throws: (any Error).self) {
+ try PropertyListDecoder().decode(
+ [VPhoneVersionRequirement].self,
+ from: Data(plist.utf8),
+ )
+ }
+ }
+}
+
+// MARK: - Selection
+
+@Suite("Patch selection")
+struct VPhonePatchSelectionTests {
+ @Test("All, allow and block each answer for a patch nobody named")
+ func includes() {
+ #expect(VPhonePatchSelection.all.includes("anything"))
+ #expect(VPhonePatchSelection.allow(["a"]).includes("a"))
+ #expect(!VPhonePatchSelection.allow(["a"]).includes("b"))
+ #expect(!VPhonePatchSelection.block(["a"]).includes("a"))
+ #expect(VPhonePatchSelection.block(["a"]).includes("b"))
+ }
+
+ @Test("Unchecking a box narrows every kind of selection")
+ func blocking() {
+ #expect(VPhonePatchSelection.all.blocking(["a"]) == .block(["a"]))
+ #expect(VPhonePatchSelection.allow(["a", "b"]).blocking(["a"]) == .allow(["b"]))
+ #expect(VPhonePatchSelection.block(["a"]).blocking(["b"]) == .block(["a", "b"]))
+ // Blocking nothing is not a change.
+ #expect(VPhonePatchSelection.allow(["a"]).blocking([]) == .allow(["a"]))
+ }
+
+ @Test("Checking a box widens every kind of selection")
+ func allowing() {
+ #expect(VPhonePatchSelection.all.allowing(["a"]) == .all)
+ #expect(VPhonePatchSelection.allow(["a"]).allowing(["b"]) == .allow(["a", "b"]))
+ #expect(VPhonePatchSelection.block(["a", "b"]).allowing(["a"]) == .block(["b"]))
+ }
+
+ @Test("A selection survives a plist round trip")
+ func coding() throws {
+ for selection: VPhonePatchSelection in [.all, .allow(["a", "b"]), .block(["c"])] {
+ let encoder = PropertyListEncoder()
+ encoder.outputFormat = .xml
+ let data = try encoder.encode([selection])
+ #expect(try PropertyListDecoder().decode([VPhonePatchSelection].self, from: data) == [selection])
+ }
+ }
+}
+
+// MARK: - Declarations
+
+@Suite("Patch declarations")
+struct VPhonePatchDeclarationTests {
+ private func declaration(_ identifier: String) -> VPhonePatchDeclaration {
+ VPhonePatchDeclaration(identifier: identifier, title: identifier, target: .firmware(.kernelcache))
+ }
+
+ @Test("A declaration covers its own record and its per-site records")
+ func covers() {
+ let kcall = declaration("jb.kcall10")
+ #expect(kcall.covers(recordIdentifier: "jb.kcall10"))
+ #expect(kcall.covers(recordIdentifier: "jb.kcall10.sy_call"))
+
+ // Record identifiers predate declarations and use both separators.
+ let rootfs = declaration("llb.rootfs")
+ #expect(rootfs.covers(recordIdentifier: "llb.rootfs_cbz_0x3b7"))
+ let sandbox = declaration("sandbox_ext")
+ #expect(sandbox.covers(recordIdentifier: "sandbox_ext_267"))
+ }
+
+ @Test("A bare textual prefix is not a site")
+ func doesNotOverreach() {
+ let debugger = declaration("kernel.debugger")
+ #expect(!debugger.covers(recordIdentifier: "kernel.debuggerless"))
+ #expect(!debugger.covers(recordIdentifier: "kernel.debug"))
+ }
+
+ @Test("A declaration survives a plist round trip, including its target")
+ func coding() throws {
+ let cases: [VPhonePatchTarget] = [
+ .firmware(.kernelcache),
+ .dyldSharedCache,
+ .prebootDeviceTree,
+ .guestExecutable(path: "/usr/libexec/seputil"),
+ .guestEntitlements(path: "/sbin/launchd"),
+ .guestFile(path: "/usr/local/bin/vphoned"),
+ ]
+ for target in cases {
+ let patch = VPhonePatchDeclaration(
+ identifier: "x.y",
+ title: "X",
+ summary: "why",
+ target: target,
+ applicability: VPhonePatchApplicability(iOSBase: .major(27)),
+ bootEssential: true,
+ )
+ let encoder = PropertyListEncoder()
+ encoder.outputFormat = .xml
+ let data = try encoder.encode([patch])
+ #expect(try PropertyListDecoder().decode([VPhonePatchDeclaration].self, from: data) == [patch])
+ }
+ }
+
+ @Test("A guest path must be absolute inside the guest")
+ func relativeGuestPathRefused() throws {
+ let plist = """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <plist version="1.0"><array><dict>
+ <key>Kind</key><string>GuestExecutable</string>
+ <key>Path</key><string>usr/libexec/seputil</string>
+ </dict></array></plist>
+ """
+ #expect(throws: (any Error).self) {
+ try PropertyListDecoder().decode([VPhonePatchTarget].self, from: Data(plist.utf8))
+ }
+ }
+}
+
+// MARK: - Resolver
+
+@Suite("Plan resolution")
+struct VPhonePatchPlanTests {
+ private func patch(
+ _ identifier: String,
+ applicability: VPhonePatchApplicability = .always,
+ bootEssential: Bool = false,
+ ) -> VPhonePatchDeclaration {
+ VPhonePatchDeclaration(
+ identifier: identifier,
+ title: identifier,
+ target: .firmware(.kernelcache),
+ applicability: applicability,
+ bootEssential: bootEssential,
+ )
+ }
+
+ private func set(
+ _ identifier: String,
+ patches: [VPhonePatchDeclaration],
+ requires: [String] = [],
+ provides: [String] = [],
+ conflictsWith: [String] = [],
+ after: [String] = [],
+ minimumPatchKitVersion: VPhoneVersion = VPhoneVersion(major: 1),
+ ) -> VPhonePatchSetManifest {
+ VPhonePatchSetManifest(
+ identifier: identifier,
+ name: identifier,
+ minimumPatchKitVersion: minimumPatchKitVersion,
+ patches: patches,
+ requires: requires,
+ provides: provides,
+ conflictsWith: conflictsWith,
+ after: after,
+ )
+ }
+
+ private func preset(
+ _ sets: [String],
+ selection: VPhonePatchSelection = .all,
+ ) -> VPhonePatchPreset {
+ VPhonePatchPreset(
+ identifier: "test",
+ title: "Test",
+ patchSets: sets.map { .bundled($0) },
+ selection: selection,
+ )
+ }
+
+ @Test("A resolved plan turns on what the selection and the version gate agree on")
+ func enabled() throws {
+ let sets = [set("a", patches: [
+ patch("always"),
+ patch("only27", applicability: VPhonePatchApplicability(iOSBase: .major(27))),
+ patch("blocked"),
+ ])]
+ let plan = try VPhonePatchPlan.resolve(
+ preset: preset(["a"], selection: .block(["blocked"])),
+ patchSets: sets,
+ iOSBase: VPhoneVersion("26.4"),
+ cloudOS: VPhoneVersion("26.4"),
+ )
+ #expect(plan.enabled == ["always"])
+ // A patch that is off and a patch that does not apply here stay
+ // distinguishable, so a log can say which happened.
+ #expect(plan.skippedByVersion == ["only27"])
+ #expect(!plan.isEnabled("blocked"))
+ #expect(!plan.isEnabled("only27"))
+ }
+
+ @Test("A VM's own boxes compose onto the preset")
+ func overrides() throws {
+ let sets = [set("a", patches: [patch("one"), patch("two"), patch("three")])]
+ let plan = try VPhonePatchPlan.resolve(
+ preset: preset(["a"], selection: .block(["two", "three"])),
+ patchSets: sets,
+ iOSBase: VPhoneVersion("26.4"),
+ cloudOS: VPhoneVersion("26.4"),
+ blocked: ["one"],
+ allowed: ["two"],
+ )
+ #expect(plan.enabled == ["two"])
+ }
+
+ @Test("Checking a box cannot defeat a version gate")
+ func overrideRespectsVersion() throws {
+ let sets = [set("a", patches: [
+ patch("only27", applicability: VPhonePatchApplicability(iOSBase: .major(27))),
+ ])]
+ let plan = try VPhonePatchPlan.resolve(
+ preset: preset(["a"], selection: .block(["only27"])),
+ patchSets: sets,
+ iOSBase: VPhoneVersion("26.4"),
+ cloudOS: VPhoneVersion("26.4"),
+ allowed: ["only27"],
+ )
+ #expect(plan.enabled.isEmpty)
+ #expect(plan.skippedByVersion == ["only27"])
+ }
+
+ @Test("A record maps back to the declaration that owns it")
+ func recordAttribution() throws {
+ let sets = [set("a", patches: [patch("kernel.sandbox"), patch("kernel.sandbox.mount_check_mount")])]
+ let plan = try VPhonePatchPlan.resolve(
+ preset: preset(["a"], selection: .allow(["kernel.sandbox"])),
+ patchSets: sets,
+ iOSBase: nil,
+ cloudOS: nil,
+ )
+ // The longest matching declaration wins, so a record is attributed to the
+ // most specific patch that claims it.
+ #expect(
+ plan.declaration(coveringRecord: "kernel.sandbox.mount_check_mount")?.identifier
+ == "kernel.sandbox.mount_check_mount",
+ )
+ #expect(plan.isRecordEnabled("kernel.sandbox.file_check_mmap"))
+ #expect(!plan.isRecordEnabled("kernel.sandbox.mount_check_mount"))
+ // A record no declaration covers is not enabled by this plan; the gate,
+ // not the plan, decides that it applies anyway.
+ #expect(!plan.isRecordEnabled("something.else"))
+ }
+
+ @Test("A preset naming an absent set is an error")
+ func unknownPatchSet() {
+ #expect(throws: VPhonePatchPlanError.unknownPatchSet(preset: "test", patchSet: "b")) {
+ try VPhonePatchPlan.resolve(
+ preset: preset(["b"]),
+ patchSets: [set("a", patches: [patch("one")])],
+ iOSBase: nil,
+ cloudOS: nil,
+ )
+ }
+ }
+
+ @Test("A selection naming a patch nothing declares is an error")
+ func unknownPatch() {
+ // The point of checking: a typo in a prewritten preset would otherwise be
+ // an allow list that turns nothing on, or a block list that blocks nothing.
+ #expect(throws: VPhonePatchPlanError.unknownPatch(preset: "test", identifier: "typo")) {
+ try VPhonePatchPlan.resolve(
+ preset: preset(["a"], selection: .block(["typo"])),
+ patchSets: [set("a", patches: [patch("one")])],
+ iOSBase: nil,
+ cloudOS: nil,
+ )
+ }
+ }
+
+ @Test("Two sets declaring the same patch is an error")
+ func duplicatePatch() {
+ #expect(throws: (any Error).self) {
+ try VPhonePatchPlan.resolve(
+ preset: preset(["a", "b"]),
+ patchSets: [
+ set("a", patches: [patch("shared")]),
+ set("b", patches: [patch("shared")]),
+ ],
+ iOSBase: nil,
+ cloudOS: nil,
+ )
+ }
+ }
+
+ @Test("An unmet requirement is an error")
+ func missingRequirement() {
+ #expect(throws: VPhonePatchPlanError.missingRequirement(patchSet: "b", capability: "cap.a")) {
+ try VPhonePatchPlan.resolve(
+ preset: preset(["b"]),
+ patchSets: [
+ set("a", patches: [patch("one")], provides: ["cap.a"]),
+ set("b", patches: [patch("two")], requires: ["cap.a"]),
+ ],
+ iOSBase: nil,
+ cloudOS: nil,
+ )
+ }
+ }
+
+ @Test("A conflict is an error from either side")
+ func conflictIsSymmetric() throws {
+ let a = set("a", patches: [patch("one")], provides: ["cap.a"])
+ let bDeclares = set("b", patches: [patch("two")], conflictsWith: ["cap.a"])
+ let bSilent = set("b", patches: [patch("two")], provides: ["cap.b"])
+ let aDeclares = set("a", patches: [patch("one")], provides: ["cap.a"], conflictsWith: ["cap.b"])
+
+ // The newer set names the older one.
+ #expect(throws: (any Error).self) {
+ try VPhonePatchPlan.resolve(
+ preset: preset(["a", "b"]),
+ patchSets: [a, bDeclares],
+ iOSBase: nil,
+ cloudOS: nil,
+ )
+ }
+ // And the other way round, so a set need not be patched to learn about a
+ // rival that came later.
+ #expect(throws: (any Error).self) {
+ try VPhonePatchPlan.resolve(
+ preset: preset(["a", "b"]),
+ patchSets: [aDeclares, bSilent],
+ iOSBase: nil,
+ cloudOS: nil,
+ )
+ }
+ }
+
+ @Test("A set needing a newer PatchKit is refused")
+ func patchKitTooOld() {
+ #expect(throws: (any Error).self) {
+ try VPhonePatchPlan.resolve(
+ preset: preset(["a"]),
+ patchSets: [set(
+ "a",
+ patches: [patch("one")],
+ minimumPatchKitVersion: VPhoneVersion(major: 99),
+ )],
+ iOSBase: nil,
+ cloudOS: nil,
+ )
+ }
+ }
+
+ @Test("After puts the sets in order, and a cycle is an error")
+ func ordering() throws {
+ let plan = try VPhonePatchPlan.resolve(
+ preset: preset(["c", "b", "a"]),
+ patchSets: [
+ set("a", patches: [patch("one")], provides: ["cap.a"]),
+ set("b", patches: [patch("two")], provides: ["cap.b"], after: ["cap.a"]),
+ set("c", patches: [patch("three")], after: ["cap.b"]),
+ ],
+ iOSBase: nil,
+ cloudOS: nil,
+ )
+ #expect(plan.patchSets.map(\.identifier) == ["a", "b", "c"])
+
+ #expect(throws: (any Error).self) {
+ try VPhonePatchPlan.resolve(
+ preset: preset(["a", "b"]),
+ patchSets: [
+ set("a", patches: [patch("one")], provides: ["cap.a"], after: ["cap.b"]),
+ set("b", patches: [patch("two")], provides: ["cap.b"], after: ["cap.a"]),
+ ],
+ iOSBase: nil,
+ cloudOS: nil,
+ )
+ }
+ }
+
+ @Test("A blocked boot-essential patch is reported, not refused")
+ func droppedBootEssentials() throws {
+ // Blocking one is allowed: that is how an external set replaces it. It
+ // must never be quiet, though.
+ let plan = try VPhonePatchPlan.resolve(
+ preset: preset(["a"], selection: .block(["vital"])),
+ patchSets: [set("a", patches: [patch("vital", bootEssential: true), patch("other")])],
+ iOSBase: nil,
+ cloudOS: nil,
+ )
+ #expect(plan.droppedBootEssentials == ["vital"])
+ #expect(plan.enabled == ["other"])
+ }
+
+ @Test("A plan knows whether a component has anything left to do")
+ func componentExpectations() throws {
+ let sets = [VPhonePatchSetManifest(
+ identifier: "a",
+ name: "a",
+ patches: [
+ VPhonePatchDeclaration(identifier: "k", title: "k", target: .firmware(.kernelcache)),
+ VPhonePatchDeclaration(identifier: "d", title: "d", target: .firmware(.deviceTree)),
+ ],
+ )]
+ let plan = try VPhonePatchPlan.resolve(
+ preset: preset(["a"], selection: .block(["d"])),
+ patchSets: sets,
+ iOSBase: nil,
+ cloudOS: nil,
+ )
+ #expect(plan.hasEnabledPatches(target: .firmware(.kernelcache)))
+ #expect(!plan.hasEnabledPatches(target: .firmware(.deviceTree)))
+ }
+}
+
+// MARK: - Gate
+
+@Suite("Patch gate")
+struct VPhonePatchGateTests {
+ @Test("An unrestricted gate applies everything")
+ func unrestricted() {
+ let gate = VPhonePatchGate.unrestricted
+ #expect(gate.isUnrestricted)
+ #expect(gate.allows(record: "anything"))
+ #expect(!gate.isUndeclared(record: "anything"))
+ }
+
+ @Test("A gate answers about record identifiers, not just declarations")
+ func records() {
+ let gate = VPhonePatchGate(declared: ["jb.kcall10", "sandbox_ext"], enabled: ["jb.kcall10"])
+ #expect(gate.allows(record: "jb.kcall10.sy_call"))
+ #expect(!gate.allows(record: "sandbox_ext_267"))
+ }
+
+ @Test("An undeclared record applies, and says so")
+ func undeclaredFailsOpen() {
+ // Dropping bytes over a missing declaration would change the firmware
+ // silently. Applying it and flagging the gap is the safer failure.
+ let gate = VPhonePatchGate(declared: ["known"], enabled: [])
+ #expect(gate.isUndeclared(record: "brand.new.patch"))
+ #expect(gate.allows(record: "brand.new.patch"))
+ #expect(!gate.isUndeclared(record: "known"))
+ #expect(!gate.allows(record: "known"))
+ }
+
+ @Test("The longest declaration owns a record")
+ func longestWins() {
+ let gate = VPhonePatchGate(
+ declared: ["kernel.sandbox", "kernel.sandbox.mount_check_mount"],
+ enabled: ["kernel.sandbox"],
+ )
+ #expect(!gate.allows(record: "kernel.sandbox.mount_check_mount"))
+ #expect(gate.allows(record: "kernel.sandbox.file_check_mmap"))
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj/project.pbxproj b/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj/project.pbxproj
index 6bf408c3..a1c089ee 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj/project.pbxproj
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand.xcodeproj/project.pbxproj
@@ -7,16 +7,13 @@
objects = {
/* Begin PBXBuildFile section */
- 5036445030653D1000CAADDF /* Capstone in Frameworks */ = {isa = PBXBuildFile; productRef = BB0000000000000000000201 /* Capstone */; };
5036445130653D1000CAADDF /* Img4tool in Frameworks */ = {isa = PBXBuildFile; productRef = BB0000000000000000000202 /* Img4tool */; };
5036445230653D1000CAADDF /* MachOKit in Frameworks */ = {isa = PBXBuildFile; productRef = BB0000000000000000000203 /* MachOKit */; };
5036445330653D1000CAADDF /* ArchiveKit in Frameworks */ = {isa = PBXBuildFile; productRef = BB0000000000000000000205 /* ArchiveKit */; };
- 50364C1A30653DE900CAADDF /* Capstone in Frameworks */ = {isa = PBXBuildFile; productRef = BB0000000000000000000201 /* Capstone */; };
50364C1B30653DE900CAADDF /* Img4tool in Frameworks */ = {isa = PBXBuildFile; productRef = BB0000000000000000000202 /* Img4tool */; };
50364C1C30653DE900CAADDF /* MachOKit in Frameworks */ = {isa = PBXBuildFile; productRef = BB0000000000000000000203 /* MachOKit */; };
50364C1D30653DE900CAADDF /* ArchiveKit in Frameworks */ = {isa = PBXBuildFile; productRef = BB0000000000000000000205 /* ArchiveKit */; };
50364C1E30653DE900CAADDF /* libVPhoneSign.a in Frameworks */ = {isa = PBXBuildFile; fileRef = BB0000000000000000000032 /* libVPhoneSign.a */; };
- BB0000000000000000000101 /* Capstone in Frameworks */ = {isa = PBXBuildFile; productRef = BB0000000000000000000201 /* Capstone */; };
BB0000000000000000000102 /* Img4tool in Frameworks */ = {isa = PBXBuildFile; productRef = BB0000000000000000000202 /* Img4tool */; };
BB0000000000000000000103 /* MachOKit in Frameworks */ = {isa = PBXBuildFile; productRef = BB0000000000000000000203 /* MachOKit */; };
BB0000000000000000000104 /* ArgumentParser in Frameworks */ = {isa = PBXBuildFile; productRef = BB0000000000000000000204 /* ArgumentParser */; };
@@ -25,6 +22,10 @@
BB0000000000000000000107 /* libFirmwarePatcher.a in Frameworks */ = {isa = PBXBuildFile; fileRef = BB0000000000000000000033 /* libFirmwarePatcher.a */; };
BB0000000000000000000108 /* libVPhoneSign.a in Frameworks */ = {isa = PBXBuildFile; fileRef = BB0000000000000000000032 /* libVPhoneSign.a */; };
BB0000000000000000000109 /* ArgumentParser in Frameworks */ = {isa = PBXBuildFile; productRef = BB0000000000000000000204 /* ArgumentParser */; };
+ BB0000000000000000000110 /* Capstone in Frameworks */ = {isa = PBXBuildFile; productRef = BB0000000000000000000201 /* Capstone */; };
+ BB0000000000000000000111 /* VPhonePatchKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BB0000000000000000000036 /* VPhonePatchKit.framework */; };
+ BB0000000000000000000112 /* VPhonePatchKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BB0000000000000000000036 /* VPhonePatchKit.framework */; };
+ BB0000000000000000000113 /* VPhonePatchKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BB0000000000000000000036 /* VPhonePatchKit.framework */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -56,6 +57,41 @@
remoteGlobalIDString = BB0000000000000000000012;
remoteInfo = VPhoneSign;
};
+ BB0000000000000000000130 /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = BB0000000000000000000001 /* Project object */;
+ proxyType = 1;
+ remoteGlobalIDString = BB0000000000000000000016;
+ remoteInfo = VPhonePatchKit;
+ };
+ BB0000000000000000000132 /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = BB0000000000000000000001 /* Project object */;
+ proxyType = 1;
+ remoteGlobalIDString = BB0000000000000000000016;
+ remoteInfo = VPhonePatchKit;
+ };
+ BB0000000000000000000134 /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = BB0000000000000000000001 /* Project object */;
+ proxyType = 1;
+ remoteGlobalIDString = BB0000000000000000000016;
+ remoteInfo = VPhonePatchKit;
+ };
+ BB0000000000000000000136 /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = BB0000000000000000000001 /* Project object */;
+ proxyType = 1;
+ remoteGlobalIDString = BB0000000000000000000016;
+ remoteInfo = VPhonePatchKit;
+ };
+ BB0000000000000000000138 /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = BB0000000000000000000001 /* Project object */;
+ proxyType = 1;
+ remoteGlobalIDString = BB0000000000000000000017;
+ remoteInfo = VPhonePatchSetExample;
+ };
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
@@ -64,6 +100,8 @@
BB0000000000000000000033 /* libFirmwarePatcher.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libFirmwarePatcher.a; sourceTree = BUILT_PRODUCTS_DIR; };
BB0000000000000000000034 /* FirmwarePatcherTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = FirmwarePatcherTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
BB0000000000000000000035 /* VPhoneSignTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = VPhoneSignTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
+ BB0000000000000000000036 /* VPhonePatchKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = VPhonePatchKit.framework; sourceTree = BUILT_PRODUCTS_DIR; };
+ BB0000000000000000000037 /* VPhonePatchSetExample.vphonepatchset */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = VPhonePatchSetExample.vphonepatchset; sourceTree = BUILT_PRODUCTS_DIR; };
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
@@ -74,6 +112,8 @@
BB0000000000000000000025 /* VPhoneSignTests */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VPhoneSignTests; sourceTree = "<group>"; };
BB0000000000000000000026 /* VPhoneSignTestFixtures */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VPhoneSignTestFixtures; sourceTree = "<group>"; };
BB0000000000000000000027 /* FirmwarePatcherTestFixtures */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = FirmwarePatcherTestFixtures; sourceTree = "<group>"; };
+ BB0000000000000000000028 /* VPhonePatchKit */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VPhonePatchKit; sourceTree = "<group>"; };
+ BB0000000000000000000029 /* VPhonePatchSetExample */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VPhonePatchSetExample; sourceTree = "<group>"; };
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
@@ -84,7 +124,7 @@
5036445330653D1000CAADDF /* ArchiveKit in Frameworks */,
5036445230653D1000CAADDF /* MachOKit in Frameworks */,
5036445130653D1000CAADDF /* Img4tool in Frameworks */,
- 5036445030653D1000CAADDF /* Capstone in Frameworks */,
+ BB0000000000000000000111 /* VPhonePatchKit.framework in Frameworks */,
BB0000000000000000000104 /* ArgumentParser in Frameworks */,
BB0000000000000000000106 /* AppleMobileDeviceLibrary in Frameworks */,
);
@@ -102,7 +142,6 @@
buildActionMask = 2147483647;
files = (
BB0000000000000000000109 /* ArgumentParser in Frameworks */,
- BB0000000000000000000101 /* Capstone in Frameworks */,
BB0000000000000000000102 /* Img4tool in Frameworks */,
BB0000000000000000000103 /* MachOKit in Frameworks */,
BB0000000000000000000105 /* ArchiveKit in Frameworks */,
@@ -113,7 +152,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
- 50364C1A30653DE900CAADDF /* Capstone in Frameworks */,
+ BB0000000000000000000112 /* VPhonePatchKit.framework in Frameworks */,
50364C1C30653DE900CAADDF /* MachOKit in Frameworks */,
BB0000000000000000000107 /* libFirmwarePatcher.a in Frameworks */,
BB0000000000000000000108 /* libVPhoneSign.a in Frameworks */,
@@ -130,6 +169,22 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
+ BB0000000000000000000046 /* Frameworks */ = {
+ isa = PBXFrameworksBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ BB0000000000000000000110 /* Capstone in Frameworks */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ BB0000000000000000000047 /* Frameworks */ = {
+ isa = PBXFrameworksBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ BB0000000000000000000113 /* VPhonePatchKit.framework in Frameworks */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
@@ -143,6 +198,8 @@
BB0000000000000000000025 /* VPhoneSignTests */,
BB0000000000000000000026 /* VPhoneSignTestFixtures */,
BB0000000000000000000027 /* FirmwarePatcherTestFixtures */,
+ BB0000000000000000000028 /* VPhonePatchKit */,
+ BB0000000000000000000029 /* VPhonePatchSetExample */,
BB0000000000000000000003 /* Products */,
);
sourceTree = "<group>";
@@ -155,6 +212,8 @@
BB0000000000000000000033 /* libFirmwarePatcher.a */,
BB0000000000000000000034 /* FirmwarePatcherTests.xctest */,
BB0000000000000000000035 /* VPhoneSignTests.xctest */,
+ BB0000000000000000000036 /* VPhonePatchKit.framework */,
+ BB0000000000000000000037 /* VPhonePatchSetExample.vphonepatchset */,
);
name = Products;
sourceTree = "<group>";
@@ -174,6 +233,7 @@
dependencies = (
BB0000000000000000000121 /* PBXTargetDependency */,
BB0000000000000000000123 /* PBXTargetDependency */,
+ BB0000000000000000000129 /* PBXTargetDependency */,
);
fileSystemSynchronizedGroups = (
BB0000000000000000000021 /* VPhoneCommand */,
@@ -181,7 +241,6 @@
name = VPhoneCommand;
packageProductDependencies = (
BB0000000000000000000204 /* ArgumentParser */,
- BB0000000000000000000201 /* Capstone */,
BB0000000000000000000202 /* Img4tool */,
BB0000000000000000000203 /* MachOKit */,
BB0000000000000000000205 /* ArchiveKit */,
@@ -221,6 +280,7 @@
);
dependencies = (
BB0000000000000000000123 /* PBXTargetDependency */,
+ BB0000000000000000000131 /* PBXTargetDependency */,
);
fileSystemSynchronizedGroups = (
BB0000000000000000000023 /* FirmwarePatcher */,
@@ -228,7 +288,6 @@
name = FirmwarePatcher;
packageProductDependencies = (
BB0000000000000000000204 /* ArgumentParser */,
- BB0000000000000000000201 /* Capstone */,
BB0000000000000000000202 /* Img4tool */,
BB0000000000000000000203 /* MachOKit */,
BB0000000000000000000205 /* ArchiveKit */,
@@ -249,13 +308,14 @@
dependencies = (
BB0000000000000000000125 /* PBXTargetDependency */,
BB0000000000000000000127 /* PBXTargetDependency */,
+ BB0000000000000000000133 /* PBXTargetDependency */,
+ BB0000000000000000000137 /* PBXTargetDependency */,
);
fileSystemSynchronizedGroups = (
BB0000000000000000000024 /* FirmwarePatcherTests */,
);
name = FirmwarePatcherTests;
packageProductDependencies = (
- BB0000000000000000000201 /* Capstone */,
BB0000000000000000000202 /* Img4tool */,
BB0000000000000000000203 /* MachOKit */,
BB0000000000000000000205 /* ArchiveKit */,
@@ -284,6 +344,49 @@
productReference = BB0000000000000000000035 /* VPhoneSignTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
+ BB0000000000000000000016 /* VPhonePatchKit */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = BB0000000000000000000086 /* Build configuration list for PBXNativeTarget "VPhonePatchKit" */;
+ buildPhases = (
+ BB0000000000000000000056 /* Sources */,
+ BB0000000000000000000046 /* Frameworks */,
+ );
+ buildRules = (
+ );
+ dependencies = (
+ );
+ fileSystemSynchronizedGroups = (
+ BB0000000000000000000028 /* VPhonePatchKit */,
+ );
+ name = VPhonePatchKit;
+ packageProductDependencies = (
+ BB0000000000000000000201 /* Capstone */,
+ );
+ productName = VPhonePatchKit;
+ productReference = BB0000000000000000000036 /* VPhonePatchKit.framework */;
+ productType = "com.apple.product-type.framework";
+ };
+ BB0000000000000000000017 /* VPhonePatchSetExample */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = BB0000000000000000000087 /* Build configuration list for PBXNativeTarget "VPhonePatchSetExample" */;
+ buildPhases = (
+ BB0000000000000000000057 /* Sources */,
+ BB0000000000000000000058 /* Resources */,
+ BB0000000000000000000047 /* Frameworks */,
+ );
+ buildRules = (
+ );
+ dependencies = (
+ BB0000000000000000000135 /* PBXTargetDependency */,
+ );
+ fileSystemSynchronizedGroups = (
+ BB0000000000000000000029 /* VPhonePatchSetExample */,
+ );
+ name = VPhonePatchSetExample;
+ productName = VPhonePatchSetExample;
+ productReference = BB0000000000000000000037 /* VPhonePatchSetExample.vphonepatchset */;
+ productType = "com.apple.product-type.bundle";
+ };
/* End PBXNativeTarget section */
/* Begin PBXProject section */
@@ -317,6 +420,8 @@
BB0000000000000000000013 /* FirmwarePatcher */,
BB0000000000000000000014 /* FirmwarePatcherTests */,
BB0000000000000000000015 /* VPhoneSignTests */,
+ BB0000000000000000000016 /* VPhonePatchKit */,
+ BB0000000000000000000017 /* VPhonePatchSetExample */,
);
};
/* End PBXProject section */
@@ -357,8 +462,32 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
+ BB0000000000000000000056 /* Sources */ = {
+ isa = PBXSourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ BB0000000000000000000057 /* Sources */ = {
+ isa = PBXSourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
/* End PBXSourcesBuildPhase section */
+/* Begin PBXResourcesBuildPhase section */
+ BB0000000000000000000058 /* Resources */ = {
+ isa = PBXResourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXResourcesBuildPhase section */
+
/* Begin PBXTargetDependency section */
BB0000000000000000000121 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
@@ -380,6 +509,31 @@
target = BB0000000000000000000012 /* VPhoneSign */;
targetProxy = BB0000000000000000000128 /* PBXContainerItemProxy */;
};
+ BB0000000000000000000129 /* PBXTargetDependency */ = {
+ isa = PBXTargetDependency;
+ target = BB0000000000000000000016 /* VPhonePatchKit */;
+ targetProxy = BB0000000000000000000130 /* PBXContainerItemProxy */;
+ };
+ BB0000000000000000000131 /* PBXTargetDependency */ = {
+ isa = PBXTargetDependency;
+ target = BB0000000000000000000016 /* VPhonePatchKit */;
+ targetProxy = BB0000000000000000000132 /* PBXContainerItemProxy */;
+ };
+ BB0000000000000000000133 /* PBXTargetDependency */ = {
+ isa = PBXTargetDependency;
+ target = BB0000000000000000000016 /* VPhonePatchKit */;
+ targetProxy = BB0000000000000000000134 /* PBXContainerItemProxy */;
+ };
+ BB0000000000000000000135 /* PBXTargetDependency */ = {
+ isa = PBXTargetDependency;
+ target = BB0000000000000000000016 /* VPhonePatchKit */;
+ targetProxy = BB0000000000000000000136 /* PBXContainerItemProxy */;
+ };
+ BB0000000000000000000137 /* PBXTargetDependency */ = {
+ isa = PBXTargetDependency;
+ target = BB0000000000000000000017 /* VPhonePatchSetExample */;
+ targetProxy = BB0000000000000000000138 /* PBXContainerItemProxy */;
+ };
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
@@ -399,6 +553,10 @@
"$(SRCROOT)/../../.build/XcodeKit/Build/Products/$(CONFIGURATION)",
"$(SRCROOT)/../../.build/XcodeRestore/Build/Products/$(CONFIGURATION)",
);
+ LD_RUNPATH_SEARCH_PATHS = (
+ "@executable_path/../Frameworks",
+ "@executable_path",
+ );
MACOSX_DEPLOYMENT_TARGET = 15.0;
OTHER_LDFLAGS = (
"$(inherited)",
@@ -436,6 +594,10 @@
"$(SRCROOT)/../../.build/XcodeKit/Build/Products/$(CONFIGURATION)",
"$(SRCROOT)/../../.build/XcodeRestore/Build/Products/$(CONFIGURATION)",
);
+ LD_RUNPATH_SEARCH_PATHS = (
+ "@executable_path/../Frameworks",
+ "@executable_path",
+ );
MACOSX_DEPLOYMENT_TARGET = 15.0;
OTHER_LDFLAGS = (
"$(inherited)",
@@ -659,6 +821,114 @@
};
name = Release;
};
+ BB000000000000000000006B /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ ARCHS = arm64;
+ BUILD_LIBRARY_FOR_DISTRIBUTION = YES;
+ CODE_SIGNING_ALLOWED = NO;
+ CURRENT_PROJECT_VERSION = 1;
+ DEFINES_MODULE = YES;
+ DYLIB_COMPATIBILITY_VERSION = 1;
+ DYLIB_CURRENT_VERSION = 1;
+ DYLIB_INSTALL_NAME_BASE = "@rpath";
+ ENABLE_TESTABILITY = NO;
+ GENERATE_INFOPLIST_FILE = YES;
+ INFOPLIST_KEY_NSHumanReadableCopyright = "";
+ INSTALL_PATH = "@rpath";
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@loader_path/../Frameworks",
+ );
+ MACOSX_DEPLOYMENT_TARGET = 15.0;
+ MARKETING_VERSION = 1.0.0;
+ PRODUCT_BUNDLE_IDENTIFIER = com.vphone.patchkit;
+ PRODUCT_NAME = VPhonePatchKit;
+ SDKROOT = macosx;
+ SKIP_INSTALL = YES;
+ SWIFT_STRICT_CONCURRENCY = complete;
+ SWIFT_VERSION = 6.0;
+ };
+ name = Debug;
+ };
+ BB000000000000000000006C /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ ARCHS = arm64;
+ BUILD_LIBRARY_FOR_DISTRIBUTION = YES;
+ CODE_SIGNING_ALLOWED = NO;
+ CURRENT_PROJECT_VERSION = 1;
+ DEFINES_MODULE = YES;
+ DYLIB_COMPATIBILITY_VERSION = 1;
+ DYLIB_CURRENT_VERSION = 1;
+ DYLIB_INSTALL_NAME_BASE = "@rpath";
+ ENABLE_TESTABILITY = NO;
+ GENERATE_INFOPLIST_FILE = YES;
+ INFOPLIST_KEY_NSHumanReadableCopyright = "";
+ INSTALL_PATH = "@rpath";
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@loader_path/../Frameworks",
+ );
+ MACOSX_DEPLOYMENT_TARGET = 15.0;
+ MARKETING_VERSION = 1.0.0;
+ PRODUCT_BUNDLE_IDENTIFIER = com.vphone.patchkit;
+ PRODUCT_NAME = VPhonePatchKit;
+ SDKROOT = macosx;
+ SKIP_INSTALL = YES;
+ SWIFT_STRICT_CONCURRENCY = complete;
+ SWIFT_VERSION = 6.0;
+ };
+ name = Release;
+ };
+ BB000000000000000000006D /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ ARCHS = arm64;
+ CODE_SIGNING_ALLOWED = NO;
+ GENERATE_INFOPLIST_FILE = YES;
+ INFOPLIST_KEY_NSHumanReadableCopyright = "";
+ LD_RUNPATH_SEARCH_PATHS = (
+ "@executable_path/../Frameworks",
+ "@loader_path/../../..",
+ );
+ MACOSX_DEPLOYMENT_TARGET = 15.0;
+ PRODUCT_BUNDLE_IDENTIFIER = com.vphone.patchset.example;
+ PRODUCT_NAME = VPhonePatchSetExample;
+ SDKROOT = macosx;
+ SKIP_INSTALL = YES;
+ SWIFT_STRICT_CONCURRENCY = complete;
+ SWIFT_VERSION = 6.0;
+ WRAPPER_EXTENSION = vphonepatchset;
+ };
+ name = Debug;
+ };
+ BB000000000000000000006E /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ ARCHS = arm64;
+ CODE_SIGNING_ALLOWED = NO;
+ GENERATE_INFOPLIST_FILE = YES;
+ INFOPLIST_KEY_NSHumanReadableCopyright = "";
+ LD_RUNPATH_SEARCH_PATHS = (
+ "@executable_path/../Frameworks",
+ "@loader_path/../../..",
+ );
+ MACOSX_DEPLOYMENT_TARGET = 15.0;
+ PRODUCT_BUNDLE_IDENTIFIER = com.vphone.patchset.example;
+ PRODUCT_NAME = VPhonePatchSetExample;
+ SDKROOT = macosx;
+ SKIP_INSTALL = YES;
+ SWIFT_STRICT_CONCURRENCY = complete;
+ SWIFT_VERSION = 6.0;
+ WRAPPER_EXTENSION = vphonepatchset;
+ };
+ name = Release;
+ };
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
@@ -716,6 +986,24 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
+ BB0000000000000000000086 /* Build configuration list for PBXNativeTarget "VPhonePatchKit" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ BB000000000000000000006B /* Debug */,
+ BB000000000000000000006C /* Release */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
+ BB0000000000000000000087 /* Build configuration list for PBXNativeTarget "VPhonePatchSetExample" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ BB000000000000000000006D /* Debug */,
+ BB000000000000000000006E /* Release */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
/* End XCConfigurationList section */
/* Begin XCRemoteSwiftPackageReference section */
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
index dfaffadb..d71de231 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
@@ -90,6 +90,9 @@ struct VPhoneCustomFirmwareInstaller {
let bundleDirectory = try pinBundle(owner: callerUID)
let bundlePath = try bundleDirectory.path
+ // Which guest patches to apply, as `fw patch` resolved them. Read through
+ // the pinned descriptor so root never follows a link out of the bundle.
+ let plan = readPatchPlan(in: bundleDirectory)
let disk = try openDiskImage(in: bundleDirectory, path: bundlePath, owner: callerUID)
let diskPath = (bundlePath as NSString).appendingPathComponent("Disk.img")
let busy = try VPhoneProcessRunner.runCapturing(
@@ -202,7 +205,14 @@ struct VPhoneCustomFirmwareInstaller {
// is left open to hold the volume busy when it is unmounted.
let systemRoot = try openGuestVolume("system", device: "\(container)s1", in: work)
let dataRoot = try openGuestVolume("data", device: "\(container)s3", in: work)
- try installMounted(system: systemRoot, data: dataRoot, restore: restore, work: work, owner: callerUID)
+ try installMounted(
+ system: systemRoot,
+ data: dataRoot,
+ restore: restore,
+ work: work,
+ owner: callerUID,
+ plan: plan,
+ )
}
try patchPreboot(volumes: volumes, work: work)
_ = try tool("/sbin/umount", [data.path])
@@ -384,26 +394,51 @@ struct VPhoneCustomFirmwareInstaller {
restore: VPhoneConfinedDirectory,
work: WorkDirectory,
owner: uid_t?,
+ plan: VPhoneVirtualMachinePatchPlan?,
) throws {
+ /// Whether the VM's patch plan turned this guest patch on.
+ ///
+ /// A VM with no plan — one created before presets, or patched by a build
+ /// that had none — gets every patch, which is what it was restored with.
+ func on(_ identifier: String) -> Bool {
+ guard let plan else { return true }
+ guard plan.isEnabled(identifier) else {
+ print(" [·] \(identifier): off in preset \(plan.presetIdentifier)")
+ return false
+ }
+ return true
+ }
+
try installCryptexes(restore: restore, system: system, work: work, owner: owner)
let version = try productVersion(system: system)
let dsc = try verifiedDyldCacheDirectory(system: system)
+ // The version branches stay: they and the declarations' applicability say
+ // the same thing, and this is what a VM with no plan still follows.
if version.hasPrefix("27.") {
- try patch("patch-iomfb-force-kern", [dsc])
- try patch("patch-dsc-maxslide", [dsc])
- try patch("patch-lsd-embedded-reg", [dsc])
- try patch("patch-xpc-lwcr", [dsc])
- try patch("patch-lockdown-mode", [dsc])
+ if on("iomfb_force_kern") { try patch("patch-iomfb-force-kern", [dsc]) }
+ if on("dsc_maxslide.zero") { try patch("patch-dsc-maxslide", [dsc]) }
+ if on("lsd_embedded_reg.entitlement_gate") { try patch("patch-lsd-embedded-reg", [dsc]) }
+ if on("xpc_lwcr") { try patch("patch-xpc-lwcr", [dsc]) }
+ if on("lockdown_mode.sysctl_error_gate") { try patch("patch-lockdown-mode", [dsc]) }
} else if version.hasPrefix("26.0") || version.hasPrefix("18.") {
- try patch("patch-iomfb-swapend", [dsc, "--target-size", "0x560"])
+ if on("dsc.iomfb_swapend") {
+ try patch("patch-iomfb-swapend", [dsc, "--target-size", "0x560"])
+ }
} else if forceDyldSharedCacheMaxSlide {
- try patch("patch-dsc-maxslide", [dsc, "--force"])
+ // Superseded by the plan: `dsc_maxslide.zero` is pinned to iOS 27, so
+ // a VM with a plan cannot force it onto a 26.x base any more.
+ if on("dsc_maxslide.zero") { try patch("patch-dsc-maxslide", [dsc, "--force"]) }
}
// These former EXP patches pair with the kernel OID rename and the
// camera DeviceTree additions in the public JB firmware pipeline.
- try patch("patch-hv-vmm-dsc", [dsc])
- try patch("patch-camera-dsc", [dsc, (dsc as NSString).appendingPathComponent("dyld_shared_cache_arm64e")])
- if let build = spoofBuild {
+ if on("hv_vmm_dsc") { try patch("patch-hv-vmm-dsc", [dsc]) }
+ if on("camera_dsc") {
+ try patch("patch-camera-dsc", [dsc, (dsc as NSString).appendingPathComponent("dyld_shared_cache_arm64e")])
+ }
+ // The preset's own parameter first; `SPOOF_BUILD` still works for a VM
+ // whose preset does not set one.
+ let buildVersion = plan?.parameters[FirmwareGuestSystemPatchSet.buildVersionParameter] ?? spoofBuild
+ if let build = buildVersion, !build.isEmpty, on("guest.build_version") {
for path in [
"System/Library/CoreServices/SystemVersion.plist",
"System/Cryptexes/OS/System/Library/CoreServices/SystemVersion.plist",
@@ -411,14 +446,16 @@ struct VPhoneCustomFirmwareInstaller {
try patchCopy(of: path, in: system, work: work, verb: "patch-build-version", arguments: [build])
}
}
- try patchMachO(
- system: system,
- work: work,
- path: "usr/libexec/seputil",
- verb: "patch-seputil",
- identifier: "com.apple.seputil",
- )
- if version.hasPrefix("27.") {
+ if on("seputil.gigalocker_uuid") {
+ try patchMachO(
+ system: system,
+ work: work,
+ path: "usr/libexec/seputil",
+ verb: "patch-seputil",
+ identifier: "com.apple.seputil",
+ )
+ }
+ if version.hasPrefix("27."), on("diskimagesiod.is_mount_complete") {
try patchMachO(
system: system,
work: work,
@@ -427,38 +464,63 @@ struct VPhoneCustomFirmwareInstaller {
preserveEntitlements: true,
)
}
- try renameGigalocker(data: data)
- try installGPUBundle(restore: restore, system: system, owner: owner)
- try patchMachO(
- system: system,
- work: work,
- path: "usr/libexec/launchd_cache_loader",
- verb: "patch-launchd-cache-loader",
- identifier: "com.apple.launchd_cache_loader",
- )
- try patchMachO(
- system: system,
- work: work,
- path: "usr/libexec/mobileactivationd",
- verb: "patch-mobileactivationd",
- )
- try patchWatchdog(system: system, work: work)
- try installVphoned(system: system, work: work)
- try installEnvironment(system: system)
- try patchMachO(
- system: system,
- work: work,
- path: "sbin/launchd",
- verb: "patch-launchd-jetsam",
- preserveEntitlements: true,
- injectedDylibPath: "/vh",
- )
- try patchDebugserver(system: system, work: work)
- if version.hasPrefix("27.") {
+ if on("guest.gigalocker_rename") { try renameGigalocker(data: data) }
+ if on("guest.gpu_bundle") {
+ try installGPUBundle(restore: restore, system: system, owner: owner)
+ }
+ if on("launchd_cache_loader.unsecure_cache_gate") {
+ try patchMachO(
+ system: system,
+ work: work,
+ path: "usr/libexec/launchd_cache_loader",
+ verb: "patch-launchd-cache-loader",
+ identifier: "com.apple.launchd_cache_loader",
+ )
+ }
+ if on("mobileactivationd.should_hactivate") {
+ try patchMachO(
+ system: system,
+ work: work,
+ path: "usr/libexec/mobileactivationd",
+ verb: "patch-mobileactivationd",
+ )
+ }
+ if on("watchdogd.hv_vmm_cache") { try patchWatchdog(system: system, work: work) }
+ if on("guest.vphoned") { try installVphoned(system: system, work: work) }
+ if on("guest.environment") { try installEnvironment(system: system) }
+ if on("launchd_jetsam.panic_guard_bypass") {
+ try patchMachO(
+ system: system,
+ work: work,
+ path: "sbin/launchd",
+ verb: "patch-launchd-jetsam",
+ preserveEntitlements: true,
+ injectedDylibPath: "/vh",
+ )
+ }
+ if on("guest.debugserver") { try patchDebugserver(system: system, work: work) }
+ if version.hasPrefix("27."), on("campo.entitlements") {
try patchCampo(system: system, work: work)
}
}
+ /// The plan `fw patch` wrote into the VM, or nil when it never ran with one.
+ private func readPatchPlan(in bundleDirectory: VPhoneConfinedDirectory) -> VPhoneVirtualMachinePatchPlan? {
+ guard let data = try? bundleDirectory.readData(VPhonePatchPresetStore.planFileName) else {
+ print("[*] No patch plan recorded; applying every guest patch")
+ return nil
+ }
+ guard let plan = try? PropertyListDecoder().decode(
+ VPhoneVirtualMachinePatchPlan.self,
+ from: data,
+ ) else {
+ print("[!] \(VPhonePatchPresetStore.planFileName) is unreadable; applying every guest patch")
+ return nil
+ }
+ print("[*] Patch preset: \(plan.presetIdentifier) (\(plan.enabledPatches.count) patches on)")
+ return plan
+ }
+
/// The dsc verbs patch a multi-gigabyte folder in place, too large to
/// stage. Open it without following any link, require plain single-link
/// files in it, and hand the tools that verified path. The path is
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift
index fec266a0..c0ad3360 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift
@@ -37,6 +37,7 @@
import ArgumentParser
import FirmwarePatcher
import Foundation
+import VPhonePatchKit
/// Where these verbs send patcher progress: stdout, like the Python.
private let machOVerbLog: @Sendable (String) -> Void = { print($0) }
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift
index c67ddbf3..6567ef9d 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift
@@ -12,6 +12,8 @@ struct VPhoneFirmwareCommand: ParsableCommand {
VPhoneFirmwareInspectCommand.self,
VPhoneFirmwarePrepareCommand.self,
VPhoneFirmwarePatchCommand.self,
+ VPhoneFirmwarePatchesCommand.self,
+ VPhoneFirmwareSetPatchesCommand.self,
VPhoneFirmwareManifestCommand.self,
VPhoneFirmwareListCommand.self,
VPhoneFirmwareResolveCommand.self,
@@ -291,9 +293,11 @@ struct VPhoneFirmwarePatchCommand: ParsableCommand {
@OptionGroup var lib: VPhoneLibraryOption
@Argument(help: "VM name") var name: String?
- @Flag(name: .customLong("force-exc-guard"), help: "Force the EXC_GUARD disable patch") var forceExcGuard = false
- @Flag(name: .customLong("frida"), help: "Opt in to Frida Stalker kernel relaxations (jb/exp only)")
- var frida = false
+ @Option(
+ name: .customLong("preset"),
+ help: "Patch preset to apply. Defaults to the VM's recorded choice, or standard.",
+ )
+ var preset: String?
@Flag(name: .shortAndLong, help: "Suppress per-component progress") var quiet = false
func run() throws {
@@ -303,16 +307,190 @@ struct VPhoneFirmwarePatchCommand: ParsableCommand {
try? VPhoneHostFilePermissions.makeAccessible(at: bundle.url)
}
+ // An explicit --preset wins and is remembered, so `cfw install` and a
+ // later re-patch agree without the flag being repeated.
+ var selection = VPhonePatchPresetStore.selection(forVM: bundle.url)
+ if let preset {
+ selection.presetIdentifier = preset
+ }
+ guard let resolved = VPhonePatchPresetStore.preset(named: selection.presetIdentifier) else {
+ let available = VPhonePatchPresetStore.availablePresets().map(\.identifier)
+ throw ValidationError(
+ "Unknown patch preset '\(selection.presetIdentifier)'. Available: \(available.joined(separator: ", "))",
+ )
+ }
+
let pipeline = FirmwarePipeline(
vmDirectory: bundle.url,
variant: .jb,
verbose: !quiet,
noBinpack: true,
- forceExcGuard: forceExcGuard,
- enableFrida: frida,
+ preset: resolved,
+ blockedPatches: Set(selection.blockedPatches),
+ allowedPatches: Set(selection.allowedPatches),
)
let records = try pipeline.patchAll()
+
+ if let plan = pipeline.resolvedPlan {
+ try VPhonePatchPresetStore.write(selection, forVM: bundle.url)
+ try VPhonePatchPresetStore.write(
+ VPhoneVirtualMachinePatchPlan(
+ plan: plan,
+ iOSBase: pipeline.baseProductVersion,
+ cloudOS: pipeline.cloudOSProductVersion,
+ ),
+ forVM: bundle.url,
+ )
+ }
+
+ try VPhoneHostFilePermissions.makeAccessible(at: bundle.url)
+ print("[fw patch] applied \(records.count) JB patches"
+ + " (preset \(selection.presetIdentifier))")
+ }
+}
+
+// MARK: - patches
+
+struct VPhoneFirmwarePatchesCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "patches",
+ abstract: "List the patch sets, presets and individual patches this bundle can apply",
+ )
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Argument(help: "VM name, to report what it is set to") var name: String?
+ @Option(name: .customLong("preset"), help: "Report against this preset instead of the VM's choice")
+ var preset: String?
+ @Flag(name: .customLong("json"), help: "Emit machine-readable output for a UI")
+ var json = false
+
+ func run() throws {
+ // A VM is optional: without one, this reports what the bundle can do.
+ var selection = VPhoneVirtualMachinePatchSelection()
+ var vmName: String?
+ if let name {
+ let resolvedName = try VPhoneVirtualMachineSelection.resolveExisting(name, in: lib.library)
+ vmName = resolvedName
+ selection = VPhonePatchPresetStore.selection(forVM: try lib.library.bundle(named: resolvedName).url)
+ }
+ if let preset {
+ selection.presetIdentifier = preset
+ }
+
+ let presets = VPhonePatchPresetStore.availablePresets()
+ guard let active = presets.first(where: { $0.identifier == selection.presetIdentifier }) else {
+ throw ValidationError(
+ "Unknown patch preset '\(selection.presetIdentifier)'."
+ + " Available: \(presets.map(\.identifier).joined(separator: ", "))",
+ )
+ }
+
+ let report = VPhonePatchCatalogReport(
+ vmName: vmName,
+ selection: selection,
+ activePreset: active,
+ presets: presets,
+ )
+ if json {
+ print(try report.jsonText())
+ } else {
+ print(report.text())
+ }
+ }
+}
+
+// MARK: - set-patches
+
+/// Records what a VM applies, without patching anything.
+///
+/// This is the write half of `fw patches`: the Launchpad's patch editor reads the
+/// JSON, composes the checkmarks onto the preset, and hands the difference back
+/// here. Keeping it a verb of its own means the app never writes into a VM bundle
+/// itself, and a person can make the same edit from a terminal.
+struct VPhoneFirmwareSetPatchesCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "set-patches",
+ abstract: "Record which patches a VM applies, for the next fw patch",
+ discussion: """
+ Replaces the VM's PatchSelection.plist. Every run writes the whole record:
+ --block and --allow name the complete lists, so a run naming neither drops
+ the VM's overrides and it follows its preset again.
+
+ Only differences from the preset are stored. An identifier the preset
+ already agrees with is dropped, so a later preset revision still reaches a
+ VM whose boxes were never touched.
+
+ Nothing is patched here. The choice applies the next time `fw patch` runs
+ for the VM, and `cfw install` follows the plan that run records.
+ """,
+ )
+
+ @OptionGroup var lib: VPhoneLibraryOption
+ @Argument(help: "VM name") var name: String?
+ @Option(
+ name: .customLong("preset"),
+ help: "Preset the choice composes onto. Defaults to the VM's recorded preset.",
+ )
+ var preset: String?
+ @Option(
+ name: .customLong("block"),
+ help: ArgumentHelp("A patch the preset turns on that this VM leaves off", valueName: "patch"),
+ )
+ var block: [String] = []
+ @Option(
+ name: .customLong("allow"),
+ help: ArgumentHelp("A patch the preset leaves off that this VM turns on", valueName: "patch"),
+ )
+ var allow: [String] = []
+
+ func run() throws {
+ let name = try VPhoneVirtualMachineSelection.resolveExisting(name, in: lib.library)
+ let bundle = try lib.library.bundle(named: name)
+
+ var selection = VPhonePatchPresetStore.selection(forVM: bundle.url)
+ if let preset {
+ selection.presetIdentifier = preset
+ }
+ guard let resolved = VPhonePatchPresetStore.preset(named: selection.presetIdentifier) else {
+ let available = VPhonePatchPresetStore.availablePresets().map(\.identifier)
+ throw ValidationError(
+ "Unknown patch preset '\(selection.presetIdentifier)'. Available: \(available.joined(separator: ", "))",
+ )
+ }
+
+ let declarations = FirmwarePatchSetCatalog.allDeclarations
+ let declared = Set(declarations.map(\.identifier))
+ // A typo would otherwise write a list that turns nothing on or off.
+ let unknown = Set(block + allow).subtracting(declared).sorted()
+ guard unknown.isEmpty else {
+ throw ValidationError(
+ "No patch declares \(unknown.joined(separator: ", ")). Run `fw patches` for the identifiers.",
+ )
+ }
+ let contradictory = Set(block).intersection(allow).sorted()
+ guard contradictory.isEmpty else {
+ throw ValidationError(
+ "\(contradictory.joined(separator: ", ")) cannot be both blocked and allowed.",
+ )
+ }
+
+ // Only differences reach the plist, whatever the caller passed.
+ let included = VPhonePatchCatalogReport.patchesInPreset(resolved)
+ selection.blockedPatches = Set(block).intersection(included).sorted()
+ selection.allowedPatches = Set(allow).subtracting(included).sorted()
+
+ let essential = Set(declarations.filter(\.bootEssential).map(\.identifier))
+ let essentialOff = Set(selection.blockedPatches).intersection(essential).sorted()
+ if !essentialOff.isEmpty {
+ FileHandle.standardError.write(Data(
+ ("warning: \(essentialOff.count) boot-essential patch(es) are off — the VM may not boot: "
+ + "\(essentialOff.joined(separator: ", "))\n").utf8,
+ ))
+ }
+
+ try VPhonePatchPresetStore.write(selection, forVM: bundle.url)
try VPhoneHostFilePermissions.makeAccessible(at: bundle.url)
- print("[fw patch] applied \(records.count) JB patches")
+ print("[fw set-patches] \(name): preset \(selection.presetIdentifier)"
+ + ", \(selection.blockedPatches.count) off, \(selection.allowedPatches.count) on")
}
}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchCatalogReport.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchCatalogReport.swift
new file mode 100644
index 00000000..7bf54f29
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchCatalogReport.swift
@@ -0,0 +1,186 @@
+// VPhonePatchCatalogReport.swift — The full patch set, as text or as JSON.
+//
+// One report serves two readers. `vphone-cli fw patches` prints it for a person,
+// and `--json` hands the same content to the Launchpad's patch editor, which
+// renders it as the checkmark list. The UI is therefore never a second copy of
+// the catalogue: it shows whatever this bundle declares, including patches from a
+// set the app has never heard of.
+//
+// The report says what each patch *is*, not whether it would land on some VM: a
+// version gate is evaluated at patch time against the two OS versions, which the
+// editor does not know. `applicability` is carried through so the UI can say
+// "iOS 27 only" beside the box.
+
+import FirmwarePatcher
+import Foundation
+import VPhonePatchKit
+
+public struct VPhonePatchCatalogReport: Sendable {
+ public let vmName: String?
+ public let selection: VPhoneVirtualMachinePatchSelection
+ public let activePreset: VPhonePatchPreset
+ public let presets: [VPhonePatchPreset]
+
+ public init(
+ vmName: String?,
+ selection: VPhoneVirtualMachinePatchSelection,
+ activePreset: VPhonePatchPreset,
+ presets: [VPhonePatchPreset],
+ ) {
+ self.vmName = vmName
+ self.selection = selection
+ self.activePreset = activePreset
+ self.presets = presets
+ }
+
+ // MARK: - JSON
+
+ /// One patch as the editor sees it.
+ struct PatchEntry: Codable, Sendable {
+ let identifier: String
+ let title: String
+ let summary: String
+ let patchSet: String
+ let patchSetName: String
+ let target: String
+ let applicability: String
+ let bootEssential: Bool
+ /// Whether the preset turns it on, before any version gate.
+ let inPreset: Bool
+ /// Whether this VM's own choice leaves it on.
+ let enabled: Bool
+ }
+
+ struct PresetEntry: Codable, Sendable {
+ let identifier: String
+ let title: String
+ let summary: String
+ let patchSets: [String]
+ }
+
+ struct Payload: Codable, Sendable {
+ let vmName: String?
+ let activePreset: String
+ let blockedPatches: [String]
+ let allowedPatches: [String]
+ let presets: [PresetEntry]
+ let patches: [PatchEntry]
+ }
+
+ /// The patches a preset turns on, before any version gate.
+ ///
+ /// `fw set-patches` normalises a VM's record against this, so both readers of
+ /// "is this patch in the preset" answer from one rule.
+ public static func patchesInPreset(_ preset: VPhonePatchPreset) -> Set<String> {
+ let presetSets = Set(preset.patchSets.map(\.identifier))
+ var result: Set<String> = []
+ for set in FirmwarePatchSetCatalog.bundled where presetSets.contains(set.identifier) {
+ for patch in set.patches where preset.selection.includes(patch.identifier) {
+ result.insert(patch.identifier)
+ }
+ }
+ return result
+ }
+
+ /// Every patch every bundled set declares, not just the active preset's.
+ ///
+ /// The editor needs the whole catalogue to show a patch that switching preset
+ /// would bring in, so `inPreset` carries the distinction rather than the list
+ /// being filtered.
+ func entries() -> [PatchEntry] {
+ let blocked = Set(selection.blockedPatches)
+ let allowed = Set(selection.allowedPatches)
+ let presetSets = Set(activePreset.patchSets.map(\.identifier))
+ let included = Self.patchesInPreset(activePreset)
+ var result: [PatchEntry] = []
+ for set in FirmwarePatchSetCatalog.bundled {
+ let setIsInPreset = presetSets.contains(set.identifier)
+ for patch in set.patches {
+ let inPreset = included.contains(patch.identifier)
+ result.append(PatchEntry(
+ identifier: patch.identifier,
+ title: patch.title,
+ summary: patch.summary,
+ patchSet: set.identifier,
+ patchSetName: set.name,
+ target: patch.target.description,
+ applicability: patch.applicability.description,
+ bootEssential: patch.bootEssential,
+ inPreset: inPreset,
+ enabled: setIsInPreset
+ && (inPreset || allowed.contains(patch.identifier))
+ && !blocked.contains(patch.identifier),
+ ))
+ }
+ }
+ return result
+ }
+
+ public func jsonText() throws -> String {
+ let payload = Payload(
+ vmName: vmName,
+ activePreset: activePreset.identifier,
+ blockedPatches: selection.blockedPatches.sorted(),
+ allowedPatches: selection.allowedPatches.sorted(),
+ presets: presets.map {
+ PresetEntry(
+ identifier: $0.identifier,
+ title: $0.title,
+ summary: $0.summary,
+ patchSets: $0.patchSets.map(\.identifier),
+ )
+ },
+ patches: entries(),
+ )
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ let data = try encoder.encode(payload)
+ return String(decoding: data, as: UTF8.self)
+ }
+
+ // MARK: - Text
+
+ public func text() -> String {
+ var lines: [String] = []
+ if let vmName {
+ lines.append("VM: \(vmName)")
+ }
+ lines.append("Preset: \(activePreset.identifier) — \(activePreset.title)")
+ if !activePreset.summary.isEmpty {
+ lines.append(" \(activePreset.summary)")
+ }
+ if !selection.blockedPatches.isEmpty {
+ lines.append("Off: \(selection.blockedPatches.sorted().joined(separator: ", "))")
+ }
+ if !selection.allowedPatches.isEmpty {
+ lines.append("On: \(selection.allowedPatches.sorted().joined(separator: ", "))")
+ }
+
+ lines.append("")
+ lines.append("Presets:")
+ for preset in presets {
+ let marker = preset.identifier == activePreset.identifier ? "*" : " "
+ lines.append(" \(marker) \(preset.identifier.padding(toLength: 12, withPad: " ", startingAt: 0))"
+ + " \(preset.title)")
+ }
+
+ let entries = entries()
+ lines.append("")
+ lines.append("Patches (\(entries.filter(\.enabled).count) of \(entries.count) on):")
+ var lastSet = ""
+ for entry in entries {
+ if entry.patchSet != lastSet {
+ lines.append("")
+ lines.append(" \(entry.patchSetName) [\(entry.patchSet)]")
+ lastSet = entry.patchSet
+ }
+ let box = entry.enabled ? "[x]" : "[ ]"
+ var notes: [String] = []
+ if entry.applicability != "any" { notes.append(entry.applicability) }
+ if entry.bootEssential { notes.append("boot-essential") }
+ let suffix = notes.isEmpty ? "" : " (\(notes.joined(separator: ", ")))"
+ lines.append(" \(box) \(entry.identifier)\(suffix)")
+ }
+ return lines.joined(separator: "\n")
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchPresetStore.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchPresetStore.swift
new file mode 100644
index 00000000..8fda4eb3
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchPresetStore.swift
@@ -0,0 +1,221 @@
+// VPhonePatchPresetStore.swift — Finding presets, and remembering a VM's choice.
+//
+// Three files matter here.
+//
+// `VPhone.bundle/Contents/Resources/patches_presets/*.plist` are the presets the
+// bundle ships. They are prewritten and reviewed; nothing in the tool writes one.
+//
+// `<vm>/PatchSelection.plist` is the VM's choice: which preset, and which patches
+// the user unchecked. It is written when the VM is created or edited, and read by
+// `fw patch`.
+//
+// `<vm>/PatchPlan.plist` is what `fw patch` actually resolved, written after the
+// boot chain is patched. `cfw install` reads it so the guest half of the install
+// applies the same selection the boot chain was built with, without resolving the
+// preset a second time against versions that may since have changed.
+
+import FirmwarePatcher
+import Foundation
+import VPhoneCoreKit
+import VPhonePatchKit
+
+// MARK: - VM Records
+
+/// A VM's patch choice: a preset, plus the boxes the user changed.
+///
+/// Only the differences from the preset are stored. A patch nobody touched follows
+/// whatever the preset says, so a later preset revision reaches VMs that never
+/// overrode it.
+public struct VPhoneVirtualMachinePatchSelection: Codable, Sendable, Hashable {
+ public var presetIdentifier: String
+ /// Patches the user unchecked.
+ public var blockedPatches: [String]
+ /// Patches the user checked that the preset leaves off. Each still has to pass
+ /// its own version gate, so checking a box cannot put a patch on an OS it was
+ /// never meant for.
+ public var allowedPatches: [String]
+
+ public init(
+ presetIdentifier: String = VPhonePatchPreset.standardIdentifier,
+ blockedPatches: [String] = [],
+ allowedPatches: [String] = [],
+ ) {
+ self.presetIdentifier = presetIdentifier
+ self.blockedPatches = blockedPatches
+ self.allowedPatches = allowedPatches
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case presetIdentifier = "Preset"
+ case blockedPatches = "BlockedPatches"
+ case allowedPatches = "AllowedPatches"
+ }
+
+ public init(from decoder: any Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ presetIdentifier = try container.decodeIfPresent(String.self, forKey: .presetIdentifier)
+ ?? VPhonePatchPreset.standardIdentifier
+ blockedPatches = try container.decodeIfPresent([String].self, forKey: .blockedPatches) ?? []
+ allowedPatches = try container.decodeIfPresent([String].self, forKey: .allowedPatches) ?? []
+ }
+}
+
+/// What `fw patch` resolved, recorded for `cfw install`.
+public struct VPhoneVirtualMachinePatchPlan: Codable, Sendable, Hashable {
+ public var presetIdentifier: String
+ public var patchSets: [String]
+ public var enabledPatches: [String]
+ public var iOSBaseVersion: String?
+ public var cloudOSVersion: String?
+ /// The preset's knobs, carried through so `cfw install` reads the same values
+ /// the boot chain was built with rather than resolving the preset again.
+ public var parameters: [String: String]
+
+ public init(plan: VPhonePatchPlan, iOSBase: VPhoneVersion?, cloudOS: VPhoneVersion?) {
+ presetIdentifier = plan.presetIdentifier
+ patchSets = plan.patchSets.map(\.identifier)
+ enabledPatches = plan.enabled.sorted()
+ iOSBaseVersion = iOSBase?.description
+ cloudOSVersion = cloudOS?.description
+ parameters = plan.parameters
+ }
+
+ /// Whether the patch declaring `identifier` was turned on for this VM.
+ public func isEnabled(_ identifier: String) -> Bool {
+ enabledPatches.contains(identifier)
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case presetIdentifier = "Preset"
+ case patchSets = "PatchSets"
+ case enabledPatches = "EnabledPatches"
+ case iOSBaseVersion = "IOSBaseVersion"
+ case cloudOSVersion = "CloudOSVersion"
+ case parameters = "Parameters"
+ }
+
+ public init(from decoder: any Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ presetIdentifier = try container.decode(String.self, forKey: .presetIdentifier)
+ patchSets = try container.decodeIfPresent([String].self, forKey: .patchSets) ?? []
+ enabledPatches = try container.decodeIfPresent([String].self, forKey: .enabledPatches) ?? []
+ iOSBaseVersion = try container.decodeIfPresent(String.self, forKey: .iOSBaseVersion)
+ cloudOSVersion = try container.decodeIfPresent(String.self, forKey: .cloudOSVersion)
+ parameters = try container.decodeIfPresent([String: String].self, forKey: .parameters) ?? [:]
+ }
+}
+
+// MARK: - Store
+
+public enum VPhonePatchPresetStore {
+ public static let selectionFileName = "PatchSelection.plist"
+ public static let planFileName = "PatchPlan.plist"
+
+ // MARK: Presets
+
+ /// Every preset available, shipped ones first.
+ ///
+ /// A staged bundle has `Contents/Resources/patches_presets` beside the
+ /// executable. A plain Xcode build of `vphone-cli` has no such directory, so
+ /// the built-in copies stand in and `fw patch` still runs.
+ ///
+ /// `~/.vphone/patches_presets` is added after those. It is the only place a
+ /// preset naming an external `.vphonepatchset` can live: the shipped directory
+ /// is inside a sealed bundle, and a shipped preset never references a set from
+ /// outside it. A user preset cannot shadow a shipped one — an identifier
+ /// already claimed is ignored, so nothing can redefine `standard`.
+ public static func availablePresets() -> [VPhonePatchPreset] {
+ var presets: [VPhonePatchPreset] = []
+ if let directory = presetsDirectory(),
+ let shipped = try? VPhonePatchPreset.readAll(fromDirectory: directory),
+ !shipped.isEmpty
+ {
+ presets = shipped
+ } else {
+ presets = FirmwarePatchSetCatalog.builtInPresets
+ }
+ let claimed = Set(presets.map(\.identifier))
+ if let user = try? VPhonePatchPreset.readAll(fromDirectory: userPresetsDirectory()) {
+ presets.append(contentsOf: user.filter { !claimed.contains($0.identifier) })
+ }
+ return presets
+ }
+
+ /// `~/.vphone/patches_presets`, where a researcher's own presets go.
+ public static func userPresetsDirectory() -> URL {
+ VPhoneResources.userDataRoot()
+ .appendingPathComponent(VPhonePatchPreset.resourceDirectoryName, isDirectory: true)
+ }
+
+ /// The preset with this identifier, or nil.
+ public static func preset(named identifier: String) -> VPhonePatchPreset? {
+ availablePresets().first { $0.identifier == identifier }
+ }
+
+ /// `Contents/Resources/patches_presets` beside the running executable.
+ static func presetsDirectory() -> URL? {
+ // Not argv[0]: a `vphone-cli` found on PATH gets a bare name there, which
+ // would resolve the presets directory against the working directory.
+ guard let executable = Bundle.main.executableURL?.resolvingSymlinksInPath() else {
+ return nil
+ }
+ let resources = executable
+ .deletingLastPathComponent() // Contents/MacOS
+ .deletingLastPathComponent() // Contents
+ .appendingPathComponent("Resources", isDirectory: true)
+ .appendingPathComponent(VPhonePatchPreset.resourceDirectoryName, isDirectory: true)
+ var isDirectory: ObjCBool = false
+ guard FileManager.default.fileExists(atPath: resources.path, isDirectory: &isDirectory),
+ isDirectory.boolValue
+ else {
+ return nil
+ }
+ return resources
+ }
+
+ // MARK: VM Selection
+
+ /// The VM's recorded choice, or the standard preset when it has none.
+ ///
+ /// A VM created before presets existed reads as standard, which is what it was
+ /// built with.
+ public static func selection(forVM directory: URL) -> VPhoneVirtualMachinePatchSelection {
+ let url = directory.appendingPathComponent(selectionFileName)
+ guard let data = try? Data(contentsOf: url),
+ let decoded = try? PropertyListDecoder().decode(
+ VPhoneVirtualMachinePatchSelection.self,
+ from: data,
+ )
+ else {
+ return VPhoneVirtualMachinePatchSelection()
+ }
+ return decoded
+ }
+
+ public static func write(
+ _ selection: VPhoneVirtualMachinePatchSelection,
+ forVM directory: URL,
+ ) throws {
+ try write(selection, to: directory.appendingPathComponent(selectionFileName))
+ }
+
+ // MARK: VM Plan
+
+ /// What the last `fw patch` resolved for this VM, or nil if it never ran with
+ /// a preset.
+ public static func plan(forVM directory: URL) -> VPhoneVirtualMachinePatchPlan? {
+ let url = directory.appendingPathComponent(planFileName)
+ guard let data = try? Data(contentsOf: url) else { return nil }
+ return try? PropertyListDecoder().decode(VPhoneVirtualMachinePatchPlan.self, from: data)
+ }
+
+ public static func write(_ plan: VPhoneVirtualMachinePatchPlan, forVM directory: URL) throws {
+ try write(plan, to: directory.appendingPathComponent(planFileName))
+ }
+
+ private static func write(_ value: some Encodable, to url: URL) throws {
+ let encoder = PropertyListEncoder()
+ encoder.outputFormat = .xml
+ try encoder.encode(value).write(to: url, options: .atomic)
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchSetCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchSetCommand.swift
new file mode 100644
index 00000000..dc96b1ba
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchSetCommand.swift
@@ -0,0 +1,212 @@
+// VPhonePatchSetCommand.swift — `vphone-cli patchset`.
+//
+// The verbs for out-of-tree patch sets: look at one, import one, list what is
+// imported, remove one. A preset then names an imported set by identifier and path
+// and `fw patch` loads it.
+//
+// `import` is deliberately its own step rather than something `fw patch` does on
+// the fly. Loading a set runs its code in the patching process, so the moment a
+// bundle becomes loadable should be a thing the user did, with a path they typed,
+// and it should be the moment the bundle gets its ad hoc signature.
+
+import ArgumentParser
+import FirmwarePatcher
+import Foundation
+import VPhoneCoreKit
+import VPhonePatchKit
+
+struct VPhonePatchSetCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "patchset",
+ abstract: "Inspect and import .vphonepatchset bundles",
+ discussion: """
+ A patch set is a loadable bundle carrying Contents/Resources/Manifest.plist
+ and one exported symbol, vphone_patch_set_principal, returning a
+ VPhonePatchSetPrincipal. The sets compiled into this bundle need none of
+ this; these verbs are for a set built outside it.
+
+ An imported set is reached by a preset that names it:
+
+ <dict>
+ <key>Kind</key> <string>External</string>
+ <key>Identifier</key> <string>com.example.patchset.mine</string>
+ <key>Path</key> <string>~/.vphone/patchsets/com.example.patchset.mine.vphonepatchset</string>
+ </dict>
+
+ Shipped presets never do this, so such a preset goes in
+ ~/.vphone/patches_presets/ and is selected with --preset.
+
+ A loaded set can patch the boot chain only. The guest half of an install
+ runs as root and loads no external set, so a guest-side declaration would
+ promise a patch that never runs and is refused at import.
+ """,
+ subcommands: [
+ VPhonePatchSetListCommand.self,
+ VPhonePatchSetInfoCommand.self,
+ VPhonePatchSetImportCommand.self,
+ VPhonePatchSetRemoveCommand.self,
+ ],
+ defaultSubcommand: VPhonePatchSetListCommand.self,
+ )
+}
+
+// MARK: - list
+
+struct VPhonePatchSetListCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "list",
+ abstract: "List the patch sets this bundle has and the ones that were imported",
+ )
+
+ func run() throws {
+ print("Bundled (\(FirmwarePatchSetCatalog.bundled.count)):")
+ for manifest in FirmwarePatchSetCatalog.bundled {
+ print(" \(manifest.identifier) \(manifest.version)"
+ + " \(manifest.patches.count) patches \(manifest.name)")
+ }
+
+ let store = try VPhonePatchSetStore.contents()
+ let records = VPhonePatchSetStore.imported()
+ print("\nImported (\(store.count)) \(VPhonePatchSetStore.directory().path):")
+ guard !store.isEmpty else {
+ print(" none — `vphone-cli patchset import <path>` adds one")
+ return
+ }
+ for set in store {
+ let identifier = set.manifest.identifier
+ print(" \(identifier) \(set.manifest.version)"
+ + " \(set.manifest.patches.count) patches \(set.manifest.name)")
+ print(" \(Self.state(of: set, record: records[identifier]))")
+ }
+ }
+
+ /// One line on whether the set on disk is still what was imported, and whether
+ /// it would load right now.
+ private static func state(
+ of set: VPhonePatchSetBundle,
+ record: VPhoneImportedPatchSet?,
+ ) -> String {
+ do {
+ try set.requireValidSignature()
+ } catch {
+ return "signature: INVALID — \(error)"
+ }
+ guard let record else {
+ return "signature: valid; no import record, so nothing to compare against"
+ }
+ let current = (try? set.codeDirectoryHash()) ?? ""
+ guard current == record.codeDirectoryHash else {
+ return "signature: valid, but re-signed since import"
+ + " (was \(record.codeDirectoryHash.prefix(16))…, now \(current.prefix(16))…)"
+ }
+ return "signature: valid, unchanged since import"
+ }
+}
+
+// MARK: - info
+
+struct VPhonePatchSetInfoCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "info",
+ abstract: "Print what a patch set declares",
+ )
+
+ @Argument(help: "A .vphonepatchset path, or the identifier of a bundled or imported set")
+ var target: String
+
+ func run() throws {
+ let manifest = try Self.manifest(for: target)
+ print("Identifier: \(manifest.identifier)")
+ print("Name: \(manifest.name)")
+ print("Version: \(manifest.version)")
+ if !manifest.summary.isEmpty { print("Summary: \(manifest.summary)") }
+ print("Needs: PatchKit \(manifest.minimumPatchKitVersion)"
+ + " (this is \(VPhoneVersion.currentPatchKit))")
+ if !manifest.provides.isEmpty { print("Provides: \(manifest.provides.joined(separator: ", "))") }
+ if !manifest.requires.isEmpty { print("Requires: \(manifest.requires.joined(separator: ", "))") }
+ if !manifest.conflictsWith.isEmpty {
+ print("Conflicts: \(manifest.conflictsWith.joined(separator: ", "))")
+ }
+ if !manifest.after.isEmpty { print("After: \(manifest.after.joined(separator: ", "))") }
+ print("\nPatches (\(manifest.patches.count)):")
+ for patch in manifest.patches {
+ let essential = patch.bootEssential ? " [boot-essential]" : ""
+ print(" \(patch.identifier)\(essential)")
+ print(" \(patch.title) — \(patch.target)")
+ print(" applies to: \(patch.applicability)")
+ }
+ }
+
+ /// A path if it is one, otherwise an identifier looked up in the store and then
+ /// among the bundled sets.
+ static func manifest(for target: String) throws -> VPhonePatchSetManifest {
+ let expanded = (target as NSString).expandingTildeInPath
+ if FileManager.default.fileExists(atPath: expanded) {
+ return try VPhonePatchSetBundle.inspect(at: URL(fileURLWithPath: expanded)).manifest
+ }
+ let stored = VPhonePatchSetStore.url(forIdentifier: target)
+ if FileManager.default.fileExists(atPath: stored.path) {
+ return try VPhonePatchSetBundle.inspect(at: stored).manifest
+ }
+ guard let bundled = FirmwarePatchSetCatalog.manifest(identifier: target) else {
+ throw ValidationError(
+ "No patch set at \(target), and no bundled or imported set with that identifier."
+ + " Run `vphone-cli patchset list`.",
+ )
+ }
+ return bundled
+ }
+}
+
+// MARK: - import
+
+struct VPhonePatchSetImportCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "import",
+ abstract: "Copy a .vphonepatchset into the store, ad hoc signing it if it is unsigned",
+ discussion: """
+ Checks the manifest first — including that every patch targets the boot
+ chain — then copies the bundle to ~/.vphone/patchsets under the identifier
+ it declares, ad hoc signs the copy if it arrived unsigned or invalid, and
+ verifies that the result passes the same check `fw patch` will make.
+
+ The set's own code never runs here.
+ """,
+ )
+
+ @Argument(help: "Path to the .vphonepatchset to import")
+ var path: String
+
+ @Flag(name: .customLong("replace"), help: "Overwrite a set already imported under this identifier")
+ var replace = false
+
+ func run() throws {
+ let source = URL(fileURLWithPath: (path as NSString).expandingTildeInPath)
+ let installed = try VPhonePatchSetStore.importSet(from: source, replacing: replace)
+ print("[patchset import] \(installed.manifest.identifier) \(installed.manifest.version)"
+ + " — \(installed.manifest.patches.count) patches")
+ print(" \(installed.url.path)")
+ print(" cdhash \(try installed.codeDirectoryHash())")
+ // The real directory, not `~/.vphone`: a run with VPHONE_ROOT set reads its
+ // presets from there, and a hint naming the wrong path is worse than none.
+ print("\nName it from a preset in \(VPhonePatchPresetStore.userPresetsDirectory().path)/ as:")
+ print(" Kind External, Identifier \(installed.manifest.identifier), Path \(installed.url.path)")
+ }
+}
+
+// MARK: - remove
+
+struct VPhonePatchSetRemoveCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "remove",
+ abstract: "Delete an imported patch set",
+ )
+
+ @Argument(help: "Identifier of the imported set")
+ var identifier: String
+
+ func run() throws {
+ try VPhonePatchSetStore.remove(identifier: identifier)
+ print("[patchset remove] \(identifier)")
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchSetStore.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchSetStore.swift
new file mode 100644
index 00000000..8308a31c
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchSetStore.swift
@@ -0,0 +1,207 @@
+// VPhonePatchSetStore.swift — Where an imported `.vphonepatchset` lives.
+//
+// The store is `~/.vphone/patchsets` (or `$VPHONE_ROOT/patchsets`). Importing a
+// set copies it there under its own identifier and ad hoc signs it if it arrived
+// unsigned, which is the one step that turns "a bundle somebody built" into "a
+// bundle this tool will load".
+//
+// What the store is not: a trust boundary. A signature is re-verified from disk on
+// every load, and that is what catches a set altered since it was signed. The
+// recorded cdhash here is provenance — `patchset list` prints whether the set on
+// disk is still the one that was imported — and the strong, pinned form of that
+// check belongs to the Launchpad helper, which is the only component that acts as
+// root. Root `cfw install` loads no external set at all, so a same-user rewrite of
+// a bundle in this store crosses no privilege boundary that a rewrite of the preset
+// naming it would not cross anyway.
+
+import Foundation
+import VPhoneCoreKit
+import VPhonePatchKit
+
+// MARK: - Record
+
+/// What was imported, so `patchset list` can say whether it still matches.
+public struct VPhoneImportedPatchSet: Codable, Sendable, Hashable {
+ public var identifier: String
+ public var name: String
+ public var version: String
+ public var codeDirectoryHash: String
+ public var importedAt: Date
+
+ private enum CodingKeys: String, CodingKey {
+ case identifier = "Identifier"
+ case name = "Name"
+ case version = "Version"
+ case codeDirectoryHash = "CDHash"
+ case importedAt = "ImportedAt"
+ }
+}
+
+// MARK: - Store
+
+public enum VPhonePatchSetStore {
+ public static let directoryName = "patchsets"
+ public static let recordFileName = "Imported.plist"
+
+ /// `~/.vphone/patchsets`, created on demand.
+ public static func directory() -> URL {
+ VPhoneResources.userDataRoot().appendingPathComponent(directoryName, isDirectory: true)
+ }
+
+ /// Where a set with this identifier is kept.
+ public static func url(forIdentifier identifier: String) -> URL {
+ directory().appendingPathComponent(
+ "\(identifier).\(VPhonePatchSetBundle.pathExtension)",
+ isDirectory: true,
+ )
+ }
+
+ // MARK: Records
+
+ public static func imported() -> [String: VPhoneImportedPatchSet] {
+ let url = directory().appendingPathComponent(recordFileName)
+ guard let data = try? Data(contentsOf: url),
+ let records = try? PropertyListDecoder().decode(
+ [String: VPhoneImportedPatchSet].self,
+ from: data,
+ )
+ else { return [:] }
+ return records
+ }
+
+ private static func write(_ records: [String: VPhoneImportedPatchSet]) throws {
+ let encoder = PropertyListEncoder()
+ encoder.outputFormat = .xml
+ try FileManager.default.createDirectory(at: directory(), withIntermediateDirectories: true)
+ try encoder.encode(records).write(
+ to: directory().appendingPathComponent(recordFileName),
+ options: .atomic,
+ )
+ }
+
+ // MARK: Contents
+
+ /// Every set in the store, whether or not it has a record.
+ ///
+ /// The directory is the truth; a set whose record went missing still loads, it
+ /// just cannot be checked against what was imported.
+ public static func contents() throws -> [VPhonePatchSetBundle] {
+ let directory = directory()
+ guard FileManager.default.fileExists(atPath: directory.path) else { return [] }
+ let names = try FileManager.default.contentsOfDirectory(atPath: directory.path)
+ var sets: [VPhonePatchSetBundle] = []
+ for name in names.sorted()
+ where name.hasSuffix("." + VPhonePatchSetBundle.pathExtension)
+ {
+ sets.append(try VPhonePatchSetBundle.inspect(
+ at: directory.appendingPathComponent(name, isDirectory: true),
+ ))
+ }
+ return sets
+ }
+
+ // MARK: Import
+
+ /// Validate `source`, ad hoc sign it if it is unsigned, and copy it into the
+ /// store under the identifier its manifest declares.
+ ///
+ /// The manifest is checked before anything is copied and before anything is
+ /// signed — including the rule that every declared patch targets the boot
+ /// chain — so a set that could never be loaded is never installed. Signing
+ /// happens on the copy in the store, never on the file the user pointed at.
+ ///
+ /// No code from the set runs here. Importing is not loading.
+ @discardableResult
+ public static func importSet(from source: URL, replacing: Bool = false) throws -> VPhonePatchSetBundle {
+ let candidate = try VPhonePatchSetBundle.inspect(at: source)
+ try candidate.validate(expecting: nil, requireSignature: false)
+
+ let destination = url(forIdentifier: candidate.manifest.identifier)
+ let manager = FileManager.default
+ if manager.fileExists(atPath: destination.path) {
+ guard replacing else {
+ throw VPhonePatchSetStoreError.alreadyImported(
+ identifier: candidate.manifest.identifier,
+ path: destination.path,
+ )
+ }
+ try manager.removeItem(at: destination)
+ }
+ try manager.createDirectory(at: directory(), withIntermediateDirectories: true)
+ try manager.copyItem(at: candidate.url, to: destination)
+
+ let installed = try VPhonePatchSetBundle.inspect(at: destination)
+ if (try? installed.requireValidSignature()) == nil {
+ try adHocSign(destination)
+ }
+ // Whatever we just did, the set has to pass the check the loader will make.
+ try installed.validate(expecting: candidate.manifest.identifier)
+
+ var records = imported()
+ records[installed.manifest.identifier] = VPhoneImportedPatchSet(
+ identifier: installed.manifest.identifier,
+ name: installed.manifest.name,
+ version: installed.manifest.version,
+ codeDirectoryHash: try installed.codeDirectoryHash(),
+ importedAt: Date(),
+ )
+ try write(records)
+ try VPhoneHostFilePermissions.makeDirectoryAccessible(at: destination)
+ return installed
+ }
+
+ public static func remove(identifier: String) throws {
+ let url = url(forIdentifier: identifier)
+ guard FileManager.default.fileExists(atPath: url.path) else {
+ throw VPhonePatchSetStoreError.notImported(identifier: identifier)
+ }
+ try FileManager.default.removeItem(at: url)
+ var records = imported()
+ records[identifier] = nil
+ try write(records)
+ }
+
+ // MARK: Signing
+
+ /// `codesign --force --sign -`, the same ad hoc seal the rest of this project
+ /// puts on a binary it produced. `/usr/bin/codesign` is part of macOS, not of
+ /// Xcode, so this holds on a machine with no developer tools.
+ ///
+ /// No `--deep`: signing a bundle seals its resources, which is exactly what a
+ /// set straight out of Xcode is missing — the linker ad hoc signs the Mach-O but
+ /// writes no `CodeResources`, so `codesign --verify` answers "code has no
+ /// resources but signature indicates they must be present". One pass over the
+ /// bundle fixes that, and `--deep` for signing is discouraged by Apple.
+ private static func adHocSign(_ url: URL) throws {
+ let result = try VPhoneProcessRunner.runCapturing(
+ URL(fileURLWithPath: "/usr/bin/codesign"),
+ ["--force", "--sign", "-", url.path],
+ )
+ guard result.succeeded else {
+ throw VPhonePatchSetStoreError.signingFailed(
+ path: url.path,
+ reason: (result.stderr + result.stdout)
+ .trimmingCharacters(in: .whitespacesAndNewlines),
+ )
+ }
+ }
+}
+
+// MARK: - Errors
+
+public enum VPhonePatchSetStoreError: Error, CustomStringConvertible, Sendable {
+ case alreadyImported(identifier: String, path: String)
+ case notImported(identifier: String)
+ case signingFailed(path: String, reason: String)
+
+ public var description: String {
+ switch self {
+ case let .alreadyImported(identifier, path):
+ "\(identifier) is already imported at \(path). Pass --replace to overwrite it."
+ case let .notImported(identifier):
+ "No imported patch set with identifier \(identifier)"
+ case let .signingFailed(path, reason):
+ "Could not ad hoc sign \(path): \(reason)"
+ }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VPhoneCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VPhoneCommand.swift
index b4f8d8e5..d07deb26 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VPhoneCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VPhoneCommand.swift
@@ -2,6 +2,7 @@ import ArgumentParser
import FirmwarePatcher
import Foundation
import VPhoneCoreKit
+import VPhonePatchKit
struct VPhoneCommand: ParsableCommand {
static let configuration = CommandConfiguration(
@@ -10,7 +11,7 @@ struct VPhoneCommand: ParsableCommand {
subcommands: [
VPhoneBootCommand.self, PatchFirmwareCommand.self, PatchComponentCommand.self, VPhoneVirtualMachineCommand.self,
VPhoneFirmwareCommand.self, VPhoneRestoreCommand.self, VPhoneRecoveryProbeCommand.self,
- VPhoneCustomFirmwareCommand.self,
+ VPhoneCustomFirmwareCommand.self, VPhonePatchSetCommand.self,
VPhoneHostCommand.self,
VPhoneSignCommand.self, VPhoneDumpEntitlementsCommand.self,
VPhoneArchiveCommand.self,
@@ -44,26 +45,26 @@ struct PatchFirmwareCommand: ParsableCommand {
@Flag(name: [.customShort("q"), .customLong("quiet")], help: "Suppress per-component progress output.")
var quiet: Bool = false
- @Flag(
- name: .customLong("force-exc-guard"),
- help: "Force-enable the EXC_GUARD (Mach port guard) disable patch on regular/jb/exp, even on bases where it isn't required to boot. Use if a third-party app's crash-reporting/RASP SDK trips a fatal GUARD_TYPE_MACH_PORT violation on launch. Always on for iOS 18 bases regardless of this flag.",
- )
- var forceExcGuard: Bool = false
-
- @Flag(
- name: .customLong("frida"),
- help: "Opt in to Frida Stalker kernel relaxations (existing-thread follow + repeated VM_PROT_COPY). jb/exp only.",
+ @Option(
+ name: .customLong("preset"),
+ help: "Patch preset to apply. Defaults to standard. Individual patches are selected per VM by `fw patch`, not here.",
)
- var frida: Bool = false
+ var preset: String = VPhonePatchPreset.standardIdentifier
mutating func run() throws {
+ guard let resolved = FirmwarePatchSetCatalog.builtInPresets.first(where: { $0.identifier == preset })
+ else {
+ let available = FirmwarePatchSetCatalog.builtInPresets.map(\.identifier)
+ throw ValidationError(
+ "Unknown patch preset '\(preset)'. Available: \(available.joined(separator: ", "))",
+ )
+ }
let pipeline = FirmwarePipeline(
vmDirectory: vmDirectory,
variant: .jb,
verbose: !quiet,
noBinpack: true,
- forceExcGuard: forceExcGuard,
- enableFrida: frida,
+ preset: resolved,
)
let records = try pipeline.patchAll()
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift
index b9242673..da3c73cc 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift
@@ -1,6 +1,7 @@
import ArgumentParser
import Foundation
import VPhoneCoreKit
+import VPhonePatchKit
struct VPhoneVirtualMachineCreateCommand: ParsableCommand {
static let configuration = CommandConfiguration(
@@ -23,11 +24,11 @@ struct VPhoneVirtualMachineCreateCommand: ParsableCommand {
help: "Zero the dyld cache maxSlide on non-27 bases (opt-in DSC-map fit)",
)
var forceDyldSharedCacheMaxSlide = false
- @Flag(
- name: .customLong("frida"),
- help: "Opt in to Frida Stalker kernel relaxations",
+ @Option(
+ name: .customLong("preset"),
+ help: "Patch preset for the new VM. Defaults to standard; run `fw patches` to see what each one applies.",
)
- var frida = false
+ var preset: String = VPhonePatchPreset.standardIdentifier
@Flag(
name: .customLong("keep-artifacts"),
help: "Keep the prepared restore tree after installation. Downloaded IPSWs always stay in the IPSW cache.",
@@ -61,7 +62,7 @@ struct VPhoneVirtualMachineCreateCommand: ParsableCommand {
URL(fileURLWithPath: ($0 as NSString).expandingTildeInPath, isDirectory: true)
} ?? VPhoneResources.ipswCacheDirectory(),
forceDyldSharedCacheMaxSlide: forceDyldSharedCacheMaxSlide,
- enableFrida: frida,
+ patchPreset: preset,
diskSizeGB: diskSize,
verbosity: VPhoneVerbosity(count: verboseCount),
keepArtifacts: keepArtifacts,
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swift
index f9ac9a07..cd0c49a9 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swift
@@ -1,5 +1,6 @@
import Foundation
import VPhoneCoreKit
+import VPhonePatchKit
// MARK: - Create Options
@@ -11,7 +12,9 @@ public extension VPhoneVirtualMachineCreator {
public var gpuDriverBundle: URL?
public var ipswCacheDirectory: URL
public var forceDyldSharedCacheMaxSlide: Bool
- public var enableFrida: Bool
+ /// Which patch preset the new VM is built with. Individual patches are
+ /// turned on or off per VM afterwards, through its patch selection.
+ public var patchPreset: String
public var cpuCount: UInt
public var memoryMB: UInt64
public var diskSizeGB: UInt64
@@ -25,7 +28,7 @@ public extension VPhoneVirtualMachineCreator {
gpuDriverBundle: URL? = nil,
ipswCacheDirectory: URL = VPhoneResources.ipswCacheDirectory(),
forceDyldSharedCacheMaxSlide: Bool = false,
- enableFrida: Bool = false,
+ patchPreset: String = VPhonePatchPreset.standardIdentifier,
cpuCount: UInt = 8,
memoryMB: UInt64 = 8192,
diskSizeGB: UInt64 = 64,
@@ -38,7 +41,7 @@ public extension VPhoneVirtualMachineCreator {
self.gpuDriverBundle = gpuDriverBundle
self.ipswCacheDirectory = ipswCacheDirectory
self.forceDyldSharedCacheMaxSlide = forceDyldSharedCacheMaxSlide
- self.enableFrida = enableFrida
+ self.patchPreset = patchPreset
self.cpuCount = cpuCount
self.memoryMB = memoryMB
self.diskSizeGB = diskSizeGB
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift
index f92a4366..62ca39a6 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift
@@ -146,7 +146,7 @@ public struct VPhoneVirtualMachineCreator {
try runFWPrepare(options: options, bundleURL: bundleURL)
print("\n=== fw patch ===")
- try runFWPatch(enableFrida: options.enableFrida, bundleURL: bundleURL, verbosity: v)
+ try runFWPatch(presetIdentifier: options.patchPreset, bundleURL: bundleURL, verbosity: v)
print("\n=== Restore phase ===")
try runRestorePhase(bundleURL: bundleURL, verbosity: v)
@@ -238,21 +238,43 @@ public struct VPhoneVirtualMachineCreator {
}
private func runFWPatch(
- enableFrida: Bool,
+ presetIdentifier: String,
bundleURL: URL,
verbosity v: VPhoneVerbosity,
) throws {
- trace("in-process FirmwarePipeline.patchAll variant=jb", v)
+ trace("in-process FirmwarePipeline.patchAll variant=jb preset=\(presetIdentifier)", v)
+ guard let preset = VPhonePatchPresetStore.preset(named: presetIdentifier) else {
+ let available = VPhonePatchPresetStore.availablePresets().map(\.identifier)
+ throw ValidationError(
+ "Unknown patch preset '\(presetIdentifier)'. Available: \(available.joined(separator: ", "))",
+ )
+ }
let pipeline = FirmwarePipeline(
vmDirectory: bundleURL,
variant: .jb,
verbose: v.showsToolDetail,
noBinpack: true,
- forceExcGuard: false,
- enableFrida: enableFrida,
+ preset: preset,
)
let records = try pipeline.patchAll()
- print("[fw patch] applied \(records.count) JB patches")
+
+ // A new VM records its choice and its plan, so `cfw install` and any later
+ // re-patch agree without the preset being named again.
+ if let plan = pipeline.resolvedPlan {
+ try VPhonePatchPresetStore.write(
+ VPhoneVirtualMachinePatchSelection(presetIdentifier: presetIdentifier),
+ forVM: bundleURL,
+ )
+ try VPhonePatchPresetStore.write(
+ VPhoneVirtualMachinePatchPlan(
+ plan: plan,
+ iOSBase: pipeline.baseProductVersion,
+ cloudOS: pipeline.cloudOSProductVersion,
+ ),
+ forVM: bundleURL,
+ )
+ }
+ print("[fw patch] applied \(records.count) JB patches (preset \(presetIdentifier))")
}
// MARK: - restore phase
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Constants.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Constants.swift
new file mode 100644
index 00000000..ec9590a4
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Constants.swift
@@ -0,0 +1,188 @@
+// ARM64Constants.swift — Pre-encoded ARM64 instruction constants.
+//
+// Every constant was generated by keystone-engine and verified
+// via capstone round-trip disassembly. Do NOT edit raw bytes
+// without updating the corresponding test case.
+
+import Foundation
+
+// MARK: - ARM64 Instruction Constants
+
+public enum ARM64 {
+ // MARK: Fixed Instructions
+
+ /// NOP — no operation
+ public static let nop = encodeU32(0xD503_201F)
+
+ /// RET — return from subroutine
+ public static let ret = encodeU32(0xD65F_03C0)
+
+ /// RETAA — return with pointer authentication (A key)
+ public static let retaa = encodeU32(0xD65F_0BFF)
+
+ /// RETAB — return with pointer authentication (B key)
+ public static let retab = encodeU32(0xD65F_0FFF)
+
+ /// PACIBSP — sign LR with B key using SP (hint #27)
+ public static let pacibsp = encodeU32(0xD503_237F)
+
+ // MARK: MOV Variants
+
+ /// MOV X0, #0 (MOVZ X0, #0)
+ public static let movX0_0 = encodeU32(0xD280_0000)
+
+ /// MOV X0, #1 (MOVZ X0, #1)
+ public static let movX0_1 = encodeU32(0xD280_0020)
+
+ /// MOV W0, #0 (MOVZ W0, #0)
+ public static let movW0_0 = encodeU32(0x5280_0000)
+
+ /// MOV W0, #1 (MOVZ W0, #1)
+ public static let movW0_1 = encodeU32(0x5280_0020)
+
+ /// MOV X0, X20 (ORR X0, XZR, X20)
+ public static let movX0X20 = encodeU32(0xAA14_03E0)
+
+ /// MOV W0, #0xA1 (MOVZ W0, #0xA1)
+ public static let movW0_0xA1 = encodeU32(0x5280_1420)
+
+ // MARK: Compare
+
+ /// CMP W0, W0 (SUBS WZR, W0, W0)
+ public static let cmpW0W0 = encodeU32(0x6B00_001F)
+
+ /// CMP X0, X0 (SUBS XZR, X0, X0)
+ public static let cmpX0X0 = encodeU32(0xEB00_001F)
+
+ // MARK: Memory
+
+ /// STRB W0, [X20, #0x30]
+ public static let strbW0X20_30 = encodeU32(0x3900_C280)
+
+ // MARK: JB Constants
+
+ /// CBZ X2, #8 (branch if X2 == 0, skip 2 instructions)
+ public static let cbzX2_8 = encodeU32(0xB400_0042)
+
+ /// STR X0, [X2]
+ public static let strX0X2 = encodeU32(0xF900_0040)
+
+ /// CMP XZR, XZR (SUBS XZR, XZR, XZR — always sets Z flag)
+ public static let cmpXzrXzr = encodeU32(0xEB1F_03FF)
+
+ // MARK: Common Prologue/Epilogue Patterns (verified via keystone)
+
+ /// STP X29, X30, [SP, #-0x10]! (push frame)
+ public static let stpFP_LR_pre: UInt32 = 0xA9BF_7BFD
+ /// MOV X29, SP (set frame pointer)
+ public static let movFP_SP: UInt32 = 0x9100_03FD
+
+ // MARK: IOUC MACF Aggregator Shape
+
+ /// LDR X10, [X10, #0x9E8] (mac_policy_list slot load)
+ public static let ldr_x10_x10_0x9e8: UInt32 = 0xF944_F54A
+ /// BLRAA X10, SP (authenticated indirect call)
+ public static let blraa_x10: UInt32 = 0xD73F_0940
+ /// BLRAB X10, SP
+ public static let blrab_x10: UInt32 = 0xD73F_0D40
+ /// BLR X10
+ public static let blr_x10: UInt32 = 0xD63F_0140
+
+ // MARK: C23 Cave Instructions (verified via keystone)
+
+ //
+ // These are the fixed instructions used in the faithful upstream C23
+ // shellcode cave (vnode getattr → uid/gid/P_SUGID fixup).
+ // Position-dependent BL/B instructions are NOT included here — they are
+ // encoded at build time by ARM64Encoder.
+
+ public static let c23_cbzX3_0xA8: UInt32 = 0xB400_0543 // cbz x3, #+0xa8
+ public static let c23_subSP_0x400: UInt32 = 0xD110_03FF // sub sp, sp, #0x400
+ public static let c23_stpFP_LR: UInt32 = 0xA900_7BFD // stp x29, x30, [sp]
+ public static let c23_stpX0X1_0x10: UInt32 = 0xA901_07E0 // stp x0, x1, [sp, #0x10]
+ public static let c23_stpX2X3_0x20: UInt32 = 0xA902_0FE2 // stp x2, x3, [sp, #0x20]
+ public static let c23_stpX4X5_0x30: UInt32 = 0xA903_17E4 // stp x4, x5, [sp, #0x30]
+ public static let c23_stpX6X7_0x40: UInt32 = 0xA904_1FE6 // stp x6, x7, [sp, #0x40]
+ public static let c23_movX2_X0: UInt32 = 0xAA00_03E2 // mov x2, x0
+ public static let c23_ldrX0_sp_0x28: UInt32 = 0xF940_17E0 // ldr x0, [sp, #0x28]
+ public static let c23_addX1_sp_0x80: UInt32 = 0x9102_03E1 // add x1, sp, #0x80
+ public static let c23_movzW8_0x380: UInt32 = 0x5280_7008 // movz w8, #0x380
+ public static let c23_stpXZR_X8: UInt32 = 0xA900_203F // stp xzr, x8, [x1]
+ public static let c23_stpXZR_XZR_0x10: UInt32 = 0xA901_7C3F // stp xzr, xzr, [x1, #0x10]
+ public static let c23_cbnzX0_0x4c: UInt32 = 0xB500_0260 // cbnz x0, #+0x4c
+ public static let c23_movW2_0: UInt32 = 0x5280_0002 // mov w2, #0
+ public static let c23_ldrW8_sp_0xcc: UInt32 = 0xB940_CFE8 // ldr w8, [sp, #0xcc]
+ public static let c23_tbzW8_11_0x14: UInt32 = 0x3658_00A8 // tbz w8, #0xb, #+0x14
+ public static let c23_ldrW8_sp_0xc4: UInt32 = 0xB940_C7E8 // ldr w8, [sp, #0xc4]
+ public static let c23_ldrX0_sp_0x18: UInt32 = 0xF940_0FE0 // ldr x0, [sp, #0x18]
+ public static let c23_strW8_x0_0x18: UInt32 = 0xB900_1808 // str w8, [x0, #0x18]
+ public static let c23_movW2_1: UInt32 = 0x5280_0022 // mov w2, #1
+ public static let c23_tbzW8_10_0x14: UInt32 = 0x3650_00A8 // tbz w8, #0xa, #+0x14
+ public static let c23_ldrW8_sp_0xc8: UInt32 = 0xB940_CBE8 // ldr w8, [sp, #0xc8]
+ public static let c23_strW8_x0_0x28: UInt32 = 0xB900_2808 // str w8, [x0, #0x28]
+ public static let c23_cbzW2_0x14: UInt32 = 0x3400_00A2 // cbz w2, #+0x14
+ public static let c23_ldrX0_sp_0x20: UInt32 = 0xF940_13E0 // ldr x0, [sp, #0x20]
+ public static let c23_ldrW8_x0_0x454: UInt32 = 0xB944_5408 // ldr w8, [x0, #0x454]
+ public static let c23_orrW8_0x100: UInt32 = 0x3218_0108 // orr w8, w8, #0x100
+ public static let c23_strW8_x0_0x454: UInt32 = 0xB904_5408 // str w8, [x0, #0x454]
+ public static let c23_ldpX0X1_0x10: UInt32 = 0xA941_07E0 // ldp x0, x1, [sp, #0x10]
+ public static let c23_ldpX2X3_0x20: UInt32 = 0xA942_0FE2 // ldp x2, x3, [sp, #0x20]
+ public static let c23_ldpX4X5_0x30: UInt32 = 0xA943_17E4 // ldp x4, x5, [sp, #0x30]
+ public static let c23_ldpX6X7_0x40: UInt32 = 0xA944_1FE6 // ldp x6, x7, [sp, #0x40]
+ public static let c23_ldpFP_LR: UInt32 = 0xA940_7BFD // ldp x29, x30, [sp]
+ public static let c23_addSP_0x400: UInt32 = 0x9110_03FF // add sp, sp, #0x400
+
+ // MARK: vfs_context_current Shape (verified via keystone)
+
+ /// mrs x0, tpidr_el1
+ public static let mrs_x0_tpidr_el1: UInt32 = 0xD538_D080
+
+ // MARK: Syscallmask C22 Cave Instructions (verified via clang/as)
+
+ public static let syscallmask_cbzX2_0x6c: UInt32 = 0xB400_0362 // cbz x2, #+0x6c
+ public static let syscallmask_subSP_0x40: UInt32 = 0xD101_03FF // sub sp, sp, #0x40
+ public static let syscallmask_stpX19X20_0x10: UInt32 = 0xA901_53F3 // stp x19, x20, [sp, #0x10]
+ public static let syscallmask_stpX21X22_0x20: UInt32 = 0xA902_5BF5 // stp x21, x22, [sp, #0x20]
+ public static let syscallmask_stpFP_LR_0x30: UInt32 = 0xA903_7BFD // stp x29, x30, [sp, #0x30]
+ public static let syscallmask_movX19_X0: UInt32 = 0xAA00_03F3 // mov x19, x0
+ public static let syscallmask_movX20_X1: UInt32 = 0xAA01_03F4 // mov x20, x1
+ public static let syscallmask_movX21_X2: UInt32 = 0xAA02_03F5 // mov x21, x2
+ public static let syscallmask_movX22_X3: UInt32 = 0xAA03_03F6 // mov x22, x3
+ public static let syscallmask_movX8_8: UInt32 = 0xD280_0108 // mov x8, #8
+ public static let syscallmask_movX0_X17: UInt32 = 0xAA11_03E0 // mov x0, x17
+ public static let syscallmask_movX1_X21: UInt32 = 0xAA15_03E1 // mov x1, x21
+ public static let syscallmask_movX2_0: UInt32 = 0xD280_0002 // mov x2, #0
+ public static let syscallmask_udivX4_X22_X8: UInt32 = 0x9AC8_0AC4 // udiv x4, x22, x8
+ public static let syscallmask_msubX10_X4_X8_X22: UInt32 = 0x9B08_D88A // msub x10, x4, x8, x22
+ public static let syscallmask_cbzX10_8: UInt32 = 0xB400_004A // cbz x10, #+8
+ public static let syscallmask_addX4_X4_1: UInt32 = 0x9100_0484 // add x4, x4, #1
+ public static let syscallmask_movX0_X19: UInt32 = 0xAA13_03E0 // mov x0, x19
+ public static let syscallmask_movX1_X20: UInt32 = 0xAA14_03E1 // mov x1, x20
+ public static let syscallmask_movX2_X21: UInt32 = 0xAA15_03E2 // mov x2, x21
+ public static let syscallmask_movX3_X22: UInt32 = 0xAA16_03E3 // mov x3, x22
+ public static let syscallmask_ldpX19X20_0x10: UInt32 = 0xA941_53F3 // ldp x19, x20, [sp, #0x10]
+ public static let syscallmask_ldpX21X22_0x20: UInt32 = 0xA942_5BF5 // ldp x21, x22, [sp, #0x20]
+ public static let syscallmask_ldpFP_LR_0x30: UInt32 = 0xA943_7BFD // ldp x29, x30, [sp, #0x30]
+ public static let syscallmask_addSP_0x40: UInt32 = 0x9101_03FF // add sp, sp, #0x40
+
+ // MARK: UInt32 Values (for pattern matching)
+
+ public static let nopU32: UInt32 = 0xD503_201F
+ public static let retU32: UInt32 = 0xD65F_03C0
+ public static let retaaU32: UInt32 = 0xD65F_0BFF
+ public static let retabU32: UInt32 = 0xD65F_0FFF
+ public static let pacibspU32: UInt32 = 0xD503_237F
+ public static let movX0_0_U32: UInt32 = 0xD280_0000 // MOV X0, #0 (MOVZ X0, #0)
+
+ /// Set of instruction uint32 values that indicate function boundaries.
+ public static let funcBoundaryU32s: Set<UInt32> = [
+ retU32, retaaU32, retabU32, pacibspU32,
+ ]
+
+ // MARK: - Helpers
+
+ @inlinable
+ public static func encodeU32(_ value: UInt32) -> Data {
+ withUnsafeBytes(of: value.littleEndian) { Data($0) }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Disassembler.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Disassembler.swift
new file mode 100644
index 00000000..38ed5bf6
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Disassembler.swift
@@ -0,0 +1,191 @@
+// ARM64Disassembler.swift — Capstone-backed ARM64 disassembly.
+//
+// Capstone is an implementation detail of VPhonePatchKit. It is imported
+// `internal`, so no Capstone type reaches the module interface: patch sets see
+// only ``ARM64Instruction`` and never link a second copy of the disassembler.
+
+internal import Capstone
+import Foundation
+
+public final class ARM64Disassembler: @unchecked Sendable {
+ private var handle: csh = 0
+
+ public init() {
+ let status = cs_open(CS_ARCH_AARCH64, CS_MODE_LITTLE_ENDIAN, &handle)
+ precondition(status == CS_ERR_OK, "Capstone could not open an AArch64 handle: \(status)")
+ cs_option(handle, CS_OPT_DETAIL, numericCast(CS_OPT_ON.rawValue))
+ cs_option(handle, CS_OPT_SKIPDATA, numericCast(CS_OPT_ON.rawValue))
+ }
+
+ deinit {
+ cs_close(&handle)
+ }
+
+ /// Disassemble instructions from data starting at the given virtual address.
+ ///
+ /// - Parameters:
+ /// - data: Raw instruction bytes.
+ /// - address: Virtual address of the first byte.
+ /// - count: Maximum number of instructions to disassemble (0 = all).
+ /// - Returns: Array of disassembled instructions.
+ public func disassemble(_ data: Data, at address: UInt64 = 0, count: Int = 0) -> [ARM64Instruction] {
+ let bytes = [UInt8](data)
+ return bytes.withUnsafeBufferPointer { buffer in
+ var raw: UnsafeMutablePointer<cs_insn>?
+ let decoded = cs_disasm(handle, buffer.baseAddress, buffer.count, address, count, &raw)
+ guard decoded > 0, let raw else { return [] }
+ defer { cs_free(raw, decoded) }
+ return (0 ..< decoded).map { ARM64Instruction(raw[$0]) }
+ }
+ }
+
+ /// Disassemble a single 4-byte instruction at the given address.
+ public func disassembleOne(_ data: Data, at address: UInt64 = 0) -> ARM64Instruction? {
+ disassemble(data, at: address, count: 1).first
+ }
+
+ /// Disassemble a single instruction from a buffer at a file offset.
+ public func disassembleOne(in buffer: Data, at offset: Int, address: UInt64? = nil) -> ARM64Instruction? {
+ guard offset >= 0, offset + 4 <= buffer.count else { return nil }
+ let slice = buffer[offset ..< offset + 4]
+ let addr = address ?? UInt64(offset)
+ return disassembleOne(Data(slice), at: addr)
+ }
+
+ /// Disassemble `count` instructions starting at file offset.
+ public func disassemble(in buffer: Data, at offset: Int, count: Int, address: UInt64? = nil) -> [ARM64Instruction] {
+ let byteCount = count * 4
+ guard offset >= 0, offset + byteCount <= buffer.count else { return [] }
+ let slice = buffer[offset ..< offset + byteCount]
+ let addr = address ?? UInt64(offset)
+ return disassemble(Data(slice), at: addr, count: count)
+ }
+
+ /// Canonical name of the instruction's first operand when it is a register
+ /// (the write target for the moves/loads/branches the patchers match), else nil.
+ ///
+ /// Replaces the brittle `operandString.components(separatedBy: ",")` parsing that
+ /// was duplicated across the JB patch files to recover a destination register's
+ /// width ("w…" vs "x…") and identity.
+ public func firstRegisterName(_ insn: ARM64Instruction) -> String? {
+ guard let first = insn.detail?.operands.first, first.type == .register else { return nil }
+ return first.reg.name
+ }
+
+ /// True iff the instruction's first (destination) operand is the named register.
+ public func writesRegister(_ insn: ARM64Instruction, named regName: String) -> Bool {
+ firstRegisterName(insn) == regName
+ }
+}
+
+// MARK: - Capstone Conversion
+
+extension ARM64Instruction {
+ init(_ raw: cs_insn) {
+ let mnemonic = withUnsafeBytes(of: raw.mnemonic) { buffer in
+ String(cString: buffer.baseAddress!.assumingMemoryBound(to: CChar.self))
+ }
+ let operandString = withUnsafeBytes(of: raw.op_str) { buffer in
+ String(cString: buffer.baseAddress!.assumingMemoryBound(to: CChar.self))
+ }
+ let bytes = withUnsafeBytes(of: raw.bytes) { Array($0.prefix(Int(raw.size))) }
+
+ var detail: ARM64InstructionDetail?
+ var groups: [UInt8] = []
+ if let rawDetail = raw.detail?.pointee {
+ groups = withUnsafeBytes(of: rawDetail.groups) { buffer in
+ Array(buffer.prefix(Int(rawDetail.groups_count)))
+ }
+ detail = ARM64InstructionDetail(rawDetail.aarch64)
+ }
+
+ self.init(
+ isDecoded: raw.id != 0,
+ address: raw.address,
+ size: raw.size,
+ bytes: bytes,
+ mnemonic: mnemonic,
+ operandString: operandString,
+ detail: detail,
+ isJump: groups.contains(UInt8(CS_GRP_JUMP.rawValue)),
+ isCall: groups.contains(UInt8(CS_GRP_CALL.rawValue)),
+ isReturn: groups.contains(UInt8(CS_GRP_RET.rawValue)),
+ )
+ }
+}
+
+extension ARM64InstructionDetail {
+ init(_ raw: cs_aarch64) {
+ let operands = withUnsafeBytes(of: raw.operands) { buffer in
+ let pointer = buffer.baseAddress!.assumingMemoryBound(to: cs_aarch64_op.self)
+ let capacity = buffer.count / MemoryLayout<cs_aarch64_op>.stride
+ return (0 ..< min(Int(raw.op_count), capacity)).map { ARM64Operand(pointer[$0]) }
+ }
+ self.init(
+ conditionCode: ARM64Condition(rawValue: raw.cc.rawValue),
+ updatesFlags: raw.update_flags,
+ postIndex: raw.post_index,
+ operands: operands,
+ )
+ }
+}
+
+extension ARM64Operand {
+ init(_ raw: cs_aarch64_op) {
+ let type: ARM64OperandType = switch raw.type {
+ case AARCH64_OP_REG: .register
+ case AARCH64_OP_IMM: .immediate
+ case AARCH64_OP_MEM: .memory
+ default: .other
+ }
+ self.init(
+ type: type,
+ reg: ARM64Register(rawValue: raw.reg.rawValue),
+ imm: raw.imm,
+ mem: ARM64MemoryOperand(
+ base: ARM64Register(rawValue: raw.mem.base.rawValue),
+ index: ARM64Register(rawValue: raw.mem.index.rawValue),
+ disp: raw.mem.disp,
+ ),
+ )
+ }
+}
+
+// MARK: - Register Identity
+
+extension ARM64Register {
+ public static let invalid = ARM64Register(rawValue: AARCH64_REG_INVALID.rawValue)
+ public static let sp = ARM64Register(rawValue: AARCH64_REG_SP.rawValue)
+ public static let wzr = ARM64Register(rawValue: AARCH64_REG_WZR.rawValue)
+ public static let xzr = ARM64Register(rawValue: AARCH64_REG_XZR.rawValue)
+
+ /// The 64-bit general register `x<number>`; x29 and x30 are FP and LR.
+ public static func x(_ number: Int) -> ARM64Register {
+ precondition((0 ... 30).contains(number), "x\(number) is not a general register")
+ return switch number {
+ case 29: ARM64Register(rawValue: AARCH64_REG_FP.rawValue)
+ case 30: ARM64Register(rawValue: AARCH64_REG_LR.rawValue)
+ default: ARM64Register(rawValue: AARCH64_REG_X0.rawValue + UInt32(number))
+ }
+ }
+
+ /// The 32-bit general register `w<number>`.
+ public static func w(_ number: Int) -> ARM64Register {
+ precondition((0 ... 30).contains(number), "w\(number) is not a general register")
+ return ARM64Register(rawValue: AARCH64_REG_W0.rawValue + UInt32(number))
+ }
+
+ /// Canonical register name, such as "x0", "w1" or "wzr".
+ public var name: String? {
+ guard let name = cs_reg_name(registerNameHandle, rawValue) else { return nil }
+ return String(cString: name)
+ }
+}
+
+/// Register names need a handle but no instruction state; one serves every lookup.
+private let registerNameHandle: csh = {
+ var handle: csh = 0
+ let status = cs_open(CS_ARCH_AARCH64, CS_MODE_LITTLE_ENDIAN, &handle)
+ precondition(status == CS_ERR_OK, "Capstone could not open an AArch64 handle: \(status)")
+ return handle
+}()
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/ARM64/ARM64Encoder.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
similarity index 100%
rename from VPhoneExecutable/VPhoneCommand/FirmwarePatcher/ARM64/ARM64Encoder.swift
rename to VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/ARM64/ARM64Inst.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Inst.swift
similarity index 100%
rename from VPhoneExecutable/VPhoneCommand/FirmwarePatcher/ARM64/ARM64Inst.swift
rename to VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Inst.swift
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Instruction.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Instruction.swift
new file mode 100644
index 00000000..3851e945
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Instruction.swift
@@ -0,0 +1,121 @@
+// ARM64Instruction.swift — PatchKit's decoded-instruction model.
+//
+// Patches match on these types, never on a disassembler's own. The fields are
+// the ones the patchers read: mnemonic and operand text for logs and anchors,
+// and typed operands for every semantic check. ARM64Disassembler fills them.
+
+import Foundation
+
+public struct ARM64Instruction: Sendable, CustomStringConvertible {
+ /// False for bytes the disassembler skipped as data.
+ public let isDecoded: Bool
+ public let address: UInt64
+ public let size: UInt16
+ public let bytes: [UInt8]
+ public let mnemonic: String
+ public let operandString: String
+ /// Operand detail; nil only when the disassembler produced none.
+ public let detail: ARM64InstructionDetail?
+ public let isJump: Bool
+ public let isCall: Bool
+ public let isReturn: Bool
+
+ public init(
+ isDecoded: Bool,
+ address: UInt64,
+ size: UInt16,
+ bytes: [UInt8],
+ mnemonic: String,
+ operandString: String,
+ detail: ARM64InstructionDetail?,
+ isJump: Bool,
+ isCall: Bool,
+ isReturn: Bool,
+ ) {
+ self.isDecoded = isDecoded
+ self.address = address
+ self.size = size
+ self.bytes = bytes
+ self.mnemonic = mnemonic
+ self.operandString = operandString
+ self.detail = detail
+ self.isJump = isJump
+ self.isCall = isCall
+ self.isReturn = isReturn
+ }
+
+ public var description: String {
+ let addr = String(format: "0x%llx", address)
+ if operandString.isEmpty {
+ return "\(addr): \(mnemonic)"
+ }
+ return "\(addr): \(mnemonic) \(operandString)"
+ }
+}
+
+public struct ARM64InstructionDetail: Sendable {
+ /// The condition a conditional instruction tests; nil when it tests none.
+ public let conditionCode: ARM64Condition?
+ public let updatesFlags: Bool
+ public let postIndex: Bool
+ public let operands: [ARM64Operand]
+
+ public init(conditionCode: ARM64Condition?, updatesFlags: Bool, postIndex: Bool, operands: [ARM64Operand]) {
+ self.conditionCode = conditionCode
+ self.updatesFlags = updatesFlags
+ self.postIndex = postIndex
+ self.operands = operands
+ }
+}
+
+public enum ARM64OperandType: Sendable {
+ case register
+ case immediate
+ case memory
+ case other
+}
+
+public struct ARM64Operand: Sendable {
+ public let type: ARM64OperandType
+ /// Meaningful when `type` is `.register`.
+ public let reg: ARM64Register
+ /// Meaningful when `type` is `.immediate`.
+ public let imm: Int64
+ /// Meaningful when `type` is `.memory`.
+ public let mem: ARM64MemoryOperand
+
+ public init(type: ARM64OperandType, reg: ARM64Register, imm: Int64, mem: ARM64MemoryOperand) {
+ self.type = type
+ self.reg = reg
+ self.imm = imm
+ self.mem = mem
+ }
+}
+
+public struct ARM64MemoryOperand: Sendable, Hashable {
+ public let base: ARM64Register
+ /// `.invalid` when the address has no index register.
+ public let index: ARM64Register
+ public let disp: Int32
+
+ public init(base: ARM64Register, index: ARM64Register, disp: Int32) {
+ self.base = base
+ self.index = index
+ self.disp = disp
+ }
+}
+
+/// A register as the disassembler identifies it. The raw value is an opaque
+/// identifier, stable within one PatchKit build: compare registers, use them as
+/// keys, and build known ones with `x(_:)`, `w(_:)` and the named constants.
+public struct ARM64Register: Sendable, Hashable, CustomStringConvertible {
+ public let rawValue: UInt32
+
+ public init(rawValue: UInt32) {
+ self.rawValue = rawValue
+ }
+
+ public var description: String {
+ name ?? "reg#\(rawValue)"
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/BinaryBuffer.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/Binary/BinaryBuffer.swift
similarity index 89%
rename from VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/BinaryBuffer.swift
rename to VPhoneExecutable/VPhoneCommand/VPhonePatchKit/Binary/BinaryBuffer.swift
index efea54c6..5179b7c8 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/BinaryBuffer.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/Binary/BinaryBuffer.swift
@@ -5,7 +5,7 @@ import Foundation
extension Data {
/// Load a little-endian integer without assuming the buffer is naturally aligned.
@inlinable
- func loadLE<T: FixedWidthInteger>(_: T.Type, at offset: Int) -> T {
+ public func loadLE<T: FixedWidthInteger>(_: T.Type, at offset: Int) -> T {
precondition(offset >= 0 && offset + MemoryLayout<T>.size <= count)
var value: T = .zero
_ = Swift.withUnsafeMutableBytes(of: &value) { dst in
@@ -37,14 +37,6 @@ public final class BinaryBuffer: @unchecked Sendable {
original = rebased
}
- public convenience init(contentsOf url: URL) throws {
- // Read, not mapped. A `BinaryBuffer` exists to be mutated, and what it
- // is built from — a kernelcache, an iBoot — is written back over the
- // path it came from. See InPlaceRewrite.swift for why a mapping cannot
- // survive that.
- try self.init(Data(contentsOfFileToRewrite: url))
- }
-
// MARK: - Read Helpers
/// Read a little-endian UInt32 at the given byte offset.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/MachOParser.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/Binary/MachOParser.swift
similarity index 93%
rename from VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/MachOParser.swift
rename to VPhoneExecutable/VPhoneCommand/VPhonePatchKit/Binary/MachOParser.swift
index 49410d52..407edea5 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/MachOParser.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/Binary/MachOParser.swift
@@ -11,6 +11,14 @@ public struct MachOSegmentInfo: Sendable {
public let vmSize: UInt64
public let fileOffset: UInt64
public let fileSize: UInt64
+
+ public init(name: String, vmAddr: UInt64, vmSize: UInt64, fileOffset: UInt64, fileSize: UInt64) {
+ self.name = name
+ self.vmAddr = vmAddr
+ self.vmSize = vmSize
+ self.fileOffset = fileOffset
+ self.fileSize = fileSize
+ }
}
/// Minimal section info extracted from a Mach-O binary.
@@ -20,6 +28,14 @@ public struct MachOSectionInfo: Sendable {
public let address: UInt64
public let size: UInt64
public let fileOffset: UInt32
+
+ public init(segmentName: String, sectionName: String, address: UInt64, size: UInt64, fileOffset: UInt32) {
+ self.segmentName = segmentName
+ self.sectionName = sectionName
+ self.address = address
+ self.size = size
+ self.fileOffset = fileOffset
+ }
}
// MARK: - MachO Parser
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchInfrastructure/PatchRecord.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/Patch/PatchRecord.swift
similarity index 95%
rename from VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchInfrastructure/PatchRecord.swift
rename to VPhoneExecutable/VPhoneCommand/VPhonePatchKit/Patch/PatchRecord.swift
index d87e9c74..a1e8a763 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchInfrastructure/PatchRecord.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/Patch/PatchRecord.swift
@@ -69,7 +69,8 @@ extension PatchRecord: CustomStringConvertible {
}
extension Data {
- var hex: String {
+ /// Lowercase hex, the spelling every patch log and record uses.
+ public var hex: String {
map { String(format: "%02x", $0) }.joined()
}
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchInfrastructure/PatcherError.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/Patch/PatcherError.swift
similarity index 100%
rename from VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchInfrastructure/PatcherError.swift
rename to VPhoneExecutable/VPhoneCommand/VPhonePatchKit/Patch/PatcherError.swift
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/Patch/PatcherProtocol.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/Patch/PatcherProtocol.swift
new file mode 100644
index 00000000..5daad30d
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/Patch/PatcherProtocol.swift
@@ -0,0 +1,73 @@
+// PatcherProtocol.swift — Common protocol for all firmware patchers.
+
+import Foundation
+
+/// A firmware patcher that can find and apply patches to a binary buffer.
+public protocol Patcher {
+ /// The component name (e.g., "kernelcache", "ibss", "txm").
+ var component: String { get }
+
+ /// Whether to print verbose output.
+ var verbose: Bool { get }
+
+ /// Which patches the resolved preset turned on.
+ ///
+ /// Defaults to ``VPhonePatchGate/unrestricted``, so a patcher built directly
+ /// applies everything it finds, exactly as it did before presets existed.
+ var gate: VPhonePatchGate { get }
+
+ /// Find all patch sites and return patch records (dry-run mode).
+ func findAll() throws -> [PatchRecord]
+
+ /// Apply all patches to the buffer. Returns the number of patches applied.
+ @discardableResult
+ func apply() throws -> Int
+}
+
+/// A patcher that owns the bytes it produced.
+///
+/// The pipeline reads a component's result through this rather than by
+/// downcasting to each concrete patcher it happens to know. That is what lets a
+/// patcher from a loaded `.vphonepatchset` contribute anything at all: the
+/// pipeline has never heard of its type, and a patcher whose bytes it could not
+/// read would apply its patches into a buffer nobody saves.
+public protocol BufferedPatcher: Patcher {
+ /// The component's bytes after ``Patcher/apply()``.
+ var patchedData: Data { get }
+}
+
+extension Patcher {
+ /// Log a message if verbose mode is enabled.
+ public func log(_ message: String) {
+ if verbose {
+ print(message)
+ }
+ }
+
+ /// Every patch applies unless the patcher says otherwise.
+ public var gate: VPhonePatchGate { .unrestricted }
+
+ /// Whether the site emitting `recordIdentifier` should be written.
+ public func gateAllows(_ recordIdentifier: String) -> Bool {
+ gate.allowsReporting(record: recordIdentifier, component: component, verbose: verbose)
+ }
+}
+
+extension VPhonePatchGate {
+ /// ``allows(record:)`` with the log line that explains the decision.
+ ///
+ /// The undeclared case is a manifest gap: the patch still applies, because
+ /// dropping bytes over a missing declaration would change the firmware
+ /// silently, and its warning prints whether or not verbose is on, so the gap
+ /// shows up in an ordinary run.
+ public func allowsReporting(record recordIdentifier: String, component: String, verbose: Bool) -> Bool {
+ if isUnrestricted { return true }
+ if isUndeclared(record: recordIdentifier) {
+ print(" [!] \(component): \(recordIdentifier) is declared by no patch set; applying it anyway")
+ return true
+ }
+ if allows(record: recordIdentifier) { return true }
+ if verbose { print(" [·] \(recordIdentifier): off in this preset") }
+ return false
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchApplicability.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchApplicability.swift
new file mode 100644
index 00000000..da2352af
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchApplicability.swift
@@ -0,0 +1,60 @@
+// VPhonePatchApplicability.swift — The version gate a patch declares.
+//
+// A VM is built from two OSes: the iPhone base whose userland is restored into
+// the guest, and the cloudOS whose kernel and boot chain run it. A patch may
+// care about either, so the gate names both and defaults to "any".
+
+import Foundation
+
+public struct VPhonePatchApplicability: Sendable, Hashable, Codable {
+ /// The iPhone base release whose userland ships in the guest.
+ public var iOSBase: VPhoneVersionRequirement
+ /// The cloudOS release supplying the kernel and boot chain.
+ public var cloudOS: VPhoneVersionRequirement
+
+ public init(
+ iOSBase: VPhoneVersionRequirement = .any,
+ cloudOS: VPhoneVersionRequirement = .any,
+ ) {
+ self.iOSBase = iOSBase
+ self.cloudOS = cloudOS
+ }
+
+ /// Applies to every pairing.
+ public static let always = VPhonePatchApplicability()
+
+ /// Both requirements must hold; an unreadable version satisfies only `.any`.
+ public func matches(iOSBase base: VPhoneVersion?, cloudOS cloud: VPhoneVersion?) -> Bool {
+ iOSBase.matches(base) && cloudOS.matches(cloud)
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case iOSBase = "IOSBase"
+ case cloudOS = "CloudOS"
+ }
+
+ public init(from decoder: any Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ iOSBase = try container.decodeIfPresent(VPhoneVersionRequirement.self, forKey: .iOSBase) ?? .any
+ cloudOS = try container.decodeIfPresent(VPhoneVersionRequirement.self, forKey: .cloudOS) ?? .any
+ }
+
+ /// Only the requirements that say something are written, so an unconditional
+ /// patch's plist entry stays empty rather than carrying two `Any` dicts.
+ public func encode(to encoder: any Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ if iOSBase != .any { try container.encode(iOSBase, forKey: .iOSBase) }
+ if cloudOS != .any { try container.encode(cloudOS, forKey: .cloudOS) }
+ }
+}
+
+extension VPhonePatchApplicability: CustomStringConvertible {
+ public var description: String {
+ switch (iOSBase, cloudOS) {
+ case (.any, .any): "any"
+ case (.any, _): "cloudOS \(cloudOS)"
+ case (_, .any): "iOS \(iOSBase)"
+ default: "iOS \(iOSBase), cloudOS \(cloudOS)"
+ }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchDeclaration.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchDeclaration.swift
new file mode 100644
index 00000000..cefaa5c7
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchDeclaration.swift
@@ -0,0 +1,100 @@
+// VPhonePatchDeclaration.swift — One selectable patch, as its set declares it.
+//
+// The identifier is the contract. It is the prefix of the ``PatchRecord``
+// identifiers the patch emits, so a patch writing four records under
+// `jb.cred_label_update_execve.*` declares one identifier and is selected or
+// blocked as a unit — a half-applied patch of that shape would not boot.
+
+import Foundation
+
+public struct VPhonePatchDeclaration: Sendable, Hashable, Codable, Identifiable {
+ /// Stable selection identity, and the record-identifier prefix.
+ public var identifier: String
+ /// Short label for a preset picker. One line, no trailing period.
+ public var title: String
+ /// What the patch does and why the guest needs it.
+ public var summary: String
+ /// What the patch writes to.
+ public var target: VPhonePatchTarget
+ /// The OS pairings the patch applies to.
+ public var applicability: VPhonePatchApplicability
+ /// True when the guest does not boot without this patch.
+ ///
+ /// Blocking one is allowed — that is how an external set replaces it — but
+ /// every caller that offers a choice says so first, and the resolver reports
+ /// which essentials a plan dropped.
+ public var bootEssential: Bool
+
+ public var id: String { identifier }
+
+ public init(
+ identifier: String,
+ title: String,
+ summary: String = "",
+ target: VPhonePatchTarget,
+ applicability: VPhonePatchApplicability = .always,
+ bootEssential: Bool = false,
+ ) {
+ self.identifier = identifier
+ self.title = title
+ self.summary = summary
+ self.target = target
+ self.applicability = applicability
+ self.bootEssential = bootEssential
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case identifier = "Identifier"
+ case title = "Title"
+ case summary = "Summary"
+ case target = "Target"
+ case applicability = "Applicability"
+ case bootEssential = "BootEssential"
+ }
+
+ public init(from decoder: any Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ identifier = try container.decode(String.self, forKey: .identifier)
+ guard !identifier.isEmpty else {
+ throw DecodingError.dataCorruptedError(
+ forKey: .identifier,
+ in: container,
+ debugDescription: "A patch identifier is what a preset names; it cannot be empty",
+ )
+ }
+ title = try container.decode(String.self, forKey: .title)
+ summary = try container.decodeIfPresent(String.self, forKey: .summary) ?? ""
+ target = try container.decode(VPhonePatchTarget.self, forKey: .target)
+ applicability = try container.decodeIfPresent(
+ VPhonePatchApplicability.self,
+ forKey: .applicability,
+ ) ?? .always
+ bootEssential = try container.decodeIfPresent(Bool.self, forKey: .bootEssential) ?? false
+ }
+
+ public func encode(to encoder: any Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encode(identifier, forKey: .identifier)
+ try container.encode(title, forKey: .title)
+ if !summary.isEmpty { try container.encode(summary, forKey: .summary) }
+ try container.encode(target, forKey: .target)
+ if applicability != .always { try container.encode(applicability, forKey: .applicability) }
+ if bootEssential { try container.encode(bootEssential, forKey: .bootEssential) }
+ }
+}
+
+extension VPhonePatchDeclaration {
+ /// Whether `recordIdentifier` came from this patch.
+ ///
+ /// A record either is the declaration itself or sits under it as
+ /// `<identifier><separator><site>`. Both separators count: record
+ /// identifiers predate declarations and spell their per-site suffix either
+ /// way — `jb.kcall10.sy_call` with a dot, `llb.rootfs_cbz_0x3b7` and
+ /// `sandbox_ext_267` with an underscore. A bare textual prefix does not
+ /// match, so `kernel.debuggerless` is not a site of `kernel.debugger`.
+ public func covers(recordIdentifier record: String) -> Bool {
+ record == identifier
+ || record.hasPrefix(identifier + ".")
+ || record.hasPrefix(identifier + "_")
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchGate.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchGate.swift
new file mode 100644
index 00000000..1f22efd1
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchGate.swift
@@ -0,0 +1,101 @@
+// VPhonePatchGate.swift — What a patcher asks before it writes.
+//
+// A gate is the plan reduced to the one question a patch site has: do I apply?
+// It is a value, not a reference, so a patcher can hold one without owning the
+// plan, and it defaults to ``unrestricted`` — a patcher built directly, as the
+// tests build them, behaves exactly as it did before gates existed.
+//
+// Gates answer about *record* identifiers, because that is what a patch site has
+// in hand, and record identifiers are finer than declarations: one declaration
+// covers `jb.kcall10.sy_call` and its three siblings. A record no declaration
+// covers is a gap in a manifest, not a patch the user turned off, so the gate
+// applies it and says so. Failing open keeps a missed declaration from silently
+// changing the firmware; the warning is what makes the gap findable.
+
+import Foundation
+
+public struct VPhonePatchGate: Sendable, Hashable {
+ private enum Policy: Sendable, Hashable {
+ case unrestricted
+ /// Declared identifiers, longest first, plus those that are enabled.
+ case plan(declared: [String], enabled: Set<String>)
+ }
+
+ private let policy: Policy
+
+ private init(policy: Policy) {
+ self.policy = policy
+ }
+
+ /// Every patch applies. The default, and what a directly built patcher gets.
+ public static let unrestricted = VPhonePatchGate(policy: .unrestricted)
+
+ /// Only the plan's enabled patches apply.
+ public init(plan: VPhonePatchPlan) {
+ policy = .plan(
+ // Longest first, so `kernel.sandbox.mount_check_mount` is consulted
+ // before a shorter declaration that also happens to cover the record.
+ declared: plan.declarations.map(\.identifier).sorted { $0.count > $1.count },
+ enabled: plan.enabled,
+ )
+ }
+
+ /// Only these declarations exist, and only these are on. For tests, and for a
+ /// caller that knows its own set without a preset in the way.
+ public init(declared: Set<String>, enabled: Set<String>) {
+ policy = .plan(declared: declared.sorted { $0.count > $1.count }, enabled: enabled)
+ }
+
+ /// Whether the patch declaring `identifier` is on.
+ ///
+ /// For a patch method that knows its own declared identifier. A method whose
+ /// sites carry finer record identifiers asks ``allows(record:)`` instead.
+ public func isEnabled(_ identifier: String) -> Bool {
+ switch policy {
+ case .unrestricted: true
+ case let .plan(_, enabled): enabled.contains(identifier)
+ }
+ }
+
+ /// Whether the site emitting `recordIdentifier` should be written.
+ ///
+ /// An undeclared record applies. See the file comment: a manifest gap must
+ /// not change the output.
+ public func allows(record recordIdentifier: String) -> Bool {
+ switch policy {
+ case .unrestricted:
+ return true
+ case let .plan(declared, enabled):
+ guard let owner = Self.declaration(covering: recordIdentifier, in: declared) else {
+ return true
+ }
+ return enabled.contains(owner)
+ }
+ }
+
+ /// True when `recordIdentifier` belongs to no declaration, so ``allows(record:)``
+ /// let it through only because failing open is safer than dropping it. The
+ /// caller logs this; nothing else should depend on it.
+ public func isUndeclared(record recordIdentifier: String) -> Bool {
+ switch policy {
+ case .unrestricted:
+ false
+ case let .plan(declared, _):
+ Self.declaration(covering: recordIdentifier, in: declared) == nil
+ }
+ }
+
+ /// True when the gate turns nothing off, so a caller can skip reporting.
+ public var isUnrestricted: Bool {
+ if case .unrestricted = policy { return true }
+ return false
+ }
+
+ /// The same rules as ``VPhonePatchDeclaration/covers(recordIdentifier:)``,
+ /// over a list already ordered longest first.
+ private static func declaration(covering record: String, in declared: [String]) -> String? {
+ declared.first {
+ record == $0 || record.hasPrefix($0 + ".") || record.hasPrefix($0 + "_")
+ }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchPlan.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchPlan.swift
new file mode 100644
index 00000000..7c861439
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchPlan.swift
@@ -0,0 +1,323 @@
+// VPhonePatchPlan.swift — Resolving a preset into the patches that will run.
+//
+// The resolver is the only place that decides whether a patch applies, and it
+// decides once, before anything is written. Every disagreement is an error
+// rather than a silent choice: a conflict, an unmet requirement, a duplicate
+// patch identifier and a name that matches nothing all stop the run. A plan that
+// resolves is a plan whose every patch is accounted for.
+
+import Foundation
+
+public struct VPhonePatchPlan: Sendable, Hashable {
+ /// The preset this plan came from.
+ public let presetIdentifier: String
+ /// The resolved sets, ordered so each runs after what it declared `After`.
+ public let patchSets: [VPhonePatchSetManifest]
+ /// The selection actually applied, preset plus any per-VM blocks.
+ public let selection: VPhonePatchSelection
+ /// The patch identifiers that will run.
+ public let enabled: Set<String>
+ /// Declared patches the selection kept but the OS pairing ruled out.
+ /// Reported so a log can say "not applicable here" rather than nothing.
+ public let skippedByVersion: Set<String>
+ /// Boot-essential patches this plan leaves out, in set order. Empty for a
+ /// plan whose guest is expected to boot unaided.
+ public let droppedBootEssentials: [String]
+ /// The preset's knobs, passed through to whichever set reads them.
+ public let parameters: [String: String]
+
+ /// Whether `identifier` — a declared patch identifier — runs.
+ public func isEnabled(_ identifier: String) -> Bool {
+ enabled.contains(identifier)
+ }
+
+ /// Whether the patch that emits `recordIdentifier` runs.
+ ///
+ /// Record identifiers are sometimes built at runtime (`sandbox_ext_3`,
+ /// `camera_dsc.<family>.<symbol>`), so this maps a record back to the
+ /// declaration that owns it instead of matching the full string.
+ public func isRecordEnabled(_ recordIdentifier: String) -> Bool {
+ guard let declaration = declaration(coveringRecord: recordIdentifier) else { return false }
+ return enabled.contains(declaration.identifier)
+ }
+
+ /// The declaration owning a record identifier, across every resolved set.
+ public func declaration(coveringRecord recordIdentifier: String) -> VPhonePatchDeclaration? {
+ for set in patchSets {
+ if let declaration = set.declaration(coveringRecord: recordIdentifier) {
+ return declaration
+ }
+ }
+ return nil
+ }
+
+ /// Every declared patch across the resolved sets, in set then declared order.
+ public var declarations: [VPhonePatchDeclaration] {
+ patchSets.flatMap(\.patches)
+ }
+
+ /// Whether this plan turns on any patch aimed at `target`.
+ ///
+ /// The pipeline asks before it insists a component produced patches: a preset
+ /// that turned everything off for one component leaves it legitimately
+ /// untouched, which is different from a patcher failing to find its site.
+ public func hasEnabledPatches(target: VPhonePatchTarget) -> Bool {
+ declarations.contains { $0.target == target && enabled.contains($0.identifier) }
+ }
+
+ /// Whether the plan includes the set with this identifier.
+ public func includesPatchSet(_ identifier: String) -> Bool {
+ patchSets.contains { $0.identifier == identifier }
+ }
+
+ /// The declaration for an identifier, if any set declares it.
+ public func declaration(for identifier: String) -> VPhonePatchDeclaration? {
+ for set in patchSets {
+ if let match = set.patches.first(where: { $0.identifier == identifier }) {
+ return match
+ }
+ }
+ return nil
+ }
+}
+
+// MARK: - Errors
+
+public enum VPhonePatchPlanError: Error, CustomStringConvertible, Sendable, Hashable {
+ /// The preset names a set nothing supplied.
+ case unknownPatchSet(preset: String, patchSet: String)
+ /// Two resolved sets claim the same identity.
+ case duplicatePatchSet(String)
+ /// Two sets declare the same patch identifier, so a selection naming it
+ /// would be ambiguous and both would write the same site.
+ case duplicatePatch(identifier: String, patchSets: [String])
+ /// A set needs a capability no resolved set provides.
+ case missingRequirement(patchSet: String, capability: String)
+ /// Two resolved sets declare they cannot sit together.
+ case conflict(patchSet: String, with: String, over: String)
+ /// The selection names a patch no resolved set declares.
+ case unknownPatch(preset: String, identifier: String)
+ /// A set needs a newer PatchKit than this framework is.
+ case patchKitTooOld(patchSet: String, required: VPhoneVersion, available: VPhoneVersion)
+ /// `After` declarations form a cycle, so no order satisfies them all.
+ case cyclicOrder([String])
+
+ public var description: String {
+ switch self {
+ case let .unknownPatchSet(preset, patchSet):
+ "Preset \(preset) names patch set \(patchSet), which is not available"
+ case let .duplicatePatchSet(identifier):
+ "Patch set \(identifier) is resolved twice"
+ case let .duplicatePatch(identifier, patchSets):
+ "Patch \(identifier) is declared by more than one set: \(patchSets.joined(separator: ", "))"
+ case let .missingRequirement(patchSet, capability):
+ "Patch set \(patchSet) requires \(capability), which no selected set provides"
+ case let .conflict(patchSet, other, capability):
+ "Patch sets \(patchSet) and \(other) conflict over \(capability)"
+ case let .unknownPatch(preset, identifier):
+ "Preset \(preset) names patch \(identifier), which no selected set declares"
+ case let .patchKitTooOld(patchSet, required, available):
+ "Patch set \(patchSet) needs PatchKit \(required); this is \(available)"
+ case let .cyclicOrder(identifiers):
+ "Patch set ordering is cyclic: \(identifiers.joined(separator: " → "))"
+ }
+ }
+}
+
+// MARK: - Resolve
+
+extension VPhonePatchPlan {
+ /// Resolve a preset against the sets that were loaded for it.
+ ///
+ /// - Parameters:
+ /// - preset: The preset to resolve.
+ /// - patchSets: Every manifest available, looked up by identifier. The
+ /// caller loads these; an external reference is checked against the
+ /// identifier its manifest declares before it gets here.
+ /// - iOSBase: The iPhone base `ProductVersion`, or nil when unread.
+ /// - cloudOS: The cloudOS `ProductVersion`, or nil when unread.
+ /// - blocked: Patch identifiers this VM turned off on top of the preset.
+ /// - allowed: Patch identifiers this VM turned on that the preset left off.
+ /// Together these two are the VM's checkmark state. Neither touches the
+ /// version gate: a patch pinned to one OS release still applies only there,
+ /// however it was selected.
+ /// - patchKitVersion: The API version to check sets against.
+ public static func resolve(
+ preset: VPhonePatchPreset,
+ patchSets available: [VPhonePatchSetManifest],
+ iOSBase: VPhoneVersion?,
+ cloudOS: VPhoneVersion?,
+ blocked: Set<String> = [],
+ allowed: Set<String> = [],
+ patchKitVersion: VPhoneVersion = .currentPatchKit,
+ ) throws -> VPhonePatchPlan {
+ var byIdentifier: [String: VPhonePatchSetManifest] = [:]
+ for set in available {
+ guard byIdentifier.updateValue(set, forKey: set.identifier) == nil else {
+ throw VPhonePatchPlanError.duplicatePatchSet(set.identifier)
+ }
+ }
+
+ // 1. Every reference resolves, exactly once.
+ var resolved: [VPhonePatchSetManifest] = []
+ var seen = Set<String>()
+ for reference in preset.patchSets {
+ guard let set = byIdentifier[reference.identifier] else {
+ throw VPhonePatchPlanError.unknownPatchSet(
+ preset: preset.identifier,
+ patchSet: reference.identifier,
+ )
+ }
+ guard seen.insert(set.identifier).inserted else {
+ throw VPhonePatchPlanError.duplicatePatchSet(set.identifier)
+ }
+ resolved.append(set)
+ }
+
+ // 2. This PatchKit is new enough for all of them.
+ for set in resolved where set.minimumPatchKitVersion > patchKitVersion {
+ throw VPhonePatchPlanError.patchKitTooOld(
+ patchSet: set.identifier,
+ required: set.minimumPatchKitVersion,
+ available: patchKitVersion,
+ )
+ }
+
+ // 3. No two sets declare the same patch. A replacement set gives its
+ // patch a new identifier and the preset blocks the original, so
+ // shadowing never has to be guessed at.
+ var owner: [String: String] = [:]
+ for set in resolved {
+ for patch in set.patches {
+ if let previous = owner[patch.identifier] {
+ throw VPhonePatchPlanError.duplicatePatch(
+ identifier: patch.identifier,
+ patchSets: [previous, set.identifier],
+ )
+ }
+ owner[patch.identifier] = set.identifier
+ }
+ }
+
+ // 4. Capabilities: requirements met, and nothing conflicting present.
+ // A capability may have more than one provider, so every provider is
+ // recorded — ordering against only one of them would be a silent choice
+ // about which `After` meant.
+ var capabilityProviders: [String: [String]] = [:]
+ for set in resolved {
+ for capability in set.capabilities.sorted() {
+ capabilityProviders[capability, default: []].append(set.identifier)
+ }
+ }
+ for set in resolved {
+ for capability in set.requires where capabilityProviders[capability] == nil {
+ throw VPhonePatchPlanError.missingRequirement(
+ patchSet: set.identifier,
+ capability: capability,
+ )
+ }
+ }
+ for set in resolved {
+ for capability in set.conflictsWith {
+ for other in capabilityProviders[capability] ?? [] where other != set.identifier {
+ throw VPhonePatchPlanError.conflict(
+ patchSet: set.identifier,
+ with: other,
+ over: capability,
+ )
+ }
+ }
+ }
+
+ // 5. Order by `After`, keeping the preset's listing order as the
+ // tie-break so a plan is reproducible.
+ let ordered = try order(resolved, capabilityProviders: capabilityProviders)
+
+ // 6. The selection must name only patches that exist, so a typo in a
+ // prewritten preset fails here instead of turning nothing on.
+ let declared = Set(owner.keys)
+ let selection = preset.selection.allowing(allowed).blocking(blocked)
+ for identifier in preset.selection.namedIdentifiers.union(allowed).union(blocked)
+ where !declared.contains(identifier)
+ {
+ throw VPhonePatchPlanError.unknownPatch(preset: preset.identifier, identifier: identifier)
+ }
+
+ // 7. Selection first, then the version gate, so a patch that is off and
+ // a patch that does not apply here stay distinguishable in the log.
+ var enabled = Set<String>()
+ var skippedByVersion = Set<String>()
+ var droppedBootEssentials: [String] = []
+ for set in ordered {
+ for patch in set.patches {
+ guard selection.includes(patch.identifier) else {
+ if patch.bootEssential { droppedBootEssentials.append(patch.identifier) }
+ continue
+ }
+ if patch.applicability.matches(iOSBase: iOSBase, cloudOS: cloudOS) {
+ enabled.insert(patch.identifier)
+ } else {
+ skippedByVersion.insert(patch.identifier)
+ }
+ }
+ }
+
+ return VPhonePatchPlan(
+ presetIdentifier: preset.identifier,
+ patchSets: ordered,
+ selection: selection,
+ enabled: enabled,
+ skippedByVersion: skippedByVersion,
+ droppedBootEssentials: droppedBootEssentials,
+ parameters: preset.parameters,
+ )
+ }
+
+ /// Stable topological sort over `After`. A set whose `After` names something
+ /// absent has nothing to wait for, so the edge is simply dropped.
+ private static func order(
+ _ sets: [VPhonePatchSetManifest],
+ capabilityProviders: [String: [String]],
+ ) throws -> [VPhonePatchSetManifest] {
+ let position = Dictionary(uniqueKeysWithValues: sets.enumerated().map { ($0.element.identifier, $0.offset) })
+ var predecessors: [String: Set<String>] = [:]
+ var successors: [String: Set<String>] = [:]
+ for set in sets {
+ predecessors[set.identifier] = []
+ successors[set.identifier] = []
+ }
+ for set in sets {
+ for capability in set.after {
+ for earlier in capabilityProviders[capability] ?? [] where earlier != set.identifier {
+ predecessors[set.identifier]?.insert(earlier)
+ successors[earlier]?.insert(set.identifier)
+ }
+ }
+ }
+
+ var ready = sets.filter { predecessors[$0.identifier]?.isEmpty ?? true }.map(\.identifier)
+ var result: [VPhonePatchSetManifest] = []
+ let byIdentifier = Dictionary(uniqueKeysWithValues: sets.map { ($0.identifier, $0) })
+ while !ready.isEmpty {
+ ready.sort { (position[$0] ?? 0) < (position[$1] ?? 0) }
+ let next = ready.removeFirst()
+ guard let set = byIdentifier[next] else { continue }
+ result.append(set)
+ for successor in (successors[next] ?? []).sorted() {
+ predecessors[successor]?.remove(next)
+ if predecessors[successor]?.isEmpty == true {
+ ready.append(successor)
+ }
+ }
+ successors[next] = []
+ }
+
+ guard result.count == sets.count else {
+ let placed = Set(result.map(\.identifier))
+ throw VPhonePatchPlanError.cyclicOrder(
+ sets.map(\.identifier).filter { !placed.contains($0) },
+ )
+ }
+ return result
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchPreset.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchPreset.swift
new file mode 100644
index 00000000..ad72aba4
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchPreset.swift
@@ -0,0 +1,201 @@
+// VPhonePatchPreset.swift — A named, prewritten combination of patch sets.
+//
+// Presets ship inside the bundle at `Contents/Resources/patches_presets/`. They
+// are written by this project, not filled in by users: a preset is a reviewed
+// claim that this combination boots. `standard` is what every VM gets; any other
+// preset is opted into explicitly with `--preset`.
+//
+// A per-VM override does not edit a preset — it narrows one, through
+// ``VPhonePatchSelection/blocking(_:)``.
+
+import Foundation
+
+/// Where a plan finds a patch set.
+///
+/// Both cases name the identifier the preset expects. An external set is loaded
+/// from a path, and the manifest found there must declare that identifier —
+/// otherwise replacing the file at that path would silently change which patches
+/// a preset applies.
+public enum VPhonePatchSetReference: Sendable, Hashable {
+ /// A set built into the bundle, named by identifier.
+ case bundled(String)
+ /// A `.vphonepatchset` outside the bundle, at a path on the host.
+ ///
+ /// Root `cfw install` refuses these outright: an external set reaches a
+ /// privileged run only after the Launchpad helper has imported it and pinned
+ /// its cdhash.
+ case external(identifier: String, path: String)
+}
+
+extension VPhonePatchSetReference {
+ /// The set identity this reference expects, whichever way it points at it.
+ public var identifier: String {
+ switch self {
+ case let .bundled(identifier): identifier
+ case let .external(identifier, _): identifier
+ }
+ }
+}
+
+public struct VPhonePatchPreset: Sendable, Hashable, Codable, Identifiable {
+ /// Selection identity, passed to `--preset`.
+ public var identifier: String
+ /// Display name for a picker.
+ public var title: String
+ /// One line on what the preset is for.
+ public var summary: String
+ /// The sets this preset draws patches from, in listed order.
+ public var patchSets: [VPhonePatchSetReference]
+ /// Which of the declared patches are on.
+ public var selection: VPhonePatchSelection
+ /// Free-form knobs a patch set reads, such as a size override.
+ public var parameters: [String: String]
+
+ public var id: String { identifier }
+
+ public init(
+ identifier: String,
+ title: String,
+ summary: String = "",
+ patchSets: [VPhonePatchSetReference],
+ selection: VPhonePatchSelection = .all,
+ parameters: [String: String] = [:],
+ ) {
+ self.identifier = identifier
+ self.title = title
+ self.summary = summary
+ self.patchSets = patchSets
+ self.selection = selection
+ self.parameters = parameters
+ }
+
+ /// The identifier a VM gets when nothing asked for another preset.
+ public static let standardIdentifier = "standard"
+
+ /// Whether this is the preset a VM gets by default.
+ public var isStandard: Bool { identifier == Self.standardIdentifier }
+
+ /// True when the preset draws on a set from outside the bundle. Root
+ /// `cfw install` refuses such a preset unless the set was imported first.
+ public var usesExternalPatchSets: Bool {
+ patchSets.contains { if case .external = $0 { true } else { false } }
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case identifier = "Identifier"
+ case title = "Title"
+ case summary = "Summary"
+ case patchSets = "PatchSets"
+ case selection = "Selection"
+ case parameters = "Parameters"
+ }
+
+ public init(from decoder: any Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ identifier = try container.decode(String.self, forKey: .identifier)
+ title = try container.decode(String.self, forKey: .title)
+ summary = try container.decodeIfPresent(String.self, forKey: .summary) ?? ""
+ patchSets = try container.decode([VPhonePatchSetReference].self, forKey: .patchSets)
+ selection = try container.decodeIfPresent(VPhonePatchSelection.self, forKey: .selection) ?? .all
+ parameters = try container.decodeIfPresent([String: String].self, forKey: .parameters) ?? [:]
+ guard !identifier.isEmpty else {
+ throw DecodingError.dataCorruptedError(
+ forKey: .identifier,
+ in: container,
+ debugDescription: "A preset identifier is what --preset names; it cannot be empty",
+ )
+ }
+ }
+
+ public func encode(to encoder: any Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encode(identifier, forKey: .identifier)
+ try container.encode(title, forKey: .title)
+ if !summary.isEmpty { try container.encode(summary, forKey: .summary) }
+ try container.encode(patchSets, forKey: .patchSets)
+ try container.encode(selection, forKey: .selection)
+ if !parameters.isEmpty { try container.encode(parameters, forKey: .parameters) }
+ }
+}
+
+// MARK: - Reference Coding
+
+extension VPhonePatchSetReference: Codable {
+ private enum Kind: String, Codable {
+ case bundled = "Bundled"
+ case external = "External"
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case kind = "Kind"
+ case identifier = "Identifier"
+ case path = "Path"
+ }
+
+ public init(from decoder: any Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ switch try container.decode(Kind.self, forKey: .kind) {
+ case .bundled:
+ self = .bundled(try container.decode(String.self, forKey: .identifier))
+ case .external:
+ self = .external(
+ identifier: try container.decode(String.self, forKey: .identifier),
+ path: try container.decode(String.self, forKey: .path),
+ )
+ }
+ }
+
+ public func encode(to encoder: any Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ switch self {
+ case let .bundled(identifier):
+ try container.encode(Kind.bundled, forKey: .kind)
+ try container.encode(identifier, forKey: .identifier)
+ case let .external(identifier, path):
+ try container.encode(Kind.external, forKey: .kind)
+ try container.encode(identifier, forKey: .identifier)
+ try container.encode(path, forKey: .path)
+ }
+ }
+}
+
+extension VPhonePatchSetReference: CustomStringConvertible {
+ public var description: String {
+ switch self {
+ case let .bundled(identifier): identifier
+ case let .external(identifier, path): "\(identifier) (external, \(path))"
+ }
+ }
+}
+
+// MARK: - Plist IO
+
+extension VPhonePatchPreset {
+ /// The bundle subdirectory holding the shipped presets.
+ public static let resourceDirectoryName = "patches_presets"
+
+ /// Read every preset in a `patches_presets` directory, sorted by identifier
+ /// with `standard` first so a picker's order is stable.
+ public static func readAll(fromDirectory directory: URL) throws -> [VPhonePatchPreset] {
+ let names = try FileManager.default.contentsOfDirectory(atPath: directory.path)
+ var presets: [VPhonePatchPreset] = []
+ for name in names.sorted() where name.hasSuffix(".plist") {
+ let url = directory.appendingPathComponent(name)
+ presets.append(try decode(Data(contentsOf: url)))
+ }
+ return presets.sorted {
+ if $0.isStandard != $1.isStandard { return $0.isStandard }
+ return $0.identifier < $1.identifier
+ }
+ }
+
+ public static func decode(_ data: Data) throws -> VPhonePatchPreset {
+ try PropertyListDecoder().decode(VPhonePatchPreset.self, from: data)
+ }
+
+ public func encodedPlist() throws -> Data {
+ let encoder = PropertyListEncoder()
+ encoder.outputFormat = .xml
+ return try encoder.encode(self)
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchSelection.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchSelection.swift
new file mode 100644
index 00000000..b46c045f
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchSelection.swift
@@ -0,0 +1,124 @@
+// VPhonePatchSelection.swift — Which declared patches a preset turns on.
+//
+// The selection is either an allow list or a block list, never both: the two
+// read the same in a plist but mean opposite things for a patch nobody named,
+// and a manifest able to carry both invites a preset where one list silently
+// wins. Making them separate cases removes the question.
+
+import Foundation
+
+public enum VPhonePatchSelection: Sendable, Hashable {
+ /// Every declared patch whose version gate matches.
+ case all
+ /// Only these patch identifiers. A patch nobody named is off.
+ case allow(Set<String>)
+ /// Everything except these identifiers. A patch nobody named is on.
+ case block(Set<String>)
+}
+
+extension VPhonePatchSelection {
+ /// Whether the selection names this patch as enabled, before the version
+ /// gate is consulted.
+ public func includes(_ identifier: String) -> Bool {
+ switch self {
+ case .all: true
+ case let .allow(identifiers): identifiers.contains(identifier)
+ case let .block(identifiers): !identifiers.contains(identifier)
+ }
+ }
+
+ /// The identifiers the selection names, whichever way it names them.
+ /// The resolver checks these against the declared patches so a typo is an
+ /// error rather than an allow list that turns nothing on.
+ public var namedIdentifiers: Set<String> {
+ switch self {
+ case .all: []
+ case let .allow(identifiers), let .block(identifiers): identifiers
+ }
+ }
+
+ /// The same selection with `identifiers` additionally turned off.
+ ///
+ /// Half of how a VM's own checkmarks compose with a preset: unchecking a patch
+ /// narrows an allow list and widens a block list.
+ public func blocking(_ identifiers: Set<String>) -> VPhonePatchSelection {
+ guard !identifiers.isEmpty else { return self }
+ switch self {
+ case .all:
+ return .block(identifiers)
+ case let .allow(allowed):
+ return .allow(allowed.subtracting(identifiers))
+ case let .block(blocked):
+ return .block(blocked.union(identifiers))
+ }
+ }
+
+ /// The same selection with `identifiers` additionally turned on.
+ ///
+ /// The other half: checking a patch the preset left out widens an allow list
+ /// and narrows a block list. It changes only the selection — a patch whose
+ /// version gate rules it out here still does not apply, so checking a box can
+ /// never put a patch somewhere it was never meant to run.
+ public func allowing(_ identifiers: Set<String>) -> VPhonePatchSelection {
+ guard !identifiers.isEmpty else { return self }
+ switch self {
+ case .all:
+ return .all
+ case let .allow(allowed):
+ return .allow(allowed.union(identifiers))
+ case let .block(blocked):
+ return .block(blocked.subtracting(identifiers))
+ }
+ }
+}
+
+// MARK: - Plist Coding
+
+extension VPhonePatchSelection: Codable {
+ private enum Kind: String, Codable {
+ case all = "All"
+ case allow = "Allow"
+ case block = "Block"
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case kind = "Kind"
+ case patches = "Patches"
+ }
+
+ public init(from decoder: any Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ switch try container.decode(Kind.self, forKey: .kind) {
+ case .all:
+ self = .all
+ case .allow:
+ self = .allow(Set(try container.decode([String].self, forKey: .patches)))
+ case .block:
+ self = .block(Set(try container.decode([String].self, forKey: .patches)))
+ }
+ }
+
+ public func encode(to encoder: any Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ switch self {
+ case .all:
+ try container.encode(Kind.all, forKey: .kind)
+ case let .allow(identifiers):
+ try container.encode(Kind.allow, forKey: .kind)
+ try container.encode(identifiers.sorted(), forKey: .patches)
+ case let .block(identifiers):
+ try container.encode(Kind.block, forKey: .kind)
+ try container.encode(identifiers.sorted(), forKey: .patches)
+ }
+ }
+}
+
+extension VPhonePatchSelection: CustomStringConvertible {
+ public var description: String {
+ switch self {
+ case .all: "all patches"
+ case let .allow(identifiers): "only \(identifiers.count) patch(es)"
+ case let .block(identifiers): "all but \(identifiers.count) patch(es)"
+ }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchSetBundle.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchSetBundle.swift
new file mode 100644
index 00000000..320afc96
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchSetBundle.swift
@@ -0,0 +1,283 @@
+// VPhonePatchSetBundle.swift — Opening a `.vphonepatchset`.
+//
+// The layout, which is an ordinary macOS loadable bundle:
+//
+// Example.vphonepatchset/
+// Contents/
+// Info.plist CFBundleExecutable names the binary below
+// MacOS/Example exports vphone_patch_set_principal,
+// linked against @rpath/VPhonePatchKit.framework
+// Resources/Manifest.plist
+// _CodeSignature/
+//
+// Everything a plan needs is in the manifest, and the manifest is read *before*
+// any code from the set is loaded — so a set that conflicts, requires something
+// absent or needs a newer PatchKit is refused without ever being mapped.
+//
+// The checks, in the order they run:
+//
+// 1. The path is a bundle with a readable `Contents/Resources/Manifest.plist`.
+// 2. The manifest declares the identifier the preset pinned. A preset names both
+// identifier and path so that swapping the file at that path is an error
+// rather than a silent change of which patches apply.
+// 3. This PatchKit is new enough for `MinimumPatchKitVersion`.
+// 4. Every declared patch targets the boot chain. A guest-side patch would have
+// to run inside `cfw install`, which is the one privileged step — and it
+// loads no external set at all. Declaring one would promise a patch that
+// never runs.
+// 5. The code signature is valid, strictly and including nested code. Ad hoc
+// counts: this proves the bundle has not changed since it was signed, not
+// who wrote it. `vphone-cli patchset import` is what ad hoc signs an
+// unsigned set, deliberately as a separate, explicit step.
+//
+// Only then is the executable mapped and its exported factory called.
+
+import Foundation
+import Security
+
+// MARK: - Errors
+
+public enum VPhonePatchSetError: Error, CustomStringConvertible, Sendable, Hashable {
+ case notABundle(path: String)
+ case manifestUnreadable(path: String, reason: String)
+ case identifierMismatch(path: String, expected: String, found: String)
+ case patchKitTooOld(patchSet: String, required: VPhoneVersion, available: VPhoneVersion)
+ case notBootChainOnly(patchSet: String, patch: String, target: String)
+ case signatureInvalid(path: String, reason: String)
+ case unsigned(path: String)
+ case principalMissing(path: String, symbol: String)
+ case principalWrongType(path: String, type: String)
+ case executableUnloadable(path: String, reason: String)
+ case componentUnsupported(principal: String, component: String)
+
+ public var description: String {
+ switch self {
+ case let .notABundle(path):
+ "\(path) is not a .\(VPhonePatchSetBundle.pathExtension) bundle"
+ case let .manifestUnreadable(path, reason):
+ "\(path) has no readable \(VPhonePatchSetManifest.resourceName): \(reason)"
+ case let .identifierMismatch(path, expected, found):
+ "\(path) declares patch set \(found); the preset pinned \(expected)"
+ case let .patchKitTooOld(patchSet, required, available):
+ "Patch set \(patchSet) needs PatchKit \(required); this is \(available)"
+ case let .notBootChainOnly(patchSet, patch, target):
+ "Patch set \(patchSet) declares \(patch) for \(target). A loaded patch set can only"
+ + " patch the boot chain: the guest half of an install runs as root and loads no"
+ + " external set."
+ case let .signatureInvalid(path, reason):
+ "\(path) has an invalid code signature: \(reason)."
+ + " Re-import it with `vphone-cli patchset import`."
+ case let .unsigned(path):
+ "\(path) is not signed. Run `vphone-cli patchset import \(path)` to ad hoc sign it."
+ case let .principalMissing(path, symbol):
+ "\(path) exports no \(symbol). A patch set defines it once with @_cdecl;"
+ + " see VPhonePatchSetPrincipal."
+ case let .principalWrongType(path, type):
+ "\(path) returned a \(type), which is not a VPhonePatchSetPrincipal."
+ + " It was probably built against a different VPhonePatchKit."
+ case let .executableUnloadable(path, reason):
+ "\(path) has no loadable executable: \(reason)"
+ case let .componentUnsupported(principal, component):
+ "\(principal) declares a patch for \(component) but builds no patcher for it"
+ }
+ }
+}
+
+// MARK: - Bundle
+
+/// A patch set on disk, with its manifest read and nothing loaded yet.
+public struct VPhonePatchSetBundle: Sendable {
+ /// The extension a patch set carries.
+ public static let pathExtension = "vphonepatchset"
+
+ public let url: URL
+ public let manifest: VPhonePatchSetManifest
+
+ private init(url: URL, manifest: VPhonePatchSetManifest) {
+ self.url = url
+ self.manifest = manifest
+ }
+
+ // MARK: Inspect
+
+ /// Read the manifest at `url` without loading any code.
+ ///
+ /// `~` is expanded, so a preset can name a set under the user's home without
+ /// hardcoding it.
+ public static func inspect(at url: URL) throws -> VPhonePatchSetBundle {
+ let resolved = URL(
+ fileURLWithPath: (url.path as NSString).expandingTildeInPath,
+ isDirectory: true,
+ )
+ guard resolved.pathExtension == pathExtension,
+ Bundle(url: resolved) != nil
+ else {
+ throw VPhonePatchSetError.notABundle(path: resolved.path)
+ }
+ do {
+ return VPhonePatchSetBundle(
+ url: resolved,
+ manifest: try VPhonePatchSetManifest.read(fromBundle: resolved),
+ )
+ } catch {
+ throw VPhonePatchSetError.manifestUnreadable(
+ path: resolved.path,
+ reason: "\(error)",
+ )
+ }
+ }
+
+ // MARK: Validate
+
+ /// Every check that can be made before the executable is mapped.
+ ///
+ /// - Parameters:
+ /// - identifier: What the preset pinned, or nil when nothing pinned one
+ /// (`patchset info` on a file the user named directly).
+ /// - patchKitVersion: The API version to check the set against.
+ /// - requireSignature: False only for a set being examined *in order to*
+ /// sign it — `patchset import` reads the manifest of an unsigned bundle
+ /// before it signs one. Loading never passes false.
+ public func validate(
+ expecting identifier: String?,
+ patchKitVersion: VPhoneVersion = .currentPatchKit,
+ requireSignature: Bool = true,
+ ) throws {
+ if let identifier, manifest.identifier != identifier {
+ throw VPhonePatchSetError.identifierMismatch(
+ path: url.path,
+ expected: identifier,
+ found: manifest.identifier,
+ )
+ }
+ guard manifest.minimumPatchKitVersion <= patchKitVersion else {
+ throw VPhonePatchSetError.patchKitTooOld(
+ patchSet: manifest.identifier,
+ required: manifest.minimumPatchKitVersion,
+ available: patchKitVersion,
+ )
+ }
+ for patch in manifest.patches where !patch.target.isBootChain {
+ throw VPhonePatchSetError.notBootChainOnly(
+ patchSet: manifest.identifier,
+ patch: patch.identifier,
+ target: patch.target.description,
+ )
+ }
+ if requireSignature {
+ try requireValidSignature()
+ }
+ }
+
+ /// The firmware components this set has an enabled patch for, in declared
+ /// order and without repeats.
+ ///
+ /// The manifest decides which components the set's code is asked about, so a
+ /// set whose patches are all off contributes no patcher at all — the same rule
+ /// the bundled sets follow, and for the same reason: a patcher built anyway
+ /// would emit records and an undeclared record applies.
+ public func enabledComponents(in plan: VPhonePatchPlan) -> [VPhoneFirmwareComponent] {
+ var components: [VPhoneFirmwareComponent] = []
+ for patch in manifest.patches where plan.isEnabled(patch.identifier) {
+ guard case let .firmware(component) = patch.target,
+ !components.contains(component)
+ else { continue }
+ components.append(component)
+ }
+ return components
+ }
+
+ // MARK: Signature
+
+ /// Refuse anything but a signature that still matches the bytes on disk.
+ ///
+ /// Strict and nested, the same flags the Launchpad helper uses on a release
+ /// bundle. Ad hoc passes: no designated requirement is checked, because a
+ /// researcher's own patch set has no team to check it against. What this does
+ /// prove is that the set has not been altered since it was signed, which is
+ /// what makes `patchset import`'s pinned cdhash mean something.
+ public func requireValidSignature() throws {
+ var code: SecStaticCode?
+ let created = SecStaticCodeCreateWithPath(url as CFURL, [], &code)
+ guard created == errSecSuccess, let code else {
+ throw VPhonePatchSetError.unsigned(path: url.path)
+ }
+ let flags = SecCSFlags(
+ rawValue: kSecCSCheckAllArchitectures | kSecCSStrictValidate | kSecCSCheckNestedCode,
+ )
+ var failure: Unmanaged<CFError>?
+ let status = SecStaticCodeCheckValidityWithErrors(code, flags, nil, &failure)
+ guard status != errSecSuccess else { return }
+ let reason = failure.map { "\($0.takeRetainedValue())" }
+ ?? "OSStatus \(status)"
+ if status == errSecCSUnsigned {
+ throw VPhonePatchSetError.unsigned(path: url.path)
+ }
+ throw VPhonePatchSetError.signatureInvalid(path: url.path, reason: reason)
+ }
+
+ /// The bundle's code-directory hash, hex, for pinning at import.
+ public func codeDirectoryHash() throws -> String {
+ var code: SecStaticCode?
+ guard SecStaticCodeCreateWithPath(url as CFURL, [], &code) == errSecSuccess,
+ let code
+ else {
+ throw VPhonePatchSetError.unsigned(path: url.path)
+ }
+ var information: CFDictionary?
+ guard SecCodeCopySigningInformation(
+ code,
+ SecCSFlags(rawValue: kSecCSSigningInformation),
+ &information,
+ ) == errSecSuccess,
+ let entries = information as? [String: Any],
+ let hash = entries[kSecCodeInfoUnique as String] as? Data
+ else {
+ throw VPhonePatchSetError.unsigned(path: url.path)
+ }
+ return hash.hex
+ }
+
+ // MARK: Load
+
+ /// Map the executable and call the set's exported factory.
+ ///
+ /// Call ``validate(expecting:patchKitVersion:requireSignature:)`` first. This
+ /// is the step after which the set's own code is running, and there is no step
+ /// after it that can take that back — a bundle is never unloaded, because Swift
+ /// metadata from a dlclosed image would outlive the mapping. `dlopen` is
+ /// therefore never paired with a `dlclose`, and a second call on an image
+ /// already mapped simply returns its handle.
+ public func loadPrincipal() throws -> VPhonePatchSetPrincipal {
+ guard let bundle = Bundle(url: url),
+ let executable = bundle.executableURL
+ else {
+ throw VPhonePatchSetError.notABundle(path: url.path)
+ }
+ guard let handle = dlopen(executable.path, RTLD_LAZY | RTLD_LOCAL) else {
+ throw VPhonePatchSetError.executableUnloadable(
+ path: executable.path,
+ reason: dlerror().map { String(cString: $0) } ?? "dlopen failed",
+ )
+ }
+ guard let symbol = dlsym(handle, vphonePatchSetPrincipalSymbol) else {
+ throw VPhonePatchSetError.principalMissing(
+ path: url.path,
+ symbol: vphonePatchSetPrincipalSymbol,
+ )
+ }
+ typealias Factory = @convention(c) () -> UnsafeMutableRawPointer
+ let made = unsafeBitCast(symbol, to: Factory.self)()
+ // Taken retained: the set's side handed over its reference. Checked rather
+ // than assumed, because a set built against a different PatchKit would
+ // return an object of a class this framework knows nothing about.
+ let object = Unmanaged<AnyObject>.fromOpaque(made).takeRetainedValue()
+ guard let principal = object as? VPhonePatchSetPrincipal else {
+ throw VPhonePatchSetError.principalWrongType(
+ path: url.path,
+ type: String(reflecting: type(of: object)),
+ )
+ }
+ return principal
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchSetManifest.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchSetManifest.swift
new file mode 100644
index 00000000..33020068
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchSetManifest.swift
@@ -0,0 +1,163 @@
+// VPhonePatchSetManifest.swift — What one patch set declares about itself.
+//
+// Every patch set — the ones built into the bundle and the ones loaded from a
+// `.vphonepatchset` — carries this as `Contents/Resources/Manifest.plist`. It is
+// read before any code from the set runs, so the resolver can reject a broken
+// combination without loading a single patch.
+
+import Foundation
+
+public struct VPhonePatchSetManifest: Sendable, Hashable, Codable, Identifiable {
+ /// Reverse-DNS identity, unique across a plan. Also an implicit capability.
+ public var identifier: String
+ /// Display name for a preset picker.
+ public var name: String
+ /// The set's own version, for logs and bug reports.
+ public var version: String
+ /// One line on what the set is for.
+ public var summary: String
+ /// The PatchKit API this set needs. A newer requirement is refused.
+ public var minimumPatchKitVersion: VPhoneVersion
+ /// Every patch the set can apply, in the order it applies them.
+ public var patches: [VPhonePatchDeclaration]
+ /// Capabilities that must be present, provided by this set or another.
+ public var requires: [String]
+ /// Capability names this set supplies beyond its own identifier.
+ public var provides: [String]
+ /// Sets or capabilities this one cannot sit beside. Enforced symmetrically:
+ /// either side naming the other is a conflict, so a set need not be patched
+ /// to learn about a newer rival.
+ public var conflictsWith: [String]
+ /// Sets or capabilities that must run before this one, when both are present.
+ public var after: [String]
+
+ public var id: String { identifier }
+
+ public init(
+ identifier: String,
+ name: String,
+ version: String = "1.0",
+ summary: String = "",
+ minimumPatchKitVersion: VPhoneVersion = VPhoneVersion(major: 1, minor: 0),
+ patches: [VPhonePatchDeclaration],
+ requires: [String] = [],
+ provides: [String] = [],
+ conflictsWith: [String] = [],
+ after: [String] = [],
+ ) {
+ self.identifier = identifier
+ self.name = name
+ self.version = version
+ self.summary = summary
+ self.minimumPatchKitVersion = minimumPatchKitVersion
+ self.patches = patches
+ self.requires = requires
+ self.provides = provides
+ self.conflictsWith = conflictsWith
+ self.after = after
+ }
+
+ /// The set's identity plus everything it declares it provides.
+ public var capabilities: Set<String> {
+ Set(provides).union([identifier])
+ }
+
+ /// The declaration owning `recordIdentifier`, if this set emits it.
+ public func declaration(coveringRecord recordIdentifier: String) -> VPhonePatchDeclaration? {
+ // Longest identifier first, so `kernel.debugger.ret` is attributed to
+ // `kernel.debugger` rather than to a shorter `kernel` umbrella.
+ patches
+ .filter { $0.covers(recordIdentifier: recordIdentifier) }
+ .max { $0.identifier.count < $1.identifier.count }
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case identifier = "Identifier"
+ case name = "Name"
+ case version = "Version"
+ case summary = "Summary"
+ case minimumPatchKitVersion = "MinimumPatchKitVersion"
+ case patches = "Patches"
+ case requires = "Requires"
+ case provides = "Provides"
+ case conflictsWith = "ConflictsWith"
+ case after = "After"
+ }
+
+ public init(from decoder: any Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ identifier = try container.decode(String.self, forKey: .identifier)
+ name = try container.decode(String.self, forKey: .name)
+ version = try container.decodeIfPresent(String.self, forKey: .version) ?? "1.0"
+ summary = try container.decodeIfPresent(String.self, forKey: .summary) ?? ""
+ minimumPatchKitVersion = try container.decodeIfPresent(
+ VPhoneVersion.self,
+ forKey: .minimumPatchKitVersion,
+ ) ?? VPhoneVersion(major: 1, minor: 0)
+ patches = try container.decode([VPhonePatchDeclaration].self, forKey: .patches)
+ requires = try container.decodeIfPresent([String].self, forKey: .requires) ?? []
+ provides = try container.decodeIfPresent([String].self, forKey: .provides) ?? []
+ conflictsWith = try container.decodeIfPresent([String].self, forKey: .conflictsWith) ?? []
+ after = try container.decodeIfPresent([String].self, forKey: .after) ?? []
+
+ guard !identifier.isEmpty else {
+ throw DecodingError.dataCorruptedError(
+ forKey: .identifier,
+ in: container,
+ debugDescription: "A patch set identifier is what a preset names; it cannot be empty",
+ )
+ }
+ var seen = Set<String>()
+ for patch in patches where !seen.insert(patch.identifier).inserted {
+ throw DecodingError.dataCorruptedError(
+ forKey: .patches,
+ in: container,
+ debugDescription: "\(identifier) declares \(patch.identifier) twice",
+ )
+ }
+ }
+
+ public func encode(to encoder: any Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encode(identifier, forKey: .identifier)
+ try container.encode(name, forKey: .name)
+ try container.encode(version, forKey: .version)
+ if !summary.isEmpty { try container.encode(summary, forKey: .summary) }
+ try container.encode(minimumPatchKitVersion, forKey: .minimumPatchKitVersion)
+ try container.encode(patches, forKey: .patches)
+ if !requires.isEmpty { try container.encode(requires, forKey: .requires) }
+ if !provides.isEmpty { try container.encode(provides, forKey: .provides) }
+ if !conflictsWith.isEmpty { try container.encode(conflictsWith, forKey: .conflictsWith) }
+ if !after.isEmpty { try container.encode(after, forKey: .after) }
+ }
+}
+
+// MARK: - Plist IO
+
+extension VPhonePatchSetManifest {
+ /// The path a patch-set bundle keeps its manifest at.
+ public static let resourceName = "Manifest.plist"
+
+ /// Read a manifest from a `.vphonepatchset` bundle directory.
+ public static func read(fromBundle bundle: URL) throws -> VPhonePatchSetManifest {
+ let url = bundle
+ .appendingPathComponent("Contents", isDirectory: true)
+ .appendingPathComponent("Resources", isDirectory: true)
+ .appendingPathComponent(resourceName)
+ guard FileManager.default.fileExists(atPath: url.path) else {
+ throw PatcherError.fileNotFound(url.path)
+ }
+ return try decode(Data(contentsOf: url))
+ }
+
+ public static func decode(_ data: Data) throws -> VPhonePatchSetManifest {
+ try PropertyListDecoder().decode(VPhonePatchSetManifest.self, from: data)
+ }
+
+ /// Encode as an XML plist, the form a patch set checks into source control.
+ public func encodedPlist() throws -> Data {
+ let encoder = PropertyListEncoder()
+ encoder.outputFormat = .xml
+ return try encoder.encode(self)
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchSetPrincipal.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchSetPrincipal.swift
new file mode 100644
index 00000000..7969537e
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchSetPrincipal.swift
@@ -0,0 +1,116 @@
+// VPhonePatchSetPrincipal.swift — The class a `.vphonepatchset` exposes.
+//
+// This is the whole code-side contract between the tool and an out-of-tree patch
+// set. The set is a loadable macOS bundle exporting one C symbol,
+// ``vphonePatchSetPrincipalSymbol``, which returns a ``VPhonePatchSetPrincipal``;
+// the loader calls it and asks the result for one patcher per firmware component
+// the set has an enabled patch for.
+//
+// Why an exported symbol and not `NSPrincipalClass`, which is how a macOS loadable
+// bundle normally names its entry point: PatchKit is built for library evolution,
+// so a class inheriting from ``VPhonePatchSetPrincipal`` has a resilient
+// superclass and its metadata is initialized at first use rather than at image
+// load. Such a class is not registered with the ObjC runtime when the bundle is
+// mapped, so `NSClassFromString` — which is what `Bundle.principalClass` resolves
+// `NSPrincipalClass` with — cannot find it, and `Bundle.principalClass` silently
+// falls back to whichever class *was* registered. A `@_cdecl` symbol has none of
+// that: it is a plain C entry point, and the metadata it needs is realized inside
+// the set's own code where it belongs.
+//
+// Why one patcher per component rather than a list: the pipeline runs patchers in
+// sequence over the same buffer, and it decides *which* components to ask about
+// from the manifest, not from the code. A set whose patches the preset turned off
+// is never asked, which mirrors the rule the bundled sets follow — a patcher whose
+// whole set is out of the plan is not constructed, because its records would be
+// declared by nothing and an undeclared record applies (see ``VPhonePatchGate``).
+//
+// The honest limit on all of this: a loaded set is code running in the patching
+// process. ``VPhonePatchSetContext/gate`` is how its patches become blockable, and
+// a patcher that ignores the gate applies regardless — nothing here can stop it,
+// and no warning will fire, because its records *are* declared. The boundary that
+// does hold is the signature check at load and the rule that root `cfw install`
+// loads no external set at all.
+
+import Foundation
+
+// MARK: - Context
+
+/// What a patch set is told about the firmware it is being run against.
+public struct VPhonePatchSetContext: Sendable {
+ /// The iPhone base `ProductVersion`, or nil when it could not be read.
+ public let iOSBase: VPhoneVersion?
+ /// The cloudOS `ProductVersion`, or nil when it could not be read.
+ public let cloudOS: VPhoneVersion?
+ /// Which patches the resolved plan turned on. A patcher assigns this to its
+ /// own ``Patcher/gate`` so a per-VM checkmark reaches its patch sites.
+ public let gate: VPhonePatchGate
+ /// The preset's knobs, for a set that reads one.
+ public let parameters: [String: String]
+ /// Whether the run is printing per-patch detail.
+ public let verbose: Bool
+
+ public init(
+ iOSBase: VPhoneVersion?,
+ cloudOS: VPhoneVersion?,
+ gate: VPhonePatchGate,
+ parameters: [String: String] = [:],
+ verbose: Bool = false,
+ ) {
+ self.iOSBase = iOSBase
+ self.cloudOS = cloudOS
+ self.gate = gate
+ self.parameters = parameters
+ self.verbose = verbose
+ }
+}
+
+// MARK: - Principal
+
+/// The symbol a `.vphonepatchset` exports, and the only name the loader looks for.
+///
+/// A set defines it once, at file scope:
+///
+/// @_cdecl("vphone_patch_set_principal")
+/// public func makeExamplePatchSetPrincipal() -> UnsafeMutableRawPointer {
+/// VPhonePatchSetPrincipal.export(VPhoneExamplePatchSet())
+/// }
+public let vphonePatchSetPrincipalSymbol = "vphone_patch_set_principal"
+
+/// The base class a `.vphonepatchset` subclasses.
+///
+/// Subclasses add no initializer, so they inherit `init()`. Nothing here is
+/// ObjC — see the file comment on why the entry point is a C symbol.
+open class VPhonePatchSetPrincipal {
+ public required init() {}
+
+ /// Hand a principal to the loader, which takes ownership of the reference.
+ ///
+ /// The set's exported function returns a raw pointer because that is what a C
+ /// entry point can return. Retaining here and releasing on the loader's side is
+ /// the whole ownership story: the principal lives as long as the run, and the
+ /// bundle is never unloaded anyway.
+ public static func export(_ principal: VPhonePatchSetPrincipal) -> UnsafeMutableRawPointer {
+ Unmanaged.passRetained(principal).toOpaque()
+ }
+
+ /// The patcher this set runs over `component`.
+ ///
+ /// Called once per component the set declares an enabled patch for, with the
+ /// component's bytes as they stand after every earlier patcher. The returned
+ /// patcher must hand its result back through ``BufferedPatcher/patchedData``;
+ /// the pipeline cannot read a buffer it has no type for.
+ ///
+ /// The default throws, so a set that declares a patch for a component its code
+ /// does not handle is a loud mismatch rather than a component silently left
+ /// alone.
+ open func makePatcher(
+ for component: VPhoneFirmwareComponent,
+ data: Data,
+ context: VPhonePatchSetContext,
+ ) throws -> any BufferedPatcher {
+ throw VPhonePatchSetError.componentUnsupported(
+ principal: String(describing: type(of: self)),
+ component: component.rawValue,
+ )
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchTarget.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchTarget.swift
new file mode 100644
index 00000000..e9c0ad36
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchTarget.swift
@@ -0,0 +1,128 @@
+// VPhonePatchTarget.swift — What a declared patch writes to.
+//
+// The target is the one piece of a declaration the loader can check before any
+// patch runs: a patch set that claims a component this PatchKit does not know
+// fails to decode instead of being skipped silently at patch time.
+
+import Foundation
+
+/// A boot-chain component, spelled the way ``FirmwarePipeline`` names it.
+public enum VPhoneFirmwareComponent: String, Sendable, Hashable, Codable, CaseIterable {
+ case avpBooter = "AVPBooter"
+ case iBSS
+ case iBEC
+ case llb = "LLB"
+ case txm = "TXM"
+ case kernelcache
+ case deviceTree = "DeviceTree"
+ case filesystem = "Filesystem"
+ case manifest = "Manifest"
+}
+
+/// Where a patch writes. Boot-chain patches run inside `fw patch`; the guest
+/// cases run inside `cfw install`, after the system volume is mounted.
+public enum VPhonePatchTarget: Sendable, Hashable {
+ /// A signed boot-chain component, patched before the IM4P is resealed.
+ case firmware(VPhoneFirmwareComponent)
+ /// The guest dyld shared cache, re-attested chunk by chunk afterwards.
+ case dyldSharedCache
+ /// A Mach-O in the mounted system volume, at that absolute guest path.
+ case guestExecutable(path: String)
+ /// The entitlements blob of a Mach-O in the mounted system volume.
+ case guestEntitlements(path: String)
+ /// A non-executable file written into the mounted system volume.
+ case guestFile(path: String)
+ /// The post-restore device tree in the guest's Preboot volume.
+ case prebootDeviceTree
+}
+
+// MARK: - Plist Coding
+
+extension VPhonePatchTarget: Codable {
+ private enum Kind: String, Codable {
+ case firmware = "Firmware"
+ case dyldSharedCache = "DyldSharedCache"
+ case guestExecutable = "GuestExecutable"
+ case guestEntitlements = "GuestEntitlements"
+ case guestFile = "GuestFile"
+ case prebootDeviceTree = "PrebootDeviceTree"
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case kind = "Kind"
+ case component = "Component"
+ case path = "Path"
+ }
+
+ public init(from decoder: any Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ let kind = try container.decode(Kind.self, forKey: .kind)
+ switch kind {
+ case .firmware:
+ self = .firmware(try container.decode(VPhoneFirmwareComponent.self, forKey: .component))
+ case .dyldSharedCache:
+ self = .dyldSharedCache
+ case .prebootDeviceTree:
+ self = .prebootDeviceTree
+ case .guestExecutable, .guestEntitlements, .guestFile:
+ let path = try container.decode(String.self, forKey: .path)
+ guard path.hasPrefix("/") else {
+ throw DecodingError.dataCorruptedError(
+ forKey: .path,
+ in: container,
+ debugDescription: "A guest path is absolute inside the guest volume, got \(path)",
+ )
+ }
+ switch kind {
+ case .guestExecutable: self = .guestExecutable(path: path)
+ case .guestEntitlements: self = .guestEntitlements(path: path)
+ default: self = .guestFile(path: path)
+ }
+ }
+ }
+
+ public func encode(to encoder: any Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ switch self {
+ case let .firmware(component):
+ try container.encode(Kind.firmware, forKey: .kind)
+ try container.encode(component, forKey: .component)
+ case .dyldSharedCache:
+ try container.encode(Kind.dyldSharedCache, forKey: .kind)
+ case .prebootDeviceTree:
+ try container.encode(Kind.prebootDeviceTree, forKey: .kind)
+ case let .guestExecutable(path):
+ try container.encode(Kind.guestExecutable, forKey: .kind)
+ try container.encode(path, forKey: .path)
+ case let .guestEntitlements(path):
+ try container.encode(Kind.guestEntitlements, forKey: .kind)
+ try container.encode(path, forKey: .path)
+ case let .guestFile(path):
+ try container.encode(Kind.guestFile, forKey: .kind)
+ try container.encode(path, forKey: .path)
+ }
+ }
+}
+
+// MARK: - Description
+
+extension VPhonePatchTarget: CustomStringConvertible {
+ public var description: String {
+ switch self {
+ case let .firmware(component): component.rawValue
+ case .dyldSharedCache: "dyld shared cache"
+ case .prebootDeviceTree: "preboot device tree"
+ case let .guestExecutable(path): path
+ case let .guestEntitlements(path): "\(path) (entitlements)"
+ case let .guestFile(path): "\(path) (file)"
+ }
+ }
+
+ /// Whether the patch runs in `fw patch` rather than `cfw install`.
+ public var isBootChain: Bool {
+ switch self {
+ case .firmware: true
+ case .dyldSharedCache, .prebootDeviceTree, .guestExecutable, .guestEntitlements, .guestFile: false
+ }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhoneVersion.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhoneVersion.swift
new file mode 100644
index 00000000..c1b73024
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhoneVersion.swift
@@ -0,0 +1,71 @@
+// VPhoneVersion.swift — A major.minor.patch version, parsed once.
+//
+// One type for every version this kit compares: the iPhone base and cloudOS
+// `ProductVersion` a patch is gated on, and the PatchKit API a patch set is built
+// against. They are the same shape and the same comparison, so they are the same
+// type — the alternative was a pair of booleans per release the pipeline cared
+// about, which stopped scaling at the second one.
+
+import Foundation
+
+public struct VPhoneVersion: Sendable, Hashable, Comparable, CustomStringConvertible {
+ public let major: Int
+ public let minor: Int
+ public let patch: Int
+
+ public init(major: Int, minor: Int = 0, patch: Int = 0) {
+ self.major = major
+ self.minor = minor
+ self.patch = patch
+ }
+
+ /// Parses "27", "26.4" or "18.6.2". A missing component reads as 0, matching
+ /// how Apple writes "27.0". Anything non-numeric is nil rather than zero, so a
+ /// misread version never silently compares equal to a real one.
+ public init?(_ text: String?) {
+ guard let text, !text.isEmpty else { return nil }
+ let fields = text.split(separator: ".", omittingEmptySubsequences: false)
+ guard fields.count <= 3 else { return nil }
+ var parsed = [0, 0, 0]
+ for (index, field) in fields.enumerated() {
+ guard let value = Int(field), value >= 0 else { return nil }
+ parsed[index] = value
+ }
+ major = parsed[0]
+ minor = parsed[1]
+ patch = parsed[2]
+ }
+
+ /// The PatchKit API this framework is. Raised when a public symbol is added, so
+ /// a set that needs the new symbol refuses to load on an older bundle.
+ public static let currentPatchKit = VPhoneVersion(major: 1, minor: 0)
+
+ public static func < (lhs: Self, rhs: Self) -> Bool {
+ (lhs.major, lhs.minor, lhs.patch) < (rhs.major, rhs.minor, rhs.patch)
+ }
+
+ public var description: String {
+ patch == 0 ? "\(major).\(minor)" : "\(major).\(minor).\(patch)"
+ }
+}
+
+// MARK: - Coding
+
+extension VPhoneVersion: Codable {
+ public init(from decoder: any Decoder) throws {
+ let container = try decoder.singleValueContainer()
+ let text = try container.decode(String.self)
+ guard let parsed = VPhoneVersion(text) else {
+ throw DecodingError.dataCorruptedError(
+ in: container,
+ debugDescription: "Not a major.minor.patch version: \(text)",
+ )
+ }
+ self = parsed
+ }
+
+ public func encode(to encoder: any Encoder) throws {
+ var container = encoder.singleValueContainer()
+ try container.encode(description)
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhoneVersionRequirement.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhoneVersionRequirement.swift
new file mode 100644
index 00000000..bbf34940
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhoneVersionRequirement.swift
@@ -0,0 +1,137 @@
+// VPhoneVersionRequirement.swift — Structured OS-version conditions.
+//
+// A patch declares which OS releases it applies to. The condition is an enum,
+// not a string like ">=27.0 <28.0": a manifest that cannot express a range it
+// did not mean cannot silently widen, and a typo is a decode error rather than
+// a patch that quietly matches everything.
+//
+// The plist form carries a `Kind` discriminator so a future case is a decode
+// error in an old PatchKit instead of a misread condition.
+
+import Foundation
+
+public enum VPhoneVersionRequirement: Sendable, Hashable {
+ /// Matches every version, including an unknown one.
+ case any
+ /// Matches any release of one major version, e.g. every 27.x.
+ case major(Int)
+ /// Matches exactly one major.minor release.
+ case release(major: Int, minor: Int)
+ /// Matches that release and everything after it.
+ case atLeast(major: Int, minor: Int)
+ /// Matches when any nested requirement matches.
+ case oneOf([VPhoneVersionRequirement])
+}
+
+// MARK: - Matching
+
+extension VPhoneVersionRequirement {
+ /// Whether `version` satisfies the requirement.
+ ///
+ /// A version the pipeline could not read satisfies only ``any``: a patch gated
+ /// on a release must not apply when nothing knows which release this is.
+ ///
+ /// Only major and minor are compared. A gate names a release, not a point
+ /// update, so 18.6.2 satisfies `.major(18)` and `.atLeast(18, 6)` alike.
+ public func matches(_ version: VPhoneVersion?) -> Bool {
+ if case .any = self { return true }
+ guard let version else { return false }
+ switch self {
+ case .any:
+ return true
+ case let .major(value):
+ return version.major == value
+ case let .release(requiredMajor, requiredMinor):
+ return version.major == requiredMajor && version.minor == requiredMinor
+ case let .atLeast(requiredMajor, requiredMinor):
+ return (version.major, version.minor) >= (requiredMajor, requiredMinor)
+ case let .oneOf(options):
+ return options.contains { $0.matches(version) }
+ }
+ }
+}
+
+// MARK: - Plist Coding
+
+extension VPhoneVersionRequirement: Codable {
+ private enum Kind: String, Codable {
+ case any = "Any"
+ case major = "Major"
+ case release = "Release"
+ case atLeast = "AtLeast"
+ case oneOf = "OneOf"
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case kind = "Kind"
+ case major = "Major"
+ case minor = "Minor"
+ case options = "Options"
+ }
+
+ public init(from decoder: any Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ switch try container.decode(Kind.self, forKey: .kind) {
+ case .any:
+ self = .any
+ case .major:
+ self = .major(try container.decode(Int.self, forKey: .major))
+ case .release:
+ self = .release(
+ major: try container.decode(Int.self, forKey: .major),
+ minor: try container.decode(Int.self, forKey: .minor),
+ )
+ case .atLeast:
+ self = .atLeast(
+ major: try container.decode(Int.self, forKey: .major),
+ minor: try container.decode(Int.self, forKey: .minor),
+ )
+ case .oneOf:
+ let options = try container.decode([VPhoneVersionRequirement].self, forKey: .options)
+ guard !options.isEmpty else {
+ throw DecodingError.dataCorruptedError(
+ forKey: .options,
+ in: container,
+ debugDescription: "OneOf needs at least one option; an empty list matches nothing",
+ )
+ }
+ self = .oneOf(options)
+ }
+ }
+
+ public func encode(to encoder: any Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ switch self {
+ case .any:
+ try container.encode(Kind.any, forKey: .kind)
+ case let .major(value):
+ try container.encode(Kind.major, forKey: .kind)
+ try container.encode(value, forKey: .major)
+ case let .release(major, minor):
+ try container.encode(Kind.release, forKey: .kind)
+ try container.encode(major, forKey: .major)
+ try container.encode(minor, forKey: .minor)
+ case let .atLeast(major, minor):
+ try container.encode(Kind.atLeast, forKey: .kind)
+ try container.encode(major, forKey: .major)
+ try container.encode(minor, forKey: .minor)
+ case let .oneOf(options):
+ try container.encode(Kind.oneOf, forKey: .kind)
+ try container.encode(options, forKey: .options)
+ }
+ }
+}
+
+// MARK: - Description
+
+extension VPhoneVersionRequirement: CustomStringConvertible {
+ public var description: String {
+ switch self {
+ case .any: "any"
+ case let .major(value): "\(value).x"
+ case let .release(major, minor): "\(major).\(minor)"
+ case let .atLeast(major, minor): "\(major).\(minor)+"
+ case let .oneOf(options): options.map(\.description).joined(separator: " | ")
+ }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchSetExample/Resources/Manifest.plist b/VPhoneExecutable/VPhoneCommand/VPhonePatchSetExample/Resources/Manifest.plist
new file mode 100644
index 00000000..75794761
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchSetExample/Resources/Manifest.plist
@@ -0,0 +1,57 @@
+<?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">
+<!--
+ Manifest.plist — what VPhonePatchSetExample.vphonepatchset declares.
+
+ This is read before any of the set's code is mapped, so everything the resolver
+ needs to reject a bad combination is here: the identity a preset pins, the
+ PatchKit version the code was built against, and one entry per selectable patch.
+
+ Identifier is the contract twice over. A preset names it, and the loader refuses
+ the bundle if the file at the pinned path declares a different one. Each patch
+ identifier is also the prefix of the PatchRecord identifiers that patch emits,
+ which is how a per-VM checkmark reaches the patch site.
+
+ Target must be Firmware for a loaded set. A guest-side patch would have to run
+ inside `cfw install`, which is the privileged step and loads no external set, so
+ declaring one is refused at import rather than promising a patch that never runs.
+-->
+<plist version="1.0">
+<dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.example</string>
+ <key>Name</key>
+ <string>Example</string>
+ <key>Version</key>
+ <string>1.0</string>
+ <key>Summary</key>
+ <string>Template patch set: one in-place iBEC string rewrite, driven by preset parameters</string>
+
+ <!-- The PatchKit API this set was built against. A bundle asking for a newer
+ one than the running framework is refused before it is loaded. -->
+ <key>MinimumPatchKitVersion</key>
+ <string>1.0</string>
+
+ <key>Patches</key>
+ <array>
+ <dict>
+ <key>Identifier</key>
+ <string>example.string_rewrite</string>
+ <key>Title</key>
+ <string>Example string rewrite</string>
+ <key>Summary</key>
+ <string>Rewrites the ASCII string named by the preset's ExampleFindString parameter as ExampleReplaceString, in place. Does nothing until a preset sets both.</string>
+ <key>Target</key>
+ <dict>
+ <key>Kind</key>
+ <string>Firmware</string>
+ <key>Component</key>
+ <string>iBEC</string>
+ </dict>
+ <!-- No Applicability key means every OS pairing. A real patch that only
+ holds on one release states it, and no preset or checkmark can
+ widen that. -->
+ </dict>
+ </array>
+</dict>
+</plist>
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchSetExample/VPhoneExamplePatchSet.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchSetExample/VPhoneExamplePatchSet.swift
new file mode 100644
index 00000000..c0e02e0d
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchSetExample/VPhoneExamplePatchSet.swift
@@ -0,0 +1,165 @@
+// VPhoneExamplePatchSet.swift — The template a `.vphonepatchset` is copied from.
+//
+// This builds `VPhonePatchSetExample.vphonepatchset`. It is not staged into
+// VPhone.bundle and no shipped preset names it: it exists so the loader has
+// something real to load in the tests, and so an author has a working set to copy
+// rather than a description of one.
+//
+// Three pieces, and that is the whole contract:
+//
+// 1. `Contents/Resources/Manifest.plist` — what the set declares. Read before any
+// of this code is mapped.
+// 2. A ``VPhonePatchSetPrincipal`` subclass, handed to the loader by the one
+// exported symbol `vphone_patch_set_principal`.
+// 3. A ``BufferedPatcher`` per component the manifest declares a patch for.
+// Anything else the pipeline cannot read bytes back from.
+//
+// What the example patch does: rewrite one ASCII string in iBEC, in place, to a
+// replacement of the same length or shorter. A string rewrite is the simplest whole
+// class of firmware patch — it is how the serial labels in the bundled boot-chain
+// set work — and it needs no instruction encoding, so the shape stays visible.
+//
+// Both strings come from the preset's `Parameters`, so the set patches nothing
+// until a preset says what to rewrite. To make this a real patch instead of a
+// template, delete the parameter lookup, hardcode your anchor, and follow it to the
+// site you actually want: `ARM64Disassembler` decodes, `ARM64Encoder` and the
+// `ARM64` constants produce replacement instructions, and `BinaryBuffer` holds the
+// bytes. Never write an instruction word as a literal — see the kernel patcher
+// guardrails in AGENTS.md.
+
+import Foundation
+import VPhonePatchKit
+
+// MARK: - Entry Point
+
+/// The one symbol the loader looks for — the name is
+/// ``vphonePatchSetPrincipalSymbol``. Copy this function verbatim into a new set and
+/// change only the class it builds.
+@_cdecl("vphone_patch_set_principal")
+public func makeExamplePatchSetPrincipal() -> UnsafeMutableRawPointer {
+ VPhonePatchSetPrincipal.export(VPhoneExamplePatchSet())
+}
+
+// MARK: - Principal
+
+/// What the exported symbol hands back.
+///
+/// No initializer is declared, so `init()` is inherited — which is what the factory
+/// above calls.
+public final class VPhoneExamplePatchSet: VPhonePatchSetPrincipal {
+ /// The preset parameter naming the string to find.
+ public static let findParameter = "ExampleFindString"
+ /// The preset parameter naming what to put there.
+ public static let replaceParameter = "ExampleReplaceString"
+
+ public override func makePatcher(
+ for component: VPhoneFirmwareComponent,
+ data: Data,
+ context: VPhonePatchSetContext,
+ ) throws -> any BufferedPatcher {
+ // One component, one patcher. A set declaring patches for several
+ // components switches here and returns a different patcher for each.
+ guard component == .iBEC else {
+ // The default implementation raises the right error: the manifest
+ // promised a patch for a component this code does not handle.
+ return try super.makePatcher(for: component, data: data, context: context)
+ }
+ return VPhoneExampleStringPatcher(
+ data: data,
+ find: context.parameters[Self.findParameter] ?? "",
+ replace: context.parameters[Self.replaceParameter] ?? "",
+ verbose: context.verbose,
+ gate: context.gate,
+ )
+ }
+}
+
+// MARK: - Patcher
+
+/// Rewrites one NUL-terminated ASCII string in place.
+///
+/// In place matters: growing a string would move everything after it, and nothing
+/// in a signed boot-chain image tolerates that. The replacement is therefore
+/// padded with NULs to the original's length and refused if it is longer.
+public final class VPhoneExampleStringPatcher: BufferedPatcher {
+ /// The record identifier, and the identifier the manifest declares. Keeping
+ /// them equal is what lets the gate turn this patch off: the gate resolves a
+ /// record to the declaration covering it, and a record no declaration covers
+ /// applies anyway, with a warning.
+ public static let patchIdentifier = "example.string_rewrite"
+
+ public let component = VPhoneFirmwareComponent.iBEC.rawValue
+ public let verbose: Bool
+ public let gate: VPhonePatchGate
+
+ public let buffer: BinaryBuffer
+ public var patchedData: Data { buffer.data }
+
+ private let find: String
+ private let replace: String
+ private var found: [PatchRecord] = []
+
+ public init(data: Data, find: String, replace: String, verbose: Bool, gate: VPhonePatchGate) {
+ buffer = BinaryBuffer(data)
+ self.find = find
+ self.replace = replace
+ self.verbose = verbose
+ self.gate = gate
+ }
+
+ // MARK: Find
+
+ public func findAll() throws -> [PatchRecord] {
+ found = []
+
+ // The gate is asked before the site is even looked for, which is the rule
+ // every patcher here follows: consulting it after the write would leave the
+ // bytes patched with nothing recording it.
+ guard gateAllows(Self.patchIdentifier) else { return [] }
+
+ guard !find.isEmpty else {
+ log(" [=] \(Self.patchIdentifier): no \(VPhoneExamplePatchSet.findParameter) in the preset")
+ return []
+ }
+ guard let anchor = find.data(using: .ascii), let replacement = replace.data(using: .ascii) else {
+ throw PatcherError.invalidFormat(
+ "\(Self.patchIdentifier): both strings must be ASCII",
+ )
+ }
+ guard replacement.count <= anchor.count else {
+ throw PatcherError.invalidFormat(
+ "\(Self.patchIdentifier): '\(replace)' is longer than '\(find)';"
+ + " a string is rewritten in place and cannot grow",
+ )
+ }
+
+ for offset in buffer.findAll(anchor) {
+ var bytes = replacement
+ bytes.append(Data(repeating: 0, count: anchor.count - replacement.count))
+ found.append(PatchRecord(
+ patchID: Self.patchIdentifier,
+ component: component,
+ fileOffset: offset,
+ originalBytes: buffer.readBytes(at: offset, count: anchor.count),
+ patchedBytes: bytes,
+ description: "Rewrite '\(find)' as '\(replace)'",
+ ))
+ }
+ if found.isEmpty {
+ log(" [=] \(Self.patchIdentifier): '\(find)' is not in this iBEC")
+ }
+ return found
+ }
+
+ // MARK: Apply
+
+ @discardableResult
+ public func apply() throws -> Int {
+ if found.isEmpty { _ = try findAll() }
+ for record in found {
+ buffer.writeBytes(at: record.fileOffset, bytes: record.patchedBytes)
+ log(" [+] \(record)")
+ }
+ return found.count
+ }
+}
diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
index 1e5e2ae0..2761d62c 100755
--- a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
+++ b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
@@ -7,6 +7,9 @@ configuration="${CONFIGURATION:?}"
bundle="${TARGET_BUILD_DIR:?}/${FULL_PRODUCT_NAME:?}"
macos="$bundle/Contents/MacOS"
resources="$bundle/Contents/Resources"
+# VPhonePatchKit is the patch API. vphone-cli links it, and patch sets resolve
+# against this one copy rather than statically linking a second disassembler.
+frameworks="$bundle/Contents/Frameworks"
# Host programs run from Contents/MacOS. Everything installed into the guest
# lives in guest-resources and never runs on the Mac.
guest="$resources/guest-resources"
@@ -53,7 +56,9 @@ if /usr/bin/nm -u "$daemon_products/vphoned" | /usr/bin/grep -q '_swift_initBorr
fi
/bin/rm -rf "$macos" "$resources"
-/bin/mkdir -p "$macos" "$guest"
+/bin/mkdir -p "$macos" "$guest" "$frameworks"
+/bin/rm -rf "$frameworks/VPhonePatchKit.framework"
+/bin/cp -R "$command_products/VPhonePatchKit.framework" "$frameworks/VPhonePatchKit.framework"
/bin/cp "$TARGET_BUILD_DIR/vphone-vm" "$macos/vphone-vm"
/bin/cp "$command_products/vphone-cli" "$macos/vphone-cli"
/bin/cp "$amfi_products/vphone-escalator" "$macos/vphone-escalator"
@@ -69,6 +74,12 @@ fi
/bin/cp "$guest_products/gpu/libAppleParavirtCompilerPluginIOGPUFamily.dylib" \
"$guest/libAppleParavirtCompilerPluginIOGPUFamily.dylib"
+# Patch presets. Prewritten plists, read by vphone-cli at patch time to decide
+# which declared patches apply. Nothing generates or edits these.
+/bin/mkdir -p "$resources/patches_presets"
+/bin/cp "$root/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/"*.plist \
+ "$resources/patches_presets/"
+
"${0:a:h}/SyncStrings.sh"
for catalog in Localizable InfoPlist; do
/usr/bin/xcrun xcstringstool compile \
@@ -84,8 +95,9 @@ compatibility_library="$(/usr/bin/xcrun swift-stdlib-tool --print \
/bin/cp "$compatibility_library" "$macos/libswiftCompatibilitySpan.vphone.dylib"
/usr/bin/install_name_tool -change @rpath/libswiftCompatibilitySpan.dylib \
@loader_path/libswiftCompatibilitySpan.vphone.dylib "$macos/vphone-vm"
-/bin/rm -f "$bundle/Contents/Frameworks/libswiftCompatibilitySpan.dylib"
+/bin/rm -f "$frameworks/libswiftCompatibilitySpan.dylib"
+/usr/bin/codesign --force --sign - "$frameworks/VPhonePatchKit.framework"
/usr/bin/codesign --force --sign - "$macos/vphone-cli"
/usr/bin/codesign --force --sign - --entitlements "$root/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements" "$guest/vphoned"
/usr/bin/codesign --force --sign - "$macos/vphone-escalator"
diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
index 60f1a8fb..f4775218 100755
--- a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
+++ b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
@@ -6,6 +6,7 @@ root="$(cd "${0:a:h}/../../.." && pwd)"
bundle="${1:-$root/.build/XcodeBundle/Build/Products/Debug/VPhone.bundle}"
macos="$bundle/Contents/MacOS"
resources="$bundle/Contents/Resources"
+frameworks="$bundle/Contents/Frameworks"
guest="$resources/guest-resources"
file_copy_spawns="$(/usr/bin/find "$root/VPhoneExecutable" "$root/VPhoneKit" \
@@ -36,6 +37,24 @@ require_signed_macho() {
for name in vphone-vm vphone-cli vphone-escalator libswiftCompatibilitySpan.vphone.dylib; do
require_signed_macho "$macos/$name"
done
+require_signed_macho "$frameworks/VPhonePatchKit.framework/Versions/A/VPhonePatchKit"
+# The patch API ships its interface so an out-of-tree patch set can build against
+# the same framework the bundle loads.
+[[ -d "$frameworks/VPhonePatchKit.framework/Versions/A/Modules/VPhonePatchKit.swiftmodule" ]] || {
+ print -u2 "VPhonePatchKit.framework has no Swift module interface"
+ exit 1
+}
+# The presets decide which declared patches apply. A bundle without the standard
+# one would fall back to vphone-cli's built-in copy, so a VM built from a shipped
+# bundle and one built from an Xcode build could get different patches.
+[[ -f "$resources/patches_presets/standard.plist" ]] || {
+ print -u2 "Missing patch preset: patches_presets/standard.plist"
+ exit 1
+}
+for preset in "$resources/patches_presets/"*.plist; do
+ /usr/bin/plutil -lint -s "$preset" || { print -u2 "Malformed patch preset: ${preset:t}"; exit 1; }
+done
+
for name in vphoned launchdhook-vphone.dylib SystemHook-vphone.dylib libcamfix.dylib libvlocation.dylib \
libvcamcaptured.dylib libAppleParavirtCompilerPluginIOGPUFamily.dylib; do
require_signed_macho "$guest/$name"
@@ -72,11 +91,14 @@ while IFS= read -r file; do
"$macos/"*)
[[ "$platform" != IOS ]] || { print -u2 "iOS binary in Contents/MacOS: ${file#$bundle/}"; exit 1; }
;;
+ "$frameworks/"*)
+ [[ "$platform" != IOS ]] || { print -u2 "iOS binary in Contents/Frameworks: ${file#$bundle/}"; exit 1; }
+ ;;
"$guest/"*)
[[ "$platform" == IOS ]] || { print -u2 "Non-iOS binary in guest-resources: ${file#$bundle/}"; exit 1; }
;;
*)
- print -u2 "Mach-O outside Contents/MacOS and guest-resources: ${file#$bundle/}"
+ print -u2 "Mach-O outside Contents/MacOS, Contents/Frameworks and guest-resources: ${file#$bundle/}"
exit 1
;;
esac
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/extended.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/extended.plist
new file mode 100644
index 00000000..ce6aa0b4
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/extended.plist
@@ -0,0 +1,83 @@
+<?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">
+<!--
+ Everything the bundle declares, including the Frida Stalker relaxations that
+ `standard` leaves off.
+
+ It names the same patch sets as standard and differs only in its selection, so
+ the two presets are readable against each other: standard is this with two
+ patches blocked. Each patch's own version gate still applies, so the Frida pair
+ lands only on cloudOS 26.4 and newer.
+-->
+<plist version="1.0">
+<dict>
+ <key>Identifier</key>
+ <string>extended</string>
+ <key>Title</key>
+ <string>Extended</string>
+ <key>Summary</key>
+ <string>Every patch this bundle declares, including the Frida Stalker relaxations.</string>
+ <key>PatchSets</key>
+ <array>
+ <dict>
+ <key>Kind</key>
+ <string>Bundled</string>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.bootchain</string>
+ </dict>
+ <dict>
+ <key>Kind</key>
+ <string>Bundled</string>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.kernel.base</string>
+ </dict>
+ <dict>
+ <key>Kind</key>
+ <string>Bundled</string>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.kernel.jailbreak</string>
+ </dict>
+ <dict>
+ <key>Kind</key>
+ <string>Bundled</string>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.kernel.hypervisor</string>
+ </dict>
+ <dict>
+ <key>Kind</key>
+ <string>Bundled</string>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.kernel.frida</string>
+ </dict>
+ <dict>
+ <key>Kind</key>
+ <string>Bundled</string>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.devicetree</string>
+ </dict>
+ <dict>
+ <key>Kind</key>
+ <string>Bundled</string>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.guest.system</string>
+ </dict>
+ <dict>
+ <key>Kind</key>
+ <string>Bundled</string>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.guest.display</string>
+ </dict>
+ <dict>
+ <key>Kind</key>
+ <string>Bundled</string>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.guest.identity</string>
+ </dict>
+ </array>
+ <key>Selection</key>
+ <dict>
+ <key>Kind</key>
+ <string>All</string>
+ </dict>
+</dict>
+</plist>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist
new file mode 100644
index 00000000..0ba689ad
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist
@@ -0,0 +1,93 @@
+<?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">
+<!--
+ The preset every VM gets unless another is named.
+
+ It draws on every patch set the bundle ships and turns on all of their patches
+ bar the Frida Stalker pair, which widen what any process in the guest may do and
+ which nothing needs in order to boot. Each patch's own version gate still decides
+ whether it lands on this pairing of iPhone base and cloudOS.
+
+ Prewritten and reviewed. Nothing in the tool edits a preset: a VM records which
+ boxes its owner changed, and those compose on top of this.
+
+ FirmwarePatchSetCatalog.standardPreset is the in-code copy a dev build without a
+ staged bundle falls back to. FirmwarePatchSetTests checks the two agree.
+-->
+<plist version="1.0">
+<dict>
+ <key>Identifier</key>
+ <string>standard</string>
+ <key>Title</key>
+ <string>Standard</string>
+ <key>Summary</key>
+ <string>The patches every vphone VM needs to boot, jailbroken, with a working display and camera.</string>
+ <key>PatchSets</key>
+ <array>
+ <dict>
+ <key>Kind</key>
+ <string>Bundled</string>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.bootchain</string>
+ </dict>
+ <dict>
+ <key>Kind</key>
+ <string>Bundled</string>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.kernel.base</string>
+ </dict>
+ <dict>
+ <key>Kind</key>
+ <string>Bundled</string>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.kernel.jailbreak</string>
+ </dict>
+ <dict>
+ <key>Kind</key>
+ <string>Bundled</string>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.kernel.hypervisor</string>
+ </dict>
+ <dict>
+ <key>Kind</key>
+ <string>Bundled</string>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.kernel.frida</string>
+ </dict>
+ <dict>
+ <key>Kind</key>
+ <string>Bundled</string>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.devicetree</string>
+ </dict>
+ <dict>
+ <key>Kind</key>
+ <string>Bundled</string>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.guest.system</string>
+ </dict>
+ <dict>
+ <key>Kind</key>
+ <string>Bundled</string>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.guest.display</string>
+ </dict>
+ <dict>
+ <key>Kind</key>
+ <string>Bundled</string>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.guest.identity</string>
+ </dict>
+ </array>
+ <key>Selection</key>
+ <dict>
+ <key>Kind</key>
+ <string>Block</string>
+ <key>Patches</key>
+ <array>
+ <string>kernelcache_frida.thread_set_state_entitlement_flag</string>
+ <string>kernelcache_frida.vm_map_delete_immutable_code</string>
+ </array>
+ </dict>
+</dict>
+</plist>
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
index 2c2ac3d0..0d490b8c 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
@@ -93,6 +93,7 @@
if let machine = model.machines.selected {
await sheet(.settings(machine), "09-machine-settings", suffix)
}
+ await sheet(.patches(labMachine), "09b-patch-settings", suffix)
await sheet(.clone(labMachine), "10-clone", suffix)
await sheet(.export(labMachine), "11-export", suffix)
await sheet(.console(path("research-01")), "12-console", suffix)
@@ -263,11 +264,35 @@
memoryMB: 12288,
diskSizeGB: 128,
network: "nat",
- enableFrida: false,
+ patches: VPhoneLaunchpadPatchSelection(),
forceDyldSharedCacheMaxSlide: false,
keepArtifacts: false,
)
+ /// Stands in for `fw patches --json`. `preset` moves the Frida patches in
+ /// and out of the preset, as the real report does.
+ static func patchCatalog(preset: String?) -> VPhoneLaunchpadPatchCatalog? {
+ let active = preset ?? "standard"
+ let frida = active == "extended"
+ let json = """
+ {"activePreset":"\(active)","blockedPatches":[],"allowedPatches":[],
+ "presets":[
+ {"identifier":"standard","title":"Standard","summary":"The patches every vphone VM needs to boot, jailbroken, with a working display and camera.","patchSets":[]},
+ {"identifier":"extended","title":"Extended","summary":"Every patch this bundle declares, including the Frida Stalker relaxations.","patchSets":[]}
+ ],
+ "patches":[
+ {"identifier":"avpbooter.dgst_bypass","title":"AVPBooter digest bypass","summary":"Accepts the resealed boot images instead of the stock digests.","patchSet":"com.vphone.patchset.bootchain","patchSetName":"Boot Chain","target":"AVPBooter","applicability":"any","bootEssential":true,"inPreset":true,"enabled":true},
+ {"identifier":"ibss.serial_label","title":"iBSS serial label","summary":"Tags iBSS serial output so the boot log names its stage.","patchSet":"com.vphone.patchset.bootchain","patchSetName":"Boot Chain","target":"iBSS","applicability":"any","bootEssential":false,"inPreset":true,"enabled":true},
+ {"identifier":"kernel.debugger","title":"Kernel debugger gate","summary":"Lets a debugger attach to any process in the guest.","patchSet":"com.vphone.patchset.kernel.base","patchSetName":"Kernel Base","target":"Kernel","applicability":"any","bootEssential":false,"inPreset":true,"enabled":true},
+ {"identifier":"kernel.thread_guard_violation","title":"Thread guard violation","summary":"Stops the guard exception the older kernels raise on first boot.","patchSet":"com.vphone.patchset.kernel.base","patchSetName":"Kernel Base","target":"Kernel","applicability":"iOS 18.x","bootEssential":true,"inPreset":true,"enabled":true},
+ {"identifier":"kernelcache_frida.thread_set_state_entitlement_flag","title":"Frida thread state entitlement","summary":"Lets Stalker set thread state without the entitlement the kernel asks for.","patchSet":"com.vphone.patchset.kernel.frida","patchSetName":"Frida Stalker","target":"Kernel","applicability":"cloudOS 26.4+","bootEssential":false,"inPreset":\(frida),"enabled":\(frida)},
+ {"identifier":"kernelcache_frida.vm_map_delete_immutable_code","title":"Frida immutable code unmap","summary":"Allows Stalker to unmap the immutable code it rewrote.","patchSet":"com.vphone.patchset.kernel.frida","patchSetName":"Frida Stalker","target":"Kernel","applicability":"cloudOS 26.4+","bootEssential":false,"inPreset":\(frida),"enabled":\(frida)},
+ {"identifier":"guest.vphoned","title":"Guest vphoned","summary":"Installs vphoned and its launch daemon into the guest.","patchSet":"com.vphone.patchset.guest.system","patchSetName":"Guest System","target":"Guest filesystem","applicability":"any","bootEssential":true,"inPreset":true,"enabled":true}
+ ]}
+ """
+ return try? JSONDecoder().decode(VPhoneLaunchpadPatchCatalog.self, from: Data(json.utf8))
+ }
+
/// What a log terminal shows in snapshot mode instead of the file.
static func log(for url: URL) -> [String] {
url.lastPathComponent.hasSuffix("-create.log") ? creationLog : console
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadCommandLine.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadCommandLine.swift
index 5f1706ab..0f415649 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadCommandLine.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadCommandLine.swift
@@ -19,6 +19,15 @@ nonisolated struct VPhoneLaunchpadError: LocalizedError {
var failureReason: String? {
detail
}
+
+ /// Any error as one string: the message, and under it the output that says
+ /// why. For a view that shows a single line of text rather than an alert
+ /// with its own detail area.
+ static func message(for error: any Error) -> String {
+ [error.localizedDescription, (error as? VPhoneLaunchpadError)?.detail]
+ .compactMap(\.self)
+ .joined(separator: "\n")
+ }
}
// MARK: - Result
@@ -36,10 +45,17 @@ nonisolated struct VPhoneLaunchpadCommandResult: Sendable {
lines.suffix(12).joined(separator: "\n")
}
- /// The last line that looks like a JSON document. stderr is merged into
- /// the same stream, so warnings can precede it.
+ /// The JSON document in the output.
+ ///
+ /// stderr is merged into the same stream, so warnings can precede it, and a
+ /// pretty-printed document spans many lines — `fw patches --json` prints
+ /// one. Only its opening brace sits at column zero, so the last line that
+ /// opens a document starts it, and it runs to the end of the output.
var jsonData: Data? {
- lines.last { $0.hasPrefix("[") || $0.hasPrefix("{") }.map { Data($0.utf8) }
+ guard let start = lines.lastIndex(where: { $0.hasPrefix("[") || $0.hasPrefix("{") }) else {
+ return nil
+ }
+ return Data(lines[start...].joined(separator: "\n").utf8)
}
}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift
index 8de6853e..b285c3ed 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift
@@ -24,7 +24,8 @@ final class VPhoneLaunchpadCreationPipeline {
var memoryMB: Int
var diskSizeGB: Int
var network: String
- var enableFrida: Bool
+ /// The preset and per-patch overrides the boot chain is built with.
+ var patches: VPhoneLaunchpadPatchSelection
var forceDyldSharedCacheMaxSlide: Bool
var keepArtifacts: Bool
@@ -124,12 +125,18 @@ final class VPhoneLaunchpadCreationPipeline {
Step.allCases.first { statuses[$0] == .failed }
}
+ /// `fw patch`, as both the step's log line and the run build it. One array so
+ /// the command the sheet shows cannot drift from the command that runs.
+ private var patchArguments: [String] {
+ ["fw", "patch", options.name] + options.patches.presetArguments
+ }
+
func command(for step: Step) -> String {
let name = options.name
return switch step {
case .create: "vm new \(name) --cpu \(options.cpuCount) --memory \(options.memoryMB) --disk-size \(options.diskSizeGB)"
case .prepare: "fw prepare \(name)"
- case .patch: "fw patch \(name)" + (options.enableFrida ? " --frida" : "")
+ case .patch: patchArguments.joined(separator: " ")
case .bootDFU: "vm launch \(name) --dfu"
case .waitDFU: "recovery-probe --ecid …"
case .restore: "restore \(name)"
@@ -226,7 +233,13 @@ final class VPhoneLaunchpadCreationPipeline {
"--cloudos-source", options.cloudOSSource] + library)
case .patch:
- try await run(["fw", "patch", name] + (options.enableFrida ? ["--frida"] : []) + library)
+ // The preset rides on `fw patch` itself; per-patch overrides are
+ // recorded first, the way `vm config` follows `vm new` above. Both
+ // lines reach the log.
+ if options.patches.hasOverrides {
+ try await run(["fw", "set-patches", name] + options.patches.setPatchesArguments + library)
+ }
+ try await run(patchArguments + library)
case .bootDFU:
let arguments = ["vm", "launch", name, "--dfu"] + library
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
index 1155e46a..201110fa 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
@@ -320,6 +320,17 @@ final class VPhoneLaunchpadMachineLibrary {
await perform(String(localized: "Saving settings…"), on: machine, arguments)
}
+ /// Records the machine's patch choice. `fw set-patches` writes the plist, so
+ /// nothing here reaches into a VM bundle itself. The choice applies the next
+ /// time the boot chain is patched.
+ func setPatches(_ machine: Path, _ selection: VPhoneLaunchpadPatchSelection) async {
+ await perform(
+ String(localized: "Saving patch settings…"),
+ on: machine,
+ ["fw", "set-patches", machine.name] + selection.setPatchesArguments + machine.libraryArguments,
+ )
+ }
+
func rename(_ machine: Path, to newName: String) async {
if await perform(String(localized: "Renaming…"), on: machine, ["vm", "rename", machine.name, newName] + machine.libraryArguments) {
selection = Path(libraryRoot: machine.libraryRoot, name: newName)
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift
index 499fa92f..a1d5a824 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift
@@ -8,6 +8,7 @@ struct VPhoneLaunchpadMachinesView: View {
case newMachine
case creation(MachinePath)
case settings(VPhoneLaunchpadMachine)
+ case patches(MachinePath)
case rename(MachinePath)
case clone(MachinePath)
case export(MachinePath)
@@ -18,6 +19,7 @@ struct VPhoneLaunchpadMachinesView: View {
case .newMachine: "new"
case let .creation(machine): "creation-\(machine.url.path)"
case let .settings(machine): "settings-\(machine.path.url.path)"
+ case let .patches(machine): "patches-\(machine.url.path)"
case let .rename(machine): "rename-\(machine.url.path)"
case let .clone(machine): "clone-\(machine.url.path)"
case let .export(machine): "export-\(machine.url.path)"
@@ -186,6 +188,8 @@ struct VPhoneLaunchpadMachinesView: View {
Divider()
Button("Settings…") { sheet = .settings(machine) }
.disabled(!isStopped)
+ Button("Patch Settings…") { sheet = .patches(machine.path) }
+ .disabled(!isStopped)
Button("Rename…") { sheet = .rename(machine.path) }
.disabled(!isStopped)
Button("Clone…") { sheet = .clone(machine.path) }
@@ -292,6 +296,12 @@ struct VPhoneLaunchpadMachinesView: View {
}
case let .settings(machine):
VPhoneLaunchpadMachineSettingsView(machine: machine)
+ case let .patches(path):
+ // The machine's own record is what the editor starts from, so it reads
+ // it back through `fw patches` rather than being handed a copy.
+ VPhoneLaunchpadPatchSettingsView(machine: path) { selection in
+ Task { await library.setPatches(path, selection) }
+ }
case let .rename(path):
VPhoneLaunchpadNameSheet(title: "Rename \(path.name)", action: "Rename", initial: path.name, machine: path) { newName in
Task { await library.rename(path, to: newName) }
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift
index 3497af74..0d1affa0 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift
@@ -23,7 +23,10 @@ struct VPhoneLaunchpadNewMachineView: View {
@State private var memoryMB = 8192
@State private var diskSizeGB = 64
@State private var network = "nat"
- @State private var enableFrida = false
+ @State private var patches = VPhoneLaunchpadPatchSelection()
+ @State private var patchCatalog: VPhoneLaunchpadPatchCatalog?
+ @State private var patchCatalogError: String?
+ @State private var showsPatchSettings = false
@State private var forceMaxSlide = false
@State private var keepArtifacts = false
@@ -106,8 +109,9 @@ struct VPhoneLaunchpadNewMachineView: View {
}
}
+ patchSection
+
Section {
- Toggle("Relax kernel restrictions for Frida Stalker", isOn: $enableFrida)
Toggle("Disable dyld shared cache randomization", isOn: $forceMaxSlide)
Toggle("Keep prepared restore files", isOn: $keepArtifacts)
} header: {
@@ -118,7 +122,14 @@ struct VPhoneLaunchpadNewMachineView: View {
}
.formStyle(.grouped)
.navigationTitle("New Machine")
- .frame(width: 560, height: 620)
+ .frame(width: 560, height: 780)
+ .sheet(isPresented: $showsPatchSettings) {
+ VPhoneLaunchpadPatchSettingsView(machine: nil, initial: patches) { selection in
+ patches = selection
+ Task { await loadPatchCatalog() }
+ }
+ .environment(model)
+ }
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Cancel") { dismiss() }
@@ -129,9 +140,74 @@ struct VPhoneLaunchpadNewMachineView: View {
}
}
.task { await loadCatalog() }
+ .task { await loadPatchCatalog() }
.onAppear { location = model.machines.preferredRoot }
}
+ // MARK: - Patches
+
+ private var patchSection: some View {
+ Section {
+ if let patchCatalog {
+ Picker("Preset", selection: presetBinding) {
+ ForEach(patchCatalog.presets) { preset in
+ Text(verbatim: preset.title).tag(preset.identifier)
+ }
+ }
+ Button("Patch Settings…") { showsPatchSettings = true }
+ } else if let patchCatalogError {
+ Label(patchCatalogError, systemImage: "exclamationmark.triangle")
+ .foregroundStyle(.secondary)
+ } else {
+ HStack {
+ ProgressView().controlSize(.small)
+ Text("Reading the bundle's patches…").foregroundStyle(.secondary)
+ }
+ }
+ } header: {
+ Text("Patches")
+ } footer: {
+ patchNote
+ }
+ }
+
+ @ViewBuilder
+ private var patchNote: some View {
+ let essentialOff = patchCatalog.map { patches.bootEssentialOff(in: $0) } ?? []
+ VStack(alignment: .leading, spacing: 4) {
+ if let summary = patchCatalog?.preset(patches.preset)?.summary, !summary.isEmpty {
+ Text(verbatim: summary).foregroundStyle(.secondary)
+ }
+ if patches.hasOverrides {
+ Text("Differs from the preset: \(patches.blocked.count) off, \(patches.allowed.count) on.")
+ .foregroundStyle(.secondary)
+ }
+ if !essentialOff.isEmpty {
+ Label {
+ Text("^[\(essentialOff.count) boot-essential patch](inflect: true) off: \(essentialOff.map(\.identifier).joined(separator: ", "))")
+ } icon: {
+ Image(systemName: "exclamationmark.triangle.fill")
+ }
+ .foregroundStyle(.orange)
+ }
+ }
+ }
+
+ /// Switching preset here re-bases the overrides for the same reason the editor
+ /// does: they are read as a difference from whichever preset is active.
+ private var presetBinding: Binding<String> {
+ Binding(
+ get: { patches.preset },
+ set: { identifier in
+ guard identifier != patches.preset else {
+ return
+ }
+ patches = VPhoneLaunchpadPatchSelection(preset: identifier)
+ Task { await loadPatchCatalog() }
+ },
+ )
+ }
+
// MARK: - Location
/// The library's locations that are mounted, the default one first, and
@@ -285,6 +361,27 @@ struct VPhoneLaunchpadNewMachineView: View {
}
}
+ /// Read again whenever the preset changes: `inPreset`, which the note and the
+ /// editor read the checkmarks against, is reported per preset.
+ private func loadPatchCatalog() async {
+ let requested = patches.preset
+ do {
+ let catalog = try await VPhoneLaunchpadPatchCatalog.read(
+ using: model.bundles.commandLine(),
+ machine: nil,
+ preset: requested,
+ )
+ // A second switch may have overtaken this read.
+ guard requested == patches.preset else {
+ return
+ }
+ patchCatalog = catalog
+ patchCatalogError = nil
+ } catch {
+ patchCatalogError = VPhoneLaunchpadError.message(for: error)
+ }
+ }
+
private func create() {
guard let (iphone, cloudOS) = sources else {
return
@@ -298,7 +395,7 @@ struct VPhoneLaunchpadNewMachineView: View {
memoryMB: memoryMB,
diskSizeGB: diskSizeGB,
network: network,
- enableFrida: enableFrida,
+ patches: patches,
forceDyldSharedCacheMaxSlide: forceMaxSlide,
keepArtifacts: keepArtifacts,
)
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swift
new file mode 100644
index 00000000..fb3de5ea
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swift
@@ -0,0 +1,199 @@
+import Foundation
+
+// MARK: - fw patches --json
+
+/// Mirrors the payload `vphone-cli fw patches --json` prints.
+///
+/// The app declares no patch of its own. Everything the editor lists comes from
+/// the active bundle, so a patch set this build of Launchpad has never heard of
+/// still appears, with its own patches and version gates.
+nonisolated struct VPhoneLaunchpadPatchCatalog: Decodable, Sendable {
+ struct Preset: Decodable, Hashable, Identifiable, Sendable {
+ let identifier: String
+ let title: String
+ let summary: String
+
+ var id: String {
+ identifier
+ }
+ }
+
+ struct Patch: Decodable, Hashable, Identifiable, Sendable {
+ let identifier: String
+ let title: String
+ let summary: String
+ let patchSet: String
+ let patchSetName: String
+ let target: String
+ /// The OS versions the patch is declared for, or `any`.
+ let applicability: String
+ let bootEssential: Bool
+ /// Whether the preset the report was made against turns it on. What the
+ /// checkmarks are a difference from.
+ let inPreset: Bool
+
+ var id: String {
+ identifier
+ }
+
+ /// False when the patch applies to every version, which is not worth a
+ /// column entry.
+ var isVersionGated: Bool {
+ applicability != "any"
+ }
+ }
+
+ /// The preset this report was made against: the VM's own, or the one `--preset`
+ /// asked for.
+ let activePreset: String
+ let blockedPatches: [String]
+ let allowedPatches: [String]
+ let presets: [Preset]
+ let patches: [Patch]
+
+ func preset(_ identifier: String) -> Preset? {
+ presets.first { $0.identifier == identifier }
+ }
+
+ func patch(_ identifier: String?) -> Patch? {
+ identifier.flatMap { needle in patches.first { $0.identifier == needle } }
+ }
+
+ /// The patches matching `filter`, in the order the bundle applies them, which
+ /// already runs one set after another.
+ func patches(matching filter: String) -> [Patch] {
+ let needle = filter.trimmingCharacters(in: .whitespaces)
+ guard !needle.isEmpty else {
+ return patches
+ }
+ return patches.filter { Self.matches($0, needle) }
+ }
+
+ private static func matches(_ patch: Patch, _ needle: String) -> Bool {
+ [patch.title, patch.identifier, patch.summary, patch.patchSetName, patch.target]
+ .contains { $0.localizedCaseInsensitiveContains(needle) }
+ }
+}
+
+// MARK: - Reading
+
+extension VPhoneLaunchpadPatchCatalog {
+ /// Reads the catalogue from the active bundle's `vphone-cli`.
+ ///
+ /// `preset` reports against that preset instead of the machine's own record,
+ /// which is how the picker re-bases what `inPreset` means. Passing neither a
+ /// machine nor a preset reports what the bundle does by default.
+ @MainActor
+ static func read(
+ using commandLine: VPhoneLaunchpadCommandLine?,
+ machine: VPhoneLaunchpadMachinePath?,
+ preset: String?,
+ ) async throws -> VPhoneLaunchpadPatchCatalog {
+ #if DEBUG
+ if VPhoneLaunchpadPreview.isActive {
+ guard let catalog = VPhoneLaunchpadPreview.patchCatalog(preset: preset) else {
+ throw VPhoneLaunchpadError(String(localized: "Unable to list the bundle's patches."))
+ }
+ return catalog
+ }
+ #endif
+ guard let commandLine else {
+ throw VPhoneLaunchpadError(
+ String(localized: "No Core Bundle version is in use. Choose a version in Core Bundle."),
+ )
+ }
+ var arguments = ["fw", "patches"]
+ if let machine {
+ arguments.append(machine.name)
+ }
+ if let preset {
+ arguments += ["--preset", preset]
+ }
+ arguments.append("--json")
+ if let machine {
+ arguments += machine.libraryArguments
+ }
+ let result = try await commandLine.run(arguments, recordInHistory: false)
+ guard result.succeeded, let data = result.jsonData else {
+ throw VPhoneLaunchpadError(
+ String(localized: "Unable to list the bundle's patches."),
+ detail: result.tail,
+ )
+ }
+ return try JSONDecoder().decode(Self.self, from: data)
+ }
+}
+
+// MARK: - Selection
+
+/// A VM's patch choice: a preset, plus only the boxes that differ from it.
+///
+/// This is what `vphone-cli fw set-patches` stores in `<vm>/PatchSelection.plist`.
+/// Storing differences rather than a full list is what lets a later preset
+/// revision reach a VM whose boxes were never touched.
+nonisolated struct VPhoneLaunchpadPatchSelection: Hashable, Sendable {
+ /// The preset `vphone-cli` uses when `--preset` is absent, mirroring
+ /// `VPhonePatchPreset.standardIdentifier`. Naming it on the command line would
+ /// only add noise, so the pipeline omits the flag for this one value.
+ static let defaultPreset = "standard"
+
+ var preset = defaultPreset
+ /// Patches the preset turns on that this VM leaves off.
+ var blocked: Set<String> = []
+ /// Patches the preset leaves off that this VM turns on.
+ var allowed: Set<String> = []
+
+ var hasOverrides: Bool {
+ !blocked.isEmpty || !allowed.isEmpty
+ }
+
+ var isDefault: Bool {
+ preset == Self.defaultPreset && !hasOverrides
+ }
+
+ /// `fw set-patches` arguments, without the VM name or library root. Each run
+ /// writes the whole record, so an empty list clears that half of it.
+ var setPatchesArguments: [String] {
+ ["--preset", preset]
+ + blocked.sorted().flatMap { ["--block", $0] }
+ + allowed.sorted().flatMap { ["--allow", $0] }
+ }
+
+ /// The `--preset` flag `fw patch` and `fw patches` carry, if any.
+ var presetArguments: [String] {
+ preset == Self.defaultPreset ? [] : ["--preset", preset]
+ }
+
+ func isOn(_ patch: VPhoneLaunchpadPatchCatalog.Patch) -> Bool {
+ patch.inPreset ? !blocked.contains(patch.identifier) : allowed.contains(patch.identifier)
+ }
+
+ /// Records a box the way it differs from the preset, so a patch that agrees
+ /// with the preset again lands in neither list.
+ mutating func set(_ patch: VPhoneLaunchpadPatchCatalog.Patch, on: Bool) {
+ let identifier = patch.identifier
+ blocked.remove(identifier)
+ allowed.remove(identifier)
+ switch (patch.inPreset, on) {
+ case (true, false): blocked.insert(identifier)
+ case (false, true): allowed.insert(identifier)
+ default: break
+ }
+ }
+
+ /// Drops overrides this catalogue makes meaningless: one the preset already
+ /// agrees with, and one naming a patch the bundle no longer declares. A
+ /// hand-edited plist, or a bundle whose presets have since changed, would
+ /// otherwise show a checkmark that stores nothing.
+ mutating func normalize(against catalog: VPhoneLaunchpadPatchCatalog) {
+ let inPreset = Set(catalog.patches.filter(\.inPreset).map(\.identifier))
+ let declared = Set(catalog.patches.map(\.identifier))
+ blocked = blocked.intersection(inPreset)
+ allowed = allowed.intersection(declared).subtracting(inPreset)
+ }
+
+ /// The boot-essential patches this choice turns off, in catalogue order.
+ func bootEssentialOff(in catalog: VPhoneLaunchpadPatchCatalog) -> [VPhoneLaunchpadPatchCatalog.Patch] {
+ catalog.patches.filter { $0.bootEssential && !isOn($0) }
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchSettingsView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchSettingsView.swift
new file mode 100644
index 00000000..26f2939f
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchSettingsView.swift
@@ -0,0 +1,318 @@
+import SwiftUI
+
+/// The patch editor: a preset, and a checkmark for every patch the bundle
+/// declares.
+///
+/// The list is never a copy of the catalogue — it is whatever
+/// `vphone-cli fw patches --json` reports, so a patch set added to the bundle
+/// shows up here without a change to Launchpad. Only the boxes that differ from
+/// the preset are kept, and switching preset re-bases them, since a difference
+/// from the preset that is no longer active means nothing.
+struct VPhoneLaunchpadPatchSettingsView: View {
+ typealias Catalog = VPhoneLaunchpadPatchCatalog
+
+ /// The machine whose record this edits, or nil while New Machine is still
+ /// composing one that no directory exists for yet.
+ let machine: VPhoneLaunchpadMachinePath?
+ /// What the boxes start from. An existing machine has its own record, read
+ /// back through `fw patches`, so only New Machine passes one.
+ let initial: VPhoneLaunchpadPatchSelection
+ /// Hands the edited choice back. An existing machine's caller writes it with
+ /// `fw set-patches`; New Machine holds it until the VM exists.
+ let onSave: (VPhoneLaunchpadPatchSelection) -> Void
+
+ @Environment(VPhoneLaunchpadModel.self) private var model
+ @Environment(\.dismiss) private var dismiss
+
+ @State private var selection: VPhoneLaunchpadPatchSelection
+ @State private var catalog: Catalog?
+ @State private var loadError: String?
+ @State private var isLoading = false
+ @State private var filter = ""
+ /// Empty keeps the order the bundle applies the patches in; a header click
+ /// replaces it.
+ @State private var sortOrder: [KeyPathComparator<Catalog.Patch>] = []
+ /// The row whose summary the detail pane reads.
+ @State private var highlighted: String?
+ @State private var confirmsBootEssential = false
+
+ init(
+ machine: VPhoneLaunchpadMachinePath?,
+ initial: VPhoneLaunchpadPatchSelection = VPhoneLaunchpadPatchSelection(),
+ onSave: @escaping (VPhoneLaunchpadPatchSelection) -> Void,
+ ) {
+ self.machine = machine
+ self.initial = initial
+ self.onSave = onSave
+ _selection = State(initialValue: initial)
+ }
+
+ private var essentialOff: [Catalog.Patch] {
+ catalog.map { selection.bootEssentialOff(in: $0) } ?? []
+ }
+
+ var body: some View {
+ VStack(spacing: 0) {
+ header
+ Divider()
+ list
+ Divider()
+ footer
+ }
+ .navigationTitle(machine.map { Text("\($0.name) Patches") } ?? Text("Patches"))
+ .frame(width: 920, height: 640)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) {
+ Button("Cancel") { dismiss() }
+ }
+ ToolbarItem(placement: .confirmationAction) {
+ Button(machine == nil ? "Done" : "Save") { commit() }
+ .disabled(catalog == nil)
+ }
+ }
+ .confirmationDialog(
+ "Leave ^[\(essentialOff.count) boot-essential patch](inflect: true) off?",
+ isPresented: $confirmsBootEssential,
+ ) {
+ Button("Leave Them Off", role: .destructive) { finish() }
+ } message: {
+ Text("The machine may not boot without \(essentialOff.map(\.identifier).joined(separator: ", ")).")
+ }
+ .task { await load(preset: machine == nil ? initial.preset : nil) }
+ }
+
+ // MARK: - Preset
+
+ private var header: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ HStack(spacing: 12) {
+ Picker("Preset", selection: presetBinding) {
+ ForEach(catalog?.presets ?? []) { preset in
+ Text(verbatim: preset.title).tag(preset.identifier)
+ }
+ }
+ .disabled(catalog == nil || isLoading)
+ .frame(width: 280)
+ if isLoading {
+ ProgressView().controlSize(.small)
+ }
+ Spacer()
+ TextField("Filter", text: $filter, prompt: Text("Filter patches"))
+ .textFieldStyle(.roundedBorder)
+ .frame(width: 200)
+ }
+ if let summary = catalog?.preset(selection.preset)?.summary, !summary.isEmpty {
+ Text(verbatim: summary)
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ .padding(12)
+ }
+
+ /// Switching preset clears both override lists: the checkmarks are read as a
+ /// difference from the preset, so a difference from the one just left behind
+ /// would silently change meaning.
+ private var presetBinding: Binding<String> {
+ Binding(
+ get: { selection.preset },
+ set: { identifier in
+ guard identifier != selection.preset else {
+ return
+ }
+ selection = VPhoneLaunchpadPatchSelection(preset: identifier)
+ Task { await load(preset: identifier) }
+ },
+ )
+ }
+
+ // MARK: - Patches
+
+ @ViewBuilder
+ private var list: some View {
+ if let catalog {
+ let rows = catalog.patches(matching: filter).sorted(using: sortOrder)
+ if rows.isEmpty {
+ ContentUnavailableView.search(text: filter)
+ } else {
+ table(rows)
+ }
+ } else if let loadError {
+ ContentUnavailableView {
+ Label("No Patch List", systemImage: "exclamationmark.triangle")
+ } description: {
+ Text(verbatim: loadError)
+ }
+ } else {
+ VStack {
+ ProgressView()
+ Text("Reading the bundle's patches…").foregroundStyle(.secondary)
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+ }
+
+ /// A flat table sorted by the order the bundle applies the patches, which
+ /// already runs one set after another. A header click regroups it; sections
+ /// were tried first and make AppKit report a reentrant table delegate.
+ private func table(_ rows: [Catalog.Patch]) -> some View {
+ Table(rows, selection: $highlighted, sortOrder: $sortOrder) {
+ TableColumn("On") { patch in
+ Toggle("On", isOn: Binding(
+ get: { selection.isOn(patch) },
+ set: { selection.set(patch, on: $0) },
+ ))
+ .labelsHidden()
+ }
+ .width(28)
+
+ TableColumn("Patch", value: \.title) { patch in
+ Text(verbatim: patch.title)
+ .lineLimit(1)
+ .help(patch.summary)
+ }
+ .width(min: 130, ideal: 180)
+
+ TableColumn("Identifier", value: \.identifier) { patch in
+ Text(verbatim: patch.identifier)
+ .font(.system(.callout, design: .monospaced))
+ .lineLimit(1)
+ .truncationMode(.middle)
+ .help(patch.identifier)
+ }
+ .width(min: 200, ideal: 350)
+
+ TableColumn("Patch Set", value: \.patchSetName) { patch in
+ Text(verbatim: patch.patchSetName).lineLimit(1)
+ }
+ .width(min: 90, ideal: 120)
+
+ TableColumn("Applies To", value: \.applicability) { patch in
+ if patch.isVersionGated {
+ Text(verbatim: patch.applicability).lineLimit(1)
+ } else {
+ Text("Any version").foregroundStyle(.tertiary).lineLimit(1)
+ }
+ }
+ .width(min: 80, ideal: 110)
+
+ TableColumn("Boot") { patch in
+ if patch.bootEssential {
+ Image(systemName: "exclamationmark.triangle")
+ .foregroundStyle(selection.isOn(patch) ? AnyShapeStyle(.secondary) : AnyShapeStyle(.orange))
+ .help(selection.isOn(patch)
+ ? String(localized: "Boot-essential")
+ : String(localized: "Boot-essential, and off"))
+ }
+ }
+ .width(32)
+ }
+ }
+
+ // MARK: - Detail
+
+ private var footer: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ if !essentialOff.isEmpty {
+ Label {
+ Text("^[\(essentialOff.count) boot-essential patch](inflect: true) off: \(essentialOff.map(\.identifier).joined(separator: ", "))")
+ .lineLimit(2)
+ } icon: {
+ Image(systemName: "exclamationmark.triangle.fill")
+ }
+ .foregroundStyle(.orange)
+ .font(.callout)
+ }
+ detail
+ Text(status)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(12)
+ }
+
+ @ViewBuilder
+ private var detail: some View {
+ if let patch = catalog?.patch(highlighted) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(verbatim: patch.title).font(.headline)
+ Text(verbatim: patch.summary)
+ .lineLimit(2)
+ .fixedSize(horizontal: false, vertical: true)
+ Text(verbatim: patch.isVersionGated
+ ? "\(patch.patchSetName) · \(patch.target) · \(patch.applicability)"
+ : "\(patch.patchSetName) · \(patch.target)")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ .frame(height: 62, alignment: .topLeading)
+ } else {
+ Text("Select a patch to read what it changes.")
+ .foregroundStyle(.secondary)
+ .frame(height: 62, alignment: .topLeading)
+ }
+ }
+
+ /// What is on, what differs from the preset, and when the choice takes effect.
+ private var status: String {
+ guard let catalog else {
+ return ""
+ }
+ let on = catalog.patches.count(where: { selection.isOn($0) })
+ var text = String(localized: "\(on) of \(catalog.patches.count) patches on.")
+ if selection.hasOverrides {
+ text += String(localized: " Differs from the preset: \(selection.blocked.count) off, \(selection.allowed.count) on.")
+ }
+ return machine == nil
+ ? text + String(localized: " Recorded when the machine is created.")
+ : text + String(localized: " Applies the next time the boot chain is patched.")
+ }
+
+ // MARK: - Actions
+
+ private func load(preset: String?) async {
+ isLoading = true
+ defer { isLoading = false }
+ do {
+ let catalog = try await Catalog.read(
+ using: model.bundles.commandLine(),
+ machine: machine,
+ preset: preset,
+ )
+ // A second switch of the picker may have overtaken this read.
+ guard preset == nil || preset == selection.preset else {
+ return
+ }
+ // A nil preset means "report what the VM has recorded", so its own
+ // choice is what the boxes start from.
+ selection.preset = catalog.activePreset
+ if preset == nil {
+ selection.blocked = Set(catalog.blockedPatches)
+ selection.allowed = Set(catalog.allowedPatches)
+ }
+ selection.normalize(against: catalog)
+ self.catalog = catalog
+ // The detail pane reserves its space either way, so it starts with
+ // something to read rather than a gap.
+ highlighted = highlighted ?? catalog.patches.first?.identifier
+ loadError = nil
+ } catch {
+ loadError = VPhoneLaunchpadError.message(for: error)
+ }
+ }
+
+ private func commit() {
+ if essentialOff.isEmpty {
+ finish()
+ } else {
+ confirmsBootEssential = true
+ }
+ }
+
+ private func finish() {
+ onSave(selection)
+ dismiss()
+ }
+}