Help us shape the future of Go! Take the 2026 Go Developer Survey

vz

package module
v4.0.0-...-17c6ceb Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 28 Imported by: 0

README

vz - Go binding with Apple Virtualization.framework

Build Go Reference

vz provides the power of the Apple Virtualization.framework in Go. Put here is block quote of overreview which is written what is Virtualization.framework from the document.

The Virtualization framework provides high-level APIs for creating and managing virtual machines (VM) on Apple silicon and Intel-based Mac computers. Use this framework to boot and run macOS or Linux-based operating systems in custom environments that you define. The framework supports the Virtual I/O Device (VIRTIO) specification, which defines standard interfaces for many device types, including network, socket, serial port, storage, entropy, and memory-balloon devices.

Usage

Please see the example directory.

Requirements

  • macOS Monterey (12.0) or later.
  • Go 1.25 or later.
  • Xcode or Command Line Tools, with CGO_ENABLED=1.

A normal go build compiles the Objective-C helpers and links Apple's frameworks. The Go bindings use purego for API calls. Consumers do not need Swift, prebuilt bridge binaries, or a generation step. go mod vendor builds from the same sources.

Installation

Initialize your project by creating a folder and then running go mod init github.com/your/repo (learn more) inside the folder. Then install vz with the go get command:

$ go get github.com/Code-Hex/vz/v4

Deprecated older versions (v1, v2).

Feature Overview

  • ✅ Virtualize Linux on a Mac (x86_64, arm64)
    • GUI Support
    • Boot Extensible Firmware Interface (EFI) ROM
    • Clipboard sharing through the SPICE agent
  • ✅ Virtualize macOS on Apple Silicon Macs (arm64)
    • Fetches the latest restore image supported by this host from the network
    • Start in recovery mode
  • ✅ Running Intel Binaries in Linux VMs with Rosetta (arm64)
  • ✅ Shared Directories
  • ✅ Virtio Sockets

Important

For binaries used in this package, you need to create an entitlements file like the one below and apply the following command.

vz.entitlements
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>com.apple.security.virtualization</key>
	<true/>
</dict>
</plist>
$ codesign --entitlements vz.entitlements -s - <YOUR BINARY PATH>

A process must have the com.apple.security.virtualization entitlement to use the Virtualization APIs.

If you want to use VZBridgedNetworkDeviceAttachment, you need to add also com.apple.vm.networking entitlement.

Build SDK

API availability depends on both the running macOS version and the build SDK. A binary built with an older SDK can return ErrBuildTargetOSVersion for newer APIs. Build with an SDK that includes the APIs you need.

Version compatibility check

The package provides a mechanism for checking the availability of the respective API through error handling:

bootLoader, err := vz.NewEFIBootLoader()
if errors.Is(err, vz.ErrUnsupportedOSVersion) || errors.Is(err, vz.ErrBuildTargetOSVersion) {
  return fallbackBootLoader()
}
if err != nil {
  return nil, err
}
return bootLoader, nil

There are two items to check.

  1. API is compatible with the version of macOS
  2. The binary was built with the API enabled

Knowledge for the Apple Virtualization.framework

There is a lot of knowledge required to use this Apple Virtualization.framework, but the information is too scattered and very difficult to understand. In most cases, this can be found in the official documentation. However, the Linux kernel knowledge required to use the feature provided by this framework is not documented. Therefore, I have compiled the knowledge I have gathered so far into this wiki.

https://github.com/Code-Hex/vz/wiki

Anyone is free to edit this wiki. It would help someone if you could add information not listed here. Let's make a good wiki together!

Testing

If you want to contribute some code, you will need to add tests.

PUI PUI Linux is used to test this library. This Linux is designed to provide only the minimum functionality required for the Apple Virtualization.framework (Virtio), so the kernel file size is very small.

The test code uses the Makefile in the project root.

$ # Download PUI PUI Linux, Only required the first time.
$ make download_kernel
$ make test

The public Go API wraps bindings generated from SDK types, ownership attributes, and availability declarations. To regenerate bindings with your installed SDK and Virtualization runtime, run:

go generate ./internal/vzbridge
go test ./cmd/vzbridgegen ./internal/vzbridge/nativegen
make test/graphics

The generator discovers all methods in the Virtualization runtime image, including private methods. Unsupported signatures remain listed with reasons in the generated Go files. For detailed compiler and runtime facts, pass -report /tmp/vzbridge.json to go run ./cmd/vzbridgegen. Reports are not generation inputs.

Private bindings are internal and unsafe. Runtime encodings do not describe ownership or variadic arguments. Callers must establish those contracts. The runtime scan describes the generating host, and every private call checks its receiver and ABI before dispatch. Regenerate on another host to discover methods specific to that host. Unused bindings have no startup registration.

Which projects use this library?

  • vfkit is a macOS command-line hypervisor for Apple and Intel CPUs that supports most of Apple's Virtualization Framework features.
  • Lima launches Linux virtual machines with automatic file sharing and port forwarding (similar to WSL2).
  • linuxkit is a toolkit for building custom minimal, immutable Linux distributions.

LICENSE

MIT License

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnsupportedOSVersion is returned when calling a method which is only
	// available in newer macOS versions.
	ErrUnsupportedOSVersion = macos.ErrUnsupportedOSVersion

	// ErrBuildTargetOSVersion indicates that the API is available but the
	// running program has disabled it.
	ErrBuildTargetOSVersion = macos.ErrBuildTargetOSVersion
)

Functions

func CanonicalizeDirectoryShareName

func CanonicalizeDirectoryShareName(name string) (string, error)

CanonicalizeDirectoryShareName applies Apple's directory share name conversion. It removes *, /, :, <, >, ?, \, and |, and discards the first NUL byte and everything after it. It returns an error if name contains invalid UTF-8, or if the filtered name is empty, is "." or "..", or exceeds 255 UTF-8 bytes.

After these checks, it removes one leading byte order mark (U+FEFF), matching Apple's string conversion. This can leave an empty name, ".", or "..". NewMultipleDirectoryShare rejects those results. Other characters, including whitespace and combining characters, are preserved. Different inputs can produce the same name; callers must handle collisions before adding names to a share map.

This function runs entirely in Go and does not require macOS 12.

see: https://developer.apple.com/documentation/virtualization/vzmultipledirectoryshare/canonicalizedname(from:)?language=objc

func CreateDiskImage

func CreateDiskImage(pathname string, size int64) error

CreateDiskImage is creating disk image with specified filename and filesize. For example, if you want to create disk with 64GiB, you can set "64 * 1024 * 1024 * 1024" to size.

Note that if you have specified a pathname which already exists, this function returns os.ErrExist error. So you can handle it with os.IsExist function.

func CreateSparseDiskImage

func CreateSparseDiskImage(ctx context.Context, pathname string, size int64) error

CreateSparseDiskImage is creating an "Apple Sparse Image Format" disk image with specified filename and filesize. The function "shells out" to diskutil, as currently this is the only known way of creating ASIF images. For example, if you want to create disk with 64GiB, you can set "64 * 1024 * 1024 * 1024" to size.

Note that ASIF is only available from macOS Tahoe, so the function will return error on earlier versions.

func IsNestedVirtualizationSupported

func IsNestedVirtualizationSupported() bool

IsNestedVirtualizationSupported reports if nested virtualization is supported.

func IsSupported

func IsSupported() bool

IsSupported reports whether the host supports hardware virtualization. It returns false on macOS versions older than 11.

func MacOSGuestAutomountTag

func MacOSGuestAutomountTag() (string, error)

MacOSGuestAutomountTag returns the macOS automount tag.

A device configured with this tag will be automatically mounted in a macOS guest. This is only supported on macOS 13 and newer, error will be returned on older versions.

func MaximumAllowedVirtioSharedMemoryRegionCount

func MaximumAllowedVirtioSharedMemoryRegionCount() (uint, error)

MaximumAllowedVirtioSharedMemoryRegionCount returns the framework's region limit.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodeviceconfiguration/maximumallowedsharedmemoryregioncount?language=objc

func SpiceAgentPortAttachmentName

func SpiceAgentPortAttachmentName() (string, error)

SpiceAgentPortAttachmentName returns the Spice agent port name.

func StartGraphicApplication

func StartGraphicApplication(w *GraphicWindow, windows ...*GraphicWindow) error

StartGraphicApplication opens one or more VM windows. Closing a window does not stop its VM. A stopped VM closes its own window.

The first call must run on the main goroutine after runtime.LockOSThread in init. It runs the event loop and returns when all windows close. While the event loop is running, calls from any goroutine add windows and return once they are displayed. A VM can have only one open window. Calls made while the application is shutting down return an error. After the event loop exits, a new application must start on the main thread. This is supported on macOS 12 and newer.

func VirtualMachineConfigurationMaximumAllowedCPUCount

func VirtualMachineConfigurationMaximumAllowedCPUCount() uint

VirtualMachineConfigurationMaximumAllowedCPUCount returns maximum number of CPUs for a virtual machine.

func VirtualMachineConfigurationMaximumAllowedMemorySize

func VirtualMachineConfigurationMaximumAllowedMemorySize() uint64

VirtualMachineConfigurationMaximumAllowedMemorySize returns maximum amount of memory allowed for a virtual machine.

func VirtualMachineConfigurationMinimumAllowedCPUCount

func VirtualMachineConfigurationMinimumAllowedCPUCount() uint

VirtualMachineConfigurationMinimumAllowedCPUCount returns minimum number of CPUs for a virtual machine.

func VirtualMachineConfigurationMinimumAllowedMemorySize

func VirtualMachineConfigurationMinimumAllowedMemorySize() uint64

VirtualMachineConfigurationMinimumAllowedMemorySize returns minimum amount of memory required by virtual machines.

Types

type BootLoader

type BootLoader interface {
	objc.NSObject
	// contains filtered or unexported methods
}

BootLoader is the interface of boot loader definitions.

type BridgedNetwork

type BridgedNetwork interface {
	objc.NSObject

	// NetworkInterfaces returns the list of network interfaces available for bridging.
	NetworkInterfaces() []BridgedNetwork

	// Identifier returns the unique identifier for this interface.
	// The identifier is the BSD name associated with the interface (e.g. "en0").
	Identifier() string

	// LocalizedDisplayName returns a display name if available (e.g. "Ethernet").
	LocalizedDisplayName() string
}

BridgedNetwork defines a network interface that bridges a physical interface with a virtual machine.

A bridged interface is shared between the virtual machine and the host system. Both host and virtual machine send and receive packets on the same physical interface but have distinct network layers.

The BridgedNetwork can be used with a BridgedNetworkDeviceAttachment to set up a network device NetworkDeviceConfiguration. see: https://developer.apple.com/documentation/virtualization/vzbridgednetworkinterface?language=objc

func NetworkInterfaces

func NetworkInterfaces() []BridgedNetwork

NewBridgedNetwork creates a new BridgedNetwork with identifier.

This is only supported on macOS 11 and newer, error will be returned on older versions.

type BridgedNetworkDeviceAttachment

type BridgedNetworkDeviceAttachment struct {
	// contains filtered or unexported fields
}

BridgedNetworkDeviceAttachment represents a physical interface on the host computer.

Use this struct when configuring a network interface for your virtual machine. A bridged network device sends and receives packets on the same physical interface as the host computer, but does so using a different network layer.

To use this attachment, your app must have the com.apple.vm.networking entitlement. If it doesn’t, the use of this attachment point results in an invalid VZVirtualMachineConfiguration object in objective-c.

see: https://developer.apple.com/documentation/virtualization/vzbridgednetworkdeviceattachment?language=objc

func NewBridgedNetworkDeviceAttachment

func NewBridgedNetworkDeviceAttachment(networkInterface BridgedNetwork) (*BridgedNetworkDeviceAttachment, error)

NewBridgedNetworkDeviceAttachment creates a new BridgedNetworkDeviceAttachment with networkInterface.

This is only supported on macOS 11 and newer, error will be returned on older versions.

func (*BridgedNetworkDeviceAttachment) String

type ConsoleDeviceConfiguration

type ConsoleDeviceConfiguration interface {
	objc.NSObject
	// contains filtered or unexported methods
}

ConsoleDeviceConfiguration interface for an console device configuration.

type ConsolePortConfiguration

type ConsolePortConfiguration interface {
	objc.NSObject
	// contains filtered or unexported methods
}

type ConsolePortEvent

type ConsolePortEvent struct {
	// DeviceIndex identifies the console device in VirtualMachine.ConsoleDevices.
	DeviceIndex int
	// PortIndex is the key in VirtioConsoleDevice.Ports.
	PortIndex uint32
	// Open reports whether the guest opened or closed the port.
	Open bool
}

ConsolePortEvent reports a guest opening or closing a console port.

type CustomVirtioContext

type CustomVirtioContext interface {
	context.Context

	// RunOnDeviceQueue runs fn on the device's serial queue, waits for fn to
	// return, and returns its error unchanged. Calls from the same queue run
	// fn directly, so fn may call other device and queue methods.
	//
	// Delegate callbacks already run on this queue, and individual device and
	// queue methods dispatch to it as well. Use RunOnDeviceQueue to group your
	// own state checks with those operations.
	//
	// A backend worker can use RunOnDeviceQueue to finish a request after
	// doing blocking I/O outside the queue. It can check whether the request is
	// still valid, write the response, and return the queue element in one call.
	// Lifecycle callbacks cannot run between those steps.
	//
	// For example, a delegate can keep per-device fields d.generation and
	// d.stopped, accessed only on the device queue. WillReset increments
	// d.generation, and WillStop sets d.stopped. The notification callback
	// records requestGeneration from d.generation when it dequeues element,
	// before passing the request to a worker. After preparing response, the
	// worker's completion function can return:
	//
	//	return ctx.RunOnDeviceQueue(func() error {
	//		if d.stopped || d.generation != requestGeneration {
	//			return nil
	//		}
	//		if err := element.WriteBytes(response); err != nil {
	//			return err
	//		}
	//		return element.ReturnToQueue()
	//	})
	//
	// This discards a result if the delegate has observed a stop or reset.
	// Serializing host operations does not prevent the guest from changing
	// its memory while fn runs.
	//
	// fn must not wait for a worker or completion handler that needs this
	// queue. That would deadlock. RunOnDeviceQueue waits only for fn, not for
	// asynchronous operations started by fn. Configuration updates and shared
	// memory mappings complete on the device queue, so any wait for their
	// completion must happen after RunOnDeviceQueue returns, outside the queue.
	//
	// RunOnDeviceQueue calls fn even after parent cancellation, allowing
	// cleanup to run. The caller decides whether to check Err inside fn.
	//
	// see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodevicedelegateprovider/devicequeue?language=objc
	RunOnDeviceQueue(fn func() error) error
}

CustomVirtioContext gives a delegate access to its parent context and the device's serial queue. A delegate may retain it for work that finishes after a callback returns. Retaining the context also keeps the native device alive, but does not extend the lifetime of guest memory or queue elements.

Deadline, Done, Err, and Value forward to the context supplied through WithCustomVirtioContext, or context.Background if that option is omitted. Device lifecycle events and provider closure do not cancel the parent. Parent cancellation does not stop the virtual machine or close the provider.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodevicedelegateprovider/devicequeue?language=objc

type CustomVirtioDevice

type CustomVirtioDevice struct {
	// contains filtered or unexported fields
}

CustomVirtioDevice is a running custom Virtio device supplied to its delegate. Callbacks may receive different Go wrappers for the same device. Use ID to identify the device across callbacks instead of comparing wrapper pointers.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodevice?language=objc

func (*CustomVirtioDevice) GuestMemoryMapping

func (d *CustomVirtioDevice) GuestMemoryMapping(physicalAddress, length uint64) *GuestMemoryMapping

GuestMemoryMapping returns a mapping of guest RAM, or nil for an invalid range. The mapping must not be used after the virtual machine reboots or shuts down.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodevice/guestmemorymapping(atphysicaladdress:length:)?language=objc

func (*CustomVirtioDevice) ID

func (d *CustomVirtioDevice) ID() uint64

ID returns a process-local identifier for this device instance. It stays the same across callbacks for the device's lifetime and differs from the ID of any other instance, including devices that share a delegate. It is not the Virtio device type ID passed to NewCustomVirtioDeviceConfiguration and must not be saved as an identifier for a restored virtual machine.

func (*CustomVirtioDevice) NegotiatedFeatures

func (d *CustomVirtioDevice) NegotiatedFeatures() *VirtioFeatureSet

NegotiatedFeatures returns the features accepted by the guest, or nil before DRIVER_OK.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodevice/negotiatedfeatures?language=objc

func (*CustomVirtioDevice) QueueAtIndex

func (d *CustomVirtioDevice) QueueAtIndex(index uint16) *VirtioQueue

QueueAtIndex returns a queue after DRIVER_OK, or nil if disabled or out of range.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodevice/queue(at:)?language=objc

func (*CustomVirtioDevice) RequestDeviceReset

func (d *CustomVirtioDevice) RequestDeviceReset()

RequestDeviceReset asks the guest to reset this device. The guest may ignore it.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodevice/requestreset()?language=objc

