Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Keep the X1 lowering's undo as words, not page runs

Jacky3555f4c085d8
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index b8cf435b..9e8ce7be 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -639,6 +639,17 @@
> `system-virtualaudio-cfw-device_state_null_gate` above.
> See [Duo bring-up](Guest/iphone_duo_bringup.md).
+> **ARM64E_X1 undo as words (2026-11-03, issue #789):** the two X1 cache
+> patches (`dyld-boot-arm64e_x1_bootstrap`, `dyld-cfw-arm64e_x1_cache`) no
+> longer keep their undo as page runs in `.vphone-dsc-undo.json`. They record
+> each changed instruction's address and original word in
+> `.vphone-dsc-undo.words` beside it; the cache bytes they write are
+> unchanged. On 24A94425 the whole-cache step went from a 24.5 GB to a 3.2 GB
+> peak, the undo data from 4.4 GB to 298 MB, and each later cache verb from
+> about 20 GB to 10 MB. A log written by 2.15.0 or earlier is converted once
+> by the hidden `cfw patch-dsc-undo-words` verb before the cache patches run.
+> See [Undo words](Guest/iphone_duo_bringup.md#undo-words-instead-of-page-runs-issue-789-2026-11-03).
+
> **Foldable VM sub-type (2026-10-23):** `preboot-cfw-devicetree_foldable_vm_subtype`
> (guest system set, Preboot device-tree repair, on in `standard`, blocked in
> `tvos` and `tvos-4k`, not applicable to boards without an entry; verb
diff --git a/Research/Guest/iphone_duo_bringup.md b/Research/Guest/iphone_duo_bringup.md
index 7e224217..370e1f6c 100644
--- a/Research/Guest/iphone_duo_bringup.md
+++ b/Research/Guest/iphone_duo_bringup.md
@@ -227,6 +227,55 @@ first screen within seconds of launch. Standalone X1 binaries outside the
cache (app executables, plug-ins such as `VirtualAudio.plugin`, daemons)
still use the on-demand handler.
+### Undo words instead of page runs (issue #789, 2026-11-03)
+
+`cfw install` on a 16 GB M4 Mac mini stopped after `X1 bootstrap cache:
+228314 instruction rewrites in 2875 page run(s)` for over an hour and the
+host slowly froze. The lowering was not the problem; its undo log was. The
+chunk set captured the original bytes of every page run it wrote, and the
+verb merged them into `.vphone-dsc-undo.json` as base64. Measured on a stock
+24A94425 cache with the 2.15.0 CLI (M5 Pro, 64 GB):
+
+| Step | 2.15.0 | Words |
+| --- | --- | --- |
+| `patch-arm64e-x1-bootstrap-cache` | 3.6 s, 0.45 GB peak | 1.6–5.2 s, 0.20 GB |
+| `patch-arm64e-x1-cache` | 99 s, **24.5 GB** peak | 48–68 s, **3.2 GB** |
+| `patch-iomfb-force-kern` (the next verb, 10 sites) | 33 s, 19.6 GB | 0.03 s, 0.01 GB |
+| Undo data on the guest | 4.4 GB JSON | 1.8 KB JSON + 298 MB words |
+| `patch-dsc-revert` of all three | — | 12.5 s, 0.42 GB |
+
+Every cache verb that recorded anything after the X1 step decoded and
+re-encoded the whole 4.4 GB file, about 20 GB each.
+
+The X1 lowering now records one (address, original word) pair per
+instruction it changed, 12 bytes apiece, in `.vphone-dsc-undo.words` beside
+the JSON log (`DyldSharedCacheUndoLog.words`), and writes its page runs with
+`capturingOriginal: false`. The JSON format is unchanged, so an older CLI
+reads every other patch's records and treats the X1 patches as having none.
+Verbs that captured no words never open the words file. Two FileHandle reads
+(`DyldSharedCacheChunkSet.read`, the re-attest page loop) now drain their
+autoreleased buffers per read: without that, the remaining 9.3 GB peak was
+3.3 GB of write-phase reads plus 3.4 GB of re-attest reads, all kept alive
+until the process exited.
+
+A guest installed by 2.15.0 or earlier still holds the page runs. `cfw
+install` and `update-environment` run `cfw patch-dsc-undo-words` first,
+which keeps from each X1 run only the words that differ from the cache now.
+On the 2.15.0 log above that took 331 s with an 8.05 GB peak once (it still
+has to decode the 4.4 GB JSON), and a second run is a 0.13 s no-op. It keeps
+24,834,435 words: the 24,834,397 lowered instructions, the corecrypto HMAC
+record (8 words), and 30 words of `iomfb_force_kern` that fall inside X1 page
+runs. Reverting only the X1 patches while that one stays puts those 30 words
+back to stock, exactly as reverting the page runs did.
+
+Checks on the 24A94425 cache: the new CLI's bootstrap + whole-cache +
+force-kern output is byte-identical to 2.15.0's in all 80 chunks; reverting
+those three from words gives back the stock cryptex's 80 chunks
+byte for byte, signatures included, and so does reverting them from the
+converted 2.15.0 log. `DyldSharedCacheUndoWordsTests` covers the merge
+rule, the file format and its damage checks, page-grouped restore over a
+synthetic cache, refusal of an unmapped word, and the conversion.
+
### VirtualAudio on 27.1
The four VirtualAudio CFW patches failed on 24A94425 because every function
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift
index 9c510cc5..35b380d7 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift
@@ -326,15 +326,19 @@ public final class DyldSharedCacheChunkSet {
/// then calls `reattestRecordedWrites(in:)` cannot under-attest. Empty
/// `data` writes nothing and records nothing; the span it hands back is
/// the single byte at `vma`, and re-attesting it is a no-op.
+ ///
+ /// `capturingOriginal: false` leaves the bytes out of the undo log even
+ /// while capture is on: a caller that records its own originals, word by
+ /// word, would otherwise keep a second copy of every page run it writes.
@discardableResult
- public func write(at vma: UInt64, _ data: Data) throws -> DyldSharedCacheWriteSpan {
+ public func write(at vma: UInt64, _ data: Data, capturingOriginal: Bool = true) throws -> DyldSharedCacheWriteSpan {
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 }
+ let captured: Data? = capturingOriginal && stateLock.withLock { undoCaptureLog != nil }
? try Self.read(url: chunkURL, offset: UInt64(range.lowerBound), length: data.count)
: nil
let handle = try FileHandle(forUpdating: chunkURL)
@@ -616,12 +620,18 @@ public final class DyldSharedCacheChunkSet {
///
/// Right for the small reads — a load command, a page, a run of a few
/// kilobytes. Wrong for a whole mapping; use `window(over:)` for those.
+ ///
+ /// The pool returns the buffer FileHandle autoreleases to the caller's
+ /// ownership. A command-line run never drains one otherwise, and the X1
+ /// lowering's 212,573 page runs kept 3.3 GB of buffers alive that way.
static func read(url: URL, offset: UInt64, length: Int) throws -> Data {
guard length > 0 else { return Data() }
- let handle = try FileHandle(forReadingFrom: url)
- defer { try? handle.close() }
- try handle.seek(toOffset: offset)
- return try handle.read(upToCount: length) ?? Data()
+ return try autoreleasepool {
+ let handle = try FileHandle(forReadingFrom: url)
+ defer { try? handle.close() }
+ try handle.seek(toOffset: offset)
+ return try handle.read(upToCount: length) ?? Data()
+ }
}
/// A whole mapping, as a slice of the MAPPED chunk file.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheCodeSignature.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheCodeSignature.swift
index 6cdc9c04..c7126a83 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheCodeSignature.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheCodeSignature.swift
@@ -355,7 +355,9 @@ public enum DyldSharedCacheCodeSignature {
let slotOffset = directory.slotOffset(forPage: pageIndex)
try handle.seek(toOffset: UInt64(pageOffset))
- let pageData = try handle.read(upToCount: directory.pageSize) ?? Data()
+ // FileHandle hands back autoreleased buffers, and a command-line
+ // run has no pool to drain them: 200,000 pages kept 3.4 GB alive.
+ let pageData = try autoreleasepool { try handle.read(upToCount: directory.pageSize) } ?? Data()
guard pageData.count == directory.pageSize else {
skip(.shortPageRead(
chunk: chunkURL.lastPathComponent,
@@ -368,7 +370,7 @@ public enum DyldSharedCacheCodeSignature {
let newHash = Data(SHA256.hash(data: pageData))
try handle.seek(toOffset: UInt64(slotOffset))
- let oldHash = try handle.read(upToCount: directory.hashSize) ?? Data()
+ let oldHash = try autoreleasepool { try handle.read(upToCount: directory.hashSize) } ?? Data()
guard oldHash != newHash else {
alreadyAttested.append(
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheUndoLog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheUndoLog.swift
index a7c539b6..b28cda08 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheUndoLog.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheUndoLog.swift
@@ -23,6 +23,15 @@
// 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.
+//
+// Byte runs suit patches that write a few dozen sites. The X1 lowering writes
+// 24.6 million instructions in 212,573 page runs; as runs that was 3.3 GB of
+// originals, a 4.4 GB JSON file, and a 24.5 GB peak to encode it, which a
+// 16 GB Mac swapped on for hours (issue #789). Such a patch keeps `words`
+// instead: the address and original of each instruction it changed and nothing
+// between them, 12 bytes apiece, in a binary file beside the JSON log
+// (`.vphone-dsc-undo.words` beside `.vphone-dsc-undo.json`). The JSON format is
+// unchanged, so an older CLI still reads every other patch's records.
import Foundation
import VPhonePatchKit
@@ -62,16 +71,70 @@ public struct DyldSharedCacheUndoLog: Codable, Sendable, Hashable {
}
}
+ /// One patch's originals, one 4-byte instruction each, in ascending address
+ /// order with no address twice.
+ public struct Words: Sendable, Hashable {
+ public fileprivate(set) var addresses: [UInt64] = []
+ public fileprivate(set) var originals: [UInt32] = []
+
+ public init() {}
+
+ public var count: Int {
+ addresses.count
+ }
+
+ public var isEmpty: Bool {
+ addresses.isEmpty
+ }
+
+ /// Append the original of the instruction at `vma`, which must be
+ /// above every address already held.
+ public mutating func append(vma: UInt64, original: UInt32) {
+ precondition(addresses.last.map { $0 < vma } ?? true, "undo words must arrive in ascending address order")
+ addresses.append(vma)
+ originals.append(original)
+ }
+
+ /// Both sets of words; where both hold an address, this one's original
+ /// wins, because it is the older and so the closer to pristine.
+ func merging(_ newer: Words) -> Words {
+ var merged = Words()
+ merged.addresses.reserveCapacity(count + newer.count)
+ merged.originals.reserveCapacity(count + newer.count)
+ var mine = 0, theirs = 0
+ while mine < count || theirs < newer.count {
+ if theirs == newer.count || mine < count && addresses[mine] <= newer.addresses[theirs] {
+ if theirs < newer.count, addresses[mine] == newer.addresses[theirs] { theirs += 1 }
+ merged.append(vma: addresses[mine], original: originals[mine])
+ mine += 1
+ } else {
+ merged.append(vma: newer.addresses[theirs], original: newer.originals[theirs])
+ theirs += 1
+ }
+ }
+ return merged
+ }
+ }
+
public var records: [Record]
+ /// Word originals by patch identifier, stored beside the JSON log rather
+ /// than in it. The empty identifier holds words not yet stamped.
+ public var words: [String: Words] = [:]
- public init(records: [Record] = []) {
+ public init(records: [Record] = [], words: [String: Words] = [:]) {
self.records = records
+ self.words = words
}
private enum CodingKeys: String, CodingKey {
case records = "Records"
}
+ /// Whether the log holds nothing to put back.
+ public var isEmpty: Bool {
+ records.isEmpty && words.values.allSatisfy(\.isEmpty)
+ }
+
// MARK: - Building
/// Append a run, assuming it has not been recorded yet. The caller — a
@@ -81,24 +144,38 @@ public struct DyldSharedCacheUndoLog: Codable, Sendable, Hashable {
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.
+ /// Add word originals, unstamped like a captured run.
+ public mutating func capture(words captured: Words) {
+ guard !captured.isEmpty else { return }
+ words[""] = words[""]?.merging(captured) ?? captured
+ }
+
+ /// Give every still-unstamped record and word 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
}
+ if let unstamped = words.removeValue(forKey: "") {
+ words[patchID] = words[patchID]?.merging(unstamped) ?? unstamped
+ }
}
- /// The identifiers that have at least one recorded run.
+ /// The identifiers that have at least one recorded run or word.
public var patchIDs: Set<String> {
- Set(records.map(\.patchID))
+ Set(records.map(\.patchID)).union(words.filter { !$0.value.isEmpty }.keys)
}
/// 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.
+ /// Words already held keep their originals.
public mutating func merge(_ other: DyldSharedCacheUndoLog) {
records.append(contentsOf: other.records)
+ for (patchID, newer) in other.words {
+ words[patchID] = words[patchID]?.merging(newer) ?? newer
+ }
}
/// The log to store after a patch run for `patchID` captured `captured`, or
@@ -122,10 +199,11 @@ public struct DyldSharedCacheUndoLog: Codable, Sendable, Hashable {
) -> DyldSharedCacheUndoLog? {
var fresh = captured
fresh.stamp(patchID: patchID)
- guard !fresh.records.isEmpty else { return nil }
+ guard !fresh.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)") })
+ merged.merge(DyldSharedCacheUndoLog(words: fresh.words))
return merged
}
@@ -167,7 +245,10 @@ public struct DyldSharedCacheUndoLog: Codable, Sendable, Hashable {
/// 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) })
+ DyldSharedCacheUndoLog(
+ records: records.filter { !patchIDs.contains($0.patchID) },
+ words: words.filter { !patchIDs.contains($0.key) },
+ )
}
/// The records belonging to any of `patchIDs`, newest write last so that a
@@ -189,16 +270,165 @@ public struct DyldSharedCacheUndoLog: Codable, Sendable, Hashable {
try JSONDecoder().decode(DyldSharedCacheUndoLog.self, from: data)
}
+ /// The JSON log in `data` with the words file in `words`, if there is one.
+ public static func decode(_ data: Data, words: Data?) throws -> DyldSharedCacheUndoLog {
+ var log = try decode(data)
+ if let words {
+ log.words = try decodeWords(words)
+ }
+ return log
+ }
+
+ /// The words file that belongs to the JSON log at `logPath`.
+ public static func wordsPath(forLog logPath: String) -> String {
+ ((logPath as NSString).deletingPathExtension as NSString).appendingPathExtension("words")!
+ }
+
+ /// The log at `url` with its words, or nil when neither file exists.
+ public static func load(log url: URL) throws -> DyldSharedCacheUndoLog? {
+ let json = try? Data(contentsOf: url)
+ let words = try? Data(contentsOf: URL(fileURLWithPath: wordsPath(forLog: url.path)), options: .alwaysMapped)
+ guard json != nil || words != nil else { return nil }
+ var log = try json.map { try decode($0) } ?? DyldSharedCacheUndoLog()
+ if let words {
+ log.words = try decodeWords(words)
+ }
+ return log
+ }
+
+ /// Write the JSON log to `url` and the words beside it, and remove a words
+ /// file the log no longer needs. The words go first: an interrupted write
+ /// then leaves words for a patch the old JSON does not name yet, never JSON
+ /// that relies on words that are not there.
+ public func write(log url: URL) throws {
+ let wordsURL = URL(fileURLWithPath: Self.wordsPath(forLog: url.path))
+ if let words = encodedWords() {
+ try words.write(to: wordsURL, options: .atomic)
+ } else if FileManager.default.fileExists(atPath: wordsURL.path) {
+ try FileManager.default.removeItem(at: wordsURL)
+ }
+ try encoded().write(to: url, options: .atomic)
+ }
+
+ static let wordsMagic = Data("VPDSCUW1".utf8)
+
+ /// The words as a file, or nil when there are none: the magic, a UInt32
+ /// patch count, then per patch a UInt16 identifier length, the UTF-8
+ /// identifier, a UInt64 word count, every address as a UInt64 and every
+ /// original as a UInt32. All little-endian; the arrays are copied as they
+ /// lie in memory, which on an arm64 host is that.
+ public func encodedWords() -> Data? {
+ let stored = words.filter { !$0.key.isEmpty && !$0.value.isEmpty }.sorted { $0.key < $1.key }
+ guard !stored.isEmpty else { return nil }
+ func append<T: FixedWidthInteger>(_ value: T, to data: inout Data) {
+ withUnsafeBytes(of: value.littleEndian) { data.append(contentsOf: $0) }
+ }
+ var data = Self.wordsMagic
+ data.reserveCapacity(16 + stored.reduce(0) { $0 + 10 + $1.key.utf8.count + 12 * $1.value.count })
+ append(UInt32(stored.count), to: &data)
+ for (patchID, run) in stored {
+ append(UInt16(patchID.utf8.count), to: &data)
+ data.append(contentsOf: Array(patchID.utf8))
+ append(UInt64(run.count), to: &data)
+ run.addresses.withUnsafeBytes { data.append(contentsOf: $0) }
+ run.originals.withUnsafeBytes { data.append(contentsOf: $0) }
+ }
+ return data
+ }
+
+ static func decodeWords(_ data: Data) throws -> [String: Words] {
+ func invalid(_ reason: String) -> DyldSharedCacheError {
+ .undoRecordInvalid(chunk: "undo words", reason: reason)
+ }
+ var cursor = data.startIndex
+ func take(_ length: Int) throws -> Range<Int> {
+ guard length >= 0, length <= data.endIndex - cursor else { throw invalid("truncated") }
+ defer { cursor += length }
+ return cursor ..< cursor + length
+ }
+ func array<T: FixedWidthInteger>(of _: T.Type, count: Int) throws -> [T] {
+ let range = try take(count * MemoryLayout<T>.size)
+ return [T](unsafeUninitializedCapacity: count) { buffer, initialized in
+ _ = data.copyBytes(to: buffer, from: range)
+ initialized = count
+ }
+ }
+ guard try data.subdata(in: take(wordsMagic.count)) == wordsMagic else { throw invalid("not an undo words file") }
+ let patches = try data.loadLE(UInt32.self, at: take(4).lowerBound - data.startIndex)
+ var words: [String: Words] = [:]
+ for _ in 0 ..< patches {
+ let length = try Int(data.loadLE(UInt16.self, at: take(2).lowerBound - data.startIndex))
+ guard let patchID = try String(data: data.subdata(in: take(length)), encoding: .utf8),
+ !patchID.isEmpty, words[patchID] == nil
+ else { throw invalid("bad or repeated patch identifier") }
+ let declared = try data.loadLE(UInt64.self, at: take(8).lowerBound - data.startIndex)
+ guard declared <= UInt64(data.endIndex - cursor) / 12 else { throw invalid("\(patchID): truncated") }
+ var run = Words()
+ run.addresses = try array(of: UInt64.self, count: Int(declared))
+ run.originals = try array(of: UInt32.self, count: Int(declared))
+ guard run.addresses.allSatisfy({ $0 % 4 == 0 }),
+ zip(run.addresses, run.addresses.dropFirst()).allSatisfy({ $0 < $1 })
+ else { throw invalid("\(patchID): addresses are not ascending aligned instructions") }
+ words[patchID] = run
+ }
+ guard cursor == data.endIndex else { throw invalid("trailing bytes") }
+ return words
+ }
+
+ // MARK: - Converting
+
+ /// This log with the runs of `patchIDs` held as words: every instruction
+ /// whose original differs from what the cache in `directory` holds now,
+ /// which is what the patch changed. Logs written before words existed hold
+ /// the X1 lowering as page runs, gigabytes of originals for instructions it
+ /// never touched. A run that is not whole aligned instructions stays a run.
+ /// Nil when no run belongs to `patchIDs`.
+ public func convertingRunsToWords(of patchIDs: Set<String>, in directory: URL) throws -> DyldSharedCacheUndoLog? {
+ guard records.contains(where: { patchIDs.contains($0.patchID) }) else { return nil }
+ try validate(in: directory, patchIDs: patchIDs)
+ var kept: [Record] = []
+ var changed: [String: [(vma: UInt64, original: UInt32)]] = [:]
+ for record in records {
+ guard patchIDs.contains(record.patchID), record.vma % 4 == 0, record.original.count % 4 == 0 else {
+ kept.append(record)
+ continue
+ }
+ let current = try DyldSharedCacheChunkSet.read(
+ url: directory.appendingPathComponent(record.chunk),
+ offset: UInt64(record.fileOffset),
+ length: record.original.count,
+ )
+ for offset in stride(from: 0, to: record.original.count, by: 4) {
+ let original = record.original.loadLE(UInt32.self, at: offset)
+ if current.loadLE(UInt32.self, at: offset) != original {
+ changed[record.patchID, default: []].append((record.vma + UInt64(offset), original))
+ }
+ }
+ }
+ var converted = DyldSharedCacheUndoLog(records: kept, words: words)
+ for (patchID, entries) in changed {
+ // The sort is stable, so of two runs holding one address the
+ // earlier, older original stays.
+ var run = Words()
+ for entry in entries.sorted(by: { $0.vma < $1.vma }) where run.addresses.last != entry.vma {
+ run.append(vma: entry.vma, original: entry.original)
+ }
+ converted.merge(DyldSharedCacheUndoLog(words: [patchID: run]))
+ }
+ return converted
+ }
+
// 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.
+ /// overlap, then their words, one read and one write per 16 KiB page. The
+ /// caller re-attests the touched pages afterwards; the returned spans are
+ /// exactly what to re-attest, one per restored run or page.
///
- /// 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.
+ /// A record naming a chunk that is not under `directory`, or a word at an
+ /// address the cache does not map, is refused before anything is written —
+ /// the log is trusted only to describe the cache it sits beside.
@discardableResult
public func restore(
patchIDs: Set<String>,
@@ -206,6 +436,24 @@ public struct DyldSharedCacheUndoLog: Codable, Sendable, Hashable {
log: ((String) -> Void)? = nil,
) throws -> [DyldSharedCacheWriteSpan] {
try validate(in: directory, patchIDs: patchIDs)
+ let wordPatches = patchIDs.compactMap { id in words[id].flatMap { $0.isEmpty ? nil : (id, $0) } }
+ .sorted { $0.0 < $1.0 }
+ let chunks = try wordPatches.isEmpty ? nil : DyldSharedCacheChunkSet(directory: directory)
+ var pages: [(patchID: String, run: Words, groups: [Range<Int>])] = []
+ for (patchID, run) in wordPatches {
+ var groups: [Range<Int>] = []
+ var index = 0
+ while index < run.count {
+ let first = index
+ while index < run.count, run.addresses[index] >> 14 == run.addresses[first] >> 14 {
+ index += 1
+ }
+ let start = run.addresses[first]
+ _ = try chunks!.fileRange(of: .init(vma: start, length: Int(run.addresses[index - 1] + 4 - start)))
+ groups.append(first ..< index)
+ }
+ pages.append((patchID, run, groups))
+ }
var spans: [DyldSharedCacheWriteSpan] = []
var openChunk: String?, openHandle: FileHandle?
defer { try? openHandle?.close() }
@@ -224,6 +472,18 @@ public struct DyldSharedCacheUndoLog: Codable, Sendable, Hashable {
log?(" [+] revert: \(record.original.count) byte(s) at 0x"
+ String(record.vma, radix: 16, uppercase: true) + " in \(record.chunk) (\(record.patchID))")
}
+ for (patchID, run, groups) in pages {
+ for group in groups {
+ let start = run.addresses[group.lowerBound]
+ var bytes = try chunks!.bytesAtVMA(start, length: Int(run.addresses[group.upperBound - 1] + 4 - start))
+ for index in group {
+ let offset = Int(run.addresses[index] - start)
+ bytes.replaceSubrange(offset ..< offset + 4, with: ARM64.encodeU32(run.originals[index]))
+ }
+ try spans.append(chunks!.write(at: start, bytes))
+ }
+ log?(" [+] revert: \(run.count) instruction(s) in \(groups.count) page run(s) (\(patchID))")
+ }
return spans
}
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheArm64eX1BootstrapPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheArm64eX1BootstrapPatcher.swift
index e782e226..7aea37d2 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheArm64eX1BootstrapPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheArm64eX1BootstrapPatcher.swift
@@ -59,6 +59,13 @@ public enum DyldSharedCacheArm64eX1BootstrapPatcher {
"/usr/lib/swift/libswiftDispatch.dylib",
]
+ /// The patches whose undo is kept as words. Logs from 2.15.0 and earlier
+ /// hold them as page runs, which `cfw install` converts once.
+ public static let wordUndoPatchIDs: Set<String> = [
+ FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap,
+ FirmwareGuestSystemPatchSet.arm64eX1CacheRemaining,
+ ]
+
public static func patch(
directory: URL,
dryRun: Bool = false,
@@ -214,6 +221,9 @@ public enum DyldSharedCacheArm64eX1BootstrapPatcher {
log(" [*] \(label): \(selected.count) image(s), \(lowered) with X1 code, \(skipped.count) skipped, \(writes.count) rewrites, \(unvisited) unvisited candidates")
guard !dryRun else { return }
+ // The originals of the changed instructions, word by word: as page runs
+ // the chunk set would keep 3.3 GB for the whole cache (issue #789).
+ var originals = DyldSharedCacheUndoLog.Words()
do {
var index = 0
var groups = 0
@@ -259,11 +269,14 @@ public enum DyldSharedCacheArm64eX1BootstrapPatcher {
for write in writes[first ..< index] {
let offset = Int(write.address - start)
let replacement = ARM64.encodeU32(write.word)
- if after.subdata(in: offset ..< offset + 4) != replacement { changed += 1 }
+ if after.subdata(in: offset ..< offset + 4) != replacement {
+ changed += 1
+ originals.append(vma: write.address, original: before.loadLE(UInt32.self, at: offset))
+ }
after.replaceSubrange(offset ..< offset + 4, with: replacement)
}
if before != after {
- try chunks.write(at: start, after)
+ try chunks.write(at: start, after, capturingOriginal: false)
groups += 1
if !skipsUnplannable {
log(" 0x\(String(start, radix: 16)): \(changed) instruction(s) [\(patchID)]")
@@ -277,11 +290,14 @@ public enum DyldSharedCacheArm64eX1BootstrapPatcher {
"\(label) re-attestation skipped \(attestation.skipped.count) pages",
)
}
- onUndo(chunks.takeUndoLog()!)
+ var undo = chunks.takeUndoLog()!
+ undo.capture(words: originals)
+ onUndo(undo)
log(" [+] \(label): \(writes.count) instruction rewrites in \(groups) page run(s)")
} catch {
var undo = chunks.takeUndoLog()!
- if !undo.records.isEmpty {
+ undo.capture(words: originals)
+ if !undo.isEmpty {
undo.stamp(patchID: patchID)
let spans = try undo.restore(patchIDs: undo.patchIDs, in: directory, log: log)
_ = try DyldSharedCacheCodeSignature.reattest(
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheUndoLogTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheUndoLogTests.swift
index 4a6e8afa..a88b23ca 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheUndoLogTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheUndoLogTests.swift
@@ -211,6 +211,190 @@ struct DyldSharedCacheUndoLogTests {
}
}
+@Suite("Dyld shared cache undo words")
+struct DyldSharedCacheUndoWordsTests {
+ static let base: UInt64 = 0x1_8000_0000
+
+ private func words(_ entries: [(UInt64, UInt32)]) -> DyldSharedCacheUndoLog.Words {
+ var words = DyldSharedCacheUndoLog.Words()
+ for (vma, original) in entries {
+ words.append(vma: vma, original: original)
+ }
+ return words
+ }
+
+ /// A two-page cache whose one mapping puts file offset 0 at `base`, with
+ /// every word past the header holding its own file offset.
+ private func withCache(_ body: (URL, URL) throws -> Void) throws {
+ let dir = URL(fileURLWithPath: NSTemporaryDirectory())
+ .appendingPathComponent("undo-words-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: dir) }
+ var bytes = Data(count: 0x8000)
+ func put<T: FixedWidthInteger>(_ value: T, at offset: Int) {
+ withUnsafeBytes(of: value.littleEndian) { bytes.replaceSubrange(offset ..< offset + $0.count, with: $0) }
+ }
+ for offset in stride(from: 0x400, to: 0x8000, by: 4) {
+ put(UInt32(offset), at: offset)
+ }
+ bytes.replaceSubrange(0 ..< 15, with: Data("dyld_v1 arm64e".utf8))
+ put(UInt32(0x238), at: 0x10)
+ put(UInt32(1), at: 0x14)
+ put(Self.base, at: 0x238)
+ put(UInt64(0x8000), at: 0x240)
+ put(UInt64(0), at: 0x248)
+ put(UInt32(5), at: 0x250)
+ put(UInt32(5), at: 0x254)
+ put(Self.base, at: 0xE0)
+ put(UInt64(0x8000), at: 0xE8)
+ let chunk = dir.appendingPathComponent("dyld_shared_cache_arm64e")
+ try bytes.write(to: chunk)
+ try body(dir, chunk)
+ }
+
+ private func word(in chunk: URL, at offset: Int) throws -> UInt32 {
+ try Data(contentsOf: chunk).loadLE(UInt32.self, at: offset)
+ }
+
+ private func overwrite(_ chunk: URL, at offsets: [Int], with bytes: [UInt8]) throws {
+ let handle = try FileHandle(forUpdating: chunk)
+ defer { try? handle.close() }
+ for offset in offsets {
+ try handle.seek(toOffset: UInt64(offset))
+ try handle.write(contentsOf: Data(bytes))
+ }
+ }
+
+ @Test
+ func `Merging keeps addresses ascending and the older original`() {
+ let older = words([(0x10, 1), (0x20, 2)])
+ let newer = words([(0x08, 7), (0x20, 9), (0x30, 3)])
+ let merged = older.merging(newer)
+ #expect(merged.addresses == [0x08, 0x10, 0x20, 0x30])
+ #expect(merged.originals == [7, 1, 2, 3])
+ }
+
+ @Test
+ func `Captured words take the identifier they are stamped with`() {
+ var log = DyldSharedCacheUndoLog()
+ log.capture(words: words([(0x10, 1)]))
+ #expect(log.patchIDs == [""])
+ log.stamp(patchID: "x1")
+ #expect(log.patchIDs == ["x1"])
+ #expect(log.words["x1"]?.originals == [1])
+ #expect(log.removing(patchIDs: ["x1"]).isEmpty)
+ }
+
+ @Test
+ func `A re-run merges new words and keeps the stored originals`() throws {
+ let existing = DyldSharedCacheUndoLog(words: ["x1": words([(0x10, 1)])])
+ var captured = DyldSharedCacheUndoLog()
+ captured.capture(words: words([(0x10, 5), (0x14, 2)]))
+ let updated = try #require(DyldSharedCacheUndoLog.updated(existing: existing, captured: captured, patchID: "x1"))
+ #expect(updated.words["x1"]?.addresses == [0x10, 0x14])
+ #expect(updated.words["x1"]?.originals == [1, 2])
+ #expect(DyldSharedCacheUndoLog.updated(existing: existing, captured: .init(), patchID: "x1") == nil)
+ }
+
+ @Test
+ func `The words file sits beside the JSON log`() {
+ #expect(DyldSharedCacheUndoLog.wordsPath(forLog: "a/b/.vphone-dsc-undo.json") == "a/b/.vphone-dsc-undo.words")
+ }
+
+ @Test
+ func `A log writes words beside its JSON and loads them back`() throws {
+ try withCache { dir, _ in
+ let url = dir.appendingPathComponent(".vphone-dsc-undo.json")
+ var log = DyldSharedCacheUndoLog(words: ["x1": words([(Self.base + 0x4000, 0xD503_201F)])])
+ log.capture(chunk: "dyld_shared_cache_arm64e", fileOffset: 0x4100, vma: Self.base + 0x4100, original: Data([1, 2]))
+ log.stamp(patchID: "other")
+ try log.write(log: url)
+ #expect(try DyldSharedCacheUndoLog.load(log: url) == log)
+ // The JSON alone is what an older CLI reads: the words are not in it.
+ #expect(try DyldSharedCacheUndoLog.decode(Data(contentsOf: url)).words.isEmpty)
+
+ // A log left without words removes the file.
+ try log.removing(patchIDs: ["x1"]).write(log: url)
+ #expect(!FileManager.default.fileExists(atPath: DyldSharedCacheUndoLog.wordsPath(forLog: url.path)))
+ }
+ }
+
+ @Test
+ func `A damaged words file is refused`() throws {
+ let log = DyldSharedCacheUndoLog(words: ["x1": words([(0x10, 1), (0x14, 2)])])
+ let data = try #require(log.encodedWords())
+ #expect(try DyldSharedCacheUndoLog.decodeWords(data) == log.words)
+ #expect(throws: DyldSharedCacheError.self) { try DyldSharedCacheUndoLog.decodeWords(data.dropLast()) }
+ #expect(throws: DyldSharedCacheError.self) { try DyldSharedCacheUndoLog.decodeWords(data + Data([0])) }
+ // The two addresses swapped.
+ var unordered = data
+ let first = unordered.count - 8 - 16
+ let swapped = unordered.subdata(in: first + 8 ..< first + 16) + unordered.subdata(in: first ..< first + 8)
+ unordered.replaceSubrange(first ..< first + 16, with: swapped)
+ #expect(throws: DyldSharedCacheError.self) { try DyldSharedCacheUndoLog.decodeWords(unordered) }
+ }
+
+ @Test
+ func `Restoring words puts back only those instructions, page by page`() throws {
+ try withCache { dir, chunk in
+ let sites = [0x3000, 0x4010, 0x4020]
+ try overwrite(chunk, at: sites, with: [0x1F, 0x20, 0x03, 0xD5])
+ // Between two sites, an unrelated write the words must not touch.
+ try overwrite(chunk, at: [0x4018], with: [0xAA, 0xAA, 0xAA, 0xAA])
+ var log = DyldSharedCacheUndoLog()
+ log.capture(words: words(sites.map { (Self.base + UInt64($0), UInt32($0)) }))
+ log.stamp(patchID: "x1")
+
+ let spans = try log.restore(patchIDs: ["x1"], in: dir)
+ #expect(spans.map(\.vma) == [Self.base + 0x3000, Self.base + 0x4010])
+ #expect(spans.map(\.length) == [4, 0x14])
+ for site in sites {
+ #expect(try word(in: chunk, at: site) == UInt32(site))
+ }
+ #expect(try word(in: chunk, at: 0x4018) == 0xAAAA_AAAA)
+ }
+ }
+
+ @Test
+ func `A word the cache does not map refuses the whole restore`() throws {
+ try withCache { dir, chunk in
+ try overwrite(chunk, at: [0x4010], with: [0, 0, 0, 0])
+ let log = DyldSharedCacheUndoLog(words: ["x1": words([(Self.base + 0x4010, 0x4010), (Self.base + 0x9000, 0)])])
+ #expect(throws: DyldSharedCacheError.self) { try log.restore(patchIDs: ["x1"], in: dir) }
+ #expect(try word(in: chunk, at: 0x4010) == 0)
+ }
+ }
+
+ @Test
+ func `Page runs from an older log become the words that differ`() throws {
+ try withCache { dir, chunk in
+ let name = chunk.lastPathComponent
+ let pristine = try Data(contentsOf: chunk)
+ try overwrite(chunk, at: [0x4004, 0x400C], with: [0x1F, 0x20, 0x03, 0xD5])
+ let run = DyldSharedCacheUndoLog.Record(
+ patchID: "x1", chunk: name, fileOffset: 0x4000, vma: Self.base + 0x4000,
+ original: pristine.subdata(in: 0x4000 ..< 0x4010),
+ )
+ let odd = DyldSharedCacheUndoLog.Record(
+ patchID: "x1", chunk: name, fileOffset: 0x4101, vma: Self.base + 0x4101, original: Data([1, 2, 3]),
+ )
+ let other = DyldSharedCacheUndoLog.Record(
+ patchID: "other", chunk: name, fileOffset: 0x5000, vma: Self.base + 0x5000, original: Data([1, 2, 3, 4]),
+ )
+ let log = DyldSharedCacheUndoLog(records: [run, odd, other])
+
+ let converted = try #require(try log.convertingRunsToWords(of: ["x1"], in: dir))
+ #expect(converted.records == [odd, other])
+ #expect(converted.words["x1"]?.addresses == [Self.base + 0x4004, Self.base + 0x400C])
+ #expect(converted.words["x1"]?.originals == [0x4004, 0x400C])
+ #expect(try converted.convertingRunsToWords(of: ["x2"], in: dir) == nil)
+
+ try converted.restore(patchIDs: ["x1"], in: dir)
+ #expect(try Data(contentsOf: chunk).subdata(in: 0x4000 ..< 0x4010) == pristine.subdata(in: 0x4000 ..< 0x4010))
+ }
+ }
+}
+
@Suite("Dyld patches whose implementation changed")
struct DyldSharedCacheOutdatedImplementationTests {
private func record(_ id: String, bytes: Int, offset: Int = 0) -> DyldSharedCacheUndoLog.Record {
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift
index 693c27db..6e6736ff 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift
@@ -49,23 +49,34 @@ struct DyldSharedCacheUndoOptions: ParsableArguments {
/// ``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).
+ /// stay unchanged (AGENTS.md). A verb that captured no words leaves the
+ /// words file alone instead of reading and rewriting hundreds of megabytes.
func persist(_ captured: DyldSharedCacheUndoLog, dryRun: Bool) throws {
- guard let undoLog, captures, !dryRun, !captured.records.isEmpty else { return }
+ guard let undoLog, captures, !dryRun, !captured.isEmpty else { return }
let url = URL(fileURLWithPath: undoLog)
- let existing = (try? Data(contentsOf: url)).flatMap { try? DyldSharedCacheUndoLog.decode($0) }
+ let wordsPath = DyldSharedCacheUndoLog.wordsPath(forLog: undoLog)
+ let withWords = captured.words.values.contains { !$0.isEmpty }
+ let existing = withWords
+ ? (try? DyldSharedCacheUndoLog.load(log: url)) ?? nil
+ : (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)
+ if withWords {
+ try merged.write(log: url)
+ } else {
+ 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 = DyldSharedCacheChunkSet.mainCacheURL(in: url.deletingLastPathComponent())
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)
+ for path in [url.path, wordsPath] where FileManager.default.fileExists(atPath: path) {
+ chmod(path, metadata.st_mode & 0o7777)
+ chown(path, metadata.st_uid, metadata.st_gid)
+ }
}
}
}
@@ -79,6 +90,7 @@ enum VPhoneCustomFirmwareDyldSharedCacheVerbs {
VPhoneCustomFirmwarePatchArm64eX1BootstrapCacheCommand.self,
VPhoneCustomFirmwarePatchArm64eX1CacheCommand.self,
VPhoneCustomFirmwareDyldSharedCacheRevertCommand.self,
+ VPhoneCustomFirmwareDyldSharedCacheUndoWordsCommand.self,
VPhoneCustomFirmwarePatchHypervisorVirtualMachineDyldSharedCacheCommand.self,
VPhoneCustomFirmwarePatchIOMFBSwapEndCommand.self,
VPhoneCustomFirmwarePatchIOMFBForceKernCommand.self,
@@ -682,11 +694,10 @@ struct VPhoneCustomFirmwareDyldSharedCacheRevertCommand: ParsableCommand {
func run() throws {
let url = URL(fileURLWithPath: undoLog)
- guard let data = try? Data(contentsOf: url) else {
+ guard let log = try DyldSharedCacheUndoLog.load(log: 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 {
@@ -698,6 +709,11 @@ struct VPhoneCustomFirmwareDyldSharedCacheRevertCommand: ParsableCommand {
print(" [.] dry-run: would restore \(record.original.count) byte(s) at 0x"
+ String(record.vma, radix: 16, uppercase: true) + " (\(record.patchID))")
}
+ for patchID in present.sorted() {
+ if let words = log.words[patchID], !words.isEmpty {
+ print(" [.] dry-run: would restore \(words.count) instruction(s) (\(patchID))")
+ }
+ }
return
}
let spans = try log.restore(
@@ -714,8 +730,54 @@ struct VPhoneCustomFirmwareDyldSharedCacheRevertCommand: ParsableCommand {
)
}
let remaining = log.removing(patchIDs: present)
- try remaining.encoded().write(to: url, options: .atomic)
- try? FileManager.default.setAttributes([.posixPermissions: 0o777], ofItemAtPath: url.path)
+ try remaining.write(log: url)
+ for path in [url.path, DyldSharedCacheUndoLog.wordsPath(forLog: undoLog)] {
+ try? FileManager.default.setAttributes([.posixPermissions: 0o777], ofItemAtPath: path)
+ }
print(" [+] reverted \(present.count) dyld patch(es): \(present.sorted().joined(separator: ", "))")
}
}
+
+// MARK: - dsc-undo-words
+
+/// Convert the X1 lowering's page runs in an undo log written by 2.15.0 or
+/// earlier into words, once. Those runs are gigabytes of originals, and every cache verb
+/// that records anything decodes and re-encodes the whole log; the words keep
+/// only the instructions the lowering changed, in the file beside it.
+/// `cfw install` and `cfw update-environment` invoke this before the cache
+/// patches; it is not a verb a researcher reaches for by hand.
+struct VPhoneCustomFirmwareDyldSharedCacheUndoWordsCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "patch-dsc-undo-words",
+ abstract: "Keep the X1 lowering's undo as words instead of page runs",
+ 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
+
+ func run() throws {
+ let url = URL(fileURLWithPath: undoLog)
+ guard let log = try DyldSharedCacheUndoLog.load(log: url),
+ let converted = try log.convertingRunsToWords(
+ of: DyldSharedCacheArm64eX1BootstrapPatcher.wordUndoPatchIDs,
+ in: chunksDirectory,
+ )
+ else { return }
+ try converted.write(log: url)
+ var metadata = stat()
+ if lstat(url.path, &metadata) == 0 {
+ let wordsPath = DyldSharedCacheUndoLog.wordsPath(forLog: undoLog)
+ chmod(wordsPath, metadata.st_mode & 0o7777)
+ chown(wordsPath, metadata.st_uid, metadata.st_gid)
+ }
+ let words = converted.words.values.reduce(0) { $0 + $1.count }
+ print(" [+] dyld undo log: \(log.records.count - converted.records.count) X1 page run(s) kept as \(words) instruction(s)")
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
index 15710bb1..47ccba1b 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
@@ -2365,7 +2365,22 @@ struct VPhoneCustomFirmwareInstaller {
}
let undoAbsolute = (dsc as NSString).appendingPathComponent(Self.dscUndoLogLeaf)
let undoRelative = "\(cacheRelative)/\(Self.dscUndoLogLeaf)"
- let undoLog = (try? system.readData(undoRelative)).flatMap { try? DyldSharedCacheUndoLog.decode($0) }
+ // A log from 2.15.0 or earlier keeps the X1 lowering as gigabytes of
+ // page runs; convert it once, before anything here decodes it.
+ if dyld.contains(where: { DyldSharedCacheArm64eX1BootstrapPatcher.wordUndoPatchIDs.contains($0.id) }),
+ (try? system.exists(undoRelative)) == true
+ {
+ do {
+ try patch("patch-dsc-undo-words", [dsc, "--undo-log", undoAbsolute])
+ } catch {
+ print(" [!] dyld undo log: keeping the X1 page runs as they are: \(error)")
+ }
+ }
+ let undoWords = DyldSharedCacheUndoLog.wordsPath(forLog: undoRelative)
+ let undoLog = (try? system.readData(undoRelative)).flatMap { json in
+ let words = (try? system.exists(undoWords)) == true ? try? system.readData(undoWords) : nil
+ return try? DyldSharedCacheUndoLog.decode(json, words: words)
+ }
let recorded = undoLog?.patchIDs ?? []
var revertable: [String] = []