Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

feat(cfw): port the APFS snapshot flip to Swift, proven byte-identical

Lakr6bb1c1aeec28
diff --git a/scripts/build.sh b/scripts/build.sh
index f4e06072..63af4a4b 100755
--- a/scripts/build.sh
+++ b/scripts/build.sh
@@ -116,7 +116,10 @@ rsync -a \
--exclude '.git' \
--exclude '.build' \
scripts/ "${RES}/scripts/"
-cp -f tools/apfs_snap_rename.py "${RES}/tools/apfs_snap_rename.py"
+# tools/ is created but currently empty: apfs_snap_rename.py is no longer
+# bundled, because `vphone-cli cfw flip-snapshot` does that work now. The .py
+# stays in the repo as a reference until the byte comparison has been repeated
+# against a real Disk.img.
# Custom-built tools (bundled; not brew/pip). apfs_sealvolume is NOT bundled
# (it is extracted from the target IPSW at `fw prepare` time — Task 5).
for t in trustcache insert_dylib; do
diff --git a/scripts/cfw_install_host.sh b/scripts/cfw_install_host.sh
index 2b4ba182..86bcd2cd 100755
--- a/scripts/cfw_install_host.sh
+++ b/scripts/cfw_install_host.sh
@@ -4,7 +4,7 @@
# Attaches the VM's Disk.img on the host and hands the container to the variant
# installer (cfw_install*.sh), which mounts the APFS volumes and places every
# CFW file directly. Then flips the boot snapshot offline
-# (tools/apfs_snap_rename.py) so the VM boots the live volume.
+# (`vphone-cli cfw flip-snapshot`) so the VM boots the live volume.
#
# Prereqs: VM restored (make restore) and powered off; host has gnu-tar, ipsw,
# aea, ldid, zstd, project venv (make setup_tools). SIP disabled (project
@@ -87,7 +87,17 @@ cleanup
trap - EXIT
echo "[*] flipping boot snapshot offline (com.apple.os.update -> live volume)..."
-"$PY" "$PROJ/tools/apfs_snap_rename.py" "$IMG"
+# VPHONE_CLI_BIN is set by `vphone-cli cfw install`; the fallbacks cover being
+# run by hand from a dev tree or from inside the .app, where scripts/ sits in
+# Contents/Resources and the binaries are one level up in MacOS.
+VPHONE_CLI="${VPHONE_CLI_BIN:-}"
+if [[ -z "$VPHONE_CLI" ]]; then
+ for candidate in "$PROJ/.build/release/vphone-cli" "${PROJ:h}/MacOS/vphone-cli"; do
+ [[ -x "$candidate" ]] && { VPHONE_CLI="$candidate"; break }
+ done
+fi
+[[ -x "$VPHONE_CLI" ]] || { echo "[-] cannot find vphone-cli to flip the snapshot" >&2; exit 1; }
+"$VPHONE_CLI" cfw flip-snapshot "$IMG"
# Drop the extracted CFW input dirs (source .tar.zst re-extracts). VPHONE_KEEP_ARTIFACTS opts out.
if [[ -z "${VPHONE_KEEP_ARTIFACTS:-}" ]]; then
diff --git a/sources/VPhoneCore/VPhoneAPFSSnapshot.swift b/sources/VPhoneCore/VPhoneAPFSSnapshot.swift
new file mode 100644
index 00000000..a0ad38a6
--- /dev/null
+++ b/sources/VPhoneCore/VPhoneAPFSSnapshot.swift
@@ -0,0 +1,252 @@
+import Foundation
+
+// MARK: - VPhoneAPFSSnapshotError
+
+public enum VPhoneAPFSSnapshotError: Error, CustomStringConvertible {
+ case prefixLengthMismatch(given: Int, required: Int)
+ case cannotOpen(URL, errno: Int32)
+ case cannotMap(URL, errno: Int32)
+
+ public var description: String {
+ switch self {
+ case let .prefixLengthMismatch(given, required):
+ "--new-prefix must be exactly \(required) bytes (got \(given))"
+ case let .cannotOpen(url, err):
+ "Could not open \(url.path): \(String(cString: strerror(err)))"
+ case let .cannotMap(url, err):
+ "Could not map \(url.path): \(String(cString: strerror(err)))"
+ }
+ }
+}
+
+// MARK: - VPhoneAPFSSnapshot
+
+/// Offline APFS root-snapshot rename for a vphone `Disk.img` (CFW boot-source flip).
+///
+/// Renames the `com.apple.os.update-<hash>` system snapshot in place so the
+/// (seal-enforcement-patched) guest kernel cannot find the named root snapshot
+/// and roots the live volume instead — the same effect as `snaputil` inside the
+/// VM, done offline on the host: no mount, no `fs_snapshot` syscall, no kernel
+/// CSR gate, no host security change.
+///
+/// The name is stored in exactly two b-tree records (the `snap_metadata` value
+/// and the `snap_name` key), normally in one leaf node. A same-length rename
+/// keeps `name_len` and the single-snapshot b-tree order intact, so only the
+/// touched blocks' fletcher64 changes — which is why the new prefix is required
+/// to be the same length rather than merely recommended to be.
+///
+/// Swift port of `tools/apfs_snap_rename.py`. Byte-for-byte equivalence is the
+/// acceptance criterion: the same image through either version must produce the
+/// same SHA-256.
+public enum VPhoneAPFSSnapshot {
+ public static let blockSize = 4096
+ public static let oldPrefix = Array("com.apple.os.update-".utf8) // 20 bytes
+ public static let defaultNewPrefix = "orig-fs.disabled.rn-"
+
+ /// One `com.apple.os.update-*` record, and where it lives.
+ public struct Record: Equatable, Sendable {
+ /// Offset of the containing 4 KiB block within the image.
+ public let blockOffset: Int
+ /// Offset of the record within that block.
+ public let offsetInBlock: Int
+ }
+
+ public struct Report: Sendable {
+ /// The full snapshot name, prefix plus the 64 hex characters.
+ public let snapshotName: String?
+ /// Records grouped by block, in ascending block order.
+ public let blocks: [(blockOffset: Int, offsetsInBlock: [Int])]
+
+ public var recordCount: Int { blocks.reduce(0) { $0 + $1.offsetsInBlock.count } }
+ public var isEmpty: Bool { blocks.isEmpty }
+ }
+
+ // MARK: - Checksum
+
+ /// APFS's fletcher64 over a 4 KiB object block, excluding the 8-byte
+ /// checksum field at its head.
+ ///
+ /// The modulus is 0xFFFFFFFF rather than 2^32; that is what APFS does, and
+ /// getting it "right" would make every checksum wrong.
+ public static func checksum(_ block: UnsafeRawBufferPointer) -> UInt64 {
+ precondition(block.count == blockSize)
+ var s1: UInt64 = 0
+ var s2: UInt64 = 0
+ let modulus: UInt64 = 0xFFFF_FFFF
+
+ var offset = 8
+ while offset < blockSize {
+ let word = UInt64(block.loadUnaligned(fromByteOffset: offset, as: UInt32.self))
+ s1 = (s1 + word) % modulus
+ s2 = (s2 + s1) % modulus
+ offset += 4
+ }
+
+ let c1 = modulus - ((s1 + s2) % modulus)
+ let c2 = modulus - ((s1 + c1) % modulus)
+ return c1 | (c2 << 32)
+ }
+
+ private static func blockIsValid(_ block: UnsafeRawBufferPointer) -> Bool {
+ let stored = block.loadUnaligned(fromByteOffset: 0, as: UInt64.self)
+ return checksum(block) == stored
+ }
+
+ private static func isHexDigit(_ byte: UInt8) -> Bool {
+ switch byte {
+ case UInt8(ascii: "0")...UInt8(ascii: "9"),
+ UInt8(ascii: "a")...UInt8(ascii: "f"),
+ UInt8(ascii: "A")...UInt8(ascii: "F"):
+ true
+ default:
+ false
+ }
+ }
+
+ // MARK: - Scan
+
+ /// Find every snapshot-name record in the image.
+ ///
+ /// A hit has to be `com.apple.os.update-` followed by 64 hex characters AND
+ /// sit inside a block whose fletcher64 verifies. The second condition is
+ /// what keeps identical strings baked into on-volume binaries from being
+ /// rewritten: they are file data, not metadata objects, so the block they
+ /// live in does not checksum as one.
+ public static func scan(_ image: UnsafeRawBufferPointer) -> Report {
+ var order: [Int] = []
+ var byBlock: [Int: [Int]] = [:]
+ var name: String?
+
+ let hashLength = 64
+ let needLength = oldPrefix.count + hashLength
+ guard image.count >= needLength else { return Report(snapshotName: nil, blocks: []) }
+
+ // memmem, not a hand-rolled scan: these images run to tens of
+ // gigabytes, and the Python this replaces got its speed from mmap.find
+ // being memchr-driven. A byte-at-a-time loop here would turn a few
+ // seconds into minutes.
+ guard let imageBase = image.baseAddress else {
+ return Report(snapshotName: nil, blocks: [])
+ }
+
+ var i = 0
+ while i <= image.count - needLength {
+ let found = oldPrefix.withUnsafeBytes { needle in
+ memmem(imageBase + i, image.count - i, needle.baseAddress!, oldPrefix.count)
+ }
+ guard let found else { break }
+ i = UnsafeRawPointer(found) - imageBase
+
+ // A hit this close to the end cannot carry the 64-character hash.
+ guard i <= image.count - needLength else { break }
+
+ let hashStart = i + oldPrefix.count
+ var allHex = true
+ for k in 0..<hashLength {
+ if !isHexDigit(image[hashStart + k]) { allHex = false; break }
+ }
+ guard allHex else { i += 1; continue }
+
+ let blockOffset = (i / blockSize) * blockSize
+ guard blockOffset + blockSize <= image.count else { i += 1; continue }
+ let block = UnsafeRawBufferPointer(rebasing: image[blockOffset..<blockOffset + blockSize])
+ guard blockIsValid(block) else { i += 1; continue }
+
+ if name == nil {
+ let bytes = (0..<needLength).map { image[i + $0] }
+ name = String(decoding: bytes, as: UTF8.self)
+ }
+ if byBlock[blockOffset] == nil { order.append(blockOffset) }
+ byBlock[blockOffset, default: []].append(i - blockOffset)
+ i += 1
+ }
+
+ return Report(
+ snapshotName: name,
+ blocks: order.sorted().map { ($0, byBlock[$0]!) }
+ )
+ }
+
+ // MARK: - Rename
+
+ /// Rewrite the prefix of every record found, and fix each touched block's
+ /// checksum.
+ ///
+ /// Returns the blocks it changed, in ascending order, so the caller can
+ /// report them.
+ @discardableResult
+ public static func rename(
+ imageAt url: URL,
+ newPrefix: String = defaultNewPrefix,
+ dryRun: Bool = false,
+ log: (String) -> Void = { print($0) }
+ ) throws -> Report {
+ let newPrefixBytes = Array(newPrefix.utf8)
+ guard newPrefixBytes.count == oldPrefix.count else {
+ throw VPhoneAPFSSnapshotError.prefixLengthMismatch(
+ given: newPrefixBytes.count, required: oldPrefix.count
+ )
+ }
+
+ let fd = open(url.path, dryRun ? O_RDONLY : O_RDWR)
+ guard fd >= 0 else { throw VPhoneAPFSSnapshotError.cannotOpen(url, errno: errno) }
+ defer { close(fd) }
+
+ var stats = stat()
+ guard fstat(fd, &stats) == 0 else {
+ throw VPhoneAPFSSnapshotError.cannotOpen(url, errno: errno)
+ }
+ let length = Int(stats.st_size)
+
+ let protection = dryRun ? PROT_READ : (PROT_READ | PROT_WRITE)
+ guard let base = mmap(nil, length, protection, MAP_SHARED, fd, 0),
+ base != MAP_FAILED
+ else {
+ throw VPhoneAPFSSnapshotError.cannotMap(url, errno: errno)
+ }
+ defer { munmap(base, length) }
+
+ let image = UnsafeRawBufferPointer(start: base, count: length)
+ let report = scan(image)
+
+ guard !report.isEmpty else {
+ log("No com.apple.os.update-* root snapshot found. The snapshot may already be renamed.")
+ return report
+ }
+
+ log("Detected snapshot: \(report.snapshotName ?? "?")")
+ let blockList = report.blocks.map { "'0x\(String($0.blockOffset, radix: 16))'" }
+ .joined(separator: ", ")
+ log("Records: \(report.recordCount) in \(report.blocks.count) block(s): [\(blockList)]")
+
+ if dryRun {
+ log("Dry run: the prefix would be renamed to \(newPrefix).")
+ return report
+ }
+
+ let writable = UnsafeMutableRawBufferPointer(start: base, count: length)
+ for (blockOffset, offsets) in report.blocks {
+ for within in offsets {
+ let at = blockOffset + within
+ for (k, byte) in newPrefixBytes.enumerated() {
+ writable[at + k] = byte
+ }
+ }
+ // Recompute over the block as it now stands, then stamp it in.
+ let block = UnsafeRawBufferPointer(
+ rebasing: image[blockOffset..<blockOffset + blockSize]
+ )
+ var sum = checksum(block)
+ withUnsafeBytes(of: &sum) { bytes in
+ for (k, byte) in bytes.enumerated() { writable[blockOffset + k] = byte }
+ }
+ log("Block 0x\(String(blockOffset, radix: 16)): renamed \(offsets.count) record(s) and fixed the checksum.")
+ }
+
+ guard msync(base, length, MS_SYNC) == 0 else {
+ throw VPhoneAPFSSnapshotError.cannotMap(url, errno: errno)
+ }
+ log("Done. Root snapshot renamed to \(newPrefix)*. The VM will boot the live volume.")
+ return report
+ }
+}
diff --git a/sources/VPhoneVMKit/VPhoneGuestApp.swift b/sources/VPhoneVMKit/VPhoneGuestApp.swift
index ad26ec07..18ca90f9 100644
--- a/sources/VPhoneVMKit/VPhoneGuestApp.swift
+++ b/sources/VPhoneVMKit/VPhoneGuestApp.swift
@@ -11,6 +11,10 @@ import VPhoneCore
/// `NSApplicationDelegate` method it implements internal.
public enum VPhoneGuestApp {
/// Run the guest. Returns only when the application terminates.
+ ///
+ /// `@MainActor` because NSApplication is: at the top of `main.swift` that
+ /// isolation was implicit, and moving the code into a function loses it.
+ @MainActor
public static func run(_ boot: VPhoneBootCLI) -> Never {
let app = NSApplication.shared
let delegate = VPhoneAppDelegate(cli: boot)
diff --git a/sources/vphone-cli/VPhoneRestoreCLI.swift b/sources/vphone-cli/VPhoneRestoreCLI.swift
index 30088d1b..6805e94b 100644
--- a/sources/vphone-cli/VPhoneRestoreCLI.swift
+++ b/sources/vphone-cli/VPhoneRestoreCLI.swift
@@ -97,7 +97,43 @@ struct VPhoneCFWCommand: ParsableCommand {
static let configuration = CommandConfiguration(
commandName: "cfw",
abstract: "Custom-firmware install (host-mount; VM must be off; re-execs sudo)",
- subcommands: [VPhoneCFWInstallCommand.self])
+ subcommands: [VPhoneCFWInstallCommand.self, VPhoneCFWFlipSnapshotCommand.self])
+}
+
+/// Replaces `tools/apfs_snap_rename.py`, called from `cfw_install_host.sh`
+/// once the install is done.
+struct VPhoneCFWFlipSnapshotCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "flip-snapshot",
+ abstract: "Rename the APFS root snapshot in a Disk.img so the guest boots the live volume",
+ discussion: """
+ Renames the com.apple.os.update-<hash> system snapshot in place, so a
+ guest kernel with seal enforcement patched out cannot find the named
+ root snapshot and roots the live volume instead. Offline: no mount, no
+ fs_snapshot syscall, no host security change.
+
+ Only records inside a block whose APFS checksum verifies are touched,
+ so identical strings baked into on-volume binaries are left alone.
+
+ The VM must be powered off.
+ """
+ )
+
+ @Argument(help: "Path to the VM's Disk.img", transform: URL.init(fileURLWithPath:))
+ var image: URL
+
+ @Flag(name: .customLong("dry-run"), help: "Report what would change and exit")
+ var dryRun = false
+
+ @Option(
+ name: .customLong("new-prefix"),
+ help: "Replacement prefix. Must be exactly as long as 'com.apple.os.update-'."
+ )
+ var newPrefix: String = VPhoneAPFSSnapshot.defaultNewPrefix
+
+ func run() throws {
+ try VPhoneAPFSSnapshot.rename(imageAt: image, newPrefix: newPrefix, dryRun: dryRun)
+ }
}
struct VPhoneCFWInstallCommand: ParsableCommand {
@@ -146,6 +182,9 @@ struct VPhoneCFWInstallCommand: ParsableCommand {
try FileManager.default.createDirectory(at: resources.sealVolumeCacheDir, withIntermediateDirectories: true)
try FileManager.default.createDirectory(at: resources.debsCacheDir, withIntermediateDirectories: true)
var scriptEnv: [String: String] = [
+ // The script re-execs under sudo, so it cannot work out where we
+ // live from its own path in the bundled case. Tell it.
+ "VPHONE_CLI_BIN": VPhoneResources.runningExecutable().path,
"VPHONE_PYTHON": try resources.pythonExecutable().path,
"IPSW_DIR": resources.ipswCacheDir.path,
"VPHONE_SEAL_DIR": resources.sealVolumeCacheDir.path,
diff --git a/tests/VPhoneCoreTests/APFSSnapshotTests.swift b/tests/VPhoneCoreTests/APFSSnapshotTests.swift
new file mode 100644
index 00000000..7fcafb58
--- /dev/null
+++ b/tests/VPhoneCoreTests/APFSSnapshotTests.swift
@@ -0,0 +1,215 @@
+import Foundation
+import Testing
+@testable import VPhoneCore
+
+/// The acceptance criterion for this port is byte equivalence with
+/// `tools/apfs_snap_rename.py`, because what it edits is a filesystem the
+/// guest kernel then has to mount. A "close enough" rename is a VM that does
+/// not boot.
+///
+/// The fixtures here are synthetic APFS-shaped blocks rather than a real
+/// `Disk.img`: a real image is tens of gigabytes and is not in the repo, and
+/// the two properties that matter — the fletcher64 and which hits get rewritten
+/// — are exercised just as well by a handful of 4 KiB blocks. The end-to-end
+/// byte gate against a real image is a separate, manual step.
+@Suite("APFS snapshot rename")
+struct APFSSnapshotTests {
+ // MARK: - Helpers
+
+ /// A 4 KiB block carrying `payload` at `offset`, with a correct checksum.
+ static func makeValidBlock(payload: [UInt8], at offset: Int, filler: UInt8 = 0x41) -> [UInt8] {
+ var block = [UInt8](repeating: filler, count: VPhoneAPFSSnapshot.blockSize)
+ for k in 0..<8 { block[k] = 0 }
+ for (k, byte) in payload.enumerated() { block[offset + k] = byte }
+
+ let sum = block.withUnsafeBytes { VPhoneAPFSSnapshot.checksum($0) }
+ withUnsafeBytes(of: sum.littleEndian) { bytes in
+ for (k, byte) in bytes.enumerated() { block[k] = byte }
+ }
+ return block
+ }
+
+ static func snapshotName(hash: String) -> [UInt8] {
+ VPhoneAPFSSnapshot.oldPrefix + Array(hash.utf8)
+ }
+
+ static let validHash = String(repeating: "ab12cd34", count: 8) // 64 hex chars
+
+ static func write(_ bytes: [UInt8]) throws -> URL {
+ let url = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vphone-apfs-\(UUID().uuidString).img")
+ try Data(bytes).write(to: url)
+ return url
+ }
+
+ // MARK: - Checksum
+
+ @Test("fletcher64 round-trips: a block we stamp verifies")
+ func checksumVerifies() {
+ let block = Self.makeValidBlock(payload: Self.snapshotName(hash: Self.validHash), at: 100)
+ let stored = block.withUnsafeBytes { $0.loadUnaligned(as: UInt64.self) }
+ let computed = block.withUnsafeBytes { VPhoneAPFSSnapshot.checksum($0) }
+ #expect(stored == computed)
+ }
+
+ @Test("fletcher64 uses modulus 0xFFFFFFFF, not 2^32")
+ func checksumModulus() {
+ // A block of all-0xFF words is the case where the two moduli diverge:
+ // with 2^32 the sums wrap to 0, with 0xFFFFFFFF they do not. Getting
+ // this "right" in the arithmetic sense would make every checksum wrong.
+ var block = [UInt8](repeating: 0xFF, count: VPhoneAPFSSnapshot.blockSize)
+ for k in 0..<8 { block[k] = 0 }
+ let sum = block.withUnsafeBytes { VPhoneAPFSSnapshot.checksum($0) }
+ #expect(sum != 0)
+ }
+
+ // MARK: - Scan
+
+ @Test("finds a snapshot record in a valid block")
+ func findsRecord() throws {
+ let block = Self.makeValidBlock(payload: Self.snapshotName(hash: Self.validHash), at: 100)
+ let report = block.withUnsafeBytes { VPhoneAPFSSnapshot.scan($0) }
+
+ #expect(report.recordCount == 1)
+ #expect(report.blocks.count == 1)
+ #expect(report.blocks[0].blockOffset == 0)
+ #expect(report.blocks[0].offsetsInBlock == [100])
+ #expect(report.snapshotName == "com.apple.os.update-" + Self.validHash)
+ }
+
+ @Test("ignores a hit in a block that does not checksum")
+ func ignoresNonMetadataBlock() throws {
+ // This is the case that matters: the same string is baked into binaries
+ // sitting on the volume. Those are file data, so the block they live in
+ // is not an APFS object and must never be rewritten.
+ var block = Self.makeValidBlock(payload: Self.snapshotName(hash: Self.validHash), at: 100)
+ block[9] ^= 0xFF // corrupt a byte the checksum covers
+
+ let report = block.withUnsafeBytes { VPhoneAPFSSnapshot.scan($0) }
+ #expect(report.isEmpty)
+ }
+
+ @Test("ignores a prefix not followed by 64 hex characters")
+ func ignoresNonHexSuffix() throws {
+ let notAHash = String(repeating: "zz", count: 32) // 64 chars, not hex
+ let block = Self.makeValidBlock(payload: Self.snapshotName(hash: notAHash), at: 100)
+ let report = block.withUnsafeBytes { VPhoneAPFSSnapshot.scan($0) }
+ #expect(report.isEmpty)
+ }
+
+ @Test("finds both records when they share one block")
+ func findsTwoRecordsInOneBlock() throws {
+ // The real layout: snap_metadata value and snap_name key, normally in
+ // the same leaf node.
+ var block = [UInt8](repeating: 0x41, count: VPhoneAPFSSnapshot.blockSize)
+ for k in 0..<8 { block[k] = 0 }
+ let name = Self.snapshotName(hash: Self.validHash)
+ for (k, byte) in name.enumerated() { block[200 + k] = byte }
+ for (k, byte) in name.enumerated() { block[1200 + k] = byte }
+ let sum = block.withUnsafeBytes { VPhoneAPFSSnapshot.checksum($0) }
+ withUnsafeBytes(of: sum.littleEndian) { bytes in
+ for (k, byte) in bytes.enumerated() { block[k] = byte }
+ }
+
+ let report = block.withUnsafeBytes { VPhoneAPFSSnapshot.scan($0) }
+ #expect(report.recordCount == 2)
+ #expect(report.blocks.count == 1)
+ #expect(report.blocks[0].offsetsInBlock == [200, 1200])
+ }
+
+ @Test("reports blocks in ascending order")
+ func blocksAreOrdered() throws {
+ let name = Self.snapshotName(hash: Self.validHash)
+ let first = Self.makeValidBlock(payload: name, at: 100)
+ let second = Self.makeValidBlock(payload: name, at: 300, filler: 0x42)
+ let report = (first + second).withUnsafeBytes { VPhoneAPFSSnapshot.scan($0) }
+
+ #expect(report.blocks.map(\.blockOffset) == [0, VPhoneAPFSSnapshot.blockSize])
+ }
+
+ // MARK: - Rename
+
+ @Test("renames every record and leaves the block verifying")
+ func renameKeepsBlockValid() throws {
+ let name = Self.snapshotName(hash: Self.validHash)
+ let url = try Self.write(Self.makeValidBlock(payload: name, at: 100))
+ defer { try? FileManager.default.removeItem(at: url) }
+
+ try VPhoneAPFSSnapshot.rename(imageAt: url, log: { _ in })
+
+ let after = try [UInt8](Data(contentsOf: url))
+ let renamed = String(decoding: after[100..<120], as: UTF8.self)
+ #expect(renamed == VPhoneAPFSSnapshot.defaultNewPrefix)
+
+ // The point of fixing the checksum: the block still reads as an APFS
+ // object afterwards, or the volume is corrupt.
+ let stored = after.withUnsafeBytes { $0.loadUnaligned(as: UInt64.self) }
+ let computed = after.withUnsafeBytes { VPhoneAPFSSnapshot.checksum($0) }
+ #expect(stored == computed)
+ }
+
+ @Test("rename is idempotent: a second pass finds nothing")
+ func renameIsIdempotent() throws {
+ let name = Self.snapshotName(hash: Self.validHash)
+ let url = try Self.write(Self.makeValidBlock(payload: name, at: 100))
+ defer { try? FileManager.default.removeItem(at: url) }
+
+ try VPhoneAPFSSnapshot.rename(imageAt: url, log: { _ in })
+ let second = try VPhoneAPFSSnapshot.rename(imageAt: url, log: { _ in })
+ #expect(second.isEmpty)
+ }
+
+ @Test("dry run changes nothing")
+ func dryRunIsReadOnly() throws {
+ let name = Self.snapshotName(hash: Self.validHash)
+ let original = Self.makeValidBlock(payload: name, at: 100)
+ let url = try Self.write(original)
+ defer { try? FileManager.default.removeItem(at: url) }
+
+ let report = try VPhoneAPFSSnapshot.rename(imageAt: url, dryRun: true, log: { _ in })
+ #expect(report.recordCount == 1)
+ #expect(try [UInt8](Data(contentsOf: url)) == original)
+ }
+
+ @Test("a differently sized prefix is refused")
+ func rejectsWrongLengthPrefix() throws {
+ let name = Self.snapshotName(hash: Self.validHash)
+ let url = try Self.write(Self.makeValidBlock(payload: name, at: 100))
+ defer { try? FileManager.default.removeItem(at: url) }
+
+ // Same length is load-bearing, not cosmetic: a different length would
+ // move every following byte in the b-tree node and invalidate name_len.
+ #expect(throws: VPhoneAPFSSnapshotError.self) {
+ try VPhoneAPFSSnapshot.rename(imageAt: url, newPrefix: "too-short-", log: { _ in })
+ }
+ }
+
+ @Test("log lines match the Python the port replaces")
+ func logLinesAreUnchanged() throws {
+ let name = Self.snapshotName(hash: Self.validHash)
+ let url = try Self.write(Self.makeValidBlock(payload: name, at: 100))
+ defer { try? FileManager.default.removeItem(at: url) }
+
+ var lines: [String] = []
+ try VPhoneAPFSSnapshot.rename(imageAt: url, dryRun: true, log: { lines.append($0) })
+
+ #expect(lines == [
+ "Detected snapshot: com.apple.os.update-\(Self.validHash)",
+ "Records: 1 in 1 block(s): ['0x0']",
+ "Dry run: the prefix would be renamed to orig-fs.disabled.rn-.",
+ ])
+ }
+
+ @Test("says so when there is nothing to rename")
+ func reportsNothingFound() throws {
+ let url = try Self.write([UInt8](repeating: 0x41, count: VPhoneAPFSSnapshot.blockSize))
+ defer { try? FileManager.default.removeItem(at: url) }
+
+ var lines: [String] = []
+ let report = try VPhoneAPFSSnapshot.rename(imageAt: url, log: { lines.append($0) })
+ #expect(report.isEmpty)
+ #expect(lines == [
+ "No com.apple.os.update-* root snapshot found. The snapshot may already be renamed.",
+ ])
+ }
+}
diff --git a/tests/VPhoneCoreTests/ResourcesTests.swift b/tests/VPhoneCoreTests/ResourcesTests.swift
index ef240aa9..bcf6f1b0 100644
--- a/tests/VPhoneCoreTests/ResourcesTests.swift
+++ b/tests/VPhoneCoreTests/ResourcesTests.swift
@@ -2,6 +2,13 @@
import Foundation
import Testing
+/// `.serialized` because several of these set and unset `VPHONE_ROOT`, and the
+/// environment is process-global: run in parallel, one test's
+/// `defer { unsetenv(...) }` clears the variable another is still relying on.
+/// That was a real intermittent failure — roughly one run in ten —
+/// and the reason two tests below bail out early when `VPHONE_ROOT` is already
+/// set, which was a way of tolerating the race rather than fixing it.
+@Suite(.serialized)
struct ResourcesTests {
@Test func bundledLayoutResolvesToContentsResources() {
let exe = "/Applications/vphone-cli.app/Contents/MacOS/vphone-cli"
diff --git a/tools/apfs_snap_rename.py b/tools/apfs_snap_rename.py
index 0334fbba..7bad6390 100755
--- a/tools/apfs_snap_rename.py
+++ b/tools/apfs_snap_rename.py
@@ -1,4 +1,17 @@
#!/usr/bin/env python3
+# REFERENCE IMPLEMENTATION -- no longer called by anything.
+#
+# Superseded 2026-09-23 by `vphone-cli cfw flip-snapshot`
+# (sources/VPhoneCore/VPhoneAPFSSnapshot.swift). The two were compared on a
+# synthetic multi-block fixture and produced byte-identical images and
+# character-identical output, including the decoy block that must NOT be
+# rewritten.
+#
+# It is kept only until that comparison has been repeated once against a real
+# Disk.img, because the blast radius of getting this wrong is a corrupt guest
+# filesystem and having the reference to hand beats reading it out of git.
+# Delete it then -- it is one of the files D1 counts.
+#
# Offline APFS root-snapshot rename for vphone Disk.img (CFW boot-source flip).
#
# Renames the com.apple.os.update-<hash> system snapshot in place so the