### 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" ] })"; ``` -------------------------------- ### 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. ``` -------------------------------- ### 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 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 ); ``` -------------------------------- ### 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 ``` -------------------------------- ### 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. ``` -------------------------------- ### 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; ``` -------------------------------- ### 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")); ``` -------------------------------- ### 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 ## HRESULT HcsSetupBaseOSLayer(PCWSTR layerPath, HANDLE vhdHandle, PCWSTR options) ### 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. ### 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 an HRESULT indicating success or failure. ``` -------------------------------- ### 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 ); ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ); ``` -------------------------------- ### 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 ); ``` -------------------------------- ### 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) - Required - 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. The caller is responsible for releasing the handle using HcsCloseComputeSystem. ### Syntax `HRESULT WINAPI HcsOpenComputeSystem(PCWSTR id, DWORD requestedAccess, 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. ### Return Values - **HRESULT** - Returns an HRESULT indicating success or failure. ``` -------------------------------- ### 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 ); ``` -------------------------------- ### 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 ``` -------------------------------- ### 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; ``` -------------------------------- ### HcsCreateComputeSystem Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcscreatecomputesystem Creates a new compute system using the provided configuration and operation handle. ```APIDOC ## HcsCreateComputeSystem ### Description Creates a new compute system. The function returns an HRESULT indicating if the operation started successfully. ### Syntax ```cpp HRESULT WINAPI HcsCreateComputeSystem( _In_ PCWSTR id, _In_ PCWSTR configuration, _In_ HCS_OPERATION operation, _In_opt_ const SECURITY_DESCRIPTOR* securityDescriptor, _Out_ HCS_SYSTEM* computeSystem ); ``` ### Parameters - **id** (PCWSTR) - Required - Unique Id identifying the compute system. - **configuration** (PCWSTR) - Required - JSON document specifying the settings of the compute system (Container, VirtualMachine, or HostedSystem). - **operation** (HCS_OPERATION) - Required - The handle to the operation that tracks the create operation. - **securityDescriptor** (const SECURITY_DESCRIPTOR*) - Optional - Reserved for future use, must be NULL. - **computeSystem** (HCS_SYSTEM*) - Required - Receives a handle to the newly created compute system. ### Return Values - **HRESULT** - Returns S_OK if the operation started successfully. Callers should use HcsWaitForOperationResult or HcsGetOperationResult to track completion. ``` -------------------------------- ### HdvInitializeDeviceHost Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hdv/hdvinitializedevicehost Initializes a device emulator host in the caller's process and associates it with the specified compute system. ```APIDOC ## HdvInitializeDeviceHost ### Description Initializes a device emulator host in the caller's process and associates it with the specified compute system. ### Syntax ```cpp HRESULT WINAPI HdvInitializeDeviceHost( _In_ HCS_SYSTEM ComputeSystem, _Out_ HDV_HOST* DeviceHost ); ``` ### Parameters - **ComputeSystem** (HCS_SYSTEM) - Required - Handle to the compute system of the VM in which the device is used. The VM's configuration must indicate that an external device host for the VM will be present. - **DeviceHost** (HDV_HOST*) - Required - Receives the handle to the device emulator host for the VM. ### Return Value - **S_OK** - Success - **HRESULT** - Error code on failure ``` -------------------------------- ### Enable and Use Compute System Operation Callbacks Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/operationcompletionsample Configures a compute system callback to handle operation completion events using a Windows event object for synchronization. Demonstrates that subsequent attempts to use individual operation callbacks will fail as expected. ```cpp // Use a windows event object as the context so that we can wait on it wil::unique_event callbackWait; callbackWait.create(); unique_hcs_system system; THROW_IF_FAILED(HcsCreateComputeSystem(L"Test", c_EmptyVM, HcsCreateOperation(nullptr, nullptr), nullptr, &system)); THROW_IF_FAILED(HcsSetComputeSystemCallback( system.get(), HcsEventOptionEnableOperationCallbacks, callbackWait.get(), [](HCS_EVENT* event, void* context) { WI_ASSERT(event->Type == HcsEventOperationCallback); wil::unique_hlocal_string resultDoc; THROW_IF_FAILED_MSG(HcsGetOperationResult(event->Operation, &resultDoc), "%ws", resultDoc.get()); HcsCloseOperation(event->Operation); SetEvent(context); })); callbackWait.wait(INFINITE); // However, once the system callback has been set, using an operation with callback fails! callbackWait.create(); HRESULT result = HcsStartComputeSystem( system.get(), HcsCreateOperation(nullptr, [](HCS_OPERATION operation, void* context){}), nullptr); THROW_HR_IF(E_UNEXPECTED, result != HCS_E_OPERATION_SYSTEM_CALLBACK_ALREADY_SET); ``` -------------------------------- ### HcsCreateEmptyGuestStateFile Syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcscreateemptygueststatefile The function signature for creating an empty guest-state file in C++. ```C++ HRESULT WINAPI HcsCreateEmptyGuestStateFile( _In_ PCWSTR guestStateFilePath ); ``` -------------------------------- ### HcsCreateEmptyRuntimeStateFile Syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcscreateemptyruntimestatefile The function signature for creating an empty runtime-state file in C++. ```cpp HRESULT WINAPI HcsCreateEmptyRuntimeStateFile( _In_ PCWSTR runtimeStateFilePath ); ``` -------------------------------- ### HcsSetupBaseOSLayer function 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 ); ``` -------------------------------- ### HdvInitializeDeviceHost function syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hdv/hdvinitializedevicehost The function signature for initializing a device emulator host in C++. ```cpp HRESULT WINAPI HdvInitializeDeviceHost( _In_ HCS_SYSTEM ComputeSystem, _Out_ HDV_HOST* DeviceHost ); ``` -------------------------------- ### HDV_PCI_DEVICE_SET_CONFIGURATION Callback Syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hdv/hdvpcidevicesetconfiguration Defines the function signature for setting the configuration of an emulated device. ```C++ typedef HRESULT (CALLBACK *HDV_PCI_DEVICE_SET_CONFIGURATION)( _In_opt_ void* DeviceContext, _In_ UINT32 ConfigurationValueCount, _In_ const PCWSTR* ConfigurationValues ); ``` -------------------------------- ### HcsInitializeLegacyWritableLayer C++ Syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcsinitializelegacywritablelayer Function signature for initializing a legacy writable layer in C++. ```C++ HRESULT WINAPI HcsInitializeLegacyWritableLayer( _In_ PCWSTR writableLayerMountPath, _In_ PCWSTR writableLayerFolderPath, _In_ PCWSTR layerData, _In_opt_ PCWSTR options ); ``` -------------------------------- ### Utility Functions for Virtual Machines Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/apioverview Functions to configure environments for running virtual machines. ```APIDOC ## HcsCreateEmptyGuestStateFile Create an empty guest-state file (.vmgs) for VMs. ## HcsCreateEmptyRuntimeStateFile Create an empty runtime-state file (.vmrs) for a VM. ## HcsGrantVmAccess Add an entry to a file's ACL that grants access for a VM. ## HcsRevokeVmAccess Remove an entry to a file's ACL that granted access for a VM. ## HcsGrantVmGroupAccess Grant VM group access (R/O) to the specified file. ## HcsRevokeVmGroupAccess Remove VM group access for the specified file. ## HcsGetProcessorCompatibilityFromSavedState Get the processor compatibility from runtime-state file (.vmrs). ``` -------------------------------- ### Pause and resume a compute system Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/computesystemsample Demonstrates how to suspend a running compute system and subsequently resume it using HCS operations. ```C++ static constexpr wchar_t c_pauseOption[] = LR"( { "SuspensionLevel": "Suspend", "HostedNotification": { "Reason": "Save" } })"; // Assume same "system" as previous sample code unique_hcs_operation pauseOperation(HcsCreateOperation(nullptr, nullptr)); THROW_IF_FAILED(HcsPauseComputeSystem(system.get(), pauseOperation.get(), c_pauseOption)); wil::unique_hlocal_string resultDoc; THROW_IF_FAILED_MSG(HcsWaitForOperationResult(pauseOperation.get(), INFINITE, &resultDoc), "ResultDoc: %ws", resultDoc.get()); // After some while, resume the compute system unique_hcs_operation resumeOperation(HcsCreateOperation(nullptr, nullptr)); THROW_IF_FAILED(HcsResumeComputeSystem(system.get(), resumeOperation.get(), nullptr)); THROW_IF_FAILED_MSG(HcsWaitForOperationResult(resumeOperation.get(), INFINITE, &resultDoc), "ResultDoc: %ws", resultDoc.get()); ``` -------------------------------- ### HcsSetComputeSystemCallback function syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcssetcomputesystemcallback The function signature for registering a compute system event callback. ```C++ HRESULT WINAPI HcsSetComputeSystemCallback( _In_ HCS_SYSTEM computeSystem, _In_ HCS_EVENT_OPTIONS callbackOptions, _In_opt_ const void* context, _In_ HCS_EVENT_CALLBACK callback ); ``` -------------------------------- ### Registering a Compute System Event Callback Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/eventcallbacksample Sets up a callback function using HcsSetComputeSystemCallback to monitor compute system events. The callback handles various HCS_EVENT types, including system exits and crash reports. ```cpp constexpr auto c_EmptyVM = LR"( { "SchemaVersion": { "Major": 2, "Minor": 1 }, "Owner": "Sample", "VirtualMachine": { "Chipset": { "Uefi": {} }, "ComputeTopology": { "Memory": { "Backing": "Physical", "SizeInMB": 1024 }, "Processor": { "Count": 2 } } }, "ShouldTerminateOnLastHandleClosed": true })"; // // Start by creating a compute system. // unique_hcs_operation operation{ HcsCreateOperation(nullptr, nullptr) }; unique_hcs_system system; THROW_IF_FAILED(HcsCreateComputeSystem(L"Test", c_EmptyVM, operation.get(), nullptr, &system)); wil::unique_hlocal_string resultDoc; THROW_IF_FAILED_MSG(HcsWaitForOperationResult(operation.get(), INFINITE, &resultDoc), "%ws", resultDoc.get()); // // Set the compute system's event callback function. // This callback is used to act on events that occur on compute systems // outside of an HCS operation. These vary on different contexts, and the // HCS_EVENT parameter determines what happened. // THROW_IF_FAILED(HcsSetComputeSystemCallback( system.get(), HcsEventOptionNone, nullptr, [](HCS_EVENT* event, void*) { switch(event->Type) { case HcsEventSystemExited: // // The compute system has exited. This usually means that it has been terminated // via HcsTerminateComputeSystem or shutdown via HcsShutdownComputeSystem. // It could also be a result of an internal error in the Host Compute Service; // or the compute system's guest operating system turning off the system. // // Normally cleanup logic in the client side would happen here // because we can deterministically know when the compute system // is not going to be around anymore. // // EventData is a JSON document that contains the system exit status. // WI_ASSERT(event->EventData != nullptr); break; case HcsEventSystemCrashInitiated: // // The compute system's guest operating system has initiated a crash (bugcheck). // This event is used to notify client code about the crash to give it a chance // to do something before the crash completes. // // EventData is a JSON document with a guest report. // WI_ASSERT(event->EventData != nullptr); break; case HcsEventSystemCrashReport: // // The compute system's guest operating system has reported a crash (bugcheck). // This event is used to notify client code about the crash completed. // // EventData is a JSON document with a guest report. // This can be used as input to HcsSubmitWerReport. // WI_ASSERT(event->EventData != nullptr); break; case HcsEventSystemRdpEnhancedModeStateChanged: // // The compute system's RDP enhanced mode state has changed. // break; case HcsEventSystemSiloJobCreated: // // Reserved for future use. // break; case HcsEventSystemGuestConnectionClosed: // // The compute system's guest connection has been closed. // This notification is called regardless of the disconnection being expected or not. // break; case HcsEventProcessExited: // // Event notification for when an HCS_PROCESS completes. // The EventData of the event is a JSON document describing // the resulting process status. // // This event notification is only valid for when HcsSetProcessCallback // is used. This will never fire for a compute system's event callback // set via HcsSetComputeSystemCallback. // WI_ASSERT(false); // Not valid for compute systems! break; case HcsEventOperationCallback: // This event type is only valid if HcsEventOptionEnableOperationCallbacks WI_ASSERT(false); // Not valid because we've used HcsEventOptionNone! break; case HcsEventServiceDisconnect: // // Event notification to indicate when the client code // has lost connection to the Host Compute Service. // This would usually mean the service crashed or has been forcefully stopped. // break; case HcsEventInvalid: default: WI_ASSERT(false); // This shouldn't happen! } })); ``` -------------------------------- ### HdvProxyDeviceHost function syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hdv/hdvproxydevicehost The function signature for registering a device host with a compute system. ```C++ HRESULT WINAPI HdvProxyDeviceHost( HCS_SYSTEM ComputeSystem, _In_ PVOID DeviceHost_IUnknown, DWORD TargetProcessId, _Out_ UINT64* IpcSectionHandle ); ``` -------------------------------- ### HcsSetComputeSystemCallback Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcssetcomputesystemcallback Registers a callback to receive notifications for the compute system. ```APIDOC ## HcsSetComputeSystemCallback ### Description Registers a callback to receive notifications for the compute system. ### Syntax ```cpp HRESULT WINAPI HcsSetComputeSystemCallback( _In_ HCS_SYSTEM computeSystem, _In_ HCS_EVENT_OPTIONS callbackOptions, _In_opt_ const void* context, _In_ HCS_EVENT_CALLBACK callback ); ``` ### Parameters - **computeSystem** (HCS_SYSTEM) - The handle to the compute system. - **callbackOptions** (HCS_EVENT_OPTIONS) - The option for callback, using one from HCS_EVENT_OPTIONS. - **context** (const void*) - Optional pointer to a context that is passed to the callback. - **callback** (HCS_EVENT_CALLBACK) - The target HCS_EVENT_CALLBACK for compute system events. ### Return Values - **HRESULT** - Returns an HRESULT indicating success or failure. ``` -------------------------------- ### HcsEnumerateComputeSystems Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcsenumeratecomputesystems Enumerates existing compute systems using a query and an operation handle. ```APIDOC ## HcsEnumerateComputeSystems ### Description Enumerates existing compute systems. Callers are expected to retrieve the result using HcsWaitForOperationResult or HcsGetOperationResult. ### Syntax `HRESULT WINAPI HcsEnumerateComputeSystems(_In_opt_ PCWSTR query, _In_ HCS_OPERATION operation);` ### Parameters - **query** (PCWSTR) - Optional - JSON document of SystemQuery specifying a query for specific compute systems. - **operation** (HCS_OPERATION) - Required - The handle to the operation that tracks the enumerate operation. ### Return Values - **S_OK** - The operation started successfully. ### Operation Results - **S_OK** - The operation finished successfully, returning a JSON document representing an array of compute system properties. ``` -------------------------------- ### HdvProxyDeviceHost Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hdv/hdvproxydevicehost Registers a device host from another process with the compute system. ```APIDOC ## HdvProxyDeviceHost ### Description Registers a device host from another process with the compute system. ### Syntax ```cpp HRESULT WINAPI HdvProxyDeviceHost( HCS_SYSTEM ComputeSystem, _In_ PVOID DeviceHost_IUnknown, DWORD TargetProcessId, _Out_ UINT64* IpcSectionHandle ); ``` ### Parameters - **ComputeSystem** (HCS_SYSTEM) - Handle to the compute system to which the device host will be associated. - **DeviceHost_IUnknown** (PVOID) - A HDV_PCI_BAR_SELECTOR specifying index of the BAR containing the address to register. - **TargetProcessId** (DWORD) - The ID of the process containing the device host. - **IpcSectionHandle** (UINT64*) - Receives the IPC handle to return to remote process. ### Return Value - **S_OK** - If the function succeeds. - **HRESULT** - An error code if the function fails. ``` -------------------------------- ### HcsGetComputeSystemProperties Syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcsgetcomputesystemproperties The function signature for querying compute system properties in C++. ```cpp HRESULT WINAPI HcsGetComputeSystemProperties( _In_ HCS_SYSTEM computeSystem, _In_ HCS_OPERATION operation, _In_opt_ PCWSTR propertyQuery ); ``` -------------------------------- ### HDV_PCI_DEVICE_GET_DETAILS Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hdv/hdvpcidevicegetdetails Callback function signature for querying the PCI description of an emulated device. ```APIDOC ## HDV_PCI_DEVICE_GET_DETAILS ### Description Function invoked to query the PCI description of the emulated device. This information is used when presenting the device to the guest partition. ### Syntax ```cpp typedef HRESULT (CALLBACK *HDV_PCI_DEVICE_GET_DETAILS)( _In_opt_ void* DeviceContext, _Out_ PHDV_PCI_PNP_ID PnpId, _Out_ UINT32 ProbedBars[HDV_PCI_BAR_COUNT] ); ``` ### Parameters - **DeviceContext** (void*) - Context pointer that was supplied to HdvCreateDeviceInstance. - **PnpId** (PHDV_PCI_PNP_ID) - Receives the vendor / device ID / ... information about the device. - **ProbedBars** (UINT32[HDV_PCI_BAR_COUNT]) - Receives the results for probing the MMIO BARs. ### Return Values - **S_OK** - Returned if function succeeds. - **HRESULT** - An error code is returned if the function fails. ``` -------------------------------- ### Retrieve VM Properties Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/tutorial Fetches and displays the properties of a compute system using HcsGetComputeSystemProperties. ```cpp THROW_IF_FAILED(HcsGetComputeSystemProperties( system.get(), operation.get(), c_VmQuery)); THROW_IF_FAILED_MSG(HcsWaitForOperationResult(operation.get(), INFINITE, &resultDoc), "ResultDoc: %ws", resultDoc.get()); // It's a failure if the result document doesn't have anything for // ::HcsGetComputeSystemProperties! THROW_HR_IF(E_UNEXPECTED, !resultDoc); wprintf(L"HCS VM properties:\n%s\n", resultDoc.get()); ``` -------------------------------- ### HdvTeardownDeviceHost function syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hdv/hdvteardowndevicehost The function signature for tearing down a device host in C++. ```cpp HRESULT WINAPI HdvTeardownDeviceHost( _In_ HDV_HOST DeviceHost ); ``` -------------------------------- ### HdvCreateGuestMemoryAperture Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hdv/hdvcreateguestmemoryaperture Creates a guest RAM aperture into the address space of the calling process. ```APIDOC ## HdvCreateGuestMemoryAperture ### Description Creates a guest RAM aperture into the address space of the calling process. ### Syntax ```cpp HRESULT WINAPI HdvCreateGuestMemoryAperture( _In_ HDV_DEVICE Requestor, _In_ UINT64 GuestPhysicalAddress, _In_ UINT32 ByteCount, _In_ BOOL WriteProtected, _Out_ void** MappedAddress ); ``` ### Parameters - **Requestor** (HDV_DEVICE) - Handle to the device requesting memory access. - **GuestPhysicalAddress** (UINT64) - Base physical address at which the aperture starts. - **ByteCount** (UINT32) - Size of the aperture in bytes. - **WriteProtected** (BOOL) - If TRUE, the process is only granted read access to the mapped memory. - **MappedAddress** (void**) - Receives the virtual address (in the calling process) at which the requested guest memory region has been mapped. ### Return Values - **S_OK** - Returned if function succeeds. - **HRESULT** - An error code is returned if the function fails. ``` -------------------------------- ### HdvReadGuestMemory Syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hdv/hdvreadguestmemory The function signature for reading guest memory in C++. ```C++ HRESULT WINAPI HdvReadGuestMemory( _In_ HDV_DEVICE Requestor, _In_ UINT64 GuestPhysicalAddress, _In_ UINT32 ByteCount, _Out_writes_(ByteCount) BYTE* Buffer ); ``` -------------------------------- ### HcsCreateProcess Function Syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcscreateprocess The function signature for initiating a process in a compute system. ```C++ HRESULT WINAPI HcsCreateProcess( _In_ HCS_SYSTEM computeSystem, _In_ PCWSTR processParameters, _In_ HCS_OPERATION operation, _In_opt_ const SECURITY_DESCRIPTOR* securityDescriptor, _Out_ HCS_PROCESS* process ); ``` -------------------------------- ### HcsInitializeWritableLayer Function Syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcsinitializewritablelayer The function signature for initializing a writable layer in C++. ```cpp HRESULT WINAPI HcsInitializeWritableLayer( _In_ PCWSTR writableLayerPath, _In_ PCWSTR layerData, _In_opt_ PCWSTR options ); ``` -------------------------------- ### HcsRevokeVmAccess Syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hcsrevokevmaccess The function signature for HcsRevokeVmAccess as defined in ComputeCore.h. ```Cpp HRESULT WINAPI HcsRevokeVmAccess( _In_ PCWSTR vmId, _In_ PCWSTR filePath ); ``` -------------------------------- ### HdvCreateSectionBackedMmioRange C++ Syntax Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hdv/hdvcreatesectionbackedmmiorange Function signature for mapping a section into device MMIO space. ```C++ HRESULT WINAPI HdvCreateSectionBackedMmioRange( _In_ HDV_DEVICE Requestor, _In_ HDV_PCI_BAR_SELECTOR BarIndex, _In_ UINT64 OffsetInPages, _In_ UINT64 LengthInPages, _In_ HDV_MMIO_MAPPING_FLAGS MappingFlags, _In_ HANDLE SectionHandle, _In_ UINT64 SectionOffsetInPages ); ``` -------------------------------- ### HDV_PCI_DEVICE_SET_CONFIGURATION Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hdv/hdvpcidevicesetconfiguration Callback function invoked to set the configuration of the emulated device. ```APIDOC ## HDV_PCI_DEVICE_SET_CONFIGURATION ### Description Function invoked to set the configuration of the emulated device. ### Syntax ```cpp typedef HRESULT (CALLBACK *HDV_PCI_DEVICE_SET_CONFIGURATION)( _In_opt_ void* DeviceContext, _In_ UINT32 ConfigurationValueCount, _In_ const PCWSTR* ConfigurationValues ); ``` ### Parameters - **DeviceContext** (void*) - Context pointer that was supplied to HdvCreateDeviceInstance. - **ConfigurationValueCount** (UINT32) - Number of elements in the ConfigurationValues array. - **ConfigurationValues** (const PCWSTR*) - Array with strings representing the configurations values. These strings are provided in the VM's configuration. ### Return Values - **S_OK** - Returned if function succeeds. - **HRESULT** - An error code is returned if the function fails. ``` -------------------------------- ### Device Virtualization API Functions Source: https://learn.microsoft.com/en-us/virtualization/api/hcs/reference/hdv/devicevirtualization The following C-style Windows API functions are available for managing device virtualization within the Host Compute Service. ```APIDOC ## Device Virtualization API Functions ### Description The HCS provides a set of C-style Windows API functions for device virtualization. All functions return an HRESULT error code indicating the result of the operation. ### Available Functions - **HdvCreateDeviceInstance**: Creates a device instance in the current host. - **HdvCreateGuestMemoryAperture**: Creates a guest RAM aperture in the address space of the calling process. - **HdvCreateSectionBackedMmioRange**: Maps a section into device MMIO space. - **HdvDeliverGuestInterrupt**: Delivers a message signaled interrupt (MSI) to the guest partition. - **HdvDestroySectionBackedMmioRange**: Unmaps a section previously mapped via HdvCreateSectionBackedMmioRange. - **HdvInitializeDeviceHost**: Initializes a device emulator host in the caller's process. - **HdvInitializeDeviceHostForProxy**: Initializes the device emulator host and associates it with a proxy. - **HdvPciDeviceGetDetails**: Queries the PCI description of the emulated device. - **HdvPciDeviceInitialize**: Initializes the emulated device. - **HdvPciDeviceSetConfiguration**: Sets the configuration of the emulated device. - **HdvPciDeviceStart**: Notifies the emulated device that virtual processors are starting. - **HdvPciDeviceStop**: Notifies the emulated device that virtual processors are stopping. - **HdvPciDeviceTeardown**: Tears down the emulated device. - **HdvPciReadConfigSpace**: Executes a read into the emulated device's PCI config space. - **HdvPciReadInterceptedMemory**: Executes an intercepted MMIO read for the emulated device. - **HdvPciWriteConfigSpace**: Executes a write into the emulated device's PCI config space. - **HdvPciWriteInterceptedMemory**: Executes an intercepted MMIO write for the emulated device. - **HdvProxyDeviceHost**: Registers a device host from another process with the compute system. - **HdvReadGuestMemory**: Reads guest primary memory (RAM) contents into a buffer. - **HdvRegisterDoorbell**: Registers a guest address to trigger an event on writes. - **HdvTeardownDeviceHost**: Tears down the device emulator host in the caller's process. - **HdvUnregisterDoorbell**: Unregisters a doorbell notification. - **HdvWriteGuestMemory**: Writes the contents of a specified buffer to guest primary memory (RAM). ```