Run a virtual iPhone on an Apple Silicon Mac.
Swift
Attach the template trim's disk image with diskutil
Jacky7b6f2f6b346e
diff --git a/Research/Host/machine_templates.md b/Research/Host/machine_templates.mdindex 4fe26932..3c11ae6d 100644--- a/Research/Host/machine_templates.md+++ b/Research/Host/machine_templates.md@@ -200,14 +200,17 @@ How it runs, without root:template or a folder directly in `.templates`, and a machine with a`TemplateSource.plist` (its blocks are the template's; deleting files wouldfree nothing).-2. `hdiutil attach -nomount -imagekey diskimage-class=CRawDiskImage Disk.img`- (`Disk.img` must be a regular single-link file, owned by the invoking user- under sudo).-3. The `Apple_APFS` partition from the attach output, its- `APFSContainerReference` from `diskutil info -plist`, and the one volume- whose `Roles` contain `System` from `diskutil apfs list -plist`, after- checking the container's physical store is that partition. No slice- numbers.+2. `diskutil image attach -noMount Disk.img` (`Disk.img` must be a regular+ single-link file, owned by the invoking user under sudo). `diskutil` takes+ no image-class key and needs none: it attaches the headerless image as raw+ and, with `-noMount`, mounts none of its volumes. A failed attach is read+ for a device all the same, and one is ejected.+3. The `Apple_APFS` partition from the attach output (`<device>\t<content>`+ lines; the synthesized container's `Apple_APFS_Container` and+ `Apple_APFS_Volume` lines are skipped), its `APFSContainerReference`+ from `diskutil info -plist`, and the one volume whose `Roles` contain+ `System` from `diskutil apfs list -plist`, after checking the+ container's physical store is that partition. No slice numbers.4. `diskutil mount -mountOptions nosuid,nodev,noowners,nobrowse -mountPoint<mkdtemp 0700 folder in /private/var/tmp>/system <volume>`. A user whoattached the image may mount it this way; as root it works the same.@@ -218,8 +221,9 @@ How it runs, without root:link at the leaf is deleted as a link, and each target must pass`VPhoneSystemTrimSpec.permits` first. Bytes removed are the `st_blocks` ofwhat went, a second hard link counting as nothing; each entry is logged.-7. Unmount (`force` as a fallback) and detach (`-force` as a fallback) on- every way out, then record `Steps.TrimTier`.+7. Unmount (`force` as a fallback) and `diskutil eject` the image's disk (a+ forced `diskutil unmountDisk` and a second eject as the fallback, the form+ macOS 15 also accepts) on every way out, then record `Steps.TrimTier`.### The snapshot dependencydiff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneMachineTemplateTrimmer.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneMachineTemplateTrimmer.swiftindex 1691140d..95ae505e 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneMachineTemplateTrimmer.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneMachineTemplateTrimmer.swift@@ -4,10 +4,10 @@ import Foundationimport VPhoneCoreKit/// Offline trim of a stopped machine's guest System volume: attach its-/// `Disk.img` without mounting, find the System-role volume, mount it-/// read-write inside a private folder, delete the trim's entries-/// (``VPhoneSystemTrimSpec/apply(to:log:)``), unmount and detach, then record-/// the trim in the machine's `Template.plist` steps.+/// `Disk.img` without mounting (`diskutil image attach -noMount`), find the+/// System-role volume, mount it read-write inside a private folder, delete+/// the trim's entries (``VPhoneSystemTrimSpec/apply(to:log:)``), unmount and+/// eject, then record the trim in the machine's `Template.plist` steps.////// Root is not needed: an image attached by a user mounts for that user/// with `noowners`. A template build under sudo runs it as root all the@@ -113,22 +113,24 @@ enum VPhoneMachineTemplateTrimmer {throw ValidationError("Cannot create \(mountPoint.path): \(String(cString: strerror(errno)))")}- let attached = try tool(- "/usr/bin/hdiutil",- ["attach", "-nomount", "-imagekey", "diskimage-class=CRawDiskImage", disk.path],+ // `diskutil image attach` has no image-class key; it reads a headerless+ // `Disk.img` as a raw image by itself. A failed attach can still leave+ // a device, so its output is read before its exit status.+ let attach = try VPhoneProcessRunner.runCapturing(+ URL(fileURLWithPath: "/usr/sbin/diskutil"), ["image", "attach", "-noMount", disk.path],)+ let attached = attach.stdoutlet disks = VPhoneGuestDiskLayout.attachedDisks(fromAttachOutput: attached)- guard let whole = disks.wholeDisk, VPhoneGuestDiskLayout.isDeviceName(whole) else {- if let range = attached.range(of: #"/dev/disk[0-9]+"#, options: .regularExpression) {- _ = try? tool("/usr/bin/hdiutil", ["detach", "-force", String(attached[range])])- }- throw VPhoneSystemTrimError.layout("hdiutil attached no disk image")- }- defer {- if (try? tool("/usr/bin/hdiutil", ["detach", whole])) == nil {- _ = try? tool("/usr/bin/hdiutil", ["detach", "-force", whole])- }- }+ guard attach.succeeded, let whole = disks.wholeDisk, VPhoneGuestDiskLayout.isDeviceName(whole) else {+ let leftover = disks.wholeDisk.flatMap { VPhoneGuestDiskLayout.isDeviceName($0) ? $0 : nil }+ ?? attached.range(of: #"/dev/disk[0-9]+"#, options: .regularExpression).map { String(attached[$0]) }+ if let leftover { eject(leftover) }+ let detail = attach.stderr.trimmingCharacters(in: .whitespacesAndNewlines)+ throw VPhoneSystemTrimError.layout(attach.succeeded+ ? "diskutil attached no disk image"+ : "diskutil image attach failed (\(attach.exitCode)): \(detail)")+ }+ defer { eject(whole) }guard let store = disks.store, VPhoneGuestDiskLayout.isDeviceName(store) else {throw VPhoneSystemTrimError.layout("the image on \(whole) has no APFS partition")}@@ -162,14 +164,29 @@ enum VPhoneMachineTemplateTrimmer {}}+ /// `diskutil eject`, and when that fails (a volume still busy), a forced+ /// `unmountDisk` and a second eject: the `diskutil` form of `hdiutil+ /// detach -force` that macOS 15 also accepts.+ private static func eject(_ device: String) {+ if (try? tool("/usr/sbin/diskutil", ["eject", device])) == nil {+ _ = try? tool("/usr/sbin/diskutil", ["unmountDisk", "force", device])+ _ = try? tool("/usr/sbin/diskutil", ["eject", device])+ }+ }+/// A fresh 0700 folder under `/private/var/tmp`, named by `mkdtemp` so it/// cannot be predicted or claimed beforehand.private static func makeWorkDirectory() throws -> URL {var template = Array("/private/var/tmp/vphone-trim.XXXXXXXX".utf8CString)- guard let made = mkdtemp(&template) else {+ // Read the name while the buffer mkdtemp returns a pointer into is+ // still pinned; `&template` lends one that ends with the call (#628).+ let made = template.withUnsafeMutableBufferPointer { buffer in+ mkdtemp(buffer.baseAddress!).map { String(cString: $0) }+ }+ guard let made else {throw ValidationError("Cannot create a work folder in /private/var/tmp: \(String(cString: strerror(errno)))")}- return URL(fileURLWithPath: String(cString: made), isDirectory: true)+ return URL(fileURLWithPath: made, isDirectory: true)}@discardableResultdiff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneSystemTrim.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneSystemTrim.swiftindex 1645e8b3..3210ffac 100644--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneSystemTrim.swift+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneSystemTrim.swift@@ -406,13 +406,15 @@ public extension VPhoneSystemTrim {// MARK: - Disk layout-/// Reading `hdiutil attach` and `diskutil` output to find a guest image's-/// System volume by its APFS role, not by slice number.+/// Reading `diskutil image attach` and `diskutil` output to find a guest+/// image's System volume by its APFS role, not by slice number.public enum VPhoneGuestDiskLayout {/// The attached image's whole disk and its APFS physical store, from- /// `hdiutil attach -nomount` output (`/dev/disk6 GUID_partition_scheme`,- /// `/dev/disk6s1 Apple_APFS`, and on macOS 27 the synthesized- /// container's own lines, which are neither).+ /// `diskutil image attach -noMount` output: one `<device>\t<content>` line+ /// per device (`/dev/disk8 \tGUID_partition_scheme`,+ /// `/dev/disk8s1\tApple_APFS`), then the synthesized container's own+ /// lines (`Apple_APFS_Container`, `Apple_APFS_Volume`), which are neither+ /// and may also come first.public static func attachedDisks(fromAttachOutput output: String) -> (wholeDisk: String?, store: String?) {let devices = output.split(whereSeparator: \.isNewline).compactMap { line -> (device: String, type: String)? inlet fields = line.split(whereSeparator: \.isWhitespace)diff --git a/VPhoneKit/VPhoneCoreKitTests/Bundle/SystemTrimTests.swift b/VPhoneKit/VPhoneCoreKitTests/Bundle/SystemTrimTests.swiftindex bae3a2d7..393747e6 100644--- a/VPhoneKit/VPhoneCoreKitTests/Bundle/SystemTrimTests.swift+++ b/VPhoneKit/VPhoneCoreKitTests/Bundle/SystemTrimTests.swift@@ -5,7 +5,7 @@ import Testing/// The offline trim of a template's System volume: the tier lists, the path/// rules, applying a trim to a folder laid out like the volume, and reading-/// the disk layout from `hdiutil` and `diskutil` output.+/// the disk layout from `diskutil image attach` and `diskutil` output.struct SystemTrimTests {// MARK: - Lists@@ -288,16 +288,24 @@ struct SystemTrimTests {// MARK: - Disk layout- @Test func `the attached disk and its APFS store come from hdiutil output`() {- let output = """- /dev/disk6 \tGUID_partition_scheme \t- /dev/disk6s1 \tApple_APFS \t- /dev/disk7 \tEF57347C-0000-11AA-AA11-0030654\t- /dev/disk7s1 \t41504653-0000-11AA-AA11-0030654\t- """+ @Test func `the attached disk and its APFS store come from diskutil image attach output`() {+ // `diskutil image attach -noMount` of a guest Disk.img on macOS 27.0.1,+ // byte for byte: the image's disk first, then the synthesized container.+ let output = "/dev/disk8 \tGUID_partition_scheme\n/dev/disk8s1\tApple_APFS\n"+ + "/dev/disk9 \tApple_APFS_Container\n"+ + (1 ... 7).map { "/dev/disk9s\($0)\tApple_APFS_Volume\n" }.joined()let disks = VPhoneGuestDiskLayout.attachedDisks(fromAttachOutput: output)- #expect(disks.wholeDisk == "disk6")- #expect(disks.store == "disk6s1")+ #expect(disks.wholeDisk == "disk8")+ #expect(disks.store == "disk8s1")+ // The container's lines first, as `hdiutil attach` printed them on+ // macOS 27, still give the image's own disk.+ let containerFirst = "/dev/disk9 \tApple_APFS_Container\n/dev/disk9s1\tApple_APFS_Volume\n"+ + "/dev/disk8 \tGUID_partition_scheme\n/dev/disk8s1\tApple_APFS\n"+ let reordered = VPhoneGuestDiskLayout.attachedDisks(fromAttachOutput: containerFirst)+ #expect(reordered.wholeDisk == "disk8")+ #expect(reordered.store == "disk8s1")+ // Without the partition-scheme line the store's parent is the disk.+ #expect(VPhoneGuestDiskLayout.attachedDisks(fromAttachOutput: "/dev/disk8s1\tApple_APFS\n").wholeDisk == "disk8")#expect(VPhoneGuestDiskLayout.attachedDisks(fromAttachOutput: "").wholeDisk == nil)#expect(VPhoneGuestDiskLayout.isDeviceName("disk12s3"))#expect(!VPhoneGuestDiskLayout.isDeviceName("/dev/disk1"))