Sample CodemacOSReviewed 2026-11-01View on Apple Developer

Running macOS in a virtual machine on Apple silicon

At a glance

Item Summary
Purpose Install and run macOS in a virtual machine using the Virtualization framework.
App architecture Five targets in one Xcode project. A command-line InstallationTool creates a VM bundle in the home directory. A macOSVirtualMachineSampleApp boots, saves, and restores that VM, and passes host USB accessories through to it. Both exist in Swift and Objective-C. A Swift-only sharedBaseImageSampleApp boots two VMs over one read-only base disk, each with its own overlay.
Main patterns Delegate or data-source callbacks (VZVirtualMachineDelegate, AAUSBAccessoryListener, NSApplicationDelegate)
Project style Language folders (Swift/, Objective-C/), each with Common/, InstallationTool/, and macOSVirtualMachineSampleApp/. Configuration is built by a stateless helper type with static factory methods. File locations are global constants.
Execution model The app delegates hop to DispatchQueue.main.async at launch. USB callbacks are nonisolated and submit work to virtualMachine.queue. The installation tool parks the main thread in dispatchMain(). The shared-image app builds configurations in a Task.detached and starts the VMs in @MainActor methods.
State/event model Completion handlers chain VM lifecycle steps (restore → resume, pause → save). KVO observations (NSKeyValueObservation) log download and install progress. Delegate callbacks end the process when the guest stops.
Key frameworks/packages Virtualization, Cocoa, AccessoryAccess (behind #if canImport), DiskImageKit (shared-image app), Foundation. No package manifest.

Project structure

Source bundle/
├── macOSVirtualMachineSampleApp.xcodeproj/   5 targets: app + tool in each language, plus sharedBaseImageSampleApp
├── macOSVirtualMachineSampleApp.entitlements virtualization, USB accessory access, audio input
├── InstallationTool.entitlements
├── Swift/
│   ├── Common/                               compiled into every Swift target
│   │   ├── MacOSVirtualMachineConfigurationHelper.swift
│   │   ├── MacOSVirtualMachineDelegate.swift
│   │   └── Path.swift
│   ├── InstallationTool/
│   │   ├── main.swift
│   │   ├── MacOSRestoreImage.swift
│   │   └── MacOSVirtualMachineInstaller.swift
│   ├── macOSVirtualMachineSampleApp/
│   │   └── AppDelegate.swift
│   └── SharedBaseImageSampleApp/
│       ├── AppDelegate.swift
│       ├── SharedVMConfigurationHelper.swift
│       └── SharedPath.swift
└── Objective-C/                              same Common / InstallationTool / app split
    ├── Common/  (Error.h, Path.h, MacOSVirtualMachineConfigurationHelper.h/.m, MacOSVirtualMachineDelegate.h/.m)
    ├── InstallationTool/
    └── macOSVirtualMachineSampleApp/

Structure observations

  • Common/ is the shared layer. The sharedBaseImageSampleApp target compiles only Path.swift and MacOSVirtualMachineConfigurationHelper.swift from it, alongside its own synchronized folder (macOSVirtualMachineSampleApp.xcodeproj/project.pbxproj:532).
  • The two programs share state only through files. The tool writes HardwareModel, MachineIdentifier, AuxiliaryStorage, and Disk.img into ~/VM.bundle/, and the apps read them back. Path.swift names every file (Swift/Common/Path.swift:10).
  • The project targets macOS 27 (macOSVirtualMachineSampleApp.xcodeproj/project.pbxproj:611). The Swift VM code is fenced with #if arch(arm64), and the installation tool logs an error on other architectures (Swift/InstallationTool/main.swift:42).

Overall architecture

Reference code

Swift/macOSVirtualMachineSampleApp/AppDelegate.swift:62 — the app assembles its configuration from the shared helper

    private func createVirtualMachine() {
        let virtualMachineConfiguration = VZVirtualMachineConfiguration()

        virtualMachineConfiguration.platform = createMacPlaform()
        virtualMachineConfiguration.bootLoader = MacOSVirtualMachineConfigurationHelper.createBootLoader()
        // ...
        virtualMachineConfiguration.usbControllers = [MacOSVirtualMachineConfigurationHelper.createUSBControllerConfiguration()]

        try! virtualMachineConfiguration.validate()

        try! virtualMachineConfiguration.validateSaveRestoreSupport()

        virtualMachine = VZVirtualMachine(configuration: virtualMachineConfiguration)
    }

Interpretation

The tool and the apps are separate processes. They meet at the ~/VM.bundle files, not through calls. MacOSVirtualMachineConfigurationHelper is the only shared code dependency. It is a struct with only static functions that each return one framework configuration object (Swift/Common/MacOSVirtualMachineConfigurationHelper.swift:13). The installer, the app, and SharedVMConfigurationHelper (Swift/SharedBaseImageSampleApp/SharedVMConfigurationHelper.swift:23) each assemble a VZVirtualMachineConfiguration from those pieces. Each one adds only what differs: a newly created platform identity in the installer, a USB controller in the app, and a per-VM MAC address and overlay disk in the shared-image app.

Ownership and state

Ownership evidence

Swift/macOSVirtualMachineSampleApp/AppDelegate.swift:22 — the app delegate stores the VM, its delegate object, and the attached USB devices

@main
class AppDelegate: NSObject, NSApplicationDelegate, AAUSBAccessoryListener {

    @IBOutlet var window: NSWindow!

    @IBOutlet weak var virtualMachineView: VZVirtualMachineView!

    private var virtualMachineResponder: MacOSVirtualMachineDelegate?

    private var virtualMachine: VZVirtualMachine!

    private var accessories: [UInt64: VZUSBPassthroughDevice] = [:]
    // ...
}

Swift/macOSVirtualMachineSampleApp/AppDelegate.swift:184 — the delegate object and the view are wired after creation

            virtualMachineResponder = MacOSVirtualMachineDelegate()
            virtualMachine.delegate = virtualMachineResponder
            virtualMachineView.virtualMachine = virtualMachine
Owner Object or state Relationship Mutation authority
AppDelegate (app) VZVirtualMachine Created in createVirtualMachine() and kept in a private property for the app’s lifetime AppDelegate; start, resume, pause, save, and restore all go through it
AppDelegate (app) MacOSVirtualMachineDelegate Created and retained in virtualMachineResponder, then assigned to virtualMachine.delegate. Inference: the separate property keeps the object alive because the VM does not retain its delegate Stateless; it calls exit when the guest stops (Swift/Common/MacOSVirtualMachineDelegate.swift:14)
AppDelegate (app) accessories keyed by registryID private dictionary written in attach and detach completion handlers AppDelegate, inside virtualMachine.queue work items
AppDelegate (app) VZVirtualMachineView weak outlet from MainMenu.xib; the window hierarchy owns the view Interface Builder
MacOSVirtualMachineInstaller VZVirtualMachine, delegate, installationObserver All private. Inference: the KVO token is stored so that progress logging outlives startInstallation (Swift/InstallationTool/MacOSVirtualMachineInstaller.swift:129) The installer
MacOSRestoreImage downloadObserver private KVO token for download progress (Swift/InstallationTool/MacOSRestoreImage.swift:46) MacOSRestoreImage
AppDelegate (shared image) virtualMachines, delegates, windows Parallel private arrays, filled once per VM index (Swift/SharedBaseImageSampleApp/AppDelegate.swift:58) startVMs(with:)

Concurrency, scheduling, and thread safety

Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.

Concern Source mechanism Verified placement or handoff Evidence
Main-queue scheduling DispatchQueue.main.async applicationDidFinishLaunching defers VM creation, delegate wiring, and start or restore to a later main-queue work item. Swift/macOSVirtualMachineSampleApp/AppDelegate.swift:182
Main-queue scheduling DispatchQueue.main.async The installer builds the VM and starts VZMacOSInstaller on the main queue, after the restore-image completion handler runs. Swift/InstallationTool/MacOSVirtualMachineInstaller.swift:49
Run-loop liveness dispatchMain() The command-line tool parks the main thread so that queued work and completion handlers can run. Swift/InstallationTool/main.swift:24
VM-queue scheduling virtualMachine.queue.async Both USB listener callbacks are nonisolated. They submit work to the VM’s queue, check state, then attach or detach. Weak captures avoid retaining the delegate from the work item. Swift/macOSVirtualMachineSampleApp/AppDelegate.swift:119
Shared-state safety VM queue plus completion handlers accessories is read inside the VM-queue work item and written in attach and detach completion handlers. The source does not name the queue those completion handlers run on, so it does not prove a single serial owner for the dictionary. Swift/macOSVirtualMachineSampleApp/AppDelegate.swift:135
Task creation Plain Task {} startListeningForUSBAccessories() creates an unstored task that awaits registerListener and replays already-connected accessories. It runs after every start and every resume, and nothing cancels it. Swift/macOSVirtualMachineSampleApp/AppDelegate.swift:90
Task execution Task { @MainActor in } and Task.detached The shared-image app starts on the main actor. It builds the two configurations, which open disk images, in a detached task, awaits .value, and then starts the VMs in a @MainActor method. Swift/SharedBaseImageSampleApp/AppDelegate.swift:91
Main-actor isolation @MainActor startVMs, createAllConfigurations, and promptOverlayReset (an NSAlert) are explicitly main-actor isolated. Swift/SharedBaseImageSampleApp/AppDelegate.swift:32
Blocking work Process.run plus waitUntilExit() The installer creates the ASIF disk by running diskutil and blocking until it exits, inside the main-queue setup path. Swift/InstallationTool/MacOSVirtualMachineInstaller.swift:160

Inference: the app’s AppDelegate conforms to NSApplicationDelegate, a main-actor protocol in current AppKit, so its unmarked members are main-actor isolated. That explains why the USB callbacks are explicitly nonisolated. The Objective-C variant uses the same hand-off with dispatch_async(_virtualMachine.queue, ...) (Objective-C/macOSVirtualMachineSampleApp/AppDelegate.m:131).

Reference code

Swift/macOSVirtualMachineSampleApp/AppDelegate.swift:118 — a framework callback crosses onto the VM’s queue before touching the VM

    nonisolated func usbAccessoryDidConnect(_ usbAccessory: AAUSBAccessory) {
        virtualMachine.queue.async { [weak self] in
            guard let self else {
                return
            }

            if self.virtualMachine.state != .running && self.virtualMachine.state != .paused {
                return
            }

            let configuration = VZUSBPassthroughDeviceConfiguration(device: usbAccessory)
            do {
                let usbDevice = try VZUSBPassthroughDevice(configuration: configuration)
                self.virtualMachine.usbControllers.first!.attach(device: usbDevice) { [weak self] error in
                    guard let self else {
                        return
                    }
                    self.accessories[usbAccessory.registryID] = usbDevice
                }
            } catch {
                return
            }
        }
    }

Swift/SharedBaseImageSampleApp/AppDelegate.swift:90 — configuration building leaves the caller’s actor in a detached task

    private func buildConfigurations() async throws -> [VZVirtualMachineConfiguration] {
        try await Task.detached {
            try (1...Self.vmCount).map {
                try SharedVMConfigurationHelper.createVirtualMachineConfiguration(vmIndex: $0)
            }
        }.value
    }

State propagation, frameworks, and dependencies

Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.

Category Mechanism or module Verified role Evidence
State propagation Completion-handler chain Restore deletes the save file, then resumes on success or cold-starts on failure. Start and resume both register for USB accessories in their handlers. Swift/macOSVirtualMachineSampleApp/AppDelegate.swift:166
State propagation KVO (observe(\.fractionCompleted)) Download and installation progress are logged from Progress observations. Swift/InstallationTool/MacOSVirtualMachineInstaller.swift:129
State propagation Delegate callback MacOSVirtualMachineDelegate turns guest stop or error into process exit. Swift/Common/MacOSVirtualMachineDelegate.swift:17
State propagation File system The tool writes the hardware model and machine identifier, which the app reads on every launch. Swift/InstallationTool/MacOSVirtualMachineInstaller.swift:71
Termination .terminateLater Quitting while running pauses and saves the VM, then replies to NSApplication. Swift/macOSVirtualMachineSampleApp/AppDelegate.swift:237
Framework import Virtualization Compilation dependency of every VM file. Swift/Common/MacOSVirtualMachineConfigurationHelper.swift:9
Framework import AccessoryAccess Imported only when available. It provides AAUSBAccessoryListener and AAUSBAccessoryManager. Swift/macOSVirtualMachineSampleApp/AppDelegate.swift:9
Framework import DiskImageKit Shared-image app only. It provides DiskImage, StackedImage, and the ASIF overlay layer. Swift/SharedBaseImageSampleApp/SharedVMConfigurationHelper.swift:11
Framework import Cocoa App delegates and windows. Swift/macOSVirtualMachineSampleApp/AppDelegate.swift:11
Entitlement com.apple.developer.accessory-access.usb Declared beside com.apple.security.virtualization in the entitlements file that the three app targets use. macOSVirtualMachineSampleApp.entitlements:5

Class and protocol design

Reference code

Swift/Common/MacOSVirtualMachineConfigurationHelper.swift:104 — static factories, including the new guest-provisioning start options

struct MacOSVirtualMachineConfigurationHelper {
    // ...
    static func createUSBControllerConfiguration() -> VZUSBControllerConfiguration {
        return VZXHCIControllerConfiguration()
    }

    static func createMacOSStartOptions() -> VZMacOSVirtualMachineStartOptions {
        let guestOptions = VZMacGuestProvisioningOptions()
        guestOptions.fullName = "Admin User"
        guestOptions.username = "admin"
        guestOptions.password = "password123!"
        guestOptions.logsInAutomatically = true
        guestOptions.enablesRemoteLogin = true

        let startOptions = VZMacOSVirtualMachineStartOptions()
        try! startOptions.setGuestProvisioning(guestOptions)

        return startOptions
    }
}
Type Responsibility Depends on
MacOSVirtualMachineConfigurationHelper Static factories for CPU, memory, boot loader, devices, USB controller, hardware model, and start options Virtualization, Path.swift constants
MacOSVirtualMachineInstaller Creates the bundle and disk, builds the install-time platform, and runs VZMacOSInstaller Helper, MacOSVirtualMachineDelegate
MacOSRestoreImage Fetches the latest supported restore image and downloads it VZMacOSRestoreImage, URLSession
MacOSVirtualMachineDelegate Ends the process when the guest stops or fails VZVirtualMachineDelegate
AppDelegate (app) Owns the VM lifecycle, save and restore, and USB passthrough Helper, AAUSBAccessoryManager
SharedVMConfigurationHelper Per-VM identity, NAT MAC address, and base-plus-overlay disk Helper, DiskImageKit
AppDelegate (shared image) Builds two configurations, recovers from incompatible overlays, and opens one window per VM SharedVMConfigurationHelper, SharedVirtualMachineDelegate

No local protocol is declared. Every conformance is to a framework protocol.

Access control

Symbol Access Verified effect Likely rationale
AppDelegate.virtualMachine, virtualMachineResponder, accessories (Swift/macOSVirtualMachineSampleApp/AppDelegate.swift:24) private Only AppDelegate can replace the VM or edit the passthrough map. Inference: VM lifecycle transitions stay inside one type.
createMacPlaform(), createVirtualMachine() (Swift/macOSVirtualMachineSampleApp/AppDelegate.swift:31) private Construction is not callable from other files. Inference: the VM is built exactly once, at launch.
startVirtualMachine(), resumeVirtualMachine(), restoreVirtualMachine() implicit internal Visible across the app module, though only AppDelegate calls them. No source-stated rationale.
MacOSRestoreImage.download(completionHandler:) (Swift/InstallationTool/MacOSRestoreImage.swift:18) public on an internal class The class is internal, so in this executable target the effective visibility is still module-wide. Inference: marks the type’s intended entry point.
MacOSVirtualMachineInstaller.setUpVirtualMachineArtifacts(), installMacOS(ipswURL:) (Swift/InstallationTool/MacOSVirtualMachineInstaller.swift:19) public on an internal class Same effective module visibility; every helper step is private. Inference: a two-call surface for main.swift.
SharedVMConfigurationHelper.createMacPlatform, createNetworkDeviceConfiguration (Swift/SharedBaseImageSampleApp/SharedVMConfigurationHelper.swift:42) private static Only createVirtualMachineConfiguration(vmIndex:) can build per-VM identity and network. Inference: per-VM invariants are applied in one assembly function.
virtualMachineView, window (Objective-C/macOSVirtualMachineSampleApp/AppDelegate.m:19) class extension in .m Outlets are hidden from the public header, which declares only the protocol conformances. Inference: keep IB wiring private to the implementation.

Reference code

Swift/InstallationTool/MacOSVirtualMachineInstaller.swift:13 — private state behind two public entry points

class MacOSVirtualMachineInstaller: NSObject {
    private var installationObserver: NSKeyValueObservation?
    private var virtualMachine: VZVirtualMachine!
    private var virtualMachineResponder: MacOSVirtualMachineDelegate?

    // Create a bundle on the user's Home directory to store any artifacts
    // that the installation produces.
    public func setUpVirtualMachineArtifacts() {
        createVMBundle()
    }
    // ...
}

Logic ownership and placement

Logic Owning type or file Placement rationale
Device and resource configuration MacOSVirtualMachineConfigurationHelper One stateless place that the installer, the app, and the shared-image app all reuse.
Hardware-model loading and validation MacOSVirtualMachineConfigurationHelper.readHardwareModel (Swift/Common/MacOSVirtualMachineConfigurationHelper.swift:38) Shared by the app and the shared-image helper; ends the process if the host cannot run the model.
Platform identity creation and persistence MacOSVirtualMachineInstaller.createMacPlatformConfiguration Only the installer creates a new machine identifier and auxiliary storage.
Disk image creation MacOSVirtualMachineInstaller.createDiskImage → createASIFDiskImage (Swift/InstallationTool/MacOSVirtualMachineInstaller.swift:188) Calls diskutil. A RAW-image function remains in the file but is not called.
VM lifecycle, save and restore, termination App AppDelegate Lifecycle hooks (applicationDidFinishLaunching, applicationShouldTerminate) map directly to VM start and save.
USB passthrough App AppDelegate The listener, the passthrough map, and the VM sit in one type.
Base and overlay stacking, overlay reset SharedVMConfigurationHelper (Swift/SharedBaseImageSampleApp/SharedVMConfigurationHelper.swift:83) Opens the base image read-only and appends an existing or new ASIF overlay for each VM.
Overlay-incompatibility recovery UI Shared-image AppDelegate.createAllConfigurations Catches IncompatibleStackingError, asks with an NSAlert, discards the overlays, and retries once.

Design patterns

Pattern Source evidence Purpose or tradeoff
Delegate or data-source callbacks Swift/Common/MacOSVirtualMachineDelegate.swift:11 (VZVirtualMachineDelegate); Swift/macOSVirtualMachineSampleApp/AppDelegate.swift:16 (AAUSBAccessoryListener) The framework reports guest stops and USB connect or disconnect events back to sample-owned objects. The VM delegate is a separate small object; the USB listener is the app delegate itself.

The static-function helper is a set of construction functions, not a polymorphic Factory: every method returns one concrete configuration and has no substitution point.

Main application flow

The flow below covers one app launch with no save file. It runs from main-queue setup to USB passthrough.

Reference code

Swift/macOSVirtualMachineSampleApp/AppDelegate.swift:182 — launch defers setup to the main queue

        DispatchQueue.main.async { [self] in
            createVirtualMachine()
            // ...
            if fileManager.fileExists(atPath: saveFileURL.path) {
                restoreVirtualMachine()
            } else {
                startVirtualMachine()
            }
        }

Swift/macOSVirtualMachineSampleApp/AppDelegate.swift:148 — the start completion handler begins USB listening

    func startVirtualMachine() {
        let startOptions = MacOSVirtualMachineConfigurationHelper.createMacOSStartOptions()
        virtualMachine.start(options: startOptions, completionHandler: { error in
            if let error {
                fatalError("Virtual machine failed to start with \(error)")
            }
            self.startListeningForUSBAccessories()
        })
    }

Swift/macOSVirtualMachineSampleApp/AppDelegate.swift:92 — an unstructured task registers the listener and replays connected devices

    func startListeningForUSBAccessories() {
        Task {
            do {
                let connectedAccessories = try await AAUSBAccessoryManager.shared.registerListener(self, matchingCriteria: [])
                for accessory in connectedAccessories {
                    usbAccessoryDidConnect(accessory)
                }
            } catch {
                fatalError("Failed to register USB accessory listener. \(error)")
            }
        }
    }

Swift/macOSVirtualMachineSampleApp/AppDelegate.swift:131 — the connect callback attaches the device from the VM queue

    nonisolated func usbAccessoryDidConnect(_ usbAccessory: AAUSBAccessory) {
        virtualMachine.queue.async { [weak self] in
            // ...
            let configuration = VZUSBPassthroughDeviceConfiguration(device: usbAccessory)
            do {
                let usbDevice = try VZUSBPassthroughDevice(configuration: configuration)
                self.virtualMachine.usbControllers.first!.attach(device: usbDevice) { [weak self] error in
                    // ...
                    self.accessories[usbAccessory.registryID] = usbDevice
                }
            } catch {
                return
            }
        }
    }

Naming conventions

  • Types: framework-prefixed role names (MacOSVirtualMachineInstaller, MacOSRestoreImage, MacOSVirtualMachineConfigurationHelper). The Shared… prefix marks the shared-base-image target (SharedVMConfigurationHelper, SharedVirtualMachineDelegate).
  • Delegate objects: MacOSVirtualMachineDelegate is the conforming type, and the property that holds it is virtualMachineResponder.
  • Methods: create… for factories (createBootLoader, createMacOSStartOptions), compute… for derived limits (computeCPUCount, computeMemorySize), read… for disk-backed loads (readHardwareModel), and lifecycle verbs on the delegate (startVirtualMachine, pauseAndSaveVirtualMachine). The source spells one factory createMacPlaform (Swift/macOSVirtualMachineSampleApp/AppDelegate.swift:31).
  • Files: one primary type per file. Path constants live in Path.swift, and per-VM path functions in SharedPath.swift.

Architecture takeaways

  • Splitting install and run into separate executables keeps the long, one-time setup out of the app. The file bundle is the only contract between them, so the format of each file is the interface.
  • A stateless configuration helper lets three different assemblies share device setup while each adds only its own difference.
  • The owner of a long-lived framework object also holds its delegate in a stored property, because the framework does not keep the delegate alive.
  • Framework callbacks that arrive off the main actor are marked nonisolated and moved explicitly to the VM’s own queue before they touch the VM.
  • The shared-image app keeps blocking disk-image work off the main actor with Task.detached, and keeps UI and VM start on the main actor. Recovery from a stale overlay is a single typed-error branch with one retry.

Source map

Source file Relevant symbols
Swift/macOSVirtualMachineSampleApp/AppDelegate.swift AppDelegate, createVirtualMachine, startListeningForUSBAccessories, usbAccessoryDidConnect, startVirtualMachine, restoreVirtualMachine, applicationShouldTerminate
Swift/Common/MacOSVirtualMachineConfigurationHelper.swift MacOSVirtualMachineConfigurationHelper, readHardwareModel, createUSBControllerConfiguration, createMacOSStartOptions
Swift/Common/MacOSVirtualMachineDelegate.swift MacOSVirtualMachineDelegate
Swift/Common/Path.swift vmBundlePath, saveFileURL and other file URLs
Swift/InstallationTool/main.swift Tool entry, dispatchMain()
Swift/InstallationTool/MacOSVirtualMachineInstaller.swift MacOSVirtualMachineInstaller, setupVirtualMachine, startInstallation, createASIFDiskImage
Swift/InstallationTool/MacOSRestoreImage.swift MacOSRestoreImage, download, downloadRestoreImage
Swift/SharedBaseImageSampleApp/AppDelegate.swift AppDelegate, startVMs, createAllConfigurations, buildConfigurations, SharedVirtualMachineDelegate
Swift/SharedBaseImageSampleApp/SharedVMConfigurationHelper.swift SharedVMConfigurationHelper, createBlockDeviceConfiguration, discardOverlay
Objective-C/macOSVirtualMachineSampleApp/AppDelegate.m AppDelegate, usbAccessoryDidConnect:
macOSVirtualMachineSampleApp.xcodeproj/project.pbxproj Targets, shared-image sources, deployment target
macOSVirtualMachineSampleApp.entitlements Virtualization and USB accessory entitlements