func (*CustomVirtioDevice) SharedMemoryRegions

func (d *CustomVirtioDevice) SharedMemoryRegions() []*VirtioSharedMemoryRegion

SharedMemoryRegions returns the regions configured for the device.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodevice/sharedmemoryregions?language=objc

func (*CustomVirtioDevice) UpdateDeviceSpecificConfiguration

func (d *CustomVirtioDevice) UpdateDeviceSpecificConfiguration(configuration *VirtioDeviceSpecificConfiguration, completion func(error)) error

UpdateDeviceSpecificConfiguration updates the device configuration asynchronously. The new configuration must have the same byte length as the original. completion runs on the device queue and must not block it.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodevice/update(_:completionhandler:)?language=objc

type CustomVirtioDeviceConfiguration

type CustomVirtioDeviceConfiguration struct {
	// contains filtered or unexported fields
}

CustomVirtioDeviceConfiguration describes a device implemented by a custom provider. It requires macOS 27 or newer.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodeviceconfiguration?language=objc

func NewCustomVirtioDeviceConfiguration

func NewCustomVirtioDeviceConfiguration(deviceID uint16, pciClassID, pciSubclassID uint8, queueCount uint16, options ...CustomVirtioDeviceConfigurationOption) (*CustomVirtioDeviceConfiguration, error)

NewCustomVirtioDeviceConfiguration creates a custom Virtio device configuration. The IDs identify the device to the guest. queueCount specifies its virtqueues.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodeviceconfiguration?language=objc

func (*CustomVirtioDeviceConfiguration) DeviceID

DeviceID returns the Virtio device ID.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodeviceconfiguration/deviceid?language=objc

func (*CustomVirtioDeviceConfiguration) DeviceSpecificConfiguration

func (c *CustomVirtioDeviceConfiguration) DeviceSpecificConfiguration() *VirtioDeviceSpecificConfiguration

DeviceSpecificConfiguration returns the configured data, or nil if absent.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodeviceconfiguration/devicespecificconfiguration?language=objc

func (*CustomVirtioDeviceConfiguration) MandatoryFeatures

func (c *CustomVirtioDeviceConfiguration) MandatoryFeatures() VirtioFeatureSet

MandatoryFeatures returns the features required from the guest driver.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodeviceconfiguration/mandatoryfeatures?language=objc

func (*CustomVirtioDeviceConfiguration) OptionalFeatures

func (c *CustomVirtioDeviceConfiguration) OptionalFeatures() VirtioFeatureSet

OptionalFeatures returns the features offered for optional negotiation.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodeviceconfiguration/optionalfeatures?language=objc

func (*CustomVirtioDeviceConfiguration) PCIClassID

func (c *CustomVirtioDeviceConfiguration) PCIClassID() uint8

PCIClassID returns the PCI class ID.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodeviceconfiguration/pciclassid?language=objc

func (*CustomVirtioDeviceConfiguration) PCISubclassID

func (c *CustomVirtioDeviceConfiguration) PCISubclassID() uint8

PCISubclassID returns the PCI subclass ID.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodeviceconfiguration/pcisubclassid?language=objc

func (*CustomVirtioDeviceConfiguration) SharedMemoryRegions

SharedMemoryRegions returns the configured shared memory regions.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodeviceconfiguration/sharedmemoryregions?language=objc

func (*CustomVirtioDeviceConfiguration) SupportsSaveRestore

func (c *CustomVirtioDeviceConfiguration) SupportsSaveRestore() bool

SupportsSaveRestore reports whether the provider implements state saving and restoration.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodeviceconfiguration/supportssaverestore?language=objc

func (*CustomVirtioDeviceConfiguration) VirtioQueueCount

func (c *CustomVirtioDeviceConfiguration) VirtioQueueCount() uint16

VirtioQueueCount returns the configured number of virtqueues.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodeviceconfiguration/virtioqueuecount?language=objc

type CustomVirtioDeviceConfigurationOption

type CustomVirtioDeviceConfigurationOption func(*CustomVirtioDeviceConfiguration) error

CustomVirtioDeviceConfigurationOption configures a custom Virtio device.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodeviceconfiguration?language=objc

func WithCustomVirtioDeviceSpecificConfiguration

func WithCustomVirtioDeviceSpecificConfiguration(configuration *VirtioDeviceSpecificConfiguration) CustomVirtioDeviceConfigurationOption

WithCustomVirtioDeviceSpecificConfiguration supplies the initial device configuration.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodeviceconfiguration/devicespecificconfiguration?language=objc

func WithCustomVirtioMandatoryFeatures

func WithCustomVirtioMandatoryFeatures(features VirtioFeatureSet) CustomVirtioDeviceConfigurationOption

WithCustomVirtioMandatoryFeatures sets features the guest must accept. The framework always enables VIRTIO_F_VERSION_1.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodeviceconfiguration/mandatoryfeatures?language=objc

func WithCustomVirtioOptionalFeatures

func WithCustomVirtioOptionalFeatures(features VirtioFeatureSet) CustomVirtioDeviceConfigurationOption

WithCustomVirtioOptionalFeatures sets features the guest may accept. The framework may enable additional features internally.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodeviceconfiguration/optionalfeatures?language=objc

func WithCustomVirtioProvider

WithCustomVirtioProvider sets the device implementation. Save and restore support is enabled when its delegate implements CustomVirtioDeviceStateDelegate.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodeviceconfiguration/provider?language=objc

type CustomVirtioDeviceDelegate

type CustomVirtioDeviceDelegate interface {
	// DidCreateDevice is called after the framework creates the device.
	//
	// see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodeviceconfigurationdelegate/customvirtioconfiguration(_:didcreatedevice:)?language=objc
	DidCreateDevice(CustomVirtioContext, *CustomVirtioDevice)

	// DidReceiveNotificationForQueue is called when the guest notifies a virtqueue.
	//
	// see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodevicedelegate/customvirtiodevice(_:didreceivenotificationfor:)?language=objc
	DidReceiveNotificationForQueue(CustomVirtioContext, *CustomVirtioDevice, *VirtioQueue)

	// DidAcceptDriverOK is called after the device and driver complete Virtio negotiation.
	//
	// see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodevicedelegate/customvirtiodevicedidacceptdriverok(_:)?language=objc
	DidAcceptDriverOK(CustomVirtioContext, *CustomVirtioDevice)

	// WillStop is called before the device stops.
	//
	// see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodevicedelegate/customvirtiodevicewillstop(_:)?language=objc
	WillStop(CustomVirtioContext, *CustomVirtioDevice)

	// WillPause is called before the device pauses.
	//
	// see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodevicedelegate/customvirtiodevicewillpause(_:)?language=objc
	WillPause(CustomVirtioContext, *CustomVirtioDevice)

	// WillResume is called before the device resumes.
	//
	// see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodevicedelegate/customvirtiodevicewillresume(_:)?language=objc
	WillResume(CustomVirtioContext, *CustomVirtioDevice)

	// WillReset is called after the device reset completes.
	//
	// see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodevicedelegate/customvirtiodevicewillreset(_:)?language=objc
	WillReset(CustomVirtioContext, *CustomVirtioDevice)
}

CustomVirtioDeviceDelegate implements a custom device on its serial device queue. Methods must not wait for virtual machine operations, which may themselves wait for the delegate, or workers that need the device queue. Queue notifications must drain NextElement until it returns nil.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodevicedelegate?language=objc

type CustomVirtioDeviceDelegateProvider

type CustomVirtioDeviceDelegateProvider struct {
	// contains filtered or unexported fields
}

CustomVirtioDeviceDelegateProvider runs a delegate on a dedicated serial queue. Create a separate provider for each device instance, including devices in different virtual machines. Call Close after its virtual machine has stopped. NewVirtualMachine rejects reuse of a provider. Once its provider check succeeds, the provider is reserved even if virtual machine construction later fails.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodevicedelegateprovider?language=objc

func NewCustomVirtioDeviceDelegateProvider

func NewCustomVirtioDeviceDelegateProvider(delegate CustomVirtioDeviceDelegate, options ...CustomVirtioDeviceDelegateProviderOption) (*CustomVirtioDeviceDelegateProvider, error)

NewCustomVirtioDeviceDelegateProvider creates a provider for delegate. A delegate may be shared by separate providers. Their callbacks can run concurrently on different device queues, so shared state needs synchronization. Each callback receives a CustomVirtioContext with access to the device queue. Its parent defaults to context.Background. WithCustomVirtioContext sets a parent for work done by the delegate, including work after a callback returns. This requires macOS 27 or newer.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodevicedelegateprovider/init(devicequeue:delegate:)?language=objc

func (*CustomVirtioDeviceDelegateProvider) Close

Close unregisters the delegate and waits for any running callback to finish. It does not cancel or wait for application workers, or invalidate retained CustomVirtioContext values. Guest resources remain subject to the VM lifecycle. It is safe to call repeatedly or from a delegate method.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodevicedelegateprovider/delegate?language=objc

type CustomVirtioDeviceDelegateProviderOption

type CustomVirtioDeviceDelegateProviderOption func(*customVirtioProviderOptions) error

CustomVirtioDeviceDelegateProviderOption configures a delegate provider.

func WithCustomVirtioContext

func WithCustomVirtioContext(ctx context.Context) CustomVirtioDeviceDelegateProviderOption

WithCustomVirtioContext sets the parent of each CustomVirtioContext passed to the delegate. The provider retains ctx for callbacks after construction. Without this option, the parent is context.Background. A nil ctx is an error.

Canceling ctx closes the delegate context's Done channel. It does not stop the virtual machine, close the provider, or prevent RunOnDeviceQueue calls.

type CustomVirtioDeviceStateDelegate

type CustomVirtioDeviceStateDelegate interface {
	// SaveStateForRestore returns the device state to save with the virtual machine.
	//
	// see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodevicedelegate/customvirtiodevicesavestate(forrestore:)?language=objc
	SaveStateForRestore(CustomVirtioContext, *CustomVirtioDevice) []byte

	// ShouldRestore restores saved device state and reports whether restoration succeeded.
	//
	// see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodevicedelegate/customvirtiodeviceshouldrestore(_:savestate:)?language=objc
	ShouldRestore(CustomVirtioContext, *CustomVirtioDevice, []byte) bool
}

CustomVirtioDeviceStateDelegate adds save and restore support to a delegate. A nil saved state indicates failure; use an empty non-nil slice for no state.

see: https://developer.apple.com/documentation/virtualization/vzcustomvirtiodevicedelegate?language=objc

type DirectoryShare

type DirectoryShare interface {
	objc.NSObject
	// contains filtered or unexported methods
}

DirectoryShare is the base interface for a directory share.

type DirectorySharingDevice

type DirectorySharingDevice interface {
	objc.NSObject
	// contains filtered or unexported methods
}

DirectorySharingDevice is a directory sharing device attached to a virtual machine.

type DirectorySharingDeviceConfiguration

type DirectorySharingDeviceConfiguration interface {
	objc.NSObject
	// contains filtered or unexported methods
}

DirectorySharingDeviceConfiguration for a directory sharing device configuration.

type DisconnectedError

type DisconnectedError struct {
	// Err is the underlying error that caused the disconnection, triggered by the framework.
	// This error provides information on why the network attachment was disconnected.
	Err error
	// The network device configuration associated with the disconnection event.
	// This configuration helps identify which network device experienced the disconnection.
	// If Config is nil, the specific configuration details are unavailable.
	Config *VirtioNetworkDeviceConfiguration
}

DisconnectedError represents an error that occurs when a VM’s network attachment is disconnected due to a network-related issue. This error is triggered by the framework when such a disconnection happens.

func (*DisconnectedError) Error

func (e *DisconnectedError) Error() string

func (*DisconnectedError) Unwrap

func (e *DisconnectedError) Unwrap() error

type DiskBlockDeviceStorageDeviceAttachment

type DiskBlockDeviceStorageDeviceAttachment struct {
	// contains filtered or unexported fields
}

DiskBlockDeviceStorageDeviceAttachment is a storage device attachment that uses a disk to store data.

The disk block device implements a storage attachment by using an actual disk rather than a disk image on a file system.

Warning: Handle the disk passed to this attachment with caution. If the disk has a file system formatted on it, the guest can destroy data in a way that isn’t recoverable.

By default, only the root user can access the disk file handle. Running virtual machines as root isn’t recommended. The best practice is to open the file in a separate process that has root privileges, then pass the open file descriptor using XPC or a Unix socket to a non-root process running Virtualization.

func NewDiskBlockDeviceStorageDeviceAttachment

func NewDiskBlockDeviceStorageDeviceAttachment(file *os.File, readOnly bool, syncMode DiskSynchronizationMode) (*DiskBlockDeviceStorageDeviceAttachment, error)

NewDiskBlockDeviceStorageDeviceAttachment creates a new block storage device attachment from a file handle and with the specified access mode, synchronization mode, and error object that you provide.

- file is the *os.File to a block device to attach to this VM. - readOnly is a boolean value that indicates whether this disk attachment is read-only; otherwise, if the file handle allows writes, the device can write data into it. this parameter affects how the Virtualization framework exposes the disk to the guest operating system by the storage controller. If you intend to use the disk in read-only mode, it’s also a best practice to open the file handle as read-only. - syncMode is one of the available DiskSynchronizationMode options.

Note that the disk attachment retains the file handle, and the handle must be open when the virtual machine starts.

This is only supported on macOS 14 and newer, error will be returned on older versions.

type DiskImageCachingMode

type DiskImageCachingMode int

DiskImageCachingMode describes the disk image caching mode.

see: https://developer.apple.com/documentation/virtualization/vzdiskimagecachingmode?language=objc

const (
	DiskImageCachingModeAutomatic DiskImageCachingMode = iota
	DiskImageCachingModeUncached
	DiskImageCachingModeCached
)

type DiskImageServer

type DiskImageServer struct {
	// contains filtered or unexported fields
}

DiskImageServer serves a disk image over the Network Block Device protocol. It owns its listener and client connections and borrows the image. It must be created with NewDiskImageServer and must not be copied.

The server runs independently of any attachment. Stop every VM using the server before calling Close, then close the image separately.

func NewDiskImageServer

func NewDiskImageServer(image *diskimagekit.DiskImage, opts ...DiskImageServerOption) (*DiskImageServer, error)

NewDiskImageServer starts an NBD server backed by image. It supports RAW, ASIF, and stacks through diskimagekit. Options are applied in order. The last value for each setting wins. Invalid images or options and listener creation failures return an error without taking ownership of a caller-supplied listener.

The caller retains ownership of image and must keep it open until Close returns. From construction until Close, do not resize the image, change its stack, or access it directly. The server synchronizes every write before acknowledging it, regardless of the attachment's synchronization mode.

Pass URL to NewNetworkBlockDeviceStorageDeviceAttachment to create an attachment. Configure its timeout, read-only mode, and synchronization mode through that constructor:

server, err := vz.NewDiskImageServer(image)
if err != nil {
	return err
}
defer server.Close()
attachment, err := vz.NewNetworkBlockDeviceStorageDeviceAttachment(
	server.URL(), 5*time.Second, false, vz.DiskSynchronizationModeFull,
)
if err != nil {
	return err
}
// Configure the VM with attachment and wait for it to stop before returning.

Releasing an attachment does not stop the server. Call Close explicitly.

func (*DiskImageServer) Close

func (s *DiskImageServer) Close() error

Close stops accepting clients, disconnects them, and waits for image operations to finish. It removes any temporary directory created by NewDiskImageServer. It does not close the borrowed image or stop a virtual machine.

Close returns an unexpected listener error or a temporary directory removal error. Repeated and concurrent calls wait for shutdown and return the same result. A closed server cannot be restarted.

func (*DiskImageServer) URL

func (s *DiskImageServer) URL() string

URL returns the NBD connection URL for NewNetworkBlockDeviceStorageDeviceAttachment. The default URL uses a Unix socket and the empty NBD export name.

type DiskImageServerOption

type DiskImageServerOption func(*diskImageServerOptions) error

DiskImageServerOption configures NewDiskImageServer.

func WithDiskImageServerListener

func WithDiskImageServerListener(listener net.Listener, serverURL string) DiskImageServerOption

WithDiskImageServerListener serves the image on listener and makes URL return serverURL, the connection URL for NBD clients. It must reach listener, directly or through a proxy, and use the empty NBD export name. For example:

nbd://127.0.0.1:10809/
nbd+unix:///?socket=/tmp/vz-disk/disk.sock

The server does not validate or connect to this URL. Without this option, NewDiskImageServer creates a Unix socket in a private temporary directory.

A successful constructor takes ownership of the selected listener. On failure, the listener remains owned by the caller. A listener replaced by a later option is never used or closed. The caller must provide any access controls because the NBD server has no authentication or encryption.

type DiskImageStorageDeviceAttachment

type DiskImageStorageDeviceAttachment struct {
	// contains filtered or unexported fields
}

DiskImageStorageDeviceAttachment is a storage device attachment using a disk image to implement the storage.

