Run a virtual iPhone on an Apple Silicon Mac.
Swift
Let an installed VM's patch selection change, and say what it reaches
Jackya153e9ddc46d
diff --git a/Documents/Guides/launchpad-cli.md b/Documents/Guides/launchpad-cli.mdindex 42f41787..32a8524d 100644--- a/Documents/Guides/launchpad-cli.md+++ b/Documents/Guides/launchpad-cli.md@@ -32,7 +32,7 @@ each from a bundle at a different time:| --- | --- | --- || Host Programs | `vphone-cli`, `vphone-vm` | The bound bundle, on every command. A new binding applies at the next start. || Guest Environment | vphoned and the hook dylibs | `cfw install` at creation, and `cfw update-environment` (stopped machine) later. |-| Boot Chain | Patched firmware, restore, CFW patches | `fw patch`, `restore` and `cfw install` at creation. Fixed; only a new machine changes it. |+| Boot Chain | Patched firmware, restore, CFW patches | `fw patch`, `restore` and `cfw install` at creation. After that, `vphone-cli fw set-patches` changes the choice and `vphone-cli fw patches <vm>` lists what has not reached the guest: guest patches apply at the next `cfw update-environment`, AVPBooter at the next `fw patch` while the restore tree is kept, and the rest of the boot chain only with a restore. Launchpad shows the count in the inspector. |The **default** bundle (formerly "active") decides only the version`vm create` binds when `--bundle` is not given, and what `exec` anddiff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex 365d0917..d19280ec 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -2641,3 +2641,36 @@ removed. There is no migration.**Opting out.** `vphone-cli fw set-patches <vm> --blockkernel-cfw-paravirt_user_clients`, then re-patch.++## Guest patches follow the selection, both ways (2026-10-04)++No new Apple binary patch. This changes how every guest-side patch in this+document (the dyld shared cache rows, the guest Mach-O and file patches, the+Preboot device-tree repairs) is applied after a VM exists, so it is recorded+here. Full write-up and live validation:+`Research/Firmware/post_creation_patch_changes.md`.++**Before.** `cfw install` applied the guest half from `PatchPlan.plist`, and+turning a guest patch off on an installed VM did nothing: the step was skipped+and the patched bytes stayed. The dyld cache patches were applied in place with+no record of what they replaced.++**Now.** `cfw install` and `cfw update-environment` resolve the guest half from+the VM's current `PatchSelection.plist`, apply what is on and revert what is+off. Mach-O, entitlement and guest-file patches revert from the `.bak` beside+the file; the Preboot device tree from `devicetree.img4.bak`; the dyld cache+from `.vphone-dsc-undo.json` in the cache directory, which holds the original+bytes of every content write a cache verb makes (slot hashes are re-derived by+re-attesting, not logged). Each cache verb takes `--undo-log`/`--undo-id`, and+the hidden `cfw patch-dsc-revert` verb applies the log. What is live is recorded+in the `Guest` part of `<vm>/PatchReceipt.plist`.++**Existing VMs.** A guest installed before this change has no undo log and no+backup for the files several patches share, so those patches are reported "not+revertible" when turned off and stay recorded as live; nothing is guessed. Every+dyld row above that a cache verb idempotently re-runs keeps its undo records, so+a revert works however many installs later it happens.++**Boot chain unchanged.** Boot-chain patches still reach a guest only through a+restore (AVPBooter through `fw patch`); `fw set-patches` and `fw patches <vm>`+say so per patch.diff --git a/Research/Firmware/post_creation_patch_changes.md b/Research/Firmware/post_creation_patch_changes.mdnew file mode 100644index 00000000..281416f6--- /dev/null+++ b/Research/Firmware/post_creation_patch_changes.md@@ -0,0 +1,181 @@+# Changing a VM's Patches After It Exists++Status: implemented and validated on a test VM 2026-10-04 (branch+`post-creation-patches`). "Current Behaviour" describes `caee5a4` (Release+2.5.0) as read from the code, before this change; "What Was Built" and+"Validation" describe the change.++## The Question++A VM's patches are chosen in the New Machine sheet and Launchpad then calls them+"Fixed once the machine is installed". The CLI does not agree: `fw set-patches`+accepts a change on any VM. This note records what a change made after creation+actually reaches, why, and the plan to make it reach everything it can.++## Current Behaviour++### Three records, no truth++| File | Meaning | Writers | Readers |+| --- | --- | --- | --- |+| `<vm>/PatchSelection.plist` | desired: preset + blocked/allowed boxes | `fw set-patches`, `fw patch`, CLI `vm create` | `fw patch`, `fw patches`, `cfw install` (late guest patches only) |+| `<vm>/PatchPlan.plist` | what the last `fw patch` resolved | `fw patch` | `cfw install`, `cfw update-environment` |+| — | what the guest runs | nobody | nobody |++- `fw set-patches` (`VPhoneFirmwareCommand.swift`, `SetPatches`) has no+ installed check. Its help says the choice applies at the next `fw patch`.+- `fw patches --json` reports the selection only. Nothing compares the+ selection, the plan, or the guest, so drift is silent.+- `PatchPlan.plist` carries no bundle version, no digest, and no evidence that+ `restore` or `cfw install` ever consumed it.+- `withLateGuestPatches` (`VPhoneCustomFirmwareInstaller.swift`) re-resolves 11+ late audio/Preboot patches against the *current* selection, so a+ `set-patches` on an installed VM changes what the next `update-environment`+ turns on, without `fw patch`. It only ever adds; it never turns one off.++### The restore tree is gone by default++`fw patch` needs `*_Restore` (`FirmwarePipelineDiscovery.findRestoreDirectory`+throws "Run vphone-cli fw prepare first"), and a full `cfw install` needs it for+the cryptex images. Launchpad and `cfw install` delete it after the first boot+unless `--keep-artifacts`. `<vm>/FirmwareOriginals/` survives that deletion+(only `*_Restore` is removed, `VPhoneRestoreInfo.removeBuiltFirmware`), so the+pristine boot-chain payloads are still on disk for every VM patched since+2026-09-30.++### Where each patch lands++Counts are declarations in `FirmwarePatcher/PatchSets/*.swift`.++| Part | Patches | Lives in | Reaches the guest by | After creation |+| --- | --- | --- | --- | --- |+| AVPBooter | 1 | VM root, `romImages.avpBooter`, read every boot | `fw patch` itself | works, but `fw patch` refuses without a restore tree |+| iBSS, iBEC | 7 | restore tree only | DFU during a restore | irrelevant to an installed guest; only the next restore uses them |+| LLB | 6 | NOR (personalized by idevicerestore, `LlbImageData`) | restore | needs a restore; `restore --no-erase` exists but is unvalidated |+| kernelcache, DeviceTree, TXM | 54 + 30 + 6 | Preboot (personalized) | restore | Preboot can be rewritten by a host mount — `cfw install` already edits `devicetree.img4` there; nothing does it for the kernelcache or TXM |+| Guest (dyld cache, Mach-O, files, entitlements, Preboot DT) | 34 | System / Preboot volumes of `Disk.img` | `cfw install`, partly `cfw update-environment` | turning on works by re-running; turning off does nothing |++Why turning a guest patch off does nothing today:++- **dyld shared cache** — patched in place, no backup. The verbs are no-ops on+ patched bytes but have no inverse. The only reset is emptying+ `System/Cryptexes/{OS,App}` so `installCryptexes` copies them again, which+ needs the restore tree.+- **Mach-O** — always re-patched from `<path>.bak`, then re-signed. When the+ patch is off the step is skipped and the patched file stays. Reverting is a+ copy back from `.bak`.+- **Preboot device tree** — edited on a staged copy and written back, with no+ backup of the personalized `devicetree.img4`.+- Only VirtualAudio has an explicit restore-from-`.bak`, in `update-environment`.++Why rewriting Preboot boots at all: the iBSS/iBEC/LLB image4 callback bypass+accepts a modified IM4P payload under the original IM4M+(`CustomFirmwarePostRestoreDeviceTree.swift` header,+`firmware_manifest_and_origins.md`). The same bypass is what a kernelcache swap+would rely on; confirm whether the stage that loads the kernelcache is covered+before shipping it.++### Bundle rebinding++`vm set-bundle` changes only the binding. Afterwards `fw patches`/`fw patch`+resolve against the new bundle's catalogue; an identifier renamed since then+makes `fw patch` throw `unknownPatch` (no migration), and `update-environment`+may turn on late guest patches the new catalogue declares.++## What Was Built++The design keeps the existing layers and adds one record:+`<vm>/PatchReceipt.plist`, `VPhoneVirtualMachinePatchReceipt` in+`VPhonePatchPresetStore.swift`. It is keyed by part — a+`VPhoneFirmwareComponent.rawValue` for boot-chain patches, `Guest` for+everything `cfw install` writes — and each step that puts patched bytes into the+guest replaces the parts it wrote, recording the enabled identifiers, the verb,+the bundle version and the date. A part a step wrote with nothing on is recorded+empty, so "reverted" and "unknown" differ. A VM with no receipt is unknown, not+empty. `NotApplicable` lists selected patches the guest has nothing for (the+board audio repair on an iPhone, the build spoof with no value), which never+count as drift.++| Step | Parts it records |+| --- | --- |+| `restore` (success) | `iBSS`, `iBEC`, `LLB`, `TXM`, `kernelcache`, `DeviceTree` from `PatchPlan.plist`, and `Guest` as empty (the system volume is re-imaged) |+| `cfw install`, `cfw update-environment` | `Guest` |++Nothing records `AVPBooter`; its drift is measured against the plan.++**Report and guard.** `fw patches <vm>` compares selection, plan and receipt per+patch; `--json` adds `part`, `wanted`, `planned`, `applied`, `pending`,+`delivery` per patch and `planRecorded`, `receiptRecorded`, `receiptParts`,+`installed`, `pendingPatches` at the top, only when a VM is named, so a 2.5+Launchpad and bundle stay interchangeable. The rule is `FirmwarePatchDrift`.+`fw set-patches` on an installed VM lists each differing patch with the step that+delivers it. Launchpad's inspector shows preset, overrides and a "Not Applied"+count read-only, through the machine's bound bundle.++**Guest patches both ways.** The guest half resolves from the current selection+(`FirmwareGuestPatchResolution`); the boot-chain half stays as `fw patch` built+it. `cfw install` and `cfw update-environment` apply what is on and revert what+is off:++- Mach-O, entitlement and guest-file patches restore from the `.bak` beside the+ file. debugserver, Campo, the build spoof and the VirtualAudio tunings now take+ one before their first write.+- The Preboot device tree keeps `devicetree.img4.bak` beside it, the+ post-identity, pre-repair tree. A run rebuilds the tree from it in staging and+ writes only when the bytes differ, so an unchanged run does not move the mtime+ vphoned's MobileGestalt cache check reads.+- The dyld cache gets an undo log, `.vphone-dsc-undo.json` in the cache+ directory, with the original bytes of every content write+ (`DyldSharedCacheUndoLog`, captured by `DyldSharedCacheChunkSet`). Slot hashes+ are not logged: a revert puts the bytes back and re-attests the page, which is+ right even when two patches share one. A re-run that writes nothing keeps the+ records; every record is validated before anything is written.+- A first backup is taken only when no patch touching that file is live, so a+ backup never captures patched bytes. Where there is none, the patch is+ reported not revertible and stays live in the receipt. On a VM installed+ before this change that is every dyld patch and every multi-edit file.+- Only dyld patches whose state changes are touched, so an unchanged+ `update-environment` does no cache scan. A failing patch is reported, keeps+ its previous state in the receipt, and does not stop the run or the vphoned+ redeploy. The environment-library rule for `update-environment` is as before.++"Prior live" is the receipt's `Guest` part; for a VM with none, the plan's guest+patches plus the late ones the old installer added.++**Not built: the boot chain without a restore.** Writing a re-patched+kernelcache, TXM or DeviceTree into Preboot was dropped before implementation;+those three, LLB, iBSS and iBEC change only through a restore, and AVPBooter only+through `fw patch`, which needs the restore tree (`--keep-artifacts`).+`restore --no-erase` (row 4 of `Research/Restore/native_restore_architecture.md`)+is still unvalidated.++## Validation (2026-10-04)++`patchtest-iphone`, iPhone 27.0 24A435 + cloudOS 26.4, `--keep-artifacts`,+driven through Launchpad (`vm set-bundle … --update-environment` runs the helper's+root `cfw update-environment`).++Installed by 2.5.0, then updated with this build:++1. First update: no dyld patch touched, `Guest` recorded, guest boots, vphoned+ answers.+2. `--block system-diskimagesiod-cfw-is_mount_complete --block dyld-cfw-camera`,+ update: diskimagesiod restored from `.bak` and dropped from the receipt; the+ camera patch reported "patched before the undo log existed; not revertible"+ and kept live. Guest boots.++Created by this build:++3. Fresh VM: receipt has `iBSS`…`DeviceTree` and `Guest`; `fw patches` reports+ no drift. The undo log holds records for the six applied dyld patches.+4. `--block dyld-cfw-camera --block preboot-cfw-devicetree_microphone_array`,+ update: both leave the receipt, the camera's records leave the undo log, the+ guest boots and vphoned answers (the reverted pages re-attested correctly).+5. Back to the preset, update: both return to the receipt, the camera's six+ records are back, the guest boots, `fw patches` reports no drift.++Not checked live: the Launchpad inspector (build only; a Debug Launchpad must+run in snapshot mode), the identity rewrite on a re-run full install, and the+helper's console log, which on these runs kept little or none of+`update-environment`'s standard output, so the evidence above is the receipt,+the undo log read through vphoned's `files.read`, and boots.diff --git a/Skills/authoring-patch-sets/SKILL.md b/Skills/authoring-patch-sets/SKILL.mdindex 1c7b63b3..3ffe49e4 100644--- a/Skills/authoring-patch-sets/SKILL.md+++ b/Skills/authoring-patch-sets/SKILL.md@@ -217,7 +217,15 @@ fails if they drift.### What a VM Records-`fw set-patches` writes `<vm>/PatchSelection.plist`, and is the only writer:+A VM carries three patch records, each with its own writers:++| File | What it says | Written by |+| --- | --- | --- |+| `<vm>/PatchSelection.plist` | what the owner wants: a preset plus the boxes they changed | `fw set-patches`; `vm create` (preset only); `fw patch` (rewrites it with what it ran, `--preset` included) |+| `<vm>/PatchPlan.plist` | what the last `fw patch` resolved | `fw patch` |+| `<vm>/PatchReceipt.plist` | what is live in the guest, part by part | each step that puts patched bytes into the guest |++`fw set-patches` is how a person changes the first:```zshvphone-cli fw set-patches lab --preset extended --block kernel-cfw-debugger@@ -230,6 +238,20 @@ still reaches a VM whose boxes were never touched. The Launchpad's patch editorreads `fw patches --json` and writes through this verb rather than touching a VMbundle itself. Blocking a boot-essential patch is allowed; it warns on stderr.+A selection reaches the guest only through the step that owns the bytes, which+depends on where the patch lands; changing it on a machine that already exists is+covered in `Research/Firmware/post_creation_patch_changes.md`. In short: the+boot chain follows the plan and reaches the guest only through a restore (or,+for AVPBooter, the next `fw patch`); guest-side patches follow the *current*+selection, and `cfw install` and `cfw update-environment` apply them both ways —+on, or reverted when turned off — and record the `Guest` part of the receipt.+`vphone-cli fw patches <vm>` compares all three records.++If your patch targets the guest, make it revertible: back the file up before+the first write (`.bak` beside it) or, for the dyld cache, write through a+`DyldSharedCacheChunkSet` with undo capture so its bytes land in the undo log.+A guest patch with no way back is reported "not revertible" and stays live.+## Out-of-Tree Patch Sets**Start from `VPhoneExecutable/VPhoneCommand/VPhonePatchSetExample`.** It is adiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swiftindex 958503a2..d82b72fc 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift@@ -108,11 +108,17 @@ public final class DyldSharedCacheChunkSet {private let architecture: String- /// Guards the two pieces of lazily built state below.+ /// Guards the three pieces of mutable state below.private let stateLock = NSLock()private var writeLog: [DyldSharedCacheWriteSpan] = []private var loadedLocalSymbols: DyldSharedCacheLocalSymbolTable?+ /// When set, every `write(at:_:)` first reads the bytes it is about to+ /// replace and captures them here, so a later run can put them back for a+ /// patch that has since been turned off. Nil disables capture, which is the+ /// default and what every read-only or throwaway use of this type wants.+ private var undoCaptureLog: DyldSharedCacheUndoLog?+// MARK: - Construction/// Open the cache under `directory`.@@ -121,9 +127,12 @@ public final class DyldSharedCacheChunkSet {/// - directory: the directory holding `dyld_shared_cache_<arch>*`./// - architecture: cache architecture suffix; `arm64e` for every device/// this project targets.- public init(directory: URL, architecture: String = "arm64e") throws {+ /// - captureUndo: start capturing the original bytes of every write into+ /// an undo log, retrievable with ``takeUndoLog()``. Off by default.+ public init(directory: URL, architecture: String = "arm64e", captureUndo: Bool = false) throws {self.directory = directoryself.architecture = architecture+ undoCaptureLog = captureUndo ? DyldSharedCacheUndoLog() : nilchunkURLs = try Self.enumerateChunks(in: directory, architecture: architecture)guard !chunkURLs.isEmpty else {throw DyldSharedCacheError.noChunksFound(directory: directory.path)@@ -302,14 +311,41 @@ public final class DyldSharedCacheChunkSet {guard !data.isEmpty else { return DyldSharedCacheWriteSpan.byte(at: vma) }let span = DyldSharedCacheWriteSpan(vma: vma, length: data.count)let (chunkURL, range) = try fileRange(of: span)+ // Capture the bytes about to be overwritten before writing, so a later+ // run can put them back. Read once here rather than re-reading the+ // whole span later, and only when capture is on.+ let captured: Data? = stateLock.withLock { undoCaptureLog != nil }+ ? try Self.read(url: chunkURL, offset: UInt64(range.lowerBound), length: data.count)+ : nillet handle = try FileHandle(forUpdating: chunkURL)defer { try? handle.close() }try handle.seek(toOffset: UInt64(range.lowerBound))try handle.write(contentsOf: data)- stateLock.withLock { writeLog.append(span) }+ stateLock.withLock {+ writeLog.append(span)+ if let captured, captured != data {+ undoCaptureLog?.capture(+ chunk: chunkURL.lastPathComponent,+ fileOffset: range.lowerBound,+ vma: vma,+ original: captured,+ )+ }+ }return span}+ /// The undo log captured so far, if capture was enabled, and clear it so a+ /// second call does not hand back the same records. The caller stamps the+ /// records with the patch identifier this cache set applied.+ public func takeUndoLog() -> DyldSharedCacheUndoLog? {+ stateLock.withLock {+ guard let log = undoCaptureLog else { return nil }+ undoCaptureLog = DyldSharedCacheUndoLog()+ return log+ }+ }+/// Every span `write(at:_:)` has put on disk through this chunk set, oldest/// first.public var recordedWrites: [DyldSharedCacheWriteSpan] {diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheError.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheError.swiftindex a80bef6c..d86f8478 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheError.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheError.swift@@ -34,6 +34,12 @@ public enum DyldSharedCacheError: Error, CustomStringConvertible, Sendable {case symbolNotFound(symbol: String, image: String?)/// An image path is not in the cache's image list.case imageNotFound(String)+ /// An undo-log record names a chunk that is not a plain file beside the+ /// cache — a path with a separator or a parent reference. Refused rather+ /// than written through.+ case undoChunkOutsideCache(chunk: String)+ /// An undo-log record does not fit the cache it claims to describe.+ case undoRecordInvalid(chunk: String, reason: String)public var description: String {switch self {@@ -63,6 +69,10 @@ public enum DyldSharedCacheError: Error, CustomStringConvertible, Sendable {}case let .imageNotFound(path):"Image \(path) is not in the cache"+ case let .undoChunkOutsideCache(chunk):+ "Undo-log chunk \(chunk) is not a plain file beside the cache"+ case let .undoRecordInvalid(chunk, reason):+ "Undo-log record for \(chunk) is invalid: \(reason)"}}}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheUndoLog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheUndoLog.swiftnew file mode 100644index 00000000..f7cd5453--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheUndoLog.swift@@ -0,0 +1,222 @@+// DyldSharedCacheUndoLog.swift — The original bytes behind every dyld-shared-cache edit.+//+// The shared cache is several gigabytes, so turning a cache patch back off+// cannot mean keeping a pristine copy. It means knowing, byte for byte, what+// each patch overwrote. Before a `DyldSharedCacheChunkSet` writes, it reads the+// bytes it is about to replace and appends them here, tagged with the chunk+// file and the file offset they came from. A later run that finds a patch now+// deselected writes those bytes back where they were and re-attests the pages+// they land in, which is byte-for-byte the pristine cache for that patch.+//+// What this does NOT store is the re-attestation writes themselves — the slot+// hashes `DyldSharedCacheCodeSignature` rewrites after a content edit. Those are+// derived, not chosen: the slot hash of a 16 KiB page is the SHA-256 of the+// page. Two patches can land in one page, so restoring one patch's slot bytes+// to "pristine" while the other patch stays would write the wrong hash for a+// page that is not pristine. The correct inverse is therefore: put the content+// bytes back, then re-hash whatever the page now holds. Re-attesting the+// restored page reproduces the pristine slot hash exactly when (and only when)+// the page is now pristine, and the right non-pristine hash otherwise. So the+// undo log records content writes and leaves the slot hashes to be recomputed.+//+// A record is keyed by the patch identifier that wrote it, so a revert can act+// on one patch without disturbing another's bytes. An identifier with no+// records is a patch that wrote nothing — an idempotent no-op on an+// already-patched or self-gated cache — and reverting it is likewise nothing.++import Foundation+import VPhonePatchKit++/// Every byte range a set of dyld-shared-cache patches overwrote, enough to put+/// the original bytes back for any subset of them.+public struct DyldSharedCacheUndoLog: Codable, Sendable, Hashable {+ /// One contiguous run of bytes a patch replaced, and what was there before.+ public struct Record: Codable, Sendable, Hashable {+ /// The patch declaration identifier whose write this was.+ public var patchID: String+ /// The chunk file, named relative to the cache directory+ /// (`dyld_shared_cache_arm64e`, `….01`, …) so the log stays valid when+ /// the cache directory is the same tree at a different absolute path.+ public var chunk: String+ /// Byte offset of the run within `chunk`.+ public var fileOffset: Int+ /// The virtual address the run starts at, for re-attestation.+ public var vma: UInt64+ /// The bytes that were there before the patch wrote. Base64 in JSON.+ public var original: Data++ public init(patchID: String, chunk: String, fileOffset: Int, vma: UInt64, original: Data) {+ self.patchID = patchID+ self.chunk = chunk+ self.fileOffset = fileOffset+ self.vma = vma+ self.original = original+ }++ private enum CodingKeys: String, CodingKey {+ case patchID = "PatchID"+ case chunk = "Chunk"+ case fileOffset = "FileOffset"+ case vma = "VMA"+ case original = "Original"+ }+ }++ public var records: [Record]++ public init(records: [Record] = []) {+ self.records = records+ }++ private enum CodingKeys: String, CodingKey {+ case records = "Records"+ }++ // MARK: - Building++ /// Append a run, assuming it has not been recorded yet. The caller — a+ /// `DyldSharedCacheChunkSet` capturing a write — supplies everything but the+ /// identifier, which `stamp(patchID:)` fills once the patch is known.+ public mutating func capture(chunk: String, fileOffset: Int, vma: UInt64, original: Data) {+ records.append(Record(patchID: "", chunk: chunk, fileOffset: fileOffset, vma: vma, original: original))+ }++ /// Give every still-unstamped record this patch identifier. Called once per+ /// patcher invocation, because one invocation applies one declared patch.+ public mutating func stamp(patchID: String) {+ for index in records.indices where records[index].patchID.isEmpty {+ records[index].patchID = patchID+ }+ }++ /// The identifiers that have at least one recorded run.+ public var patchIDs: Set<String> {+ Set(records.map(\.patchID))+ }++ /// Fold `other`'s records in after this log's. A patch identifier present in+ /// both keeps both sides' runs; de-duplication is not needed because each+ /// run is a distinct (chunk, offset) a patch wrote exactly once per install.+ public mutating func merge(_ other: DyldSharedCacheUndoLog) {+ records.append(contentsOf: other.records)+ }++ /// The log to store after a patch run for `patchID` captured `captured`, or+ /// nil when the stored log should be left exactly as it is.+ ///+ /// Nothing captured — an idempotent re-run over sites that already carry+ /// the patch, a self-gated no-op, or a dry run — returns nil, so the+ /// originals an earlier run recorded for the patch are kept. Without that a+ /// second install would forget how to revert every patch it found already+ /// applied.+ ///+ /// Something captured is merged in, not swapped in: a run can find some+ /// sites of a patch already written and write the rest, and only the new+ /// sites are captured. A record for a (chunk, offset) the log already has+ /// keeps the older original, which is the byte that was there before any+ /// run touched it.+ public static func updated(+ existing: DyldSharedCacheUndoLog?,+ captured: DyldSharedCacheUndoLog,+ patchID: String,+ ) -> DyldSharedCacheUndoLog? {+ var fresh = captured+ fresh.stamp(patchID: patchID)+ guard !fresh.records.isEmpty else { return nil }+ var merged = existing ?? DyldSharedCacheUndoLog()+ let known = Set(merged.records.map { "\($0.chunk)@\($0.fileOffset)" })+ merged.records.append(contentsOf: fresh.records.filter { !known.contains("\($0.chunk)@\($0.fileOffset)") })+ return merged+ }++ /// Check every record against the cache in `directory` before anything is+ /// written: a plain chunk name, a regular file that is not a link, a+ /// non-negative offset, and a run that ends inside the file. One bad record+ /// refuses the whole log — a log that does not describe this cache must not+ /// half-revert it.+ public func validate(in directory: URL, patchIDs: Set<String>? = nil) throws {+ var sizes: [String: Int] = [:]+ for record in records where patchIDs?.contains(record.patchID) ?? true {+ guard !record.chunk.isEmpty, !record.chunk.contains("/"), record.chunk != ".", record.chunk != ".."+ else {+ throw DyldSharedCacheError.undoChunkOutsideCache(chunk: record.chunk)+ }+ let size: Int+ if let known = sizes[record.chunk] {+ size = known+ } else {+ var metadata = stat()+ let path = directory.appendingPathComponent(record.chunk).path+ guard lstat(path, &metadata) == 0, metadata.st_mode & S_IFMT == S_IFREG else {+ throw DyldSharedCacheError.undoRecordInvalid(chunk: record.chunk, reason: "not a regular file beside the cache")+ }+ size = Int(metadata.st_size)+ sizes[record.chunk] = size+ }+ guard record.fileOffset >= 0, !record.original.isEmpty,+ record.fileOffset <= size, record.original.count <= size - record.fileOffset+ else {+ throw DyldSharedCacheError.undoRecordInvalid(+ chunk: record.chunk,+ reason: "offset \(record.fileOffset) + \(record.original.count) bytes is outside the file (\(size) bytes)",+ )+ }+ }+ }++ /// This log without any record belonging to `patchIDs` — what remains after+ /// those patches are reverted and their runs no longer describe the cache.+ public func removing(patchIDs: Set<String>) -> DyldSharedCacheUndoLog {+ DyldSharedCacheUndoLog(records: records.filter { !patchIDs.contains($0.patchID) })+ }++ /// The records belonging to any of `patchIDs`, newest write last so that a+ /// restore replays them in reverse and the earliest original wins when two+ /// runs of one patch overlap (they do not today, but order makes it safe).+ public func records(forPatchIDs patchIDs: Set<String>) -> [Record] {+ records.filter { patchIDs.contains($0.patchID) }+ }++ // MARK: - Serialisation++ public func encoded() throws -> Data {+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.sortedKeys]+ return try encoder.encode(self)+ }++ public static func decode(_ data: Data) throws -> DyldSharedCacheUndoLog {+ try JSONDecoder().decode(DyldSharedCacheUndoLog.self, from: data)+ }++ // MARK: - Restoring++ /// Put the original bytes of `patchIDs` back into the chunk files under+ /// `directory`, in reverse record order so an earlier write wins any+ /// overlap. The caller re-attests the touched pages afterwards; the returned+ /// spans are exactly what to re-attest, one per restored run.+ ///+ /// A record naming a chunk that is not under `directory` is refused rather+ /// than written through a path that escaped the cache — the log is trusted+ /// only to describe the cache it sits beside.+ @discardableResult+ public func restore(+ patchIDs: Set<String>,+ in directory: URL,+ log: ((String) -> Void)? = nil,+ ) throws -> [DyldSharedCacheWriteSpan] {+ try validate(in: directory, patchIDs: patchIDs)+ var spans: [DyldSharedCacheWriteSpan] = []+ for record in records(forPatchIDs: patchIDs).reversed() {+ let url = directory.appendingPathComponent(record.chunk)+ let handle = try FileHandle(forUpdating: url)+ defer { try? handle.close() }+ try handle.seek(toOffset: UInt64(record.fileOffset))+ try handle.write(contentsOf: record.original)+ spans.append(DyldSharedCacheWriteSpan(vma: record.vma, length: record.original.count))+ log?(" [+] revert: \(record.original.count) byte(s) at 0x"+ + String(record.vma, radix: 16, uppercase: true) + " in \(record.chunk) (\(record.patchID))")+ }+ return spans+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheCameraPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheCameraPatcher.swiftindex 25041f2d..371dc036 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheCameraPatcher.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheCameraPatcher.swift@@ -203,6 +203,8 @@ public enum DyldSharedCacheCameraPatcher {symbolCacheURL: URL? = nil,dryRun: Bool = false,force: Bool = false,+ captureUndo: Bool = false,+ onUndo: ((DyldSharedCacheUndoLog) -> Void)? = nil,log: ((String) -> Void)? = stdoutLog,) throws -> Result {try apply(@@ -211,6 +213,8 @@ public enum DyldSharedCacheCameraPatcher {symbolCacheURL: symbolCacheURL,dryRun: dryRun,force: force,+ captureUndo: captureUndo,+ onUndo: onUndo,log: log,)}@@ -244,9 +248,12 @@ public enum DyldSharedCacheCameraPatcher {symbolCacheURL: URL?,dryRun: Bool,force: Bool,+ captureUndo: Bool = false,+ onUndo: ((DyldSharedCacheUndoLog) -> Void)? = nil,log: ((String) -> Void)?,) throws -> Result {- let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory)+ let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory, captureUndo: captureUndo)+ defer { if captureUndo, let undo = chunks.takeUndoLog() { onUndo?(undo) } }let resolver = try DyldSharedCacheSymbolResolver(mainCacheURL: symbolCacheURL ?? chunks.mainCacheURL,)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher.swiftindex 0ce1204e..4993e208 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher.swift@@ -234,9 +234,12 @@ public enum DyldSharedCacheHypervisorVirtualMachinePatcher {public static func patch(chunksDirectory: URL,dryRun: Bool = false,+ captureUndo: Bool = false,+ onUndo: ((DyldSharedCacheUndoLog) -> Void)? = nil,log: ((String) -> Void)? = DyldSharedCacheCodeSignature.stderrLog,) throws -> Result {- let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory)+ let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory, captureUndo: captureUndo)+ defer { if captureUndo, let undo = chunks.takeUndoLog() { onUndo?(undo) } }log?(" [.] \(chunksDirectory.path): \(chunks.chunkURLs.count) chunk(s), "+ "\(chunks.mappings.count) mapping(s), "diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBForceKernPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBForceKernPatcher.swiftindex 200097de..fddca9d8 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBForceKernPatcher.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBForceKernPatcher.swift@@ -168,9 +168,12 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {public static func patch(chunksDirectory: URL,dryRun: Bool = false,+ captureUndo: Bool = false,+ onUndo: ((DyldSharedCacheUndoLog) -> Void)? = nil,log: ((String) -> Void)? = stdoutLog,) throws -> Outcome {- let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory)+ let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory, captureUndo: captureUndo)+ defer { if captureUndo, let undo = chunks.takeUndoLog() { onUndo?(undo) } }let resolver = try DyldSharedCacheSymbolResolver(chunks: chunks)return try patch(chunks: chunks, resolver: resolver, dryRun: dryRun, log: log)}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBSwapEndPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBSwapEndPatcher.swiftindex 57539aaf..bcda7a6c 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBSwapEndPatcher.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBSwapEndPatcher.swift@@ -125,6 +125,8 @@ public enum DyldSharedCacheIOMFBSwapEndPatcher {chunksDirectory: URL,targetSize: UInt32 = defaultTargetSize,dryRun: Bool = false,+ captureUndo: Bool = false,+ onUndo: ((DyldSharedCacheUndoLog) -> Void)? = nil,log: ((String) -> Void)? = DyldSharedCacheCodeSignature.stderrLog,) throws -> DyldSharedCacheIOMFBSwapEndPatch {// Before opening a 6.7 GB cache and its 1.2 GB symbol table: a target@@ -132,7 +134,8 @@ public enum DyldSharedCacheIOMFBSwapEndPatcher {// as one rather than as whatever the cache happens to say first._ = try replacement(forTargetSize: targetSize)- let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory)+ let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory, captureUndo: captureUndo)+ defer { if captureUndo, let undo = chunks.takeUndoLog() { onUndo?(undo) } }let resolver = try DyldSharedCacheSymbolResolver(chunks: chunks)return try patch(chunks: chunks,diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLSDEmbeddedRegPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLSDEmbeddedRegPatcher.swiftindex 774d2d09..8de9e1ec 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLSDEmbeddedRegPatcher.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLSDEmbeddedRegPatcher.swift@@ -153,9 +153,12 @@ public enum DyldSharedCacheLSDEmbeddedRegPatcher {public static func patch(chunksDirectory: URL,dryRun: Bool = false,+ captureUndo: Bool = false,+ onUndo: ((DyldSharedCacheUndoLog) -> Void)? = nil,log: ((String) -> Void)? = stdoutLog,) throws -> Report {- let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory)+ let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory, captureUndo: captureUndo)+ defer { if captureUndo, let undo = chunks.takeUndoLog() { onUndo?(undo) } }log?(" [.] \(chunksDirectory.path): \(chunks.chunkURLs.count) chunk(s), "+ "\(chunks.mappings.count) mapping(s)")diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLockdownModePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLockdownModePatcher.swiftindex 3aee8ddf..9c346cd2 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLockdownModePatcher.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheLockdownModePatcher.swift@@ -132,9 +132,13 @@ public enum DyldSharedCacheLockdownModePatcher {public static func patch(chunksDirectory: URL,dryRun: Bool = false,+ captureUndo: Bool = false,+ onUndo: ((DyldSharedCacheUndoLog) -> Void)? = nil,log: ((String) -> Void)? = DyldSharedCacheCodeSignature.stderrLog,) throws -> Outcome {- try patch(in: DyldSharedCacheChunkSet(directory: chunksDirectory), dryRun: dryRun, log: log)+ let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory, captureUndo: captureUndo)+ defer { if captureUndo, let undo = chunks.takeUndoLog() { onUndo?(undo) } }+ return try patch(in: chunks, dryRun: dryRun, log: log)}/// Patch an already-open cache.diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMISTrustAuthPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMISTrustAuthPatcher.swiftindex 1b112726..20104d6c 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMISTrustAuthPatcher.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMISTrustAuthPatcher.swift@@ -266,9 +266,12 @@ public enum DyldSharedCacheMISTrustAuthPatcher {public static func patch(chunksDirectory: URL,dryRun: Bool = false,+ captureUndo: Bool = false,+ onUndo: ((DyldSharedCacheUndoLog) -> Void)? = nil,log: ((String) -> Void)? = stdoutLog,) throws -> Report {- let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory)+ let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory, captureUndo: captureUndo)+ defer { if captureUndo, let undo = chunks.takeUndoLog() { onUndo?(undo) } }log?(" [.] \(chunksDirectory.path): \(chunks.chunkURLs.count) chunk(s), "+ "\(chunks.mappings.count) mapping(s)")diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swiftindex 04c89665..c359b4b0 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMaxSlidePatcher.swift@@ -198,6 +198,8 @@ public enum DyldSharedCacheMaxSlidePatcher {kernelRegionSize: UInt64 = kernelSharedRegionSize,dryRun: Bool = false,force: Bool = false,+ captureUndo: Bool = false,+ onUndo: ((DyldSharedCacheUndoLog) -> Void)? = nil,verbose: Bool = true,) throws -> Result {let mainChunkName = "dyld_shared_cache_\(architecture)"@@ -210,7 +212,10 @@ public enum DyldSharedCacheMaxSlidePatcher {// The patcher's own chunk set: see the note at the top of the file about// why its write log must not be the caller's.- let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory, architecture: architecture)+ let chunks = try DyldSharedCacheChunkSet(+ directory: chunksDirectory, architecture: architecture, captureUndo: captureUndo,+ )+ defer { if captureUndo, let undo = chunks.takeUndoLog() { onUndo?(undo) } }let headerVMA = try headerVMA(of: chunks)let header = try readHeader(from: chunks, at: headerVMA, chunkName: mainChunkName)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheXPCLWCRPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheXPCLWCRPatcher.swiftindex f864f014..fd633d52 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheXPCLWCRPatcher.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheXPCLWCRPatcher.swift@@ -116,9 +116,12 @@ public enum DyldSharedCacheXPCLWCRPatcher {public static func apply(directory: URL,dryRun: Bool = false,+ captureUndo: Bool = false,+ onUndo: ((DyldSharedCacheUndoLog) -> Void)? = nil,log: ((String) -> Void)? = DyldSharedCacheCodeSignature.stderrLog,) throws -> Outcome {- let chunks = try DyldSharedCacheChunkSet(directory: directory)+ let chunks = try DyldSharedCacheChunkSet(directory: directory, captureUndo: captureUndo)+ defer { if captureUndo, let undo = chunks.takeUndoLog() { onUndo?(undo) } }return try apply(chunks: chunks, dryRun: dryRun, log: log)}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swiftnew file mode 100644index 00000000..e090fdbf--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift@@ -0,0 +1,55 @@+// FirmwareGuestPatchResolution.swift — Which guest patches an installed VM should run now.+//+// A VM carries two patch records the guest half of an install reads: the plan+// `fw patch` resolved, and the selection its owner has since edited. They can+// disagree, and which one wins depends on where a patch lands.+//+// A boot-chain patch was built into the restore tree or `FirmwareOriginals` the+// moment `fw patch` ran; the bytes are already in those files, so the plan is+// the truth for them and the current selection cannot change them without+// another `fw patch`. A guest patch is different: nothing writes it until the+// guest half of an install runs, and that half runs every `cfw install` and+// `cfw update-environment`. So a guest patch should follow the current+// selection, which is both what lets `fw set-patches` then `cfw+// update-environment` turn one on and what lets it turn one off.+//+// `VPhoneCustomFirmwareInstaller.withLateGuestPatches` used to do a narrow+// version of this — it merged in a short list of guest patches newer than most+// VMs' plans, and only ever added. This resolves the whole guest half from the+// selection, both directions, and the installer's late-patch list is gone.++import Foundation+import VPhonePatchKit++public enum FirmwareGuestPatchResolution {+ /// Every bundled-set patch whose bytes the guest half of an install writes —+ /// the dyld shared cache, a guest Mach-O, its entitlements, a guest file, or+ /// the Preboot device tree. The complement is the boot chain, which `fw+ /// patch` owns.+ public static var guestTargetIdentifiers: Set<String> {+ Set(+ FirmwarePatchSetCatalog.allDeclarations+ .filter { !$0.target.isBootChain }+ .map(\.identifier),+ )+ }++ /// The identifiers the guest half should apply now: boot-chain patches as+ /// the plan resolved them, guest patches as the current selection resolves+ /// them. A guest patch the plan had on but the selection now blocks drops+ /// out; one the plan never had but the selection now allows comes in.+ public static func effectiveEnabled(+ planEnabled: Set<String>,+ selectionEnabled: Set<String>,+ ) -> Set<String> {+ let guest = guestTargetIdentifiers+ return planEnabled.subtracting(guest).union(selectionEnabled.intersection(guest))+ }++ /// The guest patches a selection leaves off — the ones a run should try to+ /// revert. Boot-chain patches are never here: this is only about the guest+ /// half.+ public static func guestPatchesOff(selectionEnabled: Set<String>) -> Set<String> {+ guestTargetIdentifiers.subtracting(selectionEnabled)+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchDrift.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchDrift.swiftnew file mode 100644index 00000000..084978f8--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchDrift.swift@@ -0,0 +1,164 @@+// FirmwarePatchDrift.swift — Where a VM's patches stand, and what a change still needs.+//+// A VM carries three patch records: the selection (what the owner wants), the+// plan (what the last `fw patch` built) and the receipt (what is live in the+// guest, part by part). This file compares them. It reads no file and writes+// none: `fw patches`, `fw set-patches` and `restore` hand it the records they+// already loaded, so the comparison is one pure rule the tests can pin.+//+// Parts are named by the caller's rule (`VPhoneVirtualMachinePatchReceipt.part(for:)`+// in `vphone-cli`), passed in as a closure so the receipt stays the one place+// that spells a part key.++import Foundation+import VPhonePatchKit++// MARK: - Delivery++/// The step that carries a change to one patch into a guest that is already+/// installed. Which one depends only on where the patch lands.+public enum FirmwarePatchDelivery: String, Sendable, Hashable, CaseIterable, Codable {+ /// AVPBooter sits in the VM folder and is read at every boot, so+ /// `fw patch` alone delivers it. `fw patch` still needs the VM's restore+ /// tree, which is kept only with `--keep-artifacts`.+ case firmwarePatch = "fw-patch"+ /// iBSS and iBEC are used only while restoring, LLB lives in NOR, and+ /// kernelcache, TXM and DeviceTree are personalized into Preboot by the+ /// restore. Nothing else writes them.+ case restore+ /// Everything `cfw install` writes into the guest volumes.+ case updateEnvironment = "update-environment"++ public init(target: VPhonePatchTarget) {+ switch target {+ case .firmware(.avpBooter):+ self = .firmwarePatch+ case .firmware:+ // Every other boot-chain component, and the restore-only+ // Filesystem/Manifest.+ self = .restore+ case .dyldSharedCache, .guestExecutable, .guestEntitlements, .guestFile, .prebootDeviceTree:+ self = .updateEnvironment+ @unknown default:+ // A target this build does not know is written by the guest install.+ self = .updateEnvironment+ }+ }+}++// MARK: - Drift++public enum FirmwarePatchDrift {+ /// The boot-chain components a successful restore writes into the guest,+ /// in boot order. AVPBooter is not among them: it never leaves the VM+ /// folder, and `fw patch` records it itself.+ public static let restoredComponents: [VPhoneFirmwareComponent] = [+ .iBSS, .iBEC, .llb, .txm, .kernelcache, .deviceTree,+ ]++ /// What a restore put into each component it wrote: the plan's enabled+ /// patches that target that component.+ ///+ /// Every component in ``restoredComponents`` is present, empty when the plan+ /// turned all of its patches off, so a receipt records "nothing" rather than+ /// leaving the part unknown.+ public static func restoredParts(+ enabledPatches: Set<String>,+ declarations: [VPhonePatchDeclaration] = FirmwarePatchSetCatalog.allDeclarations,+ ) -> [VPhoneFirmwareComponent: [String]] {+ var result: [VPhoneFirmwareComponent: [String]] = [:]+ for component in restoredComponents {+ result[component] = declarations+ .filter { $0.target == .firmware(component) && enabledPatches.contains($0.identifier) }+ .map(\.identifier)+ .sorted()+ }+ return result+ }++ /// The patches the selection turns on that also pass their version gate.+ ///+ /// `selected` is the selection before any gate (a preset plus the VM's+ /// boxes). A patch pinned to another OS release is not wanted on this VM,+ /// however it was selected, so it never counts as drift. With neither+ /// version known there is nothing to gate against and the selection stands.+ public static func wantedPatches(+ selected: Set<String>,+ declarations: [VPhonePatchDeclaration],+ iOSBase: VPhoneVersion?,+ cloudOS: VPhoneVersion?,+ ) -> Set<String> {+ guard iOSBase != nil || cloudOS != nil else { return selected }+ return Set(declarations.lazy+ .filter { selected.contains($0.identifier) }+ .filter { $0.applicability.matches(iOSBase: iOSBase, cloudOS: cloudOS) }+ .map(\.identifier))+ }++ /// One patch, compared across the three records.+ public struct PatchState: Sendable, Hashable {+ public let identifier: String+ public let target: VPhonePatchTarget+ /// The receipt part the patch lives in.+ public let part: String+ /// Whether the current selection wants it, after the version gate.+ public let wanted: Bool+ /// Whether the last `fw patch` turned it on; nil with no plan.+ public let planned: Bool?+ /// Whether it is live in the guest; nil when the receipt does not+ /// record its part.+ public let applied: Bool?++ /// What the guest is believed to run: the receipt where it records the+ /// part, else the plan, which is what the next restore or install+ /// would write. Nil when neither says.+ public var reference: Bool? {+ applied ?? planned+ }++ /// Whether the wanted state still has to reach the guest. Nil when+ /// nothing records what the guest has.+ public var isPending: Bool? {+ reference.map { $0 != wanted }+ }++ public var delivery: FirmwarePatchDelivery {+ FirmwarePatchDelivery(target: target)+ }+ }++ /// Every declaration, compared.+ ///+ /// - Parameters:+ /// - wanted: ``wantedPatches(selected:declarations:iOSBase:cloudOS:)``.+ /// - planned: The plan's enabled patches, or nil with no plan.+ /// - applied: The receipt's patches by part, or nil with no receipt. A+ /// part missing from it leaves its patches' `applied` nil.+ /// - part: The receipt's rule for naming a target's part.+ public static func states(+ declarations: [VPhonePatchDeclaration],+ wanted: Set<String>,+ planned: Set<String>?,+ applied: [String: Set<String>]?,+ notApplicable: Set<String> = [],+ part: (VPhonePatchTarget) -> String,+ ) -> [PatchState] {+ declarations.map { declaration in+ let part = part(declaration.target)+ let isWanted = wanted.contains(declaration.identifier)+ // A patch the guest has nothing for reads as whatever is wanted,+ // so turning it on or off is never reported as pending.+ let isApplied = applied?[part].map {+ notApplicable.contains(declaration.identifier) ? isWanted : $0.contains(declaration.identifier)+ }+ return PatchState(+ identifier: declaration.identifier,+ target: declaration.target,+ part: part,+ wanted: isWanted,+ planned: planned.map { $0.contains(declaration.identifier) },+ applied: isApplied,+ )+ }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheUndoLogTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheUndoLogTests.swiftnew file mode 100644index 00000000..7a3ca93d--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheUndoLogTests.swift@@ -0,0 +1,212 @@+// DyldSharedCacheUndoLogTests.swift — The dyld-cache undo log, over a synthetic buffer.+//+// The undo log records the original bytes behind each cache edit so a later run+// can put them back for a patch turned off. These tests do not need the 6.7 GB+// cache: they build chunk-sized files in a temp directory, "patch" a range by+// writing over it while recording the original, then restore and assert the+// bytes are back. Idempotence — patching an already-patched range records+// nothing — is checked at the record level, which is where the live chunk set+// skips a no-op write.++@testable import FirmwarePatcher+import Foundation+import Testing++@Suite("Dyld shared cache undo log")+struct DyldSharedCacheUndoLogTests {+ /// A temp directory with one "chunk" file of known bytes, cleaned up after.+ private func withChunk(+ name: String = "dyld_shared_cache_arm64e",+ bytes: [UInt8],+ _ body: (URL, URL) throws -> Void,+ ) throws {+ let dir = URL(fileURLWithPath: NSTemporaryDirectory())+ .appendingPathComponent("undo-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: dir) }+ let chunk = dir.appendingPathComponent(name)+ try Data(bytes).write(to: chunk)+ try body(dir, chunk)+ }++ /// Overwrite `[offset, offset+patched.count)` and return the original bytes.+ private func overwrite(_ url: URL, offset: Int, patched: [UInt8]) throws -> Data {+ let handle = try FileHandle(forUpdating: url)+ defer { try? handle.close() }+ try handle.seek(toOffset: UInt64(offset))+ let original = try handle.read(upToCount: patched.count) ?? Data()+ try handle.seek(toOffset: UInt64(offset))+ try handle.write(contentsOf: Data(patched))+ return original+ }++ @Test+ func `Restore puts the original bytes back for the named patch`() throws {+ try withChunk(bytes: Array(0 ..< 64)) { dir, chunk in+ let original = try overwrite(chunk, offset: 16, patched: [0xAA, 0xBB, 0xCC, 0xDD])++ var log = DyldSharedCacheUndoLog()+ log.capture(chunk: chunk.lastPathComponent, fileOffset: 16, vma: 0x1_0000, original: original)+ log.stamp(patchID: "dyld-boot-example")++ // The range reads as the patched bytes before the revert.+ #expect(try Data(contentsOf: chunk)[16 ..< 20] == Data([0xAA, 0xBB, 0xCC, 0xDD]))++ let spans = try log.restore(patchIDs: ["dyld-boot-example"], in: dir)+ #expect(spans.count == 1)+ #expect(spans.first?.vma == 0x1_0000)+ #expect(spans.first?.length == 4)++ // And the original 16,17,18,19 are back.+ #expect(try Data(contentsOf: chunk)[16 ..< 20] == Data([16, 17, 18, 19]))+ }+ }++ @Test+ func `Restore touches only the named patch`() throws {+ try withChunk(bytes: Array(repeating: 0, count: 64)) { dir, chunk in+ let a = try overwrite(chunk, offset: 0, patched: [1, 1, 1, 1])+ let b = try overwrite(chunk, offset: 32, patched: [2, 2, 2, 2])+ var log = DyldSharedCacheUndoLog()+ log.capture(chunk: chunk.lastPathComponent, fileOffset: 0, vma: 0x1000, original: a)+ log.stamp(patchID: "patch-a")+ var logB = DyldSharedCacheUndoLog()+ logB.capture(chunk: chunk.lastPathComponent, fileOffset: 32, vma: 0x2000, original: b)+ logB.stamp(patchID: "patch-b")+ log.merge(logB)++ try log.restore(patchIDs: ["patch-a"], in: dir)+ let data = try Data(contentsOf: chunk)+ #expect(data[0 ..< 4] == Data([0, 0, 0, 0]), "patch-a reverted")+ #expect(data[32 ..< 36] == Data([2, 2, 2, 2]), "patch-b untouched")++ #expect(log.patchIDs == ["patch-a", "patch-b"])+ #expect(log.removing(patchIDs: ["patch-a"]).patchIDs == ["patch-b"])+ }+ }++ @Test+ func `Restore is idempotent`() throws {+ try withChunk(bytes: Array(0 ..< 32)) { dir, chunk in+ let original = try overwrite(chunk, offset: 8, patched: [0xFF, 0xFF])+ var log = DyldSharedCacheUndoLog()+ log.capture(chunk: chunk.lastPathComponent, fileOffset: 8, vma: 0x4000, original: original)+ log.stamp(patchID: "p")++ try log.restore(patchIDs: ["p"], in: dir)+ let afterFirst = try Data(contentsOf: chunk)+ try log.restore(patchIDs: ["p"], in: dir)+ let afterSecond = try Data(contentsOf: chunk)+ #expect(afterFirst == afterSecond)+ #expect(afterFirst[8 ..< 10] == Data([8, 9]))+ }+ }++ @Test+ func `A plist round-trips through encode and decode`() throws {+ var log = DyldSharedCacheUndoLog()+ log.capture(chunk: "dyld_shared_cache_arm64e.01", fileOffset: 0x2000, vma: 0x1_8000, original: Data([1, 2, 3, 4, 5]))+ log.stamp(patchID: "dyld-cfw-camera")+ let decoded = try DyldSharedCacheUndoLog.decode(log.encoded())+ #expect(decoded == log)+ #expect(decoded.records.first?.original == Data([1, 2, 3, 4, 5]))+ #expect(decoded.records.first?.patchID == "dyld-cfw-camera")+ }++ @Test+ func `Stamp only fills records that have no identifier yet`() {+ var log = DyldSharedCacheUndoLog()+ log.capture(chunk: "c", fileOffset: 0, vma: 0, original: Data([0]))+ log.stamp(patchID: "first")+ log.capture(chunk: "c", fileOffset: 1, vma: 1, original: Data([1]))+ log.stamp(patchID: "second")+ #expect(log.records(forPatchIDs: ["first"]).count == 1)+ #expect(log.records(forPatchIDs: ["second"]).count == 1)+ }++ @Test+ func `A chunk name with a path separator is refused`() throws {+ try withChunk(bytes: [0, 0, 0, 0]) { dir, _ in+ var log = DyldSharedCacheUndoLog()+ log.capture(chunk: "../escape", fileOffset: 0, vma: 0, original: Data([9]))+ log.stamp(patchID: "p")+ #expect(throws: DyldSharedCacheError.self) {+ try log.restore(patchIDs: ["p"], in: dir)+ }+ }+ }++ // MARK: - updated (the merge rule a re-run uses)++ @Test+ func `An empty capture keeps the stored records for the patch`() {+ var existing = DyldSharedCacheUndoLog()+ existing.capture(chunk: "c", fileOffset: 0, vma: 0x1000, original: Data([1, 2]))+ existing.stamp(patchID: "p")+ // An idempotent re-run captured nothing: the log must be left as it is,+ // not emptied — nil means "do not write".+ let updated = DyldSharedCacheUndoLog.updated(existing: existing, captured: DyldSharedCacheUndoLog(), patchID: "p")+ #expect(updated == nil)+ }++ @Test+ func `A capture of new sites merges without dropping the old`() {+ var existing = DyldSharedCacheUndoLog()+ existing.capture(chunk: "c", fileOffset: 0, vma: 0x1000, original: Data([1]))+ existing.stamp(patchID: "p")+ var captured = DyldSharedCacheUndoLog()+ captured.capture(chunk: "c", fileOffset: 16, vma: 0x1010, original: Data([2]))+ let updated = DyldSharedCacheUndoLog.updated(existing: existing, captured: captured, patchID: "p")+ #expect(updated?.records.count == 2)+ #expect(updated?.records(forPatchIDs: ["p"]).count == 2)+ }++ @Test+ func `A re-capture of a known site keeps the earliest original`() {+ var existing = DyldSharedCacheUndoLog()+ existing.capture(chunk: "c", fileOffset: 8, vma: 0x2000, original: Data([0xAA]))+ existing.stamp(patchID: "p")+ var captured = DyldSharedCacheUndoLog()+ // Same (chunk, offset) as the stored record: the earlier original wins.+ captured.capture(chunk: "c", fileOffset: 8, vma: 0x2000, original: Data([0xBB]))+ let updated = DyldSharedCacheUndoLog.updated(existing: existing, captured: captured, patchID: "p")+ #expect(updated?.records.count == 1)+ #expect(updated?.records.first?.original == Data([0xAA]))+ }++ // MARK: - validate (item 9)++ @Test+ func `Validate refuses a record that runs past the chunk`() throws {+ try withChunk(bytes: Array(repeating: 0, count: 16)) { dir, chunk in+ var log = DyldSharedCacheUndoLog()+ log.capture(chunk: chunk.lastPathComponent, fileOffset: 12, vma: 0, original: Data([1, 2, 3, 4, 5, 6, 7, 8]))+ log.stamp(patchID: "p")+ #expect(throws: DyldSharedCacheError.self) {+ try log.validate(in: dir)+ }+ }+ }++ @Test+ func `Validate refuses a chunk that is not a file beside the cache`() throws {+ try withChunk(bytes: [0, 0, 0, 0]) { dir, _ in+ var log = DyldSharedCacheUndoLog()+ log.capture(chunk: "does_not_exist", fileOffset: 0, vma: 0, original: Data([1]))+ log.stamp(patchID: "p")+ #expect(throws: DyldSharedCacheError.self) {+ try log.validate(in: dir)+ }+ }+ }++ @Test+ func `Validate accepts a record that fits`() throws {+ try withChunk(bytes: Array(0 ..< 32)) { dir, chunk in+ var log = DyldSharedCacheUndoLog()+ log.capture(chunk: chunk.lastPathComponent, fileOffset: 28, vma: 0, original: Data([1, 2, 3, 4]))+ log.stamp(patchID: "p")+ try log.validate(in: dir) // does not throw+ }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swiftnew file mode 100644index 00000000..8b7572c1--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift@@ -0,0 +1,104 @@+// FirmwareGuestPatchResolutionTests.swift — The guest-half selection resolver.+//+// `FirmwareGuestPatchResolution` decides which patches the guest half of an+// install applies now: the boot chain as the plan recorded it, the guest half+// as the current selection resolves it. These tests pin that split and the+// membership of the guest-target set against the real bundled catalogue.++import FirmwarePatcher+import Foundation+import Testing+import VPhonePatchKit++@Suite("Guest patch resolution")+struct FirmwareGuestPatchResolutionTests {+ @Test+ func `Guest target identifiers include the guest patches and exclude the boot chain`() {+ let guest = FirmwareGuestPatchResolution.guestTargetIdentifiers++ // A dyld-cache patch, a guest Mach-O, a guest file, and a Preboot+ // device-tree patch are all guest-half.+ #expect(guest.contains("dyld-boot-lockdown_mode"))+ #expect(guest.contains("system-seputil-boot-gigalocker_uuid"))+ #expect(guest.contains("system-vphoned-boot-install"))+ #expect(guest.contains(FirmwareGuestSystemPatchSet.prebootHaptics))+ #expect(guest.contains(FirmwareGuestIdentityPatchSet.prebootDeviceTreeIdentity))++ // Every boot-chain patch is excluded: those are `fw patch`'s, not the+ // guest half's.+ for declaration in FirmwarePatchSetCatalog.allDeclarations where declaration.target.isBootChain {+ #expect(!guest.contains(declaration.identifier), "\(declaration.identifier) is boot-chain")+ }++ // And the set is exactly the non-boot-chain declarations.+ let expected = Set(+ FirmwarePatchSetCatalog.allDeclarations+ .filter { !$0.target.isBootChain }+ .map(\.identifier),+ )+ #expect(guest == expected)+ }++ @Test+ func `Effective enabled keeps boot chain from the plan and guest half from the selection`() {+ let guest = FirmwareGuestPatchResolution.guestTargetIdentifiers+ let bootChain = Set(+ FirmwarePatchSetCatalog.allDeclarations+ .filter { $0.target.isBootChain }+ .map(\.identifier),+ )+ guard+ let boot = bootChain.first,+ let guestOn = guest.first,+ let guestOff = guest.dropFirst().first+ else {+ Issue.record("the bundled catalogue has too few patches to exercise the split")+ return+ }++ // The plan had a boot patch and one guest patch on; the selection now+ // has a *different* guest patch on and the old one off.+ let planEnabled: Set<String> = [boot, guestOn]+ let selectionEnabled: Set<String> = [guestOff]++ let effective = FirmwareGuestPatchResolution.effectiveEnabled(+ planEnabled: planEnabled,+ selectionEnabled: selectionEnabled,+ )++ #expect(effective.contains(boot), "the boot patch stays from the plan")+ #expect(effective.contains(guestOff), "a guest patch the selection turned on comes in")+ #expect(!effective.contains(guestOn), "a guest patch the selection turned off drops out")+ }++ @Test+ func `A boot-chain selection cannot add or drop guest patches`() {+ let guest = FirmwareGuestPatchResolution.guestTargetIdentifiers+ guard let guestID = guest.first else {+ Issue.record("no guest patches in the catalogue")+ return+ }+ // The selection resolves the guest patch off but names a boot patch the+ // plan never had: the boot side is the plan's alone, so nothing from the+ // selection's boot choices leaks in.+ let planEnabled: Set<String> = [guestID]+ let selectionEnabled: Set<String> = []+ let effective = FirmwareGuestPatchResolution.effectiveEnabled(+ planEnabled: planEnabled,+ selectionEnabled: selectionEnabled,+ )+ #expect(effective.isEmpty, "the guest patch drops and no boot patch is invented")+ }++ @Test+ func `Guest patches off is the guest set minus the selection`() {+ let guest = FirmwareGuestPatchResolution.guestTargetIdentifiers+ guard let on = guest.first else {+ Issue.record("no guest patches in the catalogue")+ return+ }+ let off = FirmwareGuestPatchResolution.guestPatchesOff(selectionEnabled: [on])+ #expect(!off.contains(on))+ #expect(off == guest.subtracting([on]))+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchDriftTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchDriftTests.swiftnew file mode 100644index 00000000..c5d4abe0--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchDriftTests.swift@@ -0,0 +1,200 @@+// FirmwarePatchDriftTests.swift — What a restore records, and what a change still needs.+//+// `FirmwarePatchDrift` is the rule `restore`, `fw patches` and `fw set-patches`+// share. These pin it on small hand-made declarations, plus the bundled+// catalogue where the rule depends on what ships.++import FirmwarePatcher+import Foundation+import Testing+import VPhonePatchKit++@Suite("Patch drift")+struct FirmwarePatchDriftTests {+ private func patch(+ _ identifier: String,+ _ target: VPhonePatchTarget,+ applicability: VPhonePatchApplicability = .always,+ ) -> VPhonePatchDeclaration {+ VPhonePatchDeclaration(identifier: identifier, title: identifier, target: target, applicability: applicability)+ }++ /// The receipt's part rule, restated so the tests do not reach into the CLI.+ private func part(_ target: VPhonePatchTarget) -> String {+ if case let .firmware(component) = target {+ return component.rawValue+ }+ return "Guest"+ }++ private var declarations: [VPhonePatchDeclaration] {+ [+ patch("avp", .firmware(.avpBooter)),+ patch("ibss", .firmware(.iBSS)),+ patch("llb", .firmware(.llb)),+ patch("kernel-a", .firmware(.kernelcache)),+ patch("kernel-b", .firmware(.kernelcache)),+ patch("txm", .firmware(.txm)),+ patch("dyld", .dyldSharedCache),+ patch("dt", .prebootDeviceTree),+ ]+ }++ // MARK: - Restore++ @Test+ func `A restore records every component it flashes, empty ones included`() {+ let parts = FirmwarePatchDrift.restoredParts(+ enabledPatches: ["avp", "ibss", "kernel-b", "kernel-a", "dyld"],+ declarations: declarations,+ )+ #expect(Set(parts.keys) == [.iBSS, .iBEC, .llb, .txm, .kernelcache, .deviceTree])+ #expect(parts[.iBSS] == ["ibss"])+ #expect(parts[.kernelcache] == ["kernel-a", "kernel-b"])+ // Off in the plan, or declaring nothing: recorded empty, not unknown.+ #expect(parts[.llb] == [])+ #expect(parts[.iBEC] == [])+ #expect(parts[.deviceTree] == [])+ // AVPBooter never leaves the VM folder, and guest patches are written+ // by cfw install, not by a restore.+ #expect(parts[.avpBooter] == nil)+ #expect(!parts.values.contains { $0.contains("dyld") })+ }++ @Test+ func `A restore of the bundled catalogue records only boot-chain patches`() {+ let everything = Set(FirmwarePatchSetCatalog.allDeclarations.map(\.identifier))+ let parts = FirmwarePatchDrift.restoredParts(enabledPatches: everything)+ let recorded = parts.values.flatMap(\.self)+ for identifier in recorded {+ let declaration = FirmwarePatchSetCatalog.allDeclarations.first { $0.identifier == identifier }+ guard case let .firmware(component)? = declaration?.target else {+ Issue.record("\(identifier) is not a boot-chain patch")+ continue+ }+ #expect(FirmwarePatchDrift.restoredComponents.contains(component))+ }+ #expect(parts[.kernelcache]?.isEmpty == false)+ }++ // MARK: - Wanted++ @Test+ func `A patch pinned to another release is not wanted, however it was selected`() {+ let gated = [+ patch("any", .firmware(.kernelcache)),+ patch("only27", .firmware(.kernelcache), applicability: VPhonePatchApplicability(iOSBase: .major(27))),+ ]+ let on26 = FirmwarePatchDrift.wantedPatches(+ selected: ["any", "only27"],+ declarations: gated,+ iOSBase: VPhoneVersion("26.4"),+ cloudOS: VPhoneVersion("26.4"),+ )+ #expect(on26 == ["any"])+ let on27 = FirmwarePatchDrift.wantedPatches(+ selected: ["any", "only27"],+ declarations: gated,+ iOSBase: VPhoneVersion("27.0"),+ cloudOS: VPhoneVersion("26.4"),+ )+ #expect(on27 == ["any", "only27"])+ // With no version known there is nothing to gate against.+ let unknown = FirmwarePatchDrift.wantedPatches(+ selected: ["only27"],+ declarations: gated,+ iOSBase: nil,+ cloudOS: nil,+ )+ #expect(unknown == ["only27"])+ }++ // MARK: - States++ private func states(+ wanted: Set<String>,+ planned: Set<String>?,+ applied: [String: Set<String>]?,+ notApplicable: Set<String> = [],+ ) -> [String: FirmwarePatchDrift.PatchState] {+ let list = FirmwarePatchDrift.states(+ declarations: declarations,+ wanted: wanted,+ planned: planned,+ applied: applied,+ notApplicable: notApplicable,+ part: part,+ )+ return Dictionary(uniqueKeysWithValues: list.map { ($0.identifier, $0) })+ }++ @Test+ func `No plan and no receipt leaves every patch unknown`() {+ let result = states(wanted: ["kernel-a"], planned: nil, applied: nil)+ #expect(result.values.allSatisfy { $0.planned == nil && $0.applied == nil && $0.isPending == nil })+ }++ @Test+ func `The receipt decides where it records the part, and the plan stands in elsewhere`() {+ let result = states(+ wanted: ["avp", "kernel-a", "dyld"],+ planned: ["avp", "kernel-a", "kernel-b", "dyld", "dt"],+ applied: ["kernelcache": ["kernel-a", "kernel-b"], "AVPBooter": ["avp"]],+ )+ // kernel-b was turned off after the restore put it in.+ #expect(result["kernel-b"]?.applied == true)+ #expect(result["kernel-b"]?.isPending == true)+ #expect(result["kernel-b"]?.delivery == .restore)+ #expect(result["kernel-a"]?.isPending == false)+ #expect(result["avp"]?.isPending == false)+ // No Guest part in the receipt: the plan says what the install wrote.+ #expect(result["dt"]?.applied == nil)+ #expect(result["dt"]?.planned == true)+ #expect(result["dt"]?.isPending == true)+ #expect(result["dt"]?.delivery == .updateEnvironment)+ #expect(result["dyld"]?.isPending == false)+ }++ @Test+ func `A patch the guest has nothing for is never pending, on or off`() {+ let on = states(wanted: ["dt"], planned: ["dt"], applied: ["Guest": []], notApplicable: ["dt"])+ #expect(on["dt"]?.isPending == false)+ let off = states(wanted: [], planned: ["dt"], applied: ["Guest": []], notApplicable: ["dt"])+ #expect(off["dt"]?.isPending == false)+ // With no Guest part recorded, the plan still decides.+ let unknown = states(wanted: ["dt"], planned: [], applied: [:], notApplicable: ["dt"])+ #expect(unknown["dt"]?.isPending == true)+ }++ @Test+ func `A part recorded empty means off, not unknown`() {+ let result = states(+ wanted: ["llb"],+ planned: ["llb"],+ applied: ["LLB": []],+ )+ #expect(result["llb"]?.applied == false)+ #expect(result["llb"]?.isPending == true)+ #expect(result["llb"]?.delivery == .restore)+ }++ // MARK: - Delivery++ @Test+ func `Each target is delivered by the step that owns its bytes`() {+ #expect(FirmwarePatchDelivery(target: .firmware(.avpBooter)) == .firmwarePatch)+ for component in [VPhoneFirmwareComponent.iBSS, .iBEC, .llb, .txm, .kernelcache, .deviceTree] {+ #expect(FirmwarePatchDelivery(target: .firmware(component)) == .restore)+ }+ let guest: [VPhonePatchTarget] = [+ .dyldSharedCache,+ .guestExecutable(path: "/usr/libexec/x"),+ .guestEntitlements(path: "/usr/libexec/x"),+ .guestFile(path: "/etc/x"),+ .prebootDeviceTree,+ ]+ for target in guest {+ #expect(FirmwarePatchDelivery(target: target) == .updateEnvironment)+ }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swiftindex 2f9139b2..04b9f22d 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift@@ -21,10 +21,58 @@ import ArgumentParserimport FirmwarePatcherimport Foundation+/// The optional undo-log flags every cache patch verb carries.+///+/// When `cfw install` runs a cache verb it passes `--undo-log <path>` and+/// `--undo-id <patch identifier>`: the verb captures the original bytes of+/// every write and appends them, tagged with the identifier, to the log at that+/// path. A later `cfw update-environment` reads the same log and, for a patch+/// the VM has since turned off, puts those bytes back. Nothing a researcher runs+/// by hand passes these, so capture stays off by default and the verbs write+/// exactly what they wrote before.+struct DyldSharedCacheUndoOptions: ParsableArguments {+ @Option(name: .customLong("undo-log"), help: "Record original bytes to this log for later revert")+ var undoLog: String?++ @Option(name: .customLong("undo-id"), help: "Patch identifier to tag the recorded bytes with")+ var undoID: String?++ var captures: Bool { undoLog != nil }++ /// Fold this verb's captured runs into the log file beside the cache.+ ///+ /// A run that captured nothing — an idempotent re-patch over already-written+ /// sites, a self-gated no-op, or a dry run — leaves the log exactly as it is,+ /// so the originals an earlier run recorded for this patch are kept (see+ /// ``DyldSharedCacheUndoLog/updated(existing:captured:patchID:)``). A dry run+ /// never writes. The log is given the owner and mode of the cache's own main+ /// chunk, not 0777: it lives inside the guest System volume, whose modes+ /// stay unchanged (AGENTS.md).+ func persist(_ captured: DyldSharedCacheUndoLog, dryRun: Bool) throws {+ guard let undoLog, captures, !dryRun else { return }+ let url = URL(fileURLWithPath: undoLog)+ let existing = (try? Data(contentsOf: url)).flatMap { try? DyldSharedCacheUndoLog.decode($0) }+ guard let merged = DyldSharedCacheUndoLog.updated(+ existing: existing, captured: captured, patchID: undoID ?? "",+ ) else { return }+ try merged.encoded().write(to: url, options: .atomic)+ // Match the cache chunk's owner and mode rather than widening it: the+ // directory name is the cache directory, so its main chunk is the+ // reference for what a file here should be owned and permissioned as.+ let mainChunk = url.deletingLastPathComponent().appendingPathComponent("dyld_shared_cache_arm64e")+ var metadata = stat()+ if lstat(mainChunk.path, &metadata) == 0 {+ chmod(url.path, metadata.st_mode & 0o7777)+ chown(url.path, metadata.st_uid, metadata.st_gid)+ }+ }+}+enum VPhoneCustomFirmwareDyldSharedCacheVerbs {/// Registered into `vphone-cli cfw` by `VPhoneCustomFirmwareCommand`.static var all: [ParsableCommand.Type] {[+ VPhoneCustomFirmwareDyldSharedCacheRevertCommand.self,VPhoneCustomFirmwarePatchHypervisorVirtualMachineDyldSharedCacheCommand.self,VPhoneCustomFirmwarePatchIOMFBSwapEndCommand.self,VPhoneCustomFirmwarePatchIOMFBForceKernCommand.self,@@ -103,12 +151,18 @@ struct VPhoneCustomFirmwarePatchHypervisorVirtualMachineDyldSharedCacheCommand:@Flag(name: .customLong("dry-run"), help: "Report every site and write nothing")var dryRun = false+ @OptionGroup var undo: DyldSharedCacheUndoOptions+func run() throws {+ var captured = DyldSharedCacheUndoLog()try DyldSharedCacheHypervisorVirtualMachinePatcher.patch(chunksDirectory: chunksDirectory,dryRun: dryRun,+ captureUndo: undo.captures,+ onUndo: { captured.merge($0) },log: VPhoneCustomFirmwareDyldSharedCacheVerbs.stdout,)+ try undo.persist(captured, dryRun: dryRun)}}@@ -155,13 +209,19 @@ struct VPhoneCustomFirmwarePatchIOMFBSwapEndCommand: ParsableCommand {@Flag(name: .customLong("dry-run"), help: "Report the site and the rewrite, and write nothing")var dryRun = false+ @OptionGroup var undo: DyldSharedCacheUndoOptions+func run() throws {+ var captured = DyldSharedCacheUndoLog()try DyldSharedCacheIOMFBSwapEndPatcher.patch(chunksDirectory: chunksDirectory,targetSize: targetSize,dryRun: dryRun,+ captureUndo: undo.captures,+ onUndo: { captured.merge($0) },log: VPhoneCustomFirmwareDyldSharedCacheVerbs.stdout,)+ try undo.persist(captured, dryRun: dryRun)}}@@ -203,12 +263,18 @@ struct VPhoneCustomFirmwarePatchIOMFBForceKernCommand: ParsableCommand {@Flag(name: .customLong("dry-run"), help: "Report every entry point and write nothing")var dryRun = false+ @OptionGroup var undo: DyldSharedCacheUndoOptions+func run() throws {+ var captured = DyldSharedCacheUndoLog()try DyldSharedCacheIOMFBForceKernPatcher.patch(chunksDirectory: chunksDirectory,dryRun: dryRun,+ captureUndo: undo.captures,+ onUndo: { captured.merge($0) },log: VPhoneCustomFirmwareDyldSharedCacheVerbs.stdout,)+ try undo.persist(captured, dryRun: dryRun)}}@@ -250,12 +316,18 @@ struct VPhoneCustomFirmwarePatchDyldSharedCacheMaxSlideCommand: ParsableCommand@Flag(name: .customLong("force"), help: "Zero maxSlide even when the cache already fits")var force = false+ @OptionGroup var undo: DyldSharedCacheUndoOptions+func run() throws {+ var captured = DyldSharedCacheUndoLog()try DyldSharedCacheMaxSlidePatcher.patch(chunksDirectory: chunksDirectory,dryRun: dryRun,force: force,+ captureUndo: undo.captures,+ onUndo: { captured.merge($0) },)+ try undo.persist(captured, dryRun: dryRun)}}@@ -294,12 +366,18 @@ struct VPhoneCustomFirmwarePatchLSDEmbeddedRegCommand: ParsableCommand {@Flag(name: .customLong("dry-run"), help: "Report the gate and write nothing")var dryRun = false+ @OptionGroup var undo: DyldSharedCacheUndoOptions+func run() throws {+ var captured = DyldSharedCacheUndoLog()try DyldSharedCacheLSDEmbeddedRegPatcher.patch(chunksDirectory: chunksDirectory,dryRun: dryRun,+ captureUndo: undo.captures,+ onUndo: { captured.merge($0) },log: VPhoneCustomFirmwareDyldSharedCacheVerbs.stdout,)+ try undo.persist(captured, dryRun: dryRun)}}@@ -341,12 +419,18 @@ struct VPhoneCustomFirmwarePatchMISTrustAuthCommand: ParsableCommand {@Flag(name: .customLong("dry-run"), help: "Report the site and write nothing")var dryRun = false+ @OptionGroup var undo: DyldSharedCacheUndoOptions+func run() throws {+ var captured = DyldSharedCacheUndoLog()try DyldSharedCacheMISTrustAuthPatcher.patch(chunksDirectory: chunksDirectory,dryRun: dryRun,+ captureUndo: undo.captures,+ onUndo: { captured.merge($0) },log: VPhoneCustomFirmwareDyldSharedCacheVerbs.stdout,)+ try undo.persist(captured, dryRun: dryRun)}}@@ -383,12 +467,18 @@ struct VPhoneCustomFirmwarePatchXPCLWCRCommand: ParsableCommand {@Flag(name: .customLong("dry-run"), help: "Report the three sites and write nothing")var dryRun = false+ @OptionGroup var undo: DyldSharedCacheUndoOptions+func run() throws {+ var captured = DyldSharedCacheUndoLog()try DyldSharedCacheXPCLWCRPatcher.apply(directory: chunksDirectory,dryRun: dryRun,+ captureUndo: undo.captures,+ onUndo: { captured.merge($0) },log: VPhoneCustomFirmwareDyldSharedCacheVerbs.stdout,)+ try undo.persist(captured, dryRun: dryRun)}}@@ -423,12 +513,18 @@ struct VPhoneCustomFirmwarePatchLockdownModeCommand: ParsableCommand {@Flag(name: .customLong("dry-run"), help: "Report the gate and write nothing")var dryRun = false+ @OptionGroup var undo: DyldSharedCacheUndoOptions+func run() throws {+ var captured = DyldSharedCacheUndoLog()try DyldSharedCacheLockdownModePatcher.patch(chunksDirectory: chunksDirectory,dryRun: dryRun,+ captureUndo: undo.captures,+ onUndo: { captured.merge($0) },log: VPhoneCustomFirmwareDyldSharedCacheVerbs.stdout,)+ try undo.persist(captured, dryRun: dryRun)}}@@ -476,13 +572,97 @@ struct VPhoneCustomFirmwarePatchCameraDyldSharedCacheCommand: ParsableCommand {@Flag(name: .customLong("force"), help: "Patch an entry point whose prologue is not the expected one")var force = false+ @OptionGroup var undo: DyldSharedCacheUndoOptions+func run() throws {+ var captured = DyldSharedCacheUndoLog()try DyldSharedCacheCameraPatcher.applyAll(chunksDirectory: chunksDirectory,symbolCacheURL: dscHeader,dryRun: dryRun,force: force,+ captureUndo: undo.captures,+ onUndo: { captured.merge($0) },+ log: VPhoneCustomFirmwareDyldSharedCacheVerbs.stdout,+ )+ try undo.persist(captured, dryRun: dryRun)+ }+}++// MARK: - dsc-revert++/// Put the pristine bytes back for cache patches a VM has turned off.+///+/// The inverse of the `--undo-log` the patch verbs write. Given the undo log+/// and the identifiers no longer selected, it restores each recorded run and+/// re-attests the pages they land in — which reproduces the original slot+/// hashes exactly when the page is now pristine and the correct ones when+/// another still-enabled patch shares the page. The log is rewritten without+/// the reverted identifiers, so a cache patch cannot be reverted twice and a+/// re-enable records its originals afresh.+///+/// `cfw install` and `cfw update-environment` invoke this; it is not a verb a+/// researcher reaches for by hand. A patch named here with no records in the+/// log is a cache patch that wrote nothing (an idempotent no-op), and reverting+/// it is correctly nothing.+struct VPhoneCustomFirmwareDyldSharedCacheRevertCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "patch-dsc-revert",+ abstract: "Restore pristine bytes for dyld-shared-cache patches that are now off",+ shouldDisplay: false,+ )++ @Argument(+ help: "The guest's /System/Library/Caches/com.apple.dyld directory",+ transform: URL.init(fileURLWithPath:),+ )+ var chunksDirectory: URL++ @Option(name: .customLong("undo-log"), help: "The undo log the patch verbs wrote")+ var undoLog: String++ @Option(name: .customLong("patch"), help: "A patch identifier to revert (repeatable)")+ var patches: [String] = []++ @Flag(name: .customLong("dry-run"), help: "Report what would be reverted and write nothing")+ var dryRun = false++ func run() throws {+ let url = URL(fileURLWithPath: undoLog)+ guard let data = try? Data(contentsOf: url) else {+ print(" [=] no dyld undo log at \(undoLog); nothing to revert")+ return+ }+ let log = try DyldSharedCacheUndoLog.decode(data)+ let wanted = Set(patches)+ let present = wanted.intersection(log.patchIDs)+ guard !present.isEmpty else {+ print(" [=] dyld undo log has no records for the patches to revert; nothing to do")+ return+ }+ if dryRun {+ for record in log.records(forPatchIDs: present) {+ print(" [.] dry-run: would restore \(record.original.count) byte(s) at 0x"+ + String(record.vma, radix: 16, uppercase: true) + " (\(record.patchID))")+ }+ return+ }+ let spans = try log.restore(+ patchIDs: present,+ in: chunksDirectory,log: VPhoneCustomFirmwareDyldSharedCacheVerbs.stdout,)+ if !spans.isEmpty {+ let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory)+ try DyldSharedCacheCodeSignature.reattest(+ in: chunks,+ modifiedSpans: spans,+ log: VPhoneCustomFirmwareDyldSharedCacheVerbs.stdout,+ )+ }+ let remaining = log.removing(patchIDs: present)+ try remaining.encoded().write(to: url, options: .atomic)+ try? FileManager.default.setAttributes([.posixPermissions: 0o777], ofItemAtPath: url.path)+ print(" [+] reverted \(present.count) dyld patch(es): \(present.sorted().joined(separator: ", "))")}}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex 39a99571..ad450e11 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -62,6 +62,18 @@ struct VPhoneCustomFirmwareInstaller {/// Guest system files belong to root:wheel.private static let guestOwner: (uid: uid_t, gid: gid_t) = (0, 0)+ /// The dyld shared cache directory on the guest system volume, and the undo+ /// log the cache verbs write beside it so a later run can revert a cache+ /// patch by putting its original bytes back. The log sits inside the cache+ /// directory because that is where the only cache it describes lives: on a+ /// full install Disk.img is cloned and the clone swapped in, so a log kept+ /// in the VM folder would describe the pre-clone cache, while one beside the+ /// cache travels with it. `verifiedDyldCacheDirectory` admits it — it is a+ /// plain single-link file, and `enumerateChunks` never mistakes a dotfile+ /// for a `dyld_shared_cache_arm64e*` chunk.+ private static let dscCacheRelative = "System/Cryptexes/OS/System/Library/Caches/com.apple.dyld"+ private static let dscUndoLogLeaf = ".vphone-dsc-undo.json"+/// Root-owned and sticky, outside every user's tree. The work folder is/// made here with `mkdtemp`, so its name cannot be predicted or claimed.private static let workParent = "/private/var/tmp"@@ -128,9 +140,28 @@ 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 = withLateGuestPatches(readPatchPlan(in: bundleDirectory), in: bundleDirectory)+ // Which guest patches to apply. The boot chain follows the plan `fw+ // patch` resolved; the guest half follows the VM's current selection,+ // both ways. Read through the pinned descriptor so root never follows a+ // link out of the bundle.+ let rawPlan = readPatchPlan(in: bundleDirectory)+ let plan = resolveGuestSelection(rawPlan, in: bundleDirectory)+ // What was live in the guest before this run, so a now-off patch this run+ // cannot revert (no backup, no undo record) stays honestly recorded.+ // The receipt's `Guest` part is the truth when it was recorded; without+ // it, the best evidence is what the old install followed — the plan's+ // guest-target patches plus the late guest patches the old+ // `withLateGuestPatches` added from the current selection. A VM that was+ // never installed has an empty prior set (its guest is pristine); that+ // is decided below, where the mounted volume says whether it was.+ let receiptGuest = (try? bundleDirectory.readData(VPhonePatchPresetStore.receiptFileName))+ .flatMap { try? VPhoneVirtualMachinePatchReceipt.decode($0) }?+ .parts[VPhoneVirtualMachinePatchReceipt.guestPart]+ .map { Set($0.patches) }+ let guestTargets = FirmwareGuestPatchResolution.guestTargetIdentifiers+ let effectiveEnabled = Set(plan?.enabledPatches ?? [])+ let priorFallback = Set(rawPlan?.enabledPatches ?? []).intersection(guestTargets)+ .union(Set(Self.lateGuestPatches).intersection(effectiveEnabled))let disk = try openDiskImage(in: bundleDirectory, path: bundlePath, owner: callerUID)let diskPath = (bundlePath as NSString).appendingPathComponent("Disk.img")let busy = try VPhoneProcessRunner.runCapturing(@@ -262,26 +293,56 @@ struct VPhoneCustomFirmwareInstaller {xartMounted = truetry mountGuestVolume("\(container)s3", at: xart)print("[*] \(mode.summary.capitalized): \(bundle.lastPathComponent)")+ // The identifiers whose bytes are live in the guest after this run, for+ // the receipt. Each step that applies or reverts a guest patch adds to+ // it, so what it holds at the end is exactly the `Guest` part.+ var liveGuest = Set<String>()+ // Resolved once the system volume is mounted (it needs the "was+ // installed" signal there), then used again by the Preboot pass.+ var priorGuest = Set<String>()do {// Every descriptor on a guest volume lives in this scope, so none// is left open to hold the volume busy when it is unmounted.let systemRoot = try openGuestVolume("system", device: "\(container)s1", in: work)let xartRoot = try openGuestVolume("xart", device: "\(container)s3", in: work)+ // `launchd.plist.bak` exists only after a full install's first+ // `installVphoned`, so it is the signal that the guest is not+ // pristine. A VM that was never installed has nothing applied, so+ // its prior set is empty whatever a stale plan might say.+ let wasInstalled = (try? systemRoot.exists("System/Library/xpc/launchd.plist.bak")) ?? false+ priorGuest = receiptGuest ?? (wasInstalled ? priorFallback : [])switch mode {case .full:guard let restore else {throw ValidationError("A full CFW install needs a prepared restore tree.")}- try installMounted(+ liveGuest = try applyGuestPatches(system: systemRoot,xart: xartRoot,restore: restore,work: work,owner: callerUID,plan: plan,+ priorGuest: priorGuest,+ environmentOnly: false,)case .environmentOnly:- try updateEnvironmentMounted(system: systemRoot, work: work, plan: plan)+ // Evidence a full install ran: nothing to update over otherwise.+ guard wasInstalled else {+ throw ValidationError(+ "This VM has no CFW install to update. Run `vphone-cli cfw install` first.",+ )+ }+ liveGuest = try applyGuestPatches(+ system: systemRoot,+ xart: nil,+ restore: nil,+ work: work,+ owner: nil,+ plan: plan,+ priorGuest: priorGuest,+ environmentOnly: true,+ )}}// The Preboot identity patches go with the boot chain and belong to a@@ -292,14 +353,32 @@ struct VPhoneCustomFirmwareInstaller {// the old tree on its Data volume, which the host cannot reach. vphoned// drops that cache at startup when it is older than the tree; see// VPhoneDaemon/Daemon/GuestMobileGestaltCache.swift.- try patchPreboot(+ let buildVersion = plan?.parameters[FirmwareGuestSystemPatchSet.buildVersionParameter] ?? spoofBuild+ let boardDeviceTree = try stageBoardDeviceTree(in: bundleDirectory, work: work)+ liveGuest.formUnion(try patchPreboot(volumes: volumes,work: work,plan: plan,+ priorGuest: priorGuest,guestDevice: guestDevice(of: restore),includeIdentity: mode == .full,- boardDeviceTree: stageBoardDeviceTree(in: bundleDirectory, work: work),- )+ buildVersion: buildVersion,+ boardDeviceTree: boardDeviceTree,+ ))+ // Selected patches this guest has nothing for, so the receipt does not+ // report them as missing forever: the board audio repair on an iPhone,+ // which has no board tree, and the build spoof with no value set. An+ // iPad whose board tree could not be recovered is not among them: its+ // repair is missing, and drift should keep saying so.+ var notApplicableGuest = Set<String>()+ let device = configuredGuestDevice(in: bundleDirectory) ?? guestDevice(of: restore)+ if !device.isPad {+ notApplicableGuest.insert(FirmwareGuestSystemPatchSet.prebootBoardAudio)+ }+ if buildVersion?.isEmpty ?? true {+ notApplicableGuest.insert("system-systemversion-cfw-build_version")+ }+ notApplicableGuest.subtract(liveGuest)// The snapshot rename is a full install's alone: it has already been// done on any VM an environment update is allowed to run against, and// this run creates no new snapshot to flip.@@ -328,6 +407,17 @@ struct VPhoneCustomFirmwareInstaller {work: work,owner: invokingUser.map { ($0.uid, $0.gid) },)+ // Record what is live in the guest now. Written through the pinned+ // bundle descriptor as the caller, 0777 like every other host VM+ // artifact, replacing only the `Guest` part so a boot-chain part a+ // restore or `fw patch` wrote stays. A failure here must not fail a+ // finished install: the guest already carries the bytes.+ recordGuestReceipt(+ live: liveGuest,+ notApplicable: notApplicableGuest,+ in: bundleDirectory,+ owner: invokingUser.map { ($0.uid, $0.gid) },+ )switch mode {case .full:print("[+] CFW system install complete; vphoned is installed, no package bootstrap was staged")@@ -336,118 +426,77 @@ struct VPhoneCustomFirmwareInstaller {}}- // MARK: - Environment update+ /// The verb to credit a receipt write to.+ private var receiptWriter: String {+ mode == .full ? "cfw install" : "cfw update-environment"+ }- /// Put this bundle's guest payload back over the copies a full install- /// already placed, and change nothing else.- ///- /// Every file written here is one `installVphoned` and `installEnvironment`- /// write during a full install, through the same confined descriptors, with- /// the same modes and owners. What is deliberately absent is everything- /// that makes a guest a CFW guest in the first place: no shared-cache or- /// Mach-O patch runs, no load command is injected, no cryptex or GPU work- /// happens, and the recorded variant is untouched.- ///- /// A missing target is left missing. The libraries are not all- /// unconditional — a VM whose plan left a patch out never received the- /// library that goes with it — and an update is not the place to add one.- ///- /// The virtio sound driver is the exception, and follows the plan instead:- /// it came after most VMs were installed, and this is the only route by- /// which a VM in use can receive it. The board audio repair that goes- /// with it touches the Preboot device tree, outside this function.- private func updateEnvironmentMounted(- system: VPhoneConfinedDirectory,- work: WorkDirectory,- plan: VPhoneVirtualMachinePatchPlan?,- ) throws {- // Evidence that a full install ran. `launchd.plist.bak` is written by- // the first `installVphoned` and by nothing else, so its absence means- // this guest has never been installed and there is nothing to update.- guard try system.exists("System/Library/xpc/launchd.plist.bak") else {- throw ValidationError(- "This VM has no CFW install to update. Run `vphone-cli cfw install` first.",+ /// Replace the receipt's `Guest` part with the identifiers live in the+ /// guest, keeping every other part. Read-modify-write through the pinned+ /// bundle descriptor so a planted link cannot redirect the write, and left+ /// 0777 and owned by the caller like Disk.img and the signed daemon copy.+ private func recordGuestReceipt(+ live: Set<String>,+ notApplicable: Set<String>,+ in bundleDirectory: VPhoneConfinedDirectory,+ owner: (uid: uid_t, gid: gid_t)?,+ ) {+ do {+ var receipt = (try? bundleDirectory.readData(VPhonePatchPresetStore.receiptFileName))+ .flatMap { try? VPhoneVirtualMachinePatchReceipt.decode($0) }+ ?? VPhoneVirtualMachinePatchReceipt()+ receipt.record(+ VPhoneVirtualMachinePatchReceipt.guestPart,+ patches: live,+ writer: receiptWriter,+ bundleVersion: bundleVersion,+ notApplicable: notApplicable,+ )+ try bundleDirectory.writeFile(+ VPhonePatchPresetStore.receiptFileName,+ contents: receipt.encoded(),+ mode: 0o777,+ owner: owner,)+ } catch {+ fputs("warning: could not record the guest patch receipt: \(error)\n", stderr)}+ }- try installVphoned(system: system, work: work)- print(" [+] vphoned and its launch daemon")-- for name in VPhoneGuestEnvironment.libraries {- let path = "usr/lib/\(name)"- guard try system.exists(path) else {- print(" [·] \(path): not on this VM, left out")- continue- }- let source = try VPhoneGuestBinaries.resolve(name)- try system.replaceFile(path, fromFileAt: source, mode: 0o755, owner: Self.guestOwner)- print(" [+] \(path)")- }+ /// This `VPhone.bundle`'s version, for the receipt, or nil for a plain+ /// `swift build` of `vphone-cli` with no bundle Info.plist beside it.+ private var bundleVersion: String? {+ let info = executable+ .deletingLastPathComponent() // Contents/MacOS+ .deletingLastPathComponent() // Contents+ .appendingPathComponent("Info.plist")+ guard let data = try? Data(contentsOf: info),+ let plist = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any]+ else { return nil }+ return plist["CFBundleShortVersionString"] as? String+ }- // Only when the guest has none, exactly as a full install does: the- // file carries a per-machine UDID choice and is not the bundle's to- // overwrite.- try installMISFixDefaults(system: system)+ // MARK: - Environment update- if plan?.isEnabled(FirmwareGuestSystemPatchSet.virtioSoundDriver) ?? true {- try installVirtioSoundDriver(system: system)- }- // Both patches ride one staged copy — `patchMachO` stages from the- // pristine backup, so two calls would not compose. The restore below- // fires only when every VirtualAudio patch is off.- var virtualAudioVerbs: [String] = []- if plan?.isEnabled(FirmwareGuestSystemPatchSet.virtualAudioSpeakerRouteThrows) ?? true {- virtualAudioVerbs.append("patch-virtualaudio")- }- if plan?.isEnabled(FirmwareGuestSystemPatchSet.virtualAudioMuteSetThrow) ?? true {- virtualAudioVerbs.append("patch-virtualaudio-mute")- }- if plan?.isEnabled(FirmwareGuestSystemPatchSet.virtualAudioSpeakerProtectionGate) ?? true {- virtualAudioVerbs.append("patch-virtualaudio-sp-gate")- }- if plan?.isEnabled(FirmwareGuestSystemPatchSet.virtualAudioVolumeModePrecondition) ?? true {- virtualAudioVerbs.append("patch-virtualaudio-volume-gate")- }- if !virtualAudioVerbs.isEmpty {- try patchMachO(- system: system,- work: work,- path: "Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin/VirtualAudio",- verbs: virtualAudioVerbs,- preserveEntitlements: true,- )- try sealGuestBundle(system: system, bundle: "Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin")- print(" [+] VirtualAudio: \(virtualAudioVerbs.joined(separator: ", "))")- } else if try system.exists("Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin/VirtualAudio.bak") {- // The patch is off but a previous install left it applied; stage- // the backup the same way `patchMachO` does and put the original- // back, so the gate means what it says.- let name = "VirtualAudio"- try work.directory.removeItem(name)- try system.copyFile(from: "Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin/VirtualAudio.bak", to: name, in: work.directory)- try system.replaceFile(- "Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin/VirtualAudio",- fromFileAt: work.file(name),- mode: 0o755,- owner: Self.guestOwner,- )- try sealGuestBundle(system: system, bundle: "Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin")- print(" [+] VirtualAudio restored from backup (patch off)")- }- if plan?.isEnabled(FirmwareGuestSystemPatchSet.virtualAudioGraphConfigurations) ?? true {- try patchVirtualAudioGraphConfigurations(system: system, work: work)- }- if plan?.isEnabled(FirmwareGuestSystemPatchSet.virtualAudioSpeakerRawChains) ?? true {- try patchVirtualAudioGraphConfigurations(- system: system, work: work, verb: "patch-virtualaudio-speaker-raw",- )- }- if plan?.isEnabled(FirmwareGuestSystemPatchSet.virtualAudioMicrophoneChains) ?? true {- try patchVirtualAudioGraphConfigurations(- system: system, work: work, verb: "patch-virtualaudio-microphone-chains",- )- }- }+ /// Guest patches declared after most VMs' plans were written, so a plan+ /// reads them as off even when the VM's selection has them on. They need no+ /// firmware change, so the guest half applies them from the selection. Kept+ /// only to reconstruct what the old `withLateGuestPatches` would have+ /// applied, for a VM that was installed but carries no receipt yet (see the+ /// prior-live fallback in `run()`).+ private static let lateGuestPatches = [+ FirmwareGuestSystemPatchSet.virtioSoundDriver,+ FirmwareGuestSystemPatchSet.prebootBoardAudio,+ FirmwareGuestSystemPatchSet.prebootHaptics,+ FirmwareGuestSystemPatchSet.prebootMicrophoneArray,+ FirmwareGuestSystemPatchSet.virtualAudioSpeakerRouteThrows,+ FirmwareGuestSystemPatchSet.virtualAudioMuteSetThrow,+ FirmwareGuestSystemPatchSet.virtualAudioSpeakerProtectionGate,+ FirmwareGuestSystemPatchSet.virtualAudioVolumeModePrecondition,+ FirmwareGuestSystemPatchSet.virtualAudioGraphConfigurations,+ FirmwareGuestSystemPatchSet.virtualAudioSpeakerRawChains,+ FirmwareGuestSystemPatchSet.virtualAudioMicrophoneChains,+ ]/// Host bookkeeping in the caller's folder, written with the caller's/// credentials as `cfw install` records the variant, never as root.@@ -615,18 +664,44 @@ struct VPhoneCustomFirmwareInstaller {// MARK: - System volume- private func installMounted(+ /// Apply the guest half of an install, both directions: every guest patch+ /// the plan turns on is written, and every one it leaves off is reverted+ /// where a backup or undo record exists. Returns the identifiers live in the+ /// guest afterwards, for the receipt — the ones applied, plus any a now-off+ /// patch could not be reverted (no backup, no undo record) that was live+ /// before, which stay in place and stay recorded.+ ///+ /// `restore` is the prepared restore tree, or nil for an environment update:+ /// the cryptexes and the GPU bundle come from it, so those steps are skipped+ /// with a note when it is absent (an installed guest already carries them).+ /// `xart` is the gigalocker volume, or nil when it was not mounted. With+ /// `environmentOnly`, the vphoned/library redeploy keeps its old narrow rule+ /// (a library absent from the VM stays absent, no `/vh` alias is created) and+ /// no restore-tree step runs.+ ///+ /// Each patch runs in isolation: one patch failing — a verb rejecting an+ /// unexpected prologue on an older VM, say — is reported and the patch is+ /// left in its prior state, but the run continues and the vphoned redeploy,+ /// done first, is never blocked. Non-patch failures (a volume that will not+ /// mount, the cryptex copy) still abort. The run exits 0 even with patch+ /// failures; they are printed as `[!]` lines and summarised at the end.+ @discardableResult+ private func applyGuestPatches(system: VPhoneConfinedDirectory,- xart: VPhoneConfinedDirectory,- restore: VPhoneConfinedDirectory,+ xart: VPhoneConfinedDirectory?,+ 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.+ priorGuest: Set<String>,+ environmentOnly: Bool,+ ) throws -> Set<String> {+ var live = Set<String>()+ var failures: [String] = []++ /// Whether the VM's plan (its guest half re-resolved from the current+ /// selection) turned this guest patch on. A VM with no plan 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 {@@ -636,199 +711,406 @@ struct VPhoneCustomFirmwareInstaller {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.") {- if on("dyld-boot-iomfb_force_kern") {- try patch("patch-iomfb-force-kern", [dsc])- }- if on("dyld-boot-maxslide") {- try patch("patch-dsc-maxslide", [dsc])+ /// A first backup of a file is safe only when no patch that touches the+ /// file was live before this run: otherwise the "original" we would+ /// snapshot already carries a patch, and a later revert to it would be a+ /// lie. When it is not safe the file's patches are not revertible.+ func backupSafe(_ ids: String...) -> Bool {+ ids.allSatisfy { !priorGuest.contains($0) }+ }++ /// Run a patch step so a throw does not abort the run: report it, keep+ /// each covered patch's prior-live state in the receipt, and carry on.+ func isolate(_ ids: [String], _ body: () throws -> Void) {+ do {+ try body()+ } catch {+ failures.append(contentsOf: ids)+ print(" [!] \(ids.joined(separator: ", ")): patch step failed, left in its prior state: \(error)")+ for id in ids where priorGuest.contains(id) { live.insert(id) }}- if on("dyld-boot-lsd_embedded_reg") {- try patch("patch-lsd-embedded-reg", [dsc])+ }++ /// A Mach-O patch: apply from the pristine backup when on, restore the+ /// backup when off. A binary off with no `.bak` (patched before backups+ /// were kept) is left as it is and, if it was live before, stays+ /// recorded as live — nothing here can put Apple's original back without+ /// the restore tree.+ func machO(+ _ identifier: String,+ path: String,+ verbs: [String] = [],+ codeIdentifier: String? = nil,+ preserveEntitlements: Bool = false,+ injectedDylibPath: String? = nil,+ bundle: String? = nil,+ ) {+ isolate([identifier]) {+ if on(identifier) {+ try patchMachO(+ system: system, work: work, path: path, verbs: verbs,+ identifier: codeIdentifier, preserveEntitlements: preserveEntitlements,+ injectedDylibPath: injectedDylibPath,+ )+ if let bundle { try sealGuestBundle(system: system, bundle: bundle) }+ live.insert(identifier)+ } else if try revertMachO(system: system, work: work, path: path, bundle: bundle) {+ print(" [+] \(identifier): restored \(path) from backup")+ } else if priorGuest.contains(identifier) {+ print(" [!] \(identifier): off now but no backup to revert; leaving the patched binary (not revertible)")+ live.insert(identifier)+ }}- if on("dyld-boot-xpc_lwcr") {- try patch("patch-xpc-lwcr", [dsc])+ }++ if let restore {+ try installCryptexes(restore: restore, system: system, work: work, owner: owner)+ }+ let version = try productVersion(system: system)++ // 1. The redeploy first, so no later patch failure can block it. vphoned+ // and the environment are boot-essential (always on). The environment+ // keeps its old narrow rule under `environmentOnly`.+ isolate(["system-vphoned-boot-install"]) {+ if on("system-vphoned-boot-install") {+ try installVphoned(system: system, work: work)+ live.insert("system-vphoned-boot-install")}- if on("dyld-boot-lockdown_mode") {- try patch("patch-lockdown-mode", [dsc])+ }+ isolate(["system-launchdaemons-boot-environment"]) {+ if on("system-launchdaemons-boot-environment") {+ try installEnvironment(system: system, environmentOnly: environmentOnly)+ live.insert("system-launchdaemons-boot-environment")}+ }++ // 2. The dyld shared cache. The version branches and the declarations'+ // applicability say the same thing; this is what a VM with no plan+ // still follows.+ let dsc = try verifiedDyldCacheDirectory(system: system)+ var dyld: [(id: String, verb: String, args: [String])] = []+ if version.hasPrefix("27.") {+ dyld += [+ ("dyld-boot-iomfb_force_kern", "patch-iomfb-force-kern", [dsc]),+ ("dyld-boot-maxslide", "patch-dsc-maxslide", [dsc]),+ ("dyld-boot-lsd_embedded_reg", "patch-lsd-embedded-reg", [dsc]),+ ("dyld-boot-xpc_lwcr", "patch-xpc-lwcr", [dsc]),+ ("dyld-boot-lockdown_mode", "patch-lockdown-mode", [dsc]),+ ]} else if version.hasPrefix("26.0") || version.hasPrefix("18.") {- if on("dyld-boot-iomfb_swapend") {- try patch("patch-iomfb-swapend", [dsc, "--target-size", "0x560"])- }+ dyld.append(("dyld-boot-iomfb_swapend", "patch-iomfb-swapend", [dsc, "--target-size", "0x560"]))}- // Version-agnostic: the guest is hacktivated on every base, so the- // profile check this opens fails on every base too. Off in `standard`,- // because libmisfix declines the same check from userspace in installd,- // misagent and SpringBoard without touching the cache — see- // FirmwarePatchSetCatalog.misTrustAuthPatch for why editing the cache- // is the worse trade on 27.- if on(FirmwarePatchSetCatalog.misTrustAuthPatch) {- try patch("patch-mis-trust-auth", [dsc])- }- // These former EXP patches pair with the kernel OID rename and the- // camera DeviceTree additions in the public CFW firmware pipeline.- if on("dyld-exp-hv_vmm") {- try patch("patch-hv-vmm-dsc", [dsc])- }- if on("dyld-cfw-camera") {- 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.+ dyld += [+ (FirmwarePatchSetCatalog.misTrustAuthPatch, "patch-mis-trust-auth", [dsc]),+ ("dyld-exp-hv_vmm", "patch-hv-vmm-dsc", [dsc]),+ ("dyld-cfw-camera", "patch-camera-dsc", [dsc, (dsc as NSString).appendingPathComponent("dyld_shared_cache_arm64e")]),+ ]+ applyDyldPatches(+ dyld, dsc: dsc, system: system, plan: plan, priorGuest: priorGuest,+ live: &live, failures: &failures,+ )++ // 3. The build-version spoof. Off by default (needs a preset parameter+ // or SPOOF_BUILD). Backed up only when it was not already applied.let buildVersion = plan?.parameters[FirmwareGuestSystemPatchSet.buildVersionParameter] ?? spoofBuild- if let build = buildVersion, !build.isEmpty, on("system-systemversion-cfw-build_version") {- for path in [- "System/Library/CoreServices/SystemVersion.plist",- "System/Cryptexes/OS/System/Library/CoreServices/SystemVersion.plist",- ] {- try patchCopy(of: path, in: system, work: work, verb: "patch-build-version", arguments: [build])+ let buildID = "system-systemversion-cfw-build_version"+ let buildPaths = [+ "System/Library/CoreServices/SystemVersion.plist",+ "System/Cryptexes/OS/System/Library/CoreServices/SystemVersion.plist",+ ]+ isolate([buildID]) {+ if let build = buildVersion, !build.isEmpty, on(buildID) {+ var applied = false+ for path in buildPaths where try system.isRegularFile(path) {+ try patchCopy(of: path, in: system, work: work, verb: "patch-build-version", arguments: [build], backupSafe: backupSafe(buildID))+ applied = true+ }+ if applied { live.insert(buildID) }+ } else if !on(buildID) {+ var reverted = false+ for path in buildPaths where try revertCopy(of: path, in: system) { reverted = true }+ if !reverted, priorGuest.contains(buildID) {+ print(" [!] \(buildID): off now but no backup to revert (not revertible)")+ live.insert(buildID)+ }}}- if on("system-seputil-boot-gigalocker_uuid") {- try patchMachO(- system: system,- work: work,- path: "usr/libexec/seputil",- verbs: ["patch-seputil"],- identifier: "com.apple.seputil",- )- }- if version.hasPrefix("27."), on("system-diskimagesiod-cfw-is_mount_complete") {- try patchMachO(- system: system,- work: work,- path: "usr/libexec/diskimagesiod",- verbs: ["patch-diskimagesiod"],- preserveEntitlements: true,- )++ machO("system-seputil-boot-gigalocker_uuid", path: "usr/libexec/seputil", verbs: ["patch-seputil"], codeIdentifier: "com.apple.seputil")+ if version.hasPrefix("27.") {+ machO("system-diskimagesiod-cfw-is_mount_complete", path: "usr/libexec/diskimagesiod", verbs: ["patch-diskimagesiod"], preserveEntitlements: true)}++ // The gigalocker rename pairs with seputil, a boot-essential first-install+ // step on the xART volume only a full install mounts. On an installed+ // guest it is already renamed, so record it live when on and leave it.if on("system-gigalocker-boot-rename") {- try renameGigalocker(xart: xart)+ isolate(["system-gigalocker-boot-rename"]) {+ if let xart {+ try renameGigalocker(xart: xart)+ } else {+ print(" [·] system-gigalocker-boot-rename: xART not mounted; left as installed")+ }+ live.insert("system-gigalocker-boot-rename")+ }}++ // The paravirtual GPU bundle comes from the restore tree, so an+ // environment update cannot (re)install it; an installed guest already+ // carries it, so record it live when on and skip with a note.if on("system-extensions-boot-gpu_bundle") {- try installGPUBundle(restore: restore, system: system, owner: owner)- }- if on("system-launchd_cache_loader-boot-unsecure_cache_gate") {- try patchMachO(- system: system,- work: work,- path: "usr/libexec/launchd_cache_loader",- verbs: ["patch-launchd-cache-loader"],- identifier: "com.apple.launchd_cache_loader",- )- }- if on("system-mobileactivationd-boot-should_hactivate") {- try patchMachO(- system: system,- work: work,- path: "usr/libexec/mobileactivationd",- verbs: ["patch-mobileactivationd"],- )- }- if on("system-watchdogd-exp-hv_vmm_cache") {- try patchWatchdog(system: system, work: work)- }- if on("system-vphoned-boot-install") {- try installVphoned(system: system, work: work)+ isolate(["system-extensions-boot-gpu_bundle"]) {+ if let restore {+ try installGPUBundle(restore: restore, system: system, owner: owner)+ } else {+ print(" [·] system-extensions-boot-gpu_bundle: no restore tree; GPU bundle left as installed")+ }+ live.insert("system-extensions-boot-gpu_bundle")+ }}- if on("system-launchdaemons-boot-environment") {- try installEnvironment(system: system)++ machO("system-launchd_cache_loader-boot-unsecure_cache_gate", path: "usr/libexec/launchd_cache_loader", verbs: ["patch-launchd-cache-loader"], codeIdentifier: "com.apple.launchd_cache_loader")+ machO("system-mobileactivationd-boot-should_hactivate", path: "usr/libexec/mobileactivationd", verbs: ["patch-mobileactivationd"])++ isolate(["system-watchdogd-exp-hv_vmm_cache"]) {+ if on("system-watchdogd-exp-hv_vmm_cache") {+ try patchWatchdog(system: system, work: work)+ live.insert("system-watchdogd-exp-hv_vmm_cache")+ } else if try revertMachO(system: system, work: work, path: "usr/libexec/watchdogd") {+ print(" [+] system-watchdogd-exp-hv_vmm_cache: restored watchdogd from backup")+ } else if priorGuest.contains("system-watchdogd-exp-hv_vmm_cache") {+ print(" [!] system-watchdogd-exp-hv_vmm_cache: off now but no backup to revert (not revertible)")+ live.insert("system-watchdogd-exp-hv_vmm_cache")+ }}+if on(FirmwareGuestSystemPatchSet.virtioSoundDriver) {- try installVirtioSoundDriver(system: system)- }- // Both patches ride one staged copy — `patchMachO` stages from the- // pristine backup, so two calls would not compose.- var virtualAudioVerbs: [String] = []- if on(FirmwareGuestSystemPatchSet.virtualAudioSpeakerRouteThrows) {- virtualAudioVerbs.append("patch-virtualaudio")- }- if on(FirmwareGuestSystemPatchSet.virtualAudioMuteSetThrow) {- virtualAudioVerbs.append("patch-virtualaudio-mute")- }- if on(FirmwareGuestSystemPatchSet.virtualAudioSpeakerProtectionGate) {- virtualAudioVerbs.append("patch-virtualaudio-sp-gate")- }- if on(FirmwareGuestSystemPatchSet.virtualAudioVolumeModePrecondition) {- virtualAudioVerbs.append("patch-virtualaudio-volume-gate")- }- if !virtualAudioVerbs.isEmpty {- try patchMachO(- system: system,- work: work,- path: "Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin/VirtualAudio",- verbs: virtualAudioVerbs,- preserveEntitlements: true,- )- try sealGuestBundle(system: system, bundle: "Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin")+ isolate([FirmwareGuestSystemPatchSet.virtioSoundDriver]) {+ try installVirtioSoundDriver(system: system)+ live.insert(FirmwareGuestSystemPatchSet.virtioSoundDriver)+ }+ } else {+ isolate([FirmwareGuestSystemPatchSet.virtioSoundDriver]) {+ if try revertVirtioSoundDriver(system: system) {+ print(" [+] \(FirmwareGuestSystemPatchSet.virtioSoundDriver): removed the virtio sound driver")+ }+ }}- if on(FirmwareGuestSystemPatchSet.virtualAudioGraphConfigurations) {- try patchVirtualAudioGraphConfigurations(system: system, work: work)++ // The VirtualAudio HAL plugin: four sub-patches ride one staged copy+ // (`patchMachO` stages from the pristine backup, so two calls would not+ // compose). On when any is on; reverted from `.bak` when all are off.+ let virtualAudio: [(id: String, verb: String)] = [+ (FirmwareGuestSystemPatchSet.virtualAudioSpeakerRouteThrows, "patch-virtualaudio"),+ (FirmwareGuestSystemPatchSet.virtualAudioMuteSetThrow, "patch-virtualaudio-mute"),+ (FirmwareGuestSystemPatchSet.virtualAudioSpeakerProtectionGate, "patch-virtualaudio-sp-gate"),+ (FirmwareGuestSystemPatchSet.virtualAudioVolumeModePrecondition, "patch-virtualaudio-volume-gate"),+ ]+ let virtualAudioBundle = "Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin"+ let virtualAudioBinary = "\(virtualAudioBundle)/VirtualAudio"+ let virtualAudioOn = virtualAudio.filter { on($0.id) }+ isolate(virtualAudio.map(\.id)) {+ if !virtualAudioOn.isEmpty {+ guard try system.isRegularFile(virtualAudioBinary) else {+ print(" [·] VirtualAudio: not on this VM, left out")+ return+ }+ try patchMachO(+ system: system, work: work, path: virtualAudioBinary,+ verbs: virtualAudioOn.map(\.verb), preserveEntitlements: true,+ )+ try sealGuestBundle(system: system, bundle: virtualAudioBundle)+ for patch in virtualAudioOn { live.insert(patch.id) }+ } else if try revertMachO(system: system, work: work, path: virtualAudioBinary, bundle: virtualAudioBundle) {+ print(" [+] VirtualAudio restored from backup (all speaker/mute patches off)")+ } else {+ for patch in virtualAudio where priorGuest.contains(patch.id) {+ print(" [!] \(patch.id): off now but no VirtualAudio backup to revert (not revertible)")+ live.insert(patch.id)+ }+ }}- if on(FirmwareGuestSystemPatchSet.virtualAudioSpeakerRawChains) {- try patchVirtualAudioGraphConfigurations(- system: system, work: work, verb: "patch-virtualaudio-speaker-raw",- )++ // The three VirtualAudio tuning patches share one+ // `graph_configurations.plist`, so there is no per-edit inverse. Restore+ // the tuning files to pristine from their backups, then re-apply+ // whichever of the three are on — which lands exactly the enabled set.+ // Backed up only when none of the three was live before.+ let graphGroup: [(id: String, verb: String)] = [+ (FirmwareGuestSystemPatchSet.virtualAudioGraphConfigurations, "patch-virtualaudio-graph-configurations"),+ (FirmwareGuestSystemPatchSet.virtualAudioSpeakerRawChains, "patch-virtualaudio-speaker-raw"),+ (FirmwareGuestSystemPatchSet.virtualAudioMicrophoneChains, "patch-virtualaudio-microphone-chains"),+ ]+ let graphOn = graphGroup.filter { on($0.id) }+ let graphBackupSafe = backupSafe(graphGroup[0].id, graphGroup[1].id, graphGroup[2].id)+ isolate(graphGroup.map(\.id)) {+ let hadGraphBackup = try restoreVirtualAudioTunings(system: system)+ if !graphOn.isEmpty {+ for entry in graphOn {+ let patched = try patchVirtualAudioGraphConfigurations(+ system: system, work: work, verb: entry.verb, backupSafe: graphBackupSafe,+ )+ if patched { live.insert(entry.id) }+ }+ } else if !hadGraphBackup {+ for entry in graphGroup where priorGuest.contains(entry.id) {+ print(" [!] \(entry.id): off now but no tuning-plist backup to revert (not revertible)")+ live.insert(entry.id)+ }+ }}- if on(FirmwareGuestSystemPatchSet.virtualAudioMicrophoneChains) {- try patchVirtualAudioGraphConfigurations(- system: system, work: work, verb: "patch-virtualaudio-microphone-chains",- )++ machO("system-launchd-boot-jetsam_panic_guard_bypass", path: "sbin/launchd", verbs: ["patch-launchd-jetsam"], preserveEntitlements: true, injectedDylibPath: "/vh")++ isolate([]) { try restoreMISFixTargets(system: system) }++ isolate(["system-debugserver-cfw-install"]) {+ if on("system-debugserver-cfw-install") {+ if try patchDebugserver(system: system, work: work, backupSafe: backupSafe("system-debugserver-cfw-install")) {+ live.insert("system-debugserver-cfw-install")+ }+ } else if try revertMachO(system: system, work: work, path: "usr/libexec/debugserver") {+ print(" [+] system-debugserver-cfw-install: restored debugserver from backup")+ } else if priorGuest.contains("system-debugserver-cfw-install") {+ print(" [!] system-debugserver-cfw-install: off now but no backup to revert (not revertible)")+ live.insert("system-debugserver-cfw-install")+ }}- if on("system-launchd-boot-jetsam_panic_guard_bypass") {- try patchMachO(- system: system,- work: work,- path: "sbin/launchd",- verbs: ["patch-launchd-jetsam"],- preserveEntitlements: true,- injectedDylibPath: "/vh",- )++ if version.hasPrefix("27.") {+ isolate(["system-campo-cfw-entitlements"]) {+ if on("system-campo-cfw-entitlements") {+ if try patchCampo(system: system, work: work, backupSafe: backupSafe("system-campo-cfw-entitlements")) {+ live.insert("system-campo-cfw-entitlements")+ }+ } else if try revertMachO(system: system, work: work, path: "Applications/Campo.app/Campo") {+ print(" [+] system-campo-cfw-entitlements: restored Campo from backup")+ } else if priorGuest.contains("system-campo-cfw-entitlements") {+ print(" [!] system-campo-cfw-entitlements: off now but no backup to revert (not revertible)")+ live.insert("system-campo-cfw-entitlements")+ }+ }}- try restoreMISFixTargets(system: system)- if on("system-debugserver-cfw-install") {- try patchDebugserver(system: system, work: work)++ if !failures.isEmpty {+ print("[!] \(failures.count) guest patch(es) failed and were left in their prior state: \(Set(failures).sorted().joined(separator: ", "))")}- if version.hasPrefix("27."), on("system-campo-cfw-entitlements") {- try patchCampo(system: system, work: work)+ return live+ }++ /// Apply the enabled dyld cache patches whose state differs from what was+ /// live before, and revert the disabled ones from the undo log the earlier+ /// install wrote. A patch already in the prior-live set is left alone — no+ /// multi-gigabyte scan when nothing changed. A disabled patch with no undo+ /// record was either never applied (nothing to do) or applied before the+ /// undo log existed; the latter is told apart by the prior-live set and+ /// reported as not revertible, staying live. Each verb runs in isolation.+ private func applyDyldPatches(+ _ dyld: [(id: String, verb: String, args: [String])],+ dsc: String,+ system: VPhoneConfinedDirectory,+ plan: VPhoneVirtualMachinePatchPlan?,+ priorGuest: Set<String>,+ live: inout Set<String>,+ failures: inout [String],+ ) {+ func enabled(_ id: String) -> Bool { plan?.isEnabled(id) ?? true }+ let undoAbsolute = (dsc as NSString).appendingPathComponent(Self.dscUndoLogLeaf)+ let undoRelative = "\(Self.dscCacheRelative)/\(Self.dscUndoLogLeaf)"+ let recorded = (try? system.readData(undoRelative))+ .flatMap { try? DyldSharedCacheUndoLog.decode($0) }?.patchIDs ?? []++ var revertable: [String] = []+ for entry in dyld {+ let want = enabled(entry.id)+ let had = priorGuest.contains(entry.id)+ switch (want, had) {+ case (true, true):+ // Already applied; leave it, no scan.+ live.insert(entry.id)+ case (true, false):+ do {+ try patch(entry.verb, entry.args + ["--undo-log", undoAbsolute, "--undo-id", entry.id])+ live.insert(entry.id)+ } catch {+ failures.append(entry.id)+ print(" [!] \(entry.id): dyld patch failed, left in its prior state: \(error)")+ }+ case (false, true):+ if recorded.contains(entry.id) {+ revertable.append(entry.id)+ } else {+ print(" [!] \(entry.id): off now but the dyld undo log has no record (patched before the undo log existed); not revertible")+ live.insert(entry.id)+ }+ case (false, false):+ break+ }+ }+ if !revertable.isEmpty {+ do {+ try patch("patch-dsc-revert", [dsc, "--undo-log", undoAbsolute] + revertable.flatMap { ["--patch", $0] })+ } catch {+ failures.append(contentsOf: revertable)+ print(" [!] dyld revert failed, left in prior state: \(error)")+ for id in revertable { live.insert(id) }+ }}}- /// Guest patches declared after most VMs' plans were written. A plan is the- /// list of what was on when `fw patch` ran, so it reads these as off on any- /// VM patched before them. They need no firmware change, so they follow the- /// VM's selection as it resolves now instead.- private static let lateGuestPatches = [- FirmwareGuestSystemPatchSet.virtioSoundDriver,- FirmwareGuestSystemPatchSet.prebootBoardAudio,- FirmwareGuestSystemPatchSet.prebootHaptics,- FirmwareGuestSystemPatchSet.prebootMicrophoneArray,- FirmwareGuestSystemPatchSet.virtualAudioSpeakerRouteThrows,- FirmwareGuestSystemPatchSet.virtualAudioMuteSetThrow,- FirmwareGuestSystemPatchSet.virtualAudioSpeakerProtectionGate,- FirmwareGuestSystemPatchSet.virtualAudioVolumeModePrecondition,- FirmwareGuestSystemPatchSet.virtualAudioGraphConfigurations,- FirmwareGuestSystemPatchSet.virtualAudioSpeakerRawChains,- FirmwareGuestSystemPatchSet.virtualAudioMicrophoneChains,- ]+ /// Restore a guest Mach-O from its `.bak`, re-sealing the bundle it lives in+ /// when one is given. Returns false when there is no backup — a binary+ /// patched before backups were kept.+ @discardableResult+ private func revertMachO(+ system: VPhoneConfinedDirectory,+ work: WorkDirectory,+ path: String,+ bundle: String? = nil,+ ) throws -> Bool {+ let backup = "\(path).bak"+ guard try system.exists(backup) else { return false }+ let name = (path as NSString).lastPathComponent+ try work.directory.removeItem(name)+ try system.copyFile(from: backup, to: name, in: work.directory)+ try system.replaceFile(path, fromFileAt: work.file(name), mode: 0o755, owner: Self.guestOwner)+ try system.removeItem(backup)+ if let bundle { try sealGuestBundle(system: system, bundle: bundle) }+ return true+ }++ /// Remove the virtio sound driver bundle. iOS ships no plugin for its+ /// kernel driver, so the pristine state is the bundle's absence — there is+ /// no backup to restore, the revert is the removal. Returns whether it was+ /// there to remove.+ @discardableResult+ private func revertVirtioSoundDriver(system: VPhoneConfinedDirectory) throws -> Bool {+ let target = "System/Library/Audio/Plug-Ins/HAL/VPhoneVirtIOSound.driver"+ guard try system.exists(target) else { return false }+ try system.removeItem(target)+ return true+ }- /// `plan`, with each late guest patch it leaves out turned on when the- /// VM's preset and its own block and allow choices select it today. A- /// preset that cannot be resolved from the bundled sets (one naming an- /// external set) leaves the plan as it is: root loads no external set.- private func withLateGuestPatches(+ /// `plan`, with its guest-patch half re-resolved from the VM's current+ /// selection — both directions. The boot-chain patches stay exactly as the+ /// plan recorded them (they were built into the restore tree and the+ /// originals when `fw patch` ran, and this run cannot change them); every+ /// guest-target patch is replaced by what the preset and the VM's own block+ /// and allow choices select today. So a guest patch the owner has since+ /// turned off drops out of the plan the guest half reads, and one they have+ /// turned on comes in — which is what makes `fw set-patches` reach an+ /// installed VM at the next `cfw install` or `cfw update-environment`.+ ///+ /// A preset that cannot be resolved from the bundled sets — one naming an+ /// external `.vphonepatchset` — leaves the plan as it is: root loads no+ /// external set, so it cannot re-resolve such a selection and must not guess.+ /// A VM with no plan at all stays nil (every guest patch applies, which is+ /// what it was restored with).+ private func resolveGuestSelection(_ plan: VPhoneVirtualMachinePatchPlan?,in bundleDirectory: VPhoneConfinedDirectory,) -> VPhoneVirtualMachinePatchPlan? {guard var plan else { return nil }- let missing = Self.lateGuestPatches.filter { !plan.isEnabled($0) }- guard !missing.isEmpty else { return plan }let selection = (try? bundleDirectory.readData(VPhonePatchPresetStore.selectionFileName)).flatMap { try? PropertyListDecoder().decode(VPhoneVirtualMachinePatchSelection.self, from: $0) }?? VPhoneVirtualMachinePatchSelection()@@ -843,12 +1125,21 @@ struct VPhoneCustomFirmwareInstaller {allowed: Set(selection.allowedPatches),)else {+ print("[!] Preset \(plan.presetIdentifier) does not resolve from bundled sets; applying the plan as recorded")return plan}- for identifier in missing where resolved.enabled.contains(identifier) {- plan.enabledPatches.append(identifier)- print("[*] \(identifier): newer than this VM's patch plan, on in preset \(plan.presetIdentifier)")+ let planEnabled = Set(plan.enabledPatches)+ let effective = FirmwareGuestPatchResolution.effectiveEnabled(+ planEnabled: planEnabled,+ selectionEnabled: resolved.enabled,+ )+ for added in effective.subtracting(planEnabled).sorted() {+ print("[*] \(added): on in the current selection, newer than this VM's patch plan")+ }+ for dropped in planEnabled.subtracting(effective).sorted() {+ print("[*] \(dropped): off in the current selection; the guest half will revert it")}+ plan.enabledPatches = effective.sorted()return plan}@@ -1081,14 +1372,27 @@ struct VPhoneCustomFirmwareInstaller {/// The launchd hook, SystemHook and the camera hooks. SystemHook loads the/// camera hooks from /usr/lib without a bootstrap or tweak loader.- private func installEnvironment(system: VPhoneConfinedDirectory) throws {+ ///+ /// `environmentOnly` keeps the old environment-update rule: a library the VM+ /// does not already have stays absent (its absence means the VM's plan never+ /// selected it), and the `/vh` alias is not created — an installed VM+ /// already has it, and an environment update does not add load-command+ /// infrastructure. A full install writes every library and creates `/vh`.+ private func installEnvironment(system: VPhoneConfinedDirectory, environmentOnly: Bool = false) throws {for name in VPhoneGuestEnvironment.libraries {+ let path = "usr/lib/\(name)"+ if environmentOnly, try !system.exists(path) {+ print(" [·] \(path): not on this VM, left out")+ continue+ }let source = try VPhoneGuestBinaries.resolve(name)- try system.replaceFile("usr/lib/\(name)", fromFileAt: source, mode: 0o755, owner: Self.guestOwner)+ try system.replaceFile(path, fromFileAt: source, mode: 0o755, owner: Self.guestOwner)+ }+ if !environmentOnly {+ // launchd has little free header space for another load command.+ // /vh fits the same 32-byte command as the old /b without reusing it.+ try installLibraryAlias(system: system, alias: "vh", target: "/usr/lib/launchdhook-vphone.dylib")}- // launchd has little free header space for another load command.- // /vh fits the same 32-byte command as the old /b without reusing it.- try installLibraryAlias(system: system, alias: "vh", target: "/usr/lib/launchdhook-vphone.dylib")try installMISFixDefaults(system: system)}@@ -1189,52 +1493,83 @@ struct VPhoneCustomFirmwareInstaller {return VPhoneGuestDevice.detect(buildManifest: manifest) ?? .default}- /// `includeIdentity` is false for an environment update, which carries- /// only the device tree repairs: the board audio repair, which needs- /// `boardDeviceTree`, and the haptics removal, which every guest gets.+ /// `includeIdentity` is false for an environment update, which carries only+ /// the device tree repairs: the board audio repair, which needs+ /// `boardDeviceTree`, the haptics removal and the microphone-array repair./// `boardDeviceTree` is the iPad's own device tree, staged from the VM's/// `FirmwareOriginals`, or nil for an iPhone guest or a VM patched before/// `fw patch` kept it.+ ///+ /// Returns the Preboot device-tree identifiers live afterwards, for the+ /// receipt. The repairs share one personalized `devicetree.img4`, so there+ /// is no per-repair inverse; instead the final tree is built in staging and+ /// written only if it differs from what is on disk, so an unchanged result+ /// never bumps the mtime (vphoned drops its MobileGestalt cache when the+ /// tree is newer than it). The backup kept beside the tree is its state+ /// *after* the identity rewrite and *before* the repairs:+ ///+ /// - full install: restore that backup to a clean base, apply identity,+ /// re-take the backup from the post-identity bytes, then apply the+ /// enabled repairs;+ /// - environment update (no identity step): restore the backup, apply the+ /// enabled repairs.+ ///+ /// A backup is taken only when the base is known clean — a backup already+ /// existed, or no repair was live before. A tree repaired before backups+ /// were kept has none, and an off repair on it is reported not revertible+ /// and left in place.+ @discardableResultprivate func patchPreboot(volumes: [[String: Any]],work: WorkDirectory,plan: VPhoneVirtualMachinePatchPlan?,+ priorGuest: Set<String>,guestDevice: VPhoneGuestDevice,includeIdentity: Bool,+ buildVersion: String?,boardDeviceTree: URL?,- ) throws {- /// Like every guest patch, a VM with no plan still gets it — except the- /// identity rewrite on an iPad guest, whose installed tree already- /// carries its own identity from `fw patch`; the rewrite would turn it- /// back into an iPhone17,3.- func on(_ identifier: String) -> Bool {- let enabled = plan?.isEnabled(identifier) ?? true- if let plan, !enabled {- print(" [·] \(identifier): off in preset \(plan.presetIdentifier)")- }- return enabled- }+ ) throws -> Set<String> {+ var live = Set<String>()+ /// Whether a device-tree patch is enabled. A VM with no plan gets every+ /// one, which is what it was restored with.+ func enabled(_ identifier: String) -> Bool { plan?.isEnabled(identifier) ?? true }+let identity = FirmwareGuestIdentityPatchSet.prebootDeviceTreeIdentityvar rewriteIdentity = falseif includeIdentity {if guestDevice.isPad {print(" [·] \(identity): skipped, the device tree already presents \(guestDevice.productType)")} else {- rewriteIdentity = on(identity)+ rewriteIdentity = enabled(identity)+ if !rewriteIdentity { print(" [·] \(identity): off in the current selection") }}+ } else if priorGuest.contains(identity) {+ // An environment update does not touch the identity rewrite; if the+ // last install wrote it, it is still live.+ live.insert(identity)}- let spoofBuild = includeIdentity ? spoofBuild : nil- var repairs: [(verb: String, arguments: [String])] = []- if let boardDeviceTree, on(FirmwareGuestSystemPatchSet.prebootBoardAudio) {- repairs.append(("patch-dt-board-audio", [boardDeviceTree.path]))- }- if on(FirmwareGuestSystemPatchSet.prebootHaptics) {- repairs.append(("patch-dt-haptics", []))++ // The repairs, which share the one devicetree.img4.+ var repairGroup: [(id: String, verb: String, arguments: [String])] = []+ if let boardDeviceTree {+ repairGroup.append((FirmwareGuestSystemPatchSet.prebootBoardAudio, "patch-dt-board-audio", [boardDeviceTree.path]))}- if on(FirmwareGuestSystemPatchSet.prebootMicrophoneArray) {- repairs.append(("patch-dt-microphone-array", []))+ repairGroup.append((FirmwareGuestSystemPatchSet.prebootHaptics, "patch-dt-haptics", []))+ repairGroup.append((FirmwareGuestSystemPatchSet.prebootMicrophoneArray, "patch-dt-microphone-array", []))+ let repairsOn = repairGroup.filter { enabled($0.id) }+ for off in repairGroup where !enabled(off.id) {+ print(" [·] \(off.id): off in the current selection")}- guard rewriteIdentity || !repairs.isEmpty || !(spoofBuild ?? "").isEmpty else { return }++ let buildID = "system-systemversion-cfw-build_version"++ // Mount only when there is device-tree work to do, a repair to revert,+ // or a build spoof to apply or revert.+ let mayRevertRepair = repairGroup.contains { !enabled($0.id) && priorGuest.contains($0.id) }+ let wantsBuild = (buildVersion.map { !$0.isEmpty } ?? false) && enabled(buildID)+ let touchesBuild = wantsBuild || priorGuest.contains(buildID)+ guard rewriteIdentity || !repairsOn.isEmpty || mayRevertRepair || touchesBuild else { return live }+guardlet preboot = volumes.first(where: { ($0["Roles"] as? [String])?.contains("Preboot") == true }),let device = preboot["DeviceIdentifier"] as? String@@ -1245,10 +1580,12 @@ struct VPhoneCustomFirmwareInstaller {_ = try work.directory.directory("preboot", create: true, mode: 0o700)try mountGuestVolume(device, at: mount)defer { _ = try? tool("/sbin/umount", [mount.path], quiet: true) }+ // Every descriptor on the Preboot volume lives in this scope, so none+ // is left open to hold it busy when the deferred unmount runs.do {let root = try openGuestVolume("preboot", device: device, in: work)- // Each candidate must be reached without a link anywhere on the- // way; one behind a link is not counted.+ // Each candidate must be reached without a link anywhere on the way;+ // one behind a link is not counted.let candidates = try root.entries().compactMap { name -> String? inlet path = "\(name)/usr/standalone/firmware/devicetree.img4"guard (try? root.isDirectory(name)) == true, (try? root.isRegularFile(path)) == true else {@@ -1259,17 +1596,99 @@ struct VPhoneCustomFirmwareInstaller {guard candidates.count == 1, let deviceTree = candidates.first else {throw ValidationError("Expected one device tree in the Preboot volume but found \(candidates.count). Restore the VM, then install CFW again.")}- if rewriteIdentity {- try patchCopy(of: deviceTree, in: root, work: work, verb: "patch-post-restore-dt")++ try buildDeviceTree(+ deviceTree, in: root, work: work,+ rewriteIdentity: rewriteIdentity, identity: identity,+ includeIdentity: includeIdentity, repairGroup: repairGroup, repairsOn: repairsOn,+ priorGuest: priorGuest, live: &live,+ )++ // The build-version spoof on the Preboot SystemVersion, its own file+ // and its own backup. The identifier is shared with the system-volume+ // copy, which the guest-patch pass already recorded; this keeps the+ // two copies in step and does not record again. It follows the same+ // preset parameter / SPOOF_BUILD the system-volume copy does.+ let version = "Cryptexes/OS/System/Library/CoreServices/SystemVersion.plist"+ if try root.isRegularFile(version) {+ if wantsBuild, let build = buildVersion {+ try patchCopy(of: version, in: root, work: work, verb: "patch-build-version", arguments: [build], backupSafe: !priorGuest.contains(buildID))+ } else if !enabled(buildID) {+ try revertCopy(of: version, in: root)+ }}- for repair in repairs {- try patchCopy(of: deviceTree, in: root, work: work, verb: repair.verb, arguments: repair.arguments)+ }++ return live+ }++ /// Build the final device tree in staging and write it only if it differs+ /// from what is on disk, so an unchanged result does not bump the mtime. See+ /// `patchPreboot` for the ordering and backup rules this implements.+ private func buildDeviceTree(+ _ deviceTree: String,+ in root: VPhoneConfinedDirectory,+ work: WorkDirectory,+ rewriteIdentity: Bool,+ identity: String,+ includeIdentity: Bool,+ repairGroup: [(id: String, verb: String, arguments: [String])],+ repairsOn: [(id: String, verb: String, arguments: [String])],+ priorGuest: Set<String>,+ live: inout Set<String>,+ ) throws {+ guard let meta = try root.status(deviceTree), meta.st_mode & S_IFMT == S_IFREG else {+ throw ValidationError("\(deviceTree) on the VM is missing or is not a regular file. Restore the VM, then install CFW again.")+ }+ let currentBytes = try root.readData(deviceTree)+ let backup = "\(deviceTree).bak"+ let hadRepairBackup = try root.exists(backup)+ // A backup is trustworthy only when the base it will describe is clean:+ // one already existed, or no repair was live before this run.+ let backupSafe = hadRepairBackup || repairGroup.allSatisfy { !priorGuest.contains($0.id) }++ // Stage the base: the clean backup when there is one, else the tree as+ // it stands now.+ let folder = "dt-\(UUID().uuidString)"+ _ = try work.directory.directory(folder, create: true, mode: 0o700)+ defer { try? work.directory.removeItem(folder) }+ let staged = work.file(folder).appendingPathComponent("devicetree.img4")+ try (hadRepairBackup ? root.readData(backup) : currentBytes).write(to: staged)++ // Identity first (full install only), so the post-identity snapshot and+ // a later repair revert never undo it.+ if rewriteIdentity {+ try patch("patch-post-restore-dt", [staged.path])+ live.insert(identity)+ }+ let postIdentity = try Data(contentsOf: staged)++ // Then the enabled repairs.+ if !repairsOn.isEmpty {+ for repair in repairsOn {+ try patch(repair.verb, [staged.path] + repair.arguments)+ live.insert(repair.id)}- if let build = spoofBuild {- let version = "Cryptexes/OS/System/Library/CoreServices/SystemVersion.plist"- if try root.isRegularFile(version) {- try patchCopy(of: version, in: root, work: work, verb: "patch-build-version", arguments: [build])- }+ } else if !backupSafe {+ for repair in repairGroup where priorGuest.contains(repair.id) {+ print(" [!] \(repair.id): off now but no device-tree backup to revert (not revertible)")+ live.insert(repair.id)+ }+ }++ let finalBytes = try Data(contentsOf: staged)+ // Write the tree only if it actually changed.+ if finalBytes != currentBytes {+ try root.replaceFile(+ deviceTree, fromFileAt: staged,+ mode: meta.st_mode & 0o7777, owner: (meta.st_uid, meta.st_gid),+ )+ }+ // (Re)take the post-identity, pre-repair backup when the base was clean,+ // and only when it changed, so a no-op run leaves it untouched.+ if backupSafe {+ if try !root.exists(backup) || root.readData(backup) != postIdentity {+ try root.writeFile(backup, contents: postIdentity, mode: meta.st_mode & 0o7777, owner: (meta.st_uid, meta.st_gid))}}}@@ -1389,12 +1808,22 @@ struct VPhoneCustomFirmwareInstaller {/// copy untouched, modification time included: vphoned drops the guest's/// MobileGestalt cache when the Preboot device tree is newer than it, so a/// repeated environment update must not make an unchanged tree look new.+ /// `backup` keeps the pre-patch bytes beside the file as `<relative>.bak`,+ /// written the instant a verb first changes it and never overwritten after,+ /// so a later run can put the original back for a patch now turned off. It+ /// is captured from the staged pre-patch copy — not the live file — so it is+ /// the true inverse of this one edit even when the file already carried+ /// another patch, and it is created only when the verb actually changes+ /// something, so a no-op on an already-patched file never snapshots patched+ /// bytes as if they were pristine. A file patched before this existed has no+ /// `.bak` and is reported not revertible rather than guessed at.private func patchCopy(of relative: String,in root: VPhoneConfinedDirectory,work: WorkDirectory,verb: String,arguments: [String] = [],+ backupSafe: Bool = false,) throws {guard let original = try root.status(relative), original.st_mode & S_IFMT == S_IFREG else {throw ValidationError("\(relative) on the VM is missing or is not a regular file. Restore the VM, then install CFW again.")@@ -1409,6 +1838,17 @@ struct VPhoneCustomFirmwareInstaller {let before = try Data(contentsOf: staged)try patch(verb, [staged.path] + arguments)guard try Data(contentsOf: staged) != before else { return }+ // Only snapshot the pre-patch bytes as the backup when no patch that+ // touches this file was live before this run: otherwise `before`+ // already carries a patch and is not a pristine original.+ if backupSafe, try !root.exists("\(relative).bak") {+ try root.writeFile(+ "\(relative).bak",+ contents: before,+ mode: original.st_mode & 0o7777,+ owner: (original.st_uid, original.st_gid),+ )+ }try root.replaceFile(relative,fromFileAt: staged,@@ -1417,27 +1857,44 @@ struct VPhoneCustomFirmwareInstaller {)}+ /// Put `<relative>.bak` back over `relative` and remove the backup, the+ /// inverse of a `backup: true` `patchCopy`. Returns false when there is no+ /// backup — a file patched before backups were kept, which the caller+ /// reports as not revertible.+ @discardableResult+ private func revertCopy(of relative: String, in root: VPhoneConfinedDirectory) throws -> Bool {+ let backup = "\(relative).bak"+ guard try root.exists(backup) else { return false }+ try root.rename(backup, to: relative)+ return true+ }+/// Run `verb` on every tuning set's graph_configurations.plist: by default/// the one that flips the speaker chains onto the generic graph path. The plist lives under the acoustic ID the/// image ships for (`Library/Audio/Tunings/<AID>/VAD/`), which varies by/// board, so the directory is walked rather than named. An image with no/// tuning sets — iOS 27's VirtualAudio reads no such plist — is left/// alone, quietly: there is nothing this patch could act on.+ /// Returns whether any tuning plist was present to act on — false when the+ /// VM has no `Library/Audio/Tunings`, so the caller does not record the+ /// patch live on an image that never had it.+ @discardableResultprivate func patchVirtualAudioGraphConfigurations(system: VPhoneConfinedDirectory,work: WorkDirectory,verb: String = "patch-virtualaudio-graph-configurations",- ) throws {+ backupSafe: Bool = false,+ ) throws -> Bool {let tunings = "Library/Audio/Tunings"guard try system.exists(tunings), try system.isDirectory(tunings) else {print(" [·] \(tunings): not on this VM, left out")- return+ return false}var patched = 0for acousticID in try system.directory(tunings).entries().sorted() {let plist = "\(tunings)/\(acousticID)/VAD/graph_configurations.plist"guard try system.isRegularFile(plist) else { continue }- try patchCopy(of: plist, in: system, work: work, verb: verb)+ try patchCopy(of: plist, in: system, work: work, verb: verb, backupSafe: backupSafe)patched += 1guard verb == "patch-virtualaudio-microphone-chains" else { continue }// The strips those chains now record through, without the gain@@ -1447,12 +1904,40 @@ struct VPhoneCustomFirmwareInstaller {where name.contains("_mic") && name.hasSuffix("_measurement.austrip"){guard try system.isRegularFile("\(strips)/\(name)") else { continue }- try patchCopy(of: "\(strips)/\(name)", in: system, work: work, verb: "patch-virtualaudio-microphone-gain")+ try patchCopy(of: "\(strips)/\(name)", in: system, work: work, verb: "patch-virtualaudio-microphone-gain", backupSafe: backupSafe)}}if patched == 0 {print(" [·] \(tunings): no graph_configurations.plist under any tuning set, left out")+ return false+ }+ return true+ }++ /// Restore every VirtualAudio tuning file that carries a `.bak` to pristine,+ /// the inverse of a `backup: true` run of+ /// `patchVirtualAudioGraphConfigurations`. The three tuning patches share+ /// one `graph_configurations.plist`, so there is no per-edit inverse: the+ /// caller restores pristine with this and then re-applies whichever of the+ /// three are still on, which lands exactly the enabled set. Returns whether+ /// any backup was found (false means the files were patched before backups+ /// were kept, and the caller reports them not revertible).+ @discardableResult+ private func restoreVirtualAudioTunings(system: VPhoneConfinedDirectory) throws -> Bool {+ let tunings = "Library/Audio/Tunings"+ guard try system.exists(tunings), try system.isDirectory(tunings) else { return false }+ var restored = false+ for acousticID in try system.directory(tunings).entries().sorted() {+ let vad = "\(tunings)/\(acousticID)/VAD"+ guard try system.exists(vad), try system.isDirectory(vad) else { continue }+ for name in try system.directory(vad).entries().sorted() where name.hasSuffix(".bak") {+ let backup = "\(vad)/\(name)"+ guard try system.isRegularFile(backup) else { continue }+ try system.rename(backup, to: "\(vad)/\(String(name.dropLast(4)))")+ restored = true+ }}+ return restored}/// Stage a guest Mach-O, patch it, re-sign it and put it back.@@ -1529,9 +2014,21 @@ struct VPhoneCustomFirmwareInstaller {return work.file(name)}- private func patchDebugserver(system: VPhoneConfinedDirectory, work: WorkDirectory) throws {+ /// Take `<target>.bak` from the guest's current binary before the first+ /// entitlement patch, so `revertMachO` can put the original back later. Only+ /// when `backupSafe` — no patch touching this binary was live before — so a+ /// binary that already carries the patch is never snapshotted as pristine.+ private func backupEntitlementTarget(_ target: String, in system: VPhoneConfinedDirectory, backupSafe: Bool) throws {+ guard backupSafe, try !system.exists("\(target).bak") else { return }+ try system.copyFile(from: target, to: "\(target).bak")+ }++ /// Returns whether the patch was applied (false when the binary or its+ /// entitlements are absent, so the caller does not record it live).+ @discardableResult+ private func patchDebugserver(system: VPhoneConfinedDirectory, work: WorkDirectory, backupSafe: Bool) throws -> Bool {let target = "usr/libexec/debugserver"- guard let staged = try stageOptional(target, from: system, work: work, label: "debugserver") else { return }+ guard let staged = try stageOptional(target, from: system, work: work, label: "debugserver") else { return false }guardlet source = try VPhoneSigner.entitlements(ofFileAt: staged).first(where: { !$0.isEmpty }),@@ -1540,7 +2037,7 @@ struct VPhoneCustomFirmwareInstaller {) as? [String: Any]else {print("[!] debugserver has no readable entitlements; patch skipped")- return+ return false}plist.removeValue(forKey: "seatbelt-profiles")plist["task_for_pid-allow"] = true@@ -1548,6 +2045,7 @@ struct VPhoneCustomFirmwareInstaller {fromPropertyList: plist,format: .xml, options: 0,)+ try backupEntitlementTarget(target, in: system, backupSafe: backupSafe)// Replacement, not merge: `plist` is already the complete set we want,// and merging it back over the file's own entitlements would re-add the// `seatbelt-profiles` removed above — merge updates and appends keys, it@@ -1557,21 +2055,26 @@ struct VPhoneCustomFirmwareInstaller {options: .init(entitlements: data),)try system.replaceFile(target, fromFileAt: staged, mode: 0o755, owner: Self.guestOwner)+ return true}- private func patchCampo(system: VPhoneConfinedDirectory, work: WorkDirectory) throws {+ /// Returns whether the patch was applied (false when Campo or its+ /// entitlements are absent, so the caller does not record it live).+ @discardableResult+ private func patchCampo(system: VPhoneConfinedDirectory, work: WorkDirectory, backupSafe: Bool) throws -> Bool {let target = "Applications/Campo.app/Campo"- guard let staged = try stageOptional(target, from: system, work: work, label: "Campo") else { return }+ guard let staged = try stageOptional(target, from: system, work: work, label: "Campo") else { return false }guardlet source = try VPhoneSigner.entitlements(ofFileAt: staged).first(where: { !$0.isEmpty })else {print("[!] Campo has no readable entitlements; patch skipped")- return+ return false}let ent = work.file("Campo.entitlements")try source.write(to: ent)try patch("patch-campo-entitlements", [ent.path])+ try backupEntitlementTarget(target, in: system, backupSafe: backupSafe)try VPhoneSigner.sign(fileAt: staged,options: .init(@@ -1580,6 +2083,7 @@ struct VPhoneCustomFirmwareInstaller {),)try system.replaceFile(target, fromFileAt: staged, mode: 0o755, owner: Self.guestOwner)+ return true}// MARK: - xART volumediff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swiftindex c9473ea3..aae19a77 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift@@ -2,6 +2,7 @@ import ArgumentParserimport FirmwarePatcherimport Foundationimport VPhoneCoreKit+import VPhonePatchKitstruct VPhoneFirmwareCommand: ParsableCommand {static let configuration = CommandConfiguration(@@ -380,6 +381,13 @@ struct VPhoneFirmwarePatchesCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "patches",abstract: "List the patch sets, presets and individual patches this bundle can apply",+ discussion: """+ With a VM named, the report also compares the VM's choice with what its+ last `fw patch` planned (PatchPlan.plist) and what is recorded as applied+ in the guest (PatchReceipt.plist), and flags each patch whose wanted state+ has not reached the guest yet. A VM no receipt-writing step has touched+ reports its applied state as unknown.+ """,)@OptionGroup var lib: VPhoneLibraryOption@@ -393,10 +401,13 @@ struct VPhoneFirmwarePatchesCommand: ParsableCommand {// A VM is optional: without one, this reports what the bundle can do.var selection = VPhoneVirtualMachinePatchSelection()var vmName: String?+ var machine: VPhonePatchCatalogReport.MachineRecords?if let name {let resolvedName = try VPhoneVirtualMachineSelection.resolveExisting(name, in: lib.library)+ let bundle = try lib.library.bundle(named: resolvedName)vmName = resolvedName- selection = try VPhonePatchPresetStore.selection(forVM: lib.library.bundle(named: resolvedName).url)+ selection = VPhonePatchPresetStore.selection(forVM: bundle.url)+ machine = .read(bundle)}if let preset {selection.presetIdentifier = preset@@ -415,11 +426,12 @@ struct VPhoneFirmwarePatchesCommand: ParsableCommand {selection: selection,activePreset: active,presets: presets,+ machine: machine,)if json {try print(report.jsonText())} else {- print(report.text())+ print(report.text(libraryArguments: lib.commandSuffix))}}}@@ -435,7 +447,7 @@ struct VPhoneFirmwarePatchesCommand: ParsableCommand {struct VPhoneFirmwareSetPatchesCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "set-patches",- abstract: "Record which patches a VM applies, for the next fw patch",+ abstract: "Record which patches a VM applies",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@@ -445,8 +457,22 @@ struct VPhoneFirmwareSetPatchesCommand: ParsableCommand {already agrees with is dropped, so a later preset revision still reaches aVM 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.+ Nothing is patched here. On a VM that is not installed yet, the next+ `fw patch`, restore and `cfw install` build it with this choice.++ On an installed VM the choice is still recorded, and the command then+ lists each patch whose new state has not reached the guest, by where it+ lands and the step that delivers it:++ AVPBooter `fw patch`; read at the next boot. Needs+ the restore tree (`--keep-artifacts`).+ Guest (system, dyld cache, `cfw update-environment` (root), which+ Preboot device tree) applies this choice both on and off.+ LLB, kernelcache, TXM, only a restore.+ DeviceTree+ iBSS, iBEC used only while restoring.++ `fw patches <vm>` shows the same comparison at any time.""",)@@ -517,5 +543,62 @@ struct VPhoneFirmwareSetPatchesCommand: ParsableCommand {try VPhoneHostFilePermissions.makeAccessible(at: bundle.url)print("[fw set-patches] \(name): preset \(selection.presetIdentifier)"+ ", \(selection.blockedPatches.count) off, \(selection.allowedPatches.count) on")+ reportPending(selection: selection, preset: resolved, bundle: bundle, name: name)+ }++ /// On an installed VM, a new choice reaches the guest only through the+ /// step that owns each part, so say which patches still differ from what+ /// the guest has (or, with no receipt, from the last plan) and how each+ /// gets there. A VM that is not installed yet needs no such note: the+ /// steps that build it read this choice.+ private func reportPending(+ selection: VPhoneVirtualMachinePatchSelection,+ preset: VPhonePatchPreset,+ bundle: VPhoneBundle,+ name: String,+ ) {+ let machine = VPhonePatchCatalogReport.MachineRecords.read(bundle)+ guard machine.installed == true else { return }+ let report = VPhonePatchCatalogReport(+ vmName: name,+ selection: selection,+ activePreset: preset,+ presets: [],+ machine: machine,+ )+ guard let states = report.states() else { return }+ let pending = states.filter { $0.isPending == true }+ if pending.isEmpty {+ if states.allSatisfy({ $0.isPending == nil }) {+ print("[fw set-patches] \(name) is installed, but neither a plan nor a receipt records"+ + " what its guest has, so what this change still needs is unknown.")+ } else {+ print("[fw set-patches] \(name) is installed and already matches this choice.")+ }+ return+ }+ print("[fw set-patches] \(name) is installed. \(pending.count) patch(es) differ from what its guest has:")+ for line in VPhonePatchCatalogReport.pendingSteps(+ pending,+ vmName: name,+ libraryArguments: lib.commandSuffix,+ ) {+ print(line)+ }+ }+}++// MARK: - Library Arguments++extension VPhoneLibraryOption {+ /// ` --library-root <root>` when one was given, for a command printed back+ /// to the user, so it finds the same VM.+ var commandSuffix: String {+ guard let libraryRoot else { return "" }+ let safe = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "/._-~+@%:,="))+ let quoted = libraryRoot.unicodeScalars.allSatisfy(safe.contains)+ ? libraryRoot+ : "'" + libraryRoot.replacingOccurrences(of: "'", with: "'\\''") + "'"+ return " --library-root \(quoted)"}}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchCatalogReport.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchCatalogReport.swiftindex 1e9cec7f..ad21dcaa 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchCatalogReport.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchCatalogReport.swift@@ -10,9 +10,16 @@// 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.+//+// With a VM named, the report also compares the VM's selection against its plan+// and receipt (`FirmwarePatchDrift`), so a change that has not reached the guest+// yet is visible. Those fields are additive and appear only with a VM: a+// Launchpad that predates them ignores them, and a newer one reading an older+// bundle finds them absent.import FirmwarePatcherimport Foundation+import VPhoneCoreKitimport VPhonePatchKitpublic struct VPhonePatchCatalogReport: Sendable {@@ -20,23 +27,87 @@ public struct VPhonePatchCatalogReport: Sendable {public let selection: VPhoneVirtualMachinePatchSelectionpublic let activePreset: VPhonePatchPresetpublic let presets: [VPhonePatchPreset]+ /// The named VM's other records, or nil when no VM was named.+ public let machine: MachineRecords?public init(vmName: String?,selection: VPhoneVirtualMachinePatchSelection,activePreset: VPhonePatchPreset,presets: [VPhonePatchPreset],+ machine: MachineRecords? = nil,) {self.vmName = vmNameself.selection = selectionself.activePreset = activePresetself.presets = presets+ self.machine = machine+ }++ // MARK: - Machine Records++ /// What a VM records beside its selection: the plan, the receipt, whether+ /// `cfw install` finished, and the OS pairing the version gates run against.+ public struct MachineRecords: Sendable {+ public let plan: VPhoneVirtualMachinePatchPlan?+ public let receipt: VPhoneVirtualMachinePatchReceipt?+ /// Whether `cfw install` finished (`restore-info.json` has a variant);+ /// nil when the VM has no snapshot to tell.+ public let installed: Bool?+ public let iOSBase: VPhoneVersion?+ public let cloudOS: VPhoneVersion?++ public init(+ plan: VPhoneVirtualMachinePatchPlan?,+ receipt: VPhoneVirtualMachinePatchReceipt?,+ installed: Bool?,+ iOSBase: VPhoneVersion?,+ cloudOS: VPhoneVersion?,+ ) {+ self.plan = plan+ self.receipt = receipt+ self.installed = installed+ self.iOSBase = iOSBase+ self.cloudOS = cloudOS+ }++ /// Reads every record from the VM folder. The versions come from the+ /// plan, which is what `fw patch` gated against, else from the restore.+ public static func read(_ bundle: VPhoneBundle) -> MachineRecords {+ let plan = VPhonePatchPresetStore.plan(forVM: bundle.url)+ let restored = VPhoneRestoreInfo.load(fromBundle: bundle)+ return MachineRecords(+ plan: plan,+ receipt: VPhonePatchPresetStore.receipt(forVM: bundle.url),+ installed: VPhoneRestoreInfo.customFirmwareInstalled(inBundle: bundle),+ iOSBase: VPhoneVersion(plan?.iOSBaseVersion ?? restored?.ios.version),+ cloudOS: VPhoneVersion(plan?.cloudOSVersion ?? restored?.cloudOS.version),+ )+ }++ /// Each declaration compared across selection, plan and receipt.+ func states(selected: Set<String>) -> [FirmwarePatchDrift.PatchState] {+ let declarations = FirmwarePatchSetCatalog.allDeclarations+ return FirmwarePatchDrift.states(+ declarations: declarations,+ wanted: FirmwarePatchDrift.wantedPatches(+ selected: selected,+ declarations: declarations,+ iOSBase: iOSBase,+ cloudOS: cloudOS,+ ),+ planned: plan.map { Set($0.enabledPatches) },+ applied: receipt.map { $0.parts.mapValues { Set($0.patches) } },+ notApplicable: Set(receipt?.parts.values.flatMap(\.notApplicable) ?? []),+ part: VPhoneVirtualMachinePatchReceipt.part(for:),+ )+ }}// MARK: - JSON/// One patch as the editor sees it.- struct PatchEntry: Codable, Sendable {+ struct PatchEntry: Encodable, Sendable {let identifier: Stringlet title: Stringlet summary: String@@ -49,22 +120,81 @@ public struct VPhonePatchCatalogReport: Sendable {let inPreset: Bool/// Whether this VM's own choice leaves it on.let enabled: Bool+ /// Set only when a VM is named.+ var state: FirmwarePatchDrift.PatchState?++ private enum CodingKeys: String, CodingKey {+ case identifier, title, summary, patchSet, patchSetName, target, applicability+ case bootEssential, inPreset, enabled+ case part, wanted, planned, applied, pending, delivery+ }++ /// The machine fields are written as `null` rather than left out when+ /// a VM is named but the record is missing, so a reader can tell "no+ /// plan" from "no VM".+ 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)+ try container.encode(summary, forKey: .summary)+ try container.encode(patchSet, forKey: .patchSet)+ try container.encode(patchSetName, forKey: .patchSetName)+ try container.encode(target, forKey: .target)+ try container.encode(applicability, forKey: .applicability)+ try container.encode(bootEssential, forKey: .bootEssential)+ try container.encode(inPreset, forKey: .inPreset)+ try container.encode(enabled, forKey: .enabled)+ guard let state else { return }+ try container.encode(state.part, forKey: .part)+ try container.encode(state.wanted, forKey: .wanted)+ try container.encode(state.planned, forKey: .planned)+ try container.encode(state.applied, forKey: .applied)+ try container.encode(state.isPending, forKey: .pending)+ try container.encode(state.isPending == true ? state.delivery.rawValue : nil, forKey: .delivery)+ }}- struct PresetEntry: Codable, Sendable {+ struct PresetEntry: Encodable, Sendable {let identifier: Stringlet title: Stringlet summary: Stringlet patchSets: [String]}- struct Payload: Codable, Sendable {+ struct Payload: Encodable, Sendable {let vmName: String?let activePreset: Stringlet blockedPatches: [String]let allowedPatches: [String]let presets: [PresetEntry]let patches: [PatchEntry]+ /// Set only when a VM is named.+ let machine: MachineRecords?++ private enum CodingKeys: String, CodingKey {+ case vmName, activePreset, blockedPatches, allowedPatches, presets, patches+ case planRecorded, receiptRecorded, receiptParts, installed, pendingPatches+ }++ func encode(to encoder: any Encoder) throws {+ var container = encoder.container(keyedBy: CodingKeys.self)+ try container.encodeIfPresent(vmName, forKey: .vmName)+ try container.encode(activePreset, forKey: .activePreset)+ try container.encode(blockedPatches, forKey: .blockedPatches)+ try container.encode(allowedPatches, forKey: .allowedPatches)+ try container.encode(presets, forKey: .presets)+ try container.encode(patches, forKey: .patches)+ guard let machine else { return }+ try container.encode(machine.plan != nil, forKey: .planRecorded)+ try container.encode(machine.receipt != nil, forKey: .receiptRecorded)+ try container.encode(machine.receipt.map { $0.parts.keys.sorted() }, forKey: .receiptParts)+ try container.encode(machine.installed, forKey: .installed)+ let known = patches.compactMap { $0.state?.isPending }+ try container.encode(+ known.isEmpty ? nil : known.count(where: { $0 }),+ forKey: .pendingPatches,+ )+ }}/// The patches a preset turns on, before any version gate.@@ -82,21 +212,44 @@ public struct VPhonePatchCatalogReport: Sendable {return result}+ /// The patches this VM's choice leaves on, before any version gate.+ public func selectedPatches() -> Set<String> {+ let presetSets = Set(activePreset.patchSets.map(\.identifier))+ let included = Self.patchesInPreset(activePreset)+ let allowed = Set(selection.allowedPatches)+ let blocked = Set(selection.blockedPatches)+ var result: Set<String> = []+ for set in FirmwarePatchSetCatalog.bundled where presetSets.contains(set.identifier) {+ for patch in set.patches+ where (included.contains(patch.identifier) || allowed.contains(patch.identifier))+ && !blocked.contains(patch.identifier)+ {+ result.insert(patch.identifier)+ }+ }+ return result+ }++ /// Each patch compared across the VM's records, or nil with no VM.+ public func states() -> [FirmwarePatchDrift.PatchState]? {+ machine?.states(selected: selectedPatches())+ }+/// 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)+ let selected = selectedPatches()+ let states = Dictionary(+ (states() ?? []).map { ($0.identifier, $0) },+ uniquingKeysWith: { first, _ in first },+ )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,@@ -106,10 +259,9 @@ public struct VPhonePatchCatalogReport: Sendable {target: patch.target.description,applicability: patch.applicability.description,bootEssential: patch.bootEssential,- inPreset: inPreset,- enabled: setIsInPreset- && (inPreset || allowed.contains(patch.identifier))- && !blocked.contains(patch.identifier),+ inPreset: included.contains(patch.identifier),+ enabled: selected.contains(patch.identifier),+ state: states[patch.identifier],))}}@@ -131,6 +283,7 @@ public struct VPhonePatchCatalogReport: Sendable {)},patches: entries(),+ machine: machine,)let encoder = JSONEncoder()encoder.outputFormatting = [.prettyPrinted, .sortedKeys]@@ -140,7 +293,7 @@ public struct VPhonePatchCatalogReport: Sendable {// MARK: - Text- public func text() -> String {+ public func text(libraryArguments: String = "") -> String {var lines: [String] = []if let vmName {lines.append("VM: \(vmName)")@@ -155,6 +308,20 @@ public struct VPhonePatchCatalogReport: Sendable {if !selection.allowedPatches.isEmpty {lines.append("On: \(selection.allowedPatches.sorted().joined(separator: ", "))")}+ if let machine {+ lines.append("Plan: " + (machine.plan.map {+ "preset \($0.presetIdentifier), \($0.enabledPatches.count) patches (last fw patch)"+ } ?? "none — fw patch has not run"))+ lines.append("Applied: " + (machine.receipt.map {+ "parts recorded: \($0.parts.keys.sorted { Self.partOrder($0) < Self.partOrder($1) }.joined(separator: ", "))"+ } ?? "no receipt — what the guest runs is not recorded"))+ let installed = switch machine.installed {+ case true?: "yes"+ case false?: "no (cfw install has not finished)"+ case nil: "unknown"+ }+ lines.append("Installed: \(installed)")+ }lines.append("")lines.append("Presets:")@@ -182,9 +349,76 @@ public struct VPhonePatchCatalogReport: Sendable {if entry.bootEssential {notes.append("boot-essential")}+ if let state = entry.state, state.isPending == true {+ notes.append(state.wanted ? "not applied yet" : "still applied")+ }let suffix = notes.isEmpty ? "" : " (\(notes.joined(separator: ", ")))"lines.append(" \(box) \(entry.identifier)\(suffix)")}++ if let vmName, let machine, let states = states() {+ let pending = states.filter { $0.isPending == true }+ if pending.isEmpty {+ if states.contains(where: { $0.isPending != nil }) {+ lines.append("")+ lines.append("Every patch matches what is recorded for this machine.")+ }+ } else if machine.installed == true {+ lines.append("")+ lines.append("\(pending.count) patch(es) differ from what the guest has. To apply them:")+ lines += Self.pendingSteps(pending, vmName: vmName, libraryArguments: libraryArguments)+ } else {+ lines.append("")+ lines.append("\(pending.count) patch(es) differ from the last fw patch. The next fw patch,"+ + " restore and cfw install build the machine with this selection.")+ }+ }return lines.joined(separator: "\n")}++ // MARK: - Pending Steps++ /// A part's position: boot-chain components in boot order, then the guest.+ static func partOrder(_ part: String) -> Int {+ let order = VPhoneFirmwareComponent.allCases.map(\.rawValue) + [VPhoneVirtualMachinePatchReceipt.guestPart]+ return order.firstIndex(of: part) ?? order.count+ }++ /// What each part still needs on an installed VM, grouped by part: the+ /// step that delivers it, then each patch with the state it is changing to.+ ///+ /// `libraryArguments` is appended to every command shown, so a VM outside+ /// the default library gets a command that finds it.+ public static func pendingSteps(+ _ pending: [FirmwarePatchDrift.PatchState],+ vmName: String,+ libraryArguments: String = "",+ ) -> [String] {+ let vm = vmName + libraryArguments+ let byPart = Dictionary(grouping: pending, by: \.part)+ var lines: [String] = []+ for part in byPart.keys.sorted(by: { partOrder($0) < partOrder($1) }) {+ let states = byPart[part] ?? []+ guard let delivery = states.first?.delivery else { continue }+ let step = switch delivery {+ case .firmwarePatch:+ "run `vphone-cli fw patch \(vm)`; it takes effect at the next boot."+ + " It needs the VM's restore tree (kept with `--keep-artifacts`)."+ case .restore where part == VPhoneFirmwareComponent.iBSS.rawValue+ || part == VPhoneFirmwareComponent.iBEC.rawValue:+ "used only while restoring, so the change matters at the next restore and not to this guest."+ case .restore:+ "only a restore writes \(part), and restoring in place"+ + " (`restore --no-erase`) is not validated yet."+ case .updateEnvironment:+ "run `sudo vphone-cli cfw update-environment \(vm)`"+ + " (in Launchpad: Update Guest Environment), with the machine off."+ }+ lines.append(" \(part): \(step)")+ for state in states.sorted(by: { $0.identifier < $1.identifier }) {+ lines.append(" \(state.wanted ? "on " : "off") \(state.identifier)")+ }+ }+ return lines+ }}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchPresetStore.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchPresetStore.swiftindex 8fda4eb3..87c440e3 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchPresetStore.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhonePatchPresetStore.swift@@ -105,11 +105,124 @@ public struct VPhoneVirtualMachinePatchPlan: Codable, Sendable, Hashable {}}+/// What is live in the guest now, part by part.+///+/// `PatchSelection.plist` is what the owner wants and `PatchPlan.plist` is what+/// the last `fw patch` built; neither says what the guest actually runs. A+/// boot-chain file patched in the restore tree reaches the guest only when a+/// restore flashes it, and a guest patch only when `cfw install` writes it. Each+/// step that puts bytes into the guest replaces its own part here, so the+/// difference between this and the plan is exactly what a change still has to+/// reach.+///+/// Parts are keyed by ``part(for:)``: a boot-chain component's raw value for a+/// `.firmware` target, ``guestPart`` for everything `cfw install` writes.+public struct VPhoneVirtualMachinePatchReceipt: Codable, Sendable, Hashable {+ public struct Entry: Codable, Sendable, Hashable {+ /// The enabled patch identifiers whose bytes are in this part, sorted.+ public var patches: [String]+ /// The verb that wrote the part: `fw patch`, `restore`, `cfw install`, …+ public var writer: String+ /// The `VPhone.bundle` version that wrote it, when known.+ public var bundleVersion: String?+ public var date: Date+ /// Selected patches the writer found nothing to do for on this guest:+ /// a repair for hardware it does not have, a spoof with no value set.+ /// They are neither live nor missing, so they never count as drift.+ public var notApplicable: [String]++ public init(+ patches: some Sequence<String>,+ writer: String,+ bundleVersion: String?,+ date: Date = Date(),+ notApplicable: some Sequence<String> = [String](),+ ) {+ self.patches = Array(Set(patches)).sorted()+ self.writer = writer+ self.bundleVersion = bundleVersion+ self.date = date+ self.notApplicable = Array(Set(notApplicable)).sorted()+ }++ private enum CodingKeys: String, CodingKey {+ case patches = "Patches"+ case writer = "Writer"+ case bundleVersion = "BundleVersion"+ case date = "Date"+ case notApplicable = "NotApplicable"+ }++ public init(from decoder: any Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ patches = try container.decode([String].self, forKey: .patches)+ writer = try container.decode(String.self, forKey: .writer)+ bundleVersion = try container.decodeIfPresent(String.self, forKey: .bundleVersion)+ date = try container.decode(Date.self, forKey: .date)+ notApplicable = try container.decodeIfPresent([String].self, forKey: .notApplicable) ?? []+ }+ }++ public static let guestPart = "Guest"++ public var parts: [String: Entry]++ public init(parts: [String: Entry] = [:]) {+ self.parts = parts+ }++ /// The part a patch with this target lives in.+ public static func part(for target: VPhonePatchTarget) -> String {+ if case let .firmware(component) = target {+ return component.rawValue+ }+ return guestPart+ }++ /// Every patch identifier live in some part.+ public var appliedPatches: Set<String> {+ Set(parts.values.flatMap(\.patches))+ }++ /// Replaces one part. A writer records every part it wrote, including one+ /// it left with no patches, so a part that was reverted reads as empty+ /// rather than as unknown.+ public mutating func record(+ _ part: String,+ patches: some Sequence<String>,+ writer: String,+ bundleVersion: String?,+ notApplicable: some Sequence<String> = [String](),+ ) {+ parts[part] = Entry(patches: patches, writer: writer, bundleVersion: bundleVersion, notApplicable: notApplicable)+ }++ private enum CodingKeys: String, CodingKey {+ case parts = "Parts"+ }++ public func encoded() throws -> Data {+ let encoder = PropertyListEncoder()+ encoder.outputFormat = .xml+ return try encoder.encode(self)+ }++ public static func decode(_ data: Data) throws -> Self {+ try PropertyListDecoder().decode(Self.self, from: data)+ }+}+// MARK: - Storepublic enum VPhonePatchPresetStore {public static let selectionFileName = "PatchSelection.plist"public static let planFileName = "PatchPlan.plist"+ /// Written by whatever puts patched bytes into the guest; see+ /// ``VPhoneVirtualMachinePatchReceipt``. Root writers (`cfw install`) go+ /// through the VM's confined directory with ``VPhoneVirtualMachinePatchReceipt/encoded()``+ /// rather than ``write(_:forVM:)``, and leave the file mode `0777` like+ /// every other host VM artifact.+ public static let receiptFileName = "PatchReceipt.plist"// MARK: Presets@@ -213,6 +326,29 @@ public enum VPhonePatchPresetStore {try write(plan, to: directory.appendingPathComponent(planFileName))}+ // MARK: VM Receipt++ /// What is live in the guest, or nil for a VM no receipt-writing build has+ /// touched — that VM's state is unknown, not empty.+ public static func receipt(forVM directory: URL) -> VPhoneVirtualMachinePatchReceipt? {+ let url = directory.appendingPathComponent(receiptFileName)+ guard let data = try? Data(contentsOf: url) else { return nil }+ return try? VPhoneVirtualMachinePatchReceipt.decode(data)+ }++ /// Reads, changes and writes the receipt in one step, starting from an+ /// empty one when the VM has none.+ public static func updateReceipt(+ forVM directory: URL,+ _ body: (inout VPhoneVirtualMachinePatchReceipt) -> Void,+ ) throws {+ var receipt = receipt(forVM: directory) ?? VPhoneVirtualMachinePatchReceipt()+ body(&receipt)+ let url = directory.appendingPathComponent(receiptFileName)+ try receipt.encoded().write(to: url, options: .atomic)+ try? FileManager.default.setAttributes([.posixPermissions: 0o777], ofItemAtPath: url.path)+ }+private static func write(_ value: some Encodable, to url: URL) throws {let encoder = PropertyListEncoder()encoder.outputFormat = .xmldiff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swiftindex 117d5ff7..ee99c9da 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift@@ -1,6 +1,8 @@import ArgumentParser+import FirmwarePatcherimport Foundationimport VPhoneCoreKit+import VPhonePatchKitimport VPhoneRestore// MARK: - Verbosity → restore logging@@ -111,6 +113,7 @@ struct VPhoneRestoreCommand: ParsableCommand {onEvent: onEvent,)recordRestoreVersions(bundle: bundle)+ recordRestoredPatches(bundle: bundle)}/// Snapshot the just-restored iOS + cloudOS versions to `restore-info.json`,@@ -131,6 +134,48 @@ struct VPhoneRestoreCommand: ParsableCommand {FileHandle.standardError.write(Data("warning: could not write restore-info.json: \(error)\n".utf8))}}++ /// Record in the VM's patch receipt what the restore just flashed: the+ /// boot-chain parts `fw patch` built into the restore tree, as its+ /// `PatchPlan.plist` lists them. Every restored part is recorded, empty+ /// ones included, so a part with everything off reads as empty rather+ /// than unknown. With no plan there is nothing to say what the restore+ /// tree carried, and the receipt is left alone.+ ///+ /// Best-effort like the versions above: the restore already succeeded.+ ///+ /// The `Guest` part is recorded empty whatever the plan says: erase and+ /// `--no-erase` both re-image the system volume, so nothing `cfw install`+ /// wrote survives a restore until the next install records it again.+ private func recordRestoredPatches(bundle: VPhoneBundle) {+ let plan = VPhonePatchPresetStore.plan(forVM: bundle.url)+ let parts = plan.map { FirmwarePatchDrift.restoredParts(enabledPatches: Set($0.enabledPatches)) } ?? [:]+ do {+ try VPhonePatchPresetStore.updateReceipt(forVM: bundle.url) { receipt in+ receipt.record(+ VPhoneVirtualMachinePatchReceipt.guestPart,+ patches: [String](),+ writer: "restore",+ bundleVersion: nil,+ )+ for (component, patches) in parts {+ receipt.record(+ VPhoneVirtualMachinePatchReceipt.part(for: .firmware(component)),+ patches: patches,+ writer: "restore",+ // No helper reads the running VPhone.bundle's version yet.+ bundleVersion: nil,+ )+ }+ }+ print("[restore] recorded \(parts.values.map(\.count).reduce(0, +)) boot-chain patches"+ + " in \(VPhonePatchPresetStore.receiptFileName)")+ } catch {+ FileHandle.standardError.write(Data(+ "warning: could not write \(VPhonePatchPresetStore.receiptFileName): \(error)\n".utf8,+ ))+ }+ }}// MARK: - recovery-probe@@ -234,6 +279,16 @@ struct VPhoneCustomFirmwareInstallCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "install",abstract: "Install CFW into a VM bundle via host mount",+ discussion: """+ The boot chain follows the plan `fw patch` resolved; the guest half —+ the dyld cache, the guest Mach-Os and files, the entitlements and the+ Preboot device tree — follows the VM's current patch selection, both+ ways, so a `fw set-patches` since the last `fw patch` takes effect here+ and a patch turned off is reverted from its backup. Records the guest+ half of the patch receipt (PatchReceipt.plist) on success.++ Needs a prepared restore tree and root; the VM must be powered off.+ """,)@OptionGroup var lib: VPhoneLibraryOption@@ -294,24 +349,33 @@ struct VPhoneCustomFirmwareInstallCommand: ParsableCommand {/// replacing a library in a running guest over the API cannot help either,/// because a daemon keeps the copy it mapped at launch.///-/// Deliberately narrow. It writes only the files a full install writes into the-/// guest, runs no patch, injects nothing, and leaves the recorded variant-/// alone, so it cannot turn a half-built VM into something that looks-/// installed. A VM that was never installed is refused rather than half-filled.+/// It applies the whole guest half of an install against an installed VM,+/// without the restore tree: the dyld cache verbs, every guest Mach-O and file+/// patch, the entitlement patches and the Preboot device-tree repairs, matched+/// to the VM's current selection both ways. A patch the owner has turned off is+/// reverted — a Mach-O or file from its backup, the device tree to its backup,+/// a dyld patch from the undo log the install recorded. The two steps that need+/// the restore tree, the cryptex copy and the GPU bundle, are skipped (an+/// installed guest already carries both); the recorded `jb` variant is left+/// alone. A VM that was never installed is refused rather than half-filled.struct VPhoneCustomFirmwareUpdateEnvironmentCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "update-environment",- abstract: "Redeploy vphoned and the guest dylibs into an installed VM (VM must be off)",+ abstract: "Match an installed VM's guest patches to its current selection (VM must be off)",discussion: """- Puts back only what this bundle ships into the guest: vphoned and its- launch daemon, the guest dylibs in /usr/lib, and the libmisfix defaults- if the VM has none. No firmware patch runs, no load command is injected,- no cryptex or GPU work happens, and the VM's recorded variant does not- change.-- Use it to move an existing VM onto a newer bundle without rebuilding it.- A library the VM does not already have is left out, because its absence- means the VM's patch plan never selected it.+ Re-applies the guest half of an install from the VM's current patch+ selection, without the restore tree. vphoned, its launch daemon, the+ guest dylibs and the libmisfix defaults are redeployed as before; on top+ of that, every guest Mach-O, file, entitlement, dyld-cache and Preboot+ device-tree patch is brought to match the selection — turned on if the+ owner has selected it since the last install, and reverted from its+ backup or the dyld undo log if the owner has turned it off. Records the+ guest half of the patch receipt (PatchReceipt.plist) on success.++ A dyld-cache patch on a VM installed before the undo log existed cannot+ be reverted and is reported and left in place. The cryptex copy and the+ GPU bundle are skipped (they need the restore tree; an installed guest+ has them already), and the VM's recorded variant does not change.An iPad VM's audio repair needs the iPad's own DeviceTree.<board>.im4pin the VM's FirmwareOriginals. When a VM patched by an older build has@@ -319,7 +383,9 @@ struct VPhoneCustomFirmwareUpdateEnvironmentCommand: ParsableCommand {its BuildManifest) and kept there; without that IPSW the repair isskipped with a [!] line naming the fix.- Needs root, and the VM must be powered off.+ Use it to move an existing VM onto a newer bundle, or to apply a+ `fw set-patches` change, without rebuilding it. Needs root, and the VM+ must be powered off.""",)diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstringsindex 87528d71..21d7bc9b 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings@@ -4904,38 +4904,13 @@}}},- "Fixed once the machine is installed" : {+ "Applied when the machine is installed" : {"localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Fixed once the machine is installed"- }- },- "ja" : {- "stringUnit" : {- "state" : "translated",- "value" : "マシンのインストール後は変更できません"- }- },- "ko" : {- "stringUnit" : {- "state" : "translated",- "value" : "머신을 설치한 후에는 변경할 수 없음"- }- },- "vi" : {- "stringUnit" : {- "state" : "translated",- "value" : "Không thể thay đổi sau khi cài máy ảo"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "虚拟机创建后即固定"- }- }+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Applied when the machine is installed" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "マシンのインストール時に適用されます" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "머신을 설치할 때 적용됨" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Được áp dụng khi cài máy ảo" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "在安装虚拟机时应用" } }}},"Free disk space" : {@@ -13123,13 +13098,94 @@"zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "默认" } }}},- "Fixed when the machine was created." : {+ "The Core Bundle that built the boot chain when the machine was created." : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "The Core Bundle that built the boot chain when the machine was created." } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "マシンの作成時にブートチェーンを構築したコアバンドルです。" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "머신을 만들 때 부트 체인을 빌드한 코어 번들입니다." } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Bundle lõi đã dựng chuỗi khởi động khi tạo máy." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "创建虚拟机时构建启动链的核心 Bundle。" } }+ }+ },+ "Overrides" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Overrides" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "変更" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "변경 사항" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Thay đổi" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "更改" } }+ }+ },+ "%lld changed from the preset" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "%lld changed from the preset" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "プリセットから %lld 件を変更" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "프리셋에서 %lld개 변경" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Đã đổi %lld so với cấu hình sẵn" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "相对预设更改了 %lld 个" } }+ }+ },+ "Off: %@" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Off: %@" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "オフ:%@" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "끔: %@" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Tắt: %@" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "关闭:%@" } }+ }+ },+ "On: %@" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "On: %@" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "オン:%@" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "켬: %@" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Bật: %@" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "启用:%@" } }+ }+ },+ "Not Applied" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Not Applied" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "未適用" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "적용 안 됨" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Chưa áp dụng" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "未应用" } }+ }+ },+ "^[%lld patch](inflect: true)" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "^[%lld patch](inflect: true)" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%lld 件のパッチ" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "패치 %lld개" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "%lld bản vá" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "%lld 个补丁" } }+ }+ },+ "The guest has every patch this machine is set to." : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "The guest has every patch this machine is set to." } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "このマシンに設定したパッチはすべてゲストに適用されています。" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "이 머신에 설정한 패치가 모두 게스트에 적용되어 있습니다." } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Máy khách đã có mọi bản vá được đặt cho máy này." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "客户机已包含为此虚拟机设定的全部补丁。" } }+ }+ },+ "The patch choice changed after the guest was built. Run vphone-cli fw patches %@ to see each patch and the step that applies it." : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "The patch choice changed after the guest was built. Run vphone-cli fw patches %@ to see each patch and the step that applies it." } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "ゲストの構築後にパッチの選択が変更されました。各パッチと適用手順を確認するには、vphone-cli fw patches %@ を実行してください。" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "게스트를 빌드한 뒤 패치 선택이 바뀌었습니다. 각 패치와 적용 단계를 보려면 vphone-cli fw patches %@ 를 실행하십시오." } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Lựa chọn bản vá đã thay đổi sau khi máy khách được dựng. Hãy chạy vphone-cli fw patches %@ để xem từng bản vá và bước áp dụng nó." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "客户机构建后补丁选择已更改。运行 vphone-cli fw patches %@ 查看每个补丁及应用它的步骤。" } }+ }+ },+ "Unavailable" : {"localizations" : {- "en" : { "stringUnit" : { "state" : "translated", "value" : "Fixed when the machine was created." } },- "ja" : { "stringUnit" : { "state" : "translated", "value" : "マシンの作成時に固定されています。" } },- "ko" : { "stringUnit" : { "state" : "translated", "value" : "머신을 만들 때 고정되었습니다." } },- "vi" : { "stringUnit" : { "state" : "translated", "value" : "Được cố định khi tạo máy." } },- "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "在创建机器时已固定。" } }+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Unavailable" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "利用できません" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "사용할 수 없음" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Không khả dụng" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "不可用" } }}},"Guest Environment" : {@@ -13150,13 +13206,13 @@"zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "主机程序" } }}},- "Host programs change at the next start. The guest environment is updated now on stopped machines; running machines keep theirs until it is updated later. The boot chain and patches stay as they were when the machine was created." : {+ "Host programs change at the next start. The guest environment is updated now on stopped machines; running machines keep theirs until it is updated later. Guest patches follow each machine’s patch choice when its guest environment is updated. The boot chain stays as it was built." : {"localizations" : {- "en" : { "stringUnit" : { "state" : "translated", "value" : "Host programs change at the next start. The guest environment is updated now on stopped machines; running machines keep theirs until it is updated later. The boot chain and patches stay as they were when the machine was created." } },- "ja" : { "stringUnit" : { "state" : "translated", "value" : "ホストプログラムは次回の起動時に切り替わります。停止中のマシンではゲスト環境を今すぐ更新します。実行中のマシンは、後で更新するまで現在のゲスト環境のままです。ブートチェーンとパッチはマシン作成時のままです。" } },- "ko" : { "stringUnit" : { "state" : "translated", "value" : "호스트 프로그램은 다음 시작부터 바뀝니다. 정지된 머신은 게스트 환경을 지금 업데이트하고, 실행 중인 머신은 나중에 업데이트할 때까지 기존 환경을 유지합니다. 부트 체인과 패치는 머신을 만들 때 그대로 유지됩니다." } },- "vi" : { "stringUnit" : { "state" : "translated", "value" : "Chương trình máy chủ sẽ thay đổi từ lần khởi động tiếp theo. Môi trường máy khách được cập nhật ngay trên các máy đang dừng; máy đang chạy giữ môi trường hiện tại cho đến khi được cập nhật sau. Chuỗi khởi động và các bản vá giữ nguyên như khi tạo máy." } },- "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "主机程序在下次启动时切换。已停止的机器会立即更新客户机环境;正在运行的机器保留原有环境,直到之后再更新。启动链和补丁保持创建机器时的状态。" } }+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Host programs change at the next start. The guest environment is updated now on stopped machines; running machines keep theirs until it is updated later. Guest patches follow each machine’s patch choice when its guest environment is updated. The boot chain stays as it was built." } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "ホストプログラムは次回の起動時に切り替わります。停止中のマシンではゲスト環境を今すぐ更新します。実行中のマシンは、後で更新するまで現在のゲスト環境のままです。ゲストのパッチは、ゲスト環境の更新時に各マシンのパッチ選択に従います。ブートチェーンは構築時のままです。" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "호스트 프로그램은 다음 시작부터 바뀝니다. 정지된 머신은 게스트 환경을 지금 업데이트하고, 실행 중인 머신은 나중에 업데이트할 때까지 기존 환경을 유지합니다. 게스트 패치는 게스트 환경을 업데이트할 때 각 머신의 패치 선택을 따릅니다. 부트 체인은 빌드된 그대로 유지됩니다." } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Chương trình máy chủ sẽ thay đổi từ lần khởi động tiếp theo. Môi trường máy khách được cập nhật ngay trên các máy đang dừng; máy đang chạy giữ môi trường hiện tại cho đến khi được cập nhật sau. Các bản vá máy khách theo lựa chọn bản vá của từng máy khi môi trường máy khách được cập nhật. Chuỗi khởi động giữ nguyên như khi được dựng." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "主机程序在下次启动时切换。已停止的机器会立即更新客户机环境;正在运行的机器保留原有环境,直到之后再更新。客户机补丁在更新客户机环境时按各机器的补丁选择应用。启动链保持构建时的状态。" } }}},"Install it in Core Bundle, or choose another version for this machine." : {@@ -13231,13 +13287,13 @@"zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "%@ 的核心 Bundle 未安装。请为它选择其他核心 Bundle。" } }}},- "The boot chain and patches are fixed when the machine is created; host programs and the guest environment can be changed later." : {+ "The boot chain is built when the machine is created. Host programs, the guest environment and guest patches can be changed later." : {"localizations" : {- "en" : { "stringUnit" : { "state" : "translated", "value" : "The boot chain and patches are fixed when the machine is created; host programs and the guest environment can be changed later." } },- "ja" : { "stringUnit" : { "state" : "translated", "value" : "ブートチェーンとパッチはマシンの作成時に固定されます。ホストプログラムとゲスト環境は後から変更できます。" } },- "ko" : { "stringUnit" : { "state" : "translated", "value" : "부트 체인과 패치는 머신을 만들 때 고정됩니다. 호스트 프로그램과 게스트 환경은 나중에 변경할 수 있습니다." } },- "vi" : { "stringUnit" : { "state" : "translated", "value" : "Chuỗi khởi động và các bản vá được cố định khi tạo máy; chương trình máy chủ và môi trường máy khách có thể thay đổi sau." } },- "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "启动链和补丁在创建机器时固定;主机程序和客户机环境之后仍可更改。" } }+ "en" : { "stringUnit" : { "state" : "translated", "value" : "The boot chain is built when the machine is created. Host programs, the guest environment and guest patches can be changed later." } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "ブートチェーンはマシンの作成時に構築されます。ホストプログラム、ゲスト環境、ゲストのパッチは後から変更できます。" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "부트 체인은 머신을 만들 때 빌드됩니다. 호스트 프로그램, 게스트 환경, 게스트 패치는 나중에 변경할 수 있습니다." } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Chuỗi khởi động được dựng khi tạo máy. Chương trình máy chủ, môi trường máy khách và các bản vá máy khách có thể thay đổi sau." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "启动链在创建机器时构建。主机程序、客户机环境和客户机补丁之后仍可更改。" } }}},"The guest environment is from %@." : {diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadChangeBundleView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadChangeBundleView.swiftindex 6a5033cd..597248f4 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadChangeBundleView.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadChangeBundleView.swift@@ -52,7 +52,7 @@ struct VPhoneLaunchpadChangeBundleView: View {}Toggle("Update guest environment", isOn: $updatesEnvironment)} footer: {- Text("Host programs change at the next start. The guest environment is updated now on stopped machines; running machines keep theirs until it is updated later. The boot chain and patches stay as they were when the machine was created.")+ Text("Host programs change at the next start. The guest environment is updated now on stopped machines; running machines keep theirs until it is updated later. Guest patches follow each machine’s patch choice when its guest environment is updated. The boot chain stays as it was built.").foregroundStyle(.secondary)}}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swiftindex fe215722..26a811cc 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift@@ -78,6 +78,11 @@ struct VPhoneLaunchpadMachineInspector: View {var onChangeBundle: (VPhoneLaunchpadMachine) -> Void = { _ in }@Environment(VPhoneLaunchpadModel.self) private var model@State private var showsCommands = false+ @State private var patchCatalog: VPhoneLaunchpadPatchCatalog?+ @State private var patchCatalogError: String?+ /// The machine the catalogue above was read for, so another machine's+ /// patches never show while its own are read.+ @State private var patchCatalogMachine: VPhoneLaunchpadMachinePath?private var library: VPhoneLaunchpadMachineLibrary {model.machines@@ -117,6 +122,8 @@ struct VPhoneLaunchpadMachineInspector: View {coreBundleSection+ patchesSection+Section("Hardware") {LabeledContent("CPU", value: String(localized: "\(machine.cpuCount) cores"))LabeledContent("Memory", value: VPhoneLaunchpadMachinesView.memory(machine.memoryMB))@@ -159,6 +166,9 @@ struct VPhoneLaunchpadMachineInspector: View {}}.formStyle(.grouped)+ .task(id: patchReadKey) {+ await loadPatches()+ }.sheet(isPresented: $showsCommands) {VPhoneLaunchpadCommandHistoryView().environment(model)@@ -194,7 +204,7 @@ struct VPhoneLaunchpadMachineInspector: View {layer("Boot Chain",binding?.bootChain ?? String(localized: "Unknown"),- help: String(localized: "Fixed when the machine was created."),+ help: String(localized: "The Core Bundle that built the boot chain when the machine was created."),)HStack {Spacer()@@ -204,6 +214,113 @@ struct VPhoneLaunchpadMachineInspector: View {}}+ // MARK: - Patches++ /// What a patch read depends on: the machine, the bundle that reads it,+ /// and the run state, so a finished update or install is read again.+ private struct PatchReadKey: Equatable {+ let machine: VPhoneLaunchpadMachinePath+ let bundle: String?+ let state: VPhoneLaunchpadMachineLibrary.RunState+ }++ private var patchReadKey: PatchReadKey {+ PatchReadKey(+ machine: machine.path,+ bundle: library.bundleVersion(for: machine.path),+ state: library.state(of: machine.path),+ )+ }++ /// The machine's patch choice, read only. The choice is changed with+ /// `vphone-cli fw set-patches`; this shows the preset, how many boxes+ /// differ from it, and, when the machine's bundle reports it, how many+ /// patches have not reached the guest yet. An older bundle does not+ /// report the last, and the row is left out.+ @ViewBuilder+ private var patchesSection: some View {+ if library.creations[machine.path]?.isRunning != true {+ Section("Patches") {+ if let catalog = patchCatalog, patchCatalogMachine == machine.path {+ LabeledContent(+ "Preset",+ value: catalog.preset(catalog.activePreset)?.displayTitle ?? catalog.activePreset,+ )+ LabeledContent("Overrides") {+ Text(catalog.overrideCount == 0+ ? String(localized: "None")+ : String(localized: "\(catalog.overrideCount) changed from the preset"))+ .help(overridesHelp(catalog))+ }+ if catalog.installed == true, let pending = catalog.pendingPatches {+ LabeledContent("Not Applied") {+ HStack(spacing: 4) {+ if pending > 0 {+ Image(systemName: "exclamationmark.triangle.fill")+ .foregroundStyle(.yellow)+ .imageScale(.small)+ }+ if pending == 0 {+ Text("None")+ } else {+ Text("^[\(pending) patch](inflect: true)")+ }+ }+ .help(pending == 0+ ? String(localized: "The guest has every patch this machine is set to.")+ : String(localized: "The patch choice changed after the guest was built. Run vphone-cli fw patches \(machine.name) to see each patch and the step that applies it."))+ }+ }+ } else if let patchCatalogError {+ Text("Unavailable")+ .foregroundStyle(.secondary)+ .help(patchCatalogError)+ } else {+ ProgressView()+ .controlSize(.small)+ .frame(maxWidth: .infinity)+ }+ }+ }+ }++ private func overridesHelp(_ catalog: VPhoneLaunchpadPatchCatalog) -> String {+ var lines: [String] = []+ if !catalog.blockedPatches.isEmpty {+ lines.append(String(localized: "Off: \(catalog.blockedPatches.joined(separator: ", "))"))+ }+ if !catalog.allowedPatches.isEmpty {+ lines.append(String(localized: "On: \(catalog.allowedPatches.joined(separator: ", "))"))+ }+ return lines.joined(separator: "\n")+ }++ private func loadPatches() async {+ let path = machine.path+ if patchCatalogMachine != path {+ patchCatalog = nil+ patchCatalogError = nil+ patchCatalogMachine = path+ }+ guard library.creations[path]?.isRunning != true else { return }+ do {+ let catalog = try await VPhoneLaunchpadPatchCatalog.read(+ using: library.commandLine(for: path),+ machine: path,+ preset: nil,+ )+ guard path == machine.path else { return }+ patchCatalog = catalog+ patchCatalogError = nil+ } catch is CancellationError {+ return+ } catch {+ guard path == machine.path else { return }+ patchCatalog = nil+ patchCatalogError = VPhoneLaunchpadError.message(for: error)+ }+ }+private func layer(_ title: LocalizedStringKey, _ value: String, warning: String? = nil, help: String) -> some View {LabeledContent(title) {HStack(spacing: 4) {diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swiftindex 08a1fa8c..d7d07e8e 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift@@ -223,7 +223,7 @@ struct VPhoneLaunchpadNewMachineView: View {}}} footer: {- Text("The boot chain and patches are fixed when the machine is created; host programs and the guest environment can be changed later.")+ Text("The boot chain is built when the machine is created. Host programs, the guest environment and guest patches can be changed later.").foregroundStyle(.secondary)}}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swiftindex 4f1655dc..b31db7f0 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swift@@ -49,6 +49,10 @@ nonisolated struct VPhoneLaunchpadPatchCatalog: Decodable, Sendable {/// Whether the preset the report was made against turns it on. What the/// checkmarks are a difference from.let inPreset: Bool+ /// Whether the machine's wanted state for this patch has not reached its+ /// guest yet. Reported only for a named machine, by a bundle that+ /// compares its records; nil otherwise.+ let pending: Bool?var id: String {identifier@@ -104,6 +108,23 @@ nonisolated struct VPhoneLaunchpadPatchCatalog: Decodable, Sendable {let presets: [Preset]let patches: [Patch]+ // Reported only for a named machine, and only by a bundle that compares a+ // machine's records. An older bundle leaves them out, and every reader+ // treats their absence as "not known".++ /// Whether `cfw install` finished on the machine; nil when unknown.+ let installed: Bool?+ /// Whether the machine has a receipt saying what its guest runs.+ let receiptRecorded: Bool?+ /// How many patches differ from what the machine's guest has, or nil when+ /// nothing records what it has.+ let pendingPatches: Int?++ /// The overrides the machine's choice makes on its preset.+ var overrideCount: Int {+ blockedPatches.count + allowedPatches.count+ }+func preset(_ identifier: String) -> Preset? {presets.first { $0.identifier == identifier }}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchSettingsView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchSettingsView.swiftindex 6eb17f96..f8d251d7 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchSettingsView.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchSettingsView.swift@@ -288,7 +288,7 @@ struct VPhoneLaunchpadPatchSettingsView: View {if selection.hasOverrides {parts.append(String(localized: "\(selection.blocked.count) turned off, \(selection.allowed.count) turned on from the preset"))}- parts.append(String(localized: "Fixed once the machine is installed"))+ parts.append(String(localized: "Applied when the machine is installed"))return parts.joined(separator: " · ")}