From 862fb3b9e3f66e471315a83530ceba23e6d1784a Mon Sep 17 00:00:00 2001 From: osy Date: Mon, 16 Nov 2026 18:50:28 -0800 Subject: [PATCH] scripting: return the guest size of existing drives UTM.sdef declares `guest size` on the drive records that `get configuration` returns, and `update configuration` grows a QCOW2 drive to it, but the records never carried it. A script could not read a drive's capacity, nor check that a resize took effect (#8190). Read the size from the image as the guest sees it: the virtual size in a QCOW2 header, the file size of a raw image or of a removable drive's CD or floppy image, and the size DiskImageKit reports for an Apple drive (an ASIF image is sparse, so its file size is never used). The configuration property is read synchronously, so this does not go through qemu-img. A drive with no image, or whose size cannot be read, has no `guest size`. Every record from `get configuration` now carries the size, so applying one back sent it for every drive, and raw and removable drives refused it with driveNotResizable. A size equal to the drive's current one now changes nothing. When the same record replaces the drive's source, the size it carries is the replaced image's, so that size is ignored too instead of growing the new image. Resolves #8190 Assisted-by: Claude:claude-opus-5-5 --- Scripting/UTM.sdef | 4 +- Scripting/UTMScriptingConfigImpl.swift | 75 ++++++++++++- .../UTMScriptingConfigImplTests.swift | 105 ++++++++++++++++++ 3 files changed, 180 insertions(+), 4 deletions(-) diff --git a/Scripting/UTM.sdef b/Scripting/UTM.sdef index 2c22df81c5..466abaf0a4 100644 --- a/Scripting/UTM.sdef +++ b/Scripting/UTM.sdef @@ -669,7 +669,7 @@ description="The size of this drive as seen by the host (in MiB)."/> + description="The size of this drive as seen by the guest (in MiB), missing when it cannot be read from the drive's image, as for a removable drive with no image. Setting it on an existing QCOW2 drive stored in the virtual machine to a different size makes the drive larger (it cannot be made smaller); back up the virtual machine first. When the same update replaces the drive's source, the size of the replaced image is ignored."/> @@ -883,7 +883,7 @@ description="The size of this drive as seen by the host (in MiB)."/> + description="The size of this drive as seen by the guest (in MiB), missing when it cannot be read from the drive's image, as for a removable drive with no image. It is only set when a drive is created."/> diff --git a/Scripting/UTMScriptingConfigImpl.swift b/Scripting/UTMScriptingConfigImpl.swift index 1edf966722..2727bda392 100644 --- a/Scripting/UTMScriptingConfigImpl.swift +++ b/Scripting/UTMScriptingConfigImpl.swift @@ -95,6 +95,8 @@ class UTMScriptingConfigImpl { ] // an empty removable drive has no source record["source"] = drive.imageURL + // nor a size, like an image whose size cannot be read + record["guestSize"] = guestSize(of: drive) return record } @@ -109,6 +111,63 @@ class UTMScriptingConfigImpl { return source.standardizedFileURL.resolvingSymlinksInPath().path == current.standardizedFileURL.resolvingSymlinksInPath().path } + /// The size of `drive`'s disk as the guest sees it (MiB), or nil when it cannot be read + /// + /// This is read from the image itself, without `qemu-img`: a scripting property is read + /// synchronously. + private func guestSize(of drive: any UTMConfigurationDrive) -> Int? { + guard let url = drive.imageURL else { + return nil + } + let scoped = url.startAccessingSecurityScopedResource() + defer { + if scoped { + url.stopAccessingSecurityScopedResource() + } + } + let header = imageHeader(of: url) + let bytes: Int64? + if drive is UTMAppleConfigurationDrive { + bytes = appleImageSize(of: url, header: header) + } else if let header = header, header.starts(with: [0x51, 0x46, 0x49, 0xfb]) { // QCOW2 + bytes = Int64(exactly: header[24..<32].reduce(UInt64(0)) { $0 << 8 | UInt64($1) }) + } else if drive.isRawImage || drive.isExternal { + // a removable drive holds a CD or floppy image: raw, whatever QEMU probes + bytes = fileSize(of: url) + } else { + bytes = nil + } + return bytes.map { Int($0 / bytesInMib) } + } + + private func appleImageSize(of url: URL, header: Data?) -> Int64? { + if #available(macOS 14, *), let info = try? UTMAppleDiskImage.info(for: url) { + return info.size + } + // an ASIF image is sparse: its file size is not the disk's + if let header = header, header.starts(with: Array("shdw".utf8)) { + return nil + } + return fileSize(of: url) + } + + private func imageHeader(of url: URL) -> Data? { + guard let file = try? FileHandle(forReadingFrom: url) else { + return nil + } + defer { + try? file.close() + } + guard let header = try? file.read(upToCount: 32), header.count == 32 else { + return nil + } + return header + } + + private func fileSize(of url: URL) -> Int64? { + (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize.map { Int64($0) } + } + private func size(of drive: any UTMConfigurationDrive) -> Int { guard let data = data else { return 0 @@ -496,6 +555,7 @@ extension UTMScriptingConfigImpl { } private func updateQemuExistingDrive(_ drive: inout UTMQemuConfigurationDrive, from record: [AnyHashable : Any]) throws { + let previous = drive if let interface = parseQemuDriveInterface(record["interface"] as? AEKeyword), interface != drive.interface { // like the interface picker in the settings drive.setInterface(interface) @@ -503,7 +563,7 @@ extension UTMScriptingConfigImpl { if let source = record["source"] as? URL, !isCurrentImage(source, of: drive) { drive.imageURL = source } - if let size = record["guestSize"] as? Int, size > 0 { + if let size = record["guestSize"] as? Int, size > 0, !isUnchangedGuestSize(size, of: drive, previous: previous) { // like the drive settings: only a qcow2 image in the VM can grow guard !drive.isExternal, !drive.isRawImage else { throw ConfigurationError.driveNotResizable @@ -511,7 +571,18 @@ extension UTMScriptingConfigImpl { pendingDriveResizes.append((id: drive.id, sizeMib: size)) } } - + + /// Is `size` what `get configuration` returns for `drive`, so that it asks for no resize? + /// + /// A record from `get configuration` carries every drive's guest size. When the same record + /// replaces the drive's source, the size it carries is still the replaced image's. + private func isUnchangedGuestSize(_ size: Int, of drive: UTMQemuConfigurationDrive, previous: UTMQemuConfigurationDrive) -> Bool { + if size == guestSize(of: drive) { + return true + } + return drive.imageURL != previous.imageURL && size == guestSize(of: previous) + } + /// Check the new guest sizes before anything is saved, so that an invalid size changes nothing /// /// A drive whose source is replaced in the same update is checked at that source, which is diff --git a/Tests/macOS/Scripting/UTMScriptingConfigImplTests.swift b/Tests/macOS/Scripting/UTMScriptingConfigImplTests.swift index a10fd0e168..b18e08df4d 100644 --- a/Tests/macOS/Scripting/UTMScriptingConfigImplTests.swift +++ b/Tests/macOS/Scripting/UTMScriptingConfigImplTests.swift @@ -224,6 +224,111 @@ import XCTest XCTAssertEqual(config.drives[0].imageURL, other) } + /// A file in a new temporary directory, removed after the test + private func temporaryFile(_ name: String) throws -> URL { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + addTeardownBlock { + try? FileManager.default.removeItem(at: directory) + } + return directory.appendingPathComponent(name) + } + + /// A QCOW2 header for a disk of `sizeMib`, all that the record reads + private func qcow2Image(sizeMib: Int) throws -> URL { + try qcow2Image(sizeBytes: UInt64(sizeMib * 1048576)) + } + + private func qcow2Image(sizeBytes: UInt64) throws -> URL { + let url = try temporaryFile("disk.qcow2") + var header = Data([0x51, 0x46, 0x49, 0xfb, 0, 0, 0, 3]) + header += Data(count: 16) + withUnsafeBytes(of: sizeBytes.bigEndian) { header += Data($0) } + try header.write(to: url) + return url + } + + /// A sparse raw image of `sizeMib` + private func rawImage(_ name: String, sizeMib: Int) throws -> URL { + let url = try temporaryFile(name) + FileManager.default.createFile(atPath: url.path, contents: nil) + let file = try FileHandle(forWritingTo: url) + try file.truncate(atOffset: UInt64(sizeMib * 1048576)) + try file.close() + return url + } + + /// `guest size` is declared on existing drive records, so `get configuration` must return + /// the size the guest sees, not the space the image takes on the host (#8190). + func testDriveRecordsReturnTheirGuestSize_8190() throws { + let config = configuration() + config.drives[0].imageURL = try qcow2Image(sizeMib: 64) + var cd = UTMQemuConfigurationDrive(forArchitecture: .aarch64, target: QEMUTarget_aarch64.virt, isExternal: true) + cd.imageURL = try rawImage("install.iso", sizeMib: 3) + let empty = UTMQemuConfigurationDrive(forArchitecture: .aarch64, target: QEMUTarget_aarch64.virt, isExternal: true) + var missing = UTMQemuConfigurationDrive(forArchitecture: .aarch64, target: QEMUTarget_aarch64.virt) + missing.imageURL = URL(fileURLWithPath: "/nonexistent/disk.qcow2") + var corrupt = UTMQemuConfigurationDrive(forArchitecture: .aarch64, target: QEMUTarget_aarch64.virt) + corrupt.imageURL = try qcow2Image(sizeBytes: UInt64.max) + config.drives += [cd, empty, missing, corrupt] + let drives = try XCTUnwrap(UTMScriptingConfigImpl(config).serializeConfiguration()["drives"] as? [[AnyHashable: Any]]) + XCTAssertEqual(drives[0]["guestSize"] as? Int, 64) + XCTAssertEqual(drives[1]["guestSize"] as? Int, 3) + XCTAssertNil(drives[2]["guestSize"], "an empty removable drive has no size") + XCTAssertNil(drives[3]["guestSize"], "an image that cannot be read has no size") + XCTAssertNil(drives[4]["guestSize"], "nor has an image with an impossible size") + } + + func testAppleDriveRecordsReturnTheirGuestSize_8190() throws { + let config = UTMAppleConfiguration() + config.drives = [UTMAppleConfigurationDrive(existingURL: try rawImage("disk.img", sizeMib: 32)), + UTMAppleConfigurationDrive(existingURL: nil, isExternal: true)] + let drives = try XCTUnwrap(UTMScriptingConfigImpl(config).serializeConfiguration()["drives"] as? [[AnyHashable: Any]]) + XCTAssertEqual(drives[0]["guestSize"] as? Int, 32) + XCTAssertNil(drives[1]["guestSize"], "an empty removable drive has no size") + } + + /// Records from `get configuration` now carry every drive's guest size: applying one back + /// must not ask to resize drives that cannot be resized, nor carry the old size over to a + /// source replaced in the same record (#8190). + func testUnchangedGuestSizeLeavesDrivesAlone_8190() throws { + let config = configuration() + config.drives[0].imageURL = try qcow2Image(sizeMib: 64) + var raw = UTMQemuConfigurationDrive(forArchitecture: .aarch64, target: QEMUTarget_aarch64.virt) + raw.isRawImage = true + raw.imageURL = try rawImage("disk.img", sizeMib: 16) + var cd = UTMQemuConfigurationDrive(forArchitecture: .aarch64, target: QEMUTarget_aarch64.virt, isExternal: true) + cd.imageURL = try rawImage("install.iso", sizeMib: 3) + config.drives += [raw, cd] + let before = try plist(config) + let wrapper = UTMScriptingConfigImpl(config) + var record = wrapper.serializeConfiguration() + try wrapper.updateConfiguration(from: record) + XCTAssertEqual(try plist(config), before) + + var drives = try XCTUnwrap(record["drives"] as? [[AnyHashable: Any]]) + let other = try rawImage("other.iso", sizeMib: 5) + drives[2]["source"] = other + record["drives"] = drives + try UTMScriptingConfigImpl(config).updateConfiguration(from: record) + XCTAssertEqual(config.drives[2].imageURL, other) + + // the size of the new image is no resize either + drives[2]["source"] = try rawImage("third.iso", sizeMib: 7) + drives[2]["guestSize"] = 7 + record["drives"] = drives + try UTMScriptingConfigImpl(config).updateConfiguration(from: record) + XCTAssertEqual(config.drives[2].imageURL, drives[2]["source"] as? URL) + + drives[1]["guestSize"] = 32 + record["drives"] = drives + XCTAssertThrowsError(try UTMScriptingConfigImpl(config).updateConfiguration(from: record), "a new size for a raw drive") { error in + guard case UTMScriptingConfigImpl.ConfigurationError.driveNotResizable = error else { + return XCTFail("\(error)") + } + } + } + /// Only a qcow2 image inside the bundle can be grown (7c01ae38). func testGuestSizeIsRejectedForRawAndRemovableDrives() throws { for (label, prepare) in [("raw", { (drive: inout UTMQemuConfigurationDrive) in drive.isRawImage = true }),