Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Seal the merged image as the restore will

Maximilian Paß28eaa5c11f86
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 450e7c48..981fc598 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -3328,3 +3328,17 @@ into the restored volume, and `seal_system_volume` failed ("mtree: cannot
generate the XML dictionary", 26.6 on cloudOS 23E5207q, 2026-10-19). Each
writable mount now deletes the directory before it unmounts, which also stops
fseventsd writing it again for that mount.
+
+The root hash `fw patch` computes has to be the one the restore computes, and
+it was not ("Invalid root hash", `apfs_sealvolume` exit 65 in
+`seal_system_volume`):
+
+- The remap's `MODIFICATION` was the time of `/private/var` in the mtree,
+ on the assumption that `removeSpecificSystemFiles` changes it last. The
+ restore's own `mtree -m` sets it from the root entry (`.`), not from the
+ newest one: run on 2026-10-19, the device took the root's
+ `1792405582.069334279` while `/private/var` said `…582.936736187`. The
+ remap takes the root's time now.
+- `createDigestAndHash` mounted the image writable only to unmount it again
+ for `apfs_sealvolume`, which needs the device; the mount changed the volume
+ after the mtree described it. It attaches the image with `-noMount` now.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherDiskImage.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherDiskImage.swift
index 3c1c0adc..be1acc1e 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherDiskImage.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherDiskImage.swift
@@ -142,6 +142,29 @@ extension CryptexFilesystemPatcher {
])
}
+ /// Attach an image without mounting anything, and return its APFS volume's
+ /// device node.
+ func attachImageWithoutMounting(path: URL) throws -> String {
+ let output: String
+ do {
+ output = try runProcess("/usr/sbin/diskutil", ["image", "attach", "-noMount", path.path])
+ } catch let ProcessError.failed(status, output) {
+ detachReportedImage(in: output)
+ throw ProcessError.failed(status, output)
+ }
+ for line in output.split(whereSeparator: \.isNewline) {
+ let fields = line.split(whereSeparator: \.isWhitespace)
+ guard fields.count >= 2, fields[0].hasPrefix("/dev/disk"), fields[1] == "Apple_APFS_Volume" else {
+ continue
+ }
+ let device = String(fields[0])
+ attachedDevices.insert(device)
+ return device
+ }
+ detachReportedImage(in: output)
+ throw FirmwareManifest.ManifestError.missingKey("APFS volume in \(path.lastPathComponent)")
+ }
+
/// Delete the event log the host's fseventsd keeps on a writable mount.
///
/// Apple's system volumes have no `.fseventsd`, and the restore writes
@@ -157,10 +180,6 @@ extension CryptexFilesystemPatcher {
}
}
- func unmount(mount: String) throws {
- _ = try runProcess("/usr/sbin/diskutil", ["unmount", mount])
- }
-
/// attachImage returns the device and mount point
func attachImage(path: URL, readonly: Bool = false, forceRW: Bool = false) throws -> (String, String) {
let process = Process()
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swift
index 557071f8..bab8ee4e 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swift
@@ -68,7 +68,10 @@ extension CryptexFilesystemPatcher {
}
func createDigestAndHash(filesystem: URL, mtree: URL, remap: Bool) throws -> (URL, URL) {
- let (device, mount) = try attachImage(path: filesystem)
+ // Not mounted: apfs_sealvolume needs only the device, and a mount would
+ // change the volume after the mtree described it, so the root hash here
+ // would differ from the one the restore computes from that mtree.
+ let device = try attachImageWithoutMounting(path: filesystem)
defer { try? detachImage(deviceNode: device) }
let tmpDir = try createTmpDir()
@@ -77,10 +80,8 @@ extension CryptexFilesystemPatcher {
let mtreeRemapPath = tmpDir.appending(path: "mtree_remap.xml")
let sealLogPath = tmpDir.appending(path: "seal.log")
- // We want to get the nanosecond timestamp of the last modification before the mtree collection.
- // We know that we remove directories in /private/var in removeSpecificSystemFiles last.
- // Therefore, we parse the modification time of /private/var.
- let modificationTime = try parsePrivateVarTime(mtree: mtree)
+ // The modification time the restore will derive from the mtree.
+ let modificationTime = try parseRootTime(mtree: mtree)
let remapContent = """
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
@@ -96,8 +97,6 @@ extension CryptexFilesystemPatcher {
print("Modification time: \(remap ? modificationTime : "none")")
FileManager.default.createFile(atPath: mtreeRemapPath.path, contents: remapContent.data(using: .utf8))
- try removeHostEventLog(mount: mount)
- try unmount(mount: mount)
let sealvolume = try identifyApfsSealvolume()
FileManager.default.createFile(atPath: sealLogPath.path, contents: nil)
do {
@@ -118,7 +117,12 @@ extension CryptexFilesystemPatcher {
return (digestDbPath, rootHashPath)
}
- func parsePrivateVarTime(mtree: URL) throws -> String {
+ /// The root directory's modification time in the mtree, in nanoseconds.
+ ///
+ /// The restore seals the volume with the time its own `mtree -m` derives,
+ /// which is the root entry's (`.`), not the newest entry's. Any other value
+ /// gives this side a root hash the restore rejects ("Invalid root hash").
+ func parseRootTime(mtree: URL) throws -> String {
guard let mtreeData = FileManager.default.contents(atPath: mtree.path),
let text = String(data: mtreeData, encoding: .utf8)
else {
@@ -126,35 +130,24 @@ extension CryptexFilesystemPatcher {
}
let lines = text.split(whereSeparator: \.isNewline).map(String.init)
- // Find the section header for /private/var
- guard let sectionIndex = lines.firstIndex(of: "# ./private/var") else {
- throw FirmwareManifest.ManifestError.fileNotFound("the /private/var entry in \(mtree.path)")
+ // The first section, "# .", describes the root; its entry is named ".".
+ guard let sectionIndex = lines.firstIndex(of: "# ."),
+ let entryIndex = lines[(sectionIndex + 1)...].firstIndex(where: { $0.hasPrefix(". ") })
+ else {
+ throw FirmwareManifest.ManifestError.fileNotFound("the root entry in \(mtree.path)")
}
-
- // Look at the lines after that header until the next section header
- for line in lines[(sectionIndex + 1)...] {
- // Stop if we hit the next section
- if line.hasPrefix("# ./") {
- break
- }
-
- // The metadata line for /private/var starts with "var "
- guard line.hasPrefix("var ") else { continue }
-
- // Extract time=...
- guard let match = line.range(of: #"time=([0-9]+(?:\.[0-9]+)?)"#,
- options: .regularExpression)
- else {
- throw FirmwareManifest.ManifestError.fileNotFound("the /private/var modification time in \(mtree.path)")
- }
-
- let matchedText = String(line[match])
- return matchedText
- .replacingOccurrences(of: "time=", with: "")
- .replacingOccurrences(of: ".", with: "")
+ // An entry continues on the next line after a trailing backslash.
+ var entry = ""
+ for line in lines[entryIndex...] {
+ entry += line
+ guard line.hasSuffix("\\") else { break }
}
-
- throw FirmwareManifest.ManifestError.fileNotFound("the /private/var entry in \(mtree.path)")
+ guard let match = entry.range(of: #"time=([0-9]+(?:\.[0-9]+)?)"#, options: .regularExpression) else {
+ throw FirmwareManifest.ManifestError.fileNotFound("the root modification time in \(mtree.path)")
+ }
+ return String(entry[match])
+ .replacingOccurrences(of: "time=", with: "")
+ .replacingOccurrences(of: ".", with: "")
}
func createMtree(filesystem: URL) throws -> URL {
@@ -180,8 +173,6 @@ extension CryptexFilesystemPatcher {
"/private/var/MobileAsset/PreinstalledAssetsV2",
"/private/var/staged_system_apps",
]
- // First: createDigestAndHash takes the remap time from /private/var,
- // so the removals below have to be the last change to the volume.
try removeHostEventLog(mount: mount)
var didEdit = false
for path in removedPaths {
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFileOpsTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFileOpsTests.swift
index d1a55a19..ec3113d7 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFileOpsTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFileOpsTests.swift
@@ -247,6 +247,32 @@ struct CryptexFileOpsTests {
</plist>
"""
+ // MARK: - Seal remap time
+
+ @Test(arguments: [
+ ". type=dir nlink=19 size=608 time=1792405582.069334279\n",
+ ". type=dir nlink=19 \\\n size=608 time=1792405582.069334279\n",
+ ])
+ func `the remap time is the root entry's, not the newest one's`(root: String) throws {
+ let scratch = try makeScratch()
+ defer { try? FileManager.default.removeItem(at: scratch) }
+ let mtree = scratch.appendingPathComponent("mtree.txt")
+ try ("""
+ #\t tree: /Volumes/LuckG23G71.D47OS
+
+ # .
+ /set type=file uid=0 gid=0 mode=0755 nlink=1 flags=none
+
+ """ + root + """
+ .file gid=80 mode=0 size=0 time=1784253250.000000000
+
+ # ./private/var
+ var type=dir nlink=31 size=992 time=1792405582.936736187
+
+ """).write(to: mtree, atomically: true, encoding: .utf8)
+ #expect(try makePatcher(scratch).parseRootTime(mtree: mtree) == "1792405582069334279")
+ }
+
@Test func `the max size comes back as the string diskutil wants back`() throws {
#expect(try CryptexFilesystemPatcher.maxResizeSize(
fromDiskutilPlist: Self.sizesPlist,