Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Re-patch the firmware originals, so fw patch can be run again

Lakra3d2382e2eca
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index d6715771..ea50753c 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -1554,3 +1554,74 @@ patches (issue #438), which `standard` now leaves off; see the note at the top.
SystemHook no longer loads `libvlocation.dylib`, the bundle no longer ships it,
and vphoned's `location.*` methods call IcliKit directly again. A guest that
already has `/usr/lib/libvlocation.dylib` keeps the file, but nothing loads it.
+
+## `fw patch` re-patches the originals, not its own output (2026-09-30)
+
+No new Apple binary patch. This changes how every boot-chain patch in this
+document is applied, so it is recorded here.
+
+**The defect.** `FirmwarePipeline` patched each component in place: load the
+file, run the patchers, save over the same path. Run `fw patch` a second time on
+the same VM and the patchers were handed the first run's output, found none of
+the shapes they had already replaced, and the component failed —
+`Patch site not found: iBSS`, taking the whole run down at the second component.
+`fw prepare` refuses to re-extract over an existing restore tree
+("A restore tree already exists at …. Remove it, then prepare the firmware
+again."), so there was no recovery path either: a VM could be patched exactly
+once, for its whole life. Editing a VM's `PatchSelection.plist` to turn a patch
+off and re-running was therefore impossible, which is why the only way to test a
+preset change was to build a new machine, and why hand-editing the recorded
+`PatchPlan.plist` was being used to get around it.
+
+**Not the same defect as issue #532's second failure.** That one was a single
+patcher, `DyldSharedCacheMISTrustAuthPatcher`, not recognising its own post-patch
+shape on 27.0 — a DSC patcher, over a cache `cfw install` handles, fixed on
+2026-09-30 by teaching `locateSite` the `pacibsp ; mov x0,#0 ; retab` form (see
+row 17). This one is structural and sits above every boot-chain patcher: it
+would bite even if each patcher were perfectly self-recognising, because nothing
+kept the bytes they were meant to match against.
+
+**The fix.** `FirmwarePipelineOriginals.swift`. The first run copies each
+boot-chain file into `<vmDirectory>/FirmwareOriginals/`, mirroring its path
+under the VM bundle, before anything is written; every later run loads from that
+copy. `fw patch` is idempotent by construction — same VM, same plan, same bytes
+on disk however many times it runs — and the pristine container is also put back
+immediately before `loader.save`, because `ContainerFirmwareLoader.save`
+repackages the IM4P it finds at the destination and would otherwise wrap the
+second run's payload in the first run's container.
+
+The stash is a direct child of the VM directory and never of the restore tree,
+so `findRestoreDirectory` (which matches a directory *name* containing
+"Restore") and the component globs (rooted at the restore tree, or
+non-recursive in the VM root) cannot resolve a component to its own copy.
+
+**Turning a patch off now reverts it.** When the resolved plan selects nothing
+for a component — either every patch blocked, or the whole patch set dropped so
+no patcher is built at all — the unpatched image is copied back. A component
+nobody has ever patched is not rewritten, so its modification date stays where
+the restore left it.
+
+**Two components opt out** (`restorable: false`): `Filesystem`
+(`CryptexFilesystemPatcher`) and `Manifest` (`ManifestHashPatcher`). Both name
+`BuildManifest.plist`, but neither is a patcher over that one file — the first
+rewrites cryptex images across the restore tree, the second rewrites hashes that
+describe files other steps produced. Restoring the manifest alone would describe
+a tree that no longer exists. Both are `.less`-only, and `.less` is excluded from
+the mechanism outright so a `.less` run over a CFW-patched VM cannot read "this
+variant builds no boot-chain patchers" as "put the boot chain back".
+
+**Existing VMs.** A machine patched by an earlier build has no stash, so the
+first run under the new code would adopt its already-patched bytes as the
+"original". That case is detected rather than accepted: if the component then
+fails to patch, the copy is deleted — so it never becomes the baseline — and the
+error says the VM was patched by a build that kept no originals and that the
+restore tree must be removed and `fw prepare` re-run. Only `patchSiteNotFound` is
+rewritten this way; every other failure means what it says and passes through.
+
+Covered by `FirmwarePatcherTests/Pipeline/FirmwarePipelineOriginalsTests.swift`
+(7 tests), which drives `patchComponents` over a synthetic component whose
+patcher flips one byte and — like every real patcher — reports no site once that
+byte is flipped. The real boot chain needs firmware fixtures that are not in the
+repository. The same harness with `restorable: false` reproduces the old
+failure, so the test for the fix and the test for the defect differ only in the
+descriptor.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift
index 5cd2f11d..dc3a2caf 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift
@@ -204,37 +204,114 @@ public final class FirmwarePipeline {
)
log("[*] Patching \(components.count) boot-chain components ...")
+ let allRecords = try patchComponents(components, restoreDir: restoreDir, plan: plan)
+
+ log("\n\(String(repeating: "=", count: 60))")
+ log(" All \(components.count) components processed successfully! (\(allRecords.count) total patches)")
+ log(String(repeating: "=", count: 60))
+
+ return allRecords
+ }
+
+ /// Patch every component in order, against the files under `restoreDir` and the
+ /// VM directory root.
+ ///
+ /// Each component is patched from the bytes the firmware shipped with rather
+ /// than from whatever the last run left behind, so running this twice produces
+ /// the same files as running it once — see FirmwarePipelineOriginals.swift for
+ /// why that is not how it used to work.
+ ///
+ /// Split out of ``patchAll()`` so a test can drive the loop, and with it the
+ /// originals behaviour, over a component whose patcher it controls. The real
+ /// boot chain needs firmware fixtures that are not in the repository.
+ func patchComponents(
+ _ components: [ComponentDescriptor],
+ restoreDir: URL,
+ plan: VPhonePatchPlan?,
+ ) throws -> [PatchRecord] {
var allRecords: [PatchRecord] = []
for component in components {
+ let baseDir = component.inRestoreDir ? restoreDir : vmDirectory
+ // `.less` never touches the boot chain: it runs the two whole-tree
+ // patchers and leaves every other component with no factories at all.
+ // Keeping it out of this entirely is what stops a `.less` run over an
+ // already patched VM reading "no patches here" as "put the unpatched
+ // boot chain back".
+ let keepsOriginal = variant != .less && component.restorable
+
guard !component.patcherFactories.isEmpty else {
log(" [=] \(component.name): no patches for \(variant.rawValue)")
+ // The preset dropped this component's whole patch set. If an earlier
+ // run patched it, the file on disk is now carrying patches nothing
+ // selects any more, so it goes back to how the restore left it.
+ if keepsOriginal,
+ let fileURL = try? findFile(
+ in: baseDir,
+ patterns: component.searchPatterns,
+ label: component.name,
+ ),
+ try restorePristine(to: fileURL)
+ {
+ log(" [+] \(component.name): unpatched image restored")
+ }
continue
}
- let baseDir = component.inRestoreDir ? restoreDir : vmDirectory
let fileURL = try findFile(in: baseDir, patterns: component.searchPatterns, label: component.name)
log("\n\(String(repeating: "=", count: 60))")
log(" \(component.name): \(fileURL.path)")
log(String(repeating: "=", count: 60))
- // Load
- let rawData = try loader.load(from: fileURL)
+ // Load — from the copy of the shipped file, not from the bytes the last
+ // run wrote. The first run is the one that puts it aside.
+ var sourceURL = fileURL
+ var stashedNow = false
+ if keepsOriginal {
+ (sourceURL, stashedNow) = try pristineInput(for: fileURL)
+ if sourceURL != fileURL {
+ log(stashedNow
+ ? " original: kept in \(Self.originalsDirectoryName)/"
+ : " original: re-patching the copy in \(Self.originalsDirectoryName)/")
+ }
+ }
+ let rawData = try loader.load(from: sourceURL)
log(" format: \(rawData.count) bytes")
- let (currentData, componentRecords) = try patchData(
- rawData,
- componentName: component.name,
- patcherFactories: component.patcherFactories,
- expectsPatches: expectsPatches(for: component.name, plan: plan),
- )
+ let currentData: Data
+ let componentRecords: [PatchRecord]
+ do {
+ (currentData, componentRecords) = try patchData(
+ rawData,
+ componentName: component.name,
+ patcherFactories: component.patcherFactories,
+ expectsPatches: expectsPatches(for: component.name, plan: plan),
+ )
+ } catch {
+ // A copy made this run is the one thing here that was never proved
+ // pristine, so it does not get to become the next run's baseline.
+ guard stashedNow else { throw error }
+ discardStash(for: fileURL)
+ throw staleFirmwareError(component: component.name, underlying: error)
+ }
- // A component whose every patch the preset turned off is left exactly
- // as it was found. Re-sealing an unmodified payload would rewrite a
- // signed image for no reason.
if componentRecords.isEmpty {
- log(" [=] unchanged, not rewritten")
+ // Every patch for this component is off. Re-sealing an unmodified
+ // payload would rewrite a signed image for no reason — but if an
+ // earlier run did patch it, the file on disk still has to go back.
+ if keepsOriginal, try restorePristine(to: fileURL) {
+ log(" [+] every patch is off, unpatched image restored")
+ } else {
+ log(" [=] unchanged, not rewritten")
+ }
} else {
+ // `save` repackages the container it finds at the destination, so
+ // the shipped one goes back first. Otherwise the second run would
+ // wrap its payload in the container the first run wrote, and two
+ // runs of the same plan would not produce the same file.
+ if keepsOriginal {
+ try restorePristine(to: fileURL)
+ }
try loader.save(currentData, to: fileURL)
log(" [+] saved")
}
@@ -242,10 +319,6 @@ public final class FirmwarePipeline {
allRecords.append(contentsOf: componentRecords)
}
- log("\n\(String(repeating: "=", count: 60))")
- log(" All \(components.count) components processed successfully! (\(allRecords.count) total patches)")
- log(String(repeating: "=", count: 60))
-
return allRecords
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
index 824e0f0c..74e92386 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
@@ -251,6 +251,9 @@ extension FirmwarePipeline {
))
// 8. Filesystem
+ // Not restorable: it reads BuildManifest.plist but writes cryptex images
+ // all over the restore tree, so putting the manifest back on its own
+ // would describe a tree that no longer exists. See ComponentDescriptor.
components.append(ComponentDescriptor(
name: "Filesystem",
inRestoreDir: true,
@@ -270,9 +273,12 @@ extension FirmwarePipeline {
[]
}
}(),
+ restorable: false,
))
// 9. Firmware Manifest - Only required when excluding the img4 signature patches.
+ // Not restorable, for the same reason as Filesystem: the hashes it writes
+ // describe files other steps produced, not the manifest's own bytes.
components.append(ComponentDescriptor(
name: "Manifest",
inRestoreDir: true,
@@ -287,6 +293,7 @@ extension FirmwarePipeline {
[]
}
}(),
+ restorable: false,
))
return appendingExternalPatchers(to: components, plan: plan, gate: gate, iOSBase: iOSBase)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineOriginals.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineOriginals.swift
index b61f1b58..4ebab9ee 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineOriginals.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineOriginals.swift
@@ -22,13 +22,17 @@
// the VM root) can resolve a component to its own pristine copy.
import Foundation
+import VPhoneCoreKit
import VPhonePatchKit
extension FirmwarePipeline {
// MARK: - Locations
/// The stash directory's name inside the VM bundle.
- static let originalsDirectoryName = "FirmwareOriginals"
+ ///
+ /// Defined in ``VPhoneBundleOperations`` because `fw prepare` and bundle export
+ /// have to agree about it — see the declaration there.
+ static let originalsDirectoryName = VPhoneBundleOperations.firmwareOriginalsDirectoryName
var originalsDirectory: URL {
vmDirectory.appendingPathComponent(Self.originalsDirectoryName)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Pipeline/FirmwarePipelineOriginalsTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Pipeline/FirmwarePipelineOriginalsTests.swift
new file mode 100644
index 00000000..f0a76c16
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Pipeline/FirmwarePipelineOriginalsTests.swift
@@ -0,0 +1,220 @@
+// FirmwarePipelineOriginalsTests.swift — `fw patch` is re-runnable.
+//
+// The defect these cover: the pipeline patched each boot-chain file in place, so a
+// second run fed the patchers the first run's output, they found none of the
+// shapes they had already replaced, and the component failed with
+// `Patch site not found: iBSS`. `fw prepare` refuses to re-extract over an
+// existing restore tree, so a VM could be patched exactly once. See
+// FirmwarePipelineOriginals.swift.
+//
+// The real boot chain needs firmware fixtures that are not in this repository, so
+// these drive `patchComponents` over a synthetic component with a patcher whose
+// behaviour is known: it rewrites one byte, and — like every real patcher — finds
+// nothing once that byte is already rewritten. `noOriginals` reproduces the old
+// behaviour from the same harness, so the test that proves the fix and the test
+// that proves the defect differ only in the descriptor.
+
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+import VPhonePatchKit
+
+// MARK: - Harness
+
+/// A patcher that flips `data[0]` from `0x00` to `0xAA`, and reports no site once
+/// it has been flipped — the shape every real patcher has, and the reason patching
+/// an already patched file fails instead of being a no-op.
+private final class OnceOnlyBytePatcher: Patcher {
+ let component = "iBSS"
+ let verbose = false
+ let data: Data
+
+ init(data: Data) { self.data = data }
+
+ func findAll() throws -> [PatchRecord] {
+ guard data.first == 0x00 else { return [] }
+ return [
+ PatchRecord(
+ patchID: "test-once",
+ component: component,
+ fileOffset: 0,
+ originalBytes: Data([0x00]),
+ patchedBytes: Data([0xAA]),
+ description: "flip the first byte",
+ ),
+ ]
+ }
+
+ func apply() throws -> Int { 1 }
+}
+
+/// Bytes in, bytes out. The shipped loader repackages IM4P containers, which these
+/// synthetic files are not.
+private struct RawFirmwareLoader: FirmwarePipeline.FirmwareLoader {
+ func load(from url: URL) throws -> Data { try Data(contentsOf: url) }
+ func save(_ data: Data, to url: URL) throws { try data.write(to: url) }
+}
+
+/// A VM directory holding one restore tree with one patchable file in it.
+private struct FakeVM {
+ let root: URL
+ let restoreDir: URL
+ let componentURL: URL
+
+ init() throws {
+ root = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString)
+ restoreDir = root.appendingPathComponent("iPhone17,3_26.6.2_23G90_Restore")
+ componentURL = restoreDir.appendingPathComponent("Firmware/dfu/iBSS.im4p")
+ try FileManager.default.createDirectory(
+ at: componentURL.deletingLastPathComponent(),
+ withIntermediateDirectories: true,
+ )
+ try Data([0x00, 0x11, 0x22]).write(to: componentURL)
+ }
+
+ func remove() { try? FileManager.default.removeItem(at: root) }
+
+ var componentBytes: Data { (try? Data(contentsOf: componentURL)) ?? Data() }
+
+ var stashURL: URL {
+ root.appendingPathComponent(FirmwarePipeline.originalsDirectoryName)
+ .appendingPathComponent("iPhone17,3_26.6.2_23G90_Restore/Firmware/dfu/iBSS.im4p")
+ }
+
+ func pipeline() -> FirmwarePipeline {
+ FirmwarePipeline(vmDirectory: root, variant: .jb, verbose: false, loader: RawFirmwareLoader())
+ }
+
+ /// The descriptor under test. `patched` false leaves the component with no
+ /// factories, which is what a preset that drops the whole boot-chain set does.
+ func descriptor(patched: Bool = true, restorable: Bool = true) -> FirmwarePipeline.ComponentDescriptor {
+ FirmwarePipeline.ComponentDescriptor(
+ name: "iBSS",
+ inRestoreDir: true,
+ searchPatterns: ["Firmware/dfu/iBSS.im4p"],
+ patcherFactories: patched ? [{ data, _ in OnceOnlyBytePatcher(data: data) }] : [],
+ restorable: restorable,
+ )
+ }
+}
+
+// MARK: - Tests
+
+struct FirmwarePipelineOriginalsTests {
+ @Test func `patching twice succeeds and lands on the same bytes`() throws {
+ let vm = try FakeVM()
+ defer { vm.remove() }
+ let pipeline = vm.pipeline()
+
+ let first = try pipeline.patchComponents([vm.descriptor()], restoreDir: vm.restoreDir, plan: nil)
+ let afterFirst = vm.componentBytes
+ #expect(first.count == 1)
+ #expect(afterFirst == Data([0xAA, 0x11, 0x22]))
+ #expect(FileManager.default.fileExists(atPath: vm.stashURL.path))
+ #expect(try Data(contentsOf: vm.stashURL) == Data([0x00, 0x11, 0x22]))
+
+ // The run that used to die with `Patch site not found`.
+ let second = try pipeline.patchComponents([vm.descriptor()], restoreDir: vm.restoreDir, plan: nil)
+ #expect(second.map(\.patchID) == first.map(\.patchID))
+ #expect(vm.componentBytes == afterFirst)
+
+ let third = try pipeline.patchComponents([vm.descriptor()], restoreDir: vm.restoreDir, plan: nil)
+ #expect(third.count == 1)
+ #expect(vm.componentBytes == afterFirst)
+ }
+
+ @Test func `without an original the second run still fails`() throws {
+ // Not a test of the old code: the same harness, with `restorable` off, is
+ // how Filesystem and Manifest still behave, and it pins what the stash is
+ // actually buying.
+ let vm = try FakeVM()
+ defer { vm.remove() }
+ let pipeline = vm.pipeline()
+ let descriptor = vm.descriptor(restorable: false)
+
+ _ = try pipeline.patchComponents([descriptor], restoreDir: vm.restoreDir, plan: nil)
+ #expect(!FileManager.default.fileExists(atPath: vm.stashURL.path))
+
+ #expect(throws: PatcherError.self) {
+ _ = try pipeline.patchComponents([descriptor], restoreDir: vm.restoreDir, plan: nil)
+ }
+ }
+
+ @Test func `dropping the whole set puts the unpatched image back`() throws {
+ let vm = try FakeVM()
+ defer { vm.remove() }
+ let pipeline = vm.pipeline()
+
+ _ = try pipeline.patchComponents([vm.descriptor()], restoreDir: vm.restoreDir, plan: nil)
+ #expect(vm.componentBytes == Data([0xAA, 0x11, 0x22]))
+
+ // The preset no longer names this component's patch set, so it builds no
+ // patchers at all. Before the originals existed this silently left the
+ // previous run's patches in the firmware.
+ let records = try pipeline.patchComponents(
+ [vm.descriptor(patched: false)],
+ restoreDir: vm.restoreDir,
+ plan: nil,
+ )
+ #expect(records.isEmpty)
+ #expect(vm.componentBytes == Data([0x00, 0x11, 0x22]))
+ }
+
+ @Test func `a VM patched by a build that kept no original says how to recover`() throws {
+ let vm = try FakeVM()
+ defer { vm.remove() }
+ let pipeline = vm.pipeline()
+
+ // What an older vphone-cli left behind: a patched file and no stash.
+ try Data([0xAA, 0x11, 0x22]).write(to: vm.componentURL)
+
+ let error = #expect(throws: PatcherError.self) {
+ _ = try pipeline.patchComponents([vm.descriptor()], restoreDir: vm.restoreDir, plan: nil)
+ }
+ #expect(error?.description.contains("fw prepare") == true)
+
+ // The patched bytes must not have been adopted as the original, or every
+ // later run would patch from them and fail the same way for ever.
+ #expect(!FileManager.default.fileExists(atPath: vm.stashURL.path))
+ #expect(vm.componentBytes == Data([0xAA, 0x11, 0x22]))
+ }
+
+ @Test func `a less run leaves an already patched boot chain alone`() throws {
+ let vm = try FakeVM()
+ defer { vm.remove() }
+
+ _ = try vm.pipeline().patchComponents([vm.descriptor()], restoreDir: vm.restoreDir, plan: nil)
+ #expect(vm.componentBytes == Data([0xAA, 0x11, 0x22]))
+
+ // `.less` gives every boot-chain component an empty factory list. That must
+ // not read as "these patches are off, put the firmware back".
+ let less = FirmwarePipeline(
+ vmDirectory: vm.root,
+ variant: .less,
+ verbose: false,
+ loader: RawFirmwareLoader(),
+ )
+ _ = try less.patchComponents([vm.descriptor(patched: false)], restoreDir: vm.restoreDir, plan: nil)
+ #expect(vm.componentBytes == Data([0xAA, 0x11, 0x22]))
+ }
+
+ @Test func `the stash never claims a file outside the VM directory or itself`() throws {
+ let vm = try FakeVM()
+ defer { vm.remove() }
+ let pipeline = vm.pipeline()
+
+ #expect(pipeline.originalURL(for: vm.componentURL)?.path == vm.stashURL.path)
+ #expect(pipeline.originalURL(for: URL(fileURLWithPath: "/tmp/elsewhere.im4p")) == nil)
+ #expect(pipeline.originalURL(for: vm.root) == nil)
+ #expect(pipeline.originalURL(for: vm.stashURL) == nil)
+ }
+
+ @Test func `only the two whole-tree components opt out of keeping an original`() throws {
+ let root = URL(fileURLWithPath: NSTemporaryDirectory())
+ let pipeline = FirmwarePipeline(vmDirectory: root, variant: .less, verbose: false)
+ let components = pipeline.buildComponentList(restoreDir: root, iOSBase: VPhoneVersion("26.6.2"))
+
+ let notRestorable = components.filter { !$0.restorable }.map(\.name).sorted()
+ #expect(notRestorable == ["Filesystem", "Manifest"])
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift
index 5cdf0ac2..8db399f5 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift
@@ -45,6 +45,19 @@ enum VPhoneFirmwarePreparer {
}
}
+ // No restore tree, so any kept boot-chain originals describe firmware that
+ // is no longer here. Leaving them would be worse than having none: the
+ // component paths under a same-named restore tree — and `AVPBooter*.bin`
+ // in the bundle root, whose name does not carry a version at all — would
+ // match, and the next `fw patch` would patch last firmware's bytes and
+ // save them over this one's. See FirmwarePipelineOriginals.swift.
+ let staleOriginals = bundle.url
+ .appendingPathComponent(VPhoneBundleOperations.firmwareOriginalsDirectoryName)
+ if fm.fileExists(atPath: staleOriginals.path) {
+ print("[*] Removing boot-chain originals kept for the previous firmware...")
+ try fm.removeItem(at: staleOriginals)
+ }
+
// Remote IPSWs go to one cache shared by every machine; keeping them
// inside the machine downloaded both again for each new one (#513).
// Local IPSWs are read in place and are never copied into the cache.
diff --git a/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneBundleTransfer.swift b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneBundleTransfer.swift
index 9cbfd538..0a3daf09 100644
--- a/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneBundleTransfer.swift
+++ b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneBundleTransfer.swift
@@ -87,6 +87,11 @@ public enum VPhoneBundleTransfer {
var excludes = VPhoneBundleOperations.exportExcludePatterns
if !includeIPSW {
excludes.append("*_Restore*")
+ // The kept boot-chain originals go with the restore tree they came
+ // from. On their own they describe firmware the archive does not
+ // carry, and the importer would have to delete them before its first
+ // `fw prepare` could be trusted.
+ excludes.append(VPhoneBundleOperations.firmwareOriginalsDirectoryName)
}
let total = progress != nil
@@ -132,7 +137,10 @@ public enum VPhoneBundleTransfer {
for case let url as URL in en {
guard url.path.count > prefix else { continue }
let rel = String(url.path.dropFirst(prefix))
- if !includeIPSW, rel.contains("_Restore") {
+ let originals = VPhoneBundleOperations.firmwareOriginalsDirectoryName
+ if !includeIPSW, rel.contains("_Restore")
+ || rel == originals || rel.hasPrefix(originals + "/")
+ {
en.skipDescendants(); continue
}
// The same match as VPhoneArchiveWriter's: the relative path or its
diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift
index c7843885..65c82bc5 100644
--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift
+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift
@@ -194,4 +194,16 @@ public enum VPhoneBundleOperations {
".pcc-restoration-*",
".pcc-system-*",
]
+
+ /// The directory holding each boot-chain file exactly as the restore tree laid
+ /// it down, so `fw patch` patches those bytes rather than its own output and
+ /// can be run again. `FirmwarePipeline` fills it; the name lives here because
+ /// three other things in the bundle have to agree about it: `fw prepare`
+ /// deletes it with the restore tree it describes, and export both excludes it
+ /// from a slim archive and leaves it out of the progress total.
+ ///
+ /// Deliberately outside the restore tree: `findRestoreDirectory` picks the
+ /// newest direct child whose name contains "Restore", so an originals
+ /// directory that matched would become a candidate restore tree.
+ public static let firmwareOriginalsDirectoryName = "FirmwareOriginals"
}