This storage device attachment uses a disk image on the host file system as the drive of the storage device. Only raw data disk images are supported. see: https://developer.apple.com/documentation/virtualization/vzdiskimagestoragedeviceattachment?language=objc

func NewDiskImageStorageDeviceAttachment

func NewDiskImageStorageDeviceAttachment(diskPath string, readOnly bool) (*DiskImageStorageDeviceAttachment, error)

NewDiskImageStorageDeviceAttachment initialize the attachment from a local file path. Returns error is not nil, assigned with the error if the initialization failed.

- diskPath is local file URL to the disk image in RAW format. - readOnly if YES, the device attachment is read-only, otherwise the device can write data to the disk image.

This is only supported on macOS 11 and newer, error will be returned on older versions.

func NewDiskImageStorageDeviceAttachmentWithCacheAndSync

func NewDiskImageStorageDeviceAttachmentWithCacheAndSync(diskPath string, readOnly bool, cachingMode DiskImageCachingMode, syncMode DiskImageSynchronizationMode) (*DiskImageStorageDeviceAttachment, error)

NewDiskImageStorageDeviceAttachmentWithCacheAndSync initialize the attachment from a local file path. Returns error is not nil, assigned with the error if the initialization failed.

- diskPath is local file URL to the disk image in RAW format. - readOnly if YES, the device attachment is read-only, otherwise the device can write data to the disk image. - cachingMode is one of the available DiskImageCachingMode options. - syncMode is to define how the disk image synchronizes with the underlying storage when the guest operating system flushes data, described by one of the available DiskImageSynchronizationMode modes.

This is only supported on macOS 12 and newer, error will be returned on older versions.

type DiskImageSynchronizationMode

type DiskImageSynchronizationMode int

DiskImageSynchronizationMode describes the disk image synchronization mode.

see: https://developer.apple.com/documentation/virtualization/vzdiskimagesynchronizationmode?language=objc

const (
	DiskImageSynchronizationModeFull DiskImageSynchronizationMode = 1 + iota
	DiskImageSynchronizationModeFsync
	DiskImageSynchronizationModeNone
)

type DiskSynchronizationMode

type DiskSynchronizationMode int

DiskSynchronizationMode describes the synchronization modes available to the guest OS.

see: https://developer.apple.com/documentation/virtualization/vzdisksynchronizationmode?language=objc

const (
	// Perform all synchronization operations as requested by the guest OS.
	//
	// Using this mode, flush and barrier commands from the guest result in
	// the system sending their counterpart synchronization commands to the
	// underlying disk implementation.
	DiskSynchronizationModeFull DiskSynchronizationMode = iota

	// DiskSynchronizationModeNone don’t synchronize the data with the permanent storage.
	//
	// This option doesn’t guarantee data integrity if any error condition occurs such as
	// disk full on the host, panic, power loss, and so on.
	//
	// This mode is useful when a VM is only run once to perform a task to completion or
	// failure. In case of failure, the state of blocks on disk and their order isn’t defined.
	//
	// Using this mode may result in improved performance since no synchronization with the underlying
	// storage is necessary.
	DiskSynchronizationModeNone
)

type EFIBootLoader

type EFIBootLoader struct {
	// contains filtered or unexported fields
}

EFIBootLoader Boot loader configuration for booting guest operating systems expecting an EFI ROM. see: https://developer.apple.com/documentation/virtualization/vzefibootloader?language=objc

func NewEFIBootLoader

func NewEFIBootLoader(opts ...NewEFIBootLoaderOption) (*EFIBootLoader, error)

NewEFIBootLoader creates a new EFI boot loader.

This is only supported on macOS 13 and newer, error will be returned on older versions.

func (*EFIBootLoader) VariableStore

func (e *EFIBootLoader) VariableStore() *EFIVariableStore

VariableStore returns EFI variable store.

type EFISignature

type EFISignature interface {
	objc.NSObject
	// contains filtered or unexported methods
}

EFISignature is a certificate or SHA-256 hash in a UEFI signature database.

see: https://developer.apple.com/documentation/virtualization/vzefisignature-c.class?language=objc

type EFISignatureDatabaseConfiguration

type EFISignatureDatabaseConfiguration struct {
	// contains filtered or unexported fields
}

EFISignatureDatabaseConfiguration holds the KEK, db, and dbx signature lists.

see: https://developer.apple.com/documentation/virtualization/vzefisignaturedatabaseconfiguration?language=objc

func NewEFISignatureDatabaseConfiguration

func NewEFISignatureDatabaseConfiguration(keyExchangeKeys, dbSignatures, dbxSignatures []*EFISignatureList) (*EFISignatureDatabaseConfiguration, error)

NewEFISignatureDatabaseConfiguration creates Secure Boot databases on macOS 27 or later. Key exchange keys must contain only X.509 certificates. Empty databases are allowed.

see: https://developer.apple.com/documentation/virtualization/vzefisignaturedatabaseconfiguration/init(keyexchangekeys:dbsignatures:dbxsignatures:)?language=objc

func (*EFISignatureDatabaseConfiguration) DbSignatures

DbSignatures returns the allowed signature (db) database entries.

see: https://developer.apple.com/documentation/virtualization/vzefisignaturedatabaseconfiguration/dbsignatures?language=objc

func (*EFISignatureDatabaseConfiguration) DbxSignatures

DbxSignatures returns the forbidden signature (dbx) database entries.

see: https://developer.apple.com/documentation/virtualization/vzefisignaturedatabaseconfiguration/dbxsignatures?language=objc

func (*EFISignatureDatabaseConfiguration) KeyExchangeKeys

func (c *EFISignatureDatabaseConfiguration) KeyExchangeKeys() []*EFISignatureList

KeyExchangeKeys returns the Key Exchange Key (KEK) database entries.

see: https://developer.apple.com/documentation/virtualization/vzefisignaturedatabaseconfiguration/keyexchangekeys?language=objc

type EFISignatureList

type EFISignatureList struct {
	// contains filtered or unexported fields
}

EFISignatureList contains X.509 certificates, SHA-256 hashes, or both.

see: https://developer.apple.com/documentation/virtualization/vzefisignaturelist?language=objc

func NewEFISignatureList

func NewEFISignatureList(signatures []EFISignature) (*EFISignatureList, error)

NewEFISignatureList creates a signature list on macOS 27 or later.

see: https://developer.apple.com/documentation/virtualization/vzefisignaturelist/initwithsignatures:?language=objc

func NewEFISignatureListFromFile

func NewEFISignatureListFromFile(path string) (*EFISignatureList, error)

NewEFISignatureListFromFile reads a DER certificate, a binary UEFI signature list, or a SHA-256 hash from path. It requires macOS 27 or later.

see: https://developer.apple.com/documentation/virtualization/vzefisignaturelist/init(contentsofurl:)?language=objc

func (*EFISignatureList) Signatures

func (s *EFISignatureList) Signatures() []EFISignature

Signatures returns the entries in the list.

see: https://developer.apple.com/documentation/virtualization/vzefisignaturelist/signatures-78pcm?language=objc

type EFISignatureSHA256Hash

type EFISignatureSHA256Hash struct {
	// contains filtered or unexported fields
}

EFISignatureSHA256Hash is a SHA-256 Secure Boot signature.

see: https://developer.apple.com/documentation/virtualization/vzefisignaturesha256hash?language=objc

func NewEFISignatureSHA256Hash

func NewEFISignatureSHA256Hash(hash [32]byte) (*EFISignatureSHA256Hash, error)

NewEFISignatureSHA256Hash creates a signature on macOS 27 or later.

see: https://developer.apple.com/documentation/virtualization/vzefisignaturesha256hash/initwithdata:?language=objc

func (*EFISignatureSHA256Hash) Data

func (s *EFISignatureSHA256Hash) Data() [32]byte

Data returns the signature's SHA-256 hash.

see: https://developer.apple.com/documentation/virtualization/vzefisignaturesha256hash/data?language=objc

type EFISignatureX509Certificate

type EFISignatureX509Certificate struct {
	// contains filtered or unexported fields
}

EFISignatureX509Certificate is a DER-encoded X.509 Secure Boot signature.

see: https://developer.apple.com/documentation/virtualization/vzefisignaturex509certificate?language=objc

func NewEFISignatureX509Certificate

func NewEFISignatureX509Certificate(der []byte) (*EFISignatureX509Certificate, error)

NewEFISignatureX509Certificate parses a DER-encoded certificate on macOS 27 or later.

see: https://developer.apple.com/documentation/virtualization/vzefisignaturex509certificate/initwithcertificate:?language=objc

func (*EFISignatureX509Certificate) Certificate

func (s *EFISignatureX509Certificate) Certificate() []byte

Certificate returns a copy of the DER-encoded certificate.

see: https://developer.apple.com/documentation/virtualization/vzefisignaturex509certificate/certificate?language=objc

type EFIVariableStore

type EFIVariableStore struct {
	// contains filtered or unexported fields
}

EFIVariableStore is EFI variable store. The EFI variable store contains NVRAM variables exposed by the EFI ROM.

see: https://developer.apple.com/documentation/virtualization/vzefivariablestore?language=objc

func NewEFIVariableStore

func NewEFIVariableStore(path string, opts ...NewEFIVariableStoreOption) (*EFIVariableStore, error)

NewEFIVariableStore Initialize the variable store. If no options are specified, it initializes from the paths that exist.

This is only supported on macOS 13 and newer, error will be returned on older versions.

func (*EFIVariableStore) DisableSecureBoot

func (e *EFIVariableStore) DisableSecureBoot() error

DisableSecureBoot disables Secure Boot while preserving its configuration. It requires macOS 27 or later.

see: https://developer.apple.com/documentation/virtualization/vzefivariablestore/disablesecureboot()?language=objc

func (*EFIVariableStore) EnableSecureBoot

func (e *EFIVariableStore) EnableSecureBoot(platformKey *EFISignatureX509Certificate) error

EnableSecureBoot enables Secure Boot with a custom Platform Key on macOS 27 or later.

see: https://developer.apple.com/documentation/virtualization/vzefivariablestore/enablesecureboot(platformkey:)?language=objc

func (*EFIVariableStore) EnableSecureBootUsingDefaultPlatformKey

func (e *EFIVariableStore) EnableSecureBootUsingDefaultPlatformKey() error

EnableSecureBootUsingDefaultPlatformKey enables Secure Boot with an Apple-managed Platform Key. It requires macOS 27 or later.

see: https://developer.apple.com/documentation/virtualization/vzefivariablestore/enablesecurebootusingdefaultplatformkey()?language=objc

func (*EFIVariableStore) EnrollDefaultSecureBootSignatures

func (e *EFIVariableStore) EnrollDefaultSecureBootSignatures() error

EnrollDefaultSecureBootSignatures adds Microsoft KEK, UEFI CA, and revocation signatures. It requires macOS 27 or later.

see: https://developer.apple.com/documentation/virtualization/vzefivariablestore/enrolldefaultsecurebootsignatures()?language=objc

func (*EFIVariableStore) EnrollSecureBootSignatures

func (e *EFIVariableStore) EnrollSecureBootSignatures(signatures *EFISignatureDatabaseConfiguration) error

EnrollSecureBootSignatures appends signatures to the KEK, db, and dbx databases. Existing signatures and the Platform Key are preserved. It requires macOS 27 or later.

see: https://developer.apple.com/documentation/virtualization/vzefivariablestore/enrollsecurebootsignatures(_:)?language=objc

func (*EFIVariableStore) EnrolledSecureBootSignatures

func (e *EFIVariableStore) EnrolledSecureBootSignatures() (*EFISignatureDatabaseConfiguration, error)

EnrolledSecureBootSignatures returns the current databases on macOS 27 or later.

see: https://developer.apple.com/documentation/virtualization/vzefivariablestore/getenrolledsecurebootsignatureswitherror:?language=objc

func (*EFIVariableStore) Path

func (e *EFIVariableStore) Path() string

Path returns the path of the variable store on the local file system.

func (*EFIVariableStore) ResetSecureBoot

func (e *EFIVariableStore) ResetSecureBoot() error

ResetSecureBoot clears the Secure Boot configuration and disables Secure Boot. It requires macOS 27 or later.

see: https://developer.apple.com/documentation/virtualization/vzefivariablestore/resetsecureboot()?language=objc

func (*EFIVariableStore) SecureBootEnabled

func (e *EFIVariableStore) SecureBootEnabled() (bool, error)

SecureBootEnabled reports whether Secure Boot is enabled on macOS 27 or later.

see: https://developer.apple.com/documentation/virtualization/vzefivariablestore/getsecurebootenabled:error:?language=objc

type EFIVariableStoreCreationOption

type EFIVariableStoreCreationOption func(*efiVariableStoreCreationOptions)

EFIVariableStoreCreationOption configures creation of an EFI variable store.

See: https://developer.apple.com/documentation/virtualization/vzefivariablestore/initializationoptions?language=objc

func WithEFIVariableStoreAllowOverwrite

func WithEFIVariableStoreAllowOverwrite(allow bool) EFIVariableStoreCreationOption

WithEFIVariableStoreAllowOverwrite controls whether creation may replace an existing file. Overwriting is allowed by default.

See: https://developer.apple.com/documentation/virtualization/vzefivariablestore/initializationoptions/allowoverwrite?language=objc

type ErrorCode

type ErrorCode int

Error type returned by the Virtualization framework. The NSError domain is VZErrorDomain, the code is one of the ErrorCode constants.

const (
	// ErrorInternal is an internal error such as the virtual machine unexpectedly stopping.
	ErrorInternal ErrorCode = 1 + iota

	// ErrorInvalidVirtualMachineConfiguration represents invalid machine configuration.
	ErrorInvalidVirtualMachineConfiguration

	// ErrorInvalidVirtualMachineState represents API used with a machine in the wrong state
	// (e.g. interacting with a machine before it is running).
	ErrorInvalidVirtualMachineState

	// ErrorInvalidVirtualMachineStateTransition is invalid change of state
	// (e.g. pausing a virtual machine that is not started).
	ErrorInvalidVirtualMachineStateTransition

	// ErrorInvalidDiskImage represents unrecognized disk image format or invalid disk image.
	ErrorInvalidDiskImage

	// ErrorVirtualMachineLimitExceeded represents the running virtual machine limit was exceeded.
	// Available from macOS 12.0 and above.
	ErrorVirtualMachineLimitExceeded

	// ErrorNetworkError represents network error occurred.
	// Available from macOS 13.0 and above.
	ErrorNetworkError

	// ErrorOutOfDiskSpace represents machine ran out of disk space.
	// Available from macOS 13.0 and above.
	ErrorOutOfDiskSpace

	// ErrorOperationCancelled represents the operation was cancelled.
	// Available from macOS 13.0 and above.
	ErrorOperationCancelled

	// ErrorNotSupported represents the operation is not supported.
	// Available from macOS 13.0 and above.
	ErrorNotSupported

	// ErrorSave represents the save operation failed.
	// Available from macOS 14.0 and above.
	ErrorSave

	// ErrorRestore represents the restore operation failed.
	// Available from macOS 14.0 and above.
	ErrorRestore
)
const (
	// ErrorRestoreImageCatalogLoadFailed represents the restore image catalog failed to load.
	// Available from macOS 13.0 and above.
	ErrorRestoreImageCatalogLoadFailed ErrorCode = 10001 + iota

	// ErrorInvalidRestoreImageCatalog represents the restore image catalog is invalid.
	// Available from macOS 13.0 and above.
	ErrorInvalidRestoreImageCatalog

	// ErrorNoSupportedRestoreImagesInCatalog represents the restore image catalog has no supported restore images.
	// Available from macOS 13.0 and above.
	ErrorNoSupportedRestoreImagesInCatalog

	// ErrorRestoreImageLoadFailed represents the restore image failed to load.
	// Available from macOS 13.0 and above.
	ErrorRestoreImageLoadFailed

	// ErrorInvalidRestoreImage represents the restore image is invalid.
	// Available from macOS 13.0 and above.
	ErrorInvalidRestoreImage

	// ErrorInstallationRequiresUpdate represents a software update is required to complete the installation.
	// Available from macOS 13.0 and above.
	ErrorInstallationRequiresUpdate

	// ErrorInstallationFailed is an error occurred during installation.
	// Available from macOS 13.0 and above.
	ErrorInstallationFailed
)

macOS installation errors.

const (
	// ErrorNetworkBlockDeviceNegotiationFailed represents the connection or the negotiation with the NBD server failed.
	// Available from macOS 14.0 and above.
	ErrorNetworkBlockDeviceNegotiationFailed ErrorCode = 20001 + iota

	// ErrorNetworkBlockDeviceDisconnected represents the NBD client is disconnected from the server.
	// Available from macOS 14.0 and above.
	ErrorNetworkBlockDeviceDisconnected
)

Network Block Device errors.

