# &VBOX_PRODUCT;

## Introduction

VirtualBox comes with comprehensive support for third-party developers. This Software Development Kit (SDK) contains all the documentation and interface files that are needed to write code that interacts with VirtualBox.

### Modularity: the building blocks of VirtualBox

VirtualBox is cleanly separated into several layers, which can be visualized like in the picture below:

The orange area represents code that runs in kernel mode, the blue area represents userspace code.

At the bottom of the stack resides the hypervisor -- the core of the virtualization engine, controlling execution of the virtual machines and making sure they do not conflict with each other or with whatever else the host computer is doing.

On top of the hypervisor, additional internal modules provide extra functionality. For example, the RDP server, which can deliver the graphical output of a VM remotely to an RDP client, is a separate module that is only loosely tacked onto the virtual graphics device.

What is primarily of interest for purposes of the SDK is the API layer block that sits on top of all the previously mentioned blocks. This API, which we call the "Main API", exposes the entire feature set of the virtualization engine below. It is completely documented in this SDK Reference -- see sdkref_classes and sdkref_enums -- and available to anyone who wishes to control VirtualBox programmatically. We chose the name "Main API" to differentiate it from other programming interfaces of VirtualBox that may be publicly accessible.

With the Main API, you can create, configure, start, stop and delete virtual machines, retrieve performance statistics about running VMs, configure the VirtualBox installation in general, and more. In fact, internally, the front-end programs `VirtualBox` and `VBoxManage` use nothing but this API as well -- there are no hidden backdoors into the virtualization engine for our own front-ends. This ensures the entire Main API is both well-documented and well-tested. (The same applies to `VBoxHeadless`, which is not shown in the image.)

### Two guises of the same "Main API": the web service or COM/XPCOM

There are several ways in which the Main API can be called by other code:

1. VirtualBox comes with a web service that maps nearly the entire Main API. The web service ships in a stand-alone executable (`vboxwebsrv`) that, when running, acts as an HTTP server, accepts SOAP connections and processes them.

   Since the entire web service API is publicly described in a web service description file (in WSDL format), you can write client programs that call the web service in any language with a toolkit that understands WSDL. These days, that includes most programming languages that are available: Java, C++, .NET, PHP, Python, Perl and probably many more.

   All of this is explained in detail in subsequent chapters of this book.

   There are two ways in which you can write client code that uses the web service:

   1. For Java as well as Python, the SDK contains easy-to-use classes that allow you to use the web service in an object-oriented, straightforward manner. We shall refer to this as the "object-oriented web service (OOWS)".

      The OO bindings for Java are described in javaapi, those for Python in glue-python-ws.

   2. Alternatively, you can use the web service directly, without the object-oriented client layer. We shall refer to this as the "raw web service".

      You will then have neither native object orientation nor full type safety, since web services are neither object-oriented nor stateful. However, in this way, you can write client code even in languages for which we do not ship object-oriented client code; all you need is a programming language with a toolkit that can parse WSDL and generate client wrapper code from it.

      We describe this further in raw-webservice, with samples for Java and Perl.

