### Manage Virtual Machines with HCS API Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/tutorial This example shows the lifecycle of a virtual machine using HCS API, including configuration, creation, and starting the system. It uses WIL for RAII-style handle management. ```cpp #include #include #include // HCS API header file #include #include #include #include #pragma comment(lib, "computecore.lib") // // Helper RAII objects around HCS system handle and HCS operation handle // HCS_OPERATION handle closed by HcsCloseOperation // HCS_SYSTEM handle closed by HcsCloseComputeSystem // using unique_hcs_operation = wil::unique_any; using unique_hcs_system = wil::unique_any; // // Create a virtual machine // static constexpr wchar_t c_VmConfiguration[] = LR"( { "SchemaVersion": { "Major": 2, "Minor": 1 }, "Owner": "Sample", "ShouldTerminateOnLastHandleClosed": true, "VirtualMachine": { "Chipset": { "Uefi": { "BootThis": { "DevicePath": "Primary disk", "DiskNumber": 0, "DeviceType": "ScsiDrive" } } }, "ComputeTopology": { "Memory": { "Backing": "Virtual", "SizeInMB": 2048 }, "Processor": { "Count": 2 } }, "Devices": { "Scsi": { "Primary disk": { "Attachments": { "0": { "Type": "VirtualDisk", "Path": "c:\\HCS_Test\\utilityvm.vhdx" } } } } } } })"; // After setting up the JSON document, we need to call into the HCS to create // the compute system, in this case, an HCS VM. // This operation doesn't need callback unique_hcs_operation operation(HcsCreateOperation(nullptr, nullptr)); unique_hcs_system system; THROW_IF_FAILED(HcsCreateComputeSystem( L"Sample", // Unique Id c_VmConfiguration, operation.get(), nullptr, // This parameter is not supported yet, always pass NULL &system)); // We need to wait on the operation explicitly because no callback was setup // Result document from waiting on the operation would usually contain // a JSON blob with either error attribution or operation specific result data // (for example, compute system properties if the operation was used to call // ::HcsGetComputeSystemProperties). // Result document isn't necessarily set all the time, so make sure to check for that! wil::unique_hlocal_string resultDoc; THROW_IF_FAILED_MSG(HcsWaitForOperationResult(operation.get(), INFINITE, &resultDoc), "ResultDoc: %ws", resultDoc.get()); // For a successful HcsCreateComputeSystem, result document doesn't have anything. // // Now that the HCS VM is created, we need to start it! // THROW_IF_FAILED(HcsStartComputeSystem( system.get(), operation.get(), nullptr)); // This parameter is not currently supported, pass NULL. THROW_IF_FAILED_MSG(HcsWaitForOperationResult(operation.get(), INFINITE, &resultDoc), "ResultDoc: %ws", resultDoc.get()); // // Get the VM memory property and print the result out // static constexpr wchar_t c_VmQuery[] = LR"( { "PropertyTypes":[ "Memory" ] })"; ``` -------------------------------- ### HcsCreateProcess Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcscreateprocess Starts a process in a compute system. ```APIDOC ## HcsCreateProcess ### Description Starts a process in a compute system. ### Syntax ```cpp HRESULT WINAPI HcsCreateProcess( _In_ HCS_SYSTEM computeSystem, _In_ PCWSTR processParameters, _In_ HCS_OPERATION operation, _In_opt_ const SECURITY_DESCRIPTOR* securityDescriptor, _Out_ HCS_PROCESS* process ); ``` ### Parameters - **computeSystem** (HCS_SYSTEM) - Required - The handle to the compute system in which to start the process. - **processParameters** (PCWSTR) - Required - JSON document of ProcessParameters specifying the command line and environment for the process. - **operation** (HCS_OPERATION) - Required - Handle to the operation that tracks the process creation operation. - **securityDescriptor** (const SECURITY_DESCRIPTOR*) - Optional - Reserved for future use, must be NULL. - **process** (HCS_PROCESS*) - Required - Receives the HCS_PROCESS handle to the newly created process. ### Return Values - **HRESULT** - Returns S_OK if the operation started successfully. ``` -------------------------------- ### HcsStartComputeSystem Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcsstartcomputesystem Starts a compute system using the provided system and operation handles. ```APIDOC ## HcsStartComputeSystem ### Description Starts a compute system. Callers are expected to get the operation's result using HcsWaitForOperationResult or HcsGetOperationResult. ### Syntax `HRESULT WINAPI HcsStartComputeSystem(HCS_SYSTEM computeSystem, HCS_OPERATION operation, PCWSTR options);` ### Parameters - **computeSystem** (HCS_SYSTEM) - Required - The handle to the compute system to start. - **operation** (HCS_OPERATION) - Required - The handle to the operation that tracks the start operation. - **options** (PCWSTR) - Optional - Reserved for future use. Must be NULL. ### Return Values - **HRESULT** - Returns S_OK if the operation started successfully. ``` -------------------------------- ### WHvSetupPartition Source: https://learn.microsoft.com/en-us/virtualization/api/hypervisor-platform/funcs/whvsetuppartition Sets up the partition, which causes the actual partition to be created in the hypervisor. ```APIDOC ## WHvSetupPartition ### Description Sets up the partition, which causes the actual partition to be created in the hypervisor. This function must be called after the partition object is created and its initial properties are configured. ### Syntax ```c HRESULT WINAPI WHvSetupPartition( _In_ WHV_PARTITION_HANDLE Partition ); ``` ### Parameters - **Partition** (WHV_PARTITION_HANDLE) - Required - Handle to the partition object. ### Return Value - **S_OK**: The function succeeded. - **WHV_E_INVALID_PARTITION_CONFIG**: A required partition property was not configured appropriately before setup. ### Requirements - **Header**: WinHvPlatform.h - **Library**: WinHvPlatform.lib - **DLL**: WinHvPlatform.dll - **Architecture**: x64, Arm64 ``` -------------------------------- ### WHvStartPartitionMigration Source: https://learn.microsoft.com/en-us/virtualization/api/hypervisor-platform/funcs/whvstartpartitionmigration Begins migrating a partition on the source host. ```APIDOC ## WHvStartPartitionMigration ### Description Begins migrating a partition on the source host. This function serializes the partition's state, properties, virtual processors, doorbells, and virtual PCI devices. ### Syntax ```c HRESULT WINAPI WHvStartPartitionMigration( _In_ WHV_PARTITION_HANDLE Partition, _Out_ HANDLE* MigrationHandle ); ``` ### Parameters - **Partition** (WHV_PARTITION_HANDLE) - Required - Handle to the partition object to migrate. - **MigrationHandle** (HANDLE*) - Required - Receives a handle that represents the in-progress migration to be transferred to the destination process. ### Return Value - **S_OK**: The function succeeded. - **HRESULT_FROM_WIN32(ERROR_INVALID_STATE)**: The partition is already involved in a migration. ### Requirements - **Header**: WinHvPlatform.h - **Library**: WinHvPlatform.lib - **DLL**: WinHvPlatform.dll ``` -------------------------------- ### HcnDeleteEndpoint Source: https://learn.microsoft.com/en-us/virtualization/api/hcn/reference/hcndeleteendpoint Deletes an endpoint identified by its GUID. ```APIDOC ## HcnDeleteEndpoint ### Description Deletes an endpoint. ### Syntax ```cpp HRESULT WINAPI HcnDeleteEndpoint( _In_ REFGUID Id, _Outptr_opt_ PWSTR* ErrorRecord ); ``` ### Parameters - **Id** (REFGUID) - Required - Id of the endpoint to delete. - **ErrorRecord** (PWSTR*) - Optional - Receives a JSON document with extended errorCode information. The caller must release the buffer using CoTaskMemFree. ### Return Values - **HRESULT** - Returns an HRESULT indicating success or failure. ### Requirements - **Minimum supported client**: Windows 10, version 1809 - **Minimum supported server**: Windows Server 2019 - **Header**: ComputeNetwork.h - **Library**: ComputeNetwork.lib - **Dll**: ComputeNetwork.dll ``` -------------------------------- ### WHvSetupPartition function syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hypervisor-platform/funcs/whvsetuppartition The function signature for initializing a partition handle. ```C HRESULT WINAPI WHvSetupPartition( _In_ WHV_PARTITION_HANDLE Partition ); ``` -------------------------------- ### HcnDeleteNetwork Source: https://learn.microsoft.com/en-us/virtualization/api/hcn/reference/hcndeletenetwork Deletes a network identified by its GUID. ```APIDOC ## HcnDeleteNetwork ### Description Deletes a network from the Host Compute Network. ### Syntax ```cpp HRESULT WINAPI HcnDeleteNetwork( _In_ REFGUID Id, _Outptr_opt_ PWSTR* ErrorRecord ); ``` ### Parameters - **Id** (REFGUID) - Required - The unique identifier of the network to delete. - **ErrorRecord** (PWSTR*) - Optional - Receives a JSON document with extended error information. The caller must release this buffer using CoTaskMemFree. ### Return Values - **HRESULT** - Returns an HRESULT indicating success or failure. ``` -------------------------------- ### HcnDeleteNamespace Source: https://learn.microsoft.com/en-us/virtualization/api/hcn/reference/hcndeletenamespace Deletes a namespace identified by the provided GUID. ```APIDOC ## HcnDeleteNamespace ### Description Deletes a namespace from the Host Compute Network. ### Syntax ```cpp HRESULT WINAPI HcnDeleteNamespace( _In_ REFGUID Id, _Outptr_opt_ PWSTR* ErrorRecord ); ``` ### Parameters - **Id** (REFGUID) - Required - The unique identifier of the namespace to delete. - **ErrorRecord** (PWSTR*) - Optional - Receives a JSON document with extended error information. The caller must release this buffer using CoTaskMemFree. ### Return Values - **HRESULT** - Returns S_OK if the operation succeeds, or an error code otherwise. ``` -------------------------------- ### HDV_PCI_DEVICE_START Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hdv/hdvpcidevicestart Callback function signature for notifying an emulated device of VM processor startup. ```APIDOC ## HDV_PCI_DEVICE_START ### Description Function called to notify the emulated device that the virtual processors of the VM are about to start. ### Syntax ```cpp typedef HRESULT (CALLBACK *HDV_PCI_DEVICE_START)( _In_opt_ void* DeviceContext ); ``` ### Parameters - **DeviceContext** (void*) - Required - Context pointer that was supplied to HdvCreateDeviceInstance ### Return Values - **S_OK** - Returned if function succeeds. - **HRESULT** - An error code is returned if the function fails. ### Requirements - **Minimum supported client**: Windows 10, version 1607 - **Minimum supported server**: Windows Server 2016 - **Library**: ComputeCore.lib - **Dll**: ComputeCore.dll ``` -------------------------------- ### HcnDeleteGuestNetworkService Source: https://learn.microsoft.com/en-us/virtualization/api/hcn/reference/hcndeleteguestnetworkservice Deletes a guest network service using its GUID. ```APIDOC ## HcnDeleteGuestNetworkService ### Description Deletes a guest network service. ### Syntax ```cpp HRESULT WINAPI HcnDeleteGuestNetworkService( _In_ REFGUID Id, _Outptr_opt_ PWSTR* ErrorRecord ); ``` ### Parameters - **Id** (REFGUID) - Required - Id of the guest network service to delete. - **ErrorRecord** (PWSTR*) - Optional - Receives a JSON document with extended errorCode information. The caller must release the buffer using CoTaskMemFree. ### Return Values - **HRESULT** - Returns an HRESULT indicating success or failure. ### Requirements - **Minimum supported client**: Windows 10, version 1809 - **Minimum supported server**: Windows Server 2019 - **Header**: ComputeNetwork.h - **Library**: ComputeNetwork.lib - **Dll**: ComputeNetwork.dll ``` -------------------------------- ### HdvCreateDeviceInstance Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hdv/hdvcreatedeviceinstance Creates a device instance in the current host and associates it with a device emulation interface and context. ```APIDOC ## HdvCreateDeviceInstance ### Description Creates a device instance in the current host and associates it with a device emulation interface and context. ### Syntax ```cpp HRESULT WINAPI HdvCreateDeviceInstance( _In_ HDV_HOST DeviceHost, _In_ HDV_DEVICE_TYPE DeviceType, _In_ const GUID* DeviceClassId, _In_ const GUID* DeviceInstanceId, _In_ const VOID* DeviceInterface, _In_opt_ void* DeviceContext, _Out_ HDV_DEVICE* DeviceHandle ); ``` ### Parameters - **DeviceHost** (HDV_HOST) - Handle to the device host in which to create the new device. - **DeviceType** (HDV_DEVICE_TYPE) - Specifies the type of the device instance to create. - **DeviceClassId** (const GUID*) - Supplies the client-defined class ID of the device instance to create. - **DeviceInstanceId** (const GUID*) - Supplies the client-defined instance ID of the device instance to create. - **DeviceInterface** (const VOID*) - Supplies a function table representing the interface exposed by the device instance. - **DeviceContext** (void*) - Optional opaque context pointer supplied to the device instance callbacks. - **DeviceHandle** (HDV_DEVICE*) - Receives a handle to the created device instance. ### Return Values - **S_OK** - Returned if function succeeds. - **HRESULT** - An error code is returned if the function fails. ``` -------------------------------- ### HcsStartComputeSystem function signature Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcsstartcomputesystem The C++ function signature for starting a compute system. ```C++ HRESULT WINAPI HcsStartComputeSystem( _In_ HCS_SYSTEM computeSystem, _In_ HCS_OPERATION operation, _In_opt_ PCWSTR options ); ``` -------------------------------- ### WHvCreateVpciDevice Source: https://learn.microsoft.com/en-us/virtualization/api/hypervisor-platform/funcs/whvcreatevpcidevice Creates a virtual PCI (VPCI) device and assigns its resources to a partition. ```APIDOC ## WHvCreateVpciDevice ### Description Creates a virtual PCI (VPCI) device and assigns the physical or virtual resources identified by VpciResource to the partition. This function programs the IOMMU so that the PCI requestor ID of the function backing the device is assigned to the partition domain. ### Syntax ```c HRESULT WINAPI WHvCreateVpciDevice( _In_ WHV_PARTITION_HANDLE Partition, _In_ UINT64 LogicalDeviceId, _In_ HANDLE VpciResource, _In_ WHV_CREATE_VPCI_DEVICE_FLAGS Flags, _In_opt_ HANDLE NotificationEventHandle ); ``` ### Parameters - **Partition** (WHV_PARTITION_HANDLE) - Required - Handle to the partition object. - **LogicalDeviceId** (UINT64) - Required - Specifies a unique identifier for the device within the scope of the partition. - **VpciResource** (HANDLE) - Required - Handle to a previously allocated VPCI resource that backs the virtual device. - **Flags** (WHV_CREATE_VPCI_DEVICE_FLAGS) - Required - Specifies optional characteristics of the device to create. - **NotificationEventHandle** (HANDLE) - Optional - Handle to an event that is signaled to notify the caller of asynchronous events associated with the VPCI device. ### Return Value Returns S_OK if the function succeeds. ``` -------------------------------- ### HCN_PORT_RANGE_RESERVATION Structure Definition Source: https://learn.microsoft.com/en-us/virtualization/api/hcn/reference/hcn_port_range_reservation Defines the starting and ending ports for a reservation range. Both values are inclusive. ```C++ typedef struct tagHCN_PORT_RANGE_RESERVATION { // start and end are inclusive USHORT startingPort; USHORT endingPort; } HCN_PORT_RANGE_RESERVATION; ``` -------------------------------- ### Create and Grant VM Access to a File Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/utilityfunctionsample Creates an empty runtime state file and grants the specified compute system access to it. Requires the compute system ID to be previously initialized. ```cpp // This assumes "Sample" has been used as the id for a compute system when created through HcsCreateComputeSystem THROW_IF_FAILED(HcsCreateEmptyRuntimeStateFile(L"emptyfile.vmrs")); THROW_IF_FAILED(HcsGrantVmAccess(L"Sample", L"emptyfile.vmrs")); ``` -------------------------------- ### LocateSavedStateFiles Source: https://learn.microsoft.com/en-us/virtualization/api/vm-dump-provider/reference/locatesavedstatefiles Locates the saved state file(s) for a given VM and/or snapshot. This function requires Hyper-V to be installed. ```APIDOC ## HRESULT LocateSavedStateFiles(LPCWSTR VmName, LPCWSTR SnapshotName, LPWSTR* BinPath, LPWSTR* VsvPath, LPWSTR* VmrsPath) ### Description Locates the saved state file(s) for a given VM and/or snapshot. This function uses WMI and the V1 or V2 virtualization namespace. ### Parameters - **VmName** (LPCWSTR) - Required - The name of the VM for which the saved state file will be located. - **SnapshotName** (LPCWSTR) - Optional - The name of the snapshot to locate its saved state file in relation to the given VM name. - **BinPath** (LPWSTR*) - Required - Returns a pointer to a NULL-terminated string containing the full path name to the BIN file. The caller must call LocalFree on the returned pointer. - **VsvPath** (LPWSTR*) - Required - Returns a pointer to a NULL-terminated string containing the full path name to the VSV file. The caller must call LocalFree on the returned pointer. - **VmrsPath** (LPWSTR*) - Required - Returns a pointer to a NULL-terminated string containing the full path name to the VMRS file. The caller must call LocalFree on the returned pointer. ### Return Value - **S_OK** - Success. - **E_OUTOFMEMORY** - Insufficient memory to return the full path(s). - **HRESULT** - Other failure codes. ``` -------------------------------- ### Define WHV_PARTITION_PROPERTY union Source: https://learn.microsoft.com/en-us/virtualization/api/hypervisor-platform/funcs/whvpartitionpropertydatatypes The primary union used for getting and setting partition properties, containing architecture-specific fields. ```C typedef union WHV_PARTITION_PROPERTY { WHV_EXTENDED_VM_EXITS ExtendedVmExits; WHV_PROCESSOR_FEATURES ProcessorFeatures; WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS SyntheticProcessorFeaturesBanks; UINT8 ProcessorClFlushSize; UINT32 ProcessorCount; BOOL SeparateSecurityDomain; BOOL NestedVirtualization; UINT64 ProcessorClockFrequency; WHV_PROCESSOR_FEATURES_BANKS ProcessorFeaturesBanks; UINT64 ReferenceTime; USHORT PrimaryNumaNode; UINT32 CpuReserve; UINT32 CpuCap; UINT32 CpuWeight; UINT64 CpuGroupId; UINT32 ProcessorFrequencyCap; BOOL AllowDeviceAssignment; BOOL DisableSmt; UINT32 PhysicalAddressWidth; #if defined(_AMD64_) WHV_PROCESSOR_XSAVE_FEATURES ProcessorXsaveFeatures; UINT32 CpuidExitList[1]; UINT64 ExceptionExitBitmap; BOOL ApicRemoteRead; WHV_X64_MSR_EXIT_BITMAP X64MsrExitBitmap; WHV_PROCESSOR_PERFMON_FEATURES ProcessorPerfmonFeatures; UINT64 InterruptClockFrequency; WHV_X64_CPUID_RESULT CpuidResultList[1]; WHV_X64_CPUID_RESULT2 CpuidResultList2[1]; WHV_MSR_ACTION_ENTRY MsrActionList[1]; WHV_MSR_ACTION UnimplementedMsrAction; WHV_X64_LOCAL_APIC_EMULATION_MODE LocalApicEmulationMode; #elif defined(_ARM64_) WHV_ARM64_IC_PARAMETERS Arm64IcParameters; #endif } WHV_PARTITION_PROPERTY; ``` -------------------------------- ### HcsSetupBaseOSLayer Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcssetupbaseoslayer Sets up a base OS layer for use on a host. ```APIDOC ## HcsSetupBaseOSLayer ### Description Sets up a base OS layer for the use on a host. The base OS layer is the first layer in the set of layers used by a container or virtual machine. ### Syntax ```cpp HRESULT WINAPI HcsSetupBaseOSLayer( _In_ PCWSTR layerPath, _In_ HANDLE vhdHandle, _In_ PCWSTR options ); ``` ### Parameters - **layerPath** (PCWSTR) - Required - Path to the root of the base OS layer. - **vhdHandle** (HANDLE) - Required - The handle to a VHD. - **options** (PCWSTR) - Required - Optional JSON document of OsLayerOptions describing options for setting up the layer. ### Return Values - **HRESULT** - Returns the status of the operation. ``` -------------------------------- ### Get Host Service Properties Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/servicesample Retrieves specific service properties like memory usage using HcsGetServiceProperties. ```C++ static constexpr wchar_t c_ServicePropertyQuery[] = LR"( { "PropertyTypes": [ "Memory" ] })"; wil::unique_hlocal_string resultDoc; THROW_IF_FAILED(HcsGetServiceProperties(c_ServicePropertyQuery, &resultDoc)); std::wcout << L"Service property is " << resultDoc.get() << std::endl; ``` -------------------------------- ### HDV_PCI_DEVICE_START Callback Syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hdv/hdvpcidevicestart Defines the function signature for the HDV_PCI_DEVICE_START callback. ```C++ typedef HRESULT (CALLBACK *HDV_PCI_DEVICE_START)( _In_opt_ void* DeviceContext ); ``` -------------------------------- ### HcnOpenNamespace function syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hcn/reference/hcnopennamespace The function signature for opening a namespace, requiring a GUID identifier and providing a handle for the namespace and an optional error record. ```C++ HRESULT WINAPI HcnOpenNamespace( _In_ REFGUID Id, _Out_ PHCN_NAMESPACE Namespace, _Outptr_opt_ PWSTR* ErrorRecord ); ``` -------------------------------- ### HDV_PCI_DEVICE_INITIALIZE Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hdv/hdvpcideviceinitialize Callback function signature for initializing an emulated PCI device. ```APIDOC ## HDV_PCI_DEVICE_INITIALIZE ### Description Function invoked to initialize the emulated device. It is called as the VM is powered on. ### Syntax ```cpp typedef HRESULT (CALLBACK *HDV_PCI_DEVICE_INITIALIZE)( _In_opt_ void* DeviceContext ); ``` ### Parameters - **DeviceContext** (void*) - Context pointer that was supplied to HdvCreateDeviceInstance. ### Return Values - **S_OK** - Returned if function succeeds. - **HRESULT** - An error code is returned if the function fails. ### Requirements - **Minimum supported client**: Windows 10, version 1607 - **Minimum supported server**: Windows Server 2016 - **Library**: ComputeCore.lib - **Dll**: ComputeCore.dll ``` -------------------------------- ### HcnOpenLoadBalancer Function Syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hcn/reference/hcnopenloadbalancer The function signature for opening a load balancer, requiring a GUID identifier and providing a handle and optional error record. ```C++ HRESULT WINAPI HcnOpenLoadBalancer( _In_ REFGUID Id, _Out_ PHCN_LOADBALANCER LoadBalancer, _Outptr_opt_ PWSTR* ErrorRecord ); ``` -------------------------------- ### HdvCreateDeviceInstance C++ Syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hdv/hdvcreatedeviceinstance The function signature for creating a device instance in the host. ```cpp HRESULT WINAPI HdvCreateDeviceInstance( _In_ HDV_HOST DeviceHost, _In_ HDV_DEVICE_TYPE DeviceType, _In_ const GUID* DeviceClassId, _In_ const GUID* DeviceInstanceId, _In_ const VOID* DeviceInterface, _In_opt_ void* DeviceContext, _Out_ HDV_DEVICE* DeviceHandle ); ``` -------------------------------- ### WHvCreateVirtualProcessor Syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hypervisor-platform/funcs/whvcreatevirtualprocessor Function signature for creating a virtual processor in a partition. ```C HRESULT WINAPI WHvCreateVirtualProcessor( _In_ WHV_PARTITION_HANDLE Partition, _In_ UINT32 VpIndex, _In_ UINT32 Flags ); ``` -------------------------------- ### HdvInitializeDeviceHostForProxy function syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hdv/hdvinitializedevicehostforproxy Defines the function signature for initializing the device host. ```C++ HRESULT WINAPI HdvInitializeDeviceHostForProxy( _In_ const GUID* VmId, _In_ PVOID ProxyInterface_IUnknown, _Out_ HDV_HOST* DeviceHostHandle ); ``` -------------------------------- ### WHvStartPartitionMigration function syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hypervisor-platform/funcs/whvstartpartitionmigration The function signature for initiating a partition migration in the Windows Hypervisor Platform. ```C HRESULT WINAPI WHvStartPartitionMigration( _In_ WHV_PARTITION_HANDLE Partition, _Out_ HANDLE* MigrationHandle ); ``` -------------------------------- ### WHvCreateVirtualProcessor Source: https://learn.microsoft.com/en-us/virtualization/api/hypervisor-platform/funcs/whvcreatevirtualprocessor Creates a new virtual processor in a partition. ```APIDOC ## WHvCreateVirtualProcessor ### Syntax ```c HRESULT WINAPI WHvCreateVirtualProcessor( _In_ WHV_PARTITION_HANDLE Partition, _In_ UINT32 VpIndex, _In_ UINT32 Flags ); ``` ### Parameters - **Partition** (WHV_PARTITION_HANDLE) - Required - Handle to the partition object. - **VpIndex** (UINT32) - Required - Specifies the index of the new virtual processor. - **Flags** (UINT32) - Required - Unused, must be zero. ### Return Value Returns S_OK if the function succeeds. ### Remarks On x64, the index of the virtual processor is used to set the APIC ID of the processor. ``` -------------------------------- ### WHvEmulatorTryIoEmulation and WHvEmulatorTryMmioEmulation Syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hypervisor-instruction-emulator/funcs/whvemulatortryemulation Function signatures for attempting I/O and MMIO emulation within the Windows Hypervisor emulator. ```C++ HRESULT WINAPI WHvEmulatorTryIoEmulation( _In_ WHV_EMULATOR_HANDLE Emulator, _In_ VOID* Context, _In_ const WHV_VP_EXIT_CONTEXT* VpContext, _In_ const WHV_X64_IO_PORT_ACCESS_CONTEXT* IoInstructionContext, _Out_ WHV_EMULATOR_STATUS* EmulatorReturnStatus ); HRESULT WINAPI WHvEmulatorTryMmioEmulation( _In_ WHV_EMULATOR_HANDLE Emulator, _In_ VOID* Context, _In_ const WHV_VP_EXIT_CONTEXT* VpContext, _In_ const WHV_MEMORY_ACCESS_CONTEXT* MmioInstructionContext, _Out_ WHV_EMULATOR_STATUS* EmulatorReturnStatus ); ``` -------------------------------- ### HcsSetupBaseOSVolume Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcssetupbaseosvolume Sets up the base OS layer for use on a host based on the mounted volume (VHD). ```APIDOC ## HcsSetupBaseOSVolume ### Description This function sets up the base OS layer for the use on a host based on the mounted volume (VHD). ### Syntax ```cpp HRESULT WINAPI HcsSetupBaseOSVolume( _In_ PCWSTR layerPath, _In_ PCWSTR volumePath, _In_ PCWSTR options ); ``` ### Parameters - **layerPath** (PCWSTR) - Required - Path to the root of the base OS layer. - **volumePath** (PCWSTR) - Required - The handle to a VHD. - **options** (PCWSTR) - Optional - JSON document of OsLayerOptions describing options for setting up the layer. ### Return Values - **HRESULT** - Returns an HRESULT indicating success or failure. ``` -------------------------------- ### HcsImportLayer Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcsimportlayer Imports a container layer and sets it up for use on boot. ```APIDOC ## HcsImportLayer ### Description Imports a container layer and sets it up for use on boot. This function is used by an application to setup a container layer that was copied in a transport format to the host. ### Syntax ```cpp HRESULT WINAPI HcsImportLayer( _In_ PCWSTR layerPath, _In_ PCWSTR sourceFolderPath, _In_ PCWSTR layerData ); ``` ### Parameters - **layerPath** (PCWSTR) - Destination path for the container layer. - **sourceFolderPath** (PCWSTR) - Source path that contains the downloaded layer files. - **layerData** (PCWSTR) - JSON document of layerData providing the locations of the antecedent layers that are used by the imported layer. ### Return Values - **HRESULT** - Returns an HRESULT indicating success or failure. ``` -------------------------------- ### HcsCreateEmptyGuestStateFile Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcscreateemptygueststatefile Creates an empty guest-state file (.vmgs) for a VM. ```APIDOC ## HcsCreateEmptyGuestStateFile ### Description Creates an empty guest-state file (.vmgs) for a VM. This file is required for VMs that are expected to be persisted and restarted multiple times. ### Syntax ```cpp HRESULT WINAPI HcsCreateEmptyGuestStateFile( _In_ PCWSTR guestStateFilePath ); ``` ### Parameters - **guestStateFilePath** (PCWSTR) - Full path to the guest-state file to create. ### Return Values - **HRESULT** - Returns an HRESULT indicating success or failure. ### Requirements - **Minimum supported client**: Windows 10, version 1809 - **Minimum supported server**: Windows Server 2019 - **Header**: ComputeCore.h - **Library**: ComputeCore.lib - **Dll**: ComputeCore.dll ``` -------------------------------- ### HcsOpenComputeSystem Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcsopencomputesystem Opens a handle to an existing compute system. ```APIDOC ## HcsOpenComputeSystem ### Description Opens a handle to an existing compute system. ### Syntax ```cpp HRESULT WINAPI HcsOpenComputeSystem( _In_ PCWSTR id, _In_ DWORD requestedAccess, _Out_ HCS_SYSTEM* computeSystem ); ``` ### Parameters - **id** (PCWSTR) - Required - Unique Id identifying the compute system. - **requestedAccess** (DWORD) - Required - Reserved for future use, must be GENERIC_ALL. - **computeSystem** (HCS_SYSTEM*) - Required - Receives a handle to the compute system. It is the responsibility of the caller to release the handle using HcsCloseComputeSystem once it is no longer in use. ### Return Values The function returns an HRESULT. ``` -------------------------------- ### HcsGetProcessInfo Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcsgetprocessinfo Retrieves the initial startup information of a process in a compute system. ```APIDOC ## HcsGetProcessInfo ### Description Returns the initial startup information of a process in a compute system. ### Syntax ```cpp HRESULT WINAPI HcsGetProcessInfo( _In_ HCS_PROCESS process, _In_ HCS_OPERATION operation ); ``` ### Parameters - **process** (HCS_PROCESS) - Required - The handle to the process to query. - **operation** (HCS_OPERATION) - Required - The handle to the operation that tracks the process. ### Return Values - **HRESULT** - Returns S_OK if the operation started successfully. Callers should use HcsWaitForOperationResultAndProcessInfo or HcsGetOperationResultAndProcessInfo to retrieve the result. ### Requirements - **Header**: ComputeCore.h - **Library**: ComputeCore.lib - **Dll**: ComputeCore.dll - **Minimum supported client**: Windows 10, version 1809 - **Minimum supported server**: Windows Server 2019 ``` -------------------------------- ### HDV_PCI_DEVICE_INITIALIZE Callback Syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hdv/hdvpcideviceinitialize Defines the function signature for the device initialization callback. ```C++ typedef HRESULT (CALLBACK *HDV_PCI_DEVICE_INITIALIZE)( _In_opt_ void* DeviceContext ); ``` -------------------------------- ### WHvCreateVirtualProcessor2 Syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hypervisor-platform/funcs/whvcreatevirtualprocessor2 Defines the structures and function signature for creating a virtual processor with properties. ```C typedef enum WHV_VIRTUAL_PROCESSOR_PROPERTY_CODE { WHvVirtualProcessorPropertyCodeNumaNode = 0x00000000, } WHV_VIRTUAL_PROCESSOR_PROPERTY_CODE; typedef struct WHV_VIRTUAL_PROCESSOR_PROPERTY { WHV_VIRTUAL_PROCESSOR_PROPERTY_CODE PropertyCode; UINT32 Reserved; union { USHORT NumaNode; UINT64 Padding; }; } WHV_VIRTUAL_PROCESSOR_PROPERTY; HRESULT WINAPI WHvCreateVirtualProcessor2( _In_ WHV_PARTITION_HANDLE Partition, _In_ UINT32 VpIndex, _In_reads_(PropertyCount) const WHV_VIRTUAL_PROCESSOR_PROPERTY* Properties, _In_ UINT32 PropertyCount ); ``` -------------------------------- ### WHvAcceptPartitionMigration Source: https://learn.microsoft.com/en-us/virtualization/api/hypervisor-platform/funcs/whvacceptpartitionmigration Accepts a migrating partition on the destination host and returns a handle to the newly created partition object. ```APIDOC ## WHvAcceptPartitionMigration ### Syntax ```c HRESULT WINAPI WHvAcceptPartitionMigration( _In_ HANDLE MigrationHandle, _Out_ WHV_PARTITION_HANDLE* Partition ); ``` ### Parameters - **MigrationHandle** (HANDLE) - Specifies the migration handle obtained from WHvStartPartitionMigration. - **Partition** (WHV_PARTITION_HANDLE*) - Receives the handle to the newly created partition object on the destination. ### Return Value - **S_OK**: Success. - **E_INVALIDARG**: Serialized partition data cannot be parsed. - **HRESULT_FROM_WIN32(ERROR_INVALID_DATA)**: Transferred handles are missing or invalid. - **HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)**: Migration version not supported by the platform. ### Remarks This function reconstructs the partition as a new object on the destination host. The partition is created in a migrating state where only WHvSetupPartition and WHvDeletePartition are permitted until migration completion. On success, the function closes the MigrationHandle. ``` -------------------------------- ### WHvMapGpaRange Syntax and Definitions Source: https://learn.microsoft.com/en-us/virtualization/api/hypervisor-platform/funcs/whvmapgparange Includes the type definitions for guest addresses, the mapping flags enumeration, and the function signature for WHvMapGpaRange. ```C // Guest physical or virtual address typedef UINT64 WHV_GUEST_PHYSICAL_ADDRESS; typedef UINT64 WHV_GUEST_VIRTUAL_ADDRESS; // Flags used by WHvMapGpaRange typedef enum WHV_MAP_GPA_RANGE_FLAGS { WHvMapGpaRangeFlagNone = 0x00000000, WHvMapGpaRangeFlagRead = 0x00000001, WHvMapGpaRangeFlagWrite = 0x00000002, WHvMapGpaRangeFlagExecute = 0x00000004, WHvMapGpaRangeFlagTrackDirtyPages = 0x00000008, } WHV_MAP_GPA_RANGE_FLAGS; // Enables bitwise operators on the WHV_MAP_GPA_RANGE_FLAGS enumeration. DEFINE_ENUM_FLAG_OPERATORS(WHV_MAP_GPA_RANGE_FLAGS); HRESULT WINAPI WHvMapGpaRange( _In_ WHV_PARTITION_HANDLE Partition, _In_ VOID* SourceAddress, _In_ WHV_GUEST_PHYSICAL_ADDRESS GuestAddress, _In_ UINT64 SizeInBytes, _In_ WHV_MAP_GPA_RANGE_FLAGS Flags ); ``` -------------------------------- ### WHvCreatePartition Syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hypervisor-platform/funcs/whvcreatepartition Defines the function signature and the handle type for the Windows Hypervisor Platform partition. ```C typedef VOID* WHV_PARTITION_HANDLE; HRESULT WINAPI WHvCreatePartition( _Out_ WHV_PARTITION_HANDLE* Partition ); ``` -------------------------------- ### HcsSetupBaseOSLayer Syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcssetupbaseoslayer The function signature for setting up a base OS layer, requiring a path, VHD handle, and optional configuration. ```C++ HRESULT WINAPI HcsSetupBaseOSLayer( _In_ PCWSTR layerPath, _In_ HANDLE vhdHandle, _In_ PCWSTR options ); ``` -------------------------------- ### WHvCreatePartition Source: https://learn.microsoft.com/en-us/virtualization/api/hypervisor-platform/funcs/whvcreatepartition Creates a new partition object and returns a handle for further configuration. ```APIDOC ## WHvCreatePartition ### Description Creates a new partition object. This function only creates the object and does not yet create the actual partition in the hypervisor; the partition must be configured using WHvSetPartitionProperty and then initialized with WHvSetupPartition. ### Syntax ```c HRESULT WINAPI WHvCreatePartition( _Out_ WHV_PARTITION_HANDLE* Partition ); ``` ### Parameters - **Partition** (WHV_PARTITION_HANDLE*) - Receives the partition handle to the newly created partition object. All operations on the partition are performed through this handle. ### Return Value - **S_OK** - The function succeeded. ### Requirements - **Header**: WinHvPlatform.h - **Library**: WinHvPlatform.lib - **DLL**: WinHvPlatform.dll - **Architecture**: x64, Arm64 ``` -------------------------------- ### WHvGetCapability Source: https://learn.microsoft.com/en-us/virtualization/api/hypervisor-platform/funcs/whvgetcapability Queries the capabilities of the API implementation, the hypervisor, and the system's processor. ```APIDOC ## WHvGetCapability ### Description Queries the capabilities of the API implementation, the hypervisor, and the system's processor. ### Syntax ```c HRESULT WHvGetCapability( WHV_CAPABILITY_CODE CapabilityCode, VOID* CapabilityBuffer, UINT32 CapabilityBufferSizeInBytes, UINT32* WrittenSizeInBytes ); ``` ### Parameters - **CapabilityCode** (WHV_CAPABILITY_CODE) - The capability to query. - **CapabilityBuffer** (VOID*) - A pointer to a buffer that receives the capability information. - **CapabilityBufferSizeInBytes** (UINT32) - The size of the buffer in bytes. - **WrittenSizeInBytes** (UINT32*) - A pointer to a variable that receives the number of bytes written to the buffer. ``` -------------------------------- ### HdvInitializeDeviceHostForProxy Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hdv/hdvinitializedevicehostforproxy Initializes the device emulator host in the caller's process and associates it with the specified proxy. A successful call must be balanced by a call to HdvTeardownDeviceHost on the same thread. ```APIDOC ## HdvInitializeDeviceHostForProxy ### Description Initializes the device emulator host in the caller's process and associates it with the specified proxy. The proxy is responsible for associating with the compute system. ### Syntax ```cpp HRESULT WINAPI HdvInitializeDeviceHostForProxy( _In_ const GUID* VmId, _In_ PVOID ProxyInterface_IUnknown, _Out_ HDV_HOST* DeviceHostHandle ); ``` ### Parameters - **VmId** (const GUID*) - The unique identifier of the compute system. - **ProxyInterface_IUnknown** (PVOID) - The interface used to communicate with the proxy. - **DeviceHostHandle** (HDV_HOST*) - A void pointer that receives a handle to the created device host. ### Return Value - **S_OK** - The function succeeded. - **HRESULT error code** - The function failed. ### Requirements - **Minimum supported client**: Windows 10, version 1607 - **Minimum supported server**: Windows Server 2016 - **Library**: vmdevicehost.lib - **Dll**: vmdevicehost.dll ``` -------------------------------- ### WHvCreateVirtualProcessor2 Source: https://learn.microsoft.com/en-us/virtualization/api/hypervisor-platform/funcs/whvcreatevirtualprocessor2 Creates a new virtual processor in a partition with optional creation-time properties. ```APIDOC ## WHvCreateVirtualProcessor2 ### Description Creates a new virtual processor in a partition with optional creation-time properties. ### Syntax ```c HRESULT WINAPI WHvCreateVirtualProcessor2( _In_ WHV_PARTITION_HANDLE Partition, _In_ UINT32 VpIndex, _In_reads_(PropertyCount) const WHV_VIRTUAL_PROCESSOR_PROPERTY* Properties, _In_ UINT32 PropertyCount ); ``` ### Parameters - **Partition** (WHV_PARTITION_HANDLE) - Required - Handle to the partition object. - **VpIndex** (UINT32) - Required - Specifies the index of the new virtual processor. - **Properties** (WHV_VIRTUAL_PROCESSOR_PROPERTY*) - Required - Specifies an array of properties to apply to the new virtual processor at creation time. May be NULL when PropertyCount is zero. - **PropertyCount** (UINT32) - Required - Specifies the number of elements in the Properties array. ### Return Value - **S_OK**: Success. - **WHV_E_VP_ALREADY_EXISTS**: A virtual processor already exists at VpIndex. - **E_INVALIDARG**: VpIndex is invalid, an unknown property code is specified, or the NumaNode value is invalid. ``` -------------------------------- ### WHvReadGpaRange C Syntax and Definitions Source: https://learn.microsoft.com/en-us/virtualization/api/hypervisor-platform/funcs/whvreadgparange Includes the function signature, required data structures for cache types and access controls, and the maximum data size constant. ```C // Guest physical address typedef UINT64 WHV_GUEST_PHYSICAL_ADDRESS; // // Maximum data size used by WHvReadGpaRange and WHvWriteGpaRange // #define WHV_READ_WRITE_GPA_RANGE_MAX_SIZE 16 typedef enum WHV_CACHE_TYPE { WHvCacheTypeUncached = 0, WHvCacheTypeWriteCombining = 1, WHvCacheTypeWriteThrough = 4, #if defined(_AMD64_) WHvCacheTypeWriteProtected = 5, #endif WHvCacheTypeWriteBack = 6 } WHV_CACHE_TYPE; typedef union WHV_INPUT_VTL { UINT8 AsUINT8; struct { UINT8 TargetVtl : 4; UINT8 UseTargetVtl : 1; UINT8 Reserved : 3; }; } WHV_INPUT_VTL; // // Control flags used by WHvReadGpaRange and WHvWriteGpaRange // typedef union WHV_ACCESS_GPA_CONTROLS { UINT64 AsUINT64; struct { // // Cache type for access // WHV_CACHE_TYPE CacheType; // // VTL whose GPA is to be accessed // WHV_INPUT_VTL InputVtl; UINT8 Reserved; UINT16 Reserved1; }; } WHV_ACCESS_GPA_CONTROLS; HRESULT WINAPI WHvReadGpaRange( _In_ WHV_PARTITION_HANDLE Partition, _In_ UINT32 VpIndex, _In_ WHV_GUEST_PHYSICAL_ADDRESS GuestAddress, _In_ WHV_ACCESS_GPA_CONTROLS Controls, _Out_writes_bytes_(DataSizeInBytes) PVOID Data, _In_ UINT32 DataSizeInBytes ); ``` -------------------------------- ### HcsCreateEmptyRuntimeStateFile Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcscreateemptyruntimestatefile Creates an empty runtime-state file (.vmrs) for a VM. ```APIDOC ## HcsCreateEmptyRuntimeStateFile ### Description Creates an empty runtime-state file (.vmrs) for a VM. This file is used to save a running VM and is specified in the options document of the HcsSaveComputeSystem function. ### Syntax ```cpp HRESULT WINAPI HcsCreateEmptyRuntimeStateFile( _In_ PCWSTR runtimeStateFilePath ); ``` ### Parameters - **runtimeStateFilePath** (PCWSTR) - Required - Full path to the runtime-state file to create. ### Return Values - **HRESULT** - Returns an HRESULT indicating success or failure. ### Requirements - **Minimum supported client**: Windows 10, version 1809 - **Minimum supported server**: Windows Server 2019 - **Header**: ComputeCore.h - **Library**: ComputeCore.lib - **Dll**: ComputeCore.dll ``` -------------------------------- ### Open a virtual machine compute system Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/computesystemsample Opens an existing compute system by name. The system handle is managed via RAII to ensure proper cleanup. ```C++ static constexpr wchar_t c_VmQuery[] = LR"( { "PropertyTypes":[ "Memory" ] })"; unique_hcs_operation operation(HcsCreateOperation(nullptr, nullptr)); unique_hcs_system system; THROW_IF_FAILED(HcsOpenComputeSystem(L"Sample", GENERIC_ALL, &system)); ``` -------------------------------- ### HcsOpenProcess Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcsopenprocess Opens an existing process in a compute system. ```APIDOC ## HcsOpenProcess ### Description Opens an existing process in a compute system. ### Syntax ```cpp HRESULT WINAPI HcsOpenProcess( _In_ HCS_SYSTEM computeSystem, _In_ DWORD processId, _In_ DWORD requestedAccess, _Out_ HCS_PROCESS* process ); ``` ### Parameters - **computeSystem** (HCS_SYSTEM) - The handle to the compute system in which to start the process. - **processId** (DWORD) - Specifies the Id of the process to open. - **requestedAccess** (DWORD) - Specifies the required access to the compute system. - **process** (HCS_PROCESS*) - Receives the handle to the process. ### Return Values The function returns an HRESULT. ``` -------------------------------- ### Enumerate all compute systems Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/computesystemsample Lists all available compute systems and outputs the result as a JSON string. ```C++ unique_hcs_operation enumOperation(HcsCreateOperation(nullptr, nullptr)); THROW_IF_FAILED(HcsEnumerateComputeSystems(nullptr, enumOperation.get())); // print out all the compute system in JSON string wil::unique_hlocal_string Enumresult; THROW_IF_FAILED(HcsWaitForOperationResult(enumOperation.get(), INFINITE, &Enumresult)); std::wcout << Enumresult.get() << std::endl; ``` -------------------------------- ### WHvGetCapability Source: https://learn.microsoft.com/en-us/virtualization/api/hypervisor-platform/funcs/whvgetcapability Queries the capabilities of the Windows Hypervisor Platform. ```APIDOC ## WHvGetCapability ### Description Queries properties and capabilities of the hypervisor, the API implementation, and the hardware platform. Applications must use this to verify feature availability before calling corresponding APIs. ### Syntax `HRESULT WHvGetCapability(WHV_CAPABILITY_CODE CapabilityCode, VOID* CapabilityInfo, UINT32 CapabilityInfoSizeInBytes, UINT32* WrittenSizeInBytes);` ### Parameters - **CapabilityCode** (WHV_CAPABILITY_CODE) - The capability to query (e.g., WHvCapabilityCodeFeatures, WHvCapabilityCodeHypervisorPresent). - **CapabilityInfo** (VOID*) - Pointer to a buffer to receive the capability information. - **CapabilityInfoSizeInBytes** (UINT32) - Size of the buffer provided. - **WrittenSizeInBytes** (UINT32*) - Pointer to receive the number of bytes written to the buffer. ### Requirements - **Header**: WinHvPlatform.h - **Library**: WinHvPlatform.lib - **DLL**: WinHvPlatform.dll ```