const (
	// ErrorUSBControllerNotFound represents controller not found.
	// Available from macOS 15.0 and above.
	ErrorUSBControllerNotFound ErrorCode = 30001 + iota

	// ErrorDeviceAlreadyAttached represents Device is already attached.
	// Available from macOS 15.0 and above.
	ErrorDeviceAlreadyAttached

	// ErrorDeviceInitializationFailure represents device initialization failure.
	// Available from macOS 15.0 and above.
	ErrorDeviceInitializationFailure

	// ErrorDeviceNotFound represents device not found.
	// Available from macOS 15.0 and above.
	ErrorDeviceNotFound
)

USB device hot-plug errors.

const (
	// ErrorGuestProvisioningInvalidFullName indicates an invalid guest account full name.
	//
	// see: https://developer.apple.com/documentation/virtualization/vzerror/guestprovisioninginvalidfullname?language=objc
	ErrorGuestProvisioningInvalidFullName ErrorCode = 40001 + iota
	// ErrorGuestProvisioningInvalidUsername indicates an invalid guest account username.
	//
	// see: https://developer.apple.com/documentation/virtualization/vzerror/guestprovisioninginvalidusername?language=objc
	ErrorGuestProvisioningInvalidUsername
	// ErrorGuestProvisioningInvalidPassword indicates an invalid guest account password.
	//
	// see: https://developer.apple.com/documentation/virtualization/vzerror/guestprovisioninginvalidpassword?language=objc
	ErrorGuestProvisioningInvalidPassword
)
const (
	// ErrorEFISecureBootEnrollmentFailed indicates that Secure Boot signatures could not be enrolled.
	//
	// see: https://developer.apple.com/documentation/virtualization/vzerror/efisecurebootenrollmentfailed?language=objc
	ErrorEFISecureBootEnrollmentFailed ErrorCode = 50001 + iota
	// ErrorEFIVariableInaccessible indicates that the EFI variable store could not be accessed.
	//
	// see: https://developer.apple.com/documentation/virtualization/vzerror/efivariableinaccessible?language=objc
	ErrorEFIVariableInaccessible
)

func (ErrorCode) String

func (i ErrorCode) String() string

type FileHandleNetworkDeviceAttachment

type FileHandleNetworkDeviceAttachment struct {
	// contains filtered or unexported fields
}

FileHandleNetworkDeviceAttachment sending raw network packets over a file handle.

The file handle attachment transmits the raw packets/frames between the virtual network interface and a file handle. The data transmitted through this attachment is at the level of the data link layer. see: https://developer.apple.com/documentation/virtualization/vzfilehandlenetworkdeviceattachment?language=objc

func NewFileHandleNetworkDeviceAttachment

func NewFileHandleNetworkDeviceAttachment(file *os.File) (*FileHandleNetworkDeviceAttachment, error)

NewFileHandleNetworkDeviceAttachment initialize the attachment with a file handle.

file parameter is holding a connected datagram socket.

This is only supported on macOS 11 and newer, error will be returned on older versions.

func (*FileHandleNetworkDeviceAttachment) MaximumTransmissionUnit

func (f *FileHandleNetworkDeviceAttachment) MaximumTransmissionUnit() int

MaximumTransmissionUnit returns the maximum transmission unit (MTU) associated with this attachment. The default MTU is 1500. On macOS 11 and 12, the MTU is always 1500.

see: https://developer.apple.com/documentation/virtualization/vzfilehandlenetworkdeviceattachment/maximumtransmissionunit?language=objc

func (*FileHandleNetworkDeviceAttachment) SetMaximumTransmissionUnit

func (f *FileHandleNetworkDeviceAttachment) SetMaximumTransmissionUnit(mtu int) error

SetMaximumTransmissionUnit sets the maximum transmission unit (MTU) associated with this attachment.

The maximum MTU allowed is 65535, and the minimum MTU allowed is 1500. An invalid MTU value will result in an invalid virtual machine configuration.

The client side of the associated datagram socket must be properly configured with the appropriate values for SO_SNDBUF, and SO_RCVBUF. Set these using the setsockopt(_:_:_:_:_:) system call. The system expects the value of SO_RCVBUF to be at least double the value of SO_SNDBUF, and for optimal performance, the recommended value of SO_RCVBUF is four times the value of SO_SNDBUF.

This is only supported on macOS 13 and newer, error will be returned on older versions.

func (*FileHandleNetworkDeviceAttachment) String

type FileHandleSerialPortAttachment

type FileHandleSerialPortAttachment struct {
	// contains filtered or unexported fields
}

FileHandleSerialPortAttachment defines a serial port attachment from a file handle.

Data written to fileHandleForReading goes to the guest. Data sent from the guest appears on fileHandleForWriting. see: https://developer.apple.com/documentation/virtualization/vzfilehandleserialportattachment?language=objc

func NewFileHandleSerialPortAttachment

func NewFileHandleSerialPortAttachment(read, write *os.File) (*FileHandleSerialPortAttachment, error)

NewFileHandleSerialPortAttachment creates a serial attachment from file handles. Data read from read is sent to the guest. Data from the guest is written to write. Either file may be nil to disable that direction, and both may be nil.

The attachment duplicates each non-nil file descriptor. The caller retains ownership of the original files and may close them after this call returns. A closed file returns an error.

This is only supported on macOS 11 and newer. An error is returned on older versions.

see: https://developer.apple.com/documentation/virtualization/vzfilehandleserialportattachment/init(filehandleforreading:filehandleforwriting:)?language=objc

type FileSerialPortAttachment

type FileSerialPortAttachment struct {
	// contains filtered or unexported fields
}

FileSerialPortAttachment defines a serial port attachment from a file.

Any data sent by the guest on the serial interface is written to the file. No data is sent to the guest over serial with this attachment. see: https://developer.apple.com/documentation/virtualization/vzfileserialportattachment?language=objc

func NewFileSerialPortAttachment

func NewFileSerialPortAttachment(path string, shouldAppend bool) (*FileSerialPortAttachment, error)

NewFileSerialPortAttachment initialize the FileSerialPortAttachment from a path of a file. If error is not nil, used to report errors if intialization fails.

  • path of the file for the attachment on the local file system.
  • shouldAppend True if the file should be opened in append mode, false otherwise. When a file is opened in append mode, writing to that file will append to the end of it.

This is only supported on macOS 11 and newer, error will be returned on older versions.

type GenericMachineIdentifier

type GenericMachineIdentifier struct {
	// contains filtered or unexported fields
}

GenericMachineIdentifier is a struct that represents a unique identifier for a virtual machine.

func NewGenericMachineIdentifier

func NewGenericMachineIdentifier() (*GenericMachineIdentifier, error)

NewGenericMachineIdentifier initialize a new machine identifier is used by guests to uniquely identify the virtual hardware.

Two virtual machines running concurrently should not use the same identifier.

If the virtual machine is serialized to disk, the identifier can be preserved in a binary representation through DataRepresentation method. The identifier can then be recreated with NewGenericMachineIdentifierWithData function from the binary representation.

This is only supported on macOS 13 and newer, error will be returned on older versions.

func NewGenericMachineIdentifierWithData

func NewGenericMachineIdentifierWithData(b []byte) (*GenericMachineIdentifier, error)

NewGenericMachineIdentifierWithData initialize a new machine identifier described by the specified data representation.

This is only supported on macOS 13 and newer, error will be returned on older versions.

func NewGenericMachineIdentifierWithDataPath

func NewGenericMachineIdentifierWithDataPath(pathname string) (*GenericMachineIdentifier, error)

NewGenericMachineIdentifierWithDataPath initialize a new machine identifier described by the specified pathname.

This is only supported on macOS 13 and newer, error will be returned on older versions.

func (*GenericMachineIdentifier) DataRepresentation

func (g *GenericMachineIdentifier) DataRepresentation() []byte

DataRepresentation opaque data representation of the machine identifier. This can be used to recreate the same machine identifier with NewGenericMachineIdentifierWithData function.

type GenericPlatformConfiguration

type GenericPlatformConfiguration struct {
	// contains filtered or unexported fields
}

GenericPlatformConfiguration is the platform configuration for a generic Intel or ARM virtual machine.

func NewGenericPlatformConfiguration

func NewGenericPlatformConfiguration(opts ...GenericPlatformConfigurationOption) (*GenericPlatformConfiguration, error)

NewGenericPlatformConfiguration creates a new generic platform configuration.

This is only supported on macOS 12 and newer, error will be returned on older versions.

func (*GenericPlatformConfiguration) MachineIdentifier

MachineIdentifier returns the machine identifier.

func (*GenericPlatformConfiguration) SetNestedVirtualizationEnabled

func (m *GenericPlatformConfiguration) SetNestedVirtualizationEnabled(enable bool) error

SetNestedVirtualizationEnabled toggles nested virtualization.

type GenericPlatformConfigurationOption

type GenericPlatformConfigurationOption func(*GenericPlatformConfiguration) error

GenericPlatformConfigurationOption is an optional function to create its configuration.

func WithGenericMachineIdentifier

func WithGenericMachineIdentifier(m *GenericMachineIdentifier) GenericPlatformConfigurationOption

WithGenericMachineIdentifier is an option to create a new GenericPlatformConfiguration.

This is only supported on macOS 13 and newer, error will be returned on older versions.

type GraphicWindow

type GraphicWindow struct {
	// contains filtered or unexported fields
}

GraphicWindow describes a VM window. Create one with NewGraphicWindow.

func NewGraphicWindow

func NewGraphicWindow(machine *VirtualMachine, width, height float64, opts ...StartGraphicApplicationOption) (*GraphicWindow, error)

NewGraphicWindow configures a window without opening it.

type GraphicsDevice

type GraphicsDevice struct {
	// contains filtered or unexported fields
}

GraphicsDevice is a graphics device attached to a virtual machine. Obtain it from VirtualMachine.GraphicsDevices.

func (*GraphicsDevice) Displays

func (d *GraphicsDevice) Displays() []*GraphicsDisplay

Displays returns the displays configured on the graphics device.

type GraphicsDisplay

type GraphicsDisplay struct {
	// contains filtered or unexported fields
}

GraphicsDisplay is a display attached to a virtual machine. Obtain it from GraphicsDevice.Displays.

func (*GraphicsDisplay) PixelsPerInch

func (d *GraphicsDisplay) PixelsPerInch() (int64, error)

PixelsPerInch returns the pixel density of a Mac graphics display. It returns an error for other display types or on macOS versions older than 14.

func (*GraphicsDisplay) ReconfigureWithConfiguration

func (d *GraphicsDisplay) ReconfigureWithConfiguration(configuration GraphicsDisplayConfiguration) error

ReconfigureWithConfiguration requests a new display configuration. The configuration type must match the display's original configuration. A nil error means the request was accepted. The guest may ignore the changes. This requires macOS 14 or newer.

func (*GraphicsDisplay) ReconfigureWithSizeInPixels

func (d *GraphicsDisplay) ReconfigureWithSizeInPixels(width, height float64) error

ReconfigureWithSizeInPixels requests a new display size in pixels. A nil error means the request was accepted. The guest may ignore the new size. This requires macOS 14 or newer.

func (*GraphicsDisplay) SizeInPixels

func (d *GraphicsDisplay) SizeInPixels() (width, height float64)

SizeInPixels returns the display's current width and height in pixels.

type GraphicsDisplayConfiguration

type GraphicsDisplayConfiguration interface {
	objc.NSObject
	// contains filtered or unexported methods
}

GraphicsDisplayConfiguration configures a graphics display. Its concrete type must match the display's original configuration.

type GraphicsDisplayEvent

type GraphicsDisplayEvent struct {
	// DeviceIndex identifies the graphics device in VirtualMachine.GraphicsDevices.
	DeviceIndex int
	// DisplayIndex identifies the display in GraphicsDevice.Displays.
	DisplayIndex int
	// Reconfiguring is true at the beginning and false when frames arrive
	// at the most recently requested size and configuration.
	Reconfiguring bool
}

GraphicsDisplayEvent reports the beginning or end of display reconfiguration.

type GuestMemoryMapping

type GuestMemoryMapping struct {
	// contains filtered or unexported fields
}

GuestMemoryMapping exposes a guest RAM range in the host address space. Its memory becomes invalid when the guest reboots or shuts down. Keep the mapping alive while using MutableBytes. Guest writes can change the bytes at any time, so copy untrusted input once before validating and interpreting it.

see: https://developer.apple.com/documentation/virtualization/vzguestmemorymapping?language=objc

func (*GuestMemoryMapping) Length

func (m *GuestMemoryMapping) Length() uint64

Length returns the mapping length in bytes.

see: https://developer.apple.com/documentation/virtualization/vzguestmemorymapping/length?language=objc

func (*GuestMemoryMapping) MutableBytes

func (m *GuestMemoryMapping) MutableBytes() unsafe.Pointer

MutableBytes returns the base pointer of the mapped memory.

see: https://developer.apple.com/documentation/virtualization/vzguestmemorymapping/mutablebytes?language=objc

func (*GuestMemoryMapping) PhysicalAddress

func (m *GuestMemoryMapping) PhysicalAddress() uint64

PhysicalAddress returns the base guest physical address.

see: https://developer.apple.com/documentation/virtualization/vzguestmemorymapping/physicaladdress?language=objc

type LinuxBootLoader

type LinuxBootLoader struct {
	// contains filtered or unexported fields
}

LinuxBootLoader Boot loader configuration for a Linux kernel. see: https://developer.apple.com/documentation/virtualization/vzlinuxbootloader?language=objc

func NewLinuxBootLoader

func NewLinuxBootLoader(vmlinuz string, opts ...LinuxBootLoaderOption) (*LinuxBootLoader, error)

NewLinuxBootLoader creates a LinuxBootLoader with the Linux kernel passed as Path.

This is only supported on macOS 11 and newer, error will be returned on older versions.

func (*LinuxBootLoader) String

func (b *LinuxBootLoader) String() string

type LinuxBootLoaderOption

type LinuxBootLoaderOption func(b *LinuxBootLoader) error

LinuxBootLoaderOption is an option for LinuxBootLoader.

func WithCommandLine

func WithCommandLine(cmdLine string) LinuxBootLoaderOption

WithCommandLine sets the command-line parameters. see: https://www.kernel.org/doc/html/latest/admin-guide/kernel-parameters.html

func WithInitrd

func WithInitrd(initrdPath string) LinuxBootLoaderOption

WithInitrd sets the optional initial RAM disk.

type MACAddress

type MACAddress struct {
	// contains filtered or unexported fields
}

MACAddress represents a media access control address (MAC address), the 48-bit ethernet address. see: https://developer.apple.com/documentation/virtualization/vzmacaddress?language=objc

func NewMACAddress

func NewMACAddress(macAddr net.HardwareAddr) (*MACAddress, error)

NewMACAddress creates a new MACAddress with a six-byte Ethernet address. It returns an error if macAddr does not contain exactly six bytes.

see: https://developer.apple.com/documentation/virtualization/vzmacaddress/init(string:)?language=objc

This is only supported on macOS 11 and newer, error will be returned on older versions.

func NewRandomLocallyAdministeredMACAddress

func NewRandomLocallyAdministeredMACAddress() (*MACAddress, error)

NewRandomLocallyAdministeredMACAddress creates a valid, random, unicast, locally administered address.

This is only supported on macOS 11 and newer, error will be returned on older versions.

func (*MACAddress) HardwareAddr

func (m *MACAddress) HardwareAddr() net.HardwareAddr

func (*MACAddress) String

func (m *MACAddress) String() string

type MemoryBalloonDevice

type MemoryBalloonDevice interface {
	objc.NSObject
	// contains filtered or unexported methods
}

MemoryBalloonDevice is the base interface for memory balloon devices.

This represents MemoryBalloonDevice in the Virtualization framework. It is an abstract class that should not be directly used.

see: https://developer.apple.com/documentation/virtualization/vzmemoryballoondevice?language=objc

type MemoryBalloonDeviceConfiguration

type MemoryBalloonDeviceConfiguration interface {
	objc.NSObject
	// contains filtered or unexported methods
}

MemoryBalloonDeviceConfiguration for a memory balloon device configuration.

type MultipleDirectoryShare

type MultipleDirectoryShare struct {
	// contains filtered or unexported fields
}

MultipleDirectoryShare defines the directory share for multiple directories.

func NewMultipleDirectoryShare

func NewMultipleDirectoryShare(shares map[string]*SharedDirectory) (*MultipleDirectoryShare, error)

NewMultipleDirectoryShare creates a new multiple directories share. It returns an error if a directory name is invalid or a directory is nil or uninitialized.

This is only supported on macOS 12 and newer, error will be returned on older versions.

type NATNetworkDeviceAttachment

type NATNetworkDeviceAttachment struct {
	// contains filtered or unexported fields
}

Network device attachment using network address translation (NAT) with outside networks.

Using the NAT attachment type, the host serves as router and performs network address translation for accesses to outside networks. see: https://developer.apple.com/documentation/virtualization/vznatnetworkdeviceattachment?language=objc

func NewNATNetworkDeviceAttachment

func NewNATNetworkDeviceAttachment() (*NATNetworkDeviceAttachment, error)

NewNATNetworkDeviceAttachment creates a new NATNetworkDeviceAttachment.

This is only supported on macOS 11 and newer, error will be returned on older versions.