2. Internally, for portability and easier maintenance, the Main API is implemented using the Component Object Model (COM), an interprocess mechanism for software components originally introduced by Microsoft for Microsoft Windows. On a Windows host, VirtualBox will use Microsoft COM; on other hosts where COM is not present, VirtualBox ships with XPCOM, a free software implementation of COM originally created by the Mozilla project for their browsers.

   So if you are familiar with COM and the C++ programming language (or with any other programming language that can handle COM/XPCOM objects, such as Java, Visual Basic or C#), then you can use the COM/XPCOM API directly. VirtualBox comes with all the necessary files and documentation to build fully functional COM applications. For an introduction, please see api_com below.

   The VirtualBox front-ends (the graphical user interfaces as well as the command line), which are all written in C++, use COM/XPCOM to call the Main API. Technically, the web service is another front-end to this COM API, mapping almost all of it to SOAP clients.

If you are wondering which approach to choose, here are a few comparisons:

### Comparison web service vs. COM/XPCOM

Web service | COM/XPCOM
Pro: Easy to use with Java and Python with the object-oriented web service; extensive support even with other languages (C++, .NET, PHP, Perl and others) | Con: Usable from languages where COM bridge available (most languages on Windows platform, Python and C++ on other hosts)
Pro: Client can be on remote machine | Con: Client must be on the same host where virtual machine is executed
Con: Significant overhead due to XML marshalling over the wire for each method call | Pro: Relatively low invocation overhead

In the following chapters, we will describe the different ways in which to program VirtualBox, starting with the method that is easiest to use and then increasing in complexity as we go along.

### About web services in general

Web services are a particular type of programming interface. Whereas, with "normal" programming, a program calls an application programming interface (API) defined by another program or the operating system and both sides of the interface have to agree on the calling convention and, in most cases, use the same programming language, web services use Internet standards such as HTTP and XML to communicate.

In some ways, web services promise to deliver the same thing as CORBA and DCOM did years ago. However, while these previous technologies relied on specific binary protocols and thus proved to be difficult to use between diverging platforms, web services circumvent these incompatibilities by using text-only standards like HTTP and XML. On the downside (and, one could say, typical of things related to XML), a lot of standards are involved before a web service can be implemented. Many of the standards invented around XML are used one way or another. As a result, web services are slow and verbose, and the details can be incredibly messy. The relevant standards here are called SOAP and WSDL, where SOAP describes the format of the messages that are exchanged (an XML document wrapped in an HTTP header), and WSDL is an XML format that describes a complete API provided by a web service. WSDL in turn uses XML Schema to describe types, which is not exactly terse either. However, as you will see from the samples provided in this chapter, the VirtualBox web service shields you from these details and is easy to use.

In order to successfully use a web service, a number of things are required -- primarily, a web service accepting connections; service descriptions; and a client that connects to that web service. Connections to the VirtualBox web service are governed by the SOAP standard, which describes how messages are to be exchanged between a service and its clients; the service descriptions are governed by WSDL.

In the case of VirtualBox, this translates into the following three components:

1. The VirtualBox web service (the "server"): this is the `vboxwebsrv` executable shipped with VirtualBox. Once you start this executable (which acts as an HTTP server on a specific TCP/IP port), clients can connect to the web service and thus control a VirtualBox installation.

2. VirtualBox also comes with WSDL files that describe the services provided by the web service. You can find these files in the `sdk/bindings/webservice/` directory. These files are understood by the web service toolkits that are shipped with most programming languages and enable you to easily access a web service even if you don't use our object-oriented client layers. VirtualBox is shipped with pre-generated web service glue code for several languages (Python, Perl, Java).

3. A client that connects to the web service in order to control the VirtualBox installation.

   Unless you use some of the samples shipped with VirtualBox, this needs to be written by you.

### Running the web service

The web service ships in a stand-alone executable, `vboxwebsrv`, that, when running, acts as an HTTP server, accepts SOAP connections, remotely or from the same machine, and processes them.

The web service executable is not delivered with the VirtualBox SDK, but instead ships with the standard VirtualBox binary package for your specific platform. The SDK contains only platform-independent text files and documentation so thus the vboxwebsrv binary is shipped with the platform-specific packages. Therefore the information on how to run vboxwebsrv as a service is included in the VirtualBox documentation and not the SDK.

The `vboxwebsrv` program, which implements the web service, is a text-mode (console) program which, after being started, simply runs until it is interrupted with Ctrl-C or a kill command.

Once the web service is started, it acts as a front-end to the VirtualBox installation of the user account that it is running under. In other words, if the web service is run under the user account of `user1`, it will see and manipulate the virtual machines and other data represented by the VirtualBox data of that user (for example, on a Linux machine, under `/home/user1/.config/VirtualBox`; see the VirtualBox User Guide for details on where this data is stored).

#### Command line options of vboxwebsrv

The web service supports the following command line options:

- `--help` (or `-h`): print a brief summary of command line options.

- `--background` (or `-b`): run the web service as a background daemon. This option is not supported on Windows hosts.

- `--host` (or `-H`): This specifies the host to bind to and defaults to "localhost".

- `--port` (or `-p`): This specifies which port to bind to on the host and defaults to 18083.

- `--ssl` (or `-s`): This enables SSL support.

- `--keyfile` (or `-K`): This specifies the file name containing the server private key and the certificate. This is a mandatory parameter if SSL is enabled.

- `--passwordfile` (or `-a`): This specifies the file name containing the password for the server private key. If unspecified or an empty string is specified this is interpreted as an empty password (i.e. the private key is not protected by a password). If the file name `-` is specified then then the password is read from the standard input stream, otherwise from the specified file. The user is responsible for appropriate access rights to protect the confidential password.

- `--cacert` (or `-c`): This specifies the file name containing the CA certificate appropriate for the server certificate.

- `--capath` (or `-C`): This specifies the directory containing several CA certificates appropriate for the server certificate.

- `--dhfile` (or `-D`): This specifies the file name containing the DH key. Alternatively it can contain the number of bits of the DH key to generate. If left empty, RSA is used.

- `--randfile` (or `-r`): This specifies the file name containing the seed for the random number generator. If left empty, an operating system specific source of the seed.

- `--timeout` (or `-t`): This specifies the session timeout, in seconds, and defaults to 300 (five minutes). A web service client that has logged on but makes no calls to the web service will automatically be disconnected after the number of seconds specified here, as if it had called the `IWebSessionManager::logoff()` method provided by the web service itself.

  It is normally vital that each web service client call this method, as the web service can accumulate large amounts of memory when running, especially if a web service client does not properly release managed object references. As a result, this timeout value should not be set too high, especially on machines with a high load on the web service, or the web service may eventually deny service.

- `--check-interval` (or `-i`): This specifies the interval in which the web service checks for timed-out clients, in seconds, and defaults to 5. This normally does not need to be changed.

- `--threads` (or `-T`): This specifies the maximum number or worker threads, and defaults to 100. This normally does not need to be changed.

- `--keepalive` (or `-k`): This specifies the maximum number of requests which can be sent in one web service connection, and defaults to 100. This normally does not need to be changed.

- `--authentication` (or `-A`): This specifies the desired web service authentication method. If the parameter is not specified or the empty string is specified it does not change the authentication method, otherwise it is set to the specified value. Using this parameter is a good measure against accidental misconfiguration, as the web service ensures periodically that it isn't changed.

- `--verbose` (or `-v`): Normally, the web service outputs only brief messages to the console each time a request is served. With this option, the web service prints much more detailed data about every request and the COM methods that those requests are mapped to internally, which can be useful for debugging client programs.

- `--pidfile` (or `-P`): Name of the PID file which is created when the daemon was started.

- `--logfile` (or `-F`) `<file>`: If this is specified, the web service not only prints its output to the console, but also writes it to the specified file. The file is created if it does not exist; if it does exist, new output is appended to it. This is useful if you run the web service unattended and need to debug problems after they have occurred.

- `--logrotate` (or `-R`): Number of old log files to keep, defaults to 10. Log rotation is disabled if set to 0.

- `--logsize` (or `-S`): Maximum size of log file in bytes, defaults to 100MB. Log rotation is triggered if the file grows beyond this limit.

- `--loginterval` (or `-I`): Maximum time interval to be put in a log file before rotation is triggered, in seconds, and defaults to one day.

#### Authenticating at web service logon

As opposed to the COM/XPCOM variant of the Main API, a client that wants to use the web service must first log on by calling the IWebsessionManager::logon() API that is specific to the web service. Logon is necessary for the web service to be stateful; internally, it maintains a session for each client that connects to it.

The `IWebsessionManager::logon()` API takes a user name and a password as arguments, which the web service then passes to a customizable authentication plugin that performs the actual authentication.

For testing purposes, it is recommended that you first disable authentication with the command:

    VBoxManage setproperty websrvauthlibrary null

This will cause all logons to succeed, regardless of user name or password. This should of course not be used in a production environment.

Generally, the mechanism by which clients are authenticated is configurable by way of the `VBoxManage` command:

    VBoxManage setproperty websrvauthlibrary default|null|<library>

This way you can specify any shared object/dynamic link module that conforms with the specifications for VirtualBox external authentication modules as laid out in section VRDE authentication of the VirtualBox User Guide; the web service uses the same kind of modules as the VirtualBox VRDE server. For technical details on VirtualBox external authentication modules see vbox-auth

By default, after installation, the web service uses the VBoxAuth module that ships with VirtualBox. This module uses PAM on FreeBSD, Linux, and Solaris hosts to authenticate users. Any valid username/password combination is accepted, it does not have to be the username and password of the user running the web service daemon. If `vboxwebsrv` doesn't run as root PAM authentication can fail, because the `/etc/shadow` file, which is used by PAM, is only readable by root. On most Linux distributions PAM uses a suid root helper internally, so make sure you test this before deploying it. One can override authentication failures due to lack of read privileges of the shadow password file by setting the environment variable `VBOX_PAM_ALLOW_INACTIVE`. Please use this variable carefully and only if you fully understand what you're doing.

## Environment-specific notes

The Main API described in sdkref_classes and sdkref_enums is mostly identical in all the supported programming environments which have been briefly mentioned in the introduction of this book. As a result, the Main API's general concepts described in concepts are the same whether you use the object-oriented web service (OOWS) for JAX-WS or a raw web service connection via, say, Perl, or whether you use C++ COM bindings.

Some things are different depending on your environment, however. These differences are explained in this chapter.

### Using the object-oriented web service (OOWS)

As explained in webservice-or-com, VirtualBox ships with client-side libraries for Java, Python and PHP that allow you to use the VirtualBox web service in an intuitive, object-oriented way. These libraries shield you from the client-side complications of managed object references and other implementation details that come with the VirtualBox web service. (If you are interested in these complications, have a look at raw-webservice).

We recommend that you start your experiments with the VirtualBox web service by using our object-oriented client libraries for JAX-WS, a web service toolkit for Java, which enables you to write code to interact with VirtualBox in the simplest manner possible.

As "interfaces", "attributes" and "methods" are COM concepts, please read the documentation in sdkref_classes and sdkref_enums with the following notes in mind.

The OOWS bindings attempt to map the Main API as closely as possible to the Java, Python and PHP languages. In other words, objects are objects, interfaces become classes, and you can call methods on objects as you would on local objects.

The main difference remains with attributes: to read an attribute, call a "getXXX" method, with "XXX" being the attribute name with a capitalized first letter. So when the Main API Reference says that `IMachine` has a "name" attribute (see IMachine::name), call `getName()` on an IMachine object to obtain a machine's name. Unless the attribute is marked as read-only in the documentation, there will also be a corresponding "set" method.

#### The object-oriented web service for JAX-WS

JAX-WS is a powerful toolkit by Sun Microsystems to build both server and client code with Java. It is part of Java 6 (JDK 1.6), but can also be obtained separately for Java 5 (JDK 1.5). The VirtualBox SDK comes with precompiled OOWS bindings working with both Java 5 and 6.

The following sections explain how to get the JAX-WS sample code running and explain a few common practices when using the JAX-WS object-oriented web service.

##### Preparations

Since JAX-WS is already integrated into Java 6, no additional preparations are needed for Java 6.

If you are using Java 5 (JDK 1.5.x), you will first need to download and install an external JAX-WS implementation, as Java 5 does not support JAX-WS out of the box; for example, you can download one from here: https://jax-ws.dev.java.net/2.1.4/JAXWS2.1.4-20080502.jar. Then perform the installation (`java -jar JAXWS2.1.4-20080502.jar`).

##### Getting started: running the sample code

To run the OOWS for JAX-WS samples that we ship with the SDK, perform the following steps:

1. Open a terminal and change to the directory where the JAX-WS samples reside.

   In `sdk/bindings/glue/java/`.

   Examine the header of `Makefile` to see if the supplied variables (Java compiler, Java executable) and a few other details match your system settings.

2. To start the VirtualBox web service, open a second terminal and change to the directory where the VirtualBox executables are located. Then type:

       ./vboxwebsrv -v

   The web service now waits for connections and will run until you press Ctrl+C in this second terminal. The -v argument causes it to log all connections to the terminal. (See runvboxwebsrv for details on how to run the web service.)

3. Back in the first terminal and still in the samples directory, to start a simple client example just type:

       make run16

   if you're on a Java 6 system; on a Java 5 system, run `make run15` instead.

   This should work on all Unix-like systems such as Linux and Solaris. For Windows systems, use commands similar to what is used in the Makefile.

   This will compile the `clienttest.java` code on the first call and then execute the resulting `clienttest` class to show the locally installed VMs (see below).

The `clienttest` sample imitates a few typical command line tasks that `VBoxManage`, VirtualBox's regular command-line front-end, would provide (see the VirtualBox User Guide for details). In particular, you can run:

- `java clienttest show vms`: show the virtual machines that are registered locally.

- `java clienttest list hostinfo`: show various information about the host this VirtualBox installation runs on.

- `java clienttest startvm <vmname|uuid>`: start the given virtual machine.

The `clienttest.java` sample code illustrates common basic practices how to use the VirtualBox OOWS for JAX-WS, which we will explain in more detail in the following chapters.

##### Logging on to the web service

Before a web service client can do anything useful, two objects need to be created, as can be seen in the `clienttest` constructor:

1. An instance of IWebsessionManager, which is an interface provided by the web service to manage "web sessions" -- that is, stateful connections to the web service with persistent objects upon which methods can be invoked.

   In the OOWS for JAX-WS, the IWebsessionManager class must be constructed explicitly, and a URL must be provided in the constructor that specifies where the web service (the server) awaits connections. The code in `clienttest.java` connects to "http://localhost:18083/", which is the default.

   The port number, by default 18083, must match the port number given to the `vboxwebsrv` command line; see vboxwebsrv-ref.

2. After that, the code calls IWebsessionManager::logon(), which is the first call that actually communicates with the server. This authenticates the client with the web service and returns an instance of IVirtualBox, the most fundamental interface of the VirtualBox web service, from which all other functionality can be derived.

   If logon doesn't work, please take another look at websrv_authenticate.

##### Object management

The current OOWS for JAX-WS has certain memory management related limitations. When you no longer need an object, call its IManagedObjectRef::release() method explicitly, which frees appropriate managed reference, as is required by the raw web service; see managed-object-references for details. This limitation may be reconsidered in a future version of the VirtualBox SDK.

#### The object-oriented web service for Python

VirtualBox comes with two flavors of a Python API: one for web service, discussed here, and one for the COM/XPCOM API discussed in pycom. The client code is mostly similar, except for the initialization part, so it is up to the application developer to choose the appropriate technology. Moreover, a common Python glue layer exists, abstracting out concrete platform access details, see glue-python.

The minimum supported Python version is 2.6.

As indicated in webservice-or-com, the COM/XPCOM API gives better performance without the SOAP overhead, and does not require a web server to be running. On the other hand, the COM/XPCOM Python API requires a suitable Python bridge for your Python installation (VirtualBox ships the most important ones for each platform

On Mac OS X only the Python versions bundled with the OS are officially supported.

). On Windows, you can use the Main API from Python if the Win32 extensions package for Python

See http://sourceforge.net/project/showfiles.php?group_id=78018.

is installed. Versions of Python Win32 extensions earlier than 2.16 are known to have bugs, leading to issues with VirtualBox Python bindings, so please make sure to use latest available Python and Win32 extensions.

The VirtualBox OOWS for Python relies on the Python ZSI SOAP implementation (see http://pywebsvcs.sourceforge.net/zsi.html), which you will need to install locally before trying the examples. Most Linux distributions come with a package for ZSI, such as `python-zsi` in Ubuntu.

To get started, open a terminal and change to the `sdk/bindings/glue/python/sample` directory, which contains an example of a simple interactive shell able to control a VirtualBox instance. The shell is written using the API layer, thereby hiding different implementation details, so it is actually an example of code shared among XPCOM, MSCOM and web services. If you are interested in how to interact with the web services layer directly, have a look at `install/vboxapi/__init__.py` which contains the glue layer for all target platforms (i.e. XPCOM, MSCOM and web services).

To start the shell, run the following commands:

    /opt/VirtualBox/vboxwebsrv -t 0 # start web service with object autocollection disabled
    export VBOX_PROGRAM_PATH=/opt/VirtualBox        # your VirtualBox installation directory
    export VBOX_SDK_PATH=/home/youruser/vbox-sdk    # where you've extracted the SDK
    ./vboxshell.py -w

See vboxshell for more details on the shell's functionality. For you, as a VirtualBox application developer, the vboxshell sample could be interesting as an example of how to write code targeting both local and remote cases (COM/XPCOM and SOAP). The common part of the shell is the same -- the only difference is how it interacts with the invocation layer. You can use the `connect` shell command to connect to remote VirtualBox servers; in this case you can skip starting the local web server.

#### The object-oriented web service for PHP

VirtualBox also comes with object-oriented web service (OOWS) wrappers for PHP5. These wrappers rely on the PHP SOAP Extension

See https://www.php.net/soap.

, which can be installed by configuring PHP with `--enable-soap`.

### Using the raw web service with any language

The following examples show you how to use the raw web service, without the object-oriented client-side code that was described in the previous chapter.

Due to the limitations of SOAP and WSDL outlined in rawws-conventions, keep the following notes in mind when reading the documentation in sdkref_classes and sdkref_enums:

1. Any COM method call becomes a plain function call in the raw web service, with the object as an additional first parameter (before the "real" parameters listed in the documentation). So when the documentation says that the `IVirtualBox` interface supports the `createMachine()` method (see IVirtualBox::createMachine()), the web service operation is `IVirtualBox_createMachine(...)`, and a managed object reference to an `IVirtualBox` object must be passed as the first argument.

2. For attributes in interfaces, there will be at least one "get" function; there will also be a "set" function, unless the attribute is "readonly". The attribute name will be appended to the "get" or "set" prefix, with a capitalized first letter. So, the "version" readonly attribute of the `IVirtualBox` interface can be retrieved by calling `IVirtualBox_getVersion(vbox)`, with `vbox` being the VirtualBox object.

3. Whenever the API documentation says that a method (or an attribute getter) returns an object, it will returned a managed object reference in the web service instead. As said above, managed object references should be released if the web service client does not log off again immediately!

#### Raw web service example for Java with Axis

Axis is an older web service toolkit created by the Apache foundation. If your distribution does not have it installed, you can get a binary from http://axis.apache.org. The following examples assume that you have Axis 1.4 installed.

The VirtualBox SDK ships with an example for Axis that, again, is called `clienttest.java` and that imitates a few `VBoxManage` commands and sends them to the VirtualBox web service.

To try out the raw web service with Axis complete the following steps:

1. Create a working directory somewhere. Under your VirtualBox installation directory, find the `sdk/webservice/samples/java/axis/` directory and copy the file `clienttest.java` to your working directory.

2. Open a terminal in your working directory. Execute the following command:

       java org.apache.axis.wsdl.WSDL2Java /path/to/vboxwebService.wsdl

   The `vboxwebService.wsdl` file should be located in the `sdk/webservice/` directory.

   If this fails, your Apache Axis may not be located on your system classpath, and you may have to adjust the CLASSPATH environment variable. Something like this:

       export CLASSPATH="/path-to-axis-1_4/lib/*":$CLASSPATH

   Use the directory where the Axis JAR files are located. Mind the quotes so that your shell passes the "*" character to the java executable without expanding. Alternatively, add a corresponding `-classpath` argument to the "java" call above.

   If the command executes successfully, you should see an "org" directory with subdirectories containing Java source files in your working directory. These classes represent the interfaces that the VirtualBox web service offers, as described by the WSDL file.

   This is the bit that makes using web services so attractive to client developers: if a language's toolkit understands WSDL, it can generate large amounts of support code automatically. Clients can then easily use this support code and can be done with just a few lines of code.

3. Next, compile the `clienttest.java` source:

       javac clienttest.java

   This should yield a "clienttest.class" file.

4. To start the VirtualBox web service, open a second terminal and change to the directory where the VirtualBox executables are located. Then type:

       ./vboxwebsrv -v

   The web service now waits for connections and will run until you press Ctrl+C in this second terminal. The -v argument causes it to log all connections to the terminal. (See runvboxwebsrv for details on how to run the web service.)

5. Back in the original terminal where you compiled the Java source, run the resulting binary, which will then connect to the web service:

       java clienttest

   The client sample will connect to the web service (on localhost, but the code could be changed to connect remotely if the web service was running on a different machine) and make a number of method calls. It will output the version number of your VirtualBox installation and a list of all virtual machines that are currently registered (with a bit of seemingly random data, which will be explained later).

#### Raw web service example for Perl

We also ship a small sample for Perl. It uses the SOAP::Lite perl module to communicate with the VirtualBox web service.

The `sdk/bindings/webservice/perl/lib/` directory contains a pre-generated Perl module that allows for communicating with the web service from Perl. You can generate such a module yourself using the "stubmaker" tool that comes with SOAP::Lite, but since that tool is slow as well as sometimes unreliable, we ship a working module with the SDK for your convenience.

Perform the following steps:

1. If SOAP::Lite is not yet installed on your system, you will need to install the package first. On Debian-based systems, the package is called `libsoap-lite-perl`; on Gentoo, it's `dev-perl/SOAP-Lite`.

2. Open a terminal in the `sdk/bindings/webservice/perl/samples/` directory.

3. To start the VirtualBox web service, open a second terminal and change to the directory where the VirtualBox executables are located. Then type:

       ./vboxwebsrv -v

   The web service now waits for connections and will run until you press Ctrl+C in this second terminal. The -v argument causes it to log all connections to the terminal. (See runvboxwebsrv for details on how to run the web service.)

4. In the first terminal with the Perl sample, run the clienttest.pl script:

       perl -I ../lib clienttest.pl

#### Programming considerations for the raw web service

If you use the raw web service, you need to keep a number of things in mind, or you will sooner or later run into issues that are not immediately obvious. By contrast, the object-oriented client-side libraries described in glue take care of these things automatically and thus greatly simplify using the web service.

##### Fundamental conventions

If you are familiar with other web services, you may find that the VirtualBox web service behaves a bit differently to accommodate for the fact that the VirtualBox web service more or less maps the VirtualBox Main COM API. The primary challenges in mapping the VirtualBox Main COM API to the web service are as follows:

- Web services, as expressed by WSDL, are not object-oriented. Even worse, they are normally stateless (or, in web services terminology, "loosely coupled"). Web service operations are entirely procedural, and one cannot normally make assumptions about the state of a web service between function calls.

  In particular, this normally means that you cannot work on objects in one method call that were created by another call.

- By contrast, the VirtualBox Main API, being expressed in COM, is object-oriented and works entirely on objects, which are grouped into public interfaces, which in turn have attributes and methods associated with them.

For the VirtualBox web service, this results in three fundamental conventions:

1. All function names in the VirtualBox web service consist of an interface name and a method name, joined together by an underscore. This is because there are only functions ("operations") in WSDL, but no classes, interfaces, or methods.

2. All calls to the VirtualBox web service (except for logon, see below) take a managed object reference as the first argument, representing the object upon which the underlying method is invoked. (Managed object references are explained in detail below; see managed-object-references.)

   So, when one would normally code, in the pseudo-code of an object-oriented language, to invoke a method upon an object:

       IMachine machine;
       result = machine.getName();

   In the VirtualBox web service, this looks something like this (again, pseudo-code):

       IMachineRef machine;
       result = IMachine_getName(machine);

3. To make the web service stateful, and objects persistent between method calls, the VirtualBox web service introduces a session manager (by way of the IWebsessionManager interface), which manages object references. Any client wishing to interact with the web service must first log on to the session manager and in turn receives a managed object reference to an object that supports the IVirtualBox interface (the basic interface in the Main API).

In other words, as opposed to other web services, the VirtualBox web service is both object-oriented and stateful.

##### Example: A typical web service client session

A typical short web service session to retrieve the version number of the VirtualBox web service (to be precise, the underlying Main API version number) looks like this:

1. A client logs on to the web service by calling IWebsessionManager::logon() with a valid user name and password. See websrv_authenticate for details about how authentication works.

2. On the server side, `vboxwebsrv` creates a session, which persists until the client calls IWebsessionManager::logoff() or the session times out after a configurable period of inactivity (see vboxwebsrv-ref).

   For the new session, the web service creates an instance of IVirtualBox. This interface is the most central one in the Main API and allows access to all other interfaces, either through attributes or method calls. For example, IVirtualBox contains a list of all virtual machines that are currently registered (as they would be listed on the left side of the VirtualBox main program).

   The web service then creates a managed object reference for this instance of IVirtualBox and returns it to the calling client, which receives it as the return value of the logon call. Something like this:

       string oVirtualBox;
       oVirtualBox = webservice.IWebsessionManager_logon("user", "pass");

   (The managed object reference "oVirtualBox" is just a string consisting of digits and dashes. However, it is a string with a meaning and will be checked by the web service. For details, see below. As hinted above, IWebsessionManager::logon() is the only operation provided by the web service which does not take a managed object reference as the first argument!)

3. The VirtualBox Main API documentation explains that the `IVirtualBox` interface has a version attribute, which is a string. For each attribute, there is a "get" and a "set" method in COM, which maps to the corresponding operations in the web service. So, to retrieve the "version" attribute of this `IVirtualBox` object, the web service client does this:

       string version;
       version = webservice.IVirtualBox_getVersion(oVirtualBox);

       print version;

   And it will print "&VBOX_VERSION_MAJOR;.&VBOX_VERSION_MINOR;.&VBOX_VERSION_BUILD;".

4. The web service client calls IWebsessionManager::logoff() with the VirtualBox managed object reference. This will clean up all allocated resources.

##### Managed object references

To a web service client, a managed object reference looks like a string: two 64-bit hex numbers separated by a dash. This string, however, represents a COM object that "lives" in the web service process. The two 64-bit numbers encoded in the managed object reference represent a session ID (which is the same for all objects in the same web service session, i.e. for all objects after one logon) and a unique object ID within that session.

Managed object references are created in two situations:

1. When a client logs on, by calling IWebsessionManager::logon().

   Upon logon, the websession manager creates one instance of IVirtualBox, which can be used for directly performing calls to its methods, or used as a parameter for calling some methods of IWebsessionManager. Creating Main API session objects is performed using IWebsessionManager::getSessionObject().

   (Technically, there is always only one IVirtualBox object, which is shared between all websessions and clients, as it is a COM singleton. However, each session receives its own managed object reference to it.)

2. Whenever a web service clients invokes an operation whose COM implementation creates COM objects.

   For example, IVirtualBox::createMachine() creates a new instance of IMachine; the COM object returned by the COM method call is then wrapped into a managed object reference by the web server, and this reference is returned to the web service client.

Internally, in the web service process, each managed object reference is simply a small data structure, containing a COM pointer to the "real" COM object, the web session ID and the object ID. This structure is allocated on creation and stored efficiently in hashes, so that the web service can look up the COM object quickly whenever a web service client wishes to make a method call. The random session ID also ensures that one web service client cannot intercept the objects of another.

Managed object references are not destroyed automatically and must be released by explicitly calling IManagedObjectRef::release(). This is important, as otherwise hundreds or thousands of managed object references (and corresponding COM objects, which can consume much more memory!) can pile up in the web service process and eventually cause it to deny service.

To reiterate: The underlying COM object, which the reference points to, is only freed if the managed object reference is released. It is therefore vital that web service clients properly clean up after the managed object references that are returned to them.

When a web service client calls IWebsessionManager::logoff(), all managed object references created during the session are automatically freed. For short-lived sessions that do not create a lot of objects, logging off may therefore be sufficient, although it is certainly not "best practice".

##### Some more detail about web service operation

###### SOAP messages

Whenever a client makes a call to a web service, this involves a complicated procedure internally. These calls are remote procedure calls. Each such procedure call typically consists of two "message" being passed, where each message is a plain-text HTTP request with a standard HTTP header and a special XML document following. This XML document encodes the name of the procedure to call and the argument names and values passed to it.

To give you an idea of what such a message looks like, assuming that a web service provides a procedure called "SayHello", which takes a string "name" as an argument and returns "Hello" with a space and that name appended, the request message could look like this:

    <?xml version="1.0" encoding="UTF-8"?>
    <SOAP-ENV:Envelope
     xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
     xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema"
     xmlns:test="http://test/">
    <SOAP-ENV:Body>
       <test:SayHello>
        <name>Peter</name>
       </test:SayHello>
     </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>

A similar message -- the "response" message -- would be sent back from the web service to the client, containing the return value "Hello Peter".

Most programming languages provide automatic support to generate such messages whenever code in that programming language makes such a request. In other words, these programming languages allow for writing something like this (in pseudo-C++ code):

    webServiceClass service("localhost", 18083); // server and port
    string result = service.SayHello("Peter");  // invoke remote procedure

and would, for these two pseudo-lines, automatically perform these steps:

1. Prepare a connection to the web service running on port 18083 of "localhost".

2. Generate a SOAP message similar to the above example for the `SayHello()` function of the web service by encoding all arguments of the remote procedure call (which could involve all kinds of type conversions and complex marshalling for arrays and structures).

3. Connect to the web service via HTTP and then send that message.

4. Wait for the web service to send a response message.

5. Decode that response message and put the return value of the remote procedure into the "result" variable.

###### Service descriptions in WSDL

In the above explanations about SOAP, it wasn't explained how the programming language learns about how to translate function calls in its own syntax into proper SOAP messages. In other words, the programming language needs to know what operations the web service supports and what types of arguments are required for the operation's data in order to be able to properly serialize and deserialize the data to and from the web service. For example, if a web service operation expects a number in "double" floating point format for a particular parameter, the programming language cannot send it a string instead.

For this, the Web Service Definition Language (WSDL) was invented, another XML substandard that describes exactly what operations the web service supports and, for each operation, which parameters and types are needed with each request and response message. WSDL descriptions can be incredibly verbose, and one of the few good things that can be said about this standard is that it is indeed supported by most programming languages.

So, if it is said that a programming language "supports" web services, this typically means that a programming language has support for parsing WSDL files and somehow integrating the remote procedure calls into the native language syntax -- for example, as shown in the Java sample in webservice-java-sample.

For details about how programming languages support web services, please refer to the documentation that comes with the individual language. Here are a few pointers:

1. For C++, among many others, the gSOAP toolkit is a good option. Parts of gSOAP are also used in VirtualBox to implement the VirtualBox web service.

2. For Java, there are several implementations already described in this document (see glue-jax-ws and webservice-java-sample).

3. Perl supports WSDL via the SOAP::Lite package. This in turn comes with a tool called `stubmaker.pl` that allows you to turn any WSDL file into a Perl package that you can import. (You can also import any WSDL file "live" by having it parsed every time the script runs, but that can take a while.) You can then code (again, assuming the above example):

       my $result = servicename->sayHello("Peter");

   A sample that uses SOAP::Lite was described in raw-webservice-perl.

### Using COM/XPCOM directly

If you do not require remote procedure calls such as those offered by the VirtualBox web service, and if you know Python or C++ as well as COM, you might find it preferable to program VirtualBox's Main API directly via COM.

COM stands for "Component Object Model" and is a standard originally introduced by Microsoft in the 1990s for Microsoft Windows. It allows for organizing software in an object-oriented way and across processes; code in one process may access objects that live in another process.

COM has several advantages: it is language-neutral, meaning that even though all of VirtualBox is internally written in C++, programs written in other languages can communicate with it. COM also cleanly separates interface from implementation, so that external programs do not need to know anything about the messy and complicated details of VirtualBox internals.

On a Windows host, all parts of VirtualBox will use the COM functionality that is native to Windows. On other hosts (including Linux), VirtualBox comes with a built-in implementation of XPCOM, as originally created by the Mozilla project, which we have enhanced to support interprocess communication on a level comparable to Microsoft COM. Internally, VirtualBox has an abstraction layer that allows the same VirtualBox code to work both with native COM as well as our XPCOM implementation.

#### Python COM API

On Windows, Python scripts can use COM and VirtualBox interfaces to control almost all aspects of virtual machine execution. For example, you can use the following commands to instantiate the VirtualBox object and start a VM:

           vbox = win32com.client.Dispatch("VirtualBox.VirtualBox")
           session = win32com.client.Dispatch("VirtualBox.Session")
           mach = vbox.findMachine("uuid or name  of machine to start")
           progress = mach.launchVMProcess(session, "gui", "")
           progress.waitForCompletion(-1)

Also, see `sdk/bindings/glue/python/samples/vboxshell.py` for more advanced usage scenarious. However, unless you have specific requirements, we strongly recommend that you use the generic glue layer described in the next section to access MS COM objects.

#### Common Python bindings layer

As different wrappers ultimately provide access to the same underlying API, and to simplify porting and development of Python applications using the VirtualBox Main API, we developed a common glue layer that abstracts out most platform-specific details from the application and allows the developer to focus on application logic. The VirtualBox installer automatically sets up this glue layer for the system default Python installation.

See glue-python-setup for details on how to set up the glue layer if you want to use a different Python installation, or if the VirtualBox installer failed to detect and set it up accordingly.

The minimum supported Python version is 2.6.

In this layer, the class `VirtualBoxManager` hides most platform-specific details. It can be used to access both the local (COM) and the web service based API. The following code can be used by an application to use the glue layer.

    # This code assumes vboxapi.py from VirtualBox distribution
    # being in PYTHONPATH, or installed system-wide
    from vboxapi import VirtualBoxManager

    # This code initializes VirtualBox manager with default style
    # and parameters
    virtualBoxManager = VirtualBoxManager(None, None)

    # Alternatively, one can be more verbose, and initialize
    # glue with web service backend, and provide authentication
    # information
    virtualBoxManager = VirtualBoxManager("WEBSERVICE",
                                          {'url':'http://myhost.com::18083/',
                                          'user':'me',
                                          'password':'secret'})

We supply the `VirtualBoxManager` constructor with 2 arguments: style and parameters. Style defines which bindings style to use (could be "MSCOM", "XPCOM" or "WEBSERVICE"), and if set to `None` defaults to usable platform bindings (MS COM on Windows, XPCOM on other platforms). The second argument defines parameters, passed to the platform-specific module, as we do in the second example, where we pass a username and password to be used to authenticate against the web service.

After obtaining the `VirtualBoxManager` instance, one can perform operations on the IVirtualBox class. For example, the following code will a start virtual machine by name or ID:

    from vboxapi import VirtualBoxManager
    mgr = VirtualBoxManager(None, None)
    vbox = mgr.getVirtualBox()
    name = "Linux"
    mach = vbox.findMachine(name)
    session = mgr.getSessionObject(vbox)
    progress = mach.launchVMProcess(session, "gui", "")
    progress.waitForCompletion(-1)
    mgr.closeMachineSession(session)

The following code will print all registered machines and their log folders:

    from vboxapi import VirtualBoxManager
    mgr = VirtualBoxManager(None, None)
    vbox = mgr.getVirtualBox()

    for m in mgr.getArray(vbox, 'machines'):
        print "Machine '%s' logs in '%s'" %(m.name, m.logFolder)

The code above demonstrates cross-platform access to array properties (certain limitations prevent one from using `vbox.machines` to access a list of available virtual machines in the case of XPCOM), and a mechanism for uniform session creation and closure (`mgr.getSessionObject()`).

##### Manual or subsequent setup

If you want to use the glue layer with a different Python installation or the installer failed to set it up, then use these steps in a shell to install the necessary files:

        # cd VBOX_INSTALL_PATH/sdk/installer
        # python vboxapisetup.py install

On Windows hosts, a Python distribution along with the win32api bindings package need to be installed as a prerequisite.

#### C++ COM API

C++ is the language that VirtualBox itself is written in, so C++ is the most direct way to use the Main API -- but it is not necessarily the easiest, as using COM and XPCOM has its own set of complications.

VirtualBox ships with sample programs that demonstrate how to use the Main API to implement a number of tasks on your host platform. These samples can be found in the `sdk/bindings/xpcom/samples` directory for Linux, Mac OS X and Solaris and `sdk/bindings/mscom/samples` for Windows. The two samples are actually different, because the one for Windows uses native COM, whereas the other uses our XPCOM implementation, as described above.

Since COM and XPCOM are conceptually very similar but vary in the implementation details, we have created a "glue" layer that shields COM client code from these differences. All VirtualBox uses is this glue layer, so the same code written once works on both Windows hosts (with native COM) as well as on other hosts (with our XPCOM implementation). It is recommended to always use this glue code instead of using the COM and XPCOM APIs directly, as it is very easy to make your code completely independent from the platform it is running on.

In order to encapsulate platform differences between Microsoft COM and XPCOM, the following items should be kept in mind when using the glue layer:

1. Attribute getters and setters. COM has the notion of "attributes" in interfaces, which roughly compare to C++ member variables in classes. The difference is that for each attribute declared in an interface, COM automatically provides a "get" method to return the attribute's value. Unless the attribute has been marked as "readonly", a "set" attribute is also provided.

   To illustrate, the IVirtualBox interface has a "version" attribute, which is read-only and of the "wstring" type (the standard string type in COM). As a result, you can call the "get" method for this attribute to retrieve the version number of VirtualBox.

   Unfortunately, the implementation differs between COM and XPCOM. Microsoft COM names the "get" method like this: `get_Attribute()`, whereas XPCOM uses this syntax: `GetAttribute()` (and accordingly for "set" methods). To hide these differences, the VirtualBox glue code provides the `COMGETTER(attrib)` and `COMSETTER(attrib)` macros. So, `COMGETTER(version)()` (note, two pairs of brackets) expands to `get_Version()` on Windows and `GetVersion()` on other platforms.

2. Unicode conversions. While the rest of the modern world has pretty much settled on encoding strings in UTF-8, COM, unfortunately, uses UCS-16 encoding. This requires a lot of conversions, in particular between the VirtualBox Main API and the Qt GUI, which, like the rest of Qt, likes to use UTF-8.

   To facilitate these conversions, VirtualBox provides the `com::Bstr` and `com::Utf8Str` classes, which support all kinds of conversions back and forth.

3. COM autopointers. Possibly the greatest pain of using COM -- reference counting -- is alleviated by the `ComPtr<>` template provided by the `ptr.h` file in the glue layer.

#### Event queue processing

Both VirtualBox client programs and front-ends should periodically perform processing of the main event queue, and do that on the application's main thread. In the case of a typical GUI Windows/Mac OS application this happens automatically in the GUI's dispatch loop. However, for CLI only application, the appropriate actions have to be taken. For C++ applications, the VirtualBox SDK provided glue method

                int EventQueue::processEventQueue(uint32_t cMsTimeout)

can be used for both blocking and non-blocking operations. For the Python bindings, a common layer provides the method

              VirtualBoxManager.waitForEvents(ms)

with similar semantics.

Things get somewhat more complicated for situations where an application using VirtualBox cannot directly control the main event loop and the main event queue is separated from the event queue of the programming library (for example in case of Qt on Unix platforms). In such a case, the application developer is advised to use a platform/toolkit specific event injection mechanism to force event queue checks either based on periodic timer events delivered to the main thread, or by using custom platform messages to notify the main thread when events are available. See the Qt (VirtualBox) front-end as an example.

#### Visual Basic and Visual Basic Script (VBS) on Windows hosts

On Windows hosts, one can control some of the VirtualBox Main API functionality from VBS scripts, and pretty much everything from Visual Basic programs.

The difference results from the way VBS treats COM safearrays, which are used to keep lists in the Main API. VBS expects every array element to be a `VARIANT`, which is too strict a limitation for any high performance API. We may lift this restriction for interface APIs in a future version, or alternatively provide conversion APIs.

VBS is a scripting language available in any recent Windows environment. As an example, the following VBS code will print the VirtualBox version:

             set vb = CreateObject("VirtualBox.VirtualBox")
             Wscript.Echo "VirtualBox version " & vb.version

See `sdk/bindings/mscom/vbs/sample/vboxinfo.vbs` for the complete sample.

Visual Basic is a popular high level language capable of accessing COM objects. The following VB code will iterate over all available virtual machines:

             Dim vb As VirtualBox.IVirtualBox

             vb = CreateObject("VirtualBox.VirtualBox")
             machines = ""
             For Each m In vb.Machines
                m = m & " " & m.Name
             Next

See `sdk/bindings/mscom/vb/sample/vboxinfo.vb` for the complete sample.

#### C bindings to the VirtualBox API

The VirtualBox API was originally designed to be object oriented and leverages XPCOM or COM as the middleware to natively map the API to C++. This means that in order to use the VirtualBox API from C there needs to be some helper code to bridge the language differences and reduce the differences between platforms.

##### Cross-platform C bindings to the VirtualBox API

Starting with version 4.3, VirtualBox offers C bindings which allows using the same C client sources for all platforms, covering Windows, Linux, Mac OS X and Solaris. It is the preferred way to write API clients, even though the old style is still available.

##### Getting started

The following sections describe how to use the VirtualBox API in a C program. The necessary files are included in the SDK, in the directories `sdk/bindings/c/include` and `sdk/bindings/c/glue`.

As part of the SDK, a sample program `tstCAPIGlue.c` is provided in the directory `sdk/bindings/c/samples` which demonstrates using the C bindings to initialize the API, get handles for VirtualBox and Session objects, make calls to list and start virtual machines, monitor events, and uninitialize resources when done. The sample program is trying to illustrate all relevant concepts, so it is a great source of detail information. Among many other generally useful code sequences it contains a function which shows how to retrieve error details in C code if they are available from the API call.

The sample program `tstCAPIGlue` can be built using the provided `Makefile` and can be run without arguments.

It uses the VBoxCAPIGlue library (source code is in directory `sdk/bindings/c/glue`, to be used in your API client code) to open the C binding layer during runtime, which is preferred to other means as it isolates the code which locates the necessary dynamic library, using a known working way which works on all platforms. If you encounter problems with this glue code in `VBoxCAPIGlue.c`, let the VirtualBox developers know, rather than inventing incompatible solutions.

The following sections document the important concepts needed to correctly use the C bindings, as it is vital for developing API client code which manages memory correctly, updates the reference counters correctly, and avoids crashes and memory leaks. Often API clients need to handle events, so the C API specifics are also described below.

##### VirtualBox C API initialization

Just like in C++, the API and the underlying middleware needs to be initialized before it can be used. The `VBoxCAPI_v&VBOX_VERSION_MAJOR;_&VBOX_VERSION_MINOR;.h` header file provides the interface to the C bindings, but you can alternatively and more conveniently just include `VBoxCAPIGlue.h`, as this avoids the VirtualBox version dependent header file name and makes sure that the global variable `g_pVBoxFuncs` contains a pointer to the structure which contains the helper function pointers. Here's how to initialize the C API:

    #include "VBoxCAPIGlue.h"
    ...
    IVirtualBoxClient *vboxclient   = NULL;

    /*
     * VBoxCGlueInit() loads the necessary dynamic library, handles errors
     * (producing an error message hinting what went wrong) and gives you
     * the pointer to the function table (g_pVBoxFuncs).
     *
     * Once you get the function table, then how and which functions
     * to use is explained below.
     *
     * g_pVBoxFuncs->pfnClientInitialize does all the necessary startup
     * action and provides us with pointers to an IVirtualBoxClient instance.
     * It should be matched by a call to g_pVBoxFuncs->pfnClientUninitialize()
     * when done.
     */

    if (VBoxCGlueInit())
    {
        fprintf(stderr, "s: FATAL: VBoxCGlueInit failed: %s\n",
                argv[0], g_szVBoxErrMsg);
        return EXIT_FAILURE;
    }

    g_pVBoxFuncs->pfnClientInitialize(NULL, &vboxclient);
    if (!vboxclient)
    {
        fprintf(stderr, "%s: FATAL: could not get VirtualBoxClient reference\n",
                argv[0]);
        return EXIT_FAILURE;
    }

If `vboxclient` is still `NULL` this means the initializationi failed and the VirtualBox C API cannot be used.

It is possible to write C applications using multiple threads which all use the VirtualBox API, as long as you're initializing the C API in each thread which your application creates. This is done with `g_pVBoxFuncs->pfnClientThreadInitialize()` and likewise before the thread is terminated the API must be uninitialized with `g_pVBoxFuncs->pfnClientThreadUninitialize()`. You don't have to use these functions in worker threads created by COM/XPCOM (which you might utilize if your code uses active event handling), since everything is initialized correctly already. On Windows the C bindings create a marshaller which supports a wide range of COM threading models, from Single-Threaded Apartments (STA) to Multithreaded Apartments (MTA), so you don't have to worry about these details unless you plan to use active event handlers. See the sample code for how to get this to work reliably (in other words think twice if passive event handling isn't the better solution after you looked at the sample code).

##### C API attribute and method invocation

Method invocation is straightforward. It looks very similar to the C++ mechanism since it also uses a macro which internally accesses the vtable and additionally needs to be passed a pointer to the object as the first argument to serve as the `this` pointer.

Using the C bindings all method invocations return a numeric result code of type `HRESULT` (with a few exceptions which normally are not relevant).

If an interface is specified as returning an object, a pointer to a pointer to the appropriate object must be passed as the last argument. The method will then store an object pointer in that location.

Likewise, attributes (properties) can be queried or set using method invocations, using specially named methods. For each attribute there exists a getter method, the name of which is composed of `get_` followed by the capitalized attribute name. Unless the attribute is read-only, an analogous `set_` method exists. Let's apply these rules to get the `IVirtualBox` reference, an `ISession` instance reference and read the IVirtualBox::revision attribute:

    IVirtualBox *vbox               = NULL;
    ISession *session               = NULL;
    HRESULT rc;
    ULONG revision;

    rc = IVirtualBoxClient_get_VirtualBox(vboxclient, &vbox);

    if (FAILED(rc) || !vbox)
    {
        PrintErrorInfo(argv[0], "FATAL: could not get VirtualBox reference", rc);
        return EXIT_FAILURE;
    }
    rc = IVirtualBoxClient_get_Session(vboxclient, &session);
    if (FAILED(rc) || !session)
    {
        PrintErrorInfo(argv[0], "FATAL: could not get Session reference", rc);
        return EXIT_FAILURE;
    }

    rc = IVirtualBox_get_Revision(vbox, &revision);
    if (SUCCEEDED(rc))
    {
        printf("Revision: %u\n", revision);
    }

The convenience macros for calling a method are named by prepending the method name with the interface name (using `_` as the separator).

So far only attribute getters were illustrated, but generic method calls are straightforward, too:

    IMachine *machine = NULL;
    BSTR vmname = ...;
    ...
    /*
     * Calling IMachine::findMachine(...)
     */
    rc = IVirtualBox_FindMachine(vbox, vmname, &machine);

As a more complicated example of a method invocation, let's call IMachine::launchVMProcess which returns an IProgress object. Note again that the method name is capitalized:

    IProgress *progress;
    ...
    rc = IMachine_LaunchVMProcess(
        machine,       /* this  */
        session,       /* arg 1 */
        sessionType,   /* arg 2 */
        env,           /* arg 3 */
        &progress      /* Out   */
    );

All objects with their methods and attributes are documented in sdkref_classes.

##### String handling

When dealing with strings you have to be aware of a string's encoding and ownership.

Internally, the API uses UTF-16 encoded strings. A set of conversion functions is provided to convert other encodings to and from UTF-16. The type of a UTF-16 character is `BSTR` (or its constant counterpart `CBSTR`), which is an array type, represented by a pointer to the start of the zero-terminated string. There are functions for converting between UTF-8 and UTF-16 strings available through `g_pVBoxFuncs`:

    int (*pfnUtf16ToUtf8)(CBSTR pwszString, char **ppszString);
    int (*pfnUtf8ToUtf16)(const char *pszString, BSTR *ppwszString);

The ownership of a string determines who is responsible for releasing resources associated with the string. Whenever the API creates a string (essentially for output parameters), ownership is transferred to the caller. To avoid resource leaks, the caller should release resources once the string is no longer needed. There are plenty of examples in the sample code.

##### Array handling

Arrays are handled somewhat similarly to strings, with the additional information of the number of elements in the array. The exact details of string passing depends on the platform middleware (COM/XPCOM), and therefore the C binding offers helper functions to gloss over these differences.

Passing arrays as input parameters to API methods is usually done by the following sequence, calling a hypothetical `IArrayDemo_PassArray` API method:

    static const ULONG aElements[] = { 1, 2, 3, 4 };
    ULONG cElements = sizeof(aElements) / sizeof(aElements[0]);
    SAFEARRAY *psa = NULL;
    psa = g_pVBoxFuncs->pfnSafeArrayCreateVector(VT_I4, 0, cElements);
    g_pVBoxFuncs->pfnSafeArrayCopyInParamHelper(psa, aElements, sizeof(aElements));
    IArrayDemo_PassArray(pThis, ComSafeArrayAsInParam(psa));
    g_pVBoxFuncs->pfnSafeArrayDestroy(psa);

Likewise, getting arrays results from output parameters is done using helper functions which manage memory allocations as part of their other functionality:

    SAFEARRAY *psa = g_pVBoxFuncs->pfnSafeArrayOutParamAlloc();
    ULONG *pData;
    ULONG cElements;
    IArrayDemo_ReturnArray(pThis, ComSafeArrayAsOutTypeParam(psa, ULONG));
    g_pVBoxFuncs->pfnSafeArrayCopyOutParamHelper((void **)&pData, &cElements, VT_I4, psa);
    g_pVBoxFuncs->pfnSafeArrayDestroy(psa);

This covers the necessary functionality for all array element types except interface references. These need special helpers to manage the reference counting correctly. The following code snippet gets the list of VMs, and passes the first IMachine reference to another API function (assuming that there is at least one element in the array, to simplify the example):

    SAFEARRAY psa = g_pVBoxFuncs->pfnSafeArrayOutParamAlloc();
    IMachine **machines = NULL;
    ULONG machineCnt = 0;
    ULONG i;
    IVirtualBox_get_Machines(virtualBox, ComSafeArrayAsOutIfaceParam(machinesSA, IMachine *));
    g_pVBoxFuncs->pfnSafeArrayCopyOutIfaceParamHelper((IUnknown ***)&machines, &machineCnt, machinesSA);
    g_pVBoxFuncs->pfnSafeArrayDestroy(machinesSA);
    /* Now "machines" contains the IMachine references, and machineCnt the
     * number of elements in the array. */
    ...
    SAFEARRAY *psa = g_pVBoxFuncs->pfnSafeArrayCreateVector(VT_IUNKNOWN, 0, 1);
    g_pVBoxFuncs->pfnSafeArrayCopyInParamHelper(psa, (void *)&machines[0], sizeof(machines[0]));
    IVirtualBox_GetMachineStates(ComSafeArrayAsInParam(psa), ...);
    ...
    g_pVBoxFuncs->pfnSafeArrayDestroy(psa);
    for (i = 0; i < machineCnt; ++i)
    {
        IMachine *machine = machines[i];
        IMachine_Release(machine);
    }
    free(machines);

Handling output parameters needs more special handling than input parameters, thus only for the former are there special helpers while the latter is handled through the generic array support.

##### Event handling

The VirtualBox API offers two types of event handling, active and passive, and consequently there is support for both with the C API binding. Active event handling (based on asynchronous callback invocation for event delivery) is more difficult, as it requires the construction of valid C++ objects in C, which is inherently platform and compiler dependent. Passive event handling is much simpler, it relies on an event loop, fetching events and triggering the necessary handlers explicitly in the API client code. Both approaches depend on an event loop to make sure that events get delivered in a timely manner but otherwise differ in what else is required to implement the respective event handler type.

The C API sample contains code for both event handling styles, and one has to modify the appropriate `#define` to select which style is actually used by the compiled program. It allows a good comparison between the two variants and the code sequences are probably worth reusing without much change in other API clients with only minor adaptions.

Active event handling needs to ensure that the following helper function is called frequently enough in the primary thread:

    g_pVBoxFuncs->pfnProcessEventQueue(cTimeoutMS);

The actual event handler implementation is quite tedious, as it has to implement a complete API interface. Especially on Windows it is a lot of work to implement the complicated `IDispatch` interface, requiring loading COM type information and using it in the `IDispatch` method implementation. Overall this is quite tedious compared to passive event handling.

Passive event handling uses a similar event loop structure, which requires calling the following function in a loop, and processing the returned event appropriately:

    rc = IEventSource_GetEvent(pEventSource, pListener, cTimeoutMS, &pEvent);

After processing the event it needs to be marked as processed with the following method call:

    rc = IEventSource_EventProcessed(pEventSource, pListener, pEvent);

This is vital for vetoable events, as they would be stuck otherwise, waiting on whether the veto comes or not. It does not do any harm for other event types, and in the end is cheaper than checking if the event at hand is vetoable or not.

The general event handling concepts are described in the API specification (see events), including how to aggregate multiple event sources for processing in one event loop. As mentioned, the sample illustrates the practical aspects of how to use both types of event handling, active and passive, from a C application. Additional hints are in the comments documenting the helper methods in `VBoxCAPI_v&VBOX_VERSION_MAJOR;_&VBOX_VERSION_MINOR;.h`. The code complexity of active event handling (and its inherently platform/compiler specific aspects) should be motivation to use passive event handling wherever possible.

##### C API uninitialization

Uninitialization is performed by `g_pVBoxFuncs->pfnClientUninitialize().` If your program can exit in more than one place, it is a good idea to install this function as an exit handler using the C library function `atexit()` just after calling `g_pVBoxFuncs->pfnClientInitialize()` , e.g.

    #include <stdlib.h>
    #include <stdio.h>

    ...

    /*
     * Make sure g_pVBoxFuncs->pfnClientUninitialize() is called at exit, no
     * matter if we return from the initial call to main or call exit()
     * somewhere else. Note that atexit registered functions are not
     * called upon abnormal termination, i.e. when calling abort() or
     * signal().
     */

    if (atexit(g_pVBoxFuncs->pfnClientUninitialize()) != 0) {
        fprintf(stderr, "failed to register g_pVBoxFuncs->pfnClientUninitialize()\n");
        exit(EXIT_FAILURE);
    }

Another idea would be to write your own `void myexit(int status)` function, calling `g_pVBoxFuncs->pfnClientUninitialize()` followed by the real `exit()`, and use it instead of `exit()` throughout your program and at the end of `main.`

If you expect your program to be terminated by a signal (e.g. a user types CTRL-C sending SIGINT) you might want to install a signal handler setting a flag noting that a signal was sent and then calling `g_pVBoxFuncs->pfnClientUninitialize()` later on, not from the handler itself.

That said, if a client program forgets to call `g_pVBoxFuncs->pfnClientUninitialize()` before it terminates, there is a mechanism in place which will eventually release references held by the client. On Windows it can take quite a while, on the order of 6-7 minutes.

##### Compiling and linking

A program using the C binding has to open the library during runtime using the help of the glue code provided and as shown in the example `tstCAPIGlue.c`. Compilation and linking can be achieved with a makefile fragment similar to:

    # Where is the SDK directory?
    PATH_SDK      = ../../..
    CAPI_INC      = -I$(PATH_SDK)/bindings/c/include
    ifdef ProgramFiles
    PLATFORM_INC  = -I$(PATH_SDK)/bindings/mscom/include
    PLATFORM_LIB  = $(PATH_SDK)/bindings/mscom/lib
    else
    PLATFORM_INC  = -I$(PATH_SDK)/bindings/xpcom/include
    PLATFORM_LIB  = $(PATH_SDK)/bindings/xpcom/lib
    endif
    GLUE_DIR      = $(PATH_SDK)/bindings/c/glue
    GLUE_INC      = -I$(GLUE_DIR)

    # Compile Glue Library
    VBoxCAPIGlue.o: $(GLUE_DIR)/VBoxCAPIGlue.c
        $(CC) $(CFLAGS) $(CAPI_INC) $(PLATFORM_INC) $(GLUE_INC) -o $@ -c $<

    # Compile interface ID list
    VirtualBox_i.o: $(PLATFORM_LIB)/VirtualBox_i.c
        $(CC) $(CFLAGS) $(CAPI_INC) $(PLATFORM_INC) $(GLUE_INC) -o $@ -c $<

    # Compile program code
    program.o: program.c
        $(CC) $(CFLAGS) $(CAPI_INC) $(PLATFORM_INC) $(GLUE_INC) -o $@ -c $<

    # Link program.
    program: program.o VBoxCAPICGlue.o VirtualBox_i.o
        $(CC) -o $@ $^ -ldl -lpthread

##### Conversion of code using legacy C bindings

This section aims to make the task of converting code using the legacy C bindings to the new style a breeze by following these key steps.

One necessary change is adjusting your Makefile to reflect the different include paths. As shown in the makefile fragment above, there are now three relevant include directories. The XPCOM include directory is still relevant for platforms where the XPCOM middleware is used but most of its include files live elsewhere now so it's good to have it last. Additionally the `VirtualBox_i.c` file needs to be compiled and linked to the program since it contains the interface IDs (IIDs) relevant for the VirtualBox API, making sure they are not replicated endlessly if the code refers to them frequently.

The C API client code should include `VBoxCAPIGlue.h` instead of `VBoxXPCOMCGlue.h` or `VBoxCAPI_v&VBOX_VERSION_MAJOR;_&VBOX_VERSION_MINOR;.h`, as this makes sure the correct macros and internal translations are selected.

All API method calls (anything mentioning `vtbl`) should be rewritten using the convenience macros for calling methods, as these hide the internal details, are generally easier to use, and are shorter to type. You should remove as many as possible `(nsISupports **)` or similar typecasts, as the new style should use the correct type in most places, increasing the type safety in case of an error in the source code.

To gloss over the platform differences, API client code should no longer rely on XPCOM specific interface names such as `nsISupports`, `nsIException` and `nsIEventQueue`, and replace them by the platform independent interface names `IUnknown` and `IErrorInfo` for the first two respectively. Event queue handling should be replaced by using the platform independent way described in c-eventhandling.

Finally adjust the string and array handling to use the new helpers, as these make sure the code works without changes with both COM and XPCOM, which are significantly different in this area. The code should be double checked to see that it uses the correct way to manage memory and is freeing it only after the last use.

##### Legacy C bindings to VirtualBox API for XPCOM

This section applies to Linux, Mac OS X and Solaris hosts only and describes deprecated use of the API from C.

Starting with version 2.2, VirtualBox offers C bindings for its API which works only on platforms using XPCOM. Refer to the old SDK documentation (included in the SDK packages for version 4.3.6 or earlier) since it still applies unchanged. The fundamental concepts are similar (but the syntactical details are quite different) to the newer cross-platform C bindings which should be used for all new code, as the support for the old C bindings will go away in a major release after version 4.3.

## Basic VirtualBox concepts; some examples

The following explains some basic VirtualBox concepts such as the VirtualBox object, sessions and how virtual machines are manipulated and launched using the Main API. The coding examples use a pseudo-code style closely related to the object-oriented web service (OOWS) for JAX-WS. Depending on which environment you are using, you will need to adjust the examples.

### Obtaining basic machine information. Reading attributes

Any program using the Main API will first need access to the global VirtualBox object (see IVirtualBox), from which all other functionality of the API is derived. With the OOWS for JAX-WS, this is returned from the IWebsessionManager::logon() call.

To enumerate virtual machines, one would look at the "machines" array attribute in the VirtualBox object (see IVirtualBox::machines). This array contains all virtual machines currently registered with the host, each of them being an instance of IMachine. From each such instance, one can query additional information, such as the UUID, the name, memory, operating system and more by looking at the attributes; see the attributes list in IMachine documentation.

As mentioned in the preceding chapters, depending on your programming environment, attributes are mapped to corresponding "get" and (if the attribute is not read-only) "set" methods. So when the documentation says that IMachine has a "name" attribute, this means you need to code something like the following to get the machine's name:

    IMachine machine = ...;
    String name = machine.getName();

Boolean attribute getters can sometimes be called `isAttribute()` due to JAX-WS naming conventions.

### Changing machine settings: Sessions

As described in the previous section, to read a machine's attribute, one invokes the corresponding "get" method. One would think that to change settings of a machine, it would suffice to call the corresponding "set" method -- for example, to set a VM's memory to 1024 MB, one would call `setMemorySize(1024)`. Try that, and you will get an error: "The machine is not mutable."

So unfortunately, things are not that easy. VirtualBox is a complicated environment in which multiple processes compete for possibly the same resources, especially machine settings. As a result, machines must be "locked" before they can either be modified or started. This is to prevent multiple processes from making conflicting changes to a machine: it should, for example, not be allowed to change the memory size of a virtual machine while it is running. (You can't add more memory to a real computer while it is running either, at least not to an ordinary PC.) Also, two processes must not change settings at the same time, or start a machine at the same time.

These requirements are implemented in the Main API by way of "sessions", in particular, the ISession interface. Each process which talks to VirtualBox needs its own instance of ISession. In the web service, you can request the creation of such an object by calling IWebsessionManager::getSessionObject(). More complex management tasks might need multiple instances of ISession, and each call returns a new one.

This session object must then be used like a mutex semaphore in common programming environments. Before you can change machine settings, you must write-lock the machine by calling IMachine::lockMachine() with your process's session object.

After the machine has been locked, the ISession::machine attribute contains a copy of the original IMachine object upon which the session was opened, but this copy is "mutable": you can invoke "set" methods on it.

When done making the changes to the machine, you must call IMachine::saveSettings(), which will copy the changes you have made from your "mutable" machine back to the real machine and write them out to the machine settings XML file. This will make your changes permanent.

Finally, it is important to always unlock the machine again, by calling ISession::unlockMachine(). Otherwise, when the calling process exits, the machine will be moved to the "aborted" state, which can lead to loss of data.

So, as an example, the sequence to change a machine's memory to 1024 MB is something like this:

    IWebsessionManager mgr ...;
    IVirtualBox vbox = mgr.logon(user, pass);
    ...
    IMachine machine = ...;  // read-only machine
    ISession session = mgr.getSessionObject();
    machine.lockMachine(session, LockType.Write); // machine is now locked for writing
    IMachine mutable = session.getMachine();      // obtain the mutable machine copy
    mutable.setMemorySize(1024);
    mutable.saveSettings();                       // write settings to XML
    session.unlockMachine();

### Launching virtual machines

To launch a virtual machine, you call IMachine::launchVMProcess(). This instructs the VirtualBox engine to start a new process containing the virtual machine. The host system sees each virtual machine as a single process, even if the virtual machine has hundreds of its own processes running inside it. (This new VM process in turn obtains a write lock on the machine, as described above, to prevent conflicting changes from other processes; this is why opening another session will fail while the VM is running.)

Starting a machine looks something like this:

    IWebsessionManager mgr ...;
    IVirtualBox vbox = mgr.logon(user, pass);
    ...
    IMachine machine = ...;  // read-only machine
    ISession session = mgr.getSessionObject();
    IProgress prog = machine.launchVMProcess(session,
                                             "gui",  // session type
                                             "");    // possibly environment setting
    prog.waitForCompletion(10000);  // give the process 10 secs
    if (prog.getResultCode() != 0)  // check success
        System.out.println("Cannot launch VM!")

The caller's session object can then be used as a sort of remote control to the VM process that was launched. It contains a "console" object (see ISession::console) with which the VM can be paused, stopped, snapshotted or other things.

### VirtualBox events

In VirtualBox, "events" provide a uniform mechanism to register for and consume specific events. A VirtualBox client can register an "event listener" (represented by the IEventListener interface), which will then get notified by the server when an event (represented by the IEvent interface) happens.

The IEvent interface is an abstract parent interface for all events that can occur in VirtualBox. The actual events that the server sends out belong to one of the specific subclasses, for example IMachineStateChangedEvent or IMediumChangedEvent.

As an example, the VirtualBox GUI waits for machine events so it can update its display when the machine state changes or machine settings are modified, even if this happens in another client. This is how the GUI can automatically refresh its display even if you manipulate a machine from a different client such as VBoxManage.

To register an event listener to listen for events, you would use code similar to the following:

    EventSource es = console.getEventSource();
    IEventListener listener = es.createListener();
    VBoxEventType aTypes[] = (VBoxEventType.OnMachineStateChanged);
            // list of event types to listen for
    es.registerListener(listener, aTypes, false /* active */);
            // register passive listener
    IEvent ev = es.getEvent(listener, 1000);
            // wait up to one second for event to happen
    if (ev != null)
    {
        // downcast to specific event interface (in this case we have only registered
        // for one type, otherwise IEvent::type would tell us)
        IMachineStateChangedEvent mcse = IMachineStateChangedEvent.queryInterface(ev);
        ... // inspect and do something
        es.eventProcessed(listener, ev);
    }
    ...
    es.unregisterListener(listener);

A graphical user interface application would most likely want to start its own thread to wait for events and then process these in a loop.

The events mechanism was introduced with VirtualBox 3.3 and replaces various callback interfaces which were called for each event in the interface. The callback mechanism was not compatible with scripting languages, local Java bindings, and remote web services as they do not support callbacks. The new mechanism with events and event listeners works with all of these.

To simplify development of applications using events, the concept of an event aggregator was introduced. Essentially it's a mechanism to aggregate multiple event sources into one single event source, and then work with this single aggregated event source instead of the original sources. As an example, one can try out the VirtualBox Python shell's `recordDemo` option which records mouse and keyboard events using an event aggregator and displays them as separate event sources. The VirtualBox Python shell (vboxshell.py) is shipped with the SDK. The `recordDemo` code is essentially:

              listener = console.eventSource.createListener()
              agg = console.eventSource.createAggregator([console.keyboard.eventSource, console.mouse.eventSource])
              agg.registerListener(listener, [ctx['global'].constants.VBoxEventType_Any], False)
              registered = True
              end = time.time() + dur
              while  time.time() < end:
                  ev = agg.getEvent(listener, 1000)
                  processEent(ev)
              agg.unregisterListener(listener)

Without using aggregators consumers would have to either poll on both sources or start multiple threads to block on those sources.

## The VirtualBox shell

VirtualBox comes with an extensible shell which allows you to control your virtual machines from the command line. It is also a non-trivial example of how to use the VirtualBox APIs from Python for all three styles of the API (COM/XPCOM/WS).

You can easily extend this shell with your own commands. Simply create a subdirectory named `.config/VirtualBox/shexts` in your home directory (`.VirtualBox/shexts` on Windows systems and `Library/VirtualBox/shexts` on macOS systems) and put a Python file implementing your shell extension commands in this directory. This file must have an array named `commands` which contains your command definitions:

            commands = {
            'cmd1': ['Command cmd1 help', cmd1],
            'cmd2': ['Command cmd2 help', cmd2]
            }

For example, to create a command for creating hard drive images, the following code can be used:

            def createHdd(ctx,args):
              # Show some meaningful error message on wrong input
              if (len(args) < 3):
                print "usage: createHdd sizeM location type"
                return 0

              # Get arguments
              size = int(args[1])
              loc = args[2]
              if len(args) > 3:
                format = args[3]
              else:
                # And provide some meaningful defaults
                format = "vdi"

            # Call VirtualBox API, using context's fields
            hdd = ctx['vb'].createMedium(format, loc, ctx['global'].constants.AccessMode_ReadWrite, \
                                         ctx['global'].constants.DeviceType_HardDisk)
            # Access constants using ctx['global'].constants
            progress = hdd.createBaseStorage(size, (ctx['global'].constants.MediumVariant_Standard, ))
            # use standard progress bar mechanism
            ctx['progressBar'](progress)

            # Report errors
            if not hdd.id:
               print "cannot create disk (file %s exist?)" %(loc)
               return 0

            # Give user some feedback on success too
            print "created HDD with id: %s" %(hdd.id)

            # 0 means continue execution, other values mean exit from the interpreter
            return 0

          commands = {
            'myCreateHDD': ['Create virtual HDD, createHdd size location type', createHdd]
            }

Just store the above text in a file named `createHdd` (or any other meaningful name) in the `shexts` directory located as described above and then start the VirtualBox shell or just issue the `reloadExts` command if the shell is already running. Your new command will now be available.

## Main API changes to support the ARM64 architecture

VirtualBox 7.1 introduces support for running virtual machines on hosts containing an ARM CPU. Since VirtualBox has been designed and developed for virtualizing x86 hardware since its inception adding support for ARM CPUs required a variety of changes to the Main API to accommodate two different CPU architectures.

### Overview of the Changes to the Main API

In order to support two different types of processor architecture in the VirtualBox Main API the key abstraction was the addition of a new interface named IPlatform which contains the details which relate to the operating environment of a VM. The IPlatform interface is distinct from the VM itself (the IMachine interface), the VM management interfaces (IVirtualBox and IConsole), as well as the global properties of the VM (the ISystemProperties interface). The contents of the IPlatform interface can be broken down into three different categories:

- properties relating to the VM which are CPU architecture-neutral (IPlatformProperties)

- properties which are CPU architecture-specific (IPlatformX86 or IPlatformARM)

- attributes of the VM which are CPU architecture-neutral such as:

  - the architecture of the VM (IPlatform::architecture)

  - the type of chipset used by the VM (IPlatform::chipsetType)

  - the type of IOMMU used by the VM (IPlatform::iommuType).

The IPlatform interface can be retrieved from the IMachine interface via the new IMachine::platform attribute. The IPlatform::architecture attribute returns the architecture type in a new enumeration named PlatformArchitecture. This enumeration value can be used to determine which CPU-specific properties to query, for example:

          IPlatform platform;
          result = machine.getPlatform(platform);

          PlatformArchitecture_T platformArch;
          result = platform.getArchitecture(platformArch);
          if (platformArch == x86)
            IPlatformX86 platformX86;
            result = platform.getX86(platformX86);
          else if (platformArch == ARM)
            IPlatformARM platformARM;
            result = platform.getARM(platformARM);
          else
            error;

The value of the PlatformArchitecture enumeration can also be used when creating a new VM using IVirtualBox::createMachine.

The CPU architecture-neutral properties in (IPlatformProperties) can be found in several places:

- They can be retrieved from the IPlatform::properties attribute.

- They can be retrieved from the ISystemProperties::platform attribute.

- They can retrieved from the IVirtualBox interface using the new IVirtualBox::getPlatformProperties method.

The attributes and methods contained in IPlatformProperties were moved from the ISystemProperties interface as they can vary based on the platform of the VM:

### IPlatformProperties Attributes

Original Attribute | New Attribute
ISystemProperties::rawModeSupported | IPlatformProperties::rawModeSupported
ISystemProperties::exclusiveHwVirt | IPlatformProperties::exclusiveHwVirt
ISystemProperties::serialPortCount | IPlatformProperties::serialPortCount
ISystemProperties::parallelPortCount | IPlatformProperties::parallelPortCount
ISystemProperties::maxBootPosition | IPlatformProperties::maxBootPosition
ISystemProperties::supportedParavirtProviders[] | IPlatformProperties::supportedParavirtProviders[]
ISystemProperties::supportedFirmwareTypes[] | IPlatformProperties::supportedFirmwareTypes[]
ISystemProperties::supportedGuestOSTypes[] | IPlatformProperties::supportedGuestOSTypes[]
ISystemProperties::getSupportedGfxControllerTypes[] | IPlatformProperties::getSupportedGfxControllerTypes[]
ISystemProperties::supportedNetAdpPromiscModePols[] | IPlatformProperties::supportedNetAdpPromiscModePols[]
ISystemProperties::supportedNetworkAdapterTypes[] | IPlatformProperties::supportedNetworkAdapterTypes[]
ISystemProperties::supportedUartTypes[] | IPlatformProperties::supportedUartTypes[]
ISystemProperties::supportedUSBControllerTypes[] | IPlatformProperties::supportedUSBControllerTypes[]
ISystemProperties::supportedAudioControllerTypes[] | IPlatformProperties::supportedAudioControllerTypes[]
ISystemProperties::supportedBootDevices[] | IPlatformProperties::supportedBootDevices[]
ISystemProperties::supportedStorageBuses[] | IPlatformProperties::supportedStorageBuses[]
ISystemProperties::supportedStorageControllerTypes[] | IPlatformProperties::supportedStorageControllerTypes[]
ISystemProperties::supportedChipsetTypes[] | IPlatformProperties::supportedChipsetTypes[]
ISystemProperties::supportedIommuTypes[] | IPlatformProperties::supportedIommuTypes[]
ISystemProperties::supportedTpmTypes[] | IPlatformProperties::supportedTpmTypes[]

### IPlatformProperties Attributes

Original Method | New Method
ISystemProperties::getDeviceTypesForStorageBus | IPlatformProperties::getDeviceTypesForStorageBus
ISystemProperties::getMaxDevicesPerPortForStorageBus | IPlatformProperties::getMaxDevicesPerPortForStorageBus
ISystemProperties::getMaxInstancesOfStorageBus | IPlatformProperties::getMaxInstancesOfStorageBus
ISystemProperties::getMaxInstancesOfUSBControllerType | IPlatformProperties::getMaxInstancesOfUSBControllerType
ISystemProperties::getMaxNetworkAdapters | IPlatformProperties::getMaxNetworkAdapters
ISystemProperties::getMaxNetworkAdaptersOfType | IPlatformProperties::getMaxNetworkAdaptersOfType
ISystemProperties::getMaxPortCountForStorageBus | IPlatformProperties::getMaxPortCountForStorageBus
ISystemProperties::getMinPortCountForStorageBus | IPlatformProperties::getMinPortCountForStorageBus
ISystemProperties::getStorageBusForControllerType | IPlatformProperties::getStorageBusForControllerType
ISystemProperties::getStorageControllerHotplugCapable | IPlatformProperties::getStorageControllerHotplugCapable
ISystemProperties::getStorageControllerTypesForBus | IPlatformProperties::getStorageControllerTypesForBus

The single attribute and all of the properties contained in the new IPlatformX86 interface were moved from the IMachine interface as they are specific to the x86 CPU architecture:

### IPlatformX86 Attribute

Original Attribute | New Attribute
IMachine::HPETEnabled | IPlatformX86::HPETEnabled

### IPlatformX86 Methods

Original Method | New Method
IMachine::getCPUIDLeaf | IPlatformX86::getCPUIDLeaf
IMachine::getCPUIDLeafByOrdinal | IPlatformX86::getCPUIDLeafByOrdinal
IMachine::getCPUProperty | IPlatformX86::getCPUProperty
IMachine::getHWVirtExProperty | IPlatformX86::getHWVirtExProperty
IMachine::removeAllCPUIDLeaves | IPlatformX86::removeAllCPUIDLeaves
IMachine::removeCPUIDLeaf | IPlatformX86::removeCPUIDLeaf
IMachine::setCPUIDLeaf | IPlatformX86::setCPUIDLeaf
IMachine::setCPUProperty | IPlatformX86::setCPUProperty
IMachine::setHWVirtExProperty | IPlatformX86::setHWVirtExProperty

An itemized breakdown of the changes made to the Main API for ARM64 support is described below.

#### Changes to Classes (Interfaces)

##### New Classes (Interfaces) Added

- IPlatform

  An umbrella-like interface containing a collection of properties and attributes of the software environment of the VM.

- IPlatformX86

  An interface containing the x86-specific properties of the software environment of the VM.

- IPlatformARM

  An interface containing the ARM-specific properties of the software environment of the VM.

- IPlatformProperties

  An interface containing the properties specific to the platform of the VM.

- IHostX86

  An interface which provides further classification of the x86-specific properties of the physical host machine.

##### Classes (Interfaces) Renamed

Original Class Name | New Class Name
IBIOSSettings | IFirmwareSettings

The IBIOSSettings interface has been renamed to the more platform-neutral IFirmwareSettings.

##### New Methods Added to Classes (Interfaces)

- IPlatformProperties IVirtualBox::getPlatformProperties

  The new IVirtualBox::getPlatformProperties method returns an IPlatformProperties object which contains the platform-specific properties of a VM as described above.

- IGraphicsAdapter::isFeatureEnabled

  The new IGraphicsAdapter::isFeatureEnabled method returns whether a graphics feature is enabled for a specific adapter or not.

- IGraphicsAdapter::setFeature

  The new IGraphicsAdapter::setFeature enables or disables a graphics feature for a specific adapter.

##### New Attributes Added to Classes (Interfaces)

- IPlatformProperties ISystemProperties::platform

  The ISystemProperties interface gets a new platform attribute which returns an IPlatformProperties object which contains the platform-specific properties of a VM as described above.

- FirmwareType IFirmwareSettings::firmwareType

  The new IFirmwareSettings interface (renamed from IBIOSSettings) gets a new firmwareType attribute which returns a FirmwareType enumeration which contains the VM's firmware type.

- PlatformArchitecture IHost::architecture

  The IHost interface gets a new architecture attribute which returns a PlatformArchitecture enumeration which contains the platform's architecture.

- IHostX86 IHost::x86

  The IHost interface gets a new x86 attribute which returns an IHostX86 object which contains the x86-specific properties of the physical host machine.

- IPlatform IMachine::platform

  The IMachine interface gets a new platform attribute which returns an IPlatform object which contains the properties related to the platform of the VM.

- IFirmwareSettings IMachine::firmwareSettings

  The IMachine interface gets a new firmwareSettings attribute which returns an IFirmWareSettings object which contains the properties related to the platform of the VM.

##### Class (Interface) Attribute Changes

##### Classes Renamed

Original Class Name | New Class Name
BIOSBootMenuMode IBIOSSettings::bootMenuMode | FirmwareBootMenuMode IFirmwareSettings::bootMenuMode
IGraphicsAdapter::accelerate3DEnabled | IGraphicsAdapter::setFeature and IGraphicsAdapter::isFeatureEnabled
IGraphicsAdapter::accelerate2DVideoEnabled | IGraphicsAdapter::setFeature and IGraphicsAdapter::isFeatureEnabled

The IBIOSSettings::bootMenuMode attribute has been moved to the new IFirmwareSettings interface and now returns the firmware boot menu mode in the new FirmwareBootMenuMode enumeration.

##### Classes Renamed

Original Class Name | New Class Name
unsigned long ISerialPort::IOBase | unsigned long ISerialPort::IOAddress

The ISerialPort::IOBase attribute has been renamed to ISerialPort::IOAddress.

#### Changes to Enumerations

##### New Enumerations Added

- PlatformArchitecture

  The new PlatformArchitecture enumeration contains the CPU architecture type of the VM.

- GraphicsFeature

  The new GraphicsFeature enumeration contains graphics features to be used with the host and / or virtual graphics controller.

##### New Enumerations Values

- CPUArchitecture

  - ARMv8_32

  - ARMv8_64

  The CPUArchitecture enumeration gets two new additions corresponding to 32-bit and 64-bit ARMv8 CPUs respectively.

- AudioControllerType

  - VirtioSound

  The AudioControllerType enumeration gets a new value named VirtioSound.

- ChipsetType

  - ARMv8Virtual

  The ChipsetType enumeration gets a new value named ARMv8Virtual.

##### Enumerations Renamed

Original Enumeration Name | New Enumeration Name
CPUPropertyType | CPUPropertyTypeX86

The CPUPropertyType enumeration has been renamed to CPUPropertyTypeX86.

##### Enumerations Renamed

Original Enumeration Name | New Enumeration Name
BIOSBootMenuMode | FirmwareBootMenuMode

The BIOSBootMenuMode enumeration has been renamed to FirmwareBootMenuMode.

## Working with the Cloud

VirtualBox supports and goes towards the Oracle tendencies like "move to the Cloud".

### OCI features

VirtualBox supports the Oracle Cloud Infrastructure (OCI). See the interfaces: ICloudClient, ICloudProvider, ICloudProfile, ICloudProviderManager.

Each cloud interface has own implementation to support OCI features. There are everal functions in the implementation which should be explained in details because OCI requires some special data or settings.

Also see the enumeration VirtualSystemDescriptionType for the possible values.

### Function ICloudClient::exportVM

See the ICloudClient::exportVM. The function exports an existing virtual machine into OCI. The final result of this operation is creation a custom image from the bootable image of VM. The Id of created image is returned in the parameter "description" (which is IVirtualSystemDescription) as an entry with the type VirtualSystemDescriptionType::CloudImageId. The standard steps here are:

- Upload VBox image to OCI Object Storage.

- Create OCI custom image from the uploaded object.

Parameter "description" must contain all information and settings needed for creation a custom image in OCI. At least next entries must be presented there before the call:

- VirtualSystemDescriptionType::Name - Name of new instance in OCI.

- VirtualSystemDescriptionType::HardDiskImage - The local path or id of bootable VM image.

- VirtualSystemDescriptionType::CloudBucket - A cloud bucket name where the exported image is uploaded.

- VirtualSystemDescriptionType::CloudImageDisplayName - A name which is assigned to a new custom image in the OCI.

- VirtualSystemDescriptionType::CloudKeepObject - Whether keep or delete an uploaded object after its usage.

- VirtualSystemDescriptionType::CloudLaunchInstance - Whether launch or not a new instance.

### Function ICloudClient::launchVM

See the ICloudClient::launchVM. The function launches a new instance in OCI with a bootable volume previously created from a custom image in OCI or as the source may be used an existing bootable volume which shouldn't be attached to any instance. For launching instance from a custom image use the parameter VirtualSystemDescriptionType::CloudImageId. For launching instance from a bootable volume use the parameter VirtualSystemDescriptionType::CloudBootVolumeId. Only one of them must be presented otherwise the error will occur. The final result of this operation is a running instance. The id of created instance is returned in the parameter "description" (which is IVirtualSystemDescription) as an entry with the type VirtualSystemDescriptionType::CloudInstanceId. Parameter "description" must contain all information and settings needed for creation a new instance in OCI. At least next entries must be presented there before the call:

- VirtualSystemDescriptionType::Name - Name of new instance in OCI.

- VirtualSystemDescriptionType::CloudOCISubnet - OCID of existing subnet in OCI which will be used by the instance.

- Use VirtualSystemDescriptionType::CloudImageId - OCID of custom image used as a bootable image for the instance or VirtualSystemDescriptionType::CloudBootVolumeId - OCID of existing and non-attached bootable volume used as a bootable volume for the instance.

- Add VirtualSystemDescriptionType::CloudBootDiskSize - The size of instance bootable volume in GB, If you use VirtualSystemDescriptionType::CloudImageId.

- VirtualSystemDescriptionType::CloudInstanceShape - The shape of instance according to OCI documentation, defines the number of CPUs and RAM memory.

- VirtualSystemDescriptionType::CloudLaunchInstance - Whether launch or not a new instance.

- VirtualSystemDescriptionType::CloudDomain - Availability domain in OCI where new instance is created.

- VirtualSystemDescriptionType::CloudPublicIP - Whether the instance will have a public IP or not.

- VirtualSystemDescriptionType::CloudPublicSSHKey - Public SSH key which is used to connect to an instance via SSH. It may be one or more records with the type VirtualSystemDescriptionType::CloudPublicSSHKey in the VirtualSystemDescription. But at least one should be presented otherwise user won't be able to connect to the instance via SSH.

### Function ICloudClient::getInstanceInfo

See the ICloudClient::getInstanceInfo. The function takes an instance id (parameter "uid"), finds the requested instance in OCI and gets back information about the found instance in the parameter "description" (which is IVirtualSystemDescription) The entries with next types will be presented in the object:

- VirtualSystemDescriptionType::Name - Displayed name of the instance.

- VirtualSystemDescriptionType::CloudDomain - Availability domain in OCI.

- VirtualSystemDescriptionType::CloudImageId - Name of custom image used for creation this instance.

- VirtualSystemDescriptionType::CloudInstanceId - The OCID of the instance.

- VirtualSystemDescriptionType::OS - Guest OS type of the instance.

- VirtualSystemDescriptionType::CloudBootDiskSize - Size of instance bootable image.

- VirtualSystemDescriptionType::CloudInstanceState - The instance state according to OCI documentation.

- VirtualSystemDescriptionType::CloudInstanceShape - The instance shape according to OCI documentation

- VirtualSystemDescriptionType::Memory - RAM memory in GB allocated for the instance.

- VirtualSystemDescriptionType::CPU - Number of virtual CPUs allocated for the instance.

### Function ICloudClient::importInstance

See the ICloudClient::importInstance. The API function imports an existing instance from the OCI to the local host. The standard steps here are:

- Create a custom image from an existing OCI instance.

- Export the custom image to OCI object (the object is created in the OCI Object Storage).

- Download the OCI object to the local host.

As the result of operation user will have a file with the suffix ".oci" on the local host. This file is a TAR archive which contains a bootable instance image in QCOW2 format and a JSON file with some metadata related to the imported instance. The function takes the parameter "description" (which is IVirtualSystemDescription) Parameter "description" must contain all information and settings needed for successful operation result. At least next entries must be presented there before the call:

- VirtualSystemDescriptionType::Name is used for the several purposes:

  - As a custom image name. A custom image is created from an instance.

  - As OCI object name. An object is a file in OCI Object Storage. The object is created from the custom image.

  - Name of imported instance on the local host. Because the result of import is a file, the file will have this name and extension ".oci".

- VirtualSystemDescriptionType::CloudInstanceId - The OCID of the existing instance.

- VirtualSystemDescriptionType::CloudBucket - a cloud bucket name in OCI Object Storage where created an OCI object from a custom image.

## Host-Guest Communication Manager

The VirtualBox Host-Guest Communication Manager (HGCM) allows a guest application or a guest driver to call a host shared library. The following features of VirtualBox are implemented using HGCM:

- Shared Folders

- Shared Clipboard

- Guest configuration interface

The shared library on the host contains a so called HGCM service. The guest HGCM client establishes a connection to the HGCM service on the host in order to call that HGCM service's entry point. When calling an HGCM service the client supplies a function code, the number of parameters for the function, and an array of the parameter arguments.

### Virtual hardware implementation

HGCM uses the Virtual Machine Monitor (VMM) virtual PCI device to exchange data between the guest and the host. The guest always acts as an initiator of requests. A request is constructed in the guest's physical memory which must be locked by the guest. The physical address is passed to the VMM device using a 32-bit `out edx, eax` instruction. The physical memory must be allocated below 4GB on 64-bit guests.

The host parses the request header and data and queues the request for the corresponding host HGCM service type. The guest continues execution and usually waits on an HGCM event semaphore.

When the request has been processed by the HGCM service, the VMM device sets the completion flag in the request header, sets the HGCM event and raises an IRQ for the guest. The IRQ handler signals the HGCM event semaphore and all HGCM callers check the completion flag in the corresponding request header. If the flag is set, the request is considered completed.

### Protocol specification

The HGCM protocol definitions are contained in the `VBox/VBoxGuest.h` header file.

#### Request header

HGCM request structures contains a generic header (VMMDevHGCMRequestHeader):

#### HGCM Request Generic Header

Name | Description
size | Size of the entire request.
version | Version of the header, must be set to `0x10001`.
type | Type of the request.
rc | HGCM return code, which will be set by the VMM device.
reserved1 | A reserved field 1.
reserved2 | A reserved field 2.
flags | HGCM flags, set by the VMM device.
result | The HGCM result code, set by the VMM device.

- All fields are 32-bit.

- Fields from `size` to `reserved2` are a standard VMM device request header, which is used for other interfaces as well.

The type field indicates the type of the HGCM request:

#### Request Types

Name (decimal value) | Description
VMMDevReq_HGCMConnect (`60`) | Connect to an HGCM service.
VMMDevReq_HGCMDisconnect (`61`) | Disconnect from the service.
VMMDevReq_HGCMCall32 (`62`) | Call an HGCM function using the 32-bit interface.
VMMDevReq_HGCMCall64 (`63`) | Call an HGCM function using the 64-bit interface.
VMMDevReq_HGCMCancel (`64`) | Cancel an HGCM request currently being processed by a host HGCM service.

The flags field may contain:

#### Flags

Name (hexadecimal value) | Description
VBOX_HGCM_REQ_DONE (`0x00000001`) | The request has been processed by the host service.
VBOX_HGCM_REQ_CANCELLED (`0x00000002`) | This request was cancelled.

#### Connect

The connection request must be issued by the guest HGCM client before it can call the HGCM service (VMMDevHGCMConnect):

#### Connect request

Name | Description
header | The generic HGCM request header with type equal to VMMDevReq_HGCMConnect (`60`).
type | The type of the service location information (32 bit).
location | The service location information (128 bytes).
clientId | The client identifier assigned to the connecting client by the HGCM subsystem (32-bit).

The type field tells the HGCM how to look for the requested service:

#### Location Information Types

Name (hexadecimal value) | Description
VMMDevHGCMLoc_LocalHost (`0x1`) | The requested service is a shared library located on the host and the location information contains the library name.
VMMDevHGCMLoc_LocalHost_Existing (`0x2`) | The requested service is a preloaded one and the location information contains the service name.

Currently preloaded HGCM services are hard-coded in VirtualBox:

- VBoxSharedFolders

- VBoxSharedClipboard

- VBoxGuestPropSvc

- VBoxSharedOpenGL

There is no difference between both types of HGCM services, only the location mechanism is different.

The client identifier is returned by the host and must be used in all subsequent requests by the client.

#### Disconnect

This request disconnects the client and makes the client identifier invalid (VMMDevHGCMDisconnect):

#### Disconnect request

Name | Description
header | The generic HGCM request header with type equal to VMMDevReq_HGCMDisconnect (`61`).
clientId | The client identifier previously returned by the connect request (32-bit).

#### Call32 and Call64

Calls the HGCM service entry point (VMMDevHGCMCall) using 32-bit or 64-bit addresses:

#### Call request

Name | Description
header | The generic HGCM request header with type equal to either VMMDevReq_HGCMCall32 (`62`) or VMMDevReq_HGCMCall64 (`63`).
clientId | The client identifier previously returned by the connect request (32-bit).
function | The function code to be processed by the service (32 bit).
cParms | The number of following parameters (32-bit). This value is 0 if the function requires no parameters.
parms | An array of parameter description structures (HGCMFunctionParameter32 or HGCMFunctionParameter64).

The 32-bit parameter description (HGCMFunctionParameter32) consists of a 32-bit type field and 8 bytes of an opaque value, so 12 bytes in total. The 64-bit variant (HGCMFunctionParameter64) consists of the 32-bit type and 12 bytes of a value, so 16 bytes in total.

#### Parameter types

Type | Format of the value
VMMDevHGCMParmType_32bit (1) | A 32-bit value.
VMMDevHGCMParmType_64bit (2) | A 64-bit value.
VMMDevHGCMParmType_PhysAddr (3) | A 32-bit size followed by a 32-bit or 64-bit guest physical address.
VMMDevHGCMParmType_LinAddr (4) | A 32-bit size followed by a 32-bit or 64-bit guest linear address. The buffer is used both for guest to host and for host to guest data.
VMMDevHGCMParmType_LinAddr_In (5) | Same as VMMDevHGCMParmType_LinAddr but the buffer is used only for host to guest data.
VMMDevHGCMParmType_LinAddr_Out (6) | Same as VMMDevHGCMParmType_LinAddr but the buffer is used only for guest to host data.
VMMDevHGCMParmType_LinAddr_Locked (7) | Same as VMMDevHGCMParmType_LinAddr but the buffer is already locked by the guest.
VMMDevHGCMParmType_LinAddr_Locked_In (1) | Same as VMMDevHGCMParmType_LinAddr_In but the buffer is already locked by the guest.
VMMDevHGCMParmType_LinAddr_Locked_Out (1) | Same as VMMDevHGCMParmType_LinAddr_Out but the buffer is already locked by the guest.

#### Cancel

This request cancels a call request (VMMDevHGCMCancel):

#### Cancel request

Name | Description
header | The generic HGCM request header with type equal to VMMDevReq_HGCMCancel (`64`).

### Guest software interface

Guest HGCM clients can call HGCM services from both drivers and applications.

#### The guest driver interface

The driver interface is implemented in the VirtualBox guest additions driver (VBoxGuest) which works with the VMM virtual device. Drivers must use the VBox Guest Library (VBGL) which provides an API for HGCM clients (`VBox/VBoxGuestLib.h` and `VBox/VBoxGuest.h`). The key VBGL API routines are as follows:

    DECLR0VBGL(int) VbglR0HGCMConnect(VBGLHGCMHANDLE *pHandle, const char *pszServiceName, HGCMCLIENTID *pidClient);

VbglR0HGCMConnect() connects to the HGCM service on the host. An example of a guest driver connecting to the VirtualBox Shared Folder HGCM service follows:

        VBoxGuestHGCMConnectInfo data;

        memset(&data, sizeof(VBoxGuestHGCMConnectInfo));

        data.result   = VINF_SUCCESS;
        data.Loc.type = VMMDevHGCMLoc_LocalHost_Existing;
        strcpy(data.Loc.u.host.achName, "VBoxSharedFolders");

        rc = VbglR0HGCMConnect(&handle, "VBoxSharedFolders"&, data);

        if (RT_SUCCESS(rc))
        {
            rc = data.result;
        }

        if (RT_SUCCESS(rc))
        {
            /* Get the assigned client identifier. */
            ulClientID = data.u32ClientID;
        }

    DECLVBGL(int) VbglR0HGCMDisconnect(VBGLHGCMHANDLE handle, VBoxGuestHGCMDisconnectInfo *pData);

VbglR0HGCMDisconnect() disconnects from the HGCM service on the host. An example of a guest driver disconnecting from an HGCM service using the client identifier from an earlier call to VbglR0HGCMConnect() follows:

        VBoxGuestHGCMDisconnectInfo data;

        RtlZeroMemory(&data, sizeof (VBoxGuestHGCMDisconnectInfo));

        data.result      = VINF_SUCCESS;
        data.u32ClientID = ulClientID;

        rc = VbglR0HGCMDisconnect(handle, &data);

    DECLVBGL(int) VbglR0HGCMCall(VBGLHGCMHANDLE handle, VBoxGuestHGCMCallInfo *pData, uint32_t cbData);

VbglR0HGCMCall() calls a function specified in the VBoxGuestHGCMCallInfo argument in the HGCM service on the host. An example of a guest driver calling the Shared Folders HGCM service to issue a read of an object in a shared folder follows:

    typedef struct _VBoxSFRead
    {
        VBoxGuestHGCMCallInfo callInfo;

        /** pointer, in: SHFLROOT
         * Root handle of the mapping which name is queried.
         */
        HGCMFunctionParameter root;

        /** value64, in:
         * SHFLHANDLE of object to read from.
         */
        HGCMFunctionParameter handle;

        /** value64, in:
         * Offset to read from.
         */
        HGCMFunctionParameter offset;

        /** value64, in/out:
         * Bytes to read/How many were read.
         */
        HGCMFunctionParameter cb;

        /** pointer, out:
         * Buffer to place data to.
         */
        HGCMFunctionParameter buffer;

    } VBoxSFRead;

    /** Number of parameters */
    #define SHFL_CPARMS_READ (5)

    ...

        VBoxSFRead data;

        /* The call information. */
        data.callInfo.result      = VINF_SUCCESS;     /* Will be returned by HGCM. */
        data.callInfo.u32ClientID = ulClientID;       /* Client identifier. */
        data.callInfo.u32Function = SHFL_FN_READ;     /* The function code. */
        data.callInfo.cParms      = SHFL_CPARMS_READ; /* Number of parameters. */

        /* Initialize parameters. */
        data.root.type                      = VMMDevHGCMParmType_32bit;
        data.root.u.value32                 = pMap->root;

        data.handle.type                    = VMMDevHGCMParmType_64bit;
        data.handle.u.value64               = hFile;

        data.offset.type                    = VMMDevHGCMParmType_64bit;
        data.offset.u.value64               = offset;

        data.cb.type                        = VMMDevHGCMParmType_32bit;
        data.cb.u.value32                   = *pcbBuffer;

        data.buffer.type                    = VMMDevHGCMParmType_LinAddr_Out;
        data.buffer.u.Pointer.size          = *pcbBuffer;
        data.buffer.u.Pointer.u.linearAddr  = (uintptr_t)pBuffer;

        rc = VbglR0HGCMCall(handle, &data.callInfo, sizeof (data));

        if (RT_SUCCESS(rc))
        {
            rc = data.callInfo.result;
            *pcbBuffer = data.cb.u.value32; /* This is returned by the HGCM service. */
        }

#### Guest application interface

Applications call the VirtualBox Guest Additions driver to utilize the HGCM interface. The following IOCTLs correspond to the `VbglR0HGCM*` functions listed above:

- `VBGL_IOCTL_HGCM_CONNECT => VbglR0HGCMConnect()`

- `VBGL_IOCTL_HGCM_DISCONNECT => VbglR0HGCMDisconnect()`

- `VBGL_IOCTL_HGCM_CALL => VbglR0HGCMCall()`

These IOCTLs get the same input buffer as the `VbglR0HGCM*` functions and the output buffer has the same format as the input buffer. The same address can be used for both the input and output buffers.

### HGCM Service Implementation

The HGCM service is a shared library with a specific set of entry points. The library must export the `VBoxHGCMSvcLoad` entry point:

    extern "C" DECLCALLBACK(DECLEXPORT(int)) VBoxHGCMSvcLoad(VBOXHGCMSVCFNTABLE *ptable)

The service must check the `ptable->cbSize` and `ptable->u32Version` fields of the input structure and fill in the remaining fields with function pointers of service entry points (listed below) and the size of the required client buffer size.

The HGCM service gets a dedicated thread which calls service entry points synchronously, thus the service entry point will only be called again once a previous call has returned. However, the guest calls can be processed asynchronously. Therefore the service must call a completion callback when the operation is actually completed. The callback can be issued from another thread as well.

Service entry points are listed in the `VBox/hgcmsvc.h` in the `VBOXHGCMSVCFNTABLE` structure.

### Service entry points

Entry Point | Description
int pfnUnload(void *pvService) | The service is being unloaded.
int pfnConnect(void *pvService, uint32_t u32ClientID, void *pvClient, uint32_t fRequestor, bool fRestoring) | A client `u32ClientID` is connected to the service. The `pvClient` parameter points to an allocated memory buffer which can be used by the service to store the client information.
int pfnDisconnect(void *pvService, uint32_t u32ClientID, void *pvClient) | A client is being disconnected.
void pfnCall(void *pvService, VBOXHGCMCALLHANDLE callHandle, uint32_t u32ClientID, void *pvClient, uint32_t function, uint32_t cParms, VBOXHGCMSVCPARM paParms[], uint64_t tsArrival) | A guest client calls a service function. The `callHandle` must be used in the VBOXHGCMSVCHELPERS::pfnCallComplete callback when the call has been processed.
int pfnHostCall(void *pvService, uint32_t function, uint32_t cParms, VBOXHGCMSVCPARM paParms[]) | Called by the VirtualBox host components to perform functions which should be not accessible by the guest. Usually this entry point is used by VirtualBox to configure the service.
int pfnSaveState(void *pvService, uint32_t u32ClientID, void *pvClient, PSSMHANDLE pSSM, PCVMMR3VTABLE pVMM) | The VM state is being saved and the service must save relevant information using the SSM API (`VBox/ssm.h`).
int pfnLoadState(void *pvService, uint32_t u32ClientID, void *pvClient, PSSMHANDLE pSSM, PCVMMR3VTABLE pVMM, uint32_t uVersion) | The VM is being restored from the saved state and the service must load the saved information and be able to continue operations from the saved state.

## RDP Web Control

The VirtualBox RDP Web Control (RDPWeb) provides remote access to a running VM. RDPWeb is an RDP (Remote Desktop Protocol) client based on Flash technology and can be used from a Web browser with a Flash plugin.

### RDPWeb features

RDPWeb is embedded into a Web page and connects to a VRDP server in order to display the remote VM screen and pass keyboard and mouse events to the VM.

### RDPWeb reference

RDPWeb consists of two required components:

- Flash movie file `RDPClientUI.swf`

- JavaScript helpers contained in `webclient.js`

The VirtualBox SDK contains sample HTML code including:

- A JavaScript library for embedding Flash content: `SWFObject.js`

- A sample HTML page: `webclient3.html`

#### RDPWeb functions

`RDPClientUI.swf` and `webclient.js` work together to provide the RDP Web Control functionality. The JavaScript code is responsible for proper Flash initialization, delivering mouse events to the Flash object, and processing resize requests from the Flash object. On the other hand, the SWF file contains a few JavaScript callable methods, which are used both from `webclient.js` and the user HTML page.

##### JavaScript functions

The `webclient.js` file contains several helper JavaScript functions. In the following table ElementId refers to an HTML element name or attribute, and Element to the HTML element itself. The HTML code

        <div id="FlashRDP">
        </div>

would have ElementId equal to FlashRDP and Element equal to the div element.

-     RDPWebClient.embedSWF(SWFFileName, ElementId)

  Uses the open-source SWFObject library to replace the HTML element with the Flash movie.

-     RDPWebClient.isRDPWebControlById(ElementId)

  Returns true if the given ElementId refers to an RDPWeb Flash element.

-     RDPWebClient.isRDPWebControlByElement(Element)

  Returns true if the given Element is an RDPWeb Flash element.

-     RDPWebClient.getFlashById(ElementId)

  Returns an element, which is referenced by the given ElementId. This function will try to resolve any element, even if it is not a Flash movie.

##### Flash methods callable from JavaScript

The `RDPWebClienUI.swf` methods can be called directly from JavaScript code on an HTML page:

- getProperty(Name)

- setProperty(Name)

- connect()

- disconnect()

- keyboardSendCAD()

##### Flash JavaScript callbacks

`RDPWebClienUI.swf` calls JavaScript functions provided by the HTML page.

#### Embedding RDPWeb in an HTML page

It is necessary to include the `webclient.js` helper script. If the SWFObject library is used, the `swfobject.js` must also be included. Using the SWFObject library allows RDPWeb flash content to be embedded in a Web page using dynamic HTML. The HTML must include a "placeholder", which consists of 2 `div` elements.

### RDPWeb change log

#### Version 1.2.28

- `keyboardLayout`, `keyboardLayouts`, `UUID` properties.

- Support for German keyboard layout on the client.

- Rebranding to Oracle.

#### Version 1.1.26

- `webclient.js` is a part of the distribution package.

- `lastError` property.

- `keyboardSendScancodes` and `keyboardSendCAD` methods.

#### Version 1.0.24

- Initial release.

## Drag and Drop

As of VirtualBox 4.2 it's possible to transfer files from the host to Linux, Solaris, and macOS guests by dragging files, directories, or text from the host into the guest's screen. This is called drag and drop (DnD).

VirtualBox 5.0 added support for Windows guests as well as the ability to transfer data in the opposite direction, that is, from the guest to the host.

Currently only the VirtualBox Manager front-end supports drag and drop.

This chapter will show how to use the required interfaces provided by VirtualBox for adding drag and drop functionality to third-party front-ends.

### Basic concepts

In order to use the interfaces provided by VirtualBox, some basic concepts need to be understood first: a drag and drop operation logically contains both a source and a target:

The source provides the data, i.e., it is the origin of data. This data can be stored within the source directly or it can be retrieved on-demand by the source itself.

The target on the other hand provides a visual representation to the source where the user can drop the data the source offers. This representation can be a window (or just a certain part of it), for example.

The source and the target have abstract interfaces called IDnDSource and IDnDTarget. VirtualBox also provides implementations of both interfaces, called IGuestDnDSource and IGuestDnDTarget. Both implementations are used in the VirtualBox Manager front-end.

### Supported formats

As the target needs to perform specific actions depending on the data the source provided, the target first needs to know what type of data it is actually going to retrieve. It might be that the source offers data the target cannot (or intentionally does not want to) support.

VirtualBox describes the data types using MIME types -- which were originally defined in RFC 2046 and are also called Content-types or media types. IGuestDnDSource and IGuestDnDTarget support the following MIME types by default:

- text/uri-list - A list of URIs (Uniform Resource Identifier, see RFC 3986) pointing to the file and/or directory paths already transferred from the source to the target.

- text/plain;charset=utf-8 and UTF8_STRING - text in UTF-8 format.

- text/plain, TEXT and STRING - plain ASCII text, depending on the source's active ANSI page (if any).

If, for whatever reason, a certain default format should not be supported or a new format should be registered, IDnDSource and IDnDTarget have methods derived from IDnDBase which provide adding, removing and enumerating specific formats.

Registering new or removing default formats on the guest side is not currently implemented.

## VirtualBox external authentication modules

VirtualBox supports arbitrary external modules to perform authentication. External authentication modules are used for remote desktop access to a VM when the VRDE authentication type is set to "external". VRDE authentication will then use the authentication module which was specified with `VBoxManage setproperty vrdeauthlibrary`. The web service will use the external authentication module specified with `VBoxManage setproperty websrvauthlibrary`.

This library will be loaded by the VM or web service process on demand, i.e. when the first remote desktop connection is made by a client or when a client that wants to use the web service logs on.

External authentication is the most flexible authentication type since the external handler can choose to both grant access to everyone (like the "null" authentication method) as well as delegate the request to the guest authentication component. When delegating the request to the guest component the external handler will still be called afterwards with the option to override the result.

An authentication library is required to implement exactly one entry point:

    #include "VBoxAuth.h"

    /**
     * Authentication library entry point.
     *
     * Parameters:
     *
     *   szCaller         The name of the component which calls the library (UTF8).
     *   pUuid            Pointer to the UUID of the accessed virtual machine. Can be NULL.
     *   guestJudgement   Result of the guest authentication.
     *   szUser           User name passed in by the client (UTF8).
     *   szPassword       Password passed in by the client (UTF8).
     *   szDomain         Domain passed in by the client (UTF8).
     *   fLogon           Boolean flag. Indicates whether the entry point is called
     *                    for a client logon or the client disconnect.
     *   clientId         Server side unique identifier of the client.
     *
     * Return code:
     *
     *   AuthResultAccessDenied    Client access has been denied.
     *   AuthResultAccessGranted   Client has the right to use the
     *                             virtual machine.
     *   AuthResultDelegateToGuest Guest operating system must
     *                             authenticate the client and the
     *                             library must be called again with
     *                             the result of the guest
     *                             authentication.
     *
     * Note: When 'fLogon' is 0, only pszCaller, pUuid and clientId are valid and the return
     *       code is ignored.
     */
    AuthResult AUTHCALL AuthEntry(
        const char *szCaller,
        PAUTHUUID pUuid,
        AuthGuestJudgement guestJudgement,
        const char *szUser,
        const char *szPassword
        const char *szDomain
        int fLogon,
        unsigned clientId)
    {
        /* Process request against your authentication source of choice. */
        // if (authSucceeded(...))
        //     return AuthResultAccessGranted;
        return AuthResultAccessDenied;
    }

A note regarding the UUID implementation of the `pUuid` argument: VirtualBox uses a consistent binary representation of UUIDs on all platforms. For this reason the integer fields comprising the UUID are stored as little endian values. If you want to pass such UUIDs to code which assumes that integer fields are big endian (often also called network byte order), you need to adjust the contents of the UUID to achieve the same string representation. The required changes are:

- reverse the order of bytes 0, 1, 2 and 3

- reverse the order of bytes 4 and 5

- reverse the order of bytes 6 and 7.

Using this conversion you will get identical results when converting the binary UUID to the string representation.

The `guestJudgement` argument contains information about the guest authentication status. For the first call, it is always set to `AuthGuestNotAsked`. If the `AuthEntry` function returns `AuthResultDelegateToGuest`, a guest authentication will be attempted and another call to the `AuthEntry` is made with its result. The guest authentication can return either granted, denied, or no judgement (the guest component chose for whatever reason to not make a decision). In case there is a problem with the guest authentication module (e.g. the Guest Additions are not installed or not running or the guest did not respond within a timeout), the "not reacted" status will be returned.

## Using the Java API

### Introduction

VirtualBox can be controlled by a Java API, both locally using COM/XPCOM and remotely using SOAP. As with the Python bindings, a generic glue layer tries to hide all platform differences, allowing for source and binary compatibility on different platforms.

### Requirements

To use the Java bindings, there are certain requirements depending on the platform. First of all, you need JDK 1.5 (Java 5) or later. Also please make sure that the version of the VirtualBox API .jar file exactly matches the version of VirtualBox in use. To avoid confusion, the VirtualBox API provides versioning in the Java package name, e.g. the package is named `org.virtualbox_3_2` for VirtualBox version 3.2.

- XPCOM - for all platforms except Microsoft Windows. A Java bridge based on JavaXPCOM is shipped with VirtualBox. The classpath must contain `vboxjxpcom.jar` and the `vbox.home` property must be set to the location where the VirtualBox binaries are. Please make sure that the JVM bitness matches the bitness of VirtualBox in use as the XPCOM bridge relies on native libraries.

  Start your application like this:

       java -cp vboxjxpcom.jar -Dvbox.home=/opt/virtualbox MyProgram

- COM - for Microsoft Windows. We rely on `Jacob` - a generic Java to COM bridge - which has to be installed separately. See http://sourceforge.net/projects/jacob-project/ for installation instructions. Also, the VirtualBox provided `vboxjmscom.jar` file must be in the class path.

  Start your application like this:

      java -cp vboxjmscom.jar;c:\jacob\jacob.jar -Djava.library.path=c:\jacob MyProgram

- SOAP - all platforms. Java 6 is required as it comes with built-in support for SOAP via the JAX-WS library. Also, the VirtualBox provided `vbojws.jar` must be in the class path. In the SOAP case it's possible to create several VirtualBoxManager instances to communicate with multiple VirtualBox hosts.

  Start your application like this:

       java -cp vboxjws.jar MyProgram

Exception handling is also generalized by the generic glue layer, so that all methods can throw `VBoxException` containing a human-readable text message (see `getMessage()` method) along with the wrapped original exception (see `getWrapped()` method).

### Example

This example shows a simple use case of the Java API. Differences for SOAP vs. local execution are minimal and limited to the connection setup phase (see `ws` variable). In the SOAP case it's possible to create several VirtualBoxManager instances to communicate with multiple VirtualBox hosts.

              import org.virtualbox_4_3.*;
              ....
              VirtualBoxManager mgr = VirtualBoxManager.createInstance(null);
              boolean ws = false; // or true, if we need the SOAP version
              if (ws)
              {
                  String url = "http://myhost:18034";
                  String user = "test";
                  String passwd = "test";
                  mgr.connect(url, user, passwd);
              }
              IVirtualBox vbox = mgr.getVBox();
              System.out.println("VirtualBox version: " + vbox.getVersion() + "\n");
              // get first VM name
              String m =  vbox.getMachines().get(0).getName();
              System.out.println("\nAttempting to start VM '" + m + "'");
              // start it
              mgr.startVm(m, null, 7000);

              if (ws)
                  mgr.disconnect();

              mgr.cleanup();

For a more complete example, see `TestVBox.java`, shipped with the SDK. It contains exception handling and error printing code which is important for reliable larger scale projects.

It is good practice in long-running API clients to process the system events every now and then in the main thread (this does not work in other threads). As a rule of thumb it makes sense to process them every few 100msec to every few seconds). This is done by calling

            mgr.waitForEvents(0);

This helps prevent a large number of system events from accumulating which can need a significant amount of memory, and as they also play a role in object cleanup it helps freeing additional memory in a timely manner which is used by the API implementation itself. Java's garbage collection approach already needs more memory due to the delayed freeing of memory used by no longer accessible objects and not processing the system events exacerbates the memory usage. The `TestVBox.java` example code sprinkles such lines over the code to achieve the desired effect. In multi-threaded applications it can be called from the main thread periodically. Sometimes it's possible to use the non-zero timeout variant of the method, which then waits the specified number of milliseconds for events, processing them immediately as they arrive. It achieves better runtime behavior than separate sleeping/processing.

## License information

The sample code files shipped with the SDK are generally licensed liberally to make it easy for anyone to use this code for their own application code.

The Java files under `sdk/bindings/webservice/java/jax-ws/` (library files for the object-oriented web service) are, by contrast, licensed under the GNU Lesser General Public License (LGPL) V2.1.

See `sdk/bindings/webservice/java/jax-ws/src/COPYING.LIB` for the full text of the LGPL 2.1.

When in doubt, please refer to the individual source code files shipped with this SDK.

## Main API change log

Generally, VirtualBox will maintain API compatibility within a major release; a major release occurs when the first or the second of the three version components of VirtualBox change (that is, in the x.y.z scheme, a major release is one where x or y change, but not when only z changes).

In other words, updates like those from 2.0.0 to 2.0.2 will not come with API breakages.

Migration between major releases most likely will lead to API breakage, so please make sure you updated code accordingly. The OOWS Java wrappers enforce that mechanism by putting VirtualBox classes into version-specific packages such as `org.virtualbox_2_2`. This approach allows for connecting to multiple VirtualBox versions simultaneously from the same Java application.

The following sections list incompatible changes that the Main API underwent since the original release of this SDK Reference with VirtualBox 2.0. A change is deemed "incompatible" only if it breaks existing client code (e.g. changes in method parameter lists, renamed or removed interfaces and similar). In other words, the list does not contain new interfaces, methods or attributes or other changes that do not affect existing client code.

### Incompatible API changes with version 7.2

- The attribute GraphicsFeature::Acceleration2DVideo has been removed.

- The attribute GuestOSType::recommended2DVideoAcceleration has been removed.

- The RecordingState enumeration has been added and is being used for the IRecordingStateChanged and IRecordingScreenStateChanged events.

### Incompatible API changes with version 7.1

- Review the Main API changes made for the ARM64 CPU architecture here for incompatible changes to interfaces, methods, and attributes.

- The Python API bindings for Python 2.x is now marked as being deprecated and will be removed in a future version. Please upgrade your code to use Python 3.

- The Python API bindings now live in a separate `python` sub directory and also now support installing via the pip package manager (e.g. `pip -v install ./vboxapi`). This also allows installing into Python virtual environments.

- The Windows host installer now uses the sub directory `installer` instead of `install` for housing the bindings installers. This now matches the directory layout for the other platforms. Please adapt your scripts if needed.

- Guest process creation requires a new parameter for specifying the current working directory for the new guest process. This is optional and can be empty. See IGuestSession::processCreate and IGuestSession::processCreateEx for more information.

- The APIs IGuestSession::fsQueryInfo and IGuestSession::fsQueryFreeSpace are now implemented. See IGuestSession::fsQueryInfo and IGuestSession::fsQueryFreeSpace for more information.

- The APIs IGuestSession::waitFor and IProcess::waitFor are now marked as being deprecated. Use IGuestSession::waitForArray and IProcess::waitForArray instead.

- The attribute IGuestSession::mountPoints has been added. This requires 7.1 (or newer) Guest Additions to be installed on the guest.

- The attribute IHost::acceleration3DAvailable has been removed. Use ISystempProperties::supportedGraphicsFeatures instead.

- Starting a recording now has to be done via the newly introduced method IRecordingSettings::start. This method also will return a recording progress object on success, which also can be retrieved at a later time via the new attribute IRecordingSettings::progress.

- The recording settings attribute IRecordingSettings::enabled does not implicitly start or stop a recording anymore, but only will indicate that recording for a VM is enabled or disabled. This attribute also will be used to determine if recording will be started automatically on VM start or restore.

- The recording settings now expose a progress object attribute via IRecordingSettings::progress, which can be used to stop an ongoing recording, track the recording progress or getting notified of recording errors.

### Incompatible API changes with version 7.0

- The machine's audio adapter has been moved into the new IAudioSettings interface, which in turn takes care of of all audio settings of a virtual machine. See IMachine::audioSettings and IAudioSettings for more information.

- The IVirtualBox::openMachine call now requires an additional password parameter. If the machine is not encrypted the parameter is ignored.

- When a new VM is being created, the default audio driver will be now AudioDriverType_Default. This driver type will automatically choose the best audio driver (backend) for the host OS &VBOX_PRODUCT; currently is running on.

- The host update functionality at IHost::update has been refactored into IHost::updateHost, which in turn uses the new IHostUpdateAgent interface, derived from the new IUpdateAgent interface.

- IGuestSession::directoryCopyFromGuest() and IGuestSession::directoryCopyToGuest() no longer implicitly copy recursively and follow symbolic links -- for this to continue working, the newly introduced flags DirectoryCopyFlag::Recursive and/or DirectoryCopyFlag::FollowLinks have to be used.

- VBoxEventType_Last has been renamed to VBoxEventType_End for consistency.

### Incompatible API changes with version 6.1

- Split off the graphics adapter part of IMachine into IGraphicsAdapter. This moved 5 attributes.

### Incompatible API changes with version 6.0

- Video recording APIs were changed as follows:

  - All attributes which were living in IMachine before have been moved to an own, dedicated interface named IRecordingSettings. This new interface can be accessed via the new IMachine::recordingSettings attribute. This should emphasize that recording is not limited to video capturing as such.

  - For further flexibility all specific per-VM-screen settings have been moved to a new interface called IRecordingScreenSettings. Such settings now exist per configured VM display and can be retrieved via the IRecordingSettings::screens attribute or the IRecordingSettings::getScreenSettings method.

    For now all screen settings will share the same settings, e.g. different settings on a per-screen basis is not implemented yet.

  - The event `IVideoCaptureChangedEvent` was renamed into `IRecordingChangedEvent`.

- Guest Control APIs were changed as follows:

  - IGuest::createSession(), IGuestSession::processCreate(), IGuestSession::processCreateEx(), IGuestSession::directoryOpen() and IGuestSession::fileOpen() now will return the new error code VBOX_E_MAXIMUM_REACHED if the limit for the according object group has been reached.

  - The enumerations FileOpenExFlags, FsObjMoveFlags and DirectoryCopyFlags have been renamed to FileOpenExFlag, FsObjMoveFlag and DirectoryCopyFlag accordingly to match the rest of the API.

  - The following methods have been implemented: `IGuestSession::directoryCopyFromGuest()` and `IGuestSession::directoryCopyToGuest()`.

    The following attributes have been implemented: `IGuestFsObjInfo::accessTime`, `IGuestFsObjInfo::birthTime`, `IGuestFsObjInfo::changeTime` and `IGuestFsObjInfo::modificationTime`.

- The webservice version of the ISharedFolder interface was changed from a struct to a managed object. This causes incompatibilities on the protocol level as the shared folder attributes are not returned in the responses of IVirtualBox::getSharedFolders and IMachine::getSharedFolders anymore. They return object UUIDs instead which need be wrapped by stub objects. The change is not visible when using the appropriate client bindings from the most recent VirtualBox SDK.

### Incompatible API changes with version 5.x

- ProcessCreateFlag::NoProfile has been renamed to ProcessCreateFlag::Profile, and the semantics have also been changed: ProcessCreateFlag::NoProfile explicitly did not utilize the guest user's profile data whereas ProcessCreateFlag::Profile explicitly does utilize the guest user’s profile data.

### Incompatible API changes with version 5.1.28

- The Host-Guest Communication Manager (HGCM) guest driver interfaces were renamed:

  - VbglHGCMConnect() was renamed to VbglR0HGCMConnect()

  - VbglHGCMDisconnect() was renamed to VbglR0HGCMDisconnect()

  - VbglHGCMCall() was renamed to VbglR0HGCMCall()

- The Host-Guest Communication Manager (HGCM) guest application interface IOCTLs were renamed:

  - VBOXGUEST_IOCTL_HGCM_CONNECT was renamed to VBGL_IOCTL_HGCM_CONNECT

  - VBOXGUEST_IOCTL_HGCM_DISCONNECT was renamed to VBGL_IOCTL_HGCM_DISCONNECT

  - VBOXGUEST_IOCTL_HGCM_CALL was renamed to VBGL_IOCTL_HGCM_CALL

### Incompatible API changes with version 5.0

- The methods for saving state, adopting a saved state file, discarding a saved state, taking a snapshot, restoring a snapshot and deleting a snapshot have been moved from `IConsole` to `IMachine`. This straightens out the logical placement of methods and was necessary to resolve a long-standing issue, preventing 32-bit API clients from invoking those operations in the case where no VM is running.

  - IMachine::saveState() replaces `IConsole::saveState()`

  - IMachine::adoptSavedState() replaces `IConsole::adoptSavedState()`

  - IMachine::discardSavedState() replaces `IConsole::discardSavedState()`

  - IMachine::takeSnapshot() replaces `IConsole::takeSnapshot()`

  - IMachine::deleteSnapshot() replaces `IConsole::deleteSnapshot()`

  - IMachine::deleteSnapshotAndAllChildren() replaces `IConsole::deleteSnapshotAndAllChildren()`

  - IMachine::deleteSnapshotRange() replaces `IConsole::deleteSnapshotRange()`

  - IMachine::restoreSnapshot() replaces `IConsole::restoreSnapshot()`

  Small adjustments to the parameter lists have been made to reduce the number of API calls when taking online snapshots (no longer needs explicit pausing), and taking a snapshot also returns now the snapshot id (useful for finding the right snapshot if there are non-unique snapshot names).

- Two new machine states have been introduced to allow proper distinction between saving state and taking a snapshot. MachineState::Saving now is used exclusively while the VM's state is being saved, without any overlaps with snapshot functionality. The new state MachineState::Snapshotting is used when an offline snapshot is taken and likewise the new state MachineState::OnlineSnapshotting is used when an online snapshot is taken.

- A new event has been introduced, which signals when a snapshot has been restored: ISnapshotRestoredEvent. Previously the event ISnapshotDeletedEvent was signalled, which isn't logical (but could be distinguished from actual deletion by the fact that the snapshot was still there).

- The method IVirtualBox::createMedium() replaces `VirtualBox::createHardDisk()`. Adjusting existing code needs adding two parameters with value `AccessMode_ReadWrite` and `DeviceType_HardDisk` respectively. The new method supports creating floppy and DVD images, and (less obviously) further API functionality such as cloning floppy images.

- The method IMachine::getStorageControllerByInstance() now has an additional parameter (first parameter), for specifying the storage bus which the storage controller must be using. The method was not useful before, as the instance numbers are only unique for a specfic storage bus.

- The attribute `IMachine::sessionType` has been renamed to IMachine::sessionName(). This cleans up the confusing terminology (as the session type is something different).

- The attribute `IMachine::guestPropertyNotificationPatterns` has been removed. In practice it was not usable because it is too global and didn't distinguish between API clients.

- Drag and drop APIs were changed as follows:

  - Methods for providing host to guest drag and drop functionality, such as `IGuest::dragHGEnter`, `IGuest::dragHGMove()`, `IGuest::dragHGLeave()`, `IGuest::dragHGDrop()` and `IGuest::dragHGPutData()`, have been moved to an abstract base class called IDnDTarget. VirtualBox implements this base class in the IGuestDnDTarget interface. The implementation can be used by using the IGuest::dnDTarget() method.

    Methods for providing guest to host drag and drop functionality, such as `IGuest::dragGHPending()`, `IGuest::dragGHDropped()` and `IGuest::dragGHGetData()`, have been moved to an abstract base class called IDnDSource. VirtualBox implements this base class in the IGuestDnDSource interface. The implementation can be used by using the IGuest::dnDSource() method.

  - The `DragAndDropAction` enumeration has been renamed to DnDAction.

  - The `DragAndDropMode` enumeration has been renamed to DnDMode.

  - The attribute `IMachine::dragAndDropMode` has been renamed to IMachine::dnDMode().

  - The event `IDragAndDropModeChangedEvent` has been renamed to IDnDModeChangedEvent.

- IDisplay and IFramebuffer interfaces were changed to allow IFramebuffer object to reside in a separate front-end process:

  - IDisplay::ResizeCompleted() has been removed, because the IFramebuffer object does not provide the screen memory anymore.

  - IDisplay::SetFramebuffer() has been replaced with IDisplay::AttachFramebuffer() and IDisplay::DetachFramebuffer().

  - IDisplay::GetFramebuffer() has been replaced with IDisplay::QueryFramebuffer().

  - IDisplay::GetScreenResolution() has a new output parameter `guestMonitorStatus` which tells whether the monitor is enabled in the guest.

  - IDisplay::TakeScreenShot() and IDisplay::TakeScreenShotToArray() have a new parameter `bitmapFormat`. As a consequence of this, IDisplay::TakeScreenShotPNGToArray() has been removed.

  - IFramebuffer::RequestResize() has been replaced with IFramebuffer::NotifyChange().

  - IFramebuffer::NotifyUpdateImage() added to support IFramebuffer objects in a different process.

  - IFramebuffer::Lock(), IFramebuffer::Unlock(), IFramebuffer::Address(), IFramebuffer::UsesGuestVRAM() have been removed because the IFramebuffer object does not provide the screen memory anymore.

- IGuestSession, IGuestFile and IGuestProcess interfaces were changed as follows:

  - Replaced IGuestSession::directoryQueryInfo and IGuestSession::fileQueryInfo with a new IGuestSession::fsObjQueryInfo method that works on any type of file system object.

  - Replaced IGuestSession::fileRemove, IGuestSession::symlinkRemoveDirectory and IGuestSession::symlinkRemoveFile with a new IGuestSession::fsObjRemove method that works on any type of file system object except directories. (fileRemove also worked on any type of object too, though that was not the intent of the method.)

  - Replaced IGuestSession::directoryRename and IGuestSession::directoryRename with a new IGuestSession::fsObjRename method that works on any type of file system object. (directoryRename and fileRename may already have worked for any kind of object, but that was never the intent of the methods.)

  - Replaced the unimplemented IGuestSession::directorySetACL and IGuestSession::fileSetACL with a new IGuestSession::fsObjSetACL method that works on all type of file system object. Also added a UNIX-style mode parameter as an alternative to the ACL.

  - Replaced IGuestSession::fileRemove, IGuestSession::symlinkRemoveDirectory and IGuestSession::symlinkRemoveFile with a new IGuestSession::fsObjRemove method that works on any type of file system object except directories (fileRemove also worked on any type of object, though that was not the intent of the method.)

  - Renamed IGuestSession::copyTo to IGuestSession::fileCopyToGuest.

  - Renamed IGuestSession::copyFrom to IGuestSession::fileCopyFromGuest.

  - Renamed the CopyFileFlag enum to FileCopyFlag.

  - Renamed the IGuestSession::environment attribute to IGuestSession::environmentChanges to better reflect what it does.

  - Changed the IGuestProcess::environment to a stub returning E_NOTIMPL since it wasn't doing what was advertised (returned changes, not the actual environment).

  - Renamed IGuestSession::environmentSet to IGuestSession::environmentScheduleSet to better reflect what it does.

  - Renamed IGuestSession::environmentUnset to IGuestSession::environmentScheduleUnset to better reflect what it does.

  - Removed IGuestSession::environmentGet it was only getting changes while giving the impression it was actual environment variables, and it did not represent scheduled unset operations.

  - Removed IGuestSession::environmentClear as it duplicates assigning an empty array to the IGuestSession::environmentChanges (formerly known as IGuestSession::environment).

  - Changed the IGuestSession::processCreate and IGuestSession::processCreateEx methods to accept arguments starting with argument zero (argv[0]) instead of argument one (argv[1]). (Not yet implemented on the guest additions side, so argv[0] will probably be ignored for a short while.)

  - Added a followSymlink parameter to the following methods:

    - IGuestSession::directoryExists

    - IGuestSession::fileExists

    - IGuestSession::fileQuerySize

  - The parameters to the IGuestSession::fileOpen and IGuestSession::fileOpenEx methods were altered:

    - The openMode string parameter was replaced by the enum FileAccessMode and renamed to accessMode.

    - The disposition string parameter was replaced by the enum FileOpenAction and renamed to openAction.

    - The unimplemented sharingMode string parameter was replaced by the enum FileSharingMode (fileOpenEx only).

    - Added a flags parameter taking a list of FileOpenExFlag values (fileOpenEx only).

    - Removed the offset parameter (fileOpenEx only).

  - IGuestFile::seek now returns the new offset.

  - Renamed the FileSeekType enum used by IGuestFile::seek to FileSeekOrigin and added the missing End value and renaming the Set to Begin.

  - Extended the unimplemented IGuestFile::setACL method with a UNIX-style mode parameter as an alternative to the ACL.

  - Renamed the IFile::openMode attribute to IFile::accessMode and change the type from string to FileAccessMode to reflect the changes to the fileOpen methods.

  - Renamed the IGuestFile::disposition attribute to IFile::openAction and change the type from string to FileOpenAction to reflect the changes to the fileOpen methods.

  - Added IGuestSession::pathStyle attribute.

  - Added IGuestSession::fsObjExists attribute.

- IConsole::GetDeviceActivity() returns information about multiple devices.

- IMachine::ReadSavedThumbnailToArray() has a new parameter `bitmapFormat`. As a consequence of this, IMachine::ReadSavedThumbnailPNGToArray() has been removed.

- IMachine::QuerySavedScreenshotPNGSize() has been renamed to IMachine::QuerySavedScreenshotInfo() which also returns an array of available screenshot formats.

- IMachine::ReadSavedScreenshotPNGToArray() has been renamed to IMachine::ReadSavedScreenshotToArray() which has a new parameter `bitmapFormat`.

- IMachine::QuerySavedThumbnailSize() has been removed.

- The method IWebsessionManager::getSessionObject() now returns a new ISession instance for every invocation. This puts the behavior in line with other binding styles, which never forced the equivalent of establishing another connection and logging in again to get another instance.

### Incompatible API changes with version 4.3

- The explicit medium locking methods IMedium::lockRead() and IMedium::lockWrite() have been redesigned. They return a lock token object reference now, and calling the IToken::abandon() method (or letting the reference count to this object drop to 0) will unlock it. This eliminates the rather common problem that an API client crash left behind locks, and also improves the safety (API clients can't release locks they didn't obtain).

- The parameter list of IAppliance::write() has been changed slightly, to allow multiple flags to be passed.

- `IMachine::delete` has been renamed to IMachine::deleteConfig(), to improve API client binding compatibility.

- `IMachine::export` has been renamed to IMachine::exportTo(), to improve API client binding compatibility.

- For IMachine::launchVMProcess() the meaning of the `type` parameter has changed slightly. Empty string now means that the per-VM or global default front-end is launched. Most callers of this method should use the empty string now, unless they really want to override the default and launch a particular front-end.

- Medium management APIs were changed as follows:

  - The type of attribute IMedium::variant() changed from `unsigned long` to `safe-array MediumVariant`. It is an array of flags instead of a set of flags which were stored inside one variable.

  - The parameter list for IMedium::cloneTo() was modified. The type of parameter variant was changed from unsigned long to safe-array MediumVariant.

  - The parameter list for IMedium::createBaseStorage() was modified. The type of parameter variant was changed from unsigned long to safe-array MediumVariant.

  - The parameter list for IMedium::createDiffStorage() was modified. The type of parameter variant was changed from unsigned long to safe-array MediumVariant.

  - The parameter list for IMedium::cloneToBase() was modified. The type of parameter variant was changed from unsigned long to safe-array MediumVariant.

- The type of attribute IMediumFormat::capabilities() changed from `unsigned long` to `safe-array MediumFormatCapabilities`. It is an array of flags instead of a set of flags which were stored inside one variable.

- The attribute IMedium::logicalSize() now returns the logical size of exactly this medium object (whether it is a base or diff image). The old behavior was no longer acceptable, as each image can have a different capacity.

- Guest control APIs - such as IGuest, IGuestSession, IGuestProcess and so on - now emit own events to provide clients much finer control and the ability to write own front-ends for guest operations. The event IGuestSessionEvent acts as an abstract base class for all guest control events. Certain guest events contain a IVirtualBoxErrorInfo member to provide more information in case of an error happened on the guest side.

- Guest control sessions on the guest started by IGuest::createSession() now are dedicated guest processes to provide more safety and performance for certain operations. Also, the IGuest::createSession() call does not wait for the guest session being created anymore due to the dedicated guest session processes just mentioned. This also will enable webservice clients to handle guest session creation more gracefully. To wait for a guest session being started, use the newly added attribute IGuestSession::status() to query the current guest session status.

- The IGuestFile APIs are now implemented to provide native guest file access from the host.

- The parameter list for IMedium::updateGuestAdditions() was modified. It now supports specifying optional command line arguments for the Guest Additions installer performing the actual update on the guest.

- A new event IGuestUserStateChangedEvent was introduced to provide guest user status updates to the host via event listeners. To use this event there needs to be at least the 4.3 Guest Additions installed on the guest. At the moment only the states "Idle" and "InUse" of the GuestUserState enumeration arei supported on Windows guests, starting at Windows 2000 SP2.

- The attribute IGuestSession::protocolVersion was added to provide a convenient way to lookup the guest session's protocol version it uses to communicate with the installed Guest Additions on the guest. Older Guest Additions will set the protocol version to 1, whereas Guest Additions 4.3 will set the protocol version to 2. This might change in the future as new features arise.

- `IDisplay::getScreenResolution` has been extended to return the display position in the guest.

- The IUSBController class is not a singleton of IMachine anymore but IMachine contains a list of USB controllers present in the VM. The USB device filter handling was moved to IUSBDeviceFilters.

### Incompatible API changes with version 4.2

- Guest control APIs for executing guest processes, working with guest files or directories have been moved to the newly introduced IGuestSession interface which can be created by calling IGuest::createSession().

  A guest session will act as a guest user's impersonation so that the guest credentials only have to be provided when creating a new guest session. There can be up to 32 guest sessions at once per VM, each session serving up to 2048 guest processes running or files opened.

  Instead of working with process or directory handles before version 4.2, there now are the dedicated interfaces IGuestProcess, IGuestDirectory and IGuestFile. To retrieve more information of a file system object the new interface IGuestFsObjInfo has been introduced.

  Even though the guest control API was changed it is backwards compatible so that it can be used with older installed Guest Additions. However, to use upcoming features like process termination or waiting for input / output new Guest Additions must be installed when these features got implemented.

  The following limitations apply:

  - The IGuestFile interface is not fully implemented yet.

  - The symbolic link APIs IGuestSession::symlinkCreate(), IGuestSession::symlinkExists(), IGuestSession::symlinkRead(), IGuestSession::symlinkRemoveDirectory() and IGuestSession::symlinkRemoveFile() are not implemented yet.

  - The directory APIs IGuestSession::directoryRemove(), IGuestSession::directoryRemoveRecursive(), IGuestSession::directoryRename() and IGuestSession::directorySetACL() are not implemented yet.

  - The temporary file creation API IGuestSession::fileCreateTemp() is not implemented yet.

  - Guest process termination via IProcess::terminate() is not implemented yet.

  - Waiting for guest process output via ProcessWaitForFlag::StdOut and ProcessWaitForFlag::StdErr is not implemented yet.

    To wait for process output, IProcess::read() with appropriate flags still can be used to periodically check for new output data to arrive. Note that ProcessCreateFlag::WaitForStdOut and / or ProcessCreateFlag::WaitForStdErr need to be specified when creating a guest process via IGuestSession::processCreate() or IGuestSession::processCreateEx().

  - ACL (Access Control List) handling in general is not implemented yet.

- The LockType enumeration now has an additional value `VM` which tells IMachine::lockMachine() to create a full-blown object structure for running a VM. This was the previous behavior with `Write`, which now only creates the minimal object structure to save time and resources (at the moment the Console object is still created, but all sub-objects such as Display, Keyboard, Mouse, Guest are not.

- Machines can be put in groups (actually an array of groups). The primary group affects the default placement of files belonging to a VM. IVirtualBox::createMachine() and IVirtualBox::composeMachineFilename() have been adjusted accordingly, the former taking an array of groups as an additional parameter and the latter taking a group as an additional parameter. The create option handling has been changed for those two methods, too.

- The method IVirtualBox::findMedium() has been removed, since it provides a subset of the functionality of IVirtualBox::openMedium().

- The use of acronyms in API enumeration, interface, attribute and method names has been made much more consistent, previously they sometimes were lowercase and sometimes mixed case. They are now consistently all caps:

  ### Renamed identifiers in VirtualBox 4.2

  Old name | New name
  PointingHidType | PointingHIDType
  KeyboardHidType | KeyboardHIDType
  IPciAddress | IPCIAddress
  IPciDeviceAttachment | IPCIDeviceAttachment
  IMachine::pointingHidType | IMachine::pointingHIDType
  IMachine::keyboardHidType | IMachine::keyboardHIDType
  IMachine::hpetEnabled | IMachine::HPETEnabled
  IMachine::sessionPid | IMachine::sessionPID
  IMachine::ioCacheEnabled | IMachine::IOCacheEnabled
  IMachine::ioCacheSize | IMachine::IOCacheSize
  IMachine::pciDeviceAssignments | IMachine::PCIDeviceAssignments
  IMachine::attachHostPciDevice() | IMachine::attachHostPCIDevice
  IMachine::detachHostPciDevice() | IMachine::detachHostPCIDevice()
  IConsole::attachedPciDevices | IConsole::attachedPCIDevices
  IHostNetworkInterface::dhcpEnabled | IHostNetworkInterface::DHCPEnabled
  IHostNetworkInterface::enableStaticIpConfig() | IHostNetworkInterface::enableStaticIPConfig()
  IHostNetworkInterface::enableStaticIpConfigV6() | IHostNetworkInterface::enableStaticIPConfigV6()
  IHostNetworkInterface::enableDynamicIpConfig() | IHostNetworkInterface::enableDynamicIPConfig()
  IHostNetworkInterface::dhcpRediscover() | IHostNetworkInterface::DHCPRediscover()
  IHost::acceleration3DAvailable
  IGuestOSType::recommendedPae | IGuestOSType::recommendedPAE
  IGuestOSType::recommendedDvdStorageController | IGuestOSType::recommendedDVDStorageController
  IGuestOSType::recommendedDvdStorageBus | IGuestOSType::recommendedDVDStorageBus
  IGuestOSType::recommendedHdStorageController | IGuestOSType::recommendedHDStorageController
  IGuestOSType::recommendedHdStorageBus | IGuestOSType::recommendedHDStorageBus
  IGuestOSType::recommendedUsbHid | IGuestOSType::recommendedUSBHID
  IGuestOSType::recommendedHpet | IGuestOSType::recommendedHPET
  IGuestOSType::recommendedUsbTablet | IGuestOSType::recommendedUSBTablet
  IGuestOSType::recommendedRtcUseUtc | IGuestOSType::recommendedRTCUseUTC
  IGuestOSType::recommendedUsb | IGuestOSType::recommendedUSB
  INetworkAdapter::natDriver | INetworkAdapter::NATEngine
  IUSBController::enabledEhci | IUSBController::enabledEHCI"
  INATEngine::tftpPrefix | INATEngine::TFTPPrefix
  INATEngine::tftpBootFile | INATEngine::TFTPBootFile
  INATEngine::tftpNextServer | INATEngine::TFTPNextServer
  INATEngine::dnsPassDomain | INATEngine::DNSPassDomain
  INATEngine::dnsProxy | INATEngine::DNSProxy
  INATEngine::dnsUseHostResolver | INATEngine::DNSUseHostResolver
  VBoxEventType::OnHostPciDevicePlug | VBoxEventType::OnHostPCIDevicePlug
  ICPUChangedEvent::cpu | ICPUChangedEvent::CPU
  INATRedirectEvent::hostIp | INATRedirectEvent::hostIP
  INATRedirectEvent::guestIp | INATRedirectEvent::guestIP
  IHostPciDevicePlugEvent | IHostPCIDevicePlugEvent

### Incompatible API changes with version 4.1

- The method IAppliance::importMachines() has one more parameter now, which allows to configure the import process in more detail.

- The method IVirtualBox::openMedium() has one more parameter now, which allows resolving duplicate medium UUIDs without the need for external tools.

- The INetworkAdapter interface has been cleaned up. The various methods to activate an attachment type have been replaced by the INetworkAdapter::attachmentType setter.

  Additionally each attachment mode now has its own attribute, which means that host only networks no longer share the settings with bridged interfaces.

  To allow introducing new network attachment implementations without making API changes, the concept of a generic network attachment driver has been introduced, which is configurable through key/value properties.

- This version introduces the guest facilities concept. A guest facility either represents a module or feature the guest is running or offering, which is defined by AdditionsFacilityType. Each facility is member of a AdditionsFacilityClass and has a current status indicated by AdditionsFacilityStatus, together with a timestamp (in ms) of the last status update.

  To address the above concept, the following changes were made:

  - In the IGuest interface, the following were removed:

    - the `supportsSeamless` attribute;

    - the `supportsGraphics` attribute;

  - The function IGuest::getFacilityStatus() was added. It quickly provides a facility's status without the need to get the facility collection with IGuest::facilities.

  - The attribute IGuest::facilities was added to provide an easy to access collection of all currently known guest facilities, that is, it contains all facilies where at least one status update was made since the guest was started.

  - The interface IAdditionsFacility was added to represent a single facility returned by IGuest::facilities.

  - AdditionsFacilityStatus was added to represent a facility's overall status.

  - AdditionsFacilityType and AdditionsFacilityClass were added to represent the facility's type and class.

### Incompatible API changes with version 4.0

- A new Java glue layer replacing the previous OOWS JAX-WS bindings was introduced. The new library allows for uniform code targeting both local (COM/XPCOM) and remote (SOAP) transports. Now, instead of `IWebsessionManager`, the new class `VirtualBoxManager` must be used. See javaapi for details.

- The confusingly named and impractical session APIs were changed. In existing client code, the following changes need to be made:

  - Replace any `IVirtualBox::openSession(uuidMachine, ...)` API call with the machine's IMachine::lockMachine() call and a `LockType.Write` argument. The functionality is unchanged, but instead of "opening a direct session on a machine" all documentation now refers to "obtaining a write lock on a machine for the client session".

  - Similarly, replace any `IVirtualBox::openExistingSession(uuidMachine, ...)` call with the machine's IMachine::lockMachine() call and a `LockType.Shared` argument. Whereas it was previously impossible to connect a client session to a running VM process in a race-free manner, the new API will atomically either write-lock the machine for the current session or establish a remote link to an existing session. Existing client code which tried calling both `openSession()` and `openExistingSession()` can now use this one call instead.

  - Third, replace any `IVirtualBox::openRemoteSession(uuidMachine, ...)` call with the machine's IMachine::launchVMProcess() call. The functionality is unchanged.

  - The SessionState enum was adjusted accordingly: "Open" is now "Locked", "Closed" is now "Unlocked", "Closing" is now "Unlocking".

- Virtual machines created with VirtualBox 4.0 or later no longer register their media in the global media registry in the `VirtualBox.xml` file. Instead, such machines list all their media in their own machine XML files. As a result, a number of media-related APIs had to be modified again.

  - Neither `IVirtualBox::createHardDisk()` nor IVirtualBox::openMedium() register media automatically any more.

  - IMachine::attachDevice() and IMachine::mountMedium() now take an IMedium object instead of a UUID as an argument. It is these two calls which add media to a registry now (either a machine registry for machines created with VirtualBox 4.0 or later or the global registry otherwise). As a consequence, if a medium is opened but never attached to a machine, it is no longer added to any registry any more.

  - To reduce code duplication, the APIs IVirtualBox::findHardDisk(), getHardDisk(), findDVDImage(), getDVDImage(), findFloppyImage() and getFloppyImage() have all been merged into IVirtualBox::findMedium(), and IVirtualBox::openHardDisk(), openDVDImage() and openFloppyImage() have all been merged into IVirtualBox::openMedium().

  - The rare use case of changing the UUID and parent UUID of a medium previously handled by `openHardDisk()` is now in a separate IMedium::setIDs method.

  - `ISystemProperties::get/setDefaultHardDiskFolder()` have been removed since disk images are now by default placed in each machine's folder.

  - The ISystemProperties::infoVDSize attribute replaces the `getMaxVDISize()` API call; this now uses bytes instead of megabytes.

- Machine management APIs were enhanced as follows:

  - IVirtualBox::createMachine() is no longer restricted to creating machines in the default "Machines" folder, but can now create machines at arbitrary locations. For this to work, the parameter list had to be changed.

  - The long-deprecated `IVirtualBox::createLegacyMachine()` API has been removed.

  - To reduce code duplication and for consistency with the aforementioned media APIs, `IVirtualBox::getMachine()` has been merged with IVirtualBox::findMachine(), and `IMachine::getSnapshot()` has been merged with IMachine::findSnapshot().

  - `IVirtualBox::unregisterMachine()` was replaced with IMachine::unregister() with additional functionality for cleaning up machine files.

  - `IMachine::deleteSettings` has been replaced by IMachine::delete, which allows specifying which disk images are to be deleted as part of the deletion, and because it can take a while it also returns a `IProgress` object reference, so that the completion of the asynchronous activities can be monitored.

  - `IConsole::forgetSavedState` has been renamed to `IConsole::discardSavedState()`.

- All event callbacks APIs were replaced with a new, generic event mechanism that can be used both locally (COM, XPCOM) and remotely (web services). Also, the new mechanism is usable from scripting languages and a local Java. See events for details. The new concept will require changes to all clients that used event callbacks.

- `additionsActive()` was replaced with additionsRunLevel() and getAdditionsStatus() in order to support a more detailed status of the current Guest Additions loading/readiness state. IGuest::additionsVersion() no longer returns the Guest Additions interface version but the installed Guest Additions version and revision in form of `3.3.0r12345`.

- To address shared folders auto-mounting support, the following APIs were extended to require an additional `automount` parameter:

  - IVirtualBox::createSharedFolder()

  - IMachine::createSharedFolder()

  - IConsole::createSharedFolder()

  Also, a new property named `autoMount` was added to the ISharedFolder interface.

- The appliance (OVF) APIs were enhanced as follows:

  - `IMachine::export` received an extra parameter `location`, which is used to decide for the disk naming.

  - IAppliance::write() received an extra parameter `manifest`, which can suppress creating the manifest file on export.

  - IVFSExplorer::entryList() received two extra parameters `sizes` and `modes`, which contains the sizes (in bytes) and the file access modes (in octal form) of the returned files.

- Support for remote desktop access to virtual machines has been cleaned up to allow third party implementations of the remote desktop server. This is called the VirtualBox Remote Desktop Extension (VRDE) and can be added to VirtualBox by installing the corresponding extension package; see the VirtualBox User Guide for details.

  The following API changes were made to support the VRDE interface:

  - `IVRDPServer` has been renamed to IVRDEServer.

  - `IRemoteDisplayInfo` has been renamed to IVRDEServerInfo.

  - IMachine::VRDEServer replaces `VRDPServer.`

  - IConsole::VRDEServerInfo replaces `RemoteDisplayInfo`.

  - ISystemProperties::VRDEAuthLibrary replaces `RemoteDisplayAuthLibrary`.

  - The following methods have been implemented in `IVRDEServer` to support generic VRDE properties:

    - IVRDEServer::setVRDEProperty

    - IVRDEServer::getVRDEProperty

    - IVRDEServer::VRDEProperties

    A few implementation-specific attributes of the old `IVRDPServer` interface have been removed and replaced with properties:

    - `IVRDPServer::Ports` has been replaced with the `"TCP/Ports"` property. The property value is a string, which contains a comma-separated list of ports or ranges of ports. Use a dash between two port numbers to specify a range. Example: `"5000,5010-5012"`

    - `IVRDPServer::NetAddress` has been replaced with the `"TCP/Address"` property. The property value is an IP address string. Example: `"127.0.0.1"`

    - `IVRDPServer::VideoChannel` has been replaced with the `"VideoChannel/Enabled"` property. The property value is either `"true"` or `"false"`

    - `IVRDPServer::VideoChannelQuality` has been replaced with the `"VideoChannel/Quality"` property. The property value is a string which contain a decimal number in range 10..100. Invalid values are ignored and the quality is set to the default value 75. Example: `"50"`

- The VirtualBox external authentication module interface has been updated and made more generic. Because of that, `VRDPAuthType` enumeration has been renamed to AuthType.

### Incompatible API changes with version 3.2

- The following interfaces were renamed for consistency:

  - IMachine::getCpuProperty() is now IMachine::getCPUProperty();

  - IMachine::setCpuProperty() is now IMachine::setCPUProperty();

  - IMachine::getCpuIdLeaf() is now IMachine::getCPUIDLeaf();

  - IMachine::setCpuIdLeaf() is now IMachine::setCPUIDLeaf();

  - IMachine::removeCpuIdLeaf() is now IMachine::removeCPUIDLeaf();

  - IMachine::removeAllCpuIdLeafs() is now IMachine::removeAllCPUIDLeaves();

  - the CpuPropertyType enum is now CPUPropertyType.

  - IVirtualBoxCallback::onSnapshotDiscarded() is now IVirtualBoxCallback::onSnapshotDeleted.

- When creating a VM configuration with IVirtualBox::createMachine() it is now possible to ignore existing configuration files which would previously have caused a failure. For this the `override` parameter was added.

- Deleting snapshots via `IConsole::deleteSnapshot()` is now possible while the associated VM is running in almost all cases. The API is unchanged, but client code that verifies machine states to determine whether snapshots can be deleted may need to be adjusted.

- The IoBackendType enumeration was replaced with a boolean flag (see IStorageController::useHostIOCache).

- To address multi-monitor support, the following APIs were extended to require an additional `screenId` parameter:

  - IMachine::querySavedThumbnailSize()

  - IMachine::readSavedThumbnailToArray()

  - IMachine::querySavedScreenshotPNGSize()

  - IMachine::readSavedScreenshotPNGToArray()

- The `shape` parameter of IConsoleCallback::onMousePointerShapeChange was changed from a implementation-specific pointer to a safearray, enabling scripting languages to process pointer shapes.

### Incompatible API changes with version 3.1

- Due to the new flexibility in medium attachments that was introduced with version 3.1 (in particular, full flexibility with attaching CD/DVD drives to arbitrary controllers), we seized the opportunity to rework all interfaces dealing with storage media to make the API more flexible as well as logical. The IStorageController, IMedium, IMediumAttachment and IMachine interfaces were affected the most. Existing code using them to configure storage and media needs to be carefully checked.

  All media (hard disks, floppies and CDs/DVDs) are now uniformly handled through the IMedium interface. The device-specific interfaces (`IHardDisk`, `IDVDImage`, `IHostDVDDrive`, `IFloppyImage` and `IHostFloppyDrive`) have been merged into IMedium; CD/DVD and floppy media no longer need special treatment. The device type of a medium determines in which context it can be used. Some functionality was moved to the other storage-related interfaces.

  `IMachine::attachHardDisk` and similar methods have been renamed and generalized to deal with any type of drive and medium. IMachine::attachDevice() is the API method for adding any drive to a storage controller. The floppy and DVD/CD drives are no longer handled specially, and that means you can have more than one of them. As before, drives can only be changed while the VM is powered off. Mounting (or unmounting) removable media at runtime is possible with IMachine::mountMedium().

  Newly created virtual machines have no storage controllers associated with them. Even the IDE Controller needs to be created explicitly. The floppy controller is now visible as a separate controller, with a new storage bus type. For each storage bus type you can query the device types which can be attached, so that it is not necessary to hardcode any attachment rules.

  This required matching changes e.g. in the callback interfaces (the medium specific change notification was replaced by a generic medium change notification) and removing associated enums (e.g. `DriveState`). In many places the incorrect use of the plural form "media" was replaced by "medium", to improve consistency.

- Reading the IMedium::state attribute no longer automatically performs an accessibility check; a new method IMedium::refreshState() does this. The attribute only returns the state now.

- There were substantial changes related to snapshots, triggered by the "branched snapshots" functionality introduced with version 3.1. IConsole::discardSnapshot was renamed to `IConsole::deleteSnapshot()`. IConsole::discardCurrentState and IConsole::discardCurrentSnapshotAndState were removed; corresponding new functionality is in `IConsole::restoreSnapshot()`. Also, when `IConsole::takeSnapshot()` is called on a running virtual machine, a live snapshot will be created. The old behavior was to temporarily pause the virtual machine while creating an online snapshot.

- The `IVRDPServer`, `IRemoteDisplayInfo"` and `IConsoleCallback` interfaces were changed to reflect VRDP server ability to bind to one of available ports from a list of ports.

  The `IVRDPServer::port` attribute has been replaced with `IVRDPServer::ports`, which is a comma-separated list of ports or ranges of ports.

  An `IRemoteDisplayInfo::port"` attribute has been added for querying the actual port VRDP server listens on.

  An IConsoleCallback::onRemoteDisplayInfoChange() notification callback has been added.

- The parameter lists for the following functions were modified:

  - IHost::removeHostOnlyNetworkInterface()

  - IHost::removeUSBDeviceFilter()

- In the OOWS bindings for JAX-WS, the behavior of structures changed: for one, we implemented natural structures field access so you can just call a "get" method to obtain a field. Secondly, setters in structures were disabled as they have no expected effect and were at best misleading.

### Incompatible API changes with version 3.0

- In the object-oriented web service bindings for JAX-WS, proper inheritance has been introduced for some classes, so explicit casting is no longer needed to call methods from a parent class. In particular, IHardDisk and other classes now properly derive from IMedium.

- All object identifiers (machines, snapshots, disks, etc) switched from GUIDs to strings (now still having string representation of GUIDs inside). As a result, no particular internal structure can be assumed for object identifiers; instead, they should be treated as opaque unique handles. This change mostly affects Java and C++ programs; for other languages, GUIDs are transparently converted to strings.

- The uses of NULL strings have been changed greatly. All out parameters now use empty strings to signal a null value. For in parameters both the old NULL and empty string is allowed. This change was necessary to support more client bindings, especially using the web service API. Many of them either have no special NULL value or have trouble dealing with it correctly in the respective library code.

- Accidentally, the `TSBool` interface still appeared in 3.0.0, and was removed in 3.0.2. This is an SDK bug, do not use the SDK for VirtualBox 3.0.0 for developing clients.

- The type of IVirtualBoxErrorInfo::resultCode changed from `result` to `long`.

- The parameter list of IVirtualBox::openHardDisk was changed.

- The method IConsole::discardSavedState was renamed to IConsole::forgetSavedState, and a parameter was added.

- The method IConsole::powerDownAsync was renamed to IConsole::powerDown, and the previous method with that name was deleted. So effectively a parameter was added.

- In the IFramebuffer interface, the following were removed:

  - the `operationSupported` attribute;

    (as a result, the `FramebufferAccelerationOperation` enum was no longer needed and removed as well);

  - the `solidFill()` method;

  - the `copyScreenBits()` method.

- In the IDisplay interface, the following were removed:

  - the `setupInternalFramebuffer()` method;

  - the `lockFramebuffer()` method;

  - the `unlockFramebuffer()` method;

  - the `registerExternalFramebuffer()` method.

### Incompatible API changes with version 2.2

- Added explicit version number into JAX-WS Java package names, such as `org.virtualbox_2_2`, allowing connect to multiple VirtualBox clients from single Java application.

- The interfaces having a "2" suffix attached to them with version 2.1 were renamed again to have that suffix removed. This time around, this change involves only the name, there are no functional differences.

  As a result, IDVDImage2 is now IDVDImage; IHardDisk2 is now IHardDisk; IHardDisk2Attachment is now IHardDiskAttachment.

  Consequentially, all related methods and attributes that had a "2" suffix have been renamed; for example, IMachine::attachHardDisk2 now becomes IMachine::attachHardDisk().

- IVirtualBox::openHardDisk has an extra parameter for opening a disk read/write or read-only.

- The remaining collections were replaced by more performant safe-arrays. This affects the following collections:

  - IGuestOSTypeCollection

  - IHostDVDDriveCollection

  - IHostFloppyDriveCollection

  - IHostUSBDeviceCollection

  - IHostUSBDeviceFilterCollection

  - IProgressCollection

  - ISharedFolderCollection

  - ISnapshotCollection

  - IUSBDeviceCollection

  - IUSBDeviceFilterCollection

- Since "Host Interface Networking" was renamed to "bridged networking" and host-only networking was introduced, all associated interfaces needed renaming as well. In detail:

  - The HostNetworkInterfaceType enum has been renamed to HostNetworkInterfaceMediumType

  - The IHostNetworkInterface::type attribute has been renamed to IHostNetworkInterface::mediumType

  - INetworkAdapter::attachToHostInterface() has been renamed to INetworkAdapter::attachToBridgedInterface

  - In the IHost interface, createHostNetworkInterface() has been renamed to createHostOnlyNetworkInterface()

  - Similarly, removeHostNetworkInterface() has been renamed to removeHostOnlyNetworkInterface()

### Incompatible API changes with version 2.1

- With VirtualBox 2.1, error codes were added to many error infos that give the caller a machine-readable (numeric) feedback in addition to the error string that has always been available. This is an ongoing process, and future versions of this SDK reference will document the error codes for each method call.

- The hard disk and other media interfaces were completely redesigned. This was necessary to account for the support of VMDK, VHD and other image types; since backwards compatibility had to be broken anyway, we seized the moment to redesign the interfaces in a more logical way.

  - Previously, the old IHardDisk interface had several derivatives called IVirtualDiskImage, IVMDKImage, IVHDImage, IISCSIHardDisk and ICustomHardDisk for the various disk formats supported by VirtualBox. The new IHardDisk2 interface that comes with version 2.1 now supports all hard disk image formats itself.

  - IHardDiskFormat is a new interface to describe the available back-ends for hard disk images (e.g. VDI, VMDK, VHD or iSCSI). The IHardDisk2::format attribute can be used to find out the back-end that is in use for a particular hard disk image. ISystemProperties::hardDiskFormats[] contains a list of all back-ends supported by the system. ISystemProperties::defaultHardDiskFormat contains the default system format.

  - In addition, the new IMedium interface is a generic interface for hard disk, DVD and floppy images that contains the attributes and methods shared between them. It can be considered a parent class of the more specific interfaces for those images, which are now IHardDisk2, IDVDImage2 and IFloppyImage2.

    In each case, the "2" versions of these interfaces replace the earlier versions that did not have the "2" suffix. Previously, the IDVDImage and IFloppyImage interfaces were entirely unrelated to IHardDisk.

  - As a result, all parts of the API that previously referenced IHardDisk, IDVDImage or IFloppyImage or any of the old subclasses are gone and will have replacements that use IHardDisk2, IDVDImage2 and IFloppyImage2; see, for example, IMachine::attachHardDisk2.

  - In particular, the IVirtualBox::hardDisks2 array replaces the earlier IVirtualBox::hardDisks collection.

- IGuestOSType was extended to group operating systems into families and for 64-bit support.

- The IHostNetworkInterface interface was completely rewritten to account for the changes in how Host Interface Networking is now implemented in VirtualBox 2.1.

- The IVirtualBox::machines2[] array replaces the former IVirtualBox::machines collection.

- Added IHost::getProcessorFeature() and ProcessorFeature enumeration.

- The parameter list for IVirtualBox::createMachine() was modified.

- Added IMachine::pushGuestProperty.

- New attributes in IMachine: accelerate3DEnabled, HWVirtExVPIDEnabled, `IMachine::guestPropertyNotificationPatterns`, CPUCount.

- Added IConsole::powerUpPaused() and IConsole::getGuestEnteredACPIMode().

- Removed ResourceUsage enumeration.