VirtualBoxImpl.cpp revision d909c33d4b2305eda2ab9995e86a53ea00d819be
/** @file
*
* VirtualBox COM class implementation
*/
/*
* Copyright (C) 2006-2007 innotek GmbH
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#include "VirtualBoxImpl.h"
#include "MachineImpl.h"
#include "HardDiskImpl.h"
#include "DVDImageImpl.h"
#include "FloppyImageImpl.h"
#include "SharedFolderImpl.h"
#include "ProgressImpl.h"
#include "HostImpl.h"
#include "USBControllerImpl.h"
#include "SystemPropertiesImpl.h"
#include "GuestOSTypeImpl.h"
#include "VirtualBoxXMLUtil.h"
#include "Logging.h"
#ifdef RT_OS_WINDOWS
#endif
#include <stdio.h>
#include <stdlib.h>
#include <iprt/cpputils.h>
#include <VBox/VBoxHDD-new.h>
#include <algorithm>
#include <set>
#include <memory> // for auto_ptr
#include <typeinfo>
// defines
/////////////////////////////////////////////////////////////////////////////
#define VBOX_GLOBAL_SETTINGS_FILE "VirtualBox.xml"
// globals
/////////////////////////////////////////////////////////////////////////////
static const char DefaultGlobalConfig [] =
{
"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" RTFILE_LINEFEED
"<!-- innotek VirtualBox Global Configuration -->" RTFILE_LINEFEED
" <Global>"RTFILE_LINEFEED
" <MachineRegistry/>"RTFILE_LINEFEED
" <DiskRegistry/>"RTFILE_LINEFEED
" <USBDeviceFilters/>"RTFILE_LINEFEED
" <SystemProperties/>"RTFILE_LINEFEED
" </Global>"RTFILE_LINEFEED
"</VirtualBox>"RTFILE_LINEFEED
};
// static
// constructor / destructor
/////////////////////////////////////////////////////////////////////////////
, mAsyncEventQ (NULL)
{}
VirtualBox::~VirtualBox() {}
{
LogFlowThisFunc (("\n"));
return init();
}
void VirtualBox::FinalRelease()
{
LogFlowThisFunc (("\n"));
uninit();
}
{
}
// public initializer/uninitializer for internal purposes only
/////////////////////////////////////////////////////////////////////////////
/**
* Initializes the VirtualBox object.
*
* @return COM result code
*/
{
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan (this);
LogFlow (("===========================================================\n"));
/* Get the VirtualBox home directory. */
{
char homeDir [RTPATH_MAX];
if (VBOX_FAILURE (vrc))
tr ("Could not create the VirtualBox home directory '%s'"
"(%Vrc)"),
}
/* compose the global config file name (always full path) */
/* store the config file name */
/* lock the config file */
{
if (!isConfigLocked())
{
/*
* This means the config file not found. This is not fatal --
* we just create an empty one.
*/
if (VBOX_SUCCESS (vrc))
(void *) DefaultGlobalConfig,
sizeof (DefaultGlobalConfig), NULL);
if (VBOX_FAILURE (vrc))
{
"'%s' (%Vrc)"),
}
else
{
/* we do not close the file to simulate lockConfig() */
}
}
}
{
try
{
using namespace settings;
/* create the host object early, machines will need it */
/* create the system properties object */
/* guest OS type objects, needed by machines */
rc = registerGuestOSTypes();
/* hard disks, needed by machines */
/* machines */
/* check hard disk consistency */
/// @todo (r=dmik) add IVirtualBox::cleanupHardDisks() instead or similar
// for (HardDiskList::const_iterator it = mData.mHardDisks.begin();
// it != mData.mHardDisks.end() && SUCCEEDED (rc);
// ++ it)
// {
// rc = (*it)->checkConsistency();
// }
// CheckComRCBreakRC ((rc));
/// @todo (dmik) if successful, check for orphan (unused) diffs
// that might be left because of the server crash, and remove
// Hmm, is it the same remark as above?..
}
{
/* we assume that error info is set by the thrower */
}
catch (...)
{
}
}
{
/* start the client watcher thread */
#if defined(RT_OS_WINDOWS)
#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
#else
# error "Port me!"
#endif
ClientWatcher, (void *) this,
RTTHREADFLAGS_WAITABLE, "Watcher");
ComAssertRC (vrc);
if (VBOX_FAILURE (vrc))
}
{
/* start the async event handler thread */
&unconst (mAsyncEventQ),
RTTHREADFLAGS_WAITABLE, "EventHandler");
/* wait until the thread sets mAsyncEventQ */
}
while (0);
/* Confirm a successful initialization when it's the case */
LogFlow (("===========================================================\n"));
return rc;
}
void VirtualBox::uninit()
{
/* Enclose the state transition Ready->InUninit->NotReady */
AutoUninitSpan autoUninitSpan (this);
if (autoUninitSpan.uninitDone())
return;
LogFlow (("===========================================================\n"));
/* tell all our child objects we've been uninitialized */
{
}
if (mData.mSystemProperties)
{
}
{
}
/*
* Uninit all other children still referenced by clients
* server-side progress operations).
*/
/* unlock the config file */
unlockConfig();
LogFlowThisFunc (("Releasing callbacks...\n"));
{
/* release all callbacks */
LogWarningFunc (("%d unregistered callbacks!\n",
}
LogFlowThisFunc (("Terminating the async event handler...\n"));
if (mAsyncEventThread != NIL_RTTHREAD)
{
/* signal to exit the event loop */
{
/*
* Wait for thread termination (only if we've successfully posted
* a NULL event!)
*/
if (VBOX_FAILURE (vrc))
LogWarningFunc (("RTThreadWait(%RTthrd) -> %Vrc\n",
mAsyncEventThread, vrc));
}
else
{
AssertMsgFailed (("postEvent(NULL) failed\n"));
}
}
LogFlowThisFunc (("Terminating the client watcher...\n"));
{
/* signal the client watcher thread */
/* wait for the termination */
}
#if defined(RT_OS_WINDOWS)
{
}
{
}
#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
{
}
#else
# error "Port me!"
#endif
LogFlow (("===========================================================\n"));
}
// IVirtualBox properties
/////////////////////////////////////////////////////////////////////////////
{
if (!aVersion)
return E_INVALIDARG;
AutoCaller autoCaller (this);
return S_OK;
}
{
if (!aHomeFolder)
return E_POINTER;
AutoCaller autoCaller (this);
return S_OK;
}
{
if (!aHost)
return E_POINTER;
AutoCaller autoCaller (this);
return S_OK;
}
{
if (!aSystemProperties)
return E_POINTER;
AutoCaller autoCaller (this);
return S_OK;
}
/** @note Locks this object for reading. */
{
if (!aMachines)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
/** @note Locks this object for reading. */
{
if (!aHardDisks)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
/** @note Locks this object for reading. */
{
if (!aDVDImages)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
/** @note Locks this object for reading. */
{
if (!aFloppyImages)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
/** @note Locks this object for reading. */
{
if (!aOperations)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
/** @note Locks this object for reading. */
{
if (!aGuestOSTypes)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
if (!aSharedFolders)
return E_POINTER;
AutoCaller autoCaller (this);
}
// IVirtualBox methods
/////////////////////////////////////////////////////////////////////////////
/** @note Locks mSystemProperties object for reading. */
{
LogFlowThisFunc (("aBaseFolder='%ls', aName='%ls' aMachine={%p}\n",
if (!aName)
return E_INVALIDARG;
if (!aMachine)
return E_POINTER;
if (!*aName)
return setError (E_INVALIDARG,
tr ("Machine name cannot be empty"));
AutoCaller autoCaller (this);
/* Compose the settings file name using the following scheme:
*
* <base_folder>/<machine_name>/<machine_name>.xml
*
* If a non-null and non-empty base folder is specified, the default
* machine folder will be used as a base folder.
*/
if (settingsFile.isEmpty())
{
/* we use the non-full folder value below to keep the path relative */
}
/* create a new object */
{
/* Create UUID if an empty one was specified. */
/* initialize the machine object */
{
/* set the return value */
ComAssertComRC (rc);
}
}
return rc;
}
{
/* null and empty strings are not allowed as path names */
if (!aSettingsFile || !(*aSettingsFile))
return E_INVALIDARG;
if (!aName)
return E_INVALIDARG;
if (!aMachine)
return E_POINTER;
if (!*aName)
return setError (E_INVALIDARG,
tr ("Machine name cannot be empty"));
AutoCaller autoCaller (this);
/* append the default extension if none */
if (!RTPathHaveExt (settingsFile))
/* create a new object */
{
/* Create UUID if an empty one was specified. */
/* initialize the machine object */
{
/* set the return value */
ComAssertComRC (rc);
}
}
return rc;
}
{
/* null and empty strings are not allowed as path names */
if (!aSettingsFile || !(*aSettingsFile))
return E_INVALIDARG;
if (!aMachine)
return E_POINTER;
AutoCaller autoCaller (this);
/* create a new object */
{
/* initialize the machine object */
{
/* set the return value */
ComAssertComRC (rc);
}
}
return rc;
}
/** @note Locks objects! */
{
if (!aMachine)
return E_INVALIDARG;
AutoCaller autoCaller (this);
/*
* we can safely cast child to Machine * here because only Machine
* implementations of IMachine can be among our children
*/
if (!machine)
{
/*
* this machine was not created by CreateMachine()
* or opened by OpenMachine() or loaded during startup
*/
tr ("The machine named '%ls' is not created within this "
}
/* fire an event */
return rc;
}
/** @note Locks objects! */
{
if (!aMachine)
return E_POINTER;
AutoCaller autoCaller (this);
/* the below will set *aMachine to NULL if machine is null */
return rc;
}
/** @note Locks this object for reading, then some machine objects for reading. */
{
if (!aName)
return E_INVALIDARG;
if (!aMachine)
return E_POINTER;
AutoCaller autoCaller (this);
/* start with not found */
{
/* take a copy for safe iteration outside the lock */
AutoReaderLock alock (this);
}
++ it)
{
/* skip inaccessible machines */
{
}
}
/* this will set (*machine) to NULL if machineObj is null */
? S_OK
: setError (E_INVALIDARG,
return rc;
}
/** @note Locks objects! */
{
return E_INVALIDARG;
AutoCaller autoCaller (this);
/* remove from the collection of registered machines */
/* save the global registry */
rc = saveSettings();
/* return the unregistered machine to the caller */
/* fire an event */
return rc;
}
{
if (!aHardDisk)
return E_POINTER;
AutoCaller autoCaller (this);
switch (aStorageType)
{
{
vdi.createObject();
break;
}
{
break;
}
{
vmdk.createObject();
break;
}
{
break;
}
{
vhd.createObject();
break;
}
default:
AssertFailed();
};
return rc;
}
/** @note Locks mSystemProperties object for reading. */
{
/* null and empty strings are not allowed locations */
return E_INVALIDARG;
if (!aHardDisk)
return E_POINTER;
AutoCaller autoCaller (this);
/* Currently, the location is always a path. So, append the
* default path if only a name is given. */
{
if (!RTPathHavePath (loc))
{
}
}
return rc;
}
/** @note Locks mSystemProperties object for reading. */
{
/* null and empty strings are not allowed as path names here */
return E_INVALIDARG;
if (!aImage)
return E_POINTER;
AutoCaller autoCaller (this);
/* append the default path if only a name is given */
{
if (!RTPathHavePath (fp))
{
}
}
vdi.createObject();
return rc;
}
/** @note Locks objects! */
{
if (!aHardDisk)
return E_POINTER;
AutoCaller autoCaller (this);
if (!child)
"this VirtualBox instance"));
/*
* we can safely cast child to HardDisk * here because only HardDisk
* implementations of IHardDisk can be among our children
*/
}
/** @note Locks objects! */
{
if (!aHardDisk)
return E_POINTER;
AutoCaller autoCaller (this);
/* the below will set *aHardDisk to NULL if hd is null */
return rc;
}
/** @note Locks objects! */
{
if (!aLocation)
return E_INVALIDARG;
if (!aHardDisk)
return E_POINTER;
AutoCaller autoCaller (this);
{
/* nothing special */
}
else
{
/* For locations represented by file paths, append the default path if
* only a name is given, and then get the full path. */
if (!RTPathHavePath (location))
{
}
/* get the full file name */
char buf [RTPATH_MAX];
if (VBOX_FAILURE (vrc))
}
&hardDisk);
/* the below will set *aHardDisk to NULL if hardDisk is null */
return rc;
}
/** @note Locks objects! */
{
if (!aFilePath)
return E_INVALIDARG;
if (!aImage)
return E_POINTER;
AutoCaller autoCaller (this);
/* append the default path if only a name is given */
{
if (!RTPathHavePath (fp))
{
}
}
/* get the full file name */
char buf [RTPATH_MAX];
if (VBOX_FAILURE (vrc))
&vdi);
/* the below will set *aImage to NULL if vdi is null */
return rc;
}
/** @note Locks objects! */
{
if (!aHardDisk)
return E_POINTER;
AutoCaller autoCaller (this);
return rc;
}
/** @note Doesn't lock anything. */
{
/* null and empty strings are not allowed as path names */
return E_INVALIDARG;
if (!aDVDImage)
return E_POINTER;
AutoCaller autoCaller (this);
/* generate an UUID if not specified */
return rc;
}
/** @note Locks objects! */
{
if (!aDVDImage)
return E_POINTER;
AutoCaller autoCaller (this);
if (!child)
"this VirtualBox instance"));
/*
* we can safely cast child to DVDImage * here because only DVDImage
* implementations of IDVDImage can be among our children
*/
FALSE /* aOnStartUp */);
}
/** @note Locks objects! */
{
if (!aDVDImage)
return E_POINTER;
AutoCaller autoCaller (this);
/* the below will set *aDVDImage to NULL if dvd is null */
return rc;
}
/** @note Locks objects! */
{
if (!aFilePath)
return E_INVALIDARG;
if (!aDVDImage)
return E_POINTER;
AutoCaller autoCaller (this);
/* get the full file name */
char buf [RTPATH_MAX];
if (VBOX_FAILURE (vrc))
/* the below will set *dvdImage to NULL if dvd is null */
return rc;
}
/** @note Locks objects! */
{
if (!aMachineIDs)
return E_POINTER;
if (aUsage == ResourceUsage_InvalidUsage)
return E_INVALIDARG;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return rc;
return S_OK;
}
/** @note Locks objects! */
{
if (!aDVDImage)
return E_POINTER;
AutoCaller autoCaller (this);
{
/* remove from the collection */
/* save the global config file */
rc = saveSettings();
{
ComAssertComRC (rc);
}
}
else
return rc;
}
/** @note Doesn't lock anything. */
{
/* null and empty strings are not allowed as path names */
return E_INVALIDARG;
if (!aFloppyImage)
return E_POINTER;
AutoCaller autoCaller (this);
/* generate an UUID if not specified */
return rc;
}
/** @note Locks objects! */
{
if (!aFloppyImage)
return E_POINTER;
AutoCaller autoCaller (this);
if (!child)
"this VirtualBox instance"));
/*
* we can safely cast child to FloppyImage * here because only FloppyImage
* implementations of IFloppyImage can be among our children
*/
FALSE /* aOnStartUp */);
}
/** @note Locks objects! */
{
if (!aFloppyImage)
return E_POINTER;
AutoCaller autoCaller (this);
/* the below will set *aFloppyImage to NULL if dvd is null */
return rc;
}
/** @note Locks objects! */
{
if (!aFilePath)
return E_INVALIDARG;
if (!aFloppyImage)
return E_POINTER;
AutoCaller autoCaller (this);
/* get the full file name */
char buf [RTPATH_MAX];
if (VBOX_FAILURE (vrc))
/* the below will set *image to NULL if img is null */
return rc;
}
/** @note Locks objects! */
{
if (!aMachineIDs)
return E_POINTER;
if (aUsage == ResourceUsage_InvalidUsage)
return E_INVALIDARG;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return rc;
return S_OK;
}
/** @note Locks objects! */
{
if (!aFloppyImage)
return E_INVALIDARG;
AutoCaller autoCaller (this);
*aFloppyImage = NULL;
{
/* remove from the collection */
/* save the global config file */
rc = saveSettings();
{
ComAssertComRC (rc);
}
}
else
tr ("A floppy image with UUID {%s} is currently in use"),
return rc;
}
/** @note Locks this object for reading. */
{
if (!aType)
return E_INVALIDARG;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
++ it)
{
{
break;
}
}
tr ("'%ls' is not a valid Guest OS type"),
aId);
}
{
return E_INVALIDARG;
AutoCaller autoCaller (this);
}
{
if (!aName)
return E_INVALIDARG;
AutoCaller autoCaller (this);
}
/**
* @note Locks this object for reading.
*/
{
if (!aNextKey)
return E_POINTER;
AutoCaller autoCaller (this);
/* start with nothing found */
if (aNextValue)
*aNextValue = NULL;
/* serialize config file access */
AutoReaderLock alock (this);
try
{
using namespace settings;
/* load the config file */
if (!extraDataNode.isNull())
{
{
{
/* if we're supposed to return the first one */
{
if (aNextValue)
{
}
return S_OK;
}
/* did we find the key we're looking for? */
{
++ it;
/* is there another item? */
{
if (aNextValue)
{
}
}
/* else it's the last one, arguments are already NULL */
return S_OK;
}
}
}
}
/* Here we are when a) there are no items at all or b) there are items
* but none of them equals to the requested non-NULL key. b) is an
* error as well as a) if the key is non-NULL. When the key is NULL
* (which is the case only when there are no items), we just fall
* through to return NULLs and S_OK. */
}
catch (...)
{
}
return rc;
}
/**
* @note Locks this object for reading.
*/
{
if (!aKey)
return E_INVALIDARG;
if (!aValue)
return E_POINTER;
AutoCaller autoCaller (this);
/* start with nothing found */
/* serialize file access */
AutoReaderLock alock (this);
try
{
using namespace settings;
/* load the config file */
if (!extraDataNode.isNull())
{
/* check if the key exists */
{
{
break;
}
}
}
}
catch (...)
{
}
return rc;
}
/**
* @note Locks this object for writing.
*/
{
if (!aKey)
return E_INVALIDARG;
AutoCaller autoCaller (this);
bool changed = false;
/* serialize file access */
try
{
using namespace settings;
/* load the config file */
{
{
extraDataItemNode = *it;
break;
}
}
/* When no key is found, oldVal is null */
if (changed)
{
/* ask for permission from all listeners */
{
LogWarningFunc (("Someone vetoed! Change refused%s%ls\n",
return setError (E_ACCESSDENIED,
tr ("Could not set extra data because someone refused "
"the requested change of '%ls' to '%ls'%s%ls"),
}
{
if (extraDataItemNode.isNull())
{
}
}
else
{
/* an old value does for sure exist here (XML schema
* guarantees that "value" may not absent in the
* <ExtraDataItem> element) */
}
/* save settings on success */
}
}
catch (...)
{
}
/* fire a notification */
return rc;
}
/**
* @note Locks objects!
*/
{
if (!aSession)
return E_INVALIDARG;
AutoCaller autoCaller (this);
/* check the session state */
if (state != SessionState_SessionClosed)
return setError (E_INVALIDARG,
tr ("The given session is already open or being opened"));
/* get the IInternalSessionControl interface */
{
/*
* tell the client watcher thread to update the set of
* machines that have open sessions
*/
/* fire an event */
}
return rc;
}
/**
* @note Locks objects!
*/
{
return E_INVALIDARG;
if (!aProgress)
return E_POINTER;
AutoCaller autoCaller (this);
/* check the session state */
if (state != SessionState_SessionClosed)
return setError (E_INVALIDARG,
tr ("The given session is already open or being opened"));
/* get the IInternalSessionControl interface */
/* create a progress object */
FALSE /* aCancelable */);
{
/* fire an event */
}
return rc;
}
/**
* @note Locks objects!
*/
{
if (!aSession)
return E_POINTER;
AutoCaller autoCaller (this);
/* check the session state */
if (state != SessionState_SessionClosed)
return setError (E_INVALIDARG,
tr ("The given session is already open or being opened"));
/* get the IInternalSessionControl interface */
return rc;
}
/**
* @note Locks this object for writing.
*/
{
if (!aCallback)
return E_INVALIDARG;
AutoCaller autoCaller (this);
return S_OK;
}
/**
* @note Locks this object for writing.
*/
{
if (!aCallback)
return E_INVALIDARG;
AutoCaller autoCaller (this);
rc = E_INVALIDARG;
else
return rc;
}
{
return E_NOTIMPL;
}
// public methods only for internal purposes
/////////////////////////////////////////////////////////////////////////////
/**
* Posts an event to the event queue that is processed asynchronously
* on a dedicated thread.
*
* Posting events to the dedicated event queue is useful to perform secondary
* actions outside any object locks -- for example, to iterate over a list
* of callbacks and inform them about some change caused by some object's
* method call.
*
* @param event event to post
* (must be allocated using |new|, will be deleted automatically
* by the event thread after processing)
*
* @note Doesn't lock any object.
*/
{
AutoCaller autoCaller (this);
{
LogWarningFunc (("VirtualBox has been uninitialized (state=%d), "
"the event is discarded!\n",
autoCaller.state()));
return S_OK;
}
return S_OK;
return E_FAIL;
}
/**
* Helper method to add a progress to the global collection of pending
* operations.
*
* @param aProgress operation to add to the collection
* @return COM status code
*
* @note Locks this object for writing.
*/
{
if (!aProgress)
return E_INVALIDARG;
AutoCaller autoCaller (this);
return S_OK;
}
/**
* Helper method to remove the progress from the global collection of pending
* operations. Usualy gets called upon progress completion.
*
* @param aId UUID of the progress operation to remove
* @return COM status code
*
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller (this);
++ it)
{
{
return S_OK;
}
}
AssertFailed(); /* should never happen */
return E_FAIL;
}
#ifdef RT_OS_WINDOWS
struct StartSVCHelperClientData
{
bool privileged;
void *user;
};
/**
* Helper method to that starts a worker thread that:
* - creates a pipe communication channel using SVCHlpClient;
* - starts a SVC Helper process that will inherit this channel;
* - executes the supplied function by passing it the created SVCHlpClient
* and opened instance to communicate to the Helper process and the given
* Progress object.
*
* The user function is supposed to communicate to the helper process
* using the \a aClient argument to do the requested job and optionally expose
* the prgress through the \a aProgress object. The user function should never
* call notifyComplete() on it: this will be done automatically using the
* result code returned by the function.
*
* Before the user function is stared, the communication channel passed to in
* the \a aClient argument, is fully set up, the function should start using
* it's write() and read() methods directly.
*
* The \a aVrc parameter of the user function may be used to return an error
* code if it is related to communication errors (for example, returned by
* the SVCHlpClient members when they fail). In this case, the correct error
* message using this value will be reported to the caller. Note that the
* value of \a aVrc is inspected only if the user function itself returns
* a success.
*
* If a failure happens anywhere before the user function would be normally
* called, it will be called anyway in special "cleanup only" mode indicated
* by \a aClient, \a aProgress and \aVrc arguments set to NULL. In this mode,
* all the function is supposed to do is to cleanup its aUser argument if
* necessary (it's assumed that the ownership of this argument is passed to
* the user function once #startSVCHelperClient() returns a success, thus
* making it responsible for the cleanup).
*
* After the user function returns, the thread will send the SVCHlpMsg::Null
* message to indicate a process termination.
*
* @param aPrivileged |true| to start the SVC Hepler process as a privlieged
* user that can perform administrative tasks
* @param aFunc user function to run
* @param aUser argument to the user function
* @param aProgress progress object that will track operation completion
*
* @note aPrivileged is currently ignored (due to some unsolved problems in
* Vista) and the process will be started as a normal (unprivileged)
* process.
*
* @note Doesn't lock anything.
*/
{
AutoCaller autoCaller (this);
/* create the SVCHelperClientThread() argument */
d (new StartSVCHelperClientData());
d->that = this;
d->privileged = aPrivileged;
static_cast <void *> (d.get()),
RTTHREADFLAGS_WAITABLE, "SVCHelper");
E_FAIL);
/* d is now owned by SVCHelperClientThread(), so release it */
d.release();
return S_OK;
}
/**
* Worker thread for startSVCHelperClient().
*/
/* static */
DECLCALLBACK(int)
{
d (static_cast <StartSVCHelperClientData *> (aUser));
bool userFuncCalled = false;
do
{
/* protect VirtualBox from uninitialization */
if (!autoCaller.isOk())
{
/* it's too late */
break;
}
int vrc = VINF_SUCCESS;
if (VBOX_FAILURE (vrc))
{
break;
}
/* get the path to the executable */
char exePathBuf [RTPATH_MAX];
if (d->privileged)
{
/* Attempt to start a privileged process using the Run As dialog */
if (!ShellExecuteEx (&shExecInfo))
{
/* hide excessive details in case of a frequent error
* (pressing the Cancel button to close the Run As dialog) */
if (vrc2 == VERR_CANCELLED)
tr ("Operatiion cancelled by the user"));
else
tr ("Could not launch a privileged process '%s' (%Vrc)"),
break;
}
}
else
{
if (VBOX_FAILURE (vrc))
{
break;
}
}
/* wait for the client to connect */
if (VBOX_SUCCESS (vrc))
{
/* start the user supplied function */
userFuncCalled = true;
}
/* send the termination signal to the process anyway */
{
if (VBOX_SUCCESS (vrc))
}
{
break;
}
}
while (0);
{
/* call the user function in the "cleanup only" mode
* to let it free resources passed to in aUser */
}
return 0;
}
#endif /* RT_OS_WINDOWS */
/**
* Sends a signal to the client watcher thread to rescan the set of machines
* that have open sessions.
*
* @note Doesn't lock anything.
*/
void VirtualBox::updateClientWatcher()
{
AutoCaller autoCaller (this);
/* sent an update request */
#if defined(RT_OS_WINDOWS)
#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
#else
# error "Port me!"
#endif
}
/**
* Adds the given child process ID to the list of processes to be reaped.
* This call should be followed by #updateClientWatcher() to take the effect.
*/
{
AutoCaller autoCaller (this);
/// @todo (dmik) Win32?
#ifndef RT_OS_WINDOWS
#endif
}
/** Event for onMachineStateChange(), onMachineDataChange(), onMachineRegistered() */
{
{}
{}
{}
{
switch (what)
{
case DataChanged:
break;
case StateChanged:
LogFlow (("OnMachineStateChange: id={%Vuuid}, state=%d\n",
break;
case Registered:
LogFlow (("OnMachineRegistered: id={%Vuuid}, registered=%d\n",
break;
}
}
};
/**
* @note Doesn't lock any object.
*/
{
}
/**
* @note Doesn't lock any object.
*/
{
}
/**
* @note Locks this object for reading.
*/
{
LogFlowThisFunc (("machine={%s} aKey={%ls} aValue={%ls}\n",
AutoCaller autoCaller (this);
{
AutoReaderLock alock (this);
}
{
{
/* if a call to this method fails for some reason (for ex., because
* the other side is dead), we ensure allowChange stays true
* (MS COM RPC implementation seems to zero all output vars before
* issuing an IPC call or after a failure, so it's essential
* there) */
allowChange = TRUE;
}
}
return allowChange;
}
/** Event for onExtraDataChange() */
{
{}
{
LogFlow (("OnExtraDataChange: machineId={%Vuuid}, key='%ls', val='%ls'\n",
}
};
/**
* @note Doesn't lock any object.
*/
{
}
/**
* @note Doesn't lock any object.
*/
{
}
/** Event for onSessionStateChange() */
{
{}
{
LogFlow (("OnSessionStateChange: machineId={%Vuuid}, sessionState=%d\n",
}
};
/**
* @note Doesn't lock any object.
*/
{
}
/** Event for onSnapshotTaken(), onSnapshotRemoved() and onSnapshotChange() */
{
: CallbackEvent (aVB)
{}
{
switch (what)
{
case Taken:
LogFlow (("OnSnapshotTaken: machineId={%Vuuid}, snapshotId={%Vuuid}\n",
break;
case Discarded:
LogFlow (("OnSnapshotDiscarded: machineId={%Vuuid}, snapshotId={%Vuuid}\n",
break;
case Changed:
LogFlow (("OnSnapshotChange: machineId={%Vuuid}, snapshotId={%Vuuid}\n",
break;
}
}
};
/**
* @note Doesn't lock any object.
*/
{
}
/**
* @note Doesn't lock any object.
*/
{
}
/**
* @note Doesn't lock any object.
*/
{
}
/**
* @note Locks this object for reading.
*/
{
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
/* unknown type must always be the first */
return type;
}
/**
* Returns the list of opened machines (i.e. machines having direct sessions
* opened by client processes).
*
* @note the returned list contains smart pointers. So, clear it as soon as
* it becomes no more necessary to release instances.
* @note it can be possible that a session machine from the list has been
* already uninitialized, so a) lock the instance and b) chheck for
* instance->isReady() return value before manipulating the object directly
* (i.e. not through COM methods).
*
* @note Locks objects for reading.
*/
{
AutoCaller autoCaller (this);
{
AutoReaderLock alock (this);
++ it)
{
/* SessionMachine is null when there are no open sessions */
}
}
return;
}
/**
* Helper to find machines that use the given DVD image.
*
* This method also checks whether an existing snapshot refers to the given
* image. However, only the machine ID is returned in this case, not IDs of
* individual snapshots.
*
* @param aId Image ID to get usage for.
* @param aUsage Type of the check.
* @param aMachineIDs Where to store the list of machine IDs (can be NULL)
*
* @return @c true if at least one machine or its snapshot found and @c false
* otherwise.
*
* @note For now, we just scan all the machines. We can optimize this later
* if required by adding the corresponding field to DVDImage and requiring all
* IDVDImage instances to be DVDImage objects.
*
* @note Locks objects for reading.
*/
{
AutoCaller autoCaller (this);
{
AutoReaderLock alock (this);
++ mit)
{
/* ignore inaccessible machines */
{
{
/* if not interested in the list, return shortly */
if (aMachineIDs == NULL)
return true;
}
}
}
}
if (aMachineIDs)
{
{
/* convert to a string of UUIDs */
{
/* replace EOS with a space char */
*(idListPtr ++) = ' ';
}
/* remove the trailing space */
*(-- idListPtr) = 0;
/* copy the string */
*aMachineIDs = idList;
}
else
{
(*aMachineIDs).setNull();
}
}
}
/**
* Helper to find machines that use the given Floppy image.
*
* This method also checks whether an existing snapshot refers to the given
* image. However, only the machine ID is returned in this case, not IDs of
* individual snapshots.
*
* @param aId Image ID to get usage for.
* @param aUsage Type of the check.
* @param aMachineIDs Where to store the list of machine IDs (can be NULL)
*
* @return @c true if at least one machine or its snapshot found and @c false
* otherwise.
*
* @note For now, we just scan all the machines. We can optimize this later
* if required by adding the corresponding field to FloppyImage and requiring all
* FloppyImage instances to be FloppyImage objects.
*
* @note Locks objects for reading.
*/
{
AutoCaller autoCaller (this);
{
AutoReaderLock alock (this);
++ mit)
{
/* ignore inaccessible machines */
{
{
/* if not interested in the list, return shortly */
if (aMachineIDs == NULL)
return true;
}
}
}
}
if (aMachineIDs)
{
{
/* convert to a string of UUIDs */
{
/* replace EOS with a space char */
*(idListPtr ++) = ' ';
}
/* remove the trailing space */
*(-- idListPtr) = 0;
/* copy the string */
*aMachineIDs = idList;
}
else
{
(*aMachineIDs).setNull();
}
}
}
/**
* Tries to calculate the relative path of the given absolute path using the
* directory of the VirtualBox settings file as the base directory.
*
* @param aPath absolute path to calculate the relative path for
* @param aResult where to put the result (used only when it's possible to
* make a relative path from the given absolute path;
* otherwise left untouched)
*
* @note Doesn't lock any object.
*/
{
AutoCaller autoCaller (this);
/* no need to lock since mHomeDir is const */
{
/* when assigning, we create a separate Utf8Str instance because both
* aPath and aResult can point to the same memory location when this
* func is called (if we just do aResult = aPath, aResult will be freed
* first, and since its the same as aPath, an attempt to copy garbage
* will be made. */
}
}
// private methods
/////////////////////////////////////////////////////////////////////////////
/**
* Searches for a Machine object with the given ID in the collection
* of registered machines.
*
* @param id
* ID of the machine
* @param doSetError
* if TRUE, the appropriate error info is set in case when the machine
* is not found
* @param machine
* where to store the found machine object (can be NULL)
*
* @return
* S_OK when found or E_INVALIDARG when not found
*
* @note Locks this object for reading.
*/
{
AutoCaller autoCaller (this);
bool found = false;
{
AutoReaderLock alock (this);
++ it)
{
/* sanity */
}
}
{
tr ("Could not find a registered machine with UUID {%Vuuid}"),
}
return rc;
}
/**
* Searches for a HardDisk object with the given ID or location specification
* in the collection of registered hard disks. If both ID and location are
* specified, the first object that matches either of them (not necessarily
* both) is returned.
*
* @param aId ID of the hard disk (NULL when unused)
* @param aLocation full location specification (NULL when unused)
* @param aSetError if TRUE, the appropriate error info is set in case when
* the disk is not found and only one search criteria (ID
* or file name) is specified.
* @param aHardDisk where to store the found hard disk object (can be NULL)
*
* @return
* S_OK when found or E_INVALIDARG when not found
*
* @note Locks objects for reading!
*/
{
AutoReaderLock alock (this);
/* first lookup the map by UUID if UUID is provided */
if (aId)
{
{
if (aHardDisk)
return S_OK;
}
}
/* then iterate and find by location */
bool found = false;
if (aLocation)
{
++ it)
{
{
/* locations of VDI and VMDK hard disks for now are just
* file paths */
(false /* aShort */))) == 0;
}
else
{
}
}
}
{
"with location '%ls'"), aLocation);
}
return rc;
}
/**
* @deprecated Use #findHardDisk() instead.
*
* Searches for a HVirtualDiskImage object with the given ID or file path in the
* collection of registered hard disks. If both ID and file path are specified,
* the first object that matches either of them (not necessarily both)
* is returned.
*
* @param aId ID of the hard disk (NULL when unused)
* @param filePathFull full path to the image file (NULL when unused)
* @param aSetError if TRUE, the appropriate error info is set in case when
* the disk is not found and only one search criteria (ID
* or file name) is specified.
* @param aHardDisk where to store the found hard disk object (can be NULL)
*
* @return
* S_OK when found or E_INVALIDARG when not found
*
* @note Locks objects for reading!
*/
{
AutoReaderLock alock (this);
/* first lookup the map by UUID if UUID is provided */
if (aId)
{
{
{
if (aImage)
return S_OK;
}
}
}
/* then iterate and find by name */
bool found = false;
if (aFilePathFull)
{
++ it)
{
continue;
}
}
{
if (aId && !aFilePathFull)
else if (aFilePathFull && !aId)
"with the file path '%ls'"), aFilePathFull);
}
return rc;
}
/**
* Searches for a DVDImage object with the given ID or file path in the
* collection of registered DVD images. If both ID and file path are specified,
* the first object that matches either of them (not necessarily both)
* is returned.
*
* @param aId
* ID of the DVD image (unused when NULL)
* @param aFilePathFull
* full path to the image file (unused when NULL)
* @param aSetError
* if TRUE, the appropriate error info is set in case when the image is not
* found and only one search criteria (ID or file name) is specified.
* @param aImage
* where to store the found DVD image object (can be NULL)
*
* @return
* S_OK when found or E_INVALIDARG when not found
*
* @note Locks this object for reading.
*/
bool aSetError,
{
bool found = false;
{
AutoReaderLock alock (this);
++ it)
{
/* DVDImage fields are constant, so no need to lock */
(aFilePathFull &&
}
}
{
if (aId && !aFilePathFull)
else if (aFilePathFull && !aId)
"with the file path '%ls'"), aFilePathFull);
}
return rc;
}
/**
* Searches for a FloppyImage object with the given ID or file path in the
* collection of registered floppy images. If both ID and file path are specified,
* the first object that matches either of them (not necessarily both)
* is returned.
*
* @param aId
* ID of the floppy image (unused when NULL)
* @param aFilePathFull
* full path to the image file (unused when NULL)
* @param aSetError
* if TRUE, the appropriate error info is set in case when the image is not
* found and only one search criteria (ID or file name) is specified.
* @param aImage
* where to store the found floppy image object (can be NULL)
*
* @return
* S_OK when found or E_INVALIDARG when not found
*
* @note Locks this object for reading.
*/
bool aSetError,
{
bool found = false;
{
AutoReaderLock alock (this);
++ it)
{
/* FloppyImage fields are constant, so no need to lock */
(aFilePathFull &&
}
}
{
if (aId && !aFilePathFull)
else if (aFilePathFull && !aId)
"with the file path '%ls'"), aFilePathFull);
}
return rc;
}
/**
* When \a aHardDisk is not NULL, searches for an object equal to the given
* hard disk in the collection of registered hard disks, or, if the given hard
* disk is HVirtualDiskImage, for an object with the given file path in the
* collection of all registered non-hard disk images (DVDs and floppies).
* Other parameters are unused.
*
* When \a aHardDisk is NULL, searches for an object with the given ID or file
* path in the collection of all registered images (VDIs, DVDs and floppies).
* If both ID and file path are specified, matching either of them will satisfy
* the search.
*
* If a matching object is found, this method returns E_INVALIDARG and sets the
* appropriate error info. Otherwise, S_OK is returned.
*
* @param aHardDisk hard disk object to check against registered media
* (NULL when unused)
* @param aId UUID of the media to check (NULL when unused)
* @param aFilePathFull full path to the image file (NULL when unused)
*
* @note Locks objects!
*/
const BSTR aFilePathFull)
{
AutoReaderLock alock (this);
if (aHardDisk)
{
++ it)
{
return setError (E_INVALIDARG,
tr ("A hard disk with UUID {%Vuuid} or with the same properties "
"('%ls') is already registered"),
}
#if !defined (VBOX_WITH_XPCOM)
#if defined(RT_OS_WINDOWS)
/// @todo (dmik) stupid BSTR declaration lacks the BCSTR counterpart
#endif
#else
#endif
}
bool found = false;
if (aId || aFilePathFull) do
{
if (!aHardDisk)
{
if (found)
break;
}
if (found)
break;
if (found)
break;
}
while (0);
if (found)
{
if (aId && !aFilePathFull)
tr ("A disk image with UUID {%Vuuid} is already registered"),
else if (aFilePathFull && !aId)
tr ("A disk image with file path '%ls' is already registered"),
else
tr ("A disk image with UUID {%Vuuid} or file path '%ls' "
}
else
return rc;
}
/**
* Reads in the machine definitions from the configuration loader
* and creates the relevant objects.
*
* @param aGlobal <Global> node.
*
* @note Can be called only from #init().
* @note Doesn't lock anything.
*/
{
using namespace settings;
AutoCaller autoCaller (this);
{
/* required */
/* required */
/* create a new machine object */
{
/* initialize the machine object and register it */
}
}
return rc;
}
/**
* Reads in the disk registration entries from the global settings file
* and creates the relevant objects
*
* @param aGlobal <Global> node
*
* @note Can be called only from #init().
* @note Doesn't lock anything.
*/
{
using namespace settings;
AutoCaller autoCaller (this);
{
/* All three media nodes are optional */
continue;
if (n == 0)
{
/* HardDisks node */
continue;
}
{
/* required */
/* required */
switch (n)
{
case 1: /* DVDImages */
{
break;
}
case 2: /* FloppyImages */
{
break;
}
default:
AssertFailed();
}
}
}
return rc;
}
/**
* Loads all hard disks from the given <HardDisks> node.
* Note that all loaded hard disks register themselves within this VirtualBox.
*
* @param aNode <HardDisks> node.
*
* @note Can be called only from #init().
* @note Doesn't lock anything.
*/
{
using namespace settings;
AutoCaller autoCaller (this);
{
/* detect the type of the hard disk (either one of VirtualDiskImage,
* ISCSIHardDisk, VMDKImage or HCustomHardDisk) */
do
{
if (!storageNode.isNull())
{
vdi.createObject();
break;
}
if (!storageNode.isNull())
{
break;
}
if (!storageNode.isNull())
{
vmdk.createObject();
break;
}
if (!storageNode.isNull())
{
break;
}
if (!storageNode.isNull())
{
vhd.createObject();
break;
}
ComAssertMsgFailedBreak (("No valid hard disk storage node!\n"),
}
while (0);
}
return rc;
}
/**
* Helper function to write out the configuration tree.
*
* @note Locks objects for reading!
*/
{
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
try
{
using namespace settings;
/* machines */
{
/* first, delete the entire machine registry */
if (!registryNode.isNull())
registryNode.zap();
/* then, recreate it */
/* write out the machines */
++ it)
{
}
}
/* disk images */
{
/* first, delete the entire disk image registr */
if (!registryNode.isNull())
registryNode.zap();
/* then, recreate it */
/* write out the hard disks */
{
}
{
++ it)
{
/* no need to lock: fields are constant */
}
}
/* write out the floppy images */
{
++ it)
{
/* no need to lock: fields are constant */
}
}
}
/* host data (USB filters) */
/* save the settings on success */
}
{
/* we assume that error info is set by the thrower */
}
catch (...)
{
}
return rc;
}
/**
* Saves all hard disks to the given <HardDisks> node.
*
* @param aNode <HardDisks> node.
*
* @note Locks this object for reding.
*/
{
using namespace settings;
AutoReaderLock alock (this);
++ it)
{
switch (hd->storageType())
{
{
break;
}
{
break;
}
{
break;
}
{
break;
}
{
break;
}
}
}
return rc;
}
/**
* Helper to register the machine.
*
* When called during VirtualBox startup, adds the given machine to the
* collection of registered machines. Otherwise tries to mark the machine
* as registered, and, if succeeded, adds it to the collection and
* saves global settings.
*
* @note The caller must have added itself as a caller of the @a aMachine
* object if calls this method not on VirtualBox startup.
*
* @param aMachine machine to register
*
* @note Locks objects!
*/
{
AutoCaller autoCaller (this);
{
{
/* sanity */
return setError (E_INVALIDARG,
tr ("Registered machine with UUID {%Vuuid} ('%ls') already exists"),
}
}
{
/* Machine::trySetRegistered() will commit and save machine settings */
}
/* add to the collection of registered machines */
rc = saveSettings();
return rc;
}
/**
* Helper to register the hard disk.
*
* @param aHardDisk object to register
* @param aFlags one of RHD_* values
*
* @note Locks objects!
*/
{
AutoCaller autoCaller (this);
/* mark the hard disk as registered only when registration is external */
if (aFlags == RHD_External)
{
}
{
/* add to the collection of top-level images */
}
/* insert to the map of hard disks */
/* save global config file if not on startup */
/// @todo (dmik) optimize later to save only the <HardDisks> node
if (aFlags != RHD_OnStartUp)
rc = saveSettings();
return rc;
}
/**
* Helper to unregister the hard disk.
*
* If the hard disk is a differencing hard disk and if the unregistration
* succeeds, the hard disk image is deleted and the object is uninitialized.
*
* @param aHardDisk hard disk to unregister
*
* @note Locks objects!
*/
{
AutoCaller autoCaller (this);
/* Lock the hard disk to ensure nobody registers it again before we delete
* the differencing image (sanity check actually -- should never happen). */
/* try to unregister */
/* remove from the map of hard disks */
{
/* non-differencing hard disk:
* remove from the collection of top-level hard disks */
}
else
{
/* differencing hard disk: delete and uninitialize
*
* Note that we ignore errors because this operation may be a result
* of unregistering a missing (inaccessible) differencing hard disk
* in which case a failure to implicitly delete the image will not
* prevent it from being unregistered and therefore should not pop up
* on the caller's side. */
}
/* save the global config file anyway (already unregistered) */
/// @todo (dmik) optimize later to save only the <HardDisks> node
return rc;
}
/**
* Helper to unregister the differencing hard disk image.
* Resets machine ID of the hard disk (to let the unregistration succeed)
* and then calls #unregisterHardDisk().
*
* @param aHardDisk differencing hard disk image to unregister
*
* @note Locks objects!
*/
{
AutoCaller autoCaller (this);
/*
* Note: it's safe to lock aHardDisk here because the same object
* will be locked by #unregisterHardDisk().
*/
/*
* deassociate the machine from the hard disk
* (otherwise trySetRegistered() will definitely fail)
*/
return unregisterHardDisk (aHardDisk);
}
/**
* Helper to update the global settings file when the name of some machine
* changes so that file and directory renaming occurs. This method ensures
* that all affected paths in the disk registry are properly updated.
*
* @param aOldPath old path (full)
* @param aNewPath new path (full)
*
* @note Locks this object + DVD, Floppy and HardDisk children for writing.
*/
{
AutoCaller autoCaller (this);
/* check DVD paths */
++ it)
{
/* no need to lock: fields are constant */
{
LogFlowThisFunc (("-> updated: full={%s} rel={%s}\n",
}
}
/* check Floppy paths */
++ it)
{
/* no need to lock: fields are constant */
{
LogFlowThisFunc (("-> updated: full={%s} rel={%s}\n",
}
}
/* check HardDisk paths */
++ it)
{
}
return rc;
}
/**
* Helper method to load the setting tree and turn expected exceptions into
* COM errors, according to arguments.
*
* Note that this method will not catch unexpected errors so it may still
* throw something.
*
* @param aTree Tree to load into settings.
* @param aFile File to load settings from.
* @param aValidate @c @true to enable tree validation.
* @param aCatchLoadErrors @c true to catch exceptions caused by file
* access or validation errors.
* @param aAddDefaults @c true to cause the substitution of default
* values for for missing attributes that have
* defaults in the XML schema.
*/
/* static */
bool aValidate,
bool aCatchLoadErrors,
bool aAddDefaults)
{
using namespace settings;
try
{
}
catch (const EIPRTFailure &err)
{
if (!aCatchLoadErrors)
throw;
tr ("Could not load the settings file '%s' (%Vrc)"),
}
{
if (!aCatchLoadErrors)
throw;
tr ("Could not load the settings file '%s'.\n%s"),
}
return S_OK;
}
/**
* Helper method to save the settings tree and turn expected exceptions to COM
* errors.
*
* Note that this method will not catch unexpected errors so it may still
* throw something.
*
* @param aTree Tree to save.
* @param aFile File to save the tree to.
*/
/* static */
{
using namespace settings;
try
{
}
catch (const EIPRTFailure &err)
{
/* this is the only expected exception for now */
tr ("Could not save the settings file '%s' (%Vrc)"),
}
return S_OK;
}
/**
* Handles unexpected exceptions by turning them into COM errors in release
* builds or by hitting a breakpoint in the release builds.
*
* Usage pattern:
* @code
try
{
// ...
}
catch (LaLalA)
{
// ...
}
catch (...)
{
rc = VirtualBox::handleUnexpectedExceptions (RT_SRC_POS);
}
* @endcode
*
* @param RT_SRC_POS_DECL "RT_SRC_POS" macro instantiation.
*/
/* static */
{
try
{
/* rethrow the current exception */
throw;
}
{
ComAssertMsgFailedPos (("Unexpected exception '%s' (%s)\n",
return E_FAIL;
}
catch (...)
{
ComAssertMsgFailedPos (("Unknown exception\n"),
return E_FAIL;
}
/* should not get here */
AssertFailed();
return E_FAIL;
}
/**
* Helper to register the DVD image.
*
* @param aImage object to register
* @param aOnStartUp whether this method called during VirtualBox init or not
*
* @return COM status code
*
* @note Locks objects!
*/
{
AutoCaller autoCaller (this);
aImage->filePathFull());
/* add to the collection */
/* save global config file if we're supposed to */
if (!aOnStartUp)
rc = saveSettings();
return rc;
}
/**
* Helper to register the floppy image.
*
* @param aImage object to register
* @param aOnStartUp whether this method called during VirtualBox init or not
*
* @return COM status code
*
* @note Locks objects!
*/
{
AutoCaller autoCaller (this);
aImage->filePathFull());
/* add to the collection */
/* save global config file if we're supposed to */
if (!aOnStartUp)
rc = saveSettings();
return rc;
}
/**
* Helper function to create the guest OS type objects and our collection
*
* @returns COM status code
*/
{
AutoCaller autoCaller (this);
// this table represents our os type / string mapping
static struct
{
const char *id; // utf-8
const char *description; // utf-8
const uint32_t recommendedRAM;
const uint32_t recommendedVRAM;
const uint32_t recommendedHDD;
} OSTypes[] =
{
/// @todo (dmik) get the list of OS types from the XML schema
/* NOTE1: we assume that unknown is always the first entry!
* NOTE2: please use powers of 2 when specifying the size of harddisks since
* '2GB' looks better than '1.95GB' (= 2000MB) */
};
{
{
OSTypes[i].description,
OSTypes[i].recommendedHDD);
}
}
return rc;
}
/**
* Helper to lock the VirtualBox configuration for write access.
*
* @note This method is not thread safe (must be called only from #init()
* or #uninit()).
*
* @note If the configuration file is not found, the method returns
* S_OK, but subsequent #isConfigLocked() will return FALSE. This is used
* in some places to determine the (valid) situation when no config file
* exists yet, and therefore a new one should be created from scatch.
*/
{
AutoCaller autoCaller (this);
Assert (!isConfigLocked());
if (!isConfigLocked())
{
/* open the associated config file */
if (VBOX_FAILURE (vrc))
{
/*
* It is ok if the file is not found, it will be created by
* init(). Otherwise return an error.
*/
if (vrc != VERR_FILE_NOT_FOUND)
tr ("Could not lock the settings file '%ls' (%Vrc)"),
}
LogFlowThisFunc (("mCfgFile.mName='%ls', mCfgFile.mHandle=%d, rc=%08X\n",
}
return rc;
}
/**
* Helper to unlock the VirtualBox configuration from write access.
*
* @note This method is not thread safe (must be called only from #init()
* or #uninit()).
*/
{
AutoCaller autoCaller (this);
if (isConfigLocked())
{
/** @todo flush the directory too. */
LogFlowThisFunc (("\n"));
}
return rc;
}
/**
* Thread function that watches the termination of all client processes
* that have opened sessions using IVirtualBox::OpenSession()
*/
// static
{
#if defined(RT_OS_WINDOWS)
AssertComRC (hrc);
/// @todo (dmik) processes reaping!
do
{
/* VirtualBox has been early uninitialized, terminate */
if (!autoCaller.isOk())
break;
do
{
/* release the caller to let uninit() ever proceed */
/*
* Restore the caller before using VirtualBox. If it fails, this
* means VirtualBox is being uninitialized and we must terminate.
*/
autoCaller.add();
if (!autoCaller.isOk())
break;
bool update = false;
if (rc == WAIT_OBJECT_0)
{
/* update event is signaled */
update = true;
}
{
/* machine mutex is released */
update = true;
}
{
/* machine mutex is abandoned due to client process termination */
update = true;
}
if (update)
{
/* obtain a new set of opened machines */
("MAXIMUM_WAIT_OBJECTS reached"));
/* renew the set of event handles */
delete [] handles;
}
}
while (true);
}
while (0);
/* delete the set of event handles */
delete [] handles;
/* delete the set of opened machines if any */
::CoUninitialize();
/// @todo (dmik) processes reaping!
/* according to PMREF, 64 is the maximum for the muxwait list */
do
{
/* VirtualBox has been early uninitialized, terminate */
if (!autoCaller.isOk())
break;
do
{
/* release the caller to let uninit() ever proceed */
/*
* Restore the caller before using VirtualBox. If it fails, this
* means VirtualBox is being uninitialized and we must terminate.
*/
autoCaller.add();
if (!autoCaller.isOk())
break;
bool update = false;
if (VBOX_SUCCESS (vrc))
{
/* update event is signaled */
update = true;
}
else
{
("RTSemEventWait returned %Vrc\n", vrc));
/* are there any mutexes? */
if (cnt > 0)
{
/* figure out what's going on with machines */
unsigned long semId = 0;
{
/* machine mutex is normally released */
{
#ifdef DEBUG
{
LogFlowFunc (("released mutex: machine='%ls'\n",
}
#endif
}
update = true;
}
else if (arc == ERROR_SEM_OWNER_DIED)
{
/* machine mutex is abandoned due to client process
* termination; find which mutex is in the Owner Died
* state */
{
unsigned long reqCnt;
if (arc == ERROR_SEM_OWNER_DIED)
{
/* close the dead mutex as asked by PMREF */
if (i >= 0 && i < cnt)
{
#ifdef DEBUG
{
LogFlowFunc (("mutex owner dead: machine='%ls'\n",
}
#endif
machines [i]->checkForDeath();
}
}
}
update = true;
}
else
("DosWaitMuxWaitSem returned %d\n", arc));
}
}
if (update)
{
/* close the old muxsem */
if (muxSem != NULLHANDLE)
::DosCloseMuxWaitSem (muxSem);
/* obtain a new set of opened machines */
/// @todo use several muxwait sems if cnt is > 64
("maximum of 64 mutex semaphores reached (%d)", cnt));
if (cnt > 64)
cnt = 64;
if (cnt > 0)
{
/* renew the set of event handles */
{
}
/* create a new muxsem */
}
}
}
while (true);
}
while (0);
/* close the muxsem */
if (muxSem != NULLHANDLE)
::DosCloseMuxWaitSem (muxSem);
/* delete the set of opened machines if any */
#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
bool need_update = false;
do
{
if (!autoCaller.isOk())
break;
do
{
/* release the caller to let uninit() ever proceed */
/*
* Restore the caller before using VirtualBox. If it fails, this
* means VirtualBox is being uninitialized and we must terminate.
*/
autoCaller.add();
if (!autoCaller.isOk())
break;
{
/* VBOX_SUCCESS (rc) means an update event is signaled */
/* obtain a new set of opened machines */
}
need_update = false;
/* reap child processes */
{
{
LogFlowFunc (("UPDATE: child process count = %d\n",
{
&status);
if (vrc == VINF_SUCCESS)
{
LogFlowFunc (("pid %d (%x) was reaped, "
"status=%d, reason=%d\n",
}
else
{
LogFlowFunc (("pid %d (%x) was NOT reaped, vrc=%Vrc\n",
if (vrc != VERR_PROCESS_RUNNING)
{
/* remove the process if it is not already running */
}
else
++ it;
}
}
}
}
}
while (true);
}
while (0);
/* delete the set of opened machines if any */
#else
# error "Port me!"
#endif
return 0;
}
/**
* Thread function that handles custom events posted using #postEvent().
*/
// static
{
// create an event queue for the current thread
// return the queue to the one who created this thread
// signal that we're ready
delete eventQ;
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/**
* Takes the current list of registered callbacks of the managed VirtualBox
* instance, and calls #handleCallback() for every callback item from the
* list, passing the item as an argument.
*
* @note Locks the managed VirtualBox object for reading but leaves the lock
* before iterating over callbacks and calling their methods.
*/
{
if (mVirtualBox.isNull())
return NULL;
if (!autoCaller.isOk())
{
LogWarningFunc (("VirtualBox has been uninitialized (state=%d), "
"the callback event is discarded!\n",
autoCaller.state()));
/* We don't need mVirtualBox any more, so release it */
return NULL;
}
{
/* Make a copy to release the lock before iterating */
/* We don't need mVirtualBox any more, so release it */
}
handleCallback (*it);
return NULL;
}