func (*NATNetworkDeviceAttachment) String

type NSError

type NSError = objcutil.NSError

NSError indicates NSError.

type NVMExpressControllerDeviceConfiguration

type NVMExpressControllerDeviceConfiguration struct {
	// contains filtered or unexported fields
}

NVMExpressControllerDeviceConfiguration is a configuration of an NVM Express Controller storage device.

This device configuration creates a storage device that conforms to the NVM Express specification revision 1.1b.

func NewNVMExpressControllerDeviceConfiguration

func NewNVMExpressControllerDeviceConfiguration(attachment StorageDeviceAttachment) (*NVMExpressControllerDeviceConfiguration, error)

NewNVMExpressControllerDeviceConfiguration creates a new NVMExpressControllerDeviceConfiguration with a device attachment.

attachment is the storage device attachment. This defines how the virtualized device operates on the host side.

This is only supported on macOS 14 and newer, error will be returned on older versions.

func (NVMExpressControllerDeviceConfiguration) Attachment

func (b NVMExpressControllerDeviceConfiguration) Attachment() StorageDeviceAttachment

type NetworkBlockDeviceStorageDeviceAttachment

type NetworkBlockDeviceStorageDeviceAttachment struct {
	// contains filtered or unexported fields
}

NetworkBlockDeviceStorageDeviceAttachment is a storage device attachment that is backed by a NBD (Network Block Device) server.

Using this attachment requires the app to have the com.apple.security.network.client entitlement because this attachment opens an outgoing network connection.

For more information about the NBD URL format read: https://github.com/NetworkBlockDevice/nbd/blob/master/doc/uri.md

func NewNetworkBlockDeviceStorageDeviceAttachment

func NewNetworkBlockDeviceStorageDeviceAttachment(url string, timeout time.Duration, forcedReadOnly bool, syncMode DiskSynchronizationMode) (*NetworkBlockDeviceStorageDeviceAttachment, error)

NewNetworkBlockDeviceStorageDeviceAttachment creates a new network block device storage attachment from an NBD Uniform Resource Indicator (URI) represented as a URL, timeout value, and read-only and synchronization modes that you provide.

- url is the NBD server URI. The format specified by https://github.com/NetworkBlockDevice/nbd/blob/master/doc/uri.md - timeout is the duration for the connection between the client and server. When the timeout expires, an attempt to reconnect with the server takes place. - forcedReadOnly if true forces the disk attachment to be read-only, regardless of whether or not the NBD server supports write requests. - syncMode is one of the available DiskSynchronizationMode options.

This is only supported on macOS 14 and newer, error will be returned on older versions.

func (*NetworkBlockDeviceStorageDeviceAttachment) DidEncounterErrorNotify

func (n *NetworkBlockDeviceStorageDeviceAttachment) DidEncounterErrorNotify(c chan<- error) (func(), error)

DidEncounterErrorNotify registers c for unrecoverable NBD errors. The NBD client can no longer function after one of these errors. Delivery follows NetworkBlockDeviceStorageDeviceAttachment.WasConnectedNotify. The returned function unregisters c.

func (*NetworkBlockDeviceStorageDeviceAttachment) WasConnectedNotify

func (n *NetworkBlockDeviceStorageDeviceAttachment) WasConnectedNotify(c chan<- struct{}) (func(), error)

WasConnectedNotify registers c for successful NBD connections and reconnections that occur after registration. Delivery never waits and drops notifications when c cannot receive them. The caller chooses the channel capacity. No past notifications are replayed. The returned function unregisters c and can be called more than once. Duplicate registrations do not duplicate delivery; either stop removes them. Stop every registration using c before closing it. The library never closes c. A nil channel or a released attachment returns an error and a nil stop function. Keep the attachment reachable while receiving notifications.

type NetworkDevice

type NetworkDevice struct {
	// contains filtered or unexported fields
}

NetworkDevice is a network device attached to a virtual machine. Obtain it from VirtualMachine.NetworkDevices.

func (*NetworkDevice) Attachment

func (d *NetworkDevice) Attachment() NetworkDeviceAttachment

Attachment returns the network attachment currently connected to the device. It returns nil when disconnected. The attachment can change while the VM is running, including after a connection failure.

func (*NetworkDevice) SetAttachment

func (d *NetworkDevice) SetAttachment(attachment NetworkDeviceAttachment) error

SetAttachment changes the network attachment, including while the VM is running. A nil attachment disconnects the device.

A nil error does not guarantee that the attachment connected successfully. Connection failures are reported through VirtualMachine.NetworkDeviceAttachmentWasDisconnectedNotify and clear the attachment. DisconnectedError.Config identifies the original device configuration; it does not track attachment changes made through this method. This requires macOS 12 or newer.

type NetworkDeviceAttachment

type NetworkDeviceAttachment interface {
	objc.NSObject
	fmt.Stringer
	// contains filtered or unexported methods
}

NetworkDeviceAttachment for a network device attachment. see: https://developer.apple.com/documentation/virtualization/vznetworkdeviceattachment?language=objc

type NewEFIBootLoaderOption

type NewEFIBootLoaderOption func(b *EFIBootLoader)

NewEFIBootLoaderOption is an option type to initialize a new EFIBootLoader.

func WithEFIVariableStore

func WithEFIVariableStore(variableStore *EFIVariableStore) NewEFIBootLoaderOption

WithEFIVariableStore sets the optional EFI variable store.

type NewEFIVariableStoreOption

type NewEFIVariableStoreOption func(*EFIVariableStore) error

NewEFIVariableStoreOption is an option type to initialize a new EFIVariableStore.

func WithCreatingEFIVariableStore

func WithCreatingEFIVariableStore(opts ...EFIVariableStoreCreationOption) NewEFIVariableStoreOption

WithCreatingEFIVariableStore creates an initialized EFI variable store at the specified path. By default, it overwrites an existing file.

See: https://developer.apple.com/documentation/virtualization/vzefivariablestore/initcreatingvariablestoreaturl:options:error:?language=objc

type NewVirtioConsolePortConfigurationOption

type NewVirtioConsolePortConfigurationOption func(*VirtioConsolePortConfiguration)

NewVirtioConsolePortConfigurationOption is an option type to initialize a new VirtioConsolePortConfiguration

func WithVirtioConsolePortConfigurationAttachment

func WithVirtioConsolePortConfigurationAttachment(attachment SerialPortAttachment) NewVirtioConsolePortConfigurationOption

WithVirtioConsolePortConfigurationAttachment sets the console port attachment. The default is nil.

func WithVirtioConsolePortConfigurationIsConsole

func WithVirtioConsolePortConfigurationIsConsole(isConsole bool) NewVirtioConsolePortConfigurationOption

WithVirtioConsolePortConfigurationIsConsole sets the console port may be marked for use as the system console. The default is false.

func WithVirtioConsolePortConfigurationName

func WithVirtioConsolePortConfigurationName(name string) NewVirtioConsolePortConfigurationOption

WithVirtioConsolePortConfigurationName sets the console port's name. The default behavior is to not use a name unless set.

type PlatformConfiguration

type PlatformConfiguration interface {
	objc.NSObject
	// contains filtered or unexported methods
}

PlatformConfiguration is an interface for a platform configuration.

type SerialPortAttachment

type SerialPortAttachment interface {
	objc.NSObject
	// contains filtered or unexported methods
}

SerialPortAttachment interface for a serial port attachment.

A serial port attachment defines how the virtual machine's serial port interfaces with the host system.

type SharedDirectory

type SharedDirectory struct {
	// contains filtered or unexported fields
}

SharedDirectory is a shared directory.

func NewSharedDirectory

func NewSharedDirectory(dirPath string, readOnly bool) (*SharedDirectory, error)

NewSharedDirectory creates a new shared directory.

This is only supported on macOS 12 and newer, error will be returned on older versions.

type SingleDirectoryShare

type SingleDirectoryShare struct {
	// contains filtered or unexported fields
}

SingleDirectoryShare defines the directory share for a single directory.

func NewSingleDirectoryShare

func NewSingleDirectoryShare(share *SharedDirectory) (*SingleDirectoryShare, error)

NewSingleDirectoryShare creates a new single directory share. It returns an error if share is nil or uninitialized.

This is only supported on macOS 12 and newer, error will be returned on older versions.

type SocketDeviceConfiguration

type SocketDeviceConfiguration interface {
	objc.NSObject
	// contains filtered or unexported methods
}

SocketDeviceConfiguration for a socket device configuration.

type SpiceAgentPortAttachment

type SpiceAgentPortAttachment struct {
	// contains filtered or unexported fields
}

SpiceAgentPortAttachment is an attachment point that enables the Spice clipboard sharing capability.

see: https://developer.apple.com/documentation/virtualization/vzspiceagentportattachment?language=objc

func NewSpiceAgentPortAttachment

func NewSpiceAgentPortAttachment() (*SpiceAgentPortAttachment, error)

NewSpiceAgentPortAttachment creates a new Spice agent port attachment.

This is only supported on macOS 13 and newer, error will be returned on older versions.

func (*SpiceAgentPortAttachment) SetSharesClipboard

func (s *SpiceAgentPortAttachment) SetSharesClipboard(enable bool)

SetSharesClipboard enables or disables clipboard sharing through the Spice agent.

See: https://developer.apple.com/documentation/virtualization/vzspiceagentportattachment/sharesclipboard?language=objc

func (*SpiceAgentPortAttachment) SharesClipboard

func (s *SpiceAgentPortAttachment) SharesClipboard() bool

SharesClipboard reports whether clipboard sharing is enabled on the attachment.

See: https://developer.apple.com/documentation/virtualization/vzspiceagentportattachment/sharesclipboard?language=objc

type StartGraphicApplicationOption

type StartGraphicApplicationOption func(*startGraphicApplicationOptions) error

StartGraphicApplicationOption is an option for display graphics start.

func WithController

func WithController(enable bool) StartGraphicApplicationOption

WithController is an option to set virtual machine controller on graphics window toolbar.

func WithWindowTitle

func WithWindowTitle(title string) StartGraphicApplicationOption

WithWindowTitle is an option to set window title of display graphics window.

type StorageDeviceAttachment

type StorageDeviceAttachment interface {
	objc.NSObject
	// contains filtered or unexported methods
}

StorageDeviceAttachment for a storage device attachment.

A storage device attachment defines how a virtual machine storage device interfaces with the host system. see: https://developer.apple.com/documentation/virtualization/vzstoragedeviceattachment?language=objc

type StorageDeviceConfiguration

type StorageDeviceConfiguration interface {
	objc.NSObject

	Attachment() StorageDeviceAttachment
	// contains filtered or unexported methods
}

StorageDeviceConfiguration for a storage device configuration.

type USBController

type USBController struct {
	// contains filtered or unexported fields
}

USBController is representing a USB controller in a virtual machine.

func (*USBController) Attach

func (u *USBController) Attach(device USBDevice) error

Attach attaches a USB device.

This is only supported on macOS 15 and newer, error will be returned on older versions.

If the device is successfully attached to the controller, it will appear in the usbDevices property, its usbController property will be set to point to the USB controller that it is attached to and completion handler will return nil. If the device was previously attached to this or another USB controller, attach function will fail with the `vz.ErrorDeviceAlreadyAttached`. If the device cannot be initialized correctly, attach function will fail with `vz.ErrorDeviceInitializationFailure`.

func (*USBController) Detach

func (u *USBController) Detach(device USBDevice) error

Detach detaches a USB device.

This is only supported on macOS 15 and newer, error will be returned on older versions.

If the device is successfully detached from the controller, it will disappear from the usbDevices property, its usbController property will be set to nil and completion handler will return nil. If the device wasn't attached to the controller at the time of calling detach method, it will fail with the `vz.ErrorDeviceNotFound` error.

func (*USBController) USBDevices

func (u *USBController) USBDevices() []USBDevice

USBDevices return a list of USB devices attached to controller.

This is only supported on macOS 15 and newer, nil will be returned on older versions.

type USBControllerConfiguration

type USBControllerConfiguration interface {
	objc.NSObject
	// contains filtered or unexported methods
}

USBControllerConfiguration for a usb controller configuration.

type USBDevice

type USBDevice interface {
	objc.NSObject

	UUID() string

	// USBController returns the controller this device is attached to, or nil if detached.
	// The returned controller does not keep the virtual machine alive.
	// This is only supported on macOS 15 and newer.
	USBController() *USBController
	// contains filtered or unexported methods
}

USBDevice is an interface that represents a USB device in a VM.

func NewUSBMassStorageDevice

func NewUSBMassStorageDevice(config *USBMassStorageDeviceConfiguration) (USBDevice, error)

NewUSBMassStorageDevice initialize the runtime USB Mass Storage device object.

This is only supported on macOS 15 and newer, error will be returned on older versions.

type USBDeviceConfiguration

type USBDeviceConfiguration interface {
	objc.NSObject
	// contains filtered or unexported methods
}

USBDeviceConfiguration describes a USB device attached when the VM starts.

see: https://developer.apple.com/documentation/virtualization/vzusbdeviceconfiguration?language=objc

type USBDeviceConfigurationOption

type USBDeviceConfigurationOption func(USBDeviceConfiguration) error

USBDeviceConfigurationOption configures a USB device at creation.

see: https://developer.apple.com/documentation/virtualization/vzusbdeviceconfiguration?language=objc

func WithUSBDeviceUUID

func WithUSBDeviceUUID(uuid string) USBDeviceConfigurationOption

WithUSBDeviceUUID sets the device UUID. Before restoring a virtual machine, use the UUID returned by USBDevice.UUID when the machine was saved. If omitted, the framework generates a UUID.

This requires macOS 15 or later. It returns an error if uuid is invalid.

see: https://developer.apple.com/documentation/virtualization/vzusbdeviceconfiguration/uuid?language=objc

type USBMassStorageDeviceConfiguration

type USBMassStorageDeviceConfiguration struct {
	// contains filtered or unexported fields
}

USBMassStorageDeviceConfiguration is a configuration of a USB Mass Storage storage device.

This device configuration creates a storage device that conforms to the USB Mass Storage specification.

see: https://developer.apple.com/documentation/virtualization/vzusbmassstoragedeviceconfiguration?language=objc

func NewUSBMassStorageDeviceConfiguration

func NewUSBMassStorageDeviceConfiguration(attachment StorageDeviceAttachment, options ...USBDeviceConfigurationOption) (*USBMassStorageDeviceConfiguration, error)

NewUSBMassStorageDeviceConfiguration initialize a USBMassStorageDeviceConfiguration with a device attachment.

This is only supported on macOS 13 and newer, error will be returned on older versions.

func (USBMassStorageDeviceConfiguration) Attachment

func (b USBMassStorageDeviceConfiguration) Attachment() StorageDeviceAttachment

type VMNetNetworkDeviceAttachment

type VMNetNetworkDeviceAttachment struct {
	// contains filtered or unexported fields
}

VMNetNetworkDeviceAttachment connects a network device to a logical vmnet network. It requires macOS 26 and newer.

func NewVMNetNetworkDeviceAttachment

func NewVMNetNetworkDeviceAttachment(network *vmnet.Network) (*VMNetNetworkDeviceAttachment, error)

NewVMNetNetworkDeviceAttachment creates an attachment sharing network with other attachments. It requires macOS 26 and newer.

func (*VMNetNetworkDeviceAttachment) Network

Network returns the logical network used by this attachment. The returned network remains usable independently of the attachment. An uninitialized attachment returns nil.

func (*VMNetNetworkDeviceAttachment) String

type VirtioBlockDeviceConfiguration

type VirtioBlockDeviceConfiguration struct {
	// contains filtered or unexported fields
}

VirtioBlockDeviceConfiguration is a configuration of a paravirtualized storage device of type Virtio Block Device.

This device configuration creates a storage device using paravirtualization. The emulated device follows the Virtio Block Device specification.

The host implementation of the device is done through an attachment subclassing VZStorageDeviceAttachment like VZDiskImageStorageDeviceAttachment. see: https://developer.apple.com/documentation/virtualization/vzvirtioblockdeviceconfiguration?language=objc

func NewVirtioBlockDeviceConfiguration

func NewVirtioBlockDeviceConfiguration(attachment StorageDeviceAttachment) (*VirtioBlockDeviceConfiguration, error)

NewVirtioBlockDeviceConfiguration initialize a VZVirtioBlockDeviceConfiguration with a device attachment.

- attachment The storage device attachment. This defines how the virtualized device operates on the host side.

This is only supported on macOS 11 and newer, error will be returned on older versions.

func (VirtioBlockDeviceConfiguration) Attachment

func (b VirtioBlockDeviceConfiguration) Attachment() StorageDeviceAttachment

func (*VirtioBlockDeviceConfiguration) BlockDeviceIdentifier

func (v *VirtioBlockDeviceConfiguration) BlockDeviceIdentifier() (string, error)

BlockDeviceIdentifier returns the device identifier is a string identifying the Virtio block device. Empty string by default.

The identifier can be retrieved in the guest via a VIRTIO_BLK_T_GET_ID request.

