Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(lume): expand macOS disks safely (#2174)

Francesco Bonaccicda10a4f41c3
diff --git a/docs/content/docs/concepts/how-lume-expands-macos-disks.mdx b/docs/content/docs/concepts/how-lume-expands-macos-disks.mdx
new file mode 100644
index 0000000000..8867bdb2e0
--- /dev/null
+++ b/docs/content/docs/concepts/how-lume-expands-macos-disks.mdx
@@ -0,0 +1,74 @@
+---
+title: How Lume expands macOS disks
+description: Understand RecoveryOS relocation, APFS growth, and rollback during a Lume disk resize.
+---
+
+A macOS virtual disk contains more than the main APFS container. Apple silicon
+macOS installations also include iBoot System Container (ISC) and paired
+RecoveryOS partitions. Their order determines where new capacity appears when
+the disk image grows.
+
+## Why growing the image is insufficient
+
+A standard Lume macOS disk has this layout:
+
+```text
+[ ISC ][ main APFS ][ RecoveryOS ]
+```
+
+Increasing the length of `disk.img` appends free sectors after RecoveryOS:
+
+```text
+[ ISC ][ main APFS ][ RecoveryOS ][ free space ]
+```
+
+APFS can grow only into adjacent free space. RecoveryOS therefore prevents the
+main container from using the appended capacity. Increasing the image length
+alone changes the virtual device size without increasing the guest filesystem.
+
+## RecoveryOS moves with its identity intact
+
+Lume resizes a stopped macOS VM offline. It copies RecoveryOS to the new end of
+the disk, preserving the partition type, unique identifier, attributes, size,
+and contents. It then rewrites both GUID Partition Table copies and asks
+`diskutil` to grow the main APFS container into the adjacent space.
+
+```text
+[ ISC ][ expanded main APFS ][ RecoveryOS ]
+```
+
+Keeping RecoveryOS preserves the paired recovery environment used by macOS
+updates and startup-security operations. Deleting the partition can make the
+space available, but leaves the VM without that paired environment.
+
+## Resizing is a transaction
+
+Before modifying the disk, Lume validates the partition table, confirms that
+the VM is stopped, and creates a copy-on-write backup when the storage volume
+supports it. A persistent marker records the transaction phase. Run, clone,
+and push operations refuse to use the VM while that marker exists.
+
+Lume verifies the relocated RecoveryOS bytes and the expanded APFS capacity
+before it updates the configured disk size. If a step fails, it restores the
+disk and configuration from the backup. A later resize invocation also detects
+and restores an interrupted transaction.
+
+Skipping the backup removes automatic rollback. It does not relax partition,
+VM-state, or post-resize verification checks.
+
+## Supported layouts
+
+The resizer accepts the standard three-partition Lume macOS layout and fails
+closed when it finds unfamiliar geometry. It supports increases only. FileVault
+guests are excluded because offline host tools cannot safely validate and grow
+their encrypted APFS state through this flow.
+
+Linux disk images do not contain paired RecoveryOS. Lume can increase their
+image size, but the guest remains responsible for growing its partition and
+filesystem.
+
+## Related pages
+
+- [Manage local Lume VMs](/how-to-guides/lume/manage-vms#expand-a-vm-disk)
+- [How SIP works in Lume VMs](/concepts/how-sip-works-in-lume-vms)
+- [Lume CLI reference](/reference/lume/cli-reference#set)
diff --git a/docs/content/docs/concepts/meta.json b/docs/content/docs/concepts/meta.json
index 55e4f5d72f..f2be3f720f 100644
--- a/docs/content/docs/concepts/meta.json
+++ b/docs/content/docs/concepts/meta.json
@@ -1 +1 @@
-{ "title": "Concepts", "icon": "Lightbulb", "pages": ["index", "what-is-computer-use", "the-no-foreground-contract", "capture-and-delivery-modalities", "how-sandboxes-work", "how-lume-unattended-setup-works", "how-sip-works-in-lume-vms"] }
+{ "title": "Concepts", "icon": "Lightbulb", "pages": ["index", "what-is-computer-use", "the-no-foreground-contract", "capture-and-delivery-modalities", "how-sandboxes-work", "how-lume-unattended-setup-works", "how-sip-works-in-lume-vms", "how-lume-expands-macos-disks"] }
diff --git a/docs/content/docs/how-to-guides/lume/expand-vm-disk.mdx b/docs/content/docs/how-to-guides/lume/expand-vm-disk.mdx
new file mode 100644
index 0000000000..fe3d097c20
--- /dev/null
+++ b/docs/content/docs/how-to-guides/lume/expand-vm-disk.mdx
@@ -0,0 +1,57 @@
+---
+title: Expand a VM disk
+description: Increase a stopped Lume VM's disk and verify the guest capacity.
+---
+
+Use this guide to increase an existing VM's total disk capacity. Lume does not
+support shrinking VM disks.
+
+## Preview the resize
+
+Stop the VM and validate the proposed size without changing the disk:
+
+```bash
+lume stop macos-tahoe
+lume set macos-tahoe --disk-size 120GB --dry-run
+```
+
+Resolve any reported layout, encryption, host-space, or VM-state error before
+continuing.
+
+## Expand the disk
+
+Set the new total capacity:
+
+```bash
+lume set macos-tahoe --disk-size 120GB
+```
+
+Lume creates a rollback copy for macOS VMs. The operation can take several
+minutes while Lume preserves RecoveryOS and expands the APFS container.
+
+Use `--keep-backup` to retain the rollback files after success:
+
+```bash
+lume set macos-tahoe --disk-size 120GB --keep-backup
+```
+
+Use `--no-backup` only when you have another verified copy of the VM. Automatic
+rollback is unavailable when a resize without a backup fails.
+
+## Verify the guest capacity
+
+Boot the VM and inspect its root container:
+
+```bash
+lume run --no-display macos-tahoe
+lume ssh macos-tahoe 'diskutil info / | grep "Container Total Space"'
+lume stop macos-tahoe
+```
+
+For Linux VMs, grow the guest partition and filesystem after Lume increases the
+image. The exact commands depend on the partition table and filesystem.
+
+See [Disk resizing limits](/reference/lume/limits#disk-resizing) for supported
+macOS layouts. Read [How Lume expands macOS
+disks](/concepts/how-lume-expands-macos-disks) for the RecoveryOS and rollback
+model.
diff --git a/docs/content/docs/how-to-guides/lume/manage-vms.mdx b/docs/content/docs/how-to-guides/lume/manage-vms.mdx
index 637b742fc5..31360921e1 100644
--- a/docs/content/docs/how-to-guides/lume/manage-vms.mdx
+++ b/docs/content/docs/how-to-guides/lume/manage-vms.mdx
@@ -86,6 +86,11 @@ The default VM directory is `~/.lume`. Run Lume as the same user that owns this
directory; `sudo lume` uses a different home directory and cannot see those
VMs.
+## Expand a VM disk
+
+Follow [Expand a VM disk](/how-to-guides/lume/expand-vm-disk) to preview the
+change, grow the disk, and verify the guest capacity.
+
## Clone and remove VMs
Clone a VM before making changes or using it as a reusable starting point:
diff --git a/docs/content/docs/how-to-guides/lume/meta.json b/docs/content/docs/how-to-guides/lume/meta.json
index a59cb1648b..b96e959fa5 100644
--- a/docs/content/docs/how-to-guides/lume/meta.json
+++ b/docs/content/docs/how-to-guides/lume/meta.json
@@ -1 +1 @@
-{ "title": "Lume", "pages": ["install-lume", "create-vanilla-vm", "manage-vms", "change-sip", "serve-api", "use-mcp-server"] }
+{ "title": "Lume", "pages": ["install-lume", "create-vanilla-vm", "manage-vms", "expand-vm-disk", "change-sip", "serve-api", "use-mcp-server"] }
diff --git a/docs/content/docs/how-to-guides/lume/use-mcp-server.mdx b/docs/content/docs/how-to-guides/lume/use-mcp-server.mdx
index 605b4dd51e..c32a4eeba3 100644
--- a/docs/content/docs/how-to-guides/lume/use-mcp-server.mdx
+++ b/docs/content/docs/how-to-guides/lume/use-mcp-server.mdx
@@ -29,8 +29,9 @@ which lume
```
Restart the MCP client after saving its configuration. The client can then
-list VMs, create Tahoe guests, run and stop VMs, clone disks, and execute SSH
-commands inside unattended guests.
+list VMs, create Tahoe guests, run and stop VMs, clone or resize disks, and
+execute SSH commands inside unattended guests. See [Lume MCP tools](/reference/lume/mcp-tools)
+for the tool schemas.
## Test the server
diff --git a/docs/content/docs/reference/lume/cli-reference.mdx b/docs/content/docs/reference/lume/cli-reference.mdx
index 768b3cb96c..6e024248b2 100644
--- a/docs/content/docs/reference/lume/cli-reference.mdx
+++ b/docs/content/docs/reference/lume/cli-reference.mdx
@@ -7,12 +7,12 @@ description: Command Line Interface reference for Lume
AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
Generated by: npx tsx scripts/docs-generators/lume.ts
Source: lume dump-docs --type cli
- Version: 0.3.13
+ Version: 0.3.14
*/}
A lightweight CLI and local API server to build, run and manage macOS VMs.
-Documented against Lume **0.3.13**. Run `lume --version` for your installed version.
+Documented against Lume **0.3.14**. Run `lume --version` for your installed version.
For installation steps, see [Install Lume](/how-to-guides/lume/install-lume).
@@ -181,10 +181,18 @@ Set new values for CPU, memory, and disk size of a virtual machine
| ---- | ---- | ------- | ----------- |
| `--cpu` | Int | - | New number of CPU cores |
| `--memory` | String | - | New memory size (e.g., 8GB) |
-| `--disk-size` | String | - | New disk size (e.g., 100GB) |
+| `--disk-size` | String | - | New total disk size. Increase only; macOS resizing preserves RecoveryOS and grows APFS. |
| `--display` | String | - | New display resolution |
| `--storage` | String | - | VM storage location to use |
+**Flags:**
+
+| Name | Default | Description |
+| ---- | ------- | ----------- |
+| `--no-backup` | false | Skip the macOS rollback backup |
+| `--keep-backup` | false | Keep rollback files after a successful macOS resize |
+| `--dry-run` | false | Validate the resize plan without modifying the disk |
+
## Image Management
### lume images
diff --git a/docs/content/docs/reference/lume/http-api.mdx b/docs/content/docs/reference/lume/http-api.mdx
index 268fd8d288..e8e562a059 100644
--- a/docs/content/docs/reference/lume/http-api.mdx
+++ b/docs/content/docs/reference/lume/http-api.mdx
@@ -7,14 +7,14 @@ description: HTTP API reference for Lume server
AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
Generated by: npx tsx scripts/docs-generators/lume.ts
Source: lume dump-docs --type api
- Version: 0.3.13
+ Version: 0.3.14
*/}
import { Tabs, Tab } from 'fumadocs-ui/components/tabs';
HTTP API for managing macOS and Linux virtual machines
-Documented against Lume **0.3.13**. Run `lume --version` for your installed version.
+Documented against Lume **0.3.14**. Run `lume --version` for your installed version.
## Default URL
@@ -319,9 +319,12 @@ Update virtual machine configuration settings
| ---- | ---- | -------- | ----------- |
| cpu | integer | No | New number of CPU cores |
| memory | string | No | New memory size (e.g., 16GB) |
-| diskSize | string | No | New disk size (e.g., 100GB) |
+| diskSize | string | No | New total disk size (increase only) |
| display | string | No | New display resolution |
| storage | string | No | VM storage location |
+| noBackup | boolean | No | Skip the macOS rollback backup (default: false) |
+| keepBackup | boolean | No | Keep rollback files after success (default: false) |
+| dryRun | boolean | No | Validate the resize plan without modifying the disk (default: false) |
#### Example Request
diff --git a/docs/content/docs/reference/lume/limits.mdx b/docs/content/docs/reference/lume/limits.mdx
index 8e56435c02..c4215fd233 100644
--- a/docs/content/docs/reference/lume/limits.mdx
+++ b/docs/content/docs/reference/lume/limits.mdx
@@ -80,3 +80,17 @@ lume ssh macos-tahoe 'id -un'
macOS VM disks use sparse files. The configured disk capacity describes the
guest's logical disk. The host allocation grows as the guest writes data.
+
+## Disk resizing
+
+- Disk resizing is increase-only and requires a stopped VM.
+- macOS resizing supports the standard Lume layout: ISC, main APFS, then paired
+ RecoveryOS.
+- FileVault-encrypted macOS guests are unsupported.
+- The host must run the same or a newer macOS version than the guest.
+- The default rollback copy requires enough host capacity for the allocated
+ RecoveryOS data and copy-on-write metadata.
+- The first macOS increase must leave enough room to relocate RecoveryOS without
+ overlapping its old location. Lume reports the minimum accepted total size.
+- Linux resizing increases the image only. Grow the partition and filesystem in
+ the guest.
diff --git a/docs/content/docs/reference/lume/mcp-tools.mdx b/docs/content/docs/reference/lume/mcp-tools.mdx
new file mode 100644
index 0000000000..93ced647eb
--- /dev/null
+++ b/docs/content/docs/reference/lume/mcp-tools.mdx
@@ -0,0 +1,27 @@
+---
+title: MCP tools
+description: Tool reference for Lume's stdio MCP server.
+---
+
+Start the server with `lume serve --mcp`. Tool names use `snake_case`.
+
+## `lume_resize_disk`
+
+Grow a stopped VM disk to a new total size.
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `name` | string | yes | VM name. |
+| `disk_size` | string | yes | New total size, such as `120GB`. Must exceed the current size. |
+| `storage` | string | no | Named storage location or direct path. |
+| `no_backup` | boolean | no | Skip the macOS rollback copy. Defaults to `false`. |
+| `keep_backup` | boolean | no | Keep rollback files after success. Defaults to `false`. |
+| `dry_run` | boolean | no | Validate and print the plan without changing the disk. Defaults to `false`. |
+
+`no_backup` and `keep_backup` cannot both be true. macOS resizing preserves the
+paired RecoveryOS partition and expands the main APFS container. Linux resizing
+increases the image only.
+
+The MCP server also exposes tools for listing, creating, running, stopping,
+cloning, deleting, and accessing VMs. Clients should discover the live tool
+list from MCP so their schemas match the installed Lume version.
diff --git a/docs/content/docs/reference/lume/meta.json b/docs/content/docs/reference/lume/meta.json
index 84be1046f3..57a2440d6b 100644
--- a/docs/content/docs/reference/lume/meta.json
+++ b/docs/content/docs/reference/lume/meta.json
@@ -1 +1 @@
-{ "title": "Lume", "pages": ["cli-reference", "http-api", "limits"] }
+{ "title": "Lume", "pages": ["cli-reference", "http-api", "mcp-tools", "limits"] }
diff --git a/libs/lume/src/Commands/Set.swift b/libs/lume/src/Commands/Set.swift
index 26c25b9325..5efb5dabbf 100644
--- a/libs/lume/src/Commands/Set.swift
+++ b/libs/lume/src/Commands/Set.swift
@@ -15,7 +15,7 @@ struct Set: AsyncParsableCommand {
@Option(help: "New memory size (e.g., 8, 8GB, or 8192MB). Numbers without units are treated as GB.", transform: { try parseSize($0) })
var memory: UInt64?
- @Option(help: "New disk size (e.g., 50, 50GB, or 51200MB). Numbers without units are treated as GB.", transform: { try parseSize($0) })
+ @Option(help: "New disk size (e.g., 50, 50GB, or 51200MB). Increase only. For macOS VMs this relocates the recovery partition and expands the main APFS container; the VM must be stopped; may take several minutes. Numbers without units are treated as GB.", transform: { try parseSize($0) })
var diskSize: UInt64?
@Option(help: "New display resolution in format WIDTHxHEIGHT.")
@@ -24,11 +24,26 @@ struct Set: AsyncParsableCommand {
@Option(name: .customLong("storage"), help: "VM storage location to use or direct path to VM location")
var storage: String?
+ @Flag(name: .customLong("no-backup"), help: "Skip the pre-resize disk backup (macOS resize only). Faster, but a failure cannot be rolled back automatically.")
+ var noBackup: Bool = false
+
+ @Flag(name: .customLong("keep-backup"), help: "Keep the pre-resize disk backup after a successful macOS resize instead of deleting it.")
+ var keepBackup: Bool = false
+
+ @Flag(name: .customLong("dry-run"), help: "Validate the disk-resize plan and print it without modifying anything (macOS resize only).")
+ var dryRun: Bool = false
+
init() {
}
@MainActor
func run() async throws {
+ if (noBackup || keepBackup || dryRun) && diskSize == nil {
+ throw ValidationError("--no-backup, --keep-backup and --dry-run are only valid together with --disk-size")
+ }
+ if noBackup && keepBackup {
+ throw ValidationError("--no-backup and --keep-backup cannot be used together")
+ }
let vmController = LumeController()
try vmController.updateSettings(
name: name,
@@ -36,7 +51,10 @@ struct Set: AsyncParsableCommand {
memory: memory,
diskSize: diskSize,
display: display?.string,
- storage: storage
+ storage: storage,
+ noBackup: noBackup,
+ keepBackup: keepBackup,
+ dryRun: dryRun
)
}
}
diff --git a/libs/lume/src/DiskResize/DiskutilContainerGrower.swift b/libs/lume/src/DiskResize/DiskutilContainerGrower.swift
new file mode 100644
index 0000000000..e96f84de0a
--- /dev/null
+++ b/libs/lume/src/DiskResize/DiskutilContainerGrower.swift
@@ -0,0 +1,114 @@
+import Foundation
+
+/// Real `ContainerGrower` that attaches the raw image with hdiutil and grows the
+/// main APFS container with `diskutil apfs resizeContainer`. Falls back to
+/// pre-growing the partition entry (Plan B) if the one-shot grow (Plan A) will
+/// not fill the adjacent gap on its own.
+@MainActor
+final class DiskutilContainerGrower: ContainerGrower {
+ func inspect(diskPath: URL) throws {
+ let session = DiskImageSession(diskPath: diskPath.path)
+ if (try? session.isAttached()) == true {
+ throw DiskResizeError.imageAttached
+ }
+ let wholeDisk = try session.attach(readWrite: false)
+ defer { session.detach() }
+ let container = try session.apfsContainer(forMainPartitionOf: wholeDisk)
+ if try isEncrypted(session: session, container: container) {
+ throw DiskResizeError.fileVaultEnabled
+ }
+ }
+
+ func grow(diskPath: URL, newRecoveryFirstLBA: UInt64) throws {
+ let handle = try FileHandle(forReadingFrom: diskPath)
+ let fileSize =
+ (try FileManager.default.attributesOfItem(atPath: diskPath.path)[.size]
+ as? NSNumber)?.uint64Value ?? 0
+ let table = try GPTTable.read(from: handle, fileSizeBytes: fileSize)
+ try handle.close()
+ let expectedSize =
+ (newRecoveryFirstLBA - table.entries[MacDiskLayout.mainIndex].startingLBA)
+ * UInt64(GPTTable.sectorSize)
+
+ // Plan A: diskutil normally stretches both P2 and its APFS container.
+ if try resizeContainer(diskPath: diskPath, expectedSize: expectedSize) { return }
+
+ Logger.info("resizeContainer did not fill the gap; pre-growing partition 2")
+ try preGrowMainPartition(diskPath: diskPath, upToLBA: newRecoveryFirstLBA - 1)
+ guard try resizeContainer(diskPath: diskPath, expectedSize: expectedSize) else {
+ throw DiskResizeError.verificationFailed(
+ "APFS physical store did not reach \(expectedSize) bytes")
+ }
+ }
+
+ // MARK: - diskutil
+
+ private func resizeContainer(diskPath: URL, expectedSize: UInt64) throws -> Bool {
+ let session = DiskImageSession(diskPath: diskPath.path)
+ let wholeDisk = try session.attach(readWrite: true)
+ defer {
+ session.unmountDiskIfMounted()
+ session.detach()
+ }
+ do {
+ _ = try session.run(
+ "/usr/sbin/diskutil", ["apfs", "resizeContainer", "\(wholeDisk)s2", "0"])
+ let container = try session.apfsContainer(forMainPartitionOf: wholeDisk)
+ let list = try session.runPlist(
+ "/usr/sbin/diskutil", ["apfs", "list", "-plist", container])
+ let containers = list["Containers"] as? [[String: Any]] ?? []
+ let matching = containers.first {
+ ($0["ContainerReference"] as? String) == container
+ || ($0["APFSContainerReference"] as? String) == container
+ }
+ let actualSize = (matching?["CapacityCeiling"] as? NSNumber)?.uint64Value ?? 0
+ return actualSize >= expectedSize
+ } catch DiskImageError.commandFailed(let command, let output) {
+ if looksLikeDirtyContainer(output) {
+ throw DiskResizeError.apfsCheckFailed(output)
+ }
+ throw DiskResizeError.commandFailed(command: command, output: output)
+ }
+ }
+
+ private func preGrowMainPartition(diskPath: URL, upToLBA endLBA: UInt64) throws {
+ let handle = try FileHandle(forUpdating: diskPath)
+ defer { try? handle.close() }
+ let fileSize =
+ ((try? FileManager.default.attributesOfItem(atPath: diskPath.path))?[.size]
+ as? NSNumber)?.uint64Value ?? 0
+ var table = try GPTTable.read(from: handle, fileSizeBytes: fileSize)
+ // Validate we still have the expected layout (recovery already relocated).
+ _ = try MacDiskLayout.fingerprint(table, fileSizeBytes: fileSize)
+ guard endLBA > table.entries[MacDiskLayout.mainIndex].endingLBA else { return }
+ table.entries[MacDiskLayout.mainIndex].endingLBA = endLBA
+ try table.write(to: handle)
+ try GPT.fullSync(handle)
+ }
+
+ private func isEncrypted(session: DiskImageSession, container: String) throws -> Bool {
+ let plist = try session.runPlist(
+ "/usr/sbin/diskutil", ["apfs", "list", "-plist", container])
+ guard let containers = plist["Containers"] as? [[String: Any]] else { return false }
+ for container in containers {
+ guard let volumes = container["Volumes"] as? [[String: Any]] else { continue }
+ for volume in volumes {
+ if (volume["FileVault"] as? Bool) == true
+ || (volume["Encryption"] as? Bool) == true
+ {
+ return true
+ }
+ }
+ }
+ return false
+ }
+
+ private func looksLikeDirtyContainer(_ output: String) -> Bool {
+ let lowered = output.lowercased()
+ return lowered.contains("could not be verified")
+ || lowered.contains("fsck")
+ || lowered.contains("not appear to be")
+ || lowered.contains("run first aid")
+ || lowered.contains("volume is not clean")
+ }
+}
diff --git a/libs/lume/src/DiskResize/GPT.swift b/libs/lume/src/DiskResize/GPT.swift
new file mode 100644
index 0000000000..6d2bb6a7e9
--- /dev/null
+++ b/libs/lume/src/DiskResize/GPT.swift
@@ -0,0 +1,433 @@
+import Darwin
+import Foundation
+
+// MARK: - CRC32
+
+/// Standard IEEE 802.3 / zlib CRC-32 (reflected, poly 0xEDB88320). Matches the
+/// checksums Apple's disk tooling writes into GPT headers.
+enum CRC32 {
+ private static let table: [UInt32] = {
+ (0..<256).map { index -> UInt32 in
+ var c = UInt32(index)
+ for _ in 0..<8 {
+ c = (c & 1) != 0 ? (0xEDB8_8320 ^ (c >> 1)) : (c >> 1)
+ }
+ return c
+ }
+ }()
+
+ static func checksum(_ bytes: [UInt8]) -> UInt32 {
+ var crc: UInt32 = 0xFFFF_FFFF
+ for byte in bytes {
+ crc = table[Int((crc ^ UInt32(byte)) & 0xFF)] ^ (crc >> 8)
+ }
+ return crc ^ 0xFFFF_FFFF
+ }
+}
+
+// MARK: - Little-endian helpers
+
+private func le32(_ b: [UInt8], _ o: Int) -> UInt32 {
+ UInt32(b[o]) | (UInt32(b[o + 1]) << 8) | (UInt32(b[o + 2]) << 16) | (UInt32(b[o + 3]) << 24)
+}
+
+private func le64(_ b: [UInt8], _ o: Int) -> UInt64 {
+ var value: UInt64 = 0
+ for i in 0..<8 { value |= UInt64(b[o + i]) << (8 * i) }
+ return value
+}
+
+private func putLE32(_ v: UInt32, into b: inout [UInt8], at o: Int) {
+ for i in 0..<4 { b[o + i] = UInt8((v >> (8 * i)) & 0xFF) }
+}
+
+private func putLE64(_ v: UInt64, into b: inout [UInt8], at o: Int) {
+ for i in 0..<8 { b[o + i] = UInt8((v >> (8 * UInt64(i))) & 0xFF) }
+}
+
+// MARK: - GPTGUID
+
+/// A GPT GUID stored as its raw 16 on-disk bytes (mixed-endian). We never need
+/// to interpret partition GUIDs beyond comparing them to known type constants
+/// and preserving them byte-for-byte, so raw storage avoids any re-encoding bug.
+struct GPTGUID: Equatable, CustomStringConvertible {
+ let bytes: [UInt8]
+
+ init(bytes: [UInt8]) {
+ precondition(bytes.count == 16, "GPT GUID must be 16 bytes")
+ self.bytes = bytes
+ }
+
+ /// Parses the canonical string form (e.g. `7C3457EF-0000-11AA-AA11-00306543ECAC`)
+ /// into the mixed-endian on-disk byte layout.
+ init?(uuidString: String) {
+ let hex = uuidString.replacingOccurrences(of: "-", with: "")
+ guard hex.count == 32 else { return nil }
+ var raw = [UInt8]()
+ raw.reserveCapacity(16)
+ var index = hex.startIndex
+ while index < hex.endIndex {
+ let next = hex.index(index, offsetBy: 2)
+ guard let byte = UInt8(hex[index..<next], radix: 16) else { return nil }
+ raw.append(byte)
+ index = next
+ }
+ // Data1 (4B) + Data2 (2B) + Data3 (2B) are little-endian; Data4/Data5 big-endian.
+ var b = [UInt8](repeating: 0, count: 16)
+ b[0] = raw[3]
+ b[1] = raw[2]
+ b[2] = raw[1]
+ b[3] = raw[0]
+ b[4] = raw[5]
+ b[5] = raw[4]
+ b[6] = raw[7]
+ b[7] = raw[6]
+ b[8] = raw[8]
+ b[9] = raw[9]
+ for i in 10..<16 { b[i] = raw[i] }
+ self.bytes = b
+ }
+
+ var isZero: Bool { bytes.allSatisfy { $0 == 0 } }
+
+ var description: String {
+ func hex(_ range: Range<Int>) -> String {
+ range.map { String(format: "%02X", bytes[$0]) }.joined()
+ }
+ let d1 = [bytes[3], bytes[2], bytes[1], bytes[0]].map { String(format: "%02X", $0) }.joined()
+ let d2 = [bytes[5], bytes[4]].map { String(format: "%02X", $0) }.joined()
+ let d3 = [bytes[7], bytes[6]].map { String(format: "%02X", $0) }.joined()
+ let d4 = hex(8..<10)
+ let d5 = hex(10..<16)
+ return "\(d1)-\(d2)-\(d3)-\(d4)-\(d5)"
+ }
+
+ // Apple partition type GUIDs (force-unwrapped: the literals are valid).
+ static let appleAPFSISC = GPTGUID(uuidString: "69646961-6700-11AA-AA11-00306543ECAC")!
+ static let appleAPFS = GPTGUID(uuidString: "7C3457EF-0000-11AA-AA11-00306543ECAC")!
+ static let appleAPFSRecovery = GPTGUID(uuidString: "52637672-7900-11AA-AA11-00306543ECAC")!
+}
+
+// MARK: - Partition entry
+
+struct GPTPartitionEntry: Equatable {
+ var typeGUID: GPTGUID
+ var uniqueGUID: GPTGUID
+ var startingLBA: UInt64
+ var endingLBA: UInt64 // inclusive
+ var attributes: UInt64
+ var nameRaw: [UInt8] // raw 72-byte UTF-16LE blob, kept verbatim
+
+ var isEmpty: Bool { typeGUID.isZero }
+ var sectorCount: UInt64 { endingLBA >= startingLBA ? endingLBA - startingLBA + 1 : 0 }
+
+ static let byteSize = 128
+
+ static func parse(_ b: [UInt8]) -> GPTPartitionEntry {
+ GPTPartitionEntry(
+ typeGUID: GPTGUID(bytes: Array(b[0..<16])),
+ uniqueGUID: GPTGUID(bytes: Array(b[16..<32])),
+ startingLBA: le64(b, 32),
+ endingLBA: le64(b, 40),
+ attributes: le64(b, 48),
+ nameRaw: Array(b[56..<128]))
+ }
+
+ func serialized() -> [UInt8] {
+ var b = [UInt8](repeating: 0, count: GPTPartitionEntry.byteSize)
+ for i in 0..<16 { b[i] = typeGUID.bytes[i] }
+ for i in 0..<16 { b[16 + i] = uniqueGUID.bytes[i] }
+ putLE64(startingLBA, into: &b, at: 32)
+ putLE64(endingLBA, into: &b, at: 40)
+ putLE64(attributes, into: &b, at: 48)
+ for i in 0..<72 { b[56 + i] = nameRaw[i] }
+ return b
+ }
+}
+
+// MARK: - Header
+
+struct GPTHeader {
+ static let signature: [UInt8] = Array("EFI PART".utf8)
+
+ var revision: UInt32
+ var headerSize: UInt32
+ var headerCRC32: UInt32
+ var myLBA: UInt64
+ var alternateLBA: UInt64
+ var firstUsableLBA: UInt64
+ var lastUsableLBA: UInt64
+ var diskGUID: GPTGUID
+ var partitionEntryLBA: UInt64
+ var numberOfPartitionEntries: UInt32
+ var sizeOfPartitionEntry: UInt32
+ var partitionEntryArrayCRC32: UInt32
+
+ /// Parses a header from a 512-byte sector. Returns nil if the signature is
+ /// wrong. Does not validate CRC (callers do that against `headerCRC32`).
+ static func parse(sector b: [UInt8]) -> GPTHeader? {
+ guard Array(b[0..<8]) == signature else { return nil }
+ return GPTHeader(
+ revision: le32(b, 8),
+ headerSize: le32(b, 12),
+ headerCRC32: le32(b, 16),
+ myLBA: le64(b, 24),
+ alternateLBA: le64(b, 32),
+ firstUsableLBA: le64(b, 40),
+ lastUsableLBA: le64(b, 48),
+ diskGUID: GPTGUID(bytes: Array(b[56..<72])),
+ partitionEntryLBA: le64(b, 72),
+ numberOfPartitionEntries: le32(b, 80),
+ sizeOfPartitionEntry: le32(b, 84),
+ partitionEntryArrayCRC32: le32(b, 88))
+ }
+
+ /// True if the stored `headerCRC32` matches the recomputed value.
+ func crcIsValid(sector b: [UInt8]) -> Bool {
+ headerCRC32 == GPTHeader.computeHeaderCRC(sector: b, headerSize: headerSize)
+ }
+
+ static func computeHeaderCRC(sector b: [UInt8], headerSize: UInt32) -> UInt32 {
+ let size = Int(headerSize)
+ guard size >= 92, size <= b.count else { return 0 }
+ var slice = Array(b[0..<size])
+ // Zero the CRC field (offset 16..<20) before checksumming.
+ for i in 16..<20 { slice[i] = 0 }
+ return CRC32.checksum(slice)
+ }
+
+ /// Serializes this header into a fresh 512-byte sector, recomputing the
+ /// header CRC over the first `headerSize` bytes.
+ func serializedSector() -> [UInt8] {
+ var b = [UInt8](repeating: 0, count: GPT.sectorSize)
+ for i in 0..<8 { b[i] = GPTHeader.signature[i] }
+ putLE32(revision, into: &b, at: 8)
+ putLE32(headerSize, into: &b, at: 12)
+ // CRC field left zero for now.
+ putLE64(myLBA, into: &b, at: 24)
+ putLE64(alternateLBA, into: &b, at: 32)
+ putLE64(firstUsableLBA, into: &b, at: 40)
+ putLE64(lastUsableLBA, into: &b, at: 48)
+ for i in 0..<16 { b[56 + i] = diskGUID.bytes[i] }
+ putLE64(partitionEntryLBA, into: &b, at: 72)
+ putLE32(numberOfPartitionEntries, into: &b, at: 80)
+ putLE32(sizeOfPartitionEntry, into: &b, at: 84)
+ putLE32(partitionEntryArrayCRC32, into: &b, at: 88)
+ let crc = GPTHeader.computeHeaderCRC(sector: b, headerSize: headerSize)
+ putLE32(crc, into: &b, at: 16)
+ return b
+ }
+}
+
+// MARK: - Table
+
+/// In-memory representation of a GPT read from a raw disk image, plus a
+/// crash-safe writer. All offsets assume 512-byte logical sectors.
+struct GPTTable {
+ static let sectorSize = 512
+
+ /// Primary header as read (fields are mutated by the resizer before write).
+ var header: GPTHeader
+ /// All `numberOfPartitionEntries` entries (populated + empty), preserved.
+ var entries: [GPTPartitionEntry]
+
+ var totalSectors: UInt64 { header.alternateLBA + 1 }
+
+ // MARK: Read
+
+ /// Reads and validates the primary GPT (and cross-checks the backup header)
+ /// from a raw disk image file handle. Throws `DiskResizeError` on any
+ /// malformation so callers get fail-closed behavior.
+ static func read(from handle: FileHandle, fileSizeBytes: UInt64) throws -> GPTTable {
+ let ss = UInt64(sectorSize)
+
+ // Primary header at LBA 1.
+ let headerSector = try readSector(handle, lba: 1)
+ guard let header = GPTHeader.parse(sector: headerSector) else {
+ // Distinguish a 4096-byte-sector image (signature at offset 4096).
+ if let alt = try? readBytes(handle, offset: 4096, count: 8),
+ alt == GPTHeader.signature
+ {
+ throw DiskResizeError.unsupportedSectorSize
+ }
+ throw DiskResizeError.unsupportedLayout("no GPT signature at LBA 1")
+ }
+ guard header.crcIsValid(sector: headerSector) else {
+ throw DiskResizeError.unsupportedLayout("primary header CRC mismatch")
+ }
+ guard header.sizeOfPartitionEntry == UInt32(GPTPartitionEntry.byteSize),
+ header.numberOfPartitionEntries >= 3, header.numberOfPartitionEntries <= 128
+ else {
+ throw DiskResizeError.unsupportedLayout("unexpected partition entry geometry")
+ }
+
+ // Primary entry array.
+ let entriesBytes = try readBytes(
+ handle,
+ offset: header.partitionEntryLBA * ss,
+ count: Int(header.numberOfPartitionEntries) * Int(header.sizeOfPartitionEntry))
+ guard CRC32.checksum(entriesBytes) == header.partitionEntryArrayCRC32 else {
+ throw DiskResizeError.unsupportedLayout("primary partition array CRC mismatch")
+ }
+ var entries = [GPTPartitionEntry]()
+ for i in 0..<Int(header.numberOfPartitionEntries) {
+ let start = i * GPTPartitionEntry.byteSize
+ entries.append(
+ GPTPartitionEntry.parse(Array(entriesBytes[start..<start + GPTPartitionEntry.byteSize])))
+ }
+
+ // Backup header consistency (must be inside the file).
+ let backupOffset = header.alternateLBA * ss
+ guard backupOffset + ss <= fileSizeBytes else {
+ throw DiskResizeError.unsupportedLayout(
+ "backup GPT header at LBA \(header.alternateLBA) is beyond the end of the file")
+ }
+ let backupSector = try readSector(handle, lba: header.alternateLBA)
+ guard let backup = GPTHeader.parse(sector: backupSector),
+ backup.crcIsValid(sector: backupSector)
+ else {
+ throw DiskResizeError.unsupportedLayout("backup GPT header missing or CRC mismatch")
+ }
+ guard backup.myLBA == header.alternateLBA, backup.alternateLBA == header.myLBA,
+ backup.firstUsableLBA == header.firstUsableLBA,
+ backup.lastUsableLBA == header.lastUsableLBA,
+ backup.diskGUID == header.diskGUID,
+ backup.numberOfPartitionEntries == header.numberOfPartitionEntries,
+ backup.sizeOfPartitionEntry == header.sizeOfPartitionEntry,
+ backup.partitionEntryArrayCRC32 == header.partitionEntryArrayCRC32
+ else {
+ throw DiskResizeError.unsupportedLayout("primary and backup GPT headers are inconsistent")
+ }
+
+ let backupEntriesOffset = backup.partitionEntryLBA * ss
+ let entriesCount = Int(backup.numberOfPartitionEntries) * Int(backup.sizeOfPartitionEntry)
+ guard backup.partitionEntryLBA > header.lastUsableLBA,
+ backupEntriesOffset + UInt64(entriesCount) <= backupOffset
+ else {
+ throw DiskResizeError.unsupportedLayout("backup partition array location is invalid")
+ }
+ let backupEntriesBytes = try readBytes(
+ handle, offset: backupEntriesOffset, count: entriesCount)
+ guard CRC32.checksum(backupEntriesBytes) == backup.partitionEntryArrayCRC32 else {
+ throw DiskResizeError.unsupportedLayout("backup partition array CRC mismatch")
+ }
+ guard backupEntriesBytes == entriesBytes else {
+ throw DiskResizeError.unsupportedLayout("primary and backup partition arrays differ")
+ }
+
+ return GPTTable(header: header, entries: entries)
+ }
+
+ // MARK: Write
+
+ /// Serializes the 128-entry array into its on-disk byte blob.
+ func serializedEntries() -> [UInt8] {
+ var blob = [UInt8]()
+ let count = Int(header.numberOfPartitionEntries)
+ blob.reserveCapacity(count * GPTPartitionEntry.byteSize)
+ for i in 0..<count { blob.append(contentsOf: entries[i].serialized()) }
+ return blob
+ }
+
+ /// Writes both GPT copies and the protective MBR using crash-safe ordering:
+ /// backup entries → backup header → fullsync → primary entries → primary
+ /// header → protective MBR → fullsync. `header.alternateLBA` /
+ /// `header.lastUsableLBA` are taken as the source of truth for total size.
+ func write(to handle: FileHandle) throws {
+ let ss = UInt64(GPTTable.sectorSize)
+ let total = totalSectors
+ let entriesBlob = serializedEntries()
+ let entriesCRC = CRC32.checksum(entriesBlob)
+ let arraySectors = UInt64(entriesBlob.count) / ss
+
+ var primary = header
+ primary.myLBA = 1
+ primary.alternateLBA = total - 1
+ primary.partitionEntryLBA = 2
+ primary.partitionEntryArrayCRC32 = entriesCRC
+
+ var backup = primary
+ backup.myLBA = total - 1
+ backup.alternateLBA = 1
+ backup.partitionEntryLBA = total - 1 - arraySectors
+
+ let entriesData = Data(entriesBlob)
+
+ // Backup copy first.
+ try handle.seek(toOffset: backup.partitionEntryLBA * ss)
+ try handle.write(contentsOf: entriesData)
+ try handle.seek(toOffset: (total - 1) * ss)
+ try handle.write(contentsOf: Data(backup.serializedSector()))
+ try GPT.fullSync(handle)
+
+ // Primary copy.
+ try handle.seek(toOffset: 2 * ss)
+ try handle.write(contentsOf: entriesData)
+ try handle.seek(toOffset: 1 * ss)
+ try handle.write(contentsOf: Data(primary.serializedSector()))
+
+ try updateProtectiveMBR(handle: handle, totalSectors: total)
+ try GPT.fullSync(handle)
+ }
+
+ /// Updates the protective MBR's 0xEE record size-in-LBA field, preserving
+ /// boot code and the 0x55AA signature. Clamps to 0xFFFFFFFF per spec.
+ private func updateProtectiveMBR(handle: FileHandle, totalSectors: UInt64) throws {
+ var mbr = try GPTTable.readSector(handle, lba: 0)
+ let sizeInLBA = UInt32(min(totalSectors - 1, UInt64(UInt32.max)))
+ var updated = false
+ for record in 0..<4 {
+ let base = 446 + record * 16
+ if mbr[base + 4] == 0xEE {
+ putLE32(sizeInLBA, into: &mbr, at: base + 12) // size-in-LBA field
+ updated = true
+ }
+ }
+ if !updated {
+ // Synthesize a canonical protective MBR record if none present.
+ let base = 446
+ mbr[base] = 0x00
+ mbr[base + 1] = 0x00
+ mbr[base + 2] = 0x02
+ mbr[base + 3] = 0x00
+ mbr[base + 4] = 0xEE
+ mbr[base + 5] = 0xFF
+ mbr[base + 6] = 0xFF
+ mbr[base + 7] = 0xFF
+ putLE32(1, into: &mbr, at: base + 8)
+ putLE32(sizeInLBA, into: &mbr, at: base + 12)
+ }
+ mbr[510] = 0x55
+ mbr[511] = 0xAA
+ try handle.seek(toOffset: 0)
+ try handle.write(contentsOf: Data(mbr))
+ }
+
+ // MARK: Low-level IO
+
+ static func readSector(_ handle: FileHandle, lba: UInt64) throws -> [UInt8] {
+ try readBytes(handle, offset: lba * UInt64(sectorSize), count: sectorSize)
+ }
+
+ static func readBytes(_ handle: FileHandle, offset: UInt64, count: Int) throws -> [UInt8] {
+ try handle.seek(toOffset: offset)
+ guard let data = try handle.read(upToCount: count), data.count == count else {
+ throw DiskResizeError.unsupportedLayout(
+ "could not read \(count) bytes at offset \(offset)")
+ }
+ return [UInt8](data)
+ }
+}
+
+// MARK: - Sync
+
+enum GPT {
+ static let sectorSize = 512
+
+ static func fullSync(_ handle: FileHandle) throws {
+ guard fcntl(handle.fileDescriptor, F_FULLFSYNC) == 0 else {
+ let details = String(cString: strerror(errno))
+ throw DiskResizeError.commandFailed(command: "fcntl(F_FULLFSYNC)", output: details)
+ }
+ }
+}
diff --git a/libs/lume/src/DiskResize/MacDiskLayout.swift b/libs/lume/src/DiskResize/MacDiskLayout.swift
new file mode 100644
index 0000000000..ecb12f9991
--- /dev/null
+++ b/libs/lume/src/DiskResize/MacDiskLayout.swift
@@ -0,0 +1,103 @@
+import Foundation
+
+/// The validated, known-good macOS 3-partition layout: iBootSystemContainer
+/// (ISC), the main APFS container, and the RecoveryOS container last on disk.
+///
+/// `fingerprint` fails closed unless every expected invariant holds, so the
+/// resize engine only ever operates on a layout it fully understands.
+struct MacDiskLayout {
+ /// 4 KiB / 512 B = 8-sector alignment used by the factory layout.
+ static let alignment: UInt64 = 8
+ static let iscIndex = 0
+ static let mainIndex = 1
+ static let recoveryIndex = 2
+
+ let table: GPTTable
+ let fileSizeBytes: UInt64
+
+ var isc: GPTPartitionEntry { table.entries[Self.iscIndex] }
+ var main: GPTPartitionEntry { table.entries[Self.mainIndex] }
+ var recovery: GPTPartitionEntry { table.entries[Self.recoveryIndex] }
+
+ var totalSectors: UInt64 { table.totalSectors }
+ var firstUsableLBA: UInt64 { table.header.firstUsableLBA }
+ var lastUsableLBA: UInt64 { table.header.lastUsableLBA }
+ var recoveryLength: UInt64 { recovery.sectorCount }
+ var gptTotalBytes: UInt64 { totalSectors * UInt64(GPTTable.sectorSize) }
+
+ static func fingerprint(_ table: GPTTable, fileSizeBytes: UInt64) throws -> MacDiskLayout {
+ func reject(_ reason: String) -> DiskResizeError { .unsupportedLayout(reason) }
+
+ let header = table.header
+ guard header.numberOfPartitionEntries == 128,
+ header.sizeOfPartitionEntry == UInt32(GPTPartitionEntry.byteSize),
+ header.partitionEntryLBA == 2
+ else {
+ throw reject("expected 128×128-byte entries at LBA 2")
+ }
+ guard header.firstUsableLBA == 34 else {
+ throw reject("FirstUsableLBA is \(header.firstUsableLBA), expected 34")
+ }
+
+ // Exactly entries 0–2 populated.
+ for i in 3..<table.entries.count where !table.entries[i].isEmpty {
+ throw reject("partition entry \(i) is unexpectedly populated")
+ }
+ guard !table.entries[0].isEmpty, !table.entries[1].isEmpty, !table.entries[2].isEmpty else {
+ throw reject("fewer than 3 populated partitions")
+ }
+
+ let isc = table.entries[iscIndex]
+ let main = table.entries[mainIndex]
+ let recovery = table.entries[recoveryIndex]
+
+ guard isc.typeGUID == GPTGUID.appleAPFSISC else {
+ throw reject("partition 1 is not Apple_APFS_ISC")
+ }
+ guard main.typeGUID == GPTGUID.appleAPFS else {
+ throw reject("partition 2 is not Apple_APFS")
+ }
+ guard recovery.typeGUID == GPTGUID.appleAPFSRecovery else {
+ throw reject("partition 3 is not Apple_APFS_Recovery")
+ }
+
+ // Ascending, non-overlapping order.
+ guard isc.startingLBA < isc.endingLBA,
+ main.startingLBA < main.endingLBA,
+ recovery.startingLBA < recovery.endingLBA
+ else {
+ throw reject("a partition has a non-positive length")
+ }
+ guard isc.endingLBA < main.startingLBA, main.endingLBA < recovery.startingLBA else {
+ throw reject("partitions are not in ascending, non-overlapping order")
+ }
+
+ // Recovery is last and hugs LastUsableLBA (0–7 sectors of slack).
+ let lastUsable = header.lastUsableLBA
+ guard recovery.endingLBA <= lastUsable else {
+ throw reject("recovery partition extends past LastUsableLBA")
+ }
+ let slack = lastUsable - recovery.endingLBA
+ guard slack <= 7 else {
+ throw reject("recovery partition ends \(slack) sectors before LastUsableLBA (expected ≤ 7)")
+ }
+
+ // 4 KiB alignment of recovery start and length.
+ guard recovery.startingLBA % alignment == 0 else {
+ throw reject("recovery start LBA \(recovery.startingLBA) is not 8-sector aligned")
+ }
+ guard recovery.sectorCount % alignment == 0 else {
+ throw reject("recovery length \(recovery.sectorCount) is not 8-sector aligned")
+ }
+
+ // GPT-described size must fit inside the file (equality = fresh disk;
+ // file larger = an old `lume set` truncate we can repair on top of).
+ let gptTotalBytes = table.totalSectors * UInt64(GPTTable.sectorSize)
+ guard gptTotalBytes <= fileSizeBytes else {
+ throw reject(
+ "GPT describes \(gptTotalBytes) bytes but the file is only \(fileSizeBytes) bytes")
+ }
+
+ return MacDiskLayout(table: table, fileSizeBytes: fileSizeBytes)
+ }
+}
diff --git a/libs/lume/src/DiskResize/MacDiskResizer.swift b/libs/lume/src/DiskResize/MacDiskResizer.swift
new file mode 100644
index 0000000000..66971ddf81
--- /dev/null
+++ b/libs/lume/src/DiskResize/MacDiskResizer.swift
@@ -0,0 +1,458 @@
+import Darwin
+import Foundation
+
+// MARK: - Options and marker
+
+struct DiskResizeOptions {
+ var backup: Bool = true
+ var keepBackup: Bool = false
+ var dryRun: Bool = false
+ // verifyBoot is reserved for a future headless boot check.
+}
+
+/// Persistent, crash-durable record that a resize transaction is underway.
+/// Its presence blocks `run`/`clone`/`push` and drives auto-recovery.
+struct ResizeMarker: Codable {
+ static let currentVersion = 1
+
+ var version: Int
+ var phase: Int
+ var oldSizeBytes: UInt64
+ var newSizeBytes: UInt64
+ var backupDiskPath: String?
+ var startedAt: Double
+}
+
+// MARK: - Container grow backend (injectable for tests)
+
+/// Abstracts the read-only preflight inspection and the APFS container growth
+/// (the parts that require attaching the image via hdiutil/diskutil), so the
+/// pure file-surgery phases can be unit-tested with a mock.
+@MainActor
+protocol ContainerGrower {
+ /// Read-only preflight: refuse if already attached or FileVault-encrypted.
+ func inspect(diskPath: URL) throws
+ /// Phase 5: grow the main APFS container into the free gap that now sits
+ /// directly before the relocated recovery partition (`newRecoveryFirstLBA`).
+ func grow(diskPath: URL, newRecoveryFirstLBA: UInt64) throws
+}
+
+// MARK: - Resizer
+
+/// Recovery-preserving offline macOS disk expansion. See the decision memo:
+/// grows the image sparsely, relocates the recovery partition byte-for-byte to
+/// the new end of disk, rewrites both GPT copies crash-safely, then grows the
+/// main APFS container into the now-adjacent gap — all with the VM stopped.
+@MainActor
+final class MacDiskResizer {
+ private let vmDir: VMDirectory
+ private let diskPath: URL
+ private let vmName: String
+ private let grower: ContainerGrower
+
+ init(
+ vmDir: VMDirectory,
+ diskPath: URL,
+ vmName: String,
+ grower: ContainerGrower? = nil
+ ) {
+ self.vmDir = vmDir
+ self.diskPath = diskPath
+ self.vmName = vmName
+ self.grower = grower ?? DiskutilContainerGrower()
+ }
+
+ // MARK: Recovery of an interrupted transaction
+
+ /// If a marker is present, roll back from the backup (if any) and return
+ /// true. Throws `resizeInProgress` when no backup exists to recover from.
+ @discardableResult
+ func recoverPendingIfAny() throws -> Bool {
+ guard let marker = try vmDir.loadResizeMarker() else { return false }
+ Logger.info(
+ "Found interrupted disk resize; rolling back",
+ metadata: ["name": vmName, "phase": "\(marker.phase)"])
+ if let backup = marker.backupDiskPath, FileManager.default.fileExists(atPath: backup) {
+ try restoreFromBackup()
+ try vmDir.clearResizeMarker()
+ deleteBackup()
+ Logger.info("Disk restored from pre-resize backup", metadata: ["name": vmName])
+ return true
+ }
+ throw DiskResizeError.resizeInProgress(vmName)
+ }
+
+ // MARK: Main entry
+
+ func resize(to newSize: UInt64, options: DiskResizeOptions) throws {
+ guard let transactionLock = try vmDir.tryAcquireResizeGuard(exclusive: true) else {
+ throw DiskResizeError.vmRunning(vmName)
+ }
+ defer {
+ flock(transactionLock.fileDescriptor, LOCK_UN)
+ try? transactionLock.close()
+ }
+
+ // Hold an exclusive lock on config.json for the whole transaction.
+ let lockHandle = try acquireLock()
+ defer {
+ flock(lockHandle.fileDescriptor, LOCK_UN)
+ try? lockHandle.close()
+ }
+
+ // Recover only after proving no running VM owns the config lock. The
+ // marker remains present throughout recovery, so new run attempts fail.
+ if try recoverPendingIfAny() {
+ Logger.info(
+ "Recovered a prior interrupted resize before starting a new one",
+ metadata: ["name": vmName])
+ }
+
+ let handle = try FileHandle(forUpdating: diskPath)
+ defer { try? handle.close() }
+
+ // ---- Phase 0: preflight (read-only) ----
+ let fileSize = fileLogicalSize()
+ let table = try GPTTable.read(from: handle, fileSizeBytes: fileSize)
+ let layout = try MacDiskLayout.fingerprint(table, fileSizeBytes: fileSize)
+
+ try validateSizeRules(newSize: newSize, fileSize: fileSize, layout: layout)
+ let plan = try computePlan(newSize: newSize, layout: layout)
+ try checkHostSpace(handle: handle, layout: layout)
+ try grower.inspect(diskPath: diskPath)
+
+ if options.dryRun {
+ let recoveryAllocated = SectorCopier.allocatedBytes(
+ fd: handle.fileDescriptor,
+ startLBA: layout.recovery.startingLBA,
+ lengthSectors: layout.recoveryLength)
+ Logger.info(
+ "Dry run: disk expansion is valid; no changes were made",
+ metadata: [
+ "name": vmName,
+ "oldSizeBytes": "\(fileSize)",
+ "newSizeBytes": "\(newSize)",
+ "oldTotalSectors": "\(layout.totalSectors)",
+ "newTotalSectors": "\(plan.newTotalSectors)",
+ "newLastUsableLBA": "\(plan.newLastUsable)",
+ "recoveryOldStart": "\(layout.recovery.startingLBA)",
+ "recoveryOldEnd": "\(layout.recovery.endingLBA)",
+ "recoveryNewStart": "\(plan.newRecoveryFirst)",
+ "recoveryNewEnd": "\(plan.newRecoveryFirst + layout.recoveryLength - 1)",
+ "recoveryLengthSectors": "\(layout.recoveryLength)",
+ "recoveryAllocatedBytes": "\(recoveryAllocated)",
+ "mainEnd": "\(layout.main.endingLBA)",
+ ])
+ return
+ }
+
+ Logger.info(
+ "Starting recovery-preserving disk expansion",
+ metadata: [
+ "name": vmName,
+ "oldSizeBytes": "\(fileSize)",
+ "newSizeBytes": "\(newSize)",
+ "recoveryOldStart": "\(layout.recovery.startingLBA)",
+ "recoveryNewStart": "\(plan.newRecoveryFirst)",
+ ])
+
+ // ---- Phase 1: backup ----
+ if options.backup {
+ try makeBackup()
+ } else {
+ Logger.info(
+ "Skipping pre-resize backup (--no-backup); rollback will not be automatic",
+ metadata: ["name": vmName])
+ }
+
+ // ---- Phase 2: arm the transaction ----
+ var marker = ResizeMarker(
+ version: ResizeMarker.currentVersion,
+ phase: 2,
+ oldSizeBytes: fileSize,
+ newSizeBytes: newSize,
+ backupDiskPath: options.backup ? vmDir.diskBackupPath.path : nil,
+ startedAt: nowTimestamp())
+ try vmDir.saveResizeMarker(marker)
+
+ do {
+ // ---- Phase 3: grow + relocate ----
+ marker.phase = 3
+ try vmDir.saveResizeMarker(marker)
+ if newSize > fileSize {
+ try handle.truncate(atOffset: newSize)
+ }
+ let preMoveHash = try SectorCopier.copyRange(
+ fd: handle.fileDescriptor,
+ srcLBA: layout.recovery.startingLBA,
+ dstLBA: plan.newRecoveryFirst,
+ lengthSectors: layout.recoveryLength)
+ try GPT.fullSync(handle)
+
+ // Free the old recovery region now, BEFORE the container grows into
+ // it, so punching a hole cannot clobber freshly-written APFS metadata.
+ SectorCopier.punchHole(
+ fd: handle.fileDescriptor,
+ startLBA: layout.recovery.startingLBA,
+ lengthSectors: layout.recoveryLength)
+
+ // ---- Phase 4: GPT commit ----
+ marker.phase = 4
+ try vmDir.saveResizeMarker(marker)
+ var newTable = table
+ newTable.header.alternateLBA = plan.newTotalSectors - 1
+ newTable.header.lastUsableLBA = plan.newLastUsable
+ newTable.entries[MacDiskLayout.recoveryIndex].startingLBA = plan.newRecoveryFirst
+ newTable.entries[MacDiskLayout.recoveryIndex].endingLBA =
+ plan.newRecoveryFirst + layout.recoveryLength - 1
+ try newTable.write(to: handle)
+ try GPT.fullSync(handle)
+
+ // ---- Phase 5: APFS container grow ----
+ marker.phase = 5
+ try vmDir.saveResizeMarker(marker)
+ try grower.grow(diskPath: diskPath, newRecoveryFirstLBA: plan.newRecoveryFirst)
+
+ // ---- Phase 6: verify + commit ----
+ marker.phase = 6
+ try vmDir.saveResizeMarker(marker)
+ try verify(preMoveHash: preMoveHash, plan: plan, layout: layout)
+ try updateConfigDiskSize(newSize)
+
+ // Success: clean up.
+ // Remove the guard first. A crash after this point can leave an
+ // unused backup, but never a marker whose recovery copy is gone.
+ try vmDir.clearResizeMarker()
+ if options.backup && !options.keepBackup { deleteBackup() }
+ Logger.info(
+ "Disk expansion completed",
+ metadata: ["name": vmName, "newSizeBytes": "\(newSize)"])
+ } catch {
+ do {
+ try rollback(afterError: error, hadBackup: options.backup)
+ } catch {
+ throw error
+ }
+ throw error
+ }
+ }
+
+ // MARK: - Phase 0 helpers
+
+ private struct Plan {
+ let newTotalSectors: UInt64
+ let newLastUsable: UInt64
+ let newRecoveryFirst: UInt64
+ }
+
+ private func validateSizeRules(newSize: UInt64, fileSize: UInt64, layout: MacDiskLayout) throws {
+ guard newSize % 4096 == 0 else {
+ throw DiskResizeError.unsupportedLayout(
+ "requested size \(newSize) is not a multiple of 4096 bytes")
+ }
+ guard newSize >= fileSize else {
+ throw DiskResizeError.shrinkNotSupported(current: fileSize, requested: newSize)
+ }
+ guard newSize > layout.gptTotalBytes else {
+ throw DiskResizeError.shrinkNotSupported(
+ current: layout.gptTotalBytes, requested: newSize)
+ }
+ // Non-overlap: the new recovery region must start past the old one.
+ let minGrowthSectors = layout.recoveryLength + 34
+ let minNewSizeRaw = layout.gptTotalBytes + minGrowthSectors * UInt64(GPTTable.sectorSize)
+ let minNewSize = roundUp(minNewSizeRaw, to: 4096)
+ guard newSize >= minNewSize else {
+ throw DiskResizeError.growthTooSmall(minimumBytes: minNewSize)
+ }
+ }
+
+ private func computePlan(newSize: UInt64, layout: MacDiskLayout) throws -> Plan {
+ let ss = UInt64(GPTTable.sectorSize)
+ let newTotalSectors = newSize / ss
+ let newLastUsable = newTotalSectors - 34
+ let recLen = layout.recoveryLength
+ // Hug the end with 0–7 sectors of slack, 8-sector aligned start.
+ let newRecoveryFirst = floorAlign(newLastUsable - recLen + 1, to: MacDiskLayout.alignment)
+ guard newRecoveryFirst > layout.recovery.endingLBA else {
+ throw DiskResizeError.growthTooSmall(
+ minimumBytes: roundUp(
+ layout.gptTotalBytes + (recLen + 34) * ss, to: 4096))
+ }
+ guard newRecoveryFirst + recLen - 1 <= newLastUsable else {
+ throw DiskResizeError.unsupportedLayout("internal: relocated recovery exceeds LastUsable")
+ }
+ return Plan(
+ newTotalSectors: newTotalSectors,
+ newLastUsable: newLastUsable,
+ newRecoveryFirst: newRecoveryFirst)
+ }
+
+ private func checkHostSpace(handle: FileHandle, layout: MacDiskLayout) throws {
+ let needed =
+ SectorCopier.allocatedBytes(
+ fd: handle.fileDescriptor,
+ startLBA: layout.recovery.startingLBA,
+ lengthSectors: layout.recoveryLength) + 64 * 1024 * 1024 // margin
+ let available: UInt64
+ if let values = try? diskPath.resourceValues(forKeys: [
+ .volumeAvailableCapacityForImportantUsageKey
+ ]), let capacity = values.volumeAvailableCapacityForImportantUsage {
+ available = UInt64(max(0, capacity))
+ } else {
+ available = .max // cannot determine; do not block
+ }
+ guard available >= needed else {
+ throw DiskResizeError.insufficientHostSpace(needed: needed, available: available)
+ }
+ }
+
+ // MARK: - Phase 6 verify
+
+ private func verify(preMoveHash: Data, plan: Plan, layout: MacDiskLayout) throws {
+ let handle = try FileHandle(forReadingFrom: diskPath)
+ defer { try? handle.close() }
+ let fileSize = fileLogicalSize()
+ let table = try GPTTable.read(from: handle, fileSizeBytes: fileSize)
+ let newLayout = try MacDiskLayout.fingerprint(table, fileSizeBytes: fileSize)
+ guard newLayout.recovery.startingLBA == plan.newRecoveryFirst else {
+ throw DiskResizeError.verificationFailed(
+ "recovery partition did not land at LBA \(plan.newRecoveryFirst)")
+ }
+ let postHash = try SectorCopier.hashRange(
+ fd: handle.fileDescriptor,
+ startLBA: plan.newRecoveryFirst,
+ lengthSectors: layout.recoveryLength)
+ guard postHash == preMoveHash else {
+ throw DiskResizeError.verificationFailed(
+ "relocated recovery bytes do not match the pre-move hash")
+ }
+ }
+
+ // MARK: - Backup / rollback
+
+ private func makeBackup() throws {
+ deleteBackup()
+ let result = Darwin.clonefile(diskPath.path, vmDir.diskBackupPath.path, 0)
+ if result != 0 {
+ let code = errno
+ throw DiskResizeError.backupFailed(
+ "clonefile failed (errno \(code): \(String(cString: strerror(code))))")
+ }
+ // Copy config.json alongside so it can be restored atomically.
+ try? FileManager.default.removeItem(atPath: vmDir.configBackupPath.path)
+ do {
+ try FileManager.default.copyItem(
+ at: vmDir.configPath.url, to: vmDir.configBackupPath.url)
+ } catch {
+ throw DiskResizeError.backupFailed(
+ "could not back up config.json: \(error.localizedDescription)")
+ }
+ }
+
+ private func deleteBackup() {
+ try? FileManager.default.removeItem(atPath: vmDir.diskBackupPath.path)
+ try? FileManager.default.removeItem(atPath: vmDir.configBackupPath.path)
+ }
+
+ private func restoreFromBackup() throws {
+ guard FileManager.default.fileExists(atPath: vmDir.diskBackupPath.path),
+ FileManager.default.fileExists(atPath: vmDir.configBackupPath.path)
+ else {
+ throw DiskResizeError.backupFailed("rollback backup is incomplete")
+ }
+ let diskRestore = diskPath.path + ".restore"
+ let configRestore = vmDir.configPath.path + ".restore"
+ try? FileManager.default.removeItem(atPath: diskRestore)
+ try? FileManager.default.removeItem(atPath: configRestore)
+ guard Darwin.clonefile(vmDir.diskBackupPath.path, diskRestore, 0) == 0 else {
+ throw DiskResizeError.backupFailed(
+ "could not stage disk restore: \(String(cString: strerror(errno)))")
+ }
+ do {
+ try FileManager.default.copyItem(
+ atPath: vmDir.configBackupPath.path, toPath: configRestore)
+ } catch {
+ try? FileManager.default.removeItem(atPath: diskRestore)
+ throw DiskResizeError.backupFailed(
+ "could not stage config restore: \(error.localizedDescription)")
+ }
+ guard Darwin.rename(configRestore, vmDir.configPath.path) == 0 else {
+ try? FileManager.default.removeItem(atPath: diskRestore)
+ throw DiskResizeError.backupFailed(
+ "could not restore config.json: \(String(cString: strerror(errno)))")
+ }
+ guard Darwin.rename(diskRestore, diskPath.path) == 0 else {
+ throw DiskResizeError.backupFailed(
+ "could not restore disk.img: \(String(cString: strerror(errno)))")
+ }
+ }
+
+ private func rollback(afterError error: Error, hadBackup: Bool) throws {
+ let originalDescription = error.localizedDescription
+ Logger.error(
+ "Disk expansion failed; rolling back",
+ metadata: ["name": vmName, "error": error.localizedDescription])
+ if hadBackup, FileManager.default.fileExists(atPath: vmDir.diskBackupPath.path) {
+ do {
+ try restoreFromBackup()
+ try vmDir.clearResizeMarker()
+ deleteBackup()
+ Logger.info("Disk restored from pre-resize backup", metadata: ["name": vmName])
+ } catch let restoreError {
+ throw DiskResizeError.rollbackFailed(
+ original: originalDescription, restore: restoreError.localizedDescription)
+ }
+ } else {
+ Logger.error(
+ "No backup available; leaving resize marker for manual recovery",
+ metadata: ["name": vmName])
+ }
+ }
+
+ // MARK: - Config
+
+ private func updateConfigDiskSize(_ newSize: UInt64) throws {
+ var config = try vmDir.loadConfig()
+ config.setDiskSize(newSize)
+ try vmDir.saveConfig(config)
+ }
+
+ // MARK: - Locking
+
+ private func acquireLock() throws -> FileHandle {
+ let handle: FileHandle
+ do {
+ handle = try FileHandle(forWritingTo: vmDir.configPath.url)
+ } catch {
+ throw DiskResizeError.commandFailed(
+ command: "open config.json", output: error.localizedDescription)
+ }
+ guard flock(handle.fileDescriptor, LOCK_EX | LOCK_NB) == 0 else {
+ try? handle.close()
+ throw DiskResizeError.vmRunning(vmName)
+ }
+ return handle
+ }
+
+ // MARK: - Misc
+
+ private func fileLogicalSize() -> UInt64 {
+ ((try? FileManager.default.attributesOfItem(atPath: diskPath.path))?[.size]
+ as? NSNumber)?.uint64Value ?? 0
+ }
+
+ private func nowTimestamp() -> Double {
+ Date().timeIntervalSince1970
+ }
+}
+
+// MARK: - Helpers
+
+private func floorAlign(_ value: UInt64, to alignment: UInt64) -> UInt64 {
+ value - (value % alignment)
+}
+
+private func roundUp(_ value: UInt64, to alignment: UInt64) -> UInt64 {
+ let remainder = value % alignment
+ return remainder == 0 ? value : value + (alignment - remainder)
+}
diff --git a/libs/lume/src/DiskResize/SectorCopier.swift b/libs/lume/src/DiskResize/SectorCopier.swift
new file mode 100644
index 0000000000..913ebc1a9a
--- /dev/null
+++ b/libs/lume/src/DiskResize/SectorCopier.swift
@@ -0,0 +1,128 @@
+import CryptoKit
+import Darwin
+import Foundation
+
+/// Positioned, sparse-aware copy/hash primitives used to relocate the recovery
+/// partition byte-for-byte and to verify it afterwards. All operations use
+/// `pread`/`pwrite` at explicit offsets so they never disturb (or depend on) a
+/// shared file offset.
+enum SectorCopier {
+ static let sectorSize: UInt64 = 512
+ static let chunkSize = 8 * 1024 * 1024 // 8 MiB
+
+ /// Copies `lengthSectors` from `srcLBA` to `dstLBA`, skipping all-zero
+ /// chunks so the destination stays sparse, and returns the SHA-256 of the
+ /// full logical source content (holes hashed as zeros). The source and
+ /// destination ranges must not overlap.
+ @discardableResult
+ static func copyRange(fd: Int32, srcLBA: UInt64, dstLBA: UInt64, lengthSectors: UInt64) throws
+ -> Data
+ {
+ let byteLen = lengthSectors * sectorSize
+ let srcStart = srcLBA * sectorSize
+ let dstStart = dstLBA * sectorSize
+ precondition(
+ disjoint(aStart: srcStart, bStart: dstStart, length: byteLen),
+ "SectorCopier.copyRange requires non-overlapping ranges")
+
+ var hasher = SHA256()
+ var buf = [UInt8](repeating: 0, count: chunkSize)
+ var offset: UInt64 = 0
+ while offset < byteLen {
+ let n = Int(min(UInt64(chunkSize), byteLen - offset))
+ let read = try preadExact(fd: fd, into: &buf, count: n, offset: srcStart + offset)
+ let chunk = Array(buf[0..<read])
+ hasher.update(data: Data(chunk))
+ if chunk.contains(where: { $0 != 0 }) {
+ try pwriteExact(fd: fd, bytes: chunk, offset: dstStart + offset)
+ }
+ offset += UInt64(read)
+ }
+ return Data(hasher.finalize())
+ }
+
+ /// SHA-256 of the logical content of a sector range (holes read as zeros).
+ static func hashRange(fd: Int32, startLBA: UInt64, lengthSectors: UInt64) throws -> Data {
+ let byteLen = lengthSectors * sectorSize
+ let start = startLBA * sectorSize
+ var hasher = SHA256()
+ var buf = [UInt8](repeating: 0, count: chunkSize)
+ var offset: UInt64 = 0
+ while offset < byteLen {
+ let n = Int(min(UInt64(chunkSize), byteLen - offset))
+ let read = try preadExact(fd: fd, into: &buf, count: n, offset: start + offset)
+ hasher.update(data: Data(buf[0..<read]))
+ offset += UInt64(read)
+ }
+ return Data(hasher.finalize())
+ }
+
+ /// Allocated (non-hole) bytes inside a sector range, via a SEEK_DATA walk.
+ static func allocatedBytes(fd: Int32, startLBA: UInt64, lengthSectors: UInt64) -> UInt64 {
+ let start = startLBA * sectorSize
+ let end = start + lengthSectors * sectorSize
+ var pos = start
+ var allocated: UInt64 = 0
+ while pos < end {
+ let dataStart = lseek(fd, off_t(pos), SEEK_DATA)
+ if dataStart < 0 || UInt64(dataStart) >= end { break }
+ let holeStart = lseek(fd, dataStart, SEEK_HOLE)
+ let regionEnd = holeStart < 0 ? end : min(UInt64(holeStart), end)
+ allocated += regionEnd - UInt64(dataStart)
+ pos = regionEnd
+ }
+ return allocated
+ }
+
+ /// Punches a hole over a sector range (best-effort; keeps the image sparse).
+ static func punchHole(fd: Int32, startLBA: UInt64, lengthSectors: UInt64) {
+ var punch = fpunchhole_t(
+ fp_flags: 0,
+ reserved: 0,
+ fp_offset: off_t(startLBA * sectorSize),
+ fp_length: off_t(lengthSectors * sectorSize))
+ _ = fcntl(fd, F_PUNCHHOLE, &punch)
+ }
+
+ // MARK: - Positioned IO
+
+ private static func preadExact(fd: Int32, into buf: inout [UInt8], count: Int, offset: UInt64)
+ throws -> Int
+ {
+ var total = 0
+ try buf.withUnsafeMutableBytes { raw in
+ let base = raw.baseAddress!
+ while total < count {
+ let n = pread(fd, base + total, count - total, off_t(offset) + off_t(total))
+ if n < 0 {
+ throw DiskResizeError.commandFailed(
+ command: "pread", output: String(cString: strerror(errno)))
+ }
+ if n == 0 { break } // EOF
+ total += n
+ }
+ }
+ return total
+ }
+
+ private static func pwriteExact(fd: Int32, bytes: [UInt8], offset: UInt64) throws {
+ try bytes.withUnsafeBytes { raw in
+ let base = raw.baseAddress!
+ var total = 0
+ while total < bytes.count {
+ let n = pwrite(fd, base + total, bytes.count - total, off_t(offset) + off_t(total))
+ if n <= 0 {
+ throw DiskResizeError.commandFailed(
+ command: "pwrite", output: String(cString: strerror(errno)))
+ }
+ total += n
+ }
+ }
+ }
+
+ private static func disjoint(aStart: UInt64, bStart: UInt64, length: UInt64) -> Bool {
+ let aEnd = aStart + length
+ let bEnd = bStart + length
+ return aEnd <= bStart || bEnd <= aStart
+ }
+}
diff --git a/libs/lume/src/Errors/Errors.swift b/libs/lume/src/Errors/Errors.swift
index e3968c19fa..498038d038 100644
--- a/libs/lume/src/Errors/Errors.swift
+++ b/libs/lume/src/Errors/Errors.swift
@@ -228,6 +228,75 @@ enum ResticError: Error {
case genericError(String)
}
+/// Errors surfaced by the recovery-preserving macOS disk expansion engine.
+///
+/// Every message is fail-closed: it states which check failed with concrete
+/// values, whether the disk was modified or rolled back, and one next step.
+enum DiskResizeError: Error, LocalizedError {
+ case vmRunning(String)
+ case resizeInProgress(String)
+ case invalidResizeMarker(String)
+ case rollbackFailed(original: String, restore: String)
+ case shrinkNotSupported(current: UInt64, requested: UInt64)
+ case growthTooSmall(minimumBytes: UInt64)
+ case unsupportedLayout(String)
+ case unsupportedSectorSize
+ case fileVaultEnabled
+ case imageAttached
+ case backupFailed(String)
+ case insufficientHostSpace(needed: UInt64, available: UInt64)
+ case apfsCheckFailed(String)
+ case containerGrowFailed(String)
+ case verificationFailed(String)
+ case commandFailed(command: String, output: String)
+
+ var errorDescription: String? {
+ switch self {
+ case .vmRunning(let name):
+ return "Cannot resize the disk of \(name): the VM is running. Stop it first."
+ case .resizeInProgress(let name):
+ return
+ "A previous disk resize of \(name) did not finish. Re-run the same command to roll it back and restore the disk from its backup."
+ case .invalidResizeMarker(let reason):
+ return "The disk-resize marker is invalid (\(reason)). The VM remains blocked to protect its disk."
+ case .rollbackFailed(let original, let restore):
+ return "Disk resize failed (\(original)), and rollback also failed (\(restore)). The resize marker was kept; do not run the VM."
+ case .shrinkNotSupported(let current, let requested):
+ return
+ "Cannot shrink the disk (current \(current) bytes, requested \(requested) bytes). Only growing is supported; the disk was not modified."
+ case .growthTooSmall(let minimumBytes):
+ return
+ "Requested growth is too small. The new size must add at least \(minimumBytes) bytes so the recovery partition can be relocated; the disk was not modified."
+ case .unsupportedLayout(let reason):
+ return
+ "The disk layout is not the expected macOS 3-partition layout (\(reason)); the disk was not modified."
+ case .unsupportedSectorSize:
+ return "Only 512-byte-sector disk images are supported; the disk was not modified."
+ case .fileVaultEnabled:
+ return
+ "The main volume is encrypted (FileVault). Encrypted containers are not supported yet; the disk was not modified."
+ case .imageAttached:
+ return
+ "disk.img is already attached to the host. Detach it (hdiutil detach) and retry; the disk was not modified."
+ case .backupFailed(let reason):
+ return
+ "Could not create the pre-resize backup (\(reason)). Free space or use a different storage location, or pass --no-backup to proceed without one; the disk was not modified."
+ case .insufficientHostSpace(let needed, let available):
+ return
+ "Not enough host free space for the resize (need ~\(needed) bytes, have \(available) bytes); the disk was not modified."
+ case .apfsCheckFailed(let output):
+ return
+ "The APFS container is not clean. Boot the VM, shut it down cleanly, and retry. Details: \(output)"
+ case .containerGrowFailed(let output):
+ return "Growing the APFS container failed: \(output). The disk was restored from backup."
+ case .verificationFailed(let reason):
+ return "Post-resize verification failed: \(reason). The disk was restored from backup."
+ case .commandFailed(let command, let output):
+ return "\(command) failed: \(output)"
+ }
+ }
+}
+
enum VmrunError: Error, LocalizedError {
case commandNotFound
case operationFailed(command: String, output: String?)
@@ -275,4 +344,4 @@ enum UnattendedError: Error, LocalizedError {
return "Health check failed: \(reason)"
}
}
-}
\ No newline at end of file
+}
diff --git a/libs/lume/src/FileSystem/VMDirectory.swift b/libs/lume/src/FileSystem/VMDirectory.swift
index 3334ad97f0..3b36f6050b 100644
--- a/libs/lume/src/FileSystem/VMDirectory.swift
+++ b/libs/lume/src/FileSystem/VMDirectory.swift
@@ -1,3 +1,4 @@
+import Darwin
import Foundation
// MARK: - VMDirectory
@@ -17,22 +18,29 @@ struct VMDirectory: Sendable {
static let config = "config.json"
static let sessions = "sessions.json"
static let provisioning = ".provisioning"
+ static let resizeMarker = "resize.lock.json"
+ static let diskBackup = "disk.img.pre-resize"
+ static let configBackup = "config.json.pre-resize"
}
-
+
// MARK: - Properties
-
+
let dir: Path
let nvramPath: Path
let diskPath: Path
let configPath: Path
let sessionsPath: Path
let provisioningPath: Path
-
+ let resizeMarkerPath: Path
+ let diskBackupPath: Path
+ let configBackupPath: Path
+ let resizeGuardPath: Path
+
/// The name of the VM directory
var name: String { dir.name }
-
+
// MARK: - Initialization
-
+
/// Creates a new VMDirectory instance
/// - Parameters:
/// - dir: The base directory path for the VM
@@ -43,6 +51,12 @@ struct VMDirectory: Sendable {
self.configPath = dir.file(FileNames.config)
self.sessionsPath = dir.file(FileNames.sessions)
self.provisioningPath = dir.file(FileNames.provisioning)
+ self.resizeMarkerPath = dir.file(FileNames.resizeMarker)
+ self.diskBackupPath = dir.file(FileNames.diskBackup)
+ self.configBackupPath = dir.file(FileNames.configBackup)
+ self.resizeGuardPath = Path(
+ dir.url.deletingLastPathComponent()
+ .appendingPathComponent(".\(dir.name).resize.guard", isDirectory: false))
}
}
@@ -81,22 +95,119 @@ extension VMDirectory {
// MARK: - Disk Management
extension VMDirectory {
- /// Resizes the VM's disk to the specified size
+ /// Resizes the VM's disk to the specified size (grow-only).
/// - Parameter size: The new size in bytes
- /// - Throws: VMDirectoryError if the disk operation fails
+ /// - Throws: VMDirectoryError if the disk operation fails or would shrink
+ /// the image (which silently truncates and corrupts the APFS tail).
func setDisk(_ size: UInt64) throws {
- do {
- if !diskPath.exists() {
- guard FileManager.default.createFile(atPath: diskPath.path, contents: nil) else {
- throw VMDirectoryError.fileCreationFailed(diskPath.path)
- }
+ if !diskPath.exists() {
+ guard FileManager.default.createFile(atPath: diskPath.path, contents: nil) else {
+ throw VMDirectoryError.fileCreationFailed(diskPath.path)
}
-
- let handle = try FileHandle(forWritingTo: diskPath.url)
- defer { try? handle.close() }
-
+ }
+
+ let currentSize =
+ ((try? FileManager.default.attributesOfItem(atPath: diskPath.path))?[.size]
+ as? NSNumber)?.uint64Value ?? 0
+ guard size >= currentSize else {
+ throw VMDirectoryError.diskOperationFailed(
+ "refusing to shrink disk from \(currentSize) to \(size) bytes")
+ }
+
+ let handle: FileHandle
+ do {
+ handle = try FileHandle(forWritingTo: diskPath.url)
+ } catch {
+ throw VMDirectoryError.diskOperationFailed(
+ "could not open \(diskPath.path): \(error.localizedDescription)")
+ }
+ defer { try? handle.close() }
+
+ do {
try handle.truncate(atOffset: size)
} catch {
+ throw VMDirectoryError.diskOperationFailed(
+ "truncate to \(size) bytes failed: \(error.localizedDescription)")
+ }
+ }
+}
+
+// MARK: - Resize Transaction Marker
+
+extension VMDirectory {
+ func tryAcquireResizeGuard(exclusive: Bool) throws -> FileHandle? {
+ if !resizeGuardPath.exists() {
+ guard FileManager.default.createFile(atPath: resizeGuardPath.path, contents: Data()) else {
+ throw VMDirectoryError.fileCreationFailed(resizeGuardPath.path)
+ }
+ }
+ let handle = try FileHandle(forUpdating: resizeGuardPath.url)
+ let operation = exclusive ? (LOCK_EX | LOCK_NB) : (LOCK_SH | LOCK_NB)
+ guard flock(handle.fileDescriptor, operation) == 0 else {
+ try? handle.close()
+ return nil
+ }
+ return handle
+ }
+
+ /// Loads the resize transaction marker if a resize is in progress.
+ func loadResizeMarker() throws -> ResizeMarker? {
+ guard resizeMarkerPath.exists() else {
+ return nil
+ }
+ do {
+ let data = try Data(contentsOf: resizeMarkerPath.url)
+ let marker = try JSONDecoder().decode(ResizeMarker.self, from: data)
+ guard marker.version == ResizeMarker.currentVersion else {
+ throw DiskResizeError.invalidResizeMarker("unsupported version \(marker.version)")
+ }
+ return marker
+ } catch let error as DiskResizeError {
+ throw error
+ } catch {
+ throw DiskResizeError.invalidResizeMarker(error.localizedDescription)
+ }
+ }
+
+ /// True if a disk resize transaction is currently armed.
+ func hasResizeMarker() -> Bool {
+ resizeMarkerPath.exists()
+ }
+
+ /// Persists (and fsyncs) the resize transaction marker.
+ func saveResizeMarker(_ marker: ResizeMarker) throws {
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = .prettyPrinted
+ let data = try encoder.encode(marker)
+ let temporary = resizeMarkerPath.path + ".tmp"
+ guard FileManager.default.createFile(atPath: temporary, contents: data) else {
+ throw VMDirectoryError.fileCreationFailed(temporary)
+ }
+ let handle = try FileHandle(forWritingTo: URL(fileURLWithPath: temporary))
+ try handle.synchronize()
+ try handle.close()
+ guard Darwin.rename(temporary, resizeMarkerPath.path) == 0 else {
+ throw VMDirectoryError.diskOperationFailed(
+ "could not commit resize marker: \(String(cString: strerror(errno)))")
+ }
+ try syncDirectory()
+ }
+
+ /// Removes the resize transaction marker after the transaction resolves.
+ func clearResizeMarker() throws {
+ guard resizeMarkerPath.exists() else { return }
+ try FileManager.default.removeItem(atPath: resizeMarkerPath.path)
+ try syncDirectory()
+ }
+
+ private func syncDirectory() throws {
+ let directoryFD = Darwin.open(dir.path, O_RDONLY)
+ guard directoryFD >= 0 else {
+ throw VMDirectoryError.diskOperationFailed("could not open VM directory for sync")
+ }
+ defer { Darwin.close(directoryFD) }
+ guard Darwin.fsync(directoryFD) == 0 else {
+ throw VMDirectoryError.diskOperationFailed("could not sync VM directory")
}
}
}
diff --git a/libs/lume/src/LumeController.swift b/libs/lume/src/LumeController.swift
index f2bffced9a..2048fea855 100644
--- a/libs/lume/src/LumeController.swift
+++ b/libs/lume/src/LumeController.swift
@@ -271,6 +271,14 @@ final class LumeController {
}
}
+ /// Validates that no disk-resize transaction is armed for a VM. Blocks
+ /// run/clone/push so an in-progress (or interrupted) resize is never raced.
+ private func validateNoPendingResize(_ vmDir: VMDirectory, name: String) throws {
+ if vmDir.hasResizeMarker() {
+ throw DiskResizeError.resizeInProgress(name)
+ }
+ }
+
@MainActor
public func clone(
name: String, newName: String, sourceLocation: String? = nil, destLocation: String? = nil
@@ -292,7 +300,25 @@ final class LumeController {
// Check if source VM is still being provisioned
let sourceVmDir = try home.getVMDirectory(normalizedName, storage: actualSourceLocation)
+ guard let resizeGuard = try sourceVmDir.tryAcquireResizeGuard(exclusive: false) else {
+ throw DiskResizeError.resizeInProgress(normalizedName)
+ }
+ defer {
+ flock(resizeGuard.fileDescriptor, LOCK_UN)
+ try? resizeGuard.close()
+ }
try validateNotProvisioning(sourceVmDir, name: normalizedName)
+ try validateNoPendingResize(sourceVmDir, name: normalizedName)
+
+ let destinationVmDir = try home.getVMDirectory(normalizedNewName, storage: destLocation)
+ guard let destinationGuard = try destinationVmDir.tryAcquireResizeGuard(exclusive: true)
+ else {
+ throw DiskResizeError.resizeInProgress(normalizedNewName)
+ }
+ defer {
+ flock(destinationGuard.fileDescriptor, LOCK_UN)
+ try? destinationGuard.close()
+ }
// Get the source VM and check if it's running
let sourceVM = try get(name: normalizedName, storage: sourceLocation)
@@ -303,12 +329,11 @@ final class LumeController {
// Check if destination already exists
do {
- let destDir = try home.getVMDirectory(normalizedNewName, storage: destLocation)
- if destDir.exists() {
+ if destinationVmDir.exists() {
Logger.error(
"Destination VM already exists",
metadata: ["destination": normalizedNewName])
- throw HomeError.directoryAlreadyExists(path: destDir.dir.path)
+ throw HomeError.directoryAlreadyExists(path: destinationVmDir.dir.path)
}
} catch VMLocationError.locationNotFound {
// Location not found is okay, we'll create it
@@ -831,11 +856,20 @@ final class LumeController {
let actualLocation = try self.validateVMExists(normalizedName, storage: storage)
vmDir = try home.getVMDirectory(normalizedName, storage: actualLocation)
}
-
+
// Stop VM if it's running
if SharedVM.shared.getVM(name: normalizedName) != nil {
try await stopVM(name: normalizedName)
}
+
+ guard let resizeGuard = try vmDir.tryAcquireResizeGuard(exclusive: true) else {
+ throw DiskResizeError.resizeInProgress(normalizedName)
+ }
+ defer {
+ flock(resizeGuard.fileDescriptor, LOCK_UN)
+ try? resizeGuard.close()
+ }
+ try validateNoPendingResize(vmDir, name: normalizedName)
try vmDir.delete()
@@ -856,8 +890,17 @@ final class LumeController {
memory: UInt64? = nil,
diskSize: UInt64? = nil,
display: String? = nil,
- storage: String? = nil
+ storage: String? = nil,
+ noBackup: Bool = false,
+ keepBackup: Bool = false,
+ dryRun: Bool = false
) throws {
+ if noBackup && keepBackup {
+ throw ValidationError("--no-backup and --keep-backup cannot be used together")
+ }
+ if diskSize == nil && (noBackup || keepBackup || dryRun) {
+ throw ValidationError("Disk-resize options require diskSize")
+ }
let normalizedName = normalizeVMName(name: name)
Logger.info(
"Updating VM settings",
@@ -884,7 +927,10 @@ final class LumeController {
try vm.setMemorySize(memory)
}
if let diskSize = diskSize {
- try vm.setDiskSize(diskSize)
+ try vm.resizeDiskSafely(
+ to: diskSize,
+ options: DiskResizeOptions(
+ backup: !noBackup, keepBackup: keepBackup, dryRun: dryRun))
}
if let display = display {
try vm.setDisplay(display)
@@ -1047,6 +1093,7 @@ final class LumeController {
// Check if VM is still being provisioned
try validateNotProvisioning(vmDir, name: normalizedName)
+ try validateNoPendingResize(vmDir, name: normalizedName)
// Validate parameters using the located VMDirectory
try validateRunParameters(
@@ -1219,6 +1266,14 @@ final class LumeController {
// Get the VM directory
let vmDir = try home.getVMDirectory(name, storage: actualLocation)
+ guard let resizeGuard = try vmDir.tryAcquireResizeGuard(exclusive: false) else {
+ throw DiskResizeError.resizeInProgress(name)
+ }
+ defer {
+ flock(resizeGuard.fileDescriptor, LOCK_UN)
+ try? resizeGuard.close()
+ }
+ try validateNoPendingResize(vmDir, name: name)
// Use configured registry to push the VM
let imageRegistry = try RegistryFactory.createRegistry(
diff --git a/libs/lume/src/Server/APIDocExtractor.swift b/libs/lume/src/Server/APIDocExtractor.swift
index 723f8afd92..875417924b 100644
--- a/libs/lume/src/Server/APIDocExtractor.swift
+++ b/libs/lume/src/Server/APIDocExtractor.swift
@@ -272,9 +272,12 @@ enum APIDocExtractor {
fields: [
APIFieldDoc(name: "cpu", type: "integer", required: false, description: "New number of CPU cores", defaultValue: nil),
APIFieldDoc(name: "memory", type: "string", required: false, description: "New memory size (e.g., 16GB)", defaultValue: nil),
- APIFieldDoc(name: "diskSize", type: "string", required: false, description: "New disk size (e.g., 100GB)", defaultValue: nil),
+ APIFieldDoc(name: "diskSize", type: "string", required: false, description: "New total disk size (increase only)", defaultValue: nil),
APIFieldDoc(name: "display", type: "string", required: false, description: "New display resolution", defaultValue: nil),
- APIFieldDoc(name: "storage", type: "string", required: false, description: "VM storage location", defaultValue: nil)
+ APIFieldDoc(name: "storage", type: "string", required: false, description: "VM storage location", defaultValue: nil),
+ APIFieldDoc(name: "noBackup", type: "boolean", required: false, description: "Skip the macOS rollback backup", defaultValue: "false"),
+ APIFieldDoc(name: "keepBackup", type: "boolean", required: false, description: "Keep rollback files after success", defaultValue: "false"),
+ APIFieldDoc(name: "dryRun", type: "boolean", required: false, description: "Validate the resize plan without modifying the disk", defaultValue: "false")
]
),
responseBody: APIResponseDoc(
diff --git a/libs/lume/src/Server/Handlers.swift b/libs/lume/src/Server/Handlers.swift
index 61f917c940..e3ffacc20a 100644
--- a/libs/lume/src/Server/Handlers.swift
+++ b/libs/lume/src/Server/Handlers.swift
@@ -256,7 +256,10 @@ extension Server {
memory: sizes.memory,
diskSize: sizes.diskSize,
display: sizes.display?.string,
- storage: request.storage
+ storage: request.storage,
+ noBackup: request.noBackup ?? false,
+ keepBackup: request.keepBackup ?? false,
+ dryRun: request.dryRun ?? false
)
return HTTPResponse(
diff --git a/libs/lume/src/Server/MCPServer.swift b/libs/lume/src/Server/MCPServer.swift
index f167fe4b1a..ce9f80e291 100644
--- a/libs/lume/src/Server/MCPServer.swift
+++ b/libs/lume/src/Server/MCPServer.swift
@@ -502,6 +502,40 @@ final class LumeMCPServer {
]),
"required": .array([.string("name")])
])
+ ),
+ Tool(
+ name: "lume_resize_disk",
+ description: "Grow a stopped VM's disk. For macOS VMs this preserves the paired RecoveryOS partition (relocating it to the new end of disk) and expands the main APFS container so future macOS updates keep working. Grow-only; the VM must be stopped; may take several minutes.",
+ inputSchema: .object([
+ "type": .string("object"),
+ "properties": .object([
+ "name": .object([
+ "type": .string("string"),
+ "description": .string("Name of the VM to resize")
+ ]),
+ "disk_size": .object([
+ "type": .string("string"),
+ "description": .string("New disk size, e.g., '100GB'. Must be larger than the current size.")
+ ]),
+ "storage": .object([
+ "type": .string("string"),
+ "description": .string("Optional storage location name or path")
+ ]),
+ "no_backup": .object([
+ "type": .string("boolean"),
+ "description": .string("Skip the pre-resize backup (faster, but no automatic rollback on failure). Default false.")
+ ]),
+ "keep_backup": .object([
+ "type": .string("boolean"),
+ "description": .string("Keep the rollback backup after a successful resize. Default false.")
+ ]),
+ "dry_run": .object([
+ "type": .string("boolean"),
+ "description": .string("Validate and print the resize plan without modifying the disk. Default false.")
+ ])
+ ]),
+ "required": .array([.string("name"), .string("disk_size")])
+ ])
)
]
}
@@ -527,6 +561,8 @@ final class LumeMCPServer {
return try await handleExec(params.arguments)
case "lume_create_vm":
return try await handleCreateVM(params.arguments)
+ case "lume_resize_disk":
+ return try await handleResizeDisk(params.arguments)
case "check_for_update":
return try await handleCheckForUpdate(params.arguments)
default:
@@ -664,6 +700,26 @@ final class LumeMCPServer {
return CallTool.Result(content: [.text("VM '\(name)' cloned to '\(newName)' successfully.")])
}
+ private func handleResizeDisk(_ args: [String: Value]?) async throws -> CallTool.Result {
+ guard let name = args?["name"]?.stringValue else {
+ return CallTool.Result(content: [.text("Error: 'name' is required")], isError: true)
+ }
+ guard let diskSizeString = args?["disk_size"]?.stringValue else {
+ return CallTool.Result(content: [.text("Error: 'disk_size' is required")], isError: true)
+ }
+ let storage = args?["storage"]?.stringValue
+ let noBackup = args?["no_backup"]?.boolValue ?? false
+ let keepBackup = args?["keep_backup"]?.boolValue ?? false
+ let dryRun = args?["dry_run"]?.boolValue ?? false
+ let diskSize = try parseSize(diskSizeString)
+
+ try controller.updateSettings(
+ name: name, diskSize: diskSize, storage: storage, noBackup: noBackup,
+ keepBackup: keepBackup, dryRun: dryRun)
+ return CallTool.Result(
+ content: [.text("VM '\(name)' disk resized to \(diskSizeString) successfully.")])
+ }
+
private func handleDeleteVM(_ args: [String: Value]?) async throws -> CallTool.Result {
guard let name = args?["name"]?.stringValue else {
return CallTool.Result(content: [.text("Error: 'name' is required")], isError: true)
diff --git a/libs/lume/src/Server/Requests.swift b/libs/lume/src/Server/Requests.swift
index df4e6a6908..9a1a83820e 100644
--- a/libs/lume/src/Server/Requests.swift
+++ b/libs/lume/src/Server/Requests.swift
@@ -111,6 +111,9 @@ struct SetVMRequest: Codable {
let diskSize: String?
let display: String?
let storage: String?
+ let noBackup: Bool?
+ let keepBackup: Bool?
+ let dryRun: Bool?
func parse() throws -> (memory: UInt64?, diskSize: UInt64?, display: VMDisplayResolution?) {
return (
diff --git a/libs/lume/src/Unattended/MacOSOfflineSetupPatcher.swift b/libs/lume/src/Unattended/MacOSOfflineSetupPatcher.swift
index 861f61ac09..29fee89f21 100644
--- a/libs/lume/src/Unattended/MacOSOfflineSetupPatcher.swift
+++ b/libs/lume/src/Unattended/MacOSOfflineSetupPatcher.swift
@@ -55,49 +55,29 @@ final class MacOSOfflineSetupPatcher {
// MARK: - Disk Attach/Mount
private struct MountedDataVolume {
- let wholeDisk: String
+ let session: DiskImageSession
let mountPoint: URL
}
private func attachDataVolume(diskPath: String) throws -> MountedDataVolume {
- let attachOutput = try run("/usr/bin/hdiutil", ["attach", "-readwrite", "-nomount", diskPath])
- guard let wholeDisk = parseWholeDisk(from: attachOutput) else {
- throw UnattendedError.commandExecutionFailed("Could not determine attached disk from hdiutil output")
- }
+ let session = DiskImageSession(diskPath: diskPath)
+ let wholeDisk = try session.attach(readWrite: true)
do {
- let container = try apfsContainer(forMainPartitionOf: wholeDisk)
- let dataDevice = try dataVolumeDevice(inContainer: container)
- _ = try run("/usr/sbin/diskutil", ["mount", dataDevice])
- let mountPoint = try mountPoint(forDevice: dataDevice)
- return MountedDataVolume(wholeDisk: wholeDisk, mountPoint: mountPoint)
+ let container = try session.apfsContainer(forMainPartitionOf: wholeDisk)
+ let dataDevice = try dataVolumeDevice(inContainer: container, session: session)
+ _ = try session.run("/usr/sbin/diskutil", ["mount", dataDevice])
+ let mountPoint = try mountPoint(forDevice: dataDevice, session: session)
+ return MountedDataVolume(session: session, mountPoint: mountPoint)
} catch {
- cleanup(mount: MountedDataVolume(wholeDisk: wholeDisk, mountPoint: URL(fileURLWithPath: "/Volumes/Data")))
+ session.unmountDiskIfMounted()
+ session.detach()
throw error
}
}
- private func parseWholeDisk(from hdiutilOutput: String) -> String? {
- for line in hdiutilOutput.split(separator: "\n") {
- let fields = line.split(whereSeparator: { $0 == " " || $0 == "\t" })
- guard fields.count >= 2 else { continue }
- if fields[1] == "GUID_partition_scheme" {
- return fields[0].replacingOccurrences(of: "/dev/", with: "")
- }
- }
- return nil
- }
-
- private func apfsContainer(forMainPartitionOf wholeDisk: String) throws -> String {
- let plist = try runPlist("/usr/sbin/diskutil", ["info", "-plist", "\(wholeDisk)s2"])
- guard let container = plist["APFSContainerReference"] as? String else {
- throw UnattendedError.commandExecutionFailed("Could not find APFS container for \(wholeDisk)s2")
- }
- return container
- }
-
- private func dataVolumeDevice(inContainer container: String) throws -> String {
- let plist = try runPlist("/usr/sbin/diskutil", ["apfs", "list", "-plist", container])
+ private func dataVolumeDevice(inContainer container: String, session: DiskImageSession) throws -> String {
+ let plist = try session.runPlist("/usr/sbin/diskutil", ["apfs", "list", "-plist", container])
guard let containers = plist["Containers"] as? [[String: Any]] else {
throw UnattendedError.commandExecutionFailed("Could not parse APFS container list for \(container)")
}
@@ -115,8 +95,8 @@ final class MacOSOfflineSetupPatcher {
throw UnattendedError.commandExecutionFailed("Could not find APFS Data volume in \(container)")
}
- private func mountPoint(forDevice device: String) throws -> URL {
- let plist = try runPlist("/usr/sbin/diskutil", ["info", "-plist", device])
+ private func mountPoint(forDevice device: String, session: DiskImageSession) throws -> URL {
+ let plist = try session.runPlist("/usr/sbin/diskutil", ["info", "-plist", device])
guard let mountPoint = plist["MountPoint"] as? String, !mountPoint.isEmpty else {
throw UnattendedError.commandExecutionFailed("Could not determine mount point for \(device)")
}
@@ -124,8 +104,8 @@ final class MacOSOfflineSetupPatcher {
}
private func cleanup(mount: MountedDataVolume) {
- _ = try? run("/usr/sbin/diskutil", ["unmount", mount.mountPoint.path])
- _ = try? run("/usr/bin/hdiutil", ["detach", "/dev/\(mount.wholeDisk)"])
+ _ = try? mount.session.run("/usr/sbin/diskutil", ["unmount", mount.mountPoint.path])
+ mount.session.detach()
}
// MARK: - Guest Patching
@@ -546,44 +526,6 @@ final class MacOSOfflineSetupPatcher {
})).sorted()
}
- // MARK: - Process Helpers
-
- private func runPlist(_ executable: String, _ arguments: [String]) throws -> [String: Any] {
- let output = try run(executable, arguments)
- guard let data = output.data(using: .utf8),
- let plist = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any] else {
- throw UnattendedError.commandExecutionFailed("Command did not return a plist: \(executable) \(arguments.joined(separator: " "))")
- }
- return plist
- }
-
- @discardableResult
- private func run(_ executable: String, _ arguments: [String]) throws -> String {
- let process = Process()
- process.executableURL = URL(fileURLWithPath: executable)
- process.arguments = arguments
-
- let output = Pipe()
- let error = Pipe()
- process.standardOutput = output
- process.standardError = error
-
- try process.run()
- process.waitUntilExit()
-
- let stdout = try output.fileHandleForReading.readToEnd() ?? Data()
- let stderr = try error.fileHandleForReading.readToEnd() ?? Data()
- let stdoutString = String(data: stdout, encoding: .utf8) ?? ""
- let stderrString = String(data: stderr, encoding: .utf8) ?? ""
-
- guard process.terminationStatus == 0 else {
- throw UnattendedError.commandExecutionFailed(
- "\(executable) \(arguments.joined(separator: " ")) failed: \(stderrString.isEmpty ? stdoutString : stderrString)"
- )
- }
-
- return stdoutString
- }
}
private extension URL {
diff --git a/libs/lume/src/Utils/CommandDocExtractor.swift b/libs/lume/src/Utils/CommandDocExtractor.swift
index bfda9a518d..487d9fa034 100644
--- a/libs/lume/src/Utils/CommandDocExtractor.swift
+++ b/libs/lume/src/Utils/CommandDocExtractor.swift
@@ -295,11 +295,15 @@ enum CommandDocExtractor {
options: [
OptionDoc(name: "cpu", shortName: nil, help: "New number of CPU cores", type: "Int", defaultValue: nil, isOptional: true),
OptionDoc(name: "memory", shortName: nil, help: "New memory size (e.g., 8GB)", type: "String", defaultValue: nil, isOptional: true),
- OptionDoc(name: "disk-size", shortName: nil, help: "New disk size (e.g., 100GB)", type: "String", defaultValue: nil, isOptional: true),
+ OptionDoc(name: "disk-size", shortName: nil, help: "New total disk size. Increase only; macOS resizing preserves RecoveryOS and grows APFS.", type: "String", defaultValue: nil, isOptional: true),
OptionDoc(name: "display", shortName: nil, help: "New display resolution", type: "String", defaultValue: nil, isOptional: true),
OptionDoc(name: "storage", shortName: nil, help: "VM storage location to use", type: "String", defaultValue: nil, isOptional: true),
],
- flags: [],
+ flags: [
+ FlagDoc(name: "no-backup", shortName: nil, help: "Skip the macOS rollback backup", defaultValue: false),
+ FlagDoc(name: "keep-backup", shortName: nil, help: "Keep rollback files after a successful macOS resize", defaultValue: false),
+ FlagDoc(name: "dry-run", shortName: nil, help: "Validate the resize plan without modifying the disk", defaultValue: false),
+ ],
subcommands: []
)
}
diff --git a/libs/lume/src/Utils/DiskImageSession.swift b/libs/lume/src/Utils/DiskImageSession.swift
new file mode 100644
index 0000000000..6b57066be1
--- /dev/null
+++ b/libs/lume/src/Utils/DiskImageSession.swift
@@ -0,0 +1,178 @@
+import Darwin
+import Foundation
+
+/// Errors thrown by ``DiskImageSession`` when a low-level disk command fails.
+enum DiskImageError: Error, LocalizedError {
+ case commandFailed(command: String, output: String)
+ case unexpectedOutput(String)
+
+ var errorDescription: String? {
+ switch self {
+ case .commandFailed(let command, let output):
+ return "\(command) failed: \(output)"
+ case .unexpectedOutput(let details):
+ return details
+ }
+ }
+}
+
+/// Wraps the `hdiutil`/`diskutil` machinery used to work on a stopped VM's raw
+/// `disk.img` offline: attach it as a block device, inspect its partitions,
+/// resolve the main APFS container, and detach it again.
+///
+/// The attach/detach/`run`/`runPlist`/`parseWholeDisk`/`apfsContainer` helpers
+/// were originally private to `MacOSOfflineSetupPatcher`; they are extracted
+/// here so both the unattended patcher and the disk-resize engine share one
+/// audited implementation.
+final class DiskImageSession {
+ let diskPath: String
+
+ /// The attached whole-disk node (e.g. `disk4`) once ``attach()`` succeeds.
+ private(set) var attachedWholeDisk: String?
+
+ init(diskPath: String) {
+ self.diskPath = diskPath
+ }
+
+ // MARK: - Attach / detach
+
+ /// Returns true if this image is already attached anywhere on the host.
+ func isAttached() throws -> Bool {
+ let plist = try runPlist("/usr/bin/hdiutil", ["info", "-plist"])
+ guard let images = plist["images"] as? [[String: Any]] else { return false }
+ let target = URL(fileURLWithPath: diskPath).resolvingSymlinksInPath().path
+ for image in images {
+ guard let imagePath = image["image-path"] as? String else { continue }
+ if URL(fileURLWithPath: imagePath).resolvingSymlinksInPath().path == target {
+ return true
+ }
+ }
+ return false
+ }
+
+ /// Attaches the image without mounting any volumes and records the
+ /// whole-disk node. Returns the node name (e.g. `disk4`).
+ @discardableResult
+ func attach(readWrite: Bool = true) throws -> String {
+ var args = ["attach"]
+ args.append(readWrite ? "-readwrite" : "-readonly")
+ args.append(contentsOf: ["-nomount", diskPath])
+ let output = try run("/usr/bin/hdiutil", args)
+ guard let wholeDisk = Self.parseWholeDisk(from: output) else {
+ detachMatchingImage()
+ throw DiskImageError.unexpectedOutput(
+ "Could not determine attached disk from hdiutil output")
+ }
+ attachedWholeDisk = wholeDisk
+ return wholeDisk
+ }
+
+ /// Detaches the attached whole disk. Retries a few times because diskutil
+ /// may briefly hold the device open (e.g. after auto-mounting a volume),
+ /// then falls back to `-force`.
+ func detach() {
+ guard let wholeDisk = attachedWholeDisk else { return }
+ let device = "/dev/\(wholeDisk)"
+ for _ in 0..<3 {
+ if (try? run("/usr/bin/hdiutil", ["detach", device])) != nil {
+ attachedWholeDisk = nil
+ return
+ }
+ Thread.sleep(forTimeInterval: 0.5)
+ }
+ _ = try? run("/usr/bin/hdiutil", ["detach", "-force", device])
+ attachedWholeDisk = nil
+ }
+
+ /// Cleans up an attachment when `hdiutil attach` succeeded but its textual
+ /// output could not be parsed. In that case `attachedWholeDisk` was never set.
+ private func detachMatchingImage() {
+ guard let plist = try? runPlist("/usr/bin/hdiutil", ["info", "-plist"]),
+ let images = plist["images"] as? [[String: Any]]
+ else { return }
+
+ let target = URL(fileURLWithPath: diskPath).resolvingSymlinksInPath().path
+ for image in images {
+ guard let imagePath = image["image-path"] as? String,
+ URL(fileURLWithPath: imagePath).resolvingSymlinksInPath().path == target,
+ let entities = image["system-entities"] as? [[String: Any]]
+ else { continue }
+
+ let devices = entities.compactMap { $0["dev-entry"] as? String }
+ if let wholeDisk = devices.first(where: { !$0.dropFirst("/dev/".count).contains("s") }) {
+ _ = try? run("/usr/bin/hdiutil", ["detach", "-force", wholeDisk])
+ }
+ }
+ }
+
+ /// Best-effort `diskutil unmountDisk` in case diskutil auto-mounted volumes
+ /// while we were attached. Safe to call even if nothing is mounted.
+ func unmountDiskIfMounted() {
+ guard let wholeDisk = attachedWholeDisk else { return }
+ _ = try? run("/usr/sbin/diskutil", ["unmountDisk", "force", "/dev/\(wholeDisk)"])
+ }
+
+ // MARK: - Partition inspection
+
+ /// Parses the whole-disk node from `hdiutil attach` output (the line whose
+ /// second field is `GUID_partition_scheme`).
+ static func parseWholeDisk(from hdiutilOutput: String) -> String? {
+ for line in hdiutilOutput.split(separator: "\n") {
+ let fields = line.split(whereSeparator: { $0 == " " || $0 == "\t" })
+ guard fields.count >= 2 else { continue }
+ if fields[1] == "GUID_partition_scheme" {
+ return fields[0].replacingOccurrences(of: "/dev/", with: "")
+ }
+ }
+ return nil
+ }
+
+ /// Resolves the APFS container reference backing the main partition
+ /// (`<wholeDisk>s2`) of an attached macOS disk.
+ func apfsContainer(forMainPartitionOf wholeDisk: String) throws -> String {
+ let plist = try runPlist("/usr/sbin/diskutil", ["info", "-plist", "\(wholeDisk)s2"])
+ guard let container = plist["APFSContainerReference"] as? String else {
+ throw DiskImageError.unexpectedOutput(
+ "Could not find APFS container for \(wholeDisk)s2")
+ }
+ return container
+ }
+
+ // MARK: - Process helpers
+
+ func runPlist(_ executable: String, _ arguments: [String]) throws -> [String: Any] {
+ let output = try run(executable, arguments)
+ guard let data = output.data(using: .utf8),
+ let plist = try PropertyListSerialization.propertyList(
+ from: data, options: [], format: nil) as? [String: Any]
+ else {
+ throw DiskImageError.unexpectedOutput(
+ "Command did not return a plist: \(executable) \(arguments.joined(separator: " "))")
+ }
+ return plist
+ }
+
+ @discardableResult
+ func run(_ executable: String, _ arguments: [String]) throws -> String {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: executable)
+ process.arguments = arguments
+
+ let output = Pipe()
+ process.standardOutput = output
+ process.standardError = output
+
+ try process.run()
+ let combined = try output.fileHandleForReading.readToEnd() ?? Data()
+ process.waitUntilExit()
+ let outputString = String(data: combined, encoding: .utf8) ?? ""
+
+ guard process.terminationStatus == 0 else {
+ throw DiskImageError.commandFailed(
+ command: "\(executable) \(arguments.joined(separator: " "))",
+ output: outputString)
+ }
+
+ return outputString
+ }
+}
diff --git a/libs/lume/src/VM/VM.swift b/libs/lume/src/VM/VM.swift
index 1a2c8ee187..c3fb83efb3 100644
--- a/libs/lume/src/VM/VM.swift
+++ b/libs/lume/src/VM/VM.swift
@@ -146,6 +146,13 @@ class VM {
vncPassword: String? = nil, recoveryMode: Bool = false, usbMassStoragePaths: [Path]? = nil,
networkMode: NetworkMode? = nil, clipboard: Bool = false
) async throws {
+ guard let resizeGuard = try vmDirContext.dir.tryAcquireResizeGuard(exclusive: false) else {
+ throw DiskResizeError.resizeInProgress(vmDirContext.name)
+ }
+ defer {
+ flock(resizeGuard.fileDescriptor, LOCK_UN)
+ try? resizeGuard.close()
+ }
Logger.info(
"VM.run method called",
metadata: [
@@ -166,6 +173,15 @@ class VM {
throw VMError.notInitialized(vmDirContext.name)
}
+ // Refuse to boot while a disk-resize transaction is armed. The marker is
+ // authoritative because run()'s emergency lock cleanup can defeat flock.
+ if vmDirContext.dir.hasResizeMarker() {
+ Logger.error(
+ "Refusing to run VM: a disk resize is in progress",
+ metadata: ["name": vmDirContext.name])
+ throw DiskResizeError.resizeInProgress(vmDirContext.name)
+ }
+
// Try to acquire lock on config file
Logger.info(
"Attempting to acquire lock on config file",
@@ -635,16 +651,6 @@ class VM {
return DiskSize(allocated: UInt64(allocated), total: UInt64(total))
}
- func resizeDisk(_ newSize: UInt64) throws {
- let currentSize = try getDiskSize()
-
- guard newSize >= currentSize.total else {
- throw VMError.resizeTooSmall(current: currentSize.total, requested: newSize)
- }
-
- try setDiskSize(newSize)
- }
-
func setCpuCount(_ newCpuCount: Int) throws {
guard !isRunning else {
throw VMError.alreadyRunning(vmDirContext.name)
@@ -661,12 +667,41 @@ class VM {
try vmDirContext.saveConfig()
}
+ /// Grow-only truncate of the raw image plus a config update. Used for
+ /// initial provisioning and for the Linux plain-grow path. macOS user
+ /// resizes go through `resizeDiskSafely` instead.
func setDiskSize(_ newDiskSize: UInt64) throws {
- try vmDirContext.setDisk(newDiskSize)
+ guard !isRunning else {
+ throw VMError.alreadyRunning(vmDirContext.name)
+ }
+ try vmDirContext.setDisk(newDiskSize) // throws on shrink / IO failure
vmDirContext.config.setDiskSize(newDiskSize)
try vmDirContext.saveConfig()
}
+ /// User-initiated disk resize entry point. For macOS guests this runs the
+ /// recovery-preserving offline transaction (relocate recovery, rewrite GPT,
+ /// grow the APFS container). For other guests it grows the image only;
+ /// in-guest `growpart`/`resize2fs` is still required.
+ func resizeDiskSafely(to newSize: UInt64, options: DiskResizeOptions) throws {
+ guard !isRunning else {
+ throw DiskResizeError.vmRunning(vmDirContext.name)
+ }
+ if vmDirContext.config.os.lowercased() == "macos" {
+ let resizer = MacDiskResizer(
+ vmDir: vmDirContext.dir,
+ diskPath: vmDirContext.diskPath.url,
+ vmName: vmDirContext.name)
+ try resizer.resize(to: newSize, options: options)
+ if !options.dryRun {
+ vmDirContext.config.setDiskSize(newSize) // keep in-memory config fresh
+ }
+ } else {
+ if options.dryRun { return }
+ try setDiskSize(newSize)
+ }
+ }
+
func setDisplay(_ newDisplay: String) throws {
guard !isRunning else {
throw VMError.alreadyRunning(vmDirContext.name)
diff --git a/libs/lume/tests/DiskResize/GPTFixtures.swift b/libs/lume/tests/DiskResize/GPTFixtures.swift
new file mode 100644
index 0000000000..9701e6a1b1
--- /dev/null
+++ b/libs/lume/tests/DiskResize/GPTFixtures.swift
@@ -0,0 +1,124 @@
+import Foundation
+
+@testable import lume
+
+/// Builds synthetic but structurally-real GPT disk images in temp files for the
+/// disk-resize unit tests: correct CRCs, mixed-endian Apple type GUIDs, and a
+/// deterministic recovery-region byte pattern so relocation can be hash-checked.
+enum GPTFixtures {
+ static let sectorSize: UInt64 = 512
+
+ /// A 64 MiB disk (131,072 sectors) laid out ISC / main APFS / recovery-last,
+ /// mirroring the real Tahoe layout at small scale.
+ static let defaultTotalSectors: UInt64 = 131_072
+
+ struct Layout {
+ var iscStart: UInt64 = 40
+ var iscEnd: UInt64 = 2_087
+ var mainStart: UInt64 = 2_088
+ var mainEnd: UInt64 = 123_031
+ var recoveryStart: UInt64 = 123_032
+ var recoveryEnd: UInt64 = 131_031 // lastUsable(131038) - 7
+ }
+
+ static func name(_ string: String) -> [UInt8] {
+ var bytes = [UInt8]()
+ for unit in string.utf16 {
+ bytes.append(UInt8(unit & 0xFF))
+ bytes.append(UInt8((unit >> 8) & 0xFF))
+ }
+ while bytes.count < 72 { bytes.append(0) }
+ return Array(bytes.prefix(72))
+ }
+
+ static func guid(_ string: String) -> GPTGUID { GPTGUID(uuidString: string)! }
+
+ static func emptyEntry() -> GPTPartitionEntry {
+ GPTPartitionEntry(
+ typeGUID: GPTGUID(bytes: [UInt8](repeating: 0, count: 16)),
+ uniqueGUID: GPTGUID(bytes: [UInt8](repeating: 0, count: 16)),
+ startingLBA: 0, endingLBA: 0, attributes: 0,
+ nameRaw: [UInt8](repeating: 0, count: 72))
+ }
+
+ static func standardEntries(_ layout: Layout = Layout()) -> [GPTPartitionEntry] {
+ var entries = [GPTPartitionEntry](repeating: emptyEntry(), count: 128)
+ entries[0] = GPTPartitionEntry(
+ typeGUID: .appleAPFSISC,
+ uniqueGUID: guid("9F198AF4-8CB8-48CF-9DCF-1CAE9DA11774"),
+ startingLBA: layout.iscStart, endingLBA: layout.iscEnd, attributes: 0,
+ nameRaw: name("iBootSystemContainer"))
+ entries[1] = GPTPartitionEntry(
+ typeGUID: .appleAPFS,
+ uniqueGUID: guid("3833D35D-646F-4B99-BCCB-A2C3B1E4F881"),
+ startingLBA: layout.mainStart, endingLBA: layout.mainEnd, attributes: 0,
+ nameRaw: name("Container"))
+ entries[2] = GPTPartitionEntry(
+ typeGUID: .appleAPFSRecovery,
+ uniqueGUID: guid("BA362677-6481-4A3F-A787-088BD36184B7"),
+ startingLBA: layout.recoveryStart, endingLBA: layout.recoveryEnd, attributes: 0,
+ nameRaw: name("RecoveryOSContainer"))
+ return entries
+ }
+
+ static func makeHeader(totalSectors: UInt64) -> GPTHeader {
+ GPTHeader(
+ revision: 0x0001_0000,
+ headerSize: 92,
+ headerCRC32: 0,
+ myLBA: 1,
+ alternateLBA: totalSectors - 1,
+ firstUsableLBA: 34,
+ lastUsableLBA: totalSectors - 34,
+ diskGUID: guid("7B049169-B6A9-4893-9D64-441B89950BFC"),
+ partitionEntryLBA: 2,
+ numberOfPartitionEntries: 128,
+ sizeOfPartitionEntry: 128,
+ partitionEntryArrayCRC32: 0)
+ }
+
+ /// Deterministic non-zero byte at a given absolute file offset.
+ static func patternByte(at offset: UInt64) -> UInt8 {
+ UInt8((offset &* 2_654_435_761 &+ 41) & 0xFF)
+ }
+
+ /// Creates a temp disk image, writes a valid GPT via `GPTTable.write`, and
+ /// fills the recovery region with the deterministic pattern. Returns the
+ /// file URL and the table that was written.
+ @discardableResult
+ static func makeDisk(
+ totalSectors: UInt64 = defaultTotalSectors,
+ layout: Layout = Layout(),
+ fillRecovery: Bool = true
+ ) throws -> (url: URL, table: GPTTable) {
+ let url = FileManager.default.temporaryDirectory
+ .appendingPathComponent("lume-gpt-\(UUID().uuidString).img")
+ FileManager.default.createFile(atPath: url.path, contents: nil)
+ let handle = try FileHandle(forUpdating: url) // write() reads the MBR back
+ try handle.truncate(atOffset: totalSectors * sectorSize)
+
+ var header = makeHeader(totalSectors: totalSectors)
+ header.lastUsableLBA = totalSectors - 34
+ let table = GPTTable(header: header, entries: standardEntries(layout))
+ try table.write(to: handle)
+
+ if fillRecovery {
+ let start = layout.recoveryStart * sectorSize
+ let end = (layout.recoveryEnd + 1) * sectorSize
+ let length = Int(end - start)
+ var bytes = [UInt8](repeating: 0, count: length)
+ for i in 0..<length { bytes[i] = patternByte(at: start + UInt64(i)) }
+ try handle.seek(toOffset: start)
+ try handle.write(contentsOf: Data(bytes))
+ }
+ try handle.close()
+ return (url, table)
+ }
+
+ static func fileSize(_ url: URL) -> UInt64 {
+ let attrs = try? FileManager.default.attributesOfItem(atPath: url.path)
+ return (attrs?[.size] as? NSNumber)?.uint64Value ?? 0
+ }
+
+ static func remove(_ url: URL) { try? FileManager.default.removeItem(at: url) }
+}
diff --git a/libs/lume/tests/DiskResize/GPTTests.swift b/libs/lume/tests/DiskResize/GPTTests.swift
new file mode 100644
index 0000000000..2bd62f8a68
--- /dev/null
+++ b/libs/lume/tests/DiskResize/GPTTests.swift
@@ -0,0 +1,321 @@
+import Foundation
+import Testing
+
+@testable import lume
+
+// MARK: - GUID / CRC primitives
+
+@Suite("GPT primitives")
+struct GPTPrimitiveTests {
+ @Test("Apple type GUIDs round-trip string ↔ raw mixed-endian bytes")
+ func guidRoundTrip() {
+ #expect(GPTGUID.appleAPFSISC.description == "69646961-6700-11AA-AA11-00306543ECAC")
+ #expect(GPTGUID.appleAPFS.description == "7C3457EF-0000-11AA-AA11-00306543ECAC")
+ #expect(GPTGUID.appleAPFSRecovery.description == "52637672-7900-11AA-AA11-00306543ECAC")
+ // First on-disk bytes of ISC are the little-endian Data1 (mixed-endian).
+ #expect(Array(GPTGUID.appleAPFSISC.bytes.prefix(4)) == [0x61, 0x69, 0x64, 0x69])
+ }
+
+ @Test("CRC32 matches the known zlib checksum of 'The quick brown fox...'")
+ func crc32KnownVector() {
+ let input = Array("The quick brown fox jumps over the lazy dog".utf8)
+ #expect(CRC32.checksum(input) == 0x414F_A339)
+ }
+}
+
+// MARK: - Round-trip
+
+@Suite("GPT read/write round-trip")
+struct GPTRoundTripTests {
+ @Test("read → write reproduces LBA 0–33 and the trailing 33 sectors byte-for-byte")
+ func roundTrip() throws {
+ let (url, _) = try GPTFixtures.makeDisk()
+ defer { GPTFixtures.remove(url) }
+
+ let ss = Int(GPTTable.sectorSize)
+ let original = try Data(contentsOf: url)
+ let total = Int(original.count) / ss
+
+ // Re-read and re-write into a copy.
+ let copy = url.appendingPathExtension("copy")
+ try original.write(to: copy)
+ defer { GPTFixtures.remove(copy) }
+
+ let readHandle = try FileHandle(forReadingFrom: copy)
+ let table = try GPTTable.read(from: readHandle, fileSizeBytes: UInt64(original.count))
+ try readHandle.close()
+
+ let writeHandle = try FileHandle(forUpdating: copy) // write() reads the MBR back
+ try table.write(to: writeHandle)
+ try writeHandle.close()
+
+ let rewritten = try Data(contentsOf: copy)
+ // First 34 sectors (MBR + primary header + primary entry array).
+ #expect(original.prefix(34 * ss) == rewritten.prefix(34 * ss))
+ // Last 33 sectors (backup entry array + backup header).
+ #expect(original.suffix(33 * ss) == rewritten.suffix(33 * ss))
+ #expect(total == Int(GPTFixtures.defaultTotalSectors))
+ }
+
+ @Test("fingerprint accepts the standard fixture and identifies all three partitions")
+ func fingerprintHappyPath() throws {
+ let (url, _) = try GPTFixtures.makeDisk()
+ defer { GPTFixtures.remove(url) }
+ let handle = try FileHandle(forReadingFrom: url)
+ defer { try? handle.close() }
+ let table = try GPTTable.read(from: handle, fileSizeBytes: GPTFixtures.fileSize(url))
+ let layout = try MacDiskLayout.fingerprint(table, fileSizeBytes: GPTFixtures.fileSize(url))
+ #expect(layout.isc.typeGUID == .appleAPFSISC)
+ #expect(layout.main.typeGUID == .appleAPFS)
+ #expect(layout.recovery.typeGUID == .appleAPFSRecovery)
+ #expect(layout.recovery.startingLBA == 123_032)
+ #expect(layout.recoveryLength == 8_000)
+ }
+
+ @Test("fingerprint accepts an already-truncated (grown) file as a repair starting state")
+ func fingerprintRepairCase() throws {
+ let (url, _) = try GPTFixtures.makeDisk()
+ defer { GPTFixtures.remove(url) }
+ // Simulate old `lume set` ftruncate: file bigger than the GPT describes.
+ let handle = try FileHandle(forWritingTo: url)
+ let grown = GPTFixtures.defaultTotalSectors * GPTFixtures.sectorSize + 10 * 1024 * 1024
+ try handle.truncate(atOffset: grown)
+ try handle.close()
+
+ let readHandle = try FileHandle(forReadingFrom: url)
+ defer { try? readHandle.close() }
+ let table = try GPTTable.read(from: readHandle, fileSizeBytes: grown)
+ #expect(throws: Never.self) {
+ _ = try MacDiskLayout.fingerprint(table, fileSizeBytes: grown)
+ }
+ }
+}
+
+// MARK: - Parser rejection
+
+@Suite("GPT parser rejection")
+struct GPTParserRejectionTests {
+ private func corrupt(_ url: URL, atOffset offset: UInt64, xor: UInt8) throws {
+ let handle = try FileHandle(forUpdating: url)
+ defer { try? handle.close() }
+ try handle.seek(toOffset: offset)
+ let byte = try handle.read(upToCount: 1) ?? Data([0])
+ try handle.seek(toOffset: offset)
+ try handle.write(contentsOf: Data([byte[byte.startIndex] ^ xor]))
+ }
+
+ @Test("bad primary header CRC is rejected")
+ func badHeaderCRC() throws {
+ let (url, _) = try GPTFixtures.makeDisk()
+ defer { GPTFixtures.remove(url) }
+ // Flip a byte in the header body (myLBA area) without fixing the CRC.
+ try corrupt(url, atOffset: 512 + 40, xor: 0xFF) // firstUsableLBA byte
+ let handle = try FileHandle(forReadingFrom: url)
+ defer { try? handle.close() }
+ #expect(throws: DiskResizeError.self) {
+ _ = try GPTTable.read(from: handle, fileSizeBytes: GPTFixtures.fileSize(url))
+ }
+ }
+
+ @Test("bad partition-array CRC is rejected")
+ func badEntriesCRC() throws {
+ let (url, _) = try GPTFixtures.makeDisk()
+ defer { GPTFixtures.remove(url) }
+ // Corrupt a byte inside the primary entry array (LBA 2).
+ try corrupt(url, atOffset: 2 * 512 + 40, xor: 0x01)
+ let handle = try FileHandle(forReadingFrom: url)
+ defer { try? handle.close() }
+ #expect(throws: DiskResizeError.self) {
+ _ = try GPTTable.read(from: handle, fileSizeBytes: GPTFixtures.fileSize(url))
+ }
+ }
+
+ @Test("bad backup partition-array CRC is rejected")
+ func badBackupEntriesCRC() throws {
+ let (url, _) = try GPTFixtures.makeDisk()
+ defer { GPTFixtures.remove(url) }
+ let handle = try FileHandle(forReadingFrom: url)
+ let table = try GPTTable.read(from: handle, fileSizeBytes: GPTFixtures.fileSize(url))
+ try handle.close()
+ let backupArrayLBA = table.header.alternateLBA - 32
+ try corrupt(url, atOffset: backupArrayLBA * 512 + 40, xor: 0x01)
+ let readHandle = try FileHandle(forReadingFrom: url)
+ defer { try? readHandle.close() }
+ #expect(throws: DiskResizeError.self) {
+ _ = try GPTTable.read(from: readHandle, fileSizeBytes: GPTFixtures.fileSize(url))
+ }
+ }
+
+ @Test("missing GPT signature is rejected")
+ func badSignature() throws {
+ let (url, _) = try GPTFixtures.makeDisk()
+ defer { GPTFixtures.remove(url) }
+ try corrupt(url, atOffset: 512, xor: 0xFF) // 'E' of "EFI PART"
+ let handle = try FileHandle(forReadingFrom: url)
+ defer { try? handle.close() }
+ #expect(throws: DiskResizeError.self) {
+ _ = try GPTTable.read(from: handle, fileSizeBytes: GPTFixtures.fileSize(url))
+ }
+ }
+
+ @Test("4096-byte-sector image reports unsupportedSectorSize")
+ func fourKSector() throws {
+ let url = FileManager.default.temporaryDirectory
+ .appendingPathComponent("lume-4k-\(UUID().uuidString).img")
+ FileManager.default.createFile(atPath: url.path, contents: nil)
+ let handle = try FileHandle(forWritingTo: url)
+ try handle.truncate(atOffset: 64 * 1024 * 1024)
+ // Put "EFI PART" at offset 4096 (LBA 1 for a 4K-sector disk), nothing at 512.
+ try handle.seek(toOffset: 4096)
+ try handle.write(contentsOf: Data("EFI PART".utf8))
+ try handle.close()
+ defer { GPTFixtures.remove(url) }
+
+ let readHandle = try FileHandle(forReadingFrom: url)
+ defer { try? readHandle.close() }
+ var thrown: DiskResizeError?
+ #expect(throws: DiskResizeError.self) {
+ do {
+ _ = try GPTTable.read(from: readHandle, fileSizeBytes: GPTFixtures.fileSize(url))
+ } catch let error as DiskResizeError {
+ thrown = error
+ throw error
+ }
+ }
+ if case .unsupportedSectorSize = thrown {
+ } else {
+ Issue.record("expected .unsupportedSectorSize, got \(String(describing: thrown))")
+ }
+ }
+
+ @Test("file smaller than the GPT-described size (missing backup) is rejected")
+ func truncatedBelowGPT() throws {
+ let (url, _) = try GPTFixtures.makeDisk()
+ defer { GPTFixtures.remove(url) }
+ let handle = try FileHandle(forWritingTo: url)
+ // Truncate so the backup header no longer exists.
+ try handle.truncate(atOffset: (GPTFixtures.defaultTotalSectors - 100) * 512)
+ try handle.close()
+ let readHandle = try FileHandle(forReadingFrom: url)
+ defer { try? readHandle.close() }
+ #expect(throws: DiskResizeError.self) {
+ _ = try GPTTable.read(
+ from: readHandle, fileSizeBytes: (GPTFixtures.defaultTotalSectors - 100) * 512)
+ }
+ }
+}
+
+// MARK: - Fingerprint rejection
+
+@Suite("MacDiskLayout fingerprint rejection")
+struct FingerprintRejectionTests {
+ private func fingerprint(
+ _ layout: GPTFixtures.Layout, mutate: (inout GPTTable) -> Void = { _ in }
+ )
+ throws -> MacDiskLayout
+ {
+ let (url, _) = try GPTFixtures.makeDisk(layout: layout)
+ defer { GPTFixtures.remove(url) }
+ let handle = try FileHandle(forReadingFrom: url)
+ defer { try? handle.close() }
+ var table = try GPTTable.read(from: handle, fileSizeBytes: GPTFixtures.fileSize(url))
+ mutate(&table)
+ return try MacDiskLayout.fingerprint(table, fileSizeBytes: GPTFixtures.fileSize(url))
+ }
+
+ @Test("only two populated partitions is rejected")
+ func twoPartitions() {
+ #expect(throws: DiskResizeError.self) {
+ _ = try fingerprint(.init()) { table in
+ table.entries[2] = GPTFixtures.emptyEntry()
+ }
+ }
+ }
+
+ @Test("a populated 4th entry is rejected")
+ func fourthEntry() {
+ #expect(throws: DiskResizeError.self) {
+ _ = try fingerprint(.init()) { table in
+ table.entries[3] = table.entries[2]
+ }
+ }
+ }
+
+ @Test("wrong type order (main and recovery swapped) is rejected")
+ func wrongTypeOrder() {
+ #expect(throws: DiskResizeError.self) {
+ _ = try fingerprint(.init()) { table in
+ table.entries.swapAt(1, 2)
+ }
+ }
+ }
+
+ @Test("recovery not last (extends past LastUsableLBA) is rejected")
+ func recoveryPastLastUsable() {
+ var layout = GPTFixtures.Layout()
+ layout.recoveryEnd = 131_050 // > lastUsable 131038
+ #expect(throws: DiskResizeError.self) { _ = try fingerprint(layout) }
+ }
+
+ @Test("recovery ending more than 7 sectors before LastUsableLBA is rejected")
+ func recoveryTooEarly() {
+ var layout = GPTFixtures.Layout()
+ layout.recoveryStart = 123_008
+ layout.recoveryEnd = 131_007 // slack = 131038 - 131007 = 31 > 7
+ #expect(throws: DiskResizeError.self) { _ = try fingerprint(layout) }
+ }
+
+ @Test("unaligned recovery start is rejected")
+ func unalignedRecovery() {
+ var layout = GPTFixtures.Layout()
+ layout.recoveryStart = 123_033 // not a multiple of 8
+ layout.recoveryEnd = 131_032
+ #expect(throws: DiskResizeError.self) { _ = try fingerprint(layout) }
+ }
+}
+
+// MARK: - SectorCopier
+
+@Suite("SectorCopier")
+struct SectorCopierTests {
+ @Test("copyRange relocates recovery bytes and the hash matches the source range")
+ func copyAndHash() throws {
+ let (url, _) = try GPTFixtures.makeDisk()
+ defer { GPTFixtures.remove(url) }
+ // Grow the file so there is room past the recovery region to copy into.
+ let handle = try FileHandle(forUpdating: url)
+ defer { try? handle.close() }
+ let newTotal = GPTFixtures.defaultTotalSectors + 20_000
+ try handle.truncate(atOffset: newTotal * 512)
+
+ let srcStart: UInt64 = 123_032
+ let len: UInt64 = 8_000
+ let dstStart: UInt64 = 140_000 // well past the source, non-overlapping
+
+ let srcHash = try SectorCopier.hashRange(
+ fd: handle.fileDescriptor, startLBA: srcStart, lengthSectors: len)
+ let copyHash = try SectorCopier.copyRange(
+ fd: handle.fileDescriptor, srcLBA: srcStart, dstLBA: dstStart, lengthSectors: len)
+ let dstHash = try SectorCopier.hashRange(
+ fd: handle.fileDescriptor, startLBA: dstStart, lengthSectors: len)
+
+ #expect(srcHash == copyHash)
+ #expect(srcHash == dstHash)
+ }
+
+ @Test("punchHole reduces allocated bytes over a region")
+ func punchReducesAllocation() throws {
+ let (url, _) = try GPTFixtures.makeDisk()
+ defer { GPTFixtures.remove(url) }
+ let handle = try FileHandle(forUpdating: url)
+ defer { try? handle.close() }
+ let fd = handle.fileDescriptor
+ let start: UInt64 = 123_032
+ let len: UInt64 = 8_000
+ let before = SectorCopier.allocatedBytes(fd: fd, startLBA: start, lengthSectors: len)
+ #expect(before > 0)
+ SectorCopier.punchHole(fd: fd, startLBA: start, lengthSectors: len)
+ let after = SectorCopier.allocatedBytes(fd: fd, startLBA: start, lengthSectors: len)
+ #expect(after < before)
+ }
+}
diff --git a/libs/lume/tests/DiskResize/MacDiskResizerTests.swift b/libs/lume/tests/DiskResize/MacDiskResizerTests.swift
new file mode 100644
index 0000000000..531ac24eab
--- /dev/null
+++ b/libs/lume/tests/DiskResize/MacDiskResizerTests.swift
@@ -0,0 +1,291 @@
+import Foundation
+import Testing
+
+@testable import lume
+
+// MARK: - Mock growers
+
+@MainActor
+final class NoopGrower: ContainerGrower {
+ var inspected = false
+ var grewToRecoveryFirst: UInt64?
+ func inspect(diskPath: URL) throws { inspected = true }
+ func grow(diskPath: URL, newRecoveryFirstLBA: UInt64) throws {
+ grewToRecoveryFirst = newRecoveryFirstLBA
+ }
+}
+
+@MainActor
+final class ThrowingGrower: ContainerGrower {
+ func inspect(diskPath: URL) throws {}
+ func grow(diskPath: URL, newRecoveryFirstLBA: UInt64) throws {
+ throw DiskResizeError.containerGrowFailed("simulated Phase 5 failure")
+ }
+}
+
+// MARK: - Fixtures for a full VM dir
+
+@MainActor
+enum ResizerFixtures {
+ /// Builds a temp VM directory containing a fixture `disk.img` and a valid
+ /// macOS `config.json`, returning the directory, the resizer, and the disk URL.
+ static func makeVMDir(
+ totalSectors: UInt64 = GPTFixtures.defaultTotalSectors,
+ oldDiskSize: UInt64,
+ grower: ContainerGrower
+ ) throws -> (vmDir: VMDirectory, resizer: MacDiskResizer, diskURL: URL) {
+ let root = FileManager.default.temporaryDirectory
+ .appendingPathComponent("lume-vm-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+
+ let (fixtureURL, _) = try GPTFixtures.makeDisk(totalSectors: totalSectors)
+ let diskURL = root.appendingPathComponent("disk.img")
+ try FileManager.default.moveItem(at: fixtureURL, to: diskURL)
+
+ let vmDir = VMDirectory(Path(root.path))
+ let config = try VMConfig(os: "macOS", diskSize: oldDiskSize, display: "1024x768")
+ try vmDir.saveConfig(config)
+
+ let resizer = MacDiskResizer(
+ vmDir: vmDir, diskPath: diskURL, vmName: vmDir.name, grower: grower)
+ return (vmDir, resizer, diskURL)
+ }
+
+ static func remove(_ vmDir: VMDirectory) {
+ try? FileManager.default.removeItem(atPath: vmDir.dir.path)
+ try? FileManager.default.removeItem(atPath: vmDir.resizeGuardPath.path)
+ }
+}
+
+// MARK: - Happy path
+
+@MainActor
+@Suite("MacDiskResizer happy path")
+struct MacDiskResizerHappyPathTests {
+ // 64 MiB → 96 MiB.
+ let oldSize: UInt64 = 64 * 1024 * 1024
+ let newSize: UInt64 = 96 * 1024 * 1024
+
+ @Test("expands, relocates recovery byte-identically, updates config and cleans up")
+ func happyPath() throws {
+ let grower = NoopGrower()
+ let (vmDir, resizer, diskURL) = try ResizerFixtures.makeVMDir(
+ oldDiskSize: oldSize, grower: grower)
+ defer { ResizerFixtures.remove(vmDir) }
+
+ // Capture the pre-move recovery hash from the original layout.
+ let preHandle = try FileHandle(forReadingFrom: diskURL)
+ let preTable = try GPTTable.read(from: preHandle, fileSizeBytes: oldSize)
+ let preLayout = try MacDiskLayout.fingerprint(preTable, fileSizeBytes: oldSize)
+ let preHash = try SectorCopier.hashRange(
+ fd: preHandle.fileDescriptor,
+ startLBA: preLayout.recovery.startingLBA,
+ lengthSectors: preLayout.recoveryLength)
+ try preHandle.close()
+
+ try resizer.resize(to: newSize, options: DiskResizeOptions())
+
+ // File grew.
+ #expect(GPTFixtures.fileSize(diskURL) == newSize)
+
+ // GPT re-fingerprints with recovery at the new tail; hash preserved.
+ let handle = try FileHandle(forReadingFrom: diskURL)
+ defer { try? handle.close() }
+ let table = try GPTTable.read(from: handle, fileSizeBytes: newSize)
+ let layout = try MacDiskLayout.fingerprint(table, fileSizeBytes: newSize)
+ let expectedTotal = newSize / 512
+ #expect(layout.totalSectors == expectedTotal)
+ #expect(table.header.lastUsableLBA == expectedTotal - 34)
+ #expect(layout.recovery.startingLBA > preLayout.recovery.endingLBA)
+ #expect(layout.recovery.startingLBA % 8 == 0)
+ #expect(layout.recoveryLength == preLayout.recoveryLength)
+ // Same recovery identity (unique GUID + name preserved).
+ #expect(layout.recovery.uniqueGUID == preLayout.recovery.uniqueGUID)
+ #expect(layout.recovery.nameRaw == preLayout.recovery.nameRaw)
+ // Recovery hugs LastUsable within 7 sectors.
+ #expect(table.header.lastUsableLBA - layout.recovery.endingLBA <= 7)
+
+ let postHash = try SectorCopier.hashRange(
+ fd: handle.fileDescriptor,
+ startLBA: layout.recovery.startingLBA,
+ lengthSectors: layout.recoveryLength)
+ #expect(postHash == preHash)
+
+ // Grower was driven with the relocated recovery start.
+ #expect(grower.grewToRecoveryFirst == layout.recovery.startingLBA)
+
+ // Config updated; marker + backup cleaned up.
+ let config = try vmDir.loadConfig()
+ #expect(config.diskSize == newSize)
+ #expect(!vmDir.hasResizeMarker())
+ #expect(!FileManager.default.fileExists(atPath: vmDir.diskBackupPath.path))
+ }
+
+ @Test("--keep-backup leaves the pre-resize backup in place")
+ func keepBackup() throws {
+ let (vmDir, resizer, _) = try ResizerFixtures.makeVMDir(
+ oldDiskSize: oldSize, grower: NoopGrower())
+ defer { ResizerFixtures.remove(vmDir) }
+ try resizer.resize(to: newSize, options: DiskResizeOptions(backup: true, keepBackup: true))
+ #expect(FileManager.default.fileExists(atPath: vmDir.diskBackupPath.path))
+ #expect(!vmDir.hasResizeMarker())
+ }
+
+ @Test("dry-run leaves disk and configuration unchanged")
+ func dryRun() throws {
+ let (vmDir, resizer, diskURL) = try ResizerFixtures.makeVMDir(
+ oldDiskSize: oldSize, grower: NoopGrower())
+ defer { ResizerFixtures.remove(vmDir) }
+ let original = try Data(contentsOf: diskURL)
+ try resizer.resize(to: newSize, options: DiskResizeOptions(dryRun: true))
+ #expect(try Data(contentsOf: diskURL) == original)
+ #expect(try vmDir.loadConfig().diskSize == oldSize)
+ #expect(!vmDir.hasResizeMarker())
+ }
+}
+
+// MARK: - Guards & rollback
+
+@MainActor
+@Suite("MacDiskResizer guards and rollback")
+struct MacDiskResizerGuardTests {
+ let oldSize: UInt64 = 64 * 1024 * 1024
+
+ @Test("shrink is refused")
+ func shrink() throws {
+ let (vmDir, resizer, _) = try ResizerFixtures.makeVMDir(
+ oldDiskSize: oldSize, grower: NoopGrower())
+ defer { ResizerFixtures.remove(vmDir) }
+ #expect(throws: DiskResizeError.self) {
+ try resizer.resize(to: 32 * 1024 * 1024, options: DiskResizeOptions())
+ }
+ #expect(!vmDir.hasResizeMarker())
+ }
+
+ @Test("growth smaller than the recovery relocation minimum is refused")
+ func growthTooSmall() throws {
+ let (vmDir, resizer, _) = try ResizerFixtures.makeVMDir(
+ oldDiskSize: oldSize, grower: NoopGrower())
+ defer { ResizerFixtures.remove(vmDir) }
+ // +1 MiB is far below recovery(≈4 MiB) + slop.
+ #expect(throws: DiskResizeError.self) {
+ try resizer.resize(to: oldSize + 1024 * 1024, options: DiskResizeOptions())
+ }
+ #expect(!vmDir.hasResizeMarker())
+ }
+
+ @Test("a held config.json lock is treated as a running VM")
+ func runningLock() throws {
+ let (vmDir, resizer, _) = try ResizerFixtures.makeVMDir(
+ oldDiskSize: oldSize, grower: NoopGrower())
+ defer { ResizerFixtures.remove(vmDir) }
+ let lock = try FileHandle(forWritingTo: vmDir.configPath.url)
+ defer {
+ flock(lock.fileDescriptor, LOCK_UN)
+ try? lock.close()
+ }
+
+ #expect(flock(lock.fileDescriptor, LOCK_EX | LOCK_NB) == 0)
+ #expect(throws: DiskResizeError.self) {
+ try resizer.resize(to: 96 * 1024 * 1024, options: DiskResizeOptions())
+ }
+ }
+
+ @Test("a shared VM-operation guard blocks resize")
+ func sharedGuardBlocksResize() throws {
+ let (vmDir, resizer, _) = try ResizerFixtures.makeVMDir(
+ oldDiskSize: oldSize, grower: NoopGrower())
+ defer { ResizerFixtures.remove(vmDir) }
+ let acquired = try vmDir.tryAcquireResizeGuard(exclusive: false)
+ let guardHandle = try #require(acquired)
+ defer {
+ flock(guardHandle.fileDescriptor, LOCK_UN)
+ try? guardHandle.close()
+ }
+ #expect(throws: DiskResizeError.self) {
+ try resizer.resize(to: 96 * 1024 * 1024, options: DiskResizeOptions())
+ }
+ }
+
+ @Test("a Phase 5 failure rolls back to the byte-identical original disk")
+ func rollbackOnGrowFailure() throws {
+ let (vmDir, resizer, diskURL) = try ResizerFixtures.makeVMDir(
+ oldDiskSize: oldSize, grower: ThrowingGrower())
+ defer { ResizerFixtures.remove(vmDir) }
+ let original = try Data(contentsOf: diskURL)
+
+ #expect(throws: DiskResizeError.self) {
+ try resizer.resize(to: 96 * 1024 * 1024, options: DiskResizeOptions())
+ }
+ // Disk restored byte-for-byte; marker + backup gone; config unchanged.
+ let restored = try Data(contentsOf: diskURL)
+ #expect(restored == original)
+ #expect(!vmDir.hasResizeMarker())
+ #expect(!FileManager.default.fileExists(atPath: vmDir.diskBackupPath.path))
+ #expect(try vmDir.loadConfig().diskSize == oldSize)
+ }
+
+ @Test("an interrupted transaction with a backup auto-recovers on next invocation")
+ func recoverPending() throws {
+ let (vmDir, resizer, diskURL) = try ResizerFixtures.makeVMDir(
+ oldDiskSize: oldSize, grower: NoopGrower())
+ defer { ResizerFixtures.remove(vmDir) }
+ let original = try Data(contentsOf: diskURL)
+
+ // Simulate a crash mid-transaction: a backup exists and a marker is armed,
+ // while the live disk has been mangled.
+ _ = Darwin.clonefile(diskURL.path, vmDir.diskBackupPath.path, 0)
+ try FileManager.default.copyItem(
+ at: vmDir.configPath.url, to: vmDir.configBackupPath.url)
+ let mangle = try FileHandle(forWritingTo: diskURL)
+ try mangle.seek(toOffset: 512)
+ try mangle.write(contentsOf: Data(repeating: 0xAB, count: 512))
+ try mangle.close()
+ try vmDir.saveResizeMarker(
+ ResizeMarker(
+ version: 1, phase: 4, oldSizeBytes: oldSize, newSizeBytes: 96 * 1024 * 1024,
+ backupDiskPath: vmDir.diskBackupPath.path, startedAt: 0))
+
+ #expect(try resizer.recoverPendingIfAny() == true)
+ #expect(try Data(contentsOf: diskURL) == original)
+ #expect(!vmDir.hasResizeMarker())
+ }
+
+ @Test("a malformed resize marker fails closed")
+ func malformedMarker() throws {
+ let (vmDir, resizer, _) = try ResizerFixtures.makeVMDir(
+ oldDiskSize: oldSize, grower: NoopGrower())
+ defer { ResizerFixtures.remove(vmDir) }
+ try Data("not-json".utf8).write(to: vmDir.resizeMarkerPath.url)
+ #expect(throws: DiskResizeError.self) {
+ try resizer.resize(to: 96 * 1024 * 1024, options: DiskResizeOptions())
+ }
+ #expect(vmDir.hasResizeMarker())
+ }
+}
+
+// MARK: - VMDirectory.setDisk regression
+
+@Suite("VMDirectory.setDisk")
+struct VMDirectorySetDiskTests {
+ private func tempVMDir() throws -> VMDirectory {
+ let root = FileManager.default.temporaryDirectory
+ .appendingPathComponent("lume-setdisk-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ return VMDirectory(Path(root.path))
+ }
+
+ @Test("grow succeeds; shrink throws instead of silently corrupting")
+ func growThenShrink() throws {
+ let vmDir = try tempVMDir()
+ defer { try? FileManager.default.removeItem(atPath: vmDir.dir.path) }
+ try vmDir.setDisk(10 * 1024 * 1024)
+ #expect(GPTFixtures.fileSize(vmDir.diskPath.url) == 10 * 1024 * 1024)
+ try vmDir.setDisk(20 * 1024 * 1024) // grow OK
+ #expect(GPTFixtures.fileSize(vmDir.diskPath.url) == 20 * 1024 * 1024)
+ #expect(throws: VMDirectoryError.self) {
+ try vmDir.setDisk(5 * 1024 * 1024) // shrink refused
+ }
+ #expect(GPTFixtures.fileSize(vmDir.diskPath.url) == 20 * 1024 * 1024)
+ }
+}