VirtualBoxImpl.cpp revision 5bd02c5476517b19d6c04fcb0ab0d2df67f7c2e3
/* $Id$ */
/** @file
* Implementation of IVirtualBox in VBoxSVC.
*/
/*
* Copyright (C) 2006-2009 Sun Microsystems, Inc.
*
* 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.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 USA or visit http://www.sun.com if you need
* additional information or have any questions.
*/
#include <iprt/cpputils.h>
#include <VBox/settings.h>
#include <package-generated.h>
#include <algorithm>
#include <set>
#include <memory> // for auto_ptr
#include <typeinfo>
#include "VirtualBoxImpl.h"
#include "VirtualBoxImplExtra.h"
#include "Global.h"
#include "MachineImpl.h"
#include "HardDiskImpl.h"
#include "MediumImpl.h"
#include "SharedFolderImpl.h"
#include "ProgressImpl.h"
#include "HostImpl.h"
#include "USBControllerImpl.h"
#include "SystemPropertiesImpl.h"
#include "GuestOSTypeImpl.h"
#include "Version.h"
#include "DHCPServerRunner.h"
#include "DHCPServerImpl.h"
#include "VirtualBoxXMLUtil.h"
#include "Logging.h"
#ifdef RT_OS_WINDOWS
#endif
// #include <stdio.h>
// #include <stdlib.h>
// defines
/////////////////////////////////////////////////////////////////////////////
#define VBOX_GLOBAL_SETTINGS_FILE "VirtualBox.xml"
// globals
/////////////////////////////////////////////////////////////////////////////
static const char gDefaultGlobalConfig [] =
{
"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" RTFILE_LINEFEED
"<!-- Sun VirtualBox Global Configuration -->" RTFILE_LINEFEED
" <Global>"RTFILE_LINEFEED
" <MachineRegistry/>"RTFILE_LINEFEED
" <MediaRegistry/>"RTFILE_LINEFEED
" <NetserviceRegistry>"RTFILE_LINEFEED
" <DHCPServers>"RTFILE_LINEFEED
" <DHCPServer "
#ifdef RT_OS_WINDOWS
"networkName=\"HostInterfaceNetworking-VirtualBox Host-Only Ethernet Adapter\" "
#else
"networkName=\"HostInterfaceNetworking-vboxnet0\" "
#endif
"IPAddress=\"192.168.56.100\" networkMask=\"255.255.255.0\" "
"lowerIP=\"192.168.56.101\" upperIP=\"192.168.56.254\" "
"enabled=\"1\"/>"RTFILE_LINEFEED
" </DHCPServers>"RTFILE_LINEFEED
" </NetserviceRegistry>"RTFILE_LINEFEED
" <USBDeviceFilters/>"RTFILE_LINEFEED
" <SystemProperties/>"RTFILE_LINEFEED
" </Global>"RTFILE_LINEFEED
"</VirtualBox>"RTFILE_LINEFEED
};
// static
// static
// static
// 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"));
sRevision = VBoxSVNRev();
if (sPackageType.isNull())
if (sSettingsFormatVersion.isNull())
LogFlowThisFunc (("Settings Format Version: %ls\n",
/* Get the VirtualBox home directory. */
{
char homeDir [RTPATH_MAX];
if (RT_FAILURE (vrc))
tr ("Could not create the VirtualBox home directory '%s'"
"(%Rrc)"),
}
/* 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 (RT_SUCCESS (vrc))
(void *) gDefaultGlobalConfig,
if (RT_FAILURE (vrc))
{
"'%s' (%Rrc)"),
}
else
{
/* we do not close the file to simulate lockConfig() */
}
}
}
{
try
{
using namespace settings;
using namespace xml;
/* no concurrent file access is possible in init() so open by handle */
#ifdef VBOX_WITH_RESOURCE_USAGE_API
/* create the performance collector object BEFORE host */
#endif /* VBOX_WITH_RESOURCE_USAGE_API */
/* create the host object early, machines will need it */
/* create the system properties object, someone may need it too */
/* guest OS type objects, needed by machines */
{
{
}
}
/* all registered media, needed by machines */
/* machines */
/* net services */
/* 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 (RT_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 */
{
}
/* Uninit all other children still referenced by clients (unregistered
* operations). */
/* Note that we release singleton children after we've all other children.
* In some cases this is important because these other children may use
* some resources of the singletons which would prevent them from
* uninitializing (as for example, mSystemProperties which owns
* HardDiskFormat objects which HardDisk objects refer to) */
if (mData.mSystemProperties)
{
}
{
}
#ifdef VBOX_WITH_RESOURCE_USAGE_API
{
}
#endif /* VBOX_WITH_RESOURCE_USAGE_API */
/* 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 (RT_FAILURE (vrc))
LogWarningFunc (("RTThreadWait(%RTthrd) -> %Rrc\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
/* Unload hard disk plugin backends. */
VDShutdown();
LogFlow (("===========================================================\n"));
}
// IVirtualBox properties
/////////////////////////////////////////////////////////////////////////////
{
AutoCaller autoCaller (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
/* mHomeDir is const and doesn't need a lock */
return S_OK;
}
{
AutoCaller autoCaller (this);
/* mCfgFile.mName is const and doesn't need a lock */
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
/* mHost is const, no need to lock */
return S_OK;
}
{
AutoCaller autoCaller (this);
/* mSystemProperties is const, no need to lock */
return S_OK;
}
{
if (ComSafeArrayOutIsNull (aMachines))
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
if (ComSafeArrayOutIsNull (aHardDisks))
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
if (ComSafeArrayOutIsNull (aDVDImages))
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
/* protect mProgressOperations */
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
#ifndef RT_OS_WINDOWS
#endif /* RT_OS_WINDOWS */
AutoCaller autoCaller (this);
}
{
#ifdef VBOX_WITH_RESOURCE_USAGE_API
AutoCaller autoCaller (this);
/* mPerformanceCollector is const, no need to lock */
return S_OK;
#else /* !VBOX_WITH_RESOURCE_USAGE_API */
#endif /* !VBOX_WITH_RESOURCE_USAGE_API */
}
{
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
// IVirtualBox methods
/////////////////////////////////////////////////////////////////////////////
/** @note Locks mSystemProperties object for reading. */
{
LogFlowThisFunc (("aName=\"%ls\",aOsTypeId =\"%ls\",aBaseFolder=\"%ls\"\n", aName, aOsTypeId, aBaseFolder));
/** @todo tighten checks on aId? */
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. */
/* Look for a GuestOSType object */
("Guest OS types array must be filled"));
{
{
{
break;
}
}
return setError (VBOX_E_OBJECT_NOT_FOUND,
}
/* initialize the machine object */
{
/* set the return value */
AssertComRC (rc);
}
return rc;
}
{
/** @todo tighten checks on aId? */
AutoCaller autoCaller (this);
/* append the default extension if none */
if (!RTPathHaveExt (settingsFile))
/* create a new object */
/* Create UUID if an empty one was specified. */
/* Look for a GuestOSType object */
("Guest OS types array must be filled"));
{
{
{
break;
}
}
return setError (VBOX_E_OBJECT_NOT_FOUND,
}
/* initialize the machine object */
{
/* set the return value */
AssertComRC (rc);
}
return rc;
}
{
AutoCaller autoCaller (this);
/* create a new object */
{
/* initialize the machine object */
{
/* set the return value */
ComAssertComRC (rc);
}
}
return rc;
}
/** @note Locks objects! */
{
AutoCaller autoCaller (this);
/* We need the children map lock here to keep the getDependentChild() result
* valid until we finish */
/* We can safely cast child to Machine * here because only Machine
* implementations of IMachine can be among our children. */
{
/* this machine was not created by CreateMachine() or opened by
* OpenMachine() or loaded during startup */
return setError (VBOX_E_INVALID_OBJECT_STATE,
tr ("The machine named '%ls' is not created within this "
}
/* fire an event */
return rc;
}
/** @note Locks objects! */
{
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. */
{
AutoCaller autoCaller (this);
/* start with not found */
{
/* take a copy for safe iteration outside the lock */
AutoReadLock alock (this);
}
++ it)
{
/* skip inaccessible machines */
{
}
}
/* this will set (*machine) to NULL if machineObj is null */
? S_OK
return rc;
}
/** @note Locks objects! */
{
return E_INVALIDARG;
AutoCaller autoCaller (this);
AutoWriteLock alock (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;
}
{
AutoCaller autoCaller (this);
/* we don't access non-const data members so no need to lock */
{
}
return rc;
}
{
AutoCaller autoCaller (this);
/* we don't access non-const data members so no need to lock */
if (aSetImageId)
{
}
if (aSetParentId)
{
/* Note that it's important to call uninit() on failure to register
* because the differencing hard disk would have been already associated
* with the parent and this association needs to be broken. */
else
}
return rc;
}
{
AutoCaller autoCaller (this);
/* the below will set *aHardDisk to NULL if hardDisk is null */
return rc;
}
{
AutoCaller autoCaller (this);
/* the below will set *aHardDisk to NULL if hardDisk is null */
return rc;
}
/** @note Doesn't lock anything. */
{
AutoCaller autoCaller (this);
/* generate an UUID if not specified */
{
}
return rc;
}
/** @note Locks objects! */
{
AutoCaller autoCaller (this);
/* the below will set *aDVDImage to NULL if image is null */
return rc;
}
/** @note Locks objects! */
{
AutoCaller autoCaller (this);
/* the below will set *aDVDImage to NULL if dvd is null */
return rc;
}
/** @note Doesn't lock anything. */
{
AutoCaller autoCaller (this);
/* generate an UUID if not specified */
{
}
return rc;
}
/** @note Locks objects! */
{
AutoCaller autoCaller (this);
/* the below will set *aFloppyImage to NULL if image is null */
return rc;
}
/** @note Locks objects! */
{
AutoCaller autoCaller (this);
/* the below will set *aFloppyImage to NULL if img is null */
return rc;
}
/** @note Locks this object for reading. */
{
/* Old ID to new ID conversion table. See r39691 for a source */
static const wchar_t *kOldNewIDs[] =
{
L"unknown", L"Other",
L"win31", L"Windows31",
L"win95", L"Windows95",
L"win98", L"Windows98",
L"winme", L"WindowsMe",
L"winnt4", L"WindowsNT4",
L"win2k", L"Windows2000",
L"winxp", L"WindowsXP",
L"win2k3", L"Windows2003",
L"winvista", L"WindowsVista",
L"win2k8", L"Windows2008",
L"ecs", L"OS2eCS",
L"fedoracore", L"Fedora",
/* the rest is covered by the case-insensitive comparison */
};
AutoCaller autoCaller (this);
/* first, look for a substitution */
{
if (id == kOldNewIDs [i])
{
break;
}
}
AutoReadLock alock (this);
++ it)
{
{
break;
}
}
tr ("'%ls' is not a valid Guest OS type"),
aId);
}
{
AutoCaller autoCaller (this);
}
{
AutoCaller autoCaller (this);
}
/**
* @note Locks this object for reading.
*/
{
AutoCaller autoCaller (this);
/* start with nothing found */
if (aNextValue)
/* serialize file access (prevent writes) */
AutoReadLock alock (this);
try
{
using namespace settings;
using namespace xml;
/* load the settings file (we don't reuse the existing handle but
* request a new one to allow for concurrent multi-threaded reads) */
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. */
return setError (VBOX_E_OBJECT_NOT_FOUND,
}
catch (...)
{
}
return rc;
}
/**
* @note Locks this object for reading.
*/
{
AutoCaller autoCaller (this);
/* start with nothing found */
/* serialize file access (prevent writes) */
AutoReadLock alock (this);
try
{
using namespace settings;
using namespace xml;
/* load the settings file (we don't reuse the existing handle but
* request a new one to allow for concurrent multi-threaded reads) */
if (!extraDataNode.isNull())
{
/* check if the key exists */
{
{
break;
}
}
}
}
catch (...)
{
}
return rc;
}
/**
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller (this);
if (!aValue)
else
bool changed = false;
/* serialize file access (prevent concurrent reads and writes) */
AutoWriteLock alock (this);
try
{
using namespace settings;
using namespace xml;
/* load the settings file */
{
{
extraDataItemNode = *it;
break;
}
}
/* When no key is found, oldVal is empty string */
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 be absent in the
* <ExtraDataItem> element). */
}
/* save settings on success */
}
}
catch (...)
{
}
/* fire a notification */
return rc;
}
/**
* @note Locks objects!
*/
{
AutoCaller autoCaller (this);
/* check the session state */
if (state != SessionState_Closed)
return setError (VBOX_E_INVALID_OBJECT_STATE,
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!
*/
{
AutoCaller autoCaller (this);
/* check the session state */
if (state != SessionState_Closed)
return setError (VBOX_E_INVALID_OBJECT_STATE,
tr ("The given session is already open or being opened"));
/* get the IInternalSessionControl interface */
/* create a progress object */
FALSE /* aCancelable */);
{
/* signal the client watcher thread */
/* fire an event */
}
return rc;
}
/**
* @note Locks objects!
*/
{
AutoCaller autoCaller (this);
/* check the session state */
if (state != SessionState_Closed)
return setError (VBOX_E_INVALID_OBJECT_STATE,
tr ("The given session is already open or being opened"));
/* get the IInternalSessionControl interface */
return rc;
}
/**
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller (this);
#if 0 /** @todo r=bird,r=pritesh: must check that the interface id match correct or we might screw up with old code! */
void *dummy;
return hrc;
#endif
AutoWriteLock alock (this);
return S_OK;
}
/**
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
rc = E_INVALIDARG;
else
return rc;
}
{
}
{
AutoCaller autoCaller (this);
return saveSettings();
}
{
AutoCaller autoCaller (this);
/* saveSettings() needs write lock */
AutoWriteLock alock (this);
/* perform backup only when there was auto-conversion */
{
}
return saveSettings();
}
// 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;
}
/**
* Adds a progress to the global collection of pending operations.
* Usually gets called upon progress object initialization.
*
* @param aProgress Operation to add to the collection.
*
* @note Doesn't lock objects.
*/
{
AutoCaller autoCaller (this);
/* protect mProgressOperations */
return S_OK;
}
/**
* Removes the progress from the global collection of pending operations.
* Usually gets called upon progress completion.
*
* @param aId UUID of the progress operation to remove
*
* @note Doesn't lock objects.
*/
{
AutoCaller autoCaller (this);
/* protect mProgressOperations */
return S_OK;
}
#ifdef RT_OS_WINDOWS
struct StartSVCHelperClientData
{
bool privileged;
void *user;
};
/**
* Helper method that starts a worker thread that:
* - creates a pipe communication channel using SVCHlpClient;
* - starts an 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 progress 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 started, the communication channel passed to
* the \a aClient argument is fully set up, the function should start using
* its 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
* 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 Helper process as a privileged
* 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 (RT_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 ("Operation cancelled by the user"));
else
tr ("Could not launch a privileged process '%s' (%Rrc)"),
break;
}
}
else
{
if (RT_FAILURE (vrc))
{
break;
}
}
/* wait for the client to connect */
if (RT_SUCCESS (vrc))
{
/* start the user supplied function */
userFuncCalled = true;
}
/* send the termination signal to the process anyway */
{
if (RT_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
AutoWriteLock alock (this);
#endif
}
/** Event for onMachineStateChange(), onMachineDataChange(), onMachineRegistered() */
{
{}
{}
{}
{
switch (what)
{
case DataChanged:
break;
case StateChanged:
LogFlow (("OnMachineStateChange: id={%RTuuid}, state=%d\n",
break;
case Registered:
LogFlow (("OnMachineRegistered: id={%RTuuid}, 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);
{
AutoReadLock 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={%RTuuid}, key='%ls', val='%ls'\n",
}
};
/**
* @note Doesn't lock any object.
*/
{
}
/**
* @note Doesn't lock any object.
*/
{
}
/** Event for onSessionStateChange() */
{
{}
{
LogFlow (("OnSessionStateChange: machineId={%RTuuid}, sessionState=%d\n",
}
};
/**
* @note Doesn't lock any object.
*/
{
}
/** Event for onSnapshotTaken(), onSnapshotRemoved() and onSnapshotChange() */
{
: CallbackEvent (aVB)
{}
{
switch (what)
{
case Taken:
LogFlow (("OnSnapshotTaken: machineId={%RTuuid}, snapshotId={%RTuuid}\n",
break;
case Discarded:
LogFlow (("OnSnapshotDiscarded: machineId={%RTuuid}, snapshotId={%RTuuid}\n",
break;
case Changed:
LogFlow (("OnSnapshotChange: machineId={%RTuuid}, snapshotId={%RTuuid}\n",
break;
}
}
};
/**
* @note Doesn't lock any object.
*/
{
}
/**
* @note Doesn't lock any object.
*/
{
}
/**
* @note Doesn't lock any object.
*/
{
}
/** Event for onGuestPropertyChange() */
{
{}
{
LogFlow (("OnGuestPropertyChange: machineId={%RTuuid}, name='%ls', value='%ls', flags='%ls'\n",
}
};
/**
* @note Doesn't lock any object.
*/
{
}
/**
* @note Locks this object for reading.
*/
{
AutoCaller autoCaller (this);
AutoReadLock alock (this);
/* unknown type must always be the first */
return type;
}
/**
* Returns the list of opened machines (machines having direct sessions opened
* by client processes) and optionally the list of direct session controls.
*
* @param aMachines Where to put opened machines (will be empty if none).
* @param aControls Where to put direct session controls (optional).
*
* @note The returned lists contain 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 do a usual AutoCaller/AutoReadLock sequence
* when accessing unprotected data directly.
*
* @note Locks objects for reading.
*/
{
AutoCaller autoCaller (this);
if (aControls)
AutoReadLock alock (this);
++ it)
{
{
if (aControls)
}
}
}
/**
* 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 VBOX_E_OBJECT_NOT_FOUND when not found
*
* @note Locks this object for reading.
*/
{
AutoCaller autoCaller (this);
bool found = false;
{
AutoReadLock alock (this);
++ it)
{
/* sanity */
}
}
{
tr ("Could not find a registered machine with UUID {%RTuuid}"),
}
return rc;
}
/**
* Searches for a HardDisk object with the given ID or location in the list 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 (unused when NULL).
* @param aLocation Full location specification (unused NULL).
* @param aSetError If @c true , the appropriate error info is set in case
* when the hard disk is not found.
* @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 this object and hard disk objects for reading.
*/
{
AutoReadLock alock (this);
/* first, look up by UUID in the map if UUID is provided */
if (aId)
{
{
if (aHardDisk)
return S_OK;
}
}
/* then iterate and search by location */
int result = -1;
if (aLocation)
{
++ it)
{
if (result == 0)
{
if (aHardDisk)
break;
}
}
}
{
if (aId)
"in the media registry ('%ls')"),
else
"in the media registry ('%ls')"),
}
return rc;
}
/**
* Searches for a DVDImage object with the given ID or location in the list 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 aLocation Full path to the image file (unused when NULL).
* @param aSetError If @c true, the appropriate error info is set in case when
* the image is not found.
* @param aImage Where to store the found image object (can be NULL).
*
* @return S_OK when found or E_INVALIDARG when not found.
*
* @note Locks this object and image objects for reading.
*/
bool aSetError,
{
{
if (RT_FAILURE (vrc))
return setError (VBOX_E_FILE_ERROR,
tr ("Invalid image file location '%ls' (%Rrc)"),
}
AutoReadLock alock (this);
bool found = false;
++ it)
{
/* no AutoCaller, registered image life time is bound to this */
if (found)
{
if (aImage)
break;
}
}
{
if (aId)
"in the media registry ('%ls')"),
else
"in the media registry ('%ls')"),
}
return rc;
}
/**
* Searches for a FloppyImage object with the given ID or location 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 aLocation Full path to the image file (unused when NULL).
* @param aSetError If @c true, the appropriate error info is set in case when
* the image is not found.
* @param aImage Where to store the found image object (can be NULL).
*
* @return S_OK when found or E_INVALIDARG when not found.
*
* @note Locks this object and image objects for reading.
*/
bool aSetError,
{
{
if (RT_FAILURE (vrc))
return setError (VBOX_E_FILE_ERROR,
tr ("Invalid image file location '%ls' (%Rrc)"),
}
AutoReadLock alock (this);
bool found = false;
++ it)
{
/* no AutoCaller, registered image life time is bound to this */
if (found)
{
if (aImage)
break;
}
}
{
if (aId)
"in the media registry ('%ls')"),
else
"in the media registry ('%ls')"),
}
return rc;
}
/**
* Calculates the absolute path of the given path taking the VirtualBox home
* directory as the current directory.
*
* @param aPath Path to calculate the absolute path for.
* @param aResult Where to put the result (used only on success, can be the
* same Utf8Str instance as passed in @a aPath).
* @return IPRT result.
*
* @note Doesn't lock any object.
*/
{
AutoCaller autoCaller (this);
/* no need to lock since mHomeDir is const */
char folder [RTPATH_MAX];
if (RT_SUCCESS (vrc))
return vrc;
}
/**
* 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
/////////////////////////////////////////////////////////////////////////////
/**
* Checks if there is a hard disk, DVD or floppy image with the given ID or
* location already registered.
*
* On return, sets @aConflict to the string describing the conflicting medium,
* or sets it to @c Null if no conflicting media is found. Returns S_OK in
* either case. A failure is unexpected.
*
* @param aId UUID to check.
* @param aLocation Location to check.
* @param aConflict Where to return parameters of the conflicting medium.
*
* @note Locks this object and media objects for reading.
*/
{
AutoReadLock alock (this);
{
{
/* Note: no AutoCaller since bound to this */
aConflict = Utf8StrFmt (
tr ("hard disk '%ls' with UUID {%RTuuid}"),
return S_OK;
}
}
{
{
/* Note: no AutoCaller since bound to this */
aConflict = Utf8StrFmt (
return S_OK;
}
}
{
{
/* Note: no AutoCaller since bound to this */
aConflict = Utf8StrFmt (
tr ("floppy image '%ls' with UUID {%RTuuid}"),
return S_OK;
}
}
return S_OK;
}
/**
* 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 media 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)
{
{
}
continue;
}
{
switch (n)
{
case 1: /* DVDImages */
{
break;
}
case 2: /* FloppyImages */
{
break;
}
default:
AssertFailed();
}
}
}
return rc;
}
/**
* Reads in the network service 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);
return S_OK;
const char *kMediaNodes[] = { "DHCPServers" };
{
/* All three media nodes are optional */
continue;
if (n == 0)
{
{
}
continue;
}
}
return rc;
}
/**
* Helper function to write out the configuration tree.
*
*/
{
AutoCaller autoCaller (this);
/* serialize file access (prevents concurrent reads and writes) */
AutoWriteLock alock (this);
try
{
using namespace settings;
using namespace xml;
/* load the settings file */
/* machines */
{
/* first, delete the entire machine registry */
if (!registryNode.isNull())
registryNode.zap();
/* then, recreate it */
/* write out the machines */
++ it)
{
}
}
/* media */
{
/* first, delete the entire media registry */
if (!registryNode.isNull())
registryNode.zap();
/* then, recreate it */
/* hard disks */
{
++ it)
{
}
}
{
++ it)
{
}
}
/* floppy images */
{
++ it)
{
}
}
}
/* netservices */
{
/* first, delete the entire netservice registry */
if (!registryNode.isNull())
registryNode.zap();
/* then, recreate it */
/* hard disks */
{
++ it)
{
}
}
}
/* host data (USB filters) */
/* save the settings on success */
}
{
/* we assume that error info is set by the thrower */
}
catch (...)
{
}
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);
AutoWriteLock alock (this);
{
{
/* sanity */
return setError (E_INVALIDARG,
tr ("Registered machine with UUID {%RTuuid} ('%ls') already exists"),
}
}
{
/* Machine::trySetRegistered() will commit and save machine settings */
}
/* add to the collection of registered machines */
rc = saveSettings();
return rc;
}
/**
* Remembers the given hard disk by storing it in the hard disk registry.
*
* @param aHardDisk Hard disk object to remember.
* @param aSaveRegistry @c true to save hard disk registry to disk (default).
*
* When @a aSaveRegistry is @c true, this operation may fail because of the
* failed #saveSettings() method it calls. In this case, the hard disk object
* will not be remembered. It is therefore the responsibility of the caller to
* call this method as the last step of some action that requires registration
* in order to make sure that only fully functional hard disk objects get
* registered.
*
* @note Locks this object for writing and @a aHardDisk for reading.
*/
bool aSaveRegistry /*= true*/)
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
conflict);
{
return setError (E_INVALIDARG,
tr ("Cannot register the hard disk '%ls' with UUID {%RTuuid} "
"because a %s already exists in the media registry ('%ls')"),
}
{
/* base (root) hard disk */
}
if (aSaveRegistry)
{
rc = saveSettings();
}
return rc;
}
/**
* Removes the given hard disk from the hard disk registry.
*
* @param aHardDisk Hard disk object to remove.
* @param aSaveRegistry @c true to save hard disk registry to disk (default).
*
* When @a aSaveRegistry is @c true, this operation may fail because of the
* failed #saveSettings() method it calls. In this case, the hard disk object
* will NOT be removed from the registry when this method returns. It is
* therefore the responsibility of the caller to call this method as the first
* step of some action that requires unregistration, before calling uninit() on
* @a aHardDisk.
*
* @note Locks this object for writing and @a aHardDisk for reading.
*/
bool aSaveRegistry /*= true*/)
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
{
/* base (root) hard disk */
}
if (aSaveRegistry)
{
rc = saveSettings();
}
return rc;
}
/**
*
* @param aImage Image object to remember.
* @param aSaveRegistry @c true to save the image registry to disk (default).
*
* When @a aSaveRegistry is @c true, this operation may fail because of the
* failed #saveSettings() method it calls. In this case, the image object
* will not be remembered. It is therefore the responsibility of the caller to
* call this method as the last step of some action that requires registration
* in order to make sure that only fully functional image objects get
* registered.
*
* @note Locks this object for writing and @a aImage for reading.
*/
bool aSaveRegistry /*= true*/)
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
conflict);
{
return setError (VBOX_E_INVALID_OBJECT_STATE,
"because a %s already exists in the media registry ('%ls')"),
}
/* add to the collection */
if (aSaveRegistry)
{
rc = saveSettings();
}
return rc;
}
/**
*
* @param aImage Image object to remove.
* @param aSaveRegistry @c true to save hard disk registry to disk (default).
*
* When @a aSaveRegistry is @c true, this operation may fail because of the
* failed #saveSettings() method it calls. In this case, the image object
* will NOT be removed from the registry when this method returns. It is
* therefore the responsibility of the caller to call this method as the first
* step of some action that requires unregistration, before calling uninit() on
* @a aImage.
*
* @note Locks this object for writing and @a aImage for reading.
*/
bool aSaveRegistry /*= true*/)
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
if (aSaveRegistry)
{
rc = saveSettings();
}
return rc;
}
/**
* Remembers the given image by storing it in the floppy image registry.
*
* @param aImage Image object to remember.
* @param aSaveRegistry @c true to save the image registry to disk (default).
*
* When @a aSaveRegistry is @c true, this operation may fail because of the
* failed #saveSettings() method it calls. In this case, the image object
* will not be remembered. It is therefore the responsibility of the caller to
* call this method as the last step of some action that requires registration
* in order to make sure that only fully functional image objects get
* registered.
*
* @note Locks this object for writing and @a aImage for reading.
*/
bool aSaveRegistry /*= true*/)
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
conflict);
{
return setError (VBOX_E_INVALID_OBJECT_STATE,
tr ("Cannot register the floppy image '%ls' with UUID {%RTuuid} "
"because a %s already exists in the media registry ('%ls')"),
}
/* add to the collection */
if (aSaveRegistry)
{
rc = saveSettings();
}
return rc;
}
/**
* Removes the given image from the floppy image registry registry.
*
* @param aImage Image object to remove.
* @param aSaveRegistry @c true to save hard disk registry to disk (default).
*
* When @a aSaveRegistry is @c true, this operation may fail because of the
* failed #saveSettings() method it calls. In this case, the image object
* will NOT be removed from the registry when this method returns. It is
* therefore the responsibility of the caller to call this method as the first
* step of some action that requires unregistration, before calling uninit() on
* @a aImage.
*
* @note Locks this object for writing and @a aImage for reading.
*/
bool aSaveRegistry /*= true*/)
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
if (aSaveRegistry)
{
rc = saveSettings();
}
return rc;
}
/**
* Attempts to cast from a raw interface pointer to an underlying object.
* On success, @a aTo will contain the object reference. On failure, @a aTo will
* be set to @c null and an extended error info will be returned.
*
* @param aFrom Interface pointer to cast from.
* @param aTo Where to store a reference to the underlying object.
*
* @note Locks #childrenLock() for reading.
*/
{
AutoCaller autoCaller (this);
/* We need the children map lock here to keep the getDependentChild() result
* valid until we finish */
if (!child)
"within this VirtualBox instance"));
/* we can safely cast child to HardDisk * here because only HardDisk
* implementations of IHardDisk can be among our children */
return S_OK;
}
/**
* 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);
AutoWriteLock alock (this);
/* check DVD paths */
++ it)
{
}
/* check Floppy paths */
++ it)
{
}
/* check HardDisk paths */
++ it)
{
}
return rc;
}
/**
* Creates the path to the specified file according to the path information
* present in the file name.
*
* Note that the given file name must contain the full path otherwise the
* extracted relative path will be created based on the current working
* directory which is normally unknown.
*
* @param aFileName Full file name which path needs to be created.
*
* @return Extended error information on failure to create the path.
*/
/* static */
{
if (!RTDirExists (dir))
{
if (RT_FAILURE (vrc))
{
tr ("Could not create the directory '%s' (%Rrc)"),
}
}
return S_OK;
}
/**
* 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 missing attributes that have
* defaults in the XML schema.
* @param aFormatVersion Where to store the current format version of the
* loaded settings tree (optional, may be NULL).
*/
/* static */
bool aValidate,
bool aCatchLoadErrors,
bool aAddDefaults,
{
using namespace settings;
try
{
/* on success, memorize the current settings file version or set it to
* the most recent version if no settings conversion took place. Note
* that it's not necessary to do it every time we load the settings file
* (i.e. only loadSettingsTree_FirstTime() passes a non-NULL
* aFormatVersion value) because currently we keep the settings
* files locked so that the only legal way to change the format version
* while VirtualBox is running is saveSettingsTree(). */
if (aFormatVersion != NULL)
{
if (aFormatVersion->isNull())
}
}
{
if (!aCatchLoadErrors)
throw;
return setError (VBOX_E_FILE_ERROR,
tr ("Could not load the settings file '%s' (%Rrc)"),
}
{
if (!aCatchLoadErrors)
throw;
return setError (VBOX_E_XML_ERROR,
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.
* @param aFormatVersion Where to store the (recent) format version of the
* saved settings tree on success.
*/
/* static */
{
using namespace settings;
try
{
/* set the current settings file version to the most recent version on
* success. See also VirtualBox::loadSettingsTree(). */
if (aFormatVersion != VBOX_XML_VERSION_FULL)
}
{
/* this is the only expected exception for now */
return setError (VBOX_E_FILE_ERROR,
tr ("Could not save the settings file '%s' (%Rrc)"),
}
return S_OK;
}
/**
* Creates a backup copy of the given settings file by suffixing it with the
* supplied version format string and optionally with numbers from .0 to .9
* if the backup file already exists.
*
* @param aFileName Original settings file name.
* @param aOldFormat Version of the original format.
* @param aBakFileName File name of the created backup copy (only on success).
*/
/* static */
const Utf8Str &aOldFormat,
{
/* try progressive suffix from .0 to .9 on failure */
if (vrc == VERR_ALREADY_EXISTS)
{
{
}
}
if (RT_FAILURE (vrc))
return setError (VBOX_E_IPRT_ERROR,
tr ("Could not copy the settings file '%s' to '%s' (%Rrc)"),
aBakFileName = nf;
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
{
/* re-throw the current exception */
throw;
}
{
ComAssertMsgFailedPos (("Unexpected exception '%s' (%s)",
return E_FAIL;
}
catch (...)
{
ComAssertMsgFailedPos (("Unknown exception"),
return E_FAIL;
}
/* should not get here */
AssertFailed();
return E_FAIL;
}
/**
* 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 scratch.
*/
{
AutoCaller autoCaller (this);
Assert (!isConfigLocked());
if (!isConfigLocked())
{
/* Open the associated config file. */
{
/* Open the associated config file only with read access. */
if (RT_FAILURE (vrc))
{
/* We even cannot open it in read mode, so there's seriously
something wrong. */
tr ("Could not even open settings file '%ls' in read mode (%Rrc)"),
}
else
{
}
}
else
{
}
if (RT_FAILURE(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
{
size_t cntSpawned = 0;
#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;
}
{
/* spawned VM process has terminated (normally or abnormally) */
update = true;
}
if (update)
{
/* close old process handles */
CloseHandle (handles [i]);
/* obtain a new set of opened machines */
cnt = 0;
{
/// @todo handle situations with more than 64 objects
("MAXIMUM_WAIT_OBJECTS reached"));
{
++ cnt;
}
}
/* obtain a new set of spawned machines */
cntSpawned = 0;
{
/// @todo handle situations with more than 64 objects
("MAXIMUM_WAIT_OBJECTS reached"));
{
pid, GetLastError()));
if (rc == 0)
{
++ cntSpawned;
}
}
}
}
}
while (true);
}
while (0);
/* close old process handles */
CloseHandle (handles [i]);
/* release sets of 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;
bool updateSpawned = false;
if (RT_SUCCESS (vrc))
{
/* update event is signaled */
update = true;
updateSpawned = true;
}
else
{
("RTSemEventWait returned %Rrc\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));
}
/* are there any spawning sessions? */
if (cntSpawned > 0)
{
for (size_t i = 0; i < cntSpawned; ++ i)
updateSpawned |= (spawnedMachines [i])->
}
}
if (update || updateSpawned)
{
if (update)
{
/* close the old muxsem */
if (muxSem != NULLHANDLE)
::DosCloseMuxWaitSem (muxSem);
/* obtain a new set of opened machines */
cnt = 0;
{
/// @todo handle situations with more than 64 objects
("maximum of 64 mutex semaphores reached (%d)",
cnt));
{
++ cnt;
}
}
if (cnt > 0)
{
/* create a new muxsem */
("DosCreateMuxWaitSem returned %d\n", arc));
}
}
if (updateSpawned)
{
/* obtain a new set of spawned machines */
{
if ((*it)->isSessionSpawning())
}
}
}
}
while (true);
}
while (0);
/* close the muxsem */
if (muxSem != NULLHANDLE)
::DosCloseMuxWaitSem (muxSem);
/* release sets of machines if any */
#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
bool update = false;
bool updateSpawned = 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;
{
/* RT_SUCCESS (rc) means an update event is signaled */
{
/* obtain a new set of opened machines */
{
}
}
{
/* obtain a new set of spawned machines */
{
if ((*it)->isSessionSpawning())
}
}
}
update = false;
updateSpawned = false;
for (size_t i = 0; i < cntSpawned; ++ i)
/* 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=%Rrc\n",
if (vrc != VERR_PROCESS_RUNNING)
{
/* remove the process if it is not already running */
}
else
++ it;
}
}
}
}
}
while (true);
}
while (0);
/* release sets of 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;
}
//STDMETHODIMP VirtualBox::CreateDHCPServerForInterface (/*IHostNetworkInterface * aIinterface,*/ IDHCPServer ** aServer)
//{
// return E_NOTIMPL;
//}
{
AutoCaller autoCaller (this);
return rc;
}
//STDMETHODIMP VirtualBox::FindDHCPServerForInterface (IHostNetworkInterface * aIinterface, IDHCPServer ** aServer)
//{
// return E_NOTIMPL;
//}
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
++ it)
{
{
break;
}
}
if (!found)
return E_INVALIDARG;
}
{
AutoCaller autoCaller (this);
return rc;
}
/**
* Remembers the given dhcp server by storing it in the hard disk registry.
*
* @param aDHCPServer Dhcp Server object to remember.
* @param aSaveRegistry @c true to save hard disk registry to disk (default).
*
* When @a aSaveRegistry is @c true, this operation may fail because of the
* failed #saveSettings() method it calls. In this case, the dhcp server object
* will not be remembered. It is therefore the responsibility of the caller to
* call this method as the last step of some action that requires registration
* in order to make sure that only fully functional dhcp server objects get
* registered.
*
* @note Locks this object for writing and @a aDHCPServer for reading.
*/
bool aSaveRegistry /*= true*/)
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
{
return E_INVALIDARG;
}
if (aSaveRegistry)
{
rc = saveSettings();
}
return rc;
}
/**
* Removes the given hard disk from the hard disk registry.
*
* @param aHardDisk Hard disk object to remove.
* @param aSaveRegistry @c true to save hard disk registry to disk (default).
*
* When @a aSaveRegistry is @c true, this operation may fail because of the
* failed #saveSettings() method it calls. In this case, the hard disk object
* will NOT be removed from the registry when this method returns. It is
* therefore the responsibility of the caller to call this method as the first
* step of some action that requires unregistration, before calling uninit() on
* @a aHardDisk.
*
* @note Locks this object for writing and @a aHardDisk for reading.
*/
bool aSaveRegistry /*= true*/)
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
if (aSaveRegistry)
{
rc = saveSettings();
}
return rc;
}
/* vi: set tabstop=4 shiftwidth=4 expandtab: */