This is only supported on macOS 12.3 and newer, error will be returned on older versions.

see: https://developer.apple.com/documentation/virtualization/vzvirtioblockdeviceconfiguration/3917717-blockdeviceidentifier

func (*VirtioBlockDeviceConfiguration) SetBlockDeviceIdentifier

func (v *VirtioBlockDeviceConfiguration) SetBlockDeviceIdentifier(identifier string) error

SetBlockDeviceIdentifier sets the device identifier is a string identifying the Virtio block device.

The device identifier must be at most 20 bytes in length and ASCII-encodable.

This is only supported on macOS 12.3 and newer, error will be returned on older versions.

see: https://developer.apple.com/documentation/virtualization/vzvirtioblockdeviceconfiguration/3917717-blockdeviceidentifier

type VirtioConsoleDevice

type VirtioConsoleDevice struct {
	// contains filtered or unexported fields
}

VirtioConsoleDevice is a console device attached to a virtual machine. Obtain it from VirtualMachine.ConsoleDevices.

func (*VirtioConsoleDevice) Ports

Ports returns the configured ports keyed by their configuration indexes. Unconfigured indexes are absent. Changing the map does not change the device.

type VirtioConsoleDeviceConfiguration

type VirtioConsoleDeviceConfiguration struct {
	// contains filtered or unexported fields
}

VirtioConsoleDeviceConfiguration is Virtio Console Device.

func NewVirtioConsoleDeviceConfiguration

func NewVirtioConsoleDeviceConfiguration(opts ...VirtioConsoleDeviceConfigurationOption) (*VirtioConsoleDeviceConfiguration, error)

NewVirtioConsoleDeviceConfiguration creates a new VirtioConsoleDeviceConfiguration.

This is only supported on macOS 13 and newer.

See: https://developer.apple.com/documentation/virtualization/vzvirtioconsoledeviceconfiguration?language=objc

func (*VirtioConsoleDeviceConfiguration) MaximumPortCount

func (v *VirtioConsoleDeviceConfiguration) MaximumPortCount() uint32

MaximumPortCount returns the maximum number of ports allocated by this device. The default is the number of ports attached to this device.

func (*VirtioConsoleDeviceConfiguration) SetVirtioConsolePortConfiguration

func (v *VirtioConsoleDeviceConfiguration) SetVirtioConsolePortConfiguration(idx int, portConfig *VirtioConsolePortConfiguration)

type VirtioConsoleDeviceConfigurationOption

type VirtioConsoleDeviceConfigurationOption func(*VirtioConsoleDeviceConfiguration) error

VirtioConsoleDeviceConfigurationOption configures a new Virtio console device.

func WithVirtioConsoleMaximumPortCount

func WithVirtioConsoleMaximumPortCount(count uint32) VirtioConsoleDeviceConfigurationOption

WithVirtioConsoleMaximumPortCount sets the number of ports allocated by the device. count must be greater than the highest port index added to the configuration. Without this option, Virtualization.framework derives the count from the ports. This option applies when creating the configuration, not while a VM is running.

See: https://developer.apple.com/documentation/virtualization/vzvirtioconsoleportconfigurationarray/maximumportcount?language=objc

type VirtioConsoleDeviceSerialPortConfiguration

type VirtioConsoleDeviceSerialPortConfiguration struct {
	// contains filtered or unexported fields
}

VirtioConsoleDeviceSerialPortConfiguration represents Virtio Console Serial Port Device.

The device creates a console which enables communication between the host and the guest through the Virtio interface. The device sets up a single port on the Virtio console device. see: https://developer.apple.com/documentation/virtualization/vzvirtioconsoledeviceserialportconfiguration?language=objc

func NewVirtioConsoleDeviceSerialPortConfiguration

func NewVirtioConsoleDeviceSerialPortConfiguration(attachment SerialPortAttachment) (*VirtioConsoleDeviceSerialPortConfiguration, error)

NewVirtioConsoleDeviceSerialPortConfiguration creates a new NewVirtioConsoleDeviceSerialPortConfiguration.

This is only supported on macOS 11 and newer, error will be returned on older versions.

type VirtioConsolePort

type VirtioConsolePort struct {
	// contains filtered or unexported fields
}

VirtioConsolePort is a port on a running or stopped virtual machine. Obtain it from VirtioConsoleDevice.Ports.

func (*VirtioConsolePort) Attachment

func (p *VirtioConsolePort) Attachment() SerialPortAttachment

Attachment returns the serial attachment currently connected to the port. It returns nil when disconnected.

func (*VirtioConsolePort) Name

func (p *VirtioConsolePort) Name() string

Name returns the configured port name, or an empty string for an unnamed port.

func (*VirtioConsolePort) SetAttachment

func (p *VirtioConsolePort) SetAttachment(attachment SerialPortAttachment) error

SetAttachment changes the port attachment, including while the VM is running. A nil attachment disconnects the port. This requires macOS 13 or newer.

type VirtioConsolePortConfiguration

type VirtioConsolePortConfiguration struct {
	// contains filtered or unexported fields
}

VirtioConsolePortConfiguration is Virtio Console Port

A console port is a two-way communication channel between a host VZSerialPortAttachment and a virtual machine console port. One or more console ports are attached to a Virtio console device.

func NewVirtioConsolePortConfiguration

func NewVirtioConsolePortConfiguration(opts ...NewVirtioConsolePortConfigurationOption) (*VirtioConsolePortConfiguration, error)

NewVirtioConsolePortConfiguration creates a new VirtioConsolePortConfiguration.

This is only supported on macOS 13 and newer, error will be returned on older versions.

func (*VirtioConsolePortConfiguration) Attachment

Attachment returns the console port attachment.

func (*VirtioConsolePortConfiguration) IsConsole

func (v *VirtioConsolePortConfiguration) IsConsole() bool

IsConsole returns the console port may be marked for use as the system console.

func (*VirtioConsolePortConfiguration) Name

Name returns the console port's name.

type VirtioDeviceSpecificConfiguration

type VirtioDeviceSpecificConfiguration struct {
	// contains filtered or unexported fields
}

VirtioDeviceSpecificConfiguration contains serialized device configuration data.

see: https://developer.apple.com/documentation/virtualization/vzvirtiodevicespecificconfiguration?language=objc

func NewVirtioDeviceSpecificConfiguration

func NewVirtioDeviceSpecificConfiguration(data []byte) (*VirtioDeviceSpecificConfiguration, error)

NewVirtioDeviceSpecificConfiguration copies data into a device configuration.

see: https://developer.apple.com/documentation/virtualization/vzvirtiodevicespecificconfiguration/init(configurationdata:)?language=objc

func (*VirtioDeviceSpecificConfiguration) ConfigurationData

func (c *VirtioDeviceSpecificConfiguration) ConfigurationData() []byte

ConfigurationData returns a copy of the configuration bytes.

see: https://developer.apple.com/documentation/virtualization/vzvirtiodevicespecificconfiguration/configurationdata?language=objc

type VirtioFeatureSet

type VirtioFeatureSet struct {
	// Subset0 contains feature bits 0 through 31.
	//
	// see: https://developer.apple.com/documentation/virtualization/vzvirtiofeatureset/subset0?language=objc
	Subset0 uint32
	// Subset1 contains feature bits 32 through 63.
	//
	// see: https://developer.apple.com/documentation/virtualization/vzvirtiofeatureset/subset1?language=objc
	Subset1 uint32
}

VirtioFeatureSet contains Virtio feature bits 0 through 31 in Subset0 and bits 32 through 63 in Subset1.

see: https://developer.apple.com/documentation/virtualization/vzvirtiofeatureset?language=objc

type VirtioFileSystemDevice

type VirtioFileSystemDevice struct {
	// contains filtered or unexported fields
}

VirtioFileSystemDevice exposes host directories to a guest through Virtio FS. Obtain it from VirtualMachine.DirectorySharingDevices.

func (*VirtioFileSystemDevice) DirectoryShare

func (d *VirtioFileSystemDevice) DirectoryShare() DirectoryShare

DirectoryShare returns the directories currently exposed to the guest. It returns nil if this device has no directory share.

func (*VirtioFileSystemDevice) SetDirectoryShare

func (d *VirtioFileSystemDevice) SetDirectoryShare(share DirectoryShare) error

SetDirectoryShare changes the directories exposed to the guest, including while the VM is running. A nil share removes access to the shared directories. Only SingleDirectoryShare and MultipleDirectoryShare are supported. Rosetta shares must be assigned to the device configuration before creating the VM. This requires macOS 12 or newer.

func (*VirtioFileSystemDevice) Tag

func (d *VirtioFileSystemDevice) Tag() string

Tag returns the label used by the guest to mount this device.

type VirtioFileSystemDeviceConfiguration

type VirtioFileSystemDeviceConfiguration struct {
	// contains filtered or unexported fields
}

VirtioFileSystemDeviceConfiguration is a configuration of a Virtio file system device.

see: https://developer.apple.com/documentation/virtualization/vzvirtiofilesystemdeviceconfiguration?language=objc

func NewVirtioFileSystemDeviceConfiguration

func NewVirtioFileSystemDeviceConfiguration(tag string) (*VirtioFileSystemDeviceConfiguration, error)

NewVirtioFileSystemDeviceConfiguration create a new VirtioFileSystemDeviceConfiguration.

This is only supported on macOS 12 and newer, error will be returned on older versions.

func (*VirtioFileSystemDeviceConfiguration) SetDirectoryShare

func (c *VirtioFileSystemDeviceConfiguration) SetDirectoryShare(share DirectoryShare)

SetDirectoryShare sets the directory share associated with this configuration.

type VirtioNetworkDeviceConfiguration

type VirtioNetworkDeviceConfiguration struct {
	// contains filtered or unexported fields
}

VirtioNetworkDeviceConfiguration is configuration of a paravirtualized network device of type Virtio Network Device.

The communication channel used on the host is defined through the attachment. It is set with the VZNetworkDeviceConfiguration.attachment property in objective-c.

The configuration is only valid with valid MACAddress and attachment.

see: https://developer.apple.com/documentation/virtualization/vzvirtionetworkdeviceconfiguration?language=objc

func NewVirtioNetworkDeviceConfiguration

func NewVirtioNetworkDeviceConfiguration(attachment NetworkDeviceAttachment) (*VirtioNetworkDeviceConfiguration, error)

NewVirtioNetworkDeviceConfiguration creates a new VirtioNetworkDeviceConfiguration with NetworkDeviceAttachment.

This is only supported on macOS 11 and newer, error will be returned on older versions.

func (*VirtioNetworkDeviceConfiguration) Attachment

func (*VirtioNetworkDeviceConfiguration) GetMACAddress

func (v *VirtioNetworkDeviceConfiguration) GetMACAddress() *MACAddress

GetMACAddress returns the media access control address of the device.

func (*VirtioNetworkDeviceConfiguration) SetMACAddress

func (v *VirtioNetworkDeviceConfiguration) SetMACAddress(macAddress *MACAddress)

type VirtioQueue

type VirtioQueue struct {
	// contains filtered or unexported fields
}

VirtioQueue carries descriptor chains between a device and the guest.

see: https://developer.apple.com/documentation/virtualization/vzvirtioqueue?language=objc

func (*VirtioQueue) Elements

func (q *VirtioQueue) Elements() iter.Seq[*VirtioQueueElement]

Elements returns an iterator over the queue's available descriptor chains. Iteration consumes elements from the live queue. Running the iterator again continues with remaining or newly available elements; it does not replay them. Call VirtioQueueElement.ReturnToQueue when each element has been processed. The iterator does not return elements to the guest.

Let the loop finish so VirtioQueue.NextElement can return nil and re-enable notifications for this queue. If the loop exits early with break or return, explicitly resume iteration or call NextElement until it returns nil. Do not wait for another notification to resume consuming the queue.

see: https://developer.apple.com/documentation/virtualization/vzvirtioqueue/nextelement()?language=objc

func (*VirtioQueue) NextElement

func (q *VirtioQueue) NextElement() *VirtioQueueElement

NextElement returns the next available descriptor chain, or nil. Keep calling NextElement until it returns nil to re-enable notifications for this queue. If a loop exits early with break or return, explicitly resume consuming the queue later. Waiting for another notification will not resume it. Return each processed element with VirtioQueueElement.ReturnToQueue.

see: https://developer.apple.com/documentation/virtualization/vzvirtioqueue/nextelement()?language=objc

func (*VirtioQueue) QueueIndex

func (q *VirtioQueue) QueueIndex() uint16

QueueIndex returns the queue's index within its device.

see: https://developer.apple.com/documentation/virtualization/vzvirtioqueue/queueindex?language=objc

func (*VirtioQueue) QueueSize

func (q *VirtioQueue) QueueSize() uint16

QueueSize returns the maximum number of available elements.

see: https://developer.apple.com/documentation/virtualization/vzvirtioqueue/queuesize?language=objc

type VirtioQueueElement

type VirtioQueueElement struct {
	// contains filtered or unexported fields
}

VirtioQueueElement is a descriptor chain obtained from NextElement. Reads and writes consume guest buffers. Prefer consuming reads over PeekBytes because the guest may change its memory between consecutive reads.

see: https://developer.apple.com/documentation/virtualization/vzvirtioqueueelement?language=objc

func (*VirtioQueueElement) PeekBytes

func (e *VirtioQueueElement) PeekBytes(length uint64) ([]byte, error)

PeekBytes copies exactly length bytes without consuming the read buffers. The guest may change these bytes before the next read.

see: https://developer.apple.com/documentation/virtualization/vzvirtioqueueelement/peekintoreadbuffers(withexactlength:)?language=objc

func (*VirtioQueueElement) ReadBuffers

func (e *VirtioQueueElement) ReadBuffers() ([][]byte, error)

ReadBuffers copies and consumes all remaining read buffers. Each returned slice owns its bytes independently of guest memory.

see: https://developer.apple.com/documentation/virtualization/vzvirtioqueueelement/readbuffers()?language=objc

func (*VirtioQueueElement) ReadBuffersAvailableByteCount

func (e *VirtioQueueElement) ReadBuffersAvailableByteCount() uint64

ReadBuffersAvailableByteCount returns the number of unread bytes.

see: https://developer.apple.com/documentation/virtualization/vzvirtioqueueelement/readbuffersavailablebytecount?language=objc

func (*VirtioQueueElement) ReadBuffersByteCount

func (e *VirtioQueueElement) ReadBuffersByteCount() uint64

ReadBuffersByteCount returns the total size of the read buffers.

see: https://developer.apple.com/documentation/virtualization/vzvirtioqueueelement/readbuffersbytecount?language=objc

func (*VirtioQueueElement) ReadBytes

func (e *VirtioQueueElement) ReadBytes(length uint64) ([]byte, error)

ReadBytes copies and consumes exactly length bytes from the read buffers.

see: https://developer.apple.com/documentation/virtualization/vzvirtioqueueelement/readbytes(withexactlength:)?language=objc

func (*VirtioQueueElement) ReadBytesIntoBuffer

func (e *VirtioQueueElement) ReadBytesIntoBuffer(buffer []byte) error

ReadBytesIntoBuffer copies and consumes len(buffer) bytes from the read buffers.

see: https://developer.apple.com/documentation/virtualization/vzvirtioqueueelement/readbytes(intobuffer:exactlength:)?language=objc

func (*VirtioQueueElement) ReturnToQueue

func (e *VirtioQueueElement) ReturnToQueue() error

ReturnToQueue returns the descriptor chain to the guest. Further reads, writes, and returns report an error.

see: https://developer.apple.com/documentation/virtualization/vzvirtioqueueelement/returntoqueue()?language=objc

func (*VirtioQueueElement) WriteBuffersAvailableByteCount

func (e *VirtioQueueElement) WriteBuffersAvailableByteCount() uint64

WriteBuffersAvailableByteCount returns the number of bytes still writable.

see: https://developer.apple.com/documentation/virtualization/vzvirtioqueueelement/writebuffersavailablebytecount?language=objc

func (*VirtioQueueElement) WriteBuffersByteCount

func (e *VirtioQueueElement) WriteBuffersByteCount() uint64

WriteBuffersByteCount returns the total size of the write buffers.

see: https://developer.apple.com/documentation/virtualization/vzvirtioqueueelement/writebuffersbytecount?language=objc

func (*VirtioQueueElement) WriteBytes

func (e *VirtioQueueElement) WriteBytes(data []byte) error

WriteBytes copies all of data into the write buffers and consumes those bytes.

see: https://developer.apple.com/documentation/virtualization/vzvirtioqueueelement/write(_:)?language=objc

func (*VirtioQueueElement) WrittenByteCount

func (e *VirtioQueueElement) WrittenByteCount() uint64

WrittenByteCount returns the number of bytes written to this element.

see: https://developer.apple.com/documentation/virtualization/vzvirtioqueueelement/writtenbytecount?language=objc

type VirtioSharedMemoryRegion

type VirtioSharedMemoryRegion struct {
	// contains filtered or unexported fields
}

VirtioSharedMemoryRegion maps host memory into a configured guest region.

