Running macOS in a virtual machine on Apple silicon
Install and run macOS in a virtual machine using the Virtualization framework.
Overview
This sample code project demonstrates how to install and run macOS virtual machines (VMs) on Apple silicon. The Xcode project includes three separate apps:
InstallationTool, a command line utility that installs macOS from a restore image, which is a file with a.ipswfile extension, onto a VM. You can use this tool to download the restore image of the most current macOS release from the network, or with your own restore image. The utility creates a VM bundle and stores the resulting VM images in your Home directory.macOSVirtualMachineSampleAppis a Mac app that runs the macOS VM thatInstallationToolinstalls. You usemacOSVirtualMachineSampleAppto launch and control the macOS VM that loads and runs macOS from the VM bundle. This app includes entitlements to enable it to use Virtualization and access the VM’s audio input, such as the microphone.sharedBaseImageSampleAppis a Mac app that demonstrates how to create two VMs that use a common base disk image using the capabilities of DiskImageKit. In this version, theInstallationToolcreates two disk images from the macOS restore image thatsharedBaseImageSampleAppconfigures and that run simultaneously. As withmacOSVirtualMachineSampleApp, this app includes entitlements to enable it to use Virtualization and access the VM’s audio input, such as the microphone.
There are five build targets in this project that represent the InstallationTool and the macOSVirtualMachineSampleApp, one set of targets each for Swift and Objective-C versions of the apps, and another target for the sharedBaseImageSampleApp.
Configure the sample code project
You need to install the virtual machine, and VM.bundle needs exist before launching the sample app.
Set up code signing for each of the project’s targets by navigating to the Signing & Capabilities settings and selecting your team from the drop-down menu.
Run
InstallationToolfrom within Xcode or in Terminal to download the latest available macOS restore image from the network and create a macOS VM image on disk.InstallationToolcreates aVM.bundlepackage in your Home directory, containing:Disk.img— The main disk image of the installed OS.AuxiliaryStorage— The auxiliary storage for macOS.MachineIdentifier— The data representation of theVZMacMachineIdentifierobject.HardwareModel— The data representation of theVZMacHardwareModelobject.RestoreImage.ipsw— The restore image downloaded from the network (this file exists only if the tool runs without arguments).
Select one of the versions of the app to launch, either
macOSVirtualMachineSampleApp(Objective-C or Swift) orsharedBaseImageSampleApp, to run the macOS guest operating system. The sample app starts the VM and configures a graphical view that you interact with. The virtual Mac continues running until you shut it down from inside the guest OS, or quit the app.To reinstall the virtual machine, delete the
VM.bundlepackage and runInstallationToolagain.
Install macOS from a restore image
After downloading a restore image, you can install macOS from that restore image.
Set up the virtual machine
The macOSVirtualMachineSampleApp versions operate identically, using a single VM image to launch a single macOS VM; the sharedBaseImageSampleApp uses different initial setup and configuration methods to enable the app to support two VMs using a common, shared base image that both VMs run.
As with the macOSVirtualMachineSampleApp, the installation tool downloads a macOS .ipsw restore image, creates an empty image (Disk.img), and then installs the OS there. This Disk.img becomes the base image that sharedBaseImageSampleApp uses to create the base image of a stack that its VMs use.
The following examples show the configuration and initialization methods for this multi-VM, Swift-only version; these methods create per-VM unique platform configurations and per-VM unique network devices the system needs to differentiate between the VMs. This example uses an index to distinguish each VM.
// Creates a per-VM platform object that includes a unique machine identifier and auxiliary storage.
private static func createMacPlatform(vmIndex: Int) -> VZMacPlatformConfiguration {
let macPlatform = VZMacPlatformConfiguration()
if !FileManager.default.fileExists(atPath: vmBundlePath) {
fatalError("Missing Virtual Machine Bundle at \(vmBundlePath). Run InstallationTool first to create it.")
}
// The installation tool creates and describes the virtual hardware, and all VMs share the same hardware model.
macPlatform.hardwareModel = MacOSVirtualMachineConfigurationHelper.readHardwareModel(hardwareModelURL: hardwareModelURL)
// Each VM needs its own machine identifier and auxiliary storage.
// Copy the auxiliary storage from the original VM (created during installation)
// so it contains the boot configuration and NVRAM.
let vmDir = vmDirectoryURL(forVM: vmIndex)
let machineIdentifierURL = machineIdentifierURL(forVM: vmIndex)
let auxiliaryStorageURL = auxiliaryStorageURL(forVM: vmIndex)
if FileManager.default.fileExists(atPath: machineIdentifierURL.path) {
guard let data = try? Data(contentsOf: machineIdentifierURL),
let machineIdentifier = VZMacMachineIdentifier(dataRepresentation: data) else {
fatalError("Failed to retrieve machine identifier for VM \(vmIndex).")
}
macPlatform.machineIdentifier = machineIdentifier
macPlatform.auxiliaryStorage = VZMacAuxiliaryStorage(contentsOf: auxiliaryStorageURL)
} else {
try! FileManager.default.createDirectory(at: vmDir, withIntermediateDirectories: true)
let machineIdentifier = VZMacMachineIdentifier()
try! machineIdentifier.dataRepresentation.write(to: machineIdentifierURL)
macPlatform.machineIdentifier = machineIdentifier
let originalAuxStorage = vmBundleURL.appendingPathComponent("AuxiliaryStorage")
try! FileManager.default.copyItem(at: originalAuxStorage, to: auxiliaryStorageURL)
macPlatform.auxiliaryStorage = VZMacAuxiliaryStorage(contentsOf: auxiliaryStorageURL)
}
return macPlatform
}
// Create a unique, per-VM block device configuration.
static func createBlockDeviceConfiguration(vmIndex: Int) throws -> VZVirtioBlockDeviceConfiguration {
let baseImage = try DiskImage(opening: .open(url: diskImageURL, mode: .readOnly))
let stackedImage: StackedImage
let overlay = overlayURL(forVM: vmIndex)
if FileManager.default.fileExists(atPath: overlay.path) {
let overlayImage = try DiskImage(opening: .open(url: overlay))
stackedImage = try baseImage.appending(overlayImage)
} else {
stackedImage = try baseImage.appending(.asifLayer(url: overlay, type: .overlay))
}
let attachment = try VZDiskImageStorageDeviceAttachment(diskImage: stackedImage)
return VZVirtioBlockDeviceConfiguration(attachment: attachment)
}
// Create a unique, per-VM network configuration; the last octet of the network MAC address is the index of the VM.
private static func createNetworkDeviceConfiguration(vmIndex: Int) -> VZVirtioNetworkDeviceConfiguration {
let networkDevice = VZVirtioNetworkDeviceConfiguration()
networkDevice.macAddress = VZMACAddress(string: String(format: "d6:a7:58:8e:78:%02x", vmIndex))!
networkDevice.attachment = VZNATNetworkDeviceAttachment()
return networkDevice
}
The app delegate starts and manages the VMs using individual machine configurations:
#if arch(arm64)
func applicationDidFinishLaunching(_ aNotification: Notification) {
Task { @MainActor in
let configurations = await createAllConfigurations()
startVMs(with: configurations)
}
}
@MainActor
private func startVMs(with configurations: [VZVirtualMachineConfiguration]) {
for index in 1...Self.vmCount {
let vm = VZVirtualMachine(configuration: configurations[index - 1])
let delegate = SharedVirtualMachineDelegate(name: "VM \(index)")
vm.delegate = delegate
let (vmWindow, vmView): (NSWindow, VZVirtualMachineView)
if index == 1 {
let view = VZVirtualMachineView()
window.title = "VM \(index) — Shared Base Image"
window.contentView = view
vmWindow = window
vmView = view
} else {
(vmWindow, vmView) = makeVMWindow(
title: "VM \(index) — Shared Base Image",
frame: windowFrame(forVM: index)
)
}
vmView.virtualMachine = vm
vmView.capturesSystemKeys = true
vmView.automaticallyReconfiguresDisplay = true
virtualMachines.append(vm)
delegates.append(delegate)
windows.append(vmWindow)
vm.start { result in
if case let .failure(error) = result {
fatalError("VM \(index) failed to start: \(error)")
}
}
}
}
@MainActor
private func createAllConfigurations() async -> [VZVirtualMachineConfiguration] {
do {
return try await buildConfigurations()
} catch is IncompatibleStackingError {
guard promptOverlayReset() else {
NSApplication.shared.terminate(nil)
fatalError("Terminating due to incompatible overlays.")
}
await discardAllOverlays()
do {
return try await buildConfigurations()
} catch {
fatalError("Failed to create VM configurations after discarding overlays: \(error)")
}
} catch {
fatalError("Failed to create VM configurations: \(error)")
}
}
private func buildConfigurations() async throws -> [VZVirtualMachineConfiguration] {
try await Task.detached {
try (1...Self.vmCount).map {
try SharedVMConfigurationHelper.createVirtualMachineConfiguration(vmIndex: $0)
}
}.value
}
private func discardAllOverlays() async {
await Task.detached {
for index in 1...Self.vmCount {
SharedVMConfigurationHelper.discardOverlay(vmIndex: index)
}
}.value
}
@MainActor
private func promptOverlayReset() -> Bool {
let alert = NSAlert()
alert.messageText = "Overlays Incompatible"
alert.informativeText =
"The base disk image has been modified. " +
"The existing overlays are no longer compatible " +
"and must be reset.\n\n" +
"Reset all overlays to start with a fresh state?"
alert.alertStyle = .warning
alert.addButton(withTitle: "Reset and Continue")
alert.addButton(withTitle: "Quit")
return alert.runModal() == .alertFirstButtonReturn
}
#else
func applicationDidFinishLaunching(_ aNotification: Notification) {
fatalError("SharedBaseImageSampleApp requires an Apple Silicon Mac.")
}
#endifThe following examples (for both Swift and Objective-C) show how the macOSVirtualMachineSampleApp sample app version uses a single VZVirtualMachineConfiguration object to configure the basic characteristics of the guest, such as the CPU count, memory size, creation of disk images, various device configurations, and a VZMacOSBootLoader object to load the operating system from the disk image:
Inside the createVirtualMachine method, the app also creates a platform configuration for the VM. VZMacPlatformConfiguration configures important macOS-specific data that the macOS guest needs to run, including the specific hardwareModel that the image supports, as well as a machineIdentifier that uniquely identifies the current VM instance and differentiates it from any others.
After creating the platform configuration, the app creates an instance of VZVirtualMachineConfiguration and adds video, virtual drives, and other devices to the system.
The Virtualization framework checks the configuration to make sure it supports saving and restoring.
Start the VM
After building the configuration data for the VM, the sample app uses the VZVirtualMachine object to start the execution of the macOS guest operating system.
Before calling the start(completionHandler:) or restoreMachineStateFrom(url:completionHandler:) methods, the sample app configures a delegate object to receive messages about the state of the virtual machine. When the macOS guest operating system shuts down, the virtual machine calls the delegate’s guestDidStop(_:) method. In response, the delegate method prints a message and exits the app. If the macOS guest stops for any reason other than a normal shutdown, the delegate prints an error message and the app exits.
Additionally, as part of the VM creation, the app also specifies macOS startup options that create a default user, including a default full name, password, whether this initial account automatically logs in, and whether the account is accessible remotely over the network using the Secure Shell protocol (SSH).
Listen for accessories and respond to connection changes
After successfully starting the VM, the app starts listening for USB accessories with the Accessory Access framework. As devices connect to or disconnect from the VM, the framework calls the usbAccessoryDidConnect(_:) and usbAccessoryDidDisconnect(_:) protocol methods to inform the app about these transitions.
If the virtual machine was running when the sample app last exited, the app calls restoreVirtualMachine to restore the state. If the virtual machine was in a shutdown state, the app calls startVirtualMachine to reboot the machine. Both methods start the VM asynchronously in the background. The VM loads the system image and boots macOS. After macOS starts, the user interacts with a VZVirtualMachineView window that displays the macOS UI and handles keyboard and mouse input through a VZMacGraphicsDeviceConfiguration as though the user is interacting directly with the Mac hardware. The VZVirtualMachineView automatically resizes the virtual machine display when the window size changes, and captures system keys such as the Globe key on a Mac keyboard.
The startVirtualMachine method calls the VM’s start(completionHandler:) method.
For a sendable wrapper that connects a VZVirtualMachineView to a virtual machine, see VZVirtualMachineViewAdaptor.
If the app previously had the VM save its state to SaveFile.vzvmsave, restoreVirtualMachine calls the VM’s restoreMachineStateFrom(url:completionHandler:) and resume(completionHandler:) methods.
If the restore fails, the framework causes the virtual machine to reboot. In either case, the framework deletes SaveFile.vzvmsave after restore completes because the VM disk no longer matches the state in the file.
Save the VM
When you close the sample app, it calls the VM’s pause(completionHandler:) and saveMachineStateTo(url:completionHandler:) methods. This captures the runtime state of the VM to SaveFile.vzvmsave, which the app uses when calling startOrRestoreVirtualMachine to resume running the VM at the same point when you relaunch the sample app.
The system defers app termination until the saveMachineStateTo(url:completionHandler:) method completes.