see: https://developer.apple.com/documentation/virtualization/vzvirtiosharedmemoryregion?language=objc

func (*VirtioSharedMemoryRegion) MapMemory

func (r *VirtioSharedMemoryRegion) MapMemory(memory unsafe.Pointer, offset, size uint64, completion func(error)) error

MapMemory asynchronously maps host memory into the region. memory, offset, and size must be aligned to the host page size. memory must point to non-Go memory that remains allocated until unmapping completes. completion runs on the device queue and must not block it.

see: https://developer.apple.com/documentation/virtualization/vzvirtiosharedmemoryregion/mapmemory(_:atoffset:size:completionhandler:)?language=objc

func (*VirtioSharedMemoryRegion) RegionID

func (r *VirtioSharedMemoryRegion) RegionID() uint8

RegionID returns the device-specific region identifier.

see: https://developer.apple.com/documentation/virtualization/vzvirtiosharedmemoryregion/regionid?language=objc

func (*VirtioSharedMemoryRegion) Size

func (r *VirtioSharedMemoryRegion) Size() uint64

Size returns the region size in bytes.

see: https://developer.apple.com/documentation/virtualization/vzvirtiosharedmemoryregion/size?language=objc

func (*VirtioSharedMemoryRegion) UnmapMemory

func (r *VirtioSharedMemoryRegion) UnmapMemory(offset, size uint64, completion func(error)) error

UnmapMemory asynchronously removes a mapping. offset and size must be aligned to the host page size. completion runs on the device queue.

see: https://developer.apple.com/documentation/virtualization/vzvirtiosharedmemoryregion/unmapmemory(atoffset:size:completionhandler:)?language=objc

type VirtioSharedMemoryRegionConfiguration

type VirtioSharedMemoryRegionConfiguration struct {
	// contains filtered or unexported fields
}

VirtioSharedMemoryRegionConfiguration reserves a region for host memory mappings.

see: https://developer.apple.com/documentation/virtualization/vzvirtiosharedmemoryregionconfiguration?language=objc

func NewVirtioSharedMemoryRegionConfiguration

func NewVirtioSharedMemoryRegionConfiguration(regionID uint8, size uint64) (*VirtioSharedMemoryRegionConfiguration, error)

NewVirtioSharedMemoryRegionConfiguration creates a region identified by regionID. The size is in bytes. This requires macOS 27 or newer.

see: https://developer.apple.com/documentation/virtualization/vzvirtiosharedmemoryregionconfiguration/init(regionid:size:)?language=objc

func (*VirtioSharedMemoryRegionConfiguration) RegionID

RegionID returns the region's device-specific identifier.

see: https://developer.apple.com/documentation/virtualization/vzvirtiosharedmemoryregionconfiguration/regionid?language=objc

func (*VirtioSharedMemoryRegionConfiguration) Size

Size returns the region size in bytes.

see: https://developer.apple.com/documentation/virtualization/vzvirtiosharedmemoryregionconfiguration/size?language=objc

type VirtioSocketConnection

type VirtioSocketConnection struct {
	// contains filtered or unexported fields
}

VirtioSocketConnection is a port-based connection between the guest operating system and the host computer.

You don’t create connection objects directly. When the guest operating system initiates a connection, the virtual machine creates the connection object and passes it to the appropriate VirtioSocketListener struct, which forwards the object to its delegate.

This is implemented net.Conn interface. This is generated from duplicated a file descriptor which is returned from virtualization.framework. macOS cannot connect directly to the Guest operating system using vsock. The vsock connection must always be made via virtualization.framework. The diagram looks like this.

┌─────────┐ ┌────────────────────────────┐ ┌────────────┐ │ macOS │<─── unix socket ───>│ virtualization.framework │<─── vsock ───>│ Guest OS │ └─────────┘ └────────────────────────────┘ └────────────┘

You will notice that this is not vsock in using this library. However, all data this connection goes through to the vsock connection to which the Guest OS is connected.

This struct does not have any pointers for objects of the Objective-C. Because the various values of the VZVirtioSocketConnection object handled by Objective-C are no longer needed after the conversion to the Go struct.

see: https://developer.apple.com/documentation/virtualization/vzvirtiosocketconnection?language=objc

func (*VirtioSocketConnection) Close

func (v *VirtioSocketConnection) Close() error

Close will be called when caused something error in socket.

func (*VirtioSocketConnection) DestinationPort

func (v *VirtioSocketConnection) DestinationPort() uint32

DestinationPort returns the destination port number of the connection.

func (*VirtioSocketConnection) LocalAddr

func (v *VirtioSocketConnection) LocalAddr() net.Addr

LocalAddr returns the local network address.

func (*VirtioSocketConnection) Read

func (v *VirtioSocketConnection) Read(b []byte) (n int, err error)

Read reads data from connection of the vsock protocol.

func (*VirtioSocketConnection) RemoteAddr

func (v *VirtioSocketConnection) RemoteAddr() net.Addr

RemoteAddr returns the remote network address.

func (*VirtioSocketConnection) SetDeadline

func (v *VirtioSocketConnection) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines associated with the connection. It is equivalent to calling both SetReadDeadline and SetWriteDeadline.

func (*VirtioSocketConnection) SetReadDeadline

func (v *VirtioSocketConnection) SetReadDeadline(t time.Time) error

SetReadDeadline sets the deadline for future Read calls and any currently-blocked Read call. A zero value for t means Read will not time out.

func (*VirtioSocketConnection) SetWriteDeadline

func (v *VirtioSocketConnection) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the deadline for future Write calls and any currently-blocked Write call. Even if write times out, it may return n > 0, indicating that some of the data was successfully written. A zero value for t means Write will not time out.

func (*VirtioSocketConnection) SourcePort

func (v *VirtioSocketConnection) SourcePort() uint32

SourcePort returns the source port number of the connection.

func (*VirtioSocketConnection) Write

func (v *VirtioSocketConnection) Write(b []byte) (n int, err error)

Write writes data to the connection of the vsock protocol.

type VirtioSocketDevice

type VirtioSocketDevice struct {
	// contains filtered or unexported fields
}

VirtioSocketDevice a device that manages port-based connections between the guest system and the host computer.

Don’t create a VirtioSocketDevice struct directly. Instead, when you request a socket device in your configuration, the virtual machine creates it and you can get it via SocketDevices method. see: https://developer.apple.com/documentation/virtualization/vzvirtiosocketdevice?language=objc

func (*VirtioSocketDevice) Connect

Connect Initiates a connection to the specified port of the guest operating system.

This method initiates the connection asynchronously, and executes the completion handler when the results are available. If the guest operating system doesn’t listen for connections to the specified port, this method does nothing.

For a successful connection, this method sets the sourcePort property of the resulting VZVirtioSocketConnection object to a random port number. see: https://developer.apple.com/documentation/virtualization/vzvirtiosocketdevice/3656677-connecttoport?language=objc

func (*VirtioSocketDevice) Listen

Listen creates a new VirtioSocketListener which is a struct that listens for port-based connection requests from the guest operating system.

Be sure to close the listener by calling `VirtioSocketListener.Close` after used this one.

This is only supported on macOS 11 and newer, error will be returned on older versions.

type VirtioSocketDeviceConfiguration

type VirtioSocketDeviceConfiguration struct {
	// contains filtered or unexported fields
}

VirtioSocketDeviceConfiguration is a configuration of the Virtio socket device.

This configuration creates a Virtio socket device for the guest which communicates with the host through the Virtio interface. Only one Virtio socket device can be used per virtual machine. see: https://developer.apple.com/documentation/virtualization/vzvirtiosocketdeviceconfiguration?language=objc

func NewVirtioSocketDeviceConfiguration

func NewVirtioSocketDeviceConfiguration() (*VirtioSocketDeviceConfiguration, error)

NewVirtioSocketDeviceConfiguration creates a new VirtioSocketDeviceConfiguration.

This is only supported on macOS 11 and newer, error will be returned on older versions.

type VirtioSocketListener

type VirtioSocketListener struct {
	// contains filtered or unexported fields
}

VirtioSocketListener a struct that listens for port-based connection requests from the guest operating system.

see: https://developer.apple.com/documentation/virtualization/vzvirtiosocketlistener?language=objc

func (*VirtioSocketListener) Accept

func (v *VirtioSocketListener) Accept() (net.Conn, error)

Accept implements the Accept method in the Listener interface; it waits for the next call and returns a net.Conn.

func (*VirtioSocketListener) AcceptVirtioSocketConnection

func (v *VirtioSocketListener) AcceptVirtioSocketConnection() (*VirtioSocketConnection, error)

AcceptVirtioSocketConnection accepts the next incoming call and returns the new connection.

func (*VirtioSocketListener) Addr

func (v *VirtioSocketListener) Addr() net.Addr

Addr returns the listener's network address, a *VirtioSocketListenerAddr.

func (*VirtioSocketListener) Close

func (v *VirtioSocketListener) Close() error

Close stops listening on the virtio socket.

type VirtioSocketListenerAddr

type VirtioSocketListenerAddr struct {
	CID  uint32
	Port uint32
}

VirtioSocketListenerAddr represents a network end point address for the vsock protocol.

func (*VirtioSocketListenerAddr) Network

func (a *VirtioSocketListenerAddr) Network() string

Network returns "vsock".

func (*VirtioSocketListenerAddr) String

func (a *VirtioSocketListenerAddr) String() string

String returns string of "<cid>:<port>"

type VirtioTraditionalMemoryBalloonDevice

type VirtioTraditionalMemoryBalloonDevice struct {
	// contains filtered or unexported fields
}

VirtioTraditionalMemoryBalloonDevice represents a Virtio traditional memory balloon device.

The balloon device allows for dynamic memory management by inflating or deflating the balloon to control memory available to the guest OS.

see: https://developer.apple.com/documentation/virtualization/vzvirtiotraditionalmemoryballoondevice?language=objc

func AsVirtioTraditionalMemoryBalloonDevice deprecated

func AsVirtioTraditionalMemoryBalloonDevice(device MemoryBalloonDevice) *VirtioTraditionalMemoryBalloonDevice

Deprecated: should direct type checking using `v, ok := device.(*VirtioTraditionalMemoryBalloonDevice)`. AsVirtioTraditionalMemoryBalloonDevice attempts to convert a MemoryBalloonDevice to a VirtioTraditionalMemoryBalloonDevice.

Returns the VirtioTraditionalMemoryBalloonDevice if the device is of that type, or nil otherwise.

func (*VirtioTraditionalMemoryBalloonDevice) GetTargetVirtualMachineMemorySize

func (v *VirtioTraditionalMemoryBalloonDevice) GetTargetVirtualMachineMemorySize() uint64

GetTargetVirtualMachineMemorySize returns the current target memory size in bytes for the virtual machine.

This is only supported on macOS 11 and newer.

func (*VirtioTraditionalMemoryBalloonDevice) SetTargetVirtualMachineMemorySize

func (v *VirtioTraditionalMemoryBalloonDevice) SetTargetVirtualMachineMemorySize(targetMemorySize uint64)

SetTargetVirtualMachineMemorySize sets the target memory size in bytes for the virtual machine.

This method inflates or deflates the memory balloon to adjust the amount of memory available to the guest OS. The target memory size must be less than the total memory configured for the virtual machine.

This is only supported on macOS 11 and newer.

type VirtioTraditionalMemoryBalloonDeviceConfiguration

type VirtioTraditionalMemoryBalloonDeviceConfiguration struct {
	// contains filtered or unexported fields
}

VirtioTraditionalMemoryBalloonDeviceConfiguration is a configuration of the Virtio traditional memory balloon device.

see: https://developer.apple.com/documentation/virtualization/vzvirtiotraditionalmemoryballoondeviceconfiguration?language=objc

func NewVirtioTraditionalMemoryBalloonDeviceConfiguration

func NewVirtioTraditionalMemoryBalloonDeviceConfiguration() (*VirtioTraditionalMemoryBalloonDeviceConfiguration, error)

NewVirtioTraditionalMemoryBalloonDeviceConfiguration creates a new VirtioTraditionalMemoryBalloonDeviceConfiguration.

This is only supported on macOS 11 and newer, error will be returned on older versions.

type VirtualMachine

type VirtualMachine struct {
	// contains filtered or unexported fields
}

VirtualMachine represents the entire state of a single virtual machine.

A Virtual Machine is the emulation of a complete hardware machine of the same architecture as the real hardware machine. When executing the Virtual Machine, the Virtualization framework uses certain hardware resources and emulates others to provide isolation and great performance.

The definition of a virtual machine starts with its configuration. This is done by setting up a VirtualMachineConfiguration struct. Once configured, the virtual machine can be started with (*VirtualMachine).Start() method.

Creating a virtual machine using the Virtualization framework requires the app to have the "com.apple.security.virtualization" entitlement. see: https://developer.apple.com/documentation/virtualization/vzvirtualmachine?language=objc

func NewVirtualMachine

func NewVirtualMachine(config *VirtualMachineConfiguration) (*VirtualMachine, error)

NewVirtualMachine creates a new VirtualMachine with VirtualMachineConfiguration.

The configuration must be valid. Validation can be performed at runtime with (*VirtualMachineConfiguration).Validate() method. The configuration is copied by the initializer.

Each virtual machine has its own serial dispatch queue. vz dispatches VM operations to that queue internally.

Each custom Virtio delegate provider may be used by only one device instance. Reusing a provider within this configuration or across construction attempts returns an error before creating the virtual machine.

This is only supported on macOS 11 and newer, error will be returned on older versions.

func (*VirtualMachine) CanPause

func (v *VirtualMachine) CanPause() bool

CanPause returns true if the machine is in a state that can be paused.

func (*VirtualMachine) CanRequestStop

func (v *VirtualMachine) CanRequestStop() bool

CanRequestStop returns whether the machine is in a state where the guest can be asked to stop.

func (*VirtualMachine) CanResume

func (v *VirtualMachine) CanResume() bool

CanResume returns true if the machine is in a state that can be resumed.

func (*VirtualMachine) CanStart

func (v *VirtualMachine) CanStart() bool

CanStart returns true if the machine is in a state that can be started.

func (*VirtualMachine) CanStop

func (v *VirtualMachine) CanStop() bool

CanStop returns whether the machine is in a state that can be stopped.

This is only supported on macOS 12 and newer, false will always be returned on older versions.

func (*VirtualMachine) ConsoleDevices

func (v *VirtualMachine) ConsoleDevices() []*VirtioConsoleDevice

ConsoleDevices returns the console devices configured on the VM. It returns nil on macOS versions older than 13.

func (*VirtualMachine) ConsolePortChangedNotify

func (v *VirtualMachine) ConsolePortChangedNotify(c chan<- ConsolePortEvent) (func(), error)

ConsolePortChangedNotify registers c for future console port opens and closes. Delivery follows VirtualMachine.StateChangedNotify. The returned function unregisters c. This requires macOS 13 or newer.

Process or flush pending attachment data before communicating with a new guest process. Closing a port does not guarantee that its output has been consumed.

func (*VirtualMachine) DidStopWithErrorNotify

func (v *VirtualMachine) DidStopWithErrorNotify(c chan<- error) (func(), error)

DidStopWithErrorNotify registers c for errors that caused the VM to stop. Normal guest shutdown and successful host Stop calls do not notify c. Delivery follows StateChangedNotify. The returned function unregisters c.

func (*VirtualMachine) DirectorySharingDevices

func (v *VirtualMachine) DirectorySharingDevices() []DirectorySharingDevice

DirectorySharingDevices returns the directory sharing devices configured on the VM. It returns nil on macOS versions older than 12.

func (*VirtualMachine) GraphicsDevices

func (v *VirtualMachine) GraphicsDevices() []*GraphicsDevice

GraphicsDevices returns the graphics devices configured on the VM. It returns nil on macOS versions older than 14.

func (*VirtualMachine) GraphicsDisplayChangedNotify

func (v *VirtualMachine) GraphicsDisplayChangedNotify(c chan<- GraphicsDisplayEvent) (func(), error)

GraphicsDisplayChangedNotify registers c for future display reconfiguration events. Delivery follows VirtualMachine.StateChangedNotify. The returned function unregisters c. This requires macOS 14 or newer.

func (*VirtualMachine) GuestDidStopNotify

func (v *VirtualMachine) GuestDidStopNotify(c chan<- struct{}) (func(), error)

GuestDidStopNotify registers c for notifications when the guest stops the VM, including in response to RequestStop. Host Stop calls and failures do not notify c. Delivery follows StateChangedNotify. The returned function unregisters c.

func (*VirtualMachine) MemoryBalloonDevices

func (v *VirtualMachine) MemoryBalloonDevices() []MemoryBalloonDevice

MemoryBalloonDevices returns the list of memory balloon devices configured on this virtual machine.

Returns an empty array if no memory balloon device is configured.

This is only supported on macOS 11 and newer.

func (*VirtualMachine) NetworkDeviceAttachmentWasDisconnectedNotify

func (v *VirtualMachine) NetworkDeviceAttachmentWasDisconnectedNotify(c chan<- *DisconnectedError) (func(), error)

NetworkDeviceAttachmentWasDisconnectedNotify registers c for network attachment disconnections, such as when a network interface fails to start. This can happen during boot, a device reset, or a reboot, and may happen more than once. The framework clears the affected runtime device's attachment when it disconnects. Delivery follows StateChangedNotify. The returned function unregisters c. This requires macOS 12 or newer.

func (*VirtualMachine) NetworkDevices

func (v *VirtualMachine) NetworkDevices() []*NetworkDevice

NetworkDevices returns the network devices configured on the VM. It returns nil on macOS versions older than 12.

func (*VirtualMachine) Pause

func (v *VirtualMachine) Pause() error

Pause a virtual machine that is in Running state.

If you want to listen status change events, use the "StateChangedNotify" method.

func (*VirtualMachine) RequestStop

func (v *VirtualMachine) RequestStop() (bool, error)

RequestStop requests that the guest turns itself off.

If returned error is not nil, assigned with the error if the request failed. Returns true if the request was made successfully.

func (*VirtualMachine) Resume

func (v *VirtualMachine) Resume() error

Resume a virtual machine that is in the Paused state.

If you want to listen status change events, use the "StateChangedNotify" method.

func (*VirtualMachine) SocketDevices

func (v *VirtualMachine) SocketDevices() []*VirtioSocketDevice

SocketDevices return the list of socket devices configured on this virtual machine. Return an empty array if no socket device is configured.

Since only NewVirtioSocketDeviceConfiguration is available in vz package, it will always return VirtioSocketDevice. see: https://developer.apple.com/documentation/virtualization/vzvirtualmachine/3656702-socketdevices?language=objc

func (*VirtualMachine) Start

Start a virtual machine that is in either Stopped or Error state.

If you want to listen status change events, use the "StateChangedNotify" method.

If options are specified, also checks whether these options are available in use your macOS version available.

func (*VirtualMachine) StartGraphicApplication

func (v *VirtualMachine) StartGraphicApplication(width, height float64, opts ...StartGraphicApplicationOption) error

StartGraphicApplication opens a window for this VM.

It follows the same threading and return behavior as the package-level StartGraphicApplication function. This is supported on macOS 12 and newer.

func (*VirtualMachine) State

State represents execution state of the virtual machine.

func (*VirtualMachine) StateChangedNotify

func (v *VirtualMachine) StateChangedNotify(c chan<- VirtualMachineState) (func(), error)

StateChangedNotify registers c for future execution state changes. Delivery never waits: a notification is dropped if c cannot receive it. The caller chooses the channel capacity. No past notifications are replayed.

To wait for a state, register a dedicated channel with capacity at least one, then check State() before waiting and after each notification. The notification value may be out of date, and intermediate states may be missed.

Registering the same channel again does not duplicate delivery. Either returned stop function removes that registration. The stop function is safe to call more than once; after it returns, that registration will not send again. Stop every registration using c before closing it. The library never closes c, including on VM release. A nil channel or a released VM returns an error and a nil stop function. Keep the VM reachable while receiving notifications.

func (*VirtualMachine) Stop

func (v *VirtualMachine) Stop() error

Stop stops a VM that’s in either a running or paused state.

The completion handler returns an error object when the VM fails to stop, or nil if the stop was successful.

If you want to listen status change events, use the "StateChangedNotify" method.

Warning: This is a destructive operation. It stops the VM without giving the guest a chance to stop cleanly.

This is only supported on macOS 12 and newer, error will be returned on older versions.

func (*VirtualMachine) USBControllers

func (v *VirtualMachine) USBControllers() []*USBController

USBControllers return the list of USB controllers configured on this virtual machine. Return an empty array if no USB controller is configured.

This is only supported on macOS 15 and newer, nil will be returned on older versions.

type VirtualMachineConfiguration

type VirtualMachineConfiguration struct {
	// contains filtered or unexported fields
}

VirtualMachineConfiguration defines the configuration of a VirtualMachine.

The following properties must be configured before creating a virtual machine:

  • bootLoader

The configuration of devices is often done in two parts: - Device configuration - Device attachment

The device configuration defines the characteristics of the emulated hardware device. For example, for a network device, the device configuration defines the type of network adapter present in the virtual machine and its MAC address.

The device attachment defines the host machine's resources that are exposed by the virtual device. For example, for a network device, the device attachment can be virtual network interface with a NAT to the real network.

Creating a virtual machine using the Virtualization framework requires the app to have the "com.apple.security.virtualization" entitlement. A VirtualMachineConfiguration is considered invalid if the application does not have the entitlement.

see: https://developer.apple.com/documentation/virtualization/vzvirtualmachineconfiguration?language=objc

func NewVirtualMachineConfiguration

func NewVirtualMachineConfiguration(bootLoader BootLoader, cpu uint, memorySize uint64, opts ...VirtualMachineConfigurationOption) (*VirtualMachineConfiguration, error)

NewVirtualMachineConfiguration creates a new configuration.

  • bootLoader parameter is used when the virtual machine starts.
  • cpu parameter is The number of CPUs must be a value between VZVirtualMachineConfiguration.minimumAllowedCPUCount and VZVirtualMachineConfiguration.maximumAllowedCPUCount.
  • memorySize parameter represents memory size in bytes. The memory size must be a multiple of a 1 megabyte (1024 * 1024 bytes) between VZVirtualMachineConfiguration.minimumAllowedMemorySize and VZVirtualMachineConfiguration.maximumAllowedMemorySize.

This is only supported on macOS 11 and newer, error will be returned on older versions.

func (*VirtualMachineConfiguration) CustomVirtioDevices

func (v *VirtualMachineConfiguration) CustomVirtioDevices() ([]*CustomVirtioDeviceConfiguration, error)

CustomVirtioDevices returns the configured custom Virtio devices.

see: https://developer.apple.com/documentation/virtualization/vzvirtualmachineconfiguration/customvirtiodevices?language=objc

func (*VirtualMachineConfiguration) Label

Label returns the name used for the VM in system services, or an empty string if no label was set. It requires macOS 27 or later.

see: https://developer.apple.com/documentation/virtualization/vzvirtualmachineconfiguration/label?language=objc

func (*VirtualMachineConfiguration) NetworkDevices

NetworkDevices return the list of network device configuration set in this virtual machine configuration. Return an empty array if no network device configuration is set.

func (*VirtualMachineConfiguration) SetAudioDevicesVirtualMachineConfiguration

func (v *VirtualMachineConfiguration) SetAudioDevicesVirtualMachineConfiguration(cs []AudioDeviceConfiguration)

SetAudioDevicesVirtualMachineConfiguration sets list of audio devices. Empty by default.

This is only supported on macOS 12 and newer. Older versions do nothing.

func (*VirtualMachineConfiguration) SetConsoleDevicesVirtualMachineConfiguration

func (v *VirtualMachineConfiguration) SetConsoleDevicesVirtualMachineConfiguration(cs []ConsoleDeviceConfiguration)

SetConsoleDevicesVirtualMachineConfiguration sets list of console devices. Empty by default.

This is only supported on macOS 13 and newer. Older versions do nothing.

func (*VirtualMachineConfiguration) SetDirectorySharingDevicesVirtualMachineConfiguration

func (v *VirtualMachineConfiguration) SetDirectorySharingDevicesVirtualMachineConfiguration(cs []DirectorySharingDeviceConfiguration)

SetDirectorySharingDevicesVirtualMachineConfiguration sets list of directory sharing devices. Empty by default.

This is only supported on macOS 12 and newer. Older versions do nothing.

func (*VirtualMachineConfiguration) SetEntropyDevicesVirtualMachineConfiguration

func (v *VirtualMachineConfiguration) SetEntropyDevicesVirtualMachineConfiguration(cs []*VirtioEntropyDeviceConfiguration)

SetEntropyDevicesVirtualMachineConfiguration sets list of entropy devices. Empty by default.

func (*VirtualMachineConfiguration) SetGraphicsDevicesVirtualMachineConfiguration

func (v *VirtualMachineConfiguration) SetGraphicsDevicesVirtualMachineConfiguration(cs []GraphicsDeviceConfiguration)

SetGraphicsDevicesVirtualMachineConfiguration sets list of graphics devices. Empty by default.

This is only supported on macOS 12 and newer. Older versions do nothing.

func (*VirtualMachineConfiguration) SetKeyboardsVirtualMachineConfiguration

func (v *VirtualMachineConfiguration) SetKeyboardsVirtualMachineConfiguration(cs []KeyboardConfiguration)

SetKeyboardsVirtualMachineConfiguration sets list of keyboards. Empty by default.

This is only supported on macOS 12 and newer. Older versions do nothing.

func (*VirtualMachineConfiguration) SetMemoryBalloonDevicesVirtualMachineConfiguration

func (v *VirtualMachineConfiguration) SetMemoryBalloonDevicesVirtualMachineConfiguration(cs []MemoryBalloonDeviceConfiguration)

SetMemoryBalloonDevicesVirtualMachineConfiguration sets list of memory balloon devices. Empty by default.

func (*VirtualMachineConfiguration) SetNetworkDevicesVirtualMachineConfiguration

func (v *VirtualMachineConfiguration) SetNetworkDevicesVirtualMachineConfiguration(cs []*VirtioNetworkDeviceConfiguration)

SetNetworkDevicesVirtualMachineConfiguration sets list of network adapters. Empty by default.

func (*VirtualMachineConfiguration) SetPlatformVirtualMachineConfiguration

func (v *VirtualMachineConfiguration) SetPlatformVirtualMachineConfiguration(c PlatformConfiguration)

SetPlatformVirtualMachineConfiguration sets the hardware platform to use. Defaults to GenericPlatformConfiguration.

This is only supported on macOS 12 and newer. Older versions do nothing.

func (*VirtualMachineConfiguration) SetPointingDevicesVirtualMachineConfiguration

func (v *VirtualMachineConfiguration) SetPointingDevicesVirtualMachineConfiguration(cs []PointingDeviceConfiguration)

SetPointingDevicesVirtualMachineConfiguration sets list of pointing devices. Empty by default.

This is only supported on macOS 12 and newer. Older versions do nothing.

func (*VirtualMachineConfiguration) SetSerialPortsVirtualMachineConfiguration

func (v *VirtualMachineConfiguration) SetSerialPortsVirtualMachineConfiguration(cs []*VirtioConsoleDeviceSerialPortConfiguration)

SetSerialPortsVirtualMachineConfiguration sets list of serial ports. Empty by default.

func (*VirtualMachineConfiguration) SetSocketDevicesVirtualMachineConfiguration

func (v *VirtualMachineConfiguration) SetSocketDevicesVirtualMachineConfiguration(cs []SocketDeviceConfiguration)

SetSocketDevicesVirtualMachineConfiguration sets list of socket devices. Empty by default.

func (*VirtualMachineConfiguration) SetStorageDevicesVirtualMachineConfiguration

func (v *VirtualMachineConfiguration) SetStorageDevicesVirtualMachineConfiguration(cs []StorageDeviceConfiguration)

SetStorageDevicesVirtualMachineConfiguration sets list of disk devices. Empty by default.

func (*VirtualMachineConfiguration) SetUSBControllersVirtualMachineConfiguration

func (v *VirtualMachineConfiguration) SetUSBControllersVirtualMachineConfiguration(us []USBControllerConfiguration)

SetUSBControllerConfiguration sets list of USB controllers. Empty by default.

This is only supported on macOS 15 and newer. Older versions do nothing.

func (*VirtualMachineConfiguration) SocketDevices

SocketDevices return the list of socket device configuration configured in this virtual machine configuration. Return an empty array if no socket device configuration is set.

func (*VirtualMachineConfiguration) StorageDevices

StorageDevices return the list of storage device configuration configured in this virtual machine configuration. Return an empty array if no storage device configuration is set.

func (*VirtualMachineConfiguration) USBControllers

USBControllers return the list of usb controller configuration configured in this virtual machine configuration. Return an empty array if no usb controller configuration is set.

func (*VirtualMachineConfiguration) Validate

func (v *VirtualMachineConfiguration) Validate() (bool, error)

Validate the configuration.

Return true if the configuration is valid. If error is not nil, assigned with the validation error if the validation failed.

type VirtualMachineConfigurationOption

type VirtualMachineConfigurationOption func(*VirtualMachineConfiguration) error

VirtualMachineConfigurationOption configures a virtual machine before creation.

see: https://developer.apple.com/documentation/virtualization/vzvirtualmachineconfiguration?language=objc

func WithCustomVirtioDevices

func WithCustomVirtioDevices(devices ...*CustomVirtioDeviceConfiguration) VirtualMachineConfigurationOption

WithCustomVirtioDevices sets the custom devices in a virtual machine. This requires macOS 27 or newer.

see: https://developer.apple.com/documentation/virtualization/vzvirtualmachineconfiguration/customvirtiodevices?language=objc

func WithVirtualMachineLabel

func WithVirtualMachineLabel(label string) VirtualMachineConfigurationOption

WithVirtualMachineLabel sets the name used for the VM in some system services. The label must contain 1 to 64 characters, including a non-whitespace character. It requires macOS 27 or later.

see: https://developer.apple.com/documentation/virtualization/vzvirtualmachineconfiguration/label?language=objc

type VirtualMachineStartOption

type VirtualMachineStartOption func(*virtualMachineStartOptions) error

VirtualMachineStartOption is an option for virtual machine start.

type VirtualMachineState

type VirtualMachineState int

VirtualMachineState represents execution state of the virtual machine.

const (
	// VirtualMachineStateStopped Initial state before the virtual machine is started.
	VirtualMachineStateStopped VirtualMachineState = iota

	// VirtualMachineStateRunning Running virtual machine.
	VirtualMachineStateRunning

	// VirtualMachineStatePaused A started virtual machine is paused.
	// This state can only be transitioned from VirtualMachineStatePausing.
	VirtualMachineStatePaused

	// VirtualMachineStateError The virtual machine has encountered an internal error.
	VirtualMachineStateError

	// VirtualMachineStateStarting The virtual machine is configuring the hardware and starting.
	VirtualMachineStateStarting

	// VirtualMachineStatePausing The virtual machine is being paused.
	// This is the intermediate state between VirtualMachineStateRunning and VirtualMachineStatePaused.
	VirtualMachineStatePausing

	// VirtualMachineStateResuming The virtual machine is being resumed.
	// This is the intermediate state between VirtualMachineStatePaused and VirtualMachineStateRunning.
	VirtualMachineStateResuming

	// VirtualMachineStateStopping The virtual machine is being stopped.
	// This is the intermediate state between VirtualMachineStateRunning and VirtualMachineStateStop.
	//
	// Available on macOS 12.0 and above.
	VirtualMachineStateStopping

	// VirtualMachineStateSaving The virtual machine is being saved.
	// This is the intermediate state between VirtualMachineStatePaused and VirtualMachineStatePaused
	//
	// Available on macOS 14.0 and above.
	VirtualMachineStateSaving

	// VirtualMachineStateRestoring	The virtual machine is being restored.
	// This is the intermediate state between VirtualMachineStateStopped and either VirtualMachineStatePaused on success or VirtualMachineStateStopped on failure.
	//
	// Available on macOS 14.0 and above.
	VirtualMachineStateRestoring
)

func (VirtualMachineState) String

func (i VirtualMachineState) String() string

type XHCIControllerConfiguration

type XHCIControllerConfiguration struct {
	// contains filtered or unexported fields
}

XHCIControllerConfiguration is a configuration of the USB XHCI controller.

This configuration creates a USB XHCI controller device for the guest. see: https://developer.apple.com/documentation/virtualization/vzxhcicontrollerconfiguration?language=objc

func NewXHCIControllerConfiguration

func NewXHCIControllerConfiguration(options ...XHCIControllerConfigurationOption) (*XHCIControllerConfiguration, error)

NewXHCIControllerConfiguration creates a new XHCIControllerConfiguration.

This is only supported on macOS 15 and newer, error will be returned on older versions.

see: https://developer.apple.com/documentation/virtualization/vzxhcicontrollerconfiguration?language=objc

func (*XHCIControllerConfiguration) USBDevices

USBDevices returns the USB devices configured for startup.

see: https://developer.apple.com/documentation/virtualization/vzusbcontrollerconfiguration/usbdevices?language=objc

type XHCIControllerConfigurationOption

type XHCIControllerConfigurationOption func(*XHCIControllerConfiguration) error

XHCIControllerConfigurationOption configures an XHCI controller at creation.

see: https://developer.apple.com/documentation/virtualization/vzxhcicontrollerconfiguration?language=objc

Directories

Path Synopsis
cmd
addtags command
codesign command
vzbridgegen command
Package diskimagekit reads and writes RAW and ASIF disk images and layered images.
Package diskimagekit reads and writes RAW and ASIF disk images and layered images.
internal
nbd
Package nbd exports a diskimagekit image or stack over the Network Block Device protocol.
Package nbd exports a diskimagekit image or stack over the Network Block Device protocol.
Package vmnet configures logical networks provided by Apple's vmnet framework.
Package vmnet configures logical networks provided by Apple's vmnet framework.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL