MachineImpl.cpp revision 1cca67fef86e003f1d86a7871eb0033354c399df
/** @file
*
* VirtualBox COM class implementation
*/
/*
* Copyright (C) 2006 InnoTek Systemberatung 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 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.
*
* If you received this file as part of a commercial VirtualBox
* distribution, then only the terms of your commercial VirtualBox
* license agreement apply instead of the previous paragraph.
*/
#if defined(__WIN__)
#endif
# include <errno.h>
#endif
#include "VirtualBoxImpl.h"
#include "MachineImpl.h"
#include "HardDiskImpl.h"
#include "HostDVDDriveImpl.h"
#include "HostFloppyDriveImpl.h"
#include "ProgressImpl.h"
#include "HardDiskAttachmentImpl.h"
#include "USBControllerImpl.h"
#include "HostImpl.h"
#include "SystemPropertiesImpl.h"
#include "SharedFolderImpl.h"
#include "GuestOSTypeImpl.h"
#include "VirtualBoxErrorInfoImpl.h"
#include "USBProxyService.h"
#include "Logging.h"
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#define HOSTSUFF_EXE ".exe"
#else /* !__WIN__ */
#define HOSTSUFF_EXE ""
#endif /* !__WIN__ */
// defines / prototypes
/////////////////////////////////////////////////////////////////////////////
/**
* Local mutability check macro for Machine implementation only.
*/
#define CHECK_SETTER() \
if (!isMutable()) \
// globals
/////////////////////////////////////////////////////////////////////////////
/**
* @note The template is NOT completely valid according to VBOX_XML_SCHEMA
* (when loading a newly created settings file, validation will be turned off)
*/
static const char DefaultMachineConfig[] =
{
"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" RTFILE_LINEFEED
"<!-- InnoTek VirtualBox Machine Configuration -->" RTFILE_LINEFEED
"</VirtualBox>" RTFILE_LINEFEED
};
/**
* Progress callback handler for lengthy operations
* (corresponds to the FNRTPROGRESS typedef).
*
* @param uPercentage Completetion precentage (0-100).
* @param pvUser Pointer to the Progress instance.
*/
{
/* update the progress object */
if (progress)
return VINF_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////
// Machine::Data structure
/////////////////////////////////////////////////////////////////////////////
{
mRegistered = FALSE;
/* mUuid is initialized in Machine::init() */
}
{
}
/////////////////////////////////////////////////////////////////////////////
// Machine::UserData structure
/////////////////////////////////////////////////////////////////////////////
{
/* default values for a newly created machine */
/* mName, mOSType, mSnapshotFolder, mSnapshotFolderFull are initialized in
* Machine::init() */
}
{
}
/////////////////////////////////////////////////////////////////////////////
// Machine::HWData structure
/////////////////////////////////////////////////////////////////////////////
{
/* default values for a newly created machine */
mMemorySize = 128;
mVRAMSize = 8;
/* default boot order: floppy - DVD - HDD */
mBootOrder [i] = DeviceType_NoDevice;
}
{
}
{
if (this == &that)
return true;
return false;
return false;
return false;
if (mSharedFolders.size() == 0)
return true;
/* Make copies to speed up comparison */
{
bool found = false;
{
{
found = true;
break;
}
else
++ thatIt;
}
if (found)
else
return false;
}
return true;
}
/////////////////////////////////////////////////////////////////////////////
// Machine::HDData structure
/////////////////////////////////////////////////////////////////////////////
{
/* default values for a newly created machine */
mHDAttachmentsChanged = false;
}
{
}
{
if (this == &that)
return true;
return false;
if (mHDAttachments.size() == 0)
return true;
/* Make copies to speed up comparison */
{
bool found = false;
{
{
found = true;
break;
}
else
++ thatIt;
}
if (found)
else
return false;
}
return true;
}
/////////////////////////////////////////////////////////////////////////////
// Machine class
/////////////////////////////////////////////////////////////////////////////
// constructor / destructor
/////////////////////////////////////////////////////////////////////////////
{
LogFlowThisFunc (("\n"));
return S_OK;
}
void Machine::FinalRelease()
{
LogFlowThisFunc (("\n"));
uninit();
}
/**
* Initializes the instance.
*
* @param aParent Associated parent object
* @param aConfigFile Local file system path to the VM settings file (can
* be relative to the VirtualBox config directory).
* @param aMode Init_New, Init_Existing or Init_Registered
* @param aName name for the machine when aMode is Init_New
* (ignored otherwise)
* @param aNameSync |TRUE| to authomatically sync settings dir and file
* name with the machine name. |FALSE| is used for legacy
* machines where the file name is specified by the
* user and should never change. Used only in Init_New
* mode (ignored otherwise).
* @param aId UUID of the machine (used only for consistency
* check when aMode is Init_Registered; must match UUID
* stored in the settings file).
*
* @return Success indicator. if not S_OK, the machine object is invalid
*/
{
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan (this);
/* share the parent weakly */
/* register with parent early, since uninit() will unconditionally
* unregister on failure */
mParent->addDependentChild (this);
/* create machine data structures */
char configFileFull [RTPATH_MAX] = {0};
/* memorize the config file name (as provided) */
/* get the full file name */
configFileFull, sizeof (configFileFull));
if (VBOX_FAILURE (vrc))
tr ("Invalid settings file name: '%ls' (%Vrc)"),
aConfigFile, vrc);
{
/* lock the settings file */
rc = lockConfig();
{
/* If the machine is registered, then, instead of returning a
* failure, we mark it as inaccessible and set the result to
* success to give it a try later */
/* fetch the current error info */
LogWarning (("Machine {%Vuuid} is inaccessible! [%ls]\n",
}
}
else
{
/* check for the file existence */
RTFILE f = NIL_RTFILE;
{
if (VBOX_SUCCESS (vrc))
RTFileClose (f);
}
else
{
tr ("Invalid settings file name: '%ls' (%Vrc)"),
}
}
/* initialize mOSType */
/* create associated BIOS settings object */
mBIOSSettings->init(this);
#ifdef VBOX_VRDP
/* create an associated VRDPServer object (default is disabled) */
mVRDPServer->init(this);
#endif
/* create an associated DVD drive object */
/* create an associated floppy drive object */
mFloppyDrive->init (this);
/* create the audio adapter object (always present, default is disabled) */
mAudioAdapter->init(this);
/* create the USB controller object (always present, default is disabled) */
mUSBController->init(this);
/* create associated network adapter objects */
{
}
if (aMode == Init_Registered)
{
/* store the supplied UUID (will be used to check for UUID consistency
* in loadSettings() */
/* try to load settings only if the settings file is accessible */
if (mData->mAccessible)
rc = registeredInit();
}
else
{
{
}
else
{
/* create the machine UUID */
/* initialize the default snapshots folder */
AssertComRC (rc);
/* memorize the provided new machine's name */
}
/* commit all changes made during the initialization */
commit();
}
/* Confirm a successful initialization when it's the case */
{
if (mData->mAccessible)
else
}
LogFlowThisFunc (("mName='%ls', mRegistered=%RTbool, mAccessible=%RTbool "
"rc=%08X\n",
return rc;
}
/**
* Initializes the registered machine by loading the settings file.
* This method is separated from #init() in order to make it possible to
* retry the operation after VirtualBox startup instead of refusing to
* startup the whole VirtualBox server in case if the settings file of some
* registered VM is invalid or inaccessible.
*
* @note Must be always called from this object's write lock
* (unless called from #init() that doesn't need any locking).
* @note Locks the mUSBController method for writing.
* @note Subclasses must not call this method.
*/
{
if (!mData->mAccessible)
rc = lockConfig();
/* Temporarily reset the registered flag in order to let setters potentially
* called from loadSettings() succeed (isMutable() used in all setters
* will return FALSE for a Machine instance if mRegistered is TRUE). */
{
unlockConfig();
}
{
/* commit all changes made during loading the settings file */
commit();
/* VirtualBox will not call trySetRegistered(), so
* inform the USB proxy about all attached USB filters */
}
else
{
/* If the machine is registered, then, instead of returning a
* failure, we mark it as inaccessible and set the result to
* success to give it a try later */
/* fetch the current error info */
LogWarning (("Machine {%Vuuid} is inaccessible! [%ls]\n",
/* rollback all changes */
rollback (false /* aNotify */);
}
/* Restore the registered flag (even on failure) */
return rc;
}
/**
* Uninitializes the instance.
* Called either from FinalRelease() or by the parent when it gets destroyed.
*
* @note The caller of this method must make sure that this object
* a) doesn't have active callers on the current thread and b) is not locked
* by the current thread; otherwise uninit() will hang either a) due to
* AutoUninitSpan waiting for a number of calls to drop to zero or b) due to
* a dead-lock caused by this thread waiting for all callers on the other
* threads are are done but preventing them from doing so by holding a lock.
*/
{
/* Enclose the state transition Ready->InUninit->NotReady */
AutoUninitSpan autoUninitSpan (this);
if (autoUninitSpan.uninitDone())
return;
/*
* Enter this object's lock because there may be a SessionMachine instance
* somewhere around, that shares our data and lock but doesn't use our
* addCaller()/removeCaller(), and it may be also accessing the same
* data members. mParent lock is necessary as well because of
* SessionMachine::uninit(), etc.
*/
{
/*
* Theoretically, this can only happen if the VirtualBox server has
* been terminated while there were clients running that owned open
* direct sessions. Since in this case we are definitely called by
* VirtualBox::uninit(), we may be sure that SessionMachine::uninit()
* won't happen on the client watcher thread (because it does
* VirtualBox::addCaller() for the duration of the
* SessionMachine::checkForDeath() call, so that VirtualBox::uninit()
* cannot happen until the VirtualBox caller is released). This is
* important, because SessionMachine::uninit() cannot correctly operate
* after we return from this method (it expects the Machine instance
* is still valid). We'll call it ourselves below.
*/
LogWarningThisFunc (("Session machine is not NULL (%p), "
"the direct session is still open!\n",
{
LogWarningThisFunc (("Setting state to Aborted!\n"));
/* set machine state using SessionMachine reimplementation */
}
/*
* Uninitialize SessionMachine using public uninit() to indicate
* an unexpected uninitialization.
*/
/* SessionMachine::uninit() must set mSession.mMachine to null */
}
/* the lock is no more necessary (SessionMachine is uninitialized) */
/* make sure the configuration is unlocked */
unlockConfig();
if (isModified())
{
LogWarningThisFunc (("Discarding unsaved settings changes!\n"));
rollback (false /* aNotify */);
}
mParent->removeDependentChild (this);
}
// IMachine properties
/////////////////////////////////////////////////////////////////////////////
{
if (!aParent)
return E_POINTER;
AutoLimitedCaller autoCaller (this);
/* mParent is constant during life time, no need to lock */
return S_OK;
}
{
if (!aAccessible)
return E_POINTER;
AutoLimitedCaller autoCaller (this);
if (!mData->mAccessible)
{
/* try to initialize the VM once more if not accessible */
AutoReadySpan autoReadySpan (this);
rc = registeredInit();
if (mData->mAccessible)
}
return rc;
}
{
if (!aAccessError)
return E_POINTER;
AutoLimitedCaller autoCaller (this);
AutoReaderLock alock (this);
{
/* return shortly */
aAccessError = NULL;
return S_OK;
}
{
}
return rc;
}
{
if (!aName)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
if (!aName)
return E_INVALIDARG;
if (!*aName)
return setError (E_INVALIDARG,
tr ("Machine name cannot be empty"));
AutoCaller autoCaller (this);
CHECK_SETTER();
return S_OK;
}
{
if (!aDescription)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
CHECK_SETTER();
return S_OK;
}
{
if (!aId)
return E_POINTER;
AutoLimitedCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
if (!aOSType)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
if (!aOSType)
return E_INVALIDARG;
AutoCaller autoCaller (this);
CHECK_SETTER();
return S_OK;
}
{
if (!memorySize)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
/* check RAM limits */
return setError (E_INVALIDARG,
tr ("Invalid RAM size: %lu MB (must be in range [%lu, %lu] MB)"),
AutoCaller autoCaller (this);
CHECK_SETTER();
return S_OK;
}
{
if (!memorySize)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
/* check VRAM limits */
return setError (E_INVALIDARG,
tr ("Invalid VRAM size: %lu MB (must be in range [%lu, %lu] MB)"),
AutoCaller autoCaller (this);
CHECK_SETTER();
return S_OK;
}
{
if (!biosSettings)
return E_POINTER;
AutoCaller autoCaller (this);
/* mBIOSSettings is constant during life time, no need to lock */
return S_OK;
}
{
if (!enabled)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
CHECK_SETTER();
/** @todo check validity! */
return S_OK;
}
{
if (!aSnapshotFolder)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
/// @todo (r=dmik):
// 1. Allow to change the name of the snapshot folder containing snapshots
// 2. Rename the folder on disk instead of just changing the property
// value (to be smart and not to leave garbage). Note that it cannot be
// done here because the change may be rolled back. Thus, the right
// place is #saveSettings().
AutoCaller autoCaller (this);
CHECK_SETTER();
tr ("The snapshot folder of a machine with snapshots cannot "
"be changed (please discard all snapshots first)"));
if (snapshotFolder.isEmpty())
{
if (isInOwnDir())
{
/* the default snapshots folder is 'Snapshots' in the machine dir */
}
else
{
/* the default snapshots folder is {UUID}, for backwards
* compatibility and to resolve conflicts */
}
}
if (VBOX_FAILURE (vrc))
tr ("Invalid snapshot folder: '%ls' (%Vrc)"),
return S_OK;
}
{
if (!attachments)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
#ifdef VBOX_VRDP
if (!vrdpServer)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
Assert (!!mVRDPServer);
return S_OK;
#else
return E_NOTIMPL;
#endif
}
{
if (!dvdDrive)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
if (!floppyDrive)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
Assert (!!mFloppyDrive);
return S_OK;
}
{
if (!audioAdapter)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
#ifdef VBOX_WITH_USB
if (!a_ppUSBController)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
#else
/* Note: The GUI depends on this method returning E_NOTIMPL with no
* extended error info to indicate that USB is simply not available
* (w/o treting it as a failure), for example, as in OSE */
return E_NOTIMPL;
#endif
}
{
if (!filePath)
return E_POINTER;
AutoLimitedCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
if (!modified)
return E_POINTER;
AutoCaller autoCaller (this);
CHECK_SETTER();
if (!isConfigLocked())
{
/*
* if we're ready and isConfigLocked() is FALSE then it means
* that no config file exists yet, so always return TRUE
*/
}
else
{
*modified = isModified();
}
return S_OK;
}
{
if (!aSessionState)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
if (!aSessionType)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
if (!aSessionPid)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
if (!machineState)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
if (!aLastStateChange)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
if (!aStateFilePath)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
if (!aCurrentSnapshot)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
if (!aSnapshotCount)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
if (!aCurrentStateModified)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
/*
* Note: for machines with no snapshots, we always return FALSE
* (mData->mCurrentStateModified will be TRUE in this case, for historical
* reasons :)
*/
return S_OK;
}
{
if (!aSharedFolders)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
coll.createObject();
return S_OK;
}
{
if (!aClipboardMode)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
CHECK_SETTER();
return S_OK;
}
// IMachine methods
/////////////////////////////////////////////////////////////////////////////
{
return setError (E_INVALIDARG,
tr ("Invalid boot position: %lu (must be in range [1, %lu])"),
if (aDevice == DeviceType_USBDevice)
tr ("Booting from USB devices is not currently supported"));
AutoCaller autoCaller (this);
CHECK_SETTER();
return S_OK;
}
{
return setError (E_INVALIDARG,
tr ("Invalid boot position: %lu (must be in range [1, %lu])"),
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
return E_INVALIDARG;
AutoCaller autoCaller (this);
CHECK_SETTER();
if (!mData->mRegistered)
tr ("Cannot attach hard disks to an unregistered machine"));
/* see if the device on the controller is already busy */
{
{
tr ("Hard disk '%ls' is already attached to device slot %d "
"on controller %d"),
}
}
/* find a hard disk by UUID */
return rc;
if (hd->isDifferencing())
tr ("Cannot attach the differencing hard disk '%ls'"),
bool dirty = false;
{
{
/*
* increase readers to protect from unregistration
* until rollback()/commit() is done
*/
// LogTraceMsg (("A: %ls proteced\n", hd->toString().raw()));
dirty = true;
break;
}
{
/* fall through */
}
{
{
/* attach directly */
// LogTraceMsg (("A: %ls associated with %Vuuid\n",
// hd->toString().raw(), mData->mUuid.raw()));
dirty = true;
}
else
{
/* determine what the hard disk is already attached to */
{
/* attached to some VM in its current state */
{
/*
* attached to us, either in the backed up list of the
* attachments or in the current one; the former is ok
* (reattachment takes place within the same
* "transaction") the latter is an error so check for it
*/
{
{
tr ("Normal/Writethrough hard disk '%ls' is "
"currently attached to device slot %d "
"on controller %d of this machine"),
}
}
/*
* dirty = false to indicate we didn't set machineId
* and prevent it from being reset in DetachHardDisk()
*/
// LogTraceMsg (("A: %ls found in old\n", hd->toString().raw()));
}
else
{
/* attached to other VM */
tr ("Normal/Writethrough hard disk '%ls' is "
"currently attached to a machine with "
"UUID {%Vuuid}"),
}
}
else
{
/*
* here we go when the HardDiskType_NormalHardDisk
* is attached to some VM (probably to this one, too)
* at some particular snapshot, so we can create a diff
* based on it
*/
/*
* increase readers to protect from unregistration
* until rollback()/commit() is done
*/
// LogTraceMsg (("A: %ls proteced\n", hd->toString().raw()));
dirty = true;
}
}
break;
}
}
// LogTraceMsg (("A: %ls attached\n", hd->toString().raw()));
/* note: diff images are actually created only in commit() */
return S_OK;
}
{
if (aCtl == DiskControllerType_InvalidController ||
return E_INVALIDARG;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
{
{
return S_OK;
}
}
return setError (E_INVALIDARG,
tr ("No hard disk attached to device slot %d on controller %d"),
}
{
if (aCtl == DiskControllerType_InvalidController ||
return E_INVALIDARG;
AutoCaller autoCaller (this);
CHECK_SETTER();
{
{
{
{
{
/* decrease readers increased in AttachHardDisk() */
hd->releaseReader();
// LogTraceMsg (("D: %ls released\n", hd->toString().raw()));
break;
}
{
/* deassociate from this machine */
// LogTraceMsg (("D: %ls deassociated\n", hd->toString().raw()));
break;
}
{
{
/* deassociate from this machine */
// LogTraceMsg (("D: %ls deassociated\n", hd->toString().raw()));
}
else
{
/* decrease readers increased in AttachHardDisk() */
hd->releaseReader();
// LogTraceMsg (("%ls released\n", hd->toString().raw()));
}
break;
}
}
}
/*
* we cannot use erase (it) below because backup() above will create
* a copy of the list and make this copy active, but the iterator
* still refers to the original and is not valid for a copy
*/
// LogTraceMsg (("D: %ls detached\n", hd->toString().raw()));
/*
* note: Non-dirty hard disks are actually deassociated
* and diff images are deleted only in commit()
*/
return S_OK;
}
}
return setError (E_INVALIDARG,
tr ("No hard disk attached to device slot %d on controller %d"),
}
{
if (!adapter)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
/**
* Returns the extra data key name following the given key. If the key
* is not found, an error is returned. If NULL is supplied, the first
* key will be returned. If key is the last item, NULL will be returned.
*
* @returns COM status code
* @param key extra data key name
* @param nextKey name of the key following "key". NULL if "key" is the last.
* @param nextValue value of the key following "key". Optional parameter.
*/
{
if (!nextKey)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
/* start with nothing found */
/*
* if we're ready and isConfigLocked() is FALSE then it means
* that no config file exists yet, so return shortly
*/
if (!isConfigLocked())
return S_OK;
/* load the config file */
CFGHANDLE configLoader = 0;
return E_FAIL;
/* navigate to the right position */
{
/* check if it exists */
bool found = false;
unsigned count;
{
/* if we're supposed to return the first one */
{
if (nextValue)
found = true;
}
/* did we find the key we're looking for? */
{
found = true;
/* is there another item? */
if (i + 1 < count)
{
if (nextValue)
found = true;
}
else
{
/* it's the last one */
}
}
}
/* if we haven't found the key, it's an error */
if (!found)
}
return rc;
}
/**
* Returns associated extra data from the configuration. If the key does
* not exist, NULL will be stored in the output pointer.
*
* @returns COM status code
* @param key extra data key
* @param value address of result pointer
*/
{
if (!key)
return E_INVALIDARG;
if (!value)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
/* start with nothing found */
/*
* if we're ready and isConfigLocked() is FALSE then it means
* that no config file exists yet, so return shortly
*/
if (!isConfigLocked())
return S_OK;
/* load the config file */
CFGHANDLE configLoader = 0;
return E_FAIL;
/* navigate to the right position */
{
/* check if it exists */
bool found = false;
unsigned count;
{
{
found = true;
}
}
}
return rc;
}
/**
* Stores associated extra data in the configuration. If the data value is NULL
* then the corresponding extra data item is deleted. This method can be called
* outside a session and therefore belongs to the non protected machine data.
*
* @param key extra data key
* @param value extra data value
*
* @note Locks mParent for reading + this object for writing.
*/
{
if (!key)
return E_INVALIDARG;
AutoCaller autoCaller (this);
/* VirtualBox::onExtraDataCanChange() needs mParent lock */
if (mType == IsSnapshotMachine)
CHECK_SETTER();
bool changed = false;
/*
* if we're ready and isConfigLocked() is FALSE then it means
* that no config file exists yet, so call saveSettings() to create one
*/
if (!isConfigLocked())
{
return rc;
}
/* load the config file */
CFGHANDLE configLoader = 0;
return rc;
CFGNODE machineNode = 0;
CFGNODE extraDataNode = 0;
if (VBOX_FAILURE (vrc))
if (extraDataNode)
{
CFGNODE extraDataItemNode = 0;
unsigned count;
for (unsigned i = 0; i < count; i++)
{
{
break;
}
extraDataItemNode = 0;
}
/*
* When no key is found, oldVal is null
* Note:
* 1. when oldVal is null, |oldVal == (BSTR) NULL| is true
* 2. we cannot do |oldVal != value| because it will compare
* BSTR pointers instead of strings (due to type conversion ops)
*/
if (changed)
{
/* ask for permission from all listeners */
{
LogWarningFunc (("Someone vetoed! Change refused!\n"));
tr ("Could not set extra data because someone refused "
}
else
{
if (value)
{
if (!extraDataItemNode)
{
/* create a new item */
}
}
else
{
/* an old value does for sure exist here */
extraDataItemNode = 0;
}
}
}
if (extraDataItemNode)
}
else
/* fire an event */
{
}
return rc;
}
{
AutoCaller autoCaller (this);
/* Under some circumstancies, saveSettings() needs mParent lock */
CHECK_SETTER();
/* the settings file path may never be null */
/* save all VM data excluding snapshots */
return saveSettings();
}
{
AutoCaller autoCaller (this);
CHECK_SETTER();
/*
* during this rollback, the session will be notified if data has
* been actually changed
*/
rollback (true /* aNotify */);
return S_OK;
}
{
AutoCaller autoCaller (this);
CHECK_SETTER();
if (mData->mRegistered)
tr ("Cannot delete settings of a registered machine"));
/* delete the settings only when the file actually exists */
if (isConfigLocked())
{
unlockConfig();
if (VBOX_FAILURE (vrc))
tr ("Could not delete the settings file '%ls' (%Vrc)"),
/* delete the Logs folder, nothing important should be left
* there (we don't check for errors because the user might have
* some private files there that we don't want to delete) */
if (RTDirExists (logFolder))
{
/* delete all VBox.log[.N] files from the Logs folder
* (this must be in sync with the rotation logic in
* Console::powerUpThread()) */
RTFileDelete (log);
for (int i = 3; i >= 0; i--)
{
RTFileDelete (log);
}
}
/* delete the Snapshots folder, nothing important should be left
* there (we don't check for errors because the user might have
* some private files there that we don't want to delete) */
if (RTDirExists (snapshotFolder))
/* delete the directory that contains the settings file, but only
* if it matches the VM name (i.e. a structure created by default in
* openConfigLoader()) */
{
if (isInOwnDir (&settingsDir))
}
}
return S_OK;
}
{
if (!aSnapshot)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return rc;
}
{
if (!aName)
return E_INVALIDARG;
if (!aSnapshot)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return rc;
}
{
/// @todo (dmik) don't forget to set
// mData->mCurrentStateModified to FALSE
}
{
return E_INVALIDARG;
AutoCaller autoCaller (this);
CHECK_SETTER();
/// @todo (dmik) check global shared folders when they are done
return rc;
return rc;
if (!accessible)
return S_OK;
}
{
if (!aName)
return E_INVALIDARG;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
CHECK_SETTER();
return rc;
return S_OK;
}
// public methods for internal purposes
/////////////////////////////////////////////////////////////////////////////
/**
* Returns the session machine object associated with the this machine.
* The returned session machine is null if no direct session is currently open.
*
* @Note locks this object for reading.
*/
{
AutoCaller autoCaller (this);
/* the machine may be inaccessible, so don't assert below */
return sm;
AutoReaderLock alock (this);
return sm;
}
/**
* Calculates the absolute path of the given path taking the directory of
* the machine settings file as the current directory.
*
* @param aPath path to calculate the absolute path for
* @param aResult where to put the result (used only on success,
* so can be the same Utf8Str instance as passed as \a aPath)
* @return VirtualBox result
*
* @note Locks this object for reading.
*/
{
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
char folder [RTPATH_MAX];
if (VBOX_SUCCESS (vrc))
return vrc;
}
/**
* Tries to calculate the relative path of the given absolute path using the
* directory of the machine 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 Locks this object for reading.
*/
{
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
{
/* 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. */
}
}
/**
* Returns the full path to the machine's log folder in the
* \a aLogFolder argument.
*/
{
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
if (isInOwnDir (&settingsDir))
{
/* Log folder is <Machines>/<VM_Name>/Logs */
}
else
{
/* Log folder is <Machines>/<VM_SnapshotFolder>/Logs */
}
}
/**
* @note Locks mParent and this object for writing,
* calls the client process (outside the lock).
*/
{
AutoCaller autoCaller (this);
/* We need VirtualBox lock because of Progress::notifyComplete() */
if (!mData->mRegistered)
return setError (E_UNEXPECTED,
return setError (E_ACCESSDENIED,
tr ("A session for the machine '%ls' is currently open "
"(or being closed)"),
/* may not be Running */
/* get the sesion PID */
{
/* This machine is awaiting for a spawning session to be opened, so
* reject any other open attempts from processes other than one
* started by #openRemoteSession(). */
LogFlowThisFunc (("mSession.mPid=%d(0x%x)\n",
return setError (E_ACCESSDENIED,
tr ("An unexpected process (PID=0x%08X) has tried to open a direct "
"session with the machine named '%ls', while only a process "
"started by OpenRemoteSession (PID=0x%08X) is allowed"),
}
/* create a SessionMachine object */
AssertComRC (rc);
{
/*
* Set the session state to Spawning to protect against subsequent
* attempts to open a session and to unregister the machine after
* we leave the lock.
*/
/*
* Leave the lock before calling the client process -- it will call
* Machine/SessionMachine methods. Leaving the lock here is quite safe
* because the state is Spawning, so that openRemotesession() and
* openExistingSession() calls will fail. This method, called before we
* enter the lock again, will fail because of the wrong PID.
*
* Note that mData->mSession.mRemoteControls accessed outside
* the lock may not be modified when state is Spawning, so it's safe.
*/
LogFlowThisFunc (("Calling AssignMachine()...\n"));
/* The failure may w/o any error info (from RPC), so provide one */
tr ("Failed to assign the machine to the session"));
{
/* complete the remote session initialization */
/* get the console from the direct session */
ComAssertComRC (rc);
{
}
/* assign machine & console to the remote sesion */
{
/*
* after openRemoteSession(), the first and the only
* entry in remoteControls is that remote session
*/
LogFlowThisFunc (("Calling AssignRemoteMachine()...\n"));
/* The failure may w/o any error info (from RPC), so provide one */
tr ("Failed to assign the machine to the remote session"));
}
aControl->Uninitialize();
}
/* enter the lock again */
/* Restore the session state */
}
/* finalize spawning amyway (this is why we don't return on errors above) */
{
/* Note that the progress object is finalized later */
/* We don't reset mSession.mPid and mType here because both are
* necessary for SessionMachine::uninit() to reap the child process
* later. */
{
/* Remove the remote control from the list on failure
* and reset session state to Closed. */
}
}
else
{
/* memorize PID of the directly opened session */
}
{
/* memorize the direct session control */
/* associate the SessionMachine with this Machine */
}
{
/* finalize the progress after setting the state, for consistency */
}
/* uninitialize the created session machine on failure */
sessionMachine->uninit();
return rc;
}
/**
* @note Locks this object for writing, calls the client process
* (inside the lock).
*/
{
AutoCaller autoCaller (this);
if (!mData->mRegistered)
return setError (E_UNEXPECTED,
return setError (E_ACCESSDENIED,
tr ("A session for the machine '%ls' is currently open "
"(or being opened or closed)"),
/* may not be Running */
/* get the path to the executable */
char path [RTPATH_MAX];
int vrc = VINF_SUCCESS;
if (type == "gui")
{
}
else
#ifdef VBOX_VRDP
if (type == "vrdp")
{
}
else
#endif /* VBOX_VRDP */
if (type == "capture")
{
}
else
{
return setError (E_INVALIDARG,
}
if (VBOX_FAILURE (vrc))
tr ("Could not launch a process for the machine '%ls' (%Vrc)"),
/*
* Note that we don't leave the lock here before calling the client,
* because it doesn't need to call us back if called with a NULL argument.
* Leaving the lock herer is dangerous because we didn't prepare the
* launch data yet, but the client we've just started may happen to be
* too fast and call openSession() that will fail (because of PID, etc.),
* so that the Machine will never get out of the Spawning session state.
*/
/* inform the session that it will be a remote one */
LogFlowThisFunc (("Calling AssignMachine (NULL)...\n"));
{
/* restore the session state */
/* The failure may w/o any error info (from RPC), so provide one */
tr ("Failed to assign the machine to the session"));
}
/* attach launch data to the machine */
return S_OK;
}
/**
* @note Locks this object for writing, calls the client process
* (outside the lock).
*/
{
AutoCaller autoCaller (this);
if (!mData->mRegistered)
return setError (E_UNEXPECTED,
return setError (E_ACCESSDENIED,
tr ("The machine '%ls' does not have an open session"),
/*
* Get the console from the direct session (note that we don't leave the
* lock here because GetRemoteConsole must not call us back).
*/
{
/* The failure may w/o any error info (from RPC), so provide one */
tr ("Failed to get a console object from the direct session"));
}
/*
* Leave the lock before calling the client process. It's safe here
* since the only thing to do after we get the lock again is to add
* the remote control to the list (which doesn't directly influence
* anything).
*/
/* attach the remote session to the machine */
LogFlowThisFunc (("Calling AssignRemoteMachine()...\n"));
/* The failure may w/o any error info (from RPC), so provide one */
tr ("Failed to assign the machine to the session"));
/* need to revalidate the state after entering the lock again */
{
aControl->Uninitialize();
return setError (E_ACCESSDENIED,
tr ("The machine '%ls' does not have an open session"),
}
/* store the control in the list */
return S_OK;
}
/**
* Checks that the registered flag of the machine can be set according to
* the argument and sets it. On success, commits and saves all settings.
*
* @note When this machine is inaccessible, the only valid value for \a
* aRegistered is FALSE (i.e. unregister the machine) because unregistered
* inaccessible machines are not currently supported. Note that unregistering
* an inaccessible machine will \b uninitialize this machine object. Therefore,
* the caller must make sure there are no active Machine::addCaller() calls
* on the current thread because this will block Machine::uninit().
*
* @note Locks this object and children for writing!
*/
{
AutoLimitedCaller autoCaller (this);
if (!mData->mAccessible)
{
/* A special case: the machine is not accessible. */
/* inaccessible machines can only be unregistered */
/* Uninitialize ourselves here because currently there may be no
* unregistered that are inaccessible (this state combination is not
* supported). Note releasing the caller and leaving the lock before
* calling uninit() */
uninit();
return S_OK;
}
if (aRegistered)
{
if (mData->mRegistered)
tr ("The machine '%ls' with UUID {%s} is already registered"),
}
else
{
tr ("Cannot unregister the machine '%ls' because it "
"is in the Saved state"),
size_t snapshotCount = 0;
if (mData->mFirstSnapshot)
if (snapshotCount)
tr ("Cannot unregister the machine '%ls' because it "
"has %d snapshots"),
tr ("Cannot unregister the machine '%ls' because it has an "
"open session"),
tr ("Cannot unregister the machine '%ls' because it "
"has %d hard disks attached"),
}
/* Ensure the settings are saved. If we are going to be registered and
* isConfigLocked() is FALSE then it means that no config file exists yet,
* so create it. */
{
}
return S_OK;
}
// protected methods
/////////////////////////////////////////////////////////////////////////////
/**
* Helper to uninitialize all associated child objects
* and to free all data structures.
*
* This method must be called as a part of the object's uninitialization
* procedure (usually done in the uninit() method).
*
* @note Must be called only from uninit().
*/
void Machine::uninitDataAndChildObjects()
{
AutoCaller autoCaller (this);
/* tell all our child objects we've been uninitialized */
/*
* uninit all children using addDependentChild()/removeDependentChild()
* in their init()/uninit() methods
*/
{
if (mNetworkAdapters [slot])
{
}
}
if (mUSBController)
{
mUSBController->uninit();
}
if (mAudioAdapter)
{
mAudioAdapter->uninit();
}
if (mFloppyDrive)
{
mFloppyDrive->uninit();
}
if (mDVDDrive)
{
}
#ifdef VBOX_VRDP
if (mVRDPServer)
{
mVRDPServer->uninit();
}
#endif
if (mBIOSSettings)
{
mBIOSSettings->uninit();
}
/* free data structures */
}
/**
* Helper to change the machine state.
*
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller (this);
{
}
return S_OK;
}
/**
* Searches for a shared folder with the given logical name
* in the collection of shared folders.
*
* @param aName logical name of the shared folder
* @param aSharedFolder where to return the found object
* @param aSetError whether to set the error info if the folder is
* not found
* @return
* S_OK when found or E_INVALIDARG when not found
*
* @note
* must be called from under the object's lock!
*/
bool aSetError /* = false */)
{
bool found = false;
++ it)
{
if (found)
aSharedFolder = *it;
}
return rc;
}
/**
* Loads all the VM settings by walking down the <Machine> node.
*
* @param aRegistered true when the machine is being loaded on VirtualBox
* startup
*
* @note This method is intended to be called only from init(), so it assumes
* all machine data fields have appropriate default values when it is called.
*
* @note Doesn't lock any objects.
*/
{
AutoCaller autoCaller (this);
char *loaderError = NULL;
XmlSchemaNS, true, cfgLdrEntityResolver,
&loaderError);
if (VBOX_FAILURE (vrc))
{
tr ("Could not load the settings file '%ls' (%Vrc)%s%s"),
if (loaderError)
return rc;
}
/*
* When reading the XML, we assume it has been validated, so we don't
* do any structural checks here, Just Assert() some things.
*/
CFGNODE machineNode = 0;
do
{
/* uuid (required) */
/* If the stored UUID is not empty, it means the registered machine
* is being loaded. Compare the loaded UUID with the stored one taken
* from the global registry. */
{
{
tr ("Machine UUID {%Vuuid} in '%ls' doesn't match its "
"UUID {%s} in the registry file '%ls'"),
break;
}
}
else
/* name (required) */
/* nameSync (optional, default is true) */
{
bool nameSync = true;
}
/* Description (optional, default is null) */
{
if (descNode)
{
}
else
}
/* OSType (required) */
{
/* look up the object in our list */
break;
}
/* stateFile (optional) */
{
if (stateFilePath)
{
if (VBOX_FAILURE (vrc))
{
tr ("Invalid saved state file path: '%ls' (%Vrc)"),
break;
}
}
else
}
/*
* currentSnapshot ID (optional)
* Note that due to XML Schema constaraints this attribute, when present,
* will guaranteedly refer to an existing snapshot definition in XML
*/
/* snapshotFolder (optional) */
{
break;
}
/* lastStateChange (optional, for compatiblity) */
{
int64_t lastStateChange = 0;
if (lastStateChange == 0)
{
/// @todo (dmik) until lastStateChange is the required attribute,
// we simply set it to the current time if missing in the config
}
}
/* aborted (optional) */
bool aborted = false;
/* currentStateModified (optional, default is true) */
{
bool val = true;
}
/*
* note: all mUserData members must be assigned prior this point because
* we need to commit changes in order to let mUserData be shared by all
* snapshot machine instances.
*/
/* Snapshot node (optional) */
{
CFGNODE snapshotNode = 0;
if (snapshotNode)
{
/* read all snapshots recursively */
break;
}
}
/* Hardware node (required) */
{
CFGNODE hardwareNode = 0;
break;
}
/* HardDiskAttachments node (required) */
{
break;
}
/*
* NOTE: the assignment below must be the last thing to do,
* otherwise it will be not possible to change the settings
* somewehere in the code above because all setters will be
* blocked by CHECK_SETTER()
*/
/* set the machine state to Aborted or Saved when appropriate */
if (aborted)
{
}
else if (mSSData->mStateFilePath)
{
}
}
while (0);
if (machineNode)
return rc;
}
/**
* Recursively loads all snapshots starting from the given.
*
* @param aNode <Snapshot> node
* @param aCurSnapshotId current snapshot ID from the settings file
* @param aParentSnapshot parent snapshot
*/
{
// create a snapshot machine object
if (stateFilePath)
{
if (VBOX_FAILURE (vrc))
tr ("Invalid saved state file path: '%ls' (%Vrc)"),
}
do
{
// Hardware node (required)
CFGNODE hardwareNode = 0;
do
{
// HardDiskAttachments node (required)
// initialize the snapshot machine
}
while (0);
}
while (0);
return rc;
// create a snapshot object
{
{
if (descNode)
{
}
}
// initialize the snapshot
return rc;
}
// memorize the first snapshot if necessary
if (!mData->mFirstSnapshot)
// memorize the current snapshot when appropriate
// Snapshots node (optional)
{
CFGNODE snapshotsNode = 0;
if (snapshotsNode)
{
unsigned cbDisks = 0;
{
}
}
}
return rc;
}
/**
* @param aNode <Hardware> node
*/
{
/* CPU node (currently not required) */
{
/* default value in case the node is not there */
if (cpuNode)
{
CFGNODE hwVirtExNode = 0;
if (hwVirtExNode)
{
if (hwVirtExEnabled == L"false")
else if (hwVirtExEnabled == L"true")
else
}
}
}
/* Memory node (required) */
{
CFGNODE memoryNode = 0;
}
/* Boot node (required) */
{
/* reset all boot order positions to NoDevice */
unsigned cOrder;
for (unsigned i = 0; i < cOrder; i++)
{
/* position (required) */
/* position unicity is guaranteed by XML Schema */
-- position;
/* device (required) */
if (device == L"None")
else if (device == L"Floppy")
else if (device == L"DVD")
else if (device == L"HardDisk")
else if (device == L"Network")
else
}
return rc;
}
/* Display node (required) */
{
CFGNODE displayNode = 0;
}
#ifdef VBOX_VRDP
/* RemoteDisplay node (optional) */
/// @todo (dmik) move the code to VRDPServer
/// @todo r=sunlover: moved. dmik, please review.
{
CFGNODE remoteDisplayNode = 0;
if (remoteDisplayNode)
{
}
}
#endif
/* BIOS node (required) */
{
do
{
/* ACPI */
{
bool enabled;
}
/* IOAPIC */
{
CFGNODE ioapicNode = 0;
if (ioapicNode)
{
bool enabled;
}
}
/* Logo (optional) */
{
if (logoNode)
{
bool enabled = false;
}
}
/* boot menu (optional) */
{
CFGNODE bootMenuNode = 0;
if (bootMenuNode)
{
if (modeStr == L"disabled")
else if (modeStr == L"menuonly")
else
}
}
}
while (0);
return rc;
}
/* DVD drive (contains either Image or HostDrive or nothing) */
/// @todo (dmik) move the code to DVDDrive
{
CFGNODE dvdDriveNode = 0;
bool fPassthrough;
do
{
if (typeNode)
{
}
else
{
if (typeNode)
{
/* find the correspoding object */
else if (rc == E_INVALIDARG)
{
/* the host DVD drive is not currently available. we
* assume it will be available later and create an
* extra object now */
}
else
}
}
}
while (0);
if (typeNode)
return rc;
}
/* Floppy drive (contains either Image or HostDrive or nothing) */
/// @todo (dmik) move the code to FloppyDrive
{
do
{
if (typeNode)
{
}
else
{
if (typeNode)
{
/* find the correspoding object */
else if (rc == E_INVALIDARG)
{
/* the host Floppy drive is not currently available. we
* assume it will be available later and create an
* extra object now */
}
else
}
}
}
while (0);
if (typeNode)
return rc;
}
/* USB Controller */
{
return rc;
}
/* Network node (required) */
/// @todo (dmik) move the code to NetworkAdapter
{
/* we assume that all network adapters are initially disabled
* and detached */
CFGNODE networkNode = 0;
unsigned cAdapters = 0;
for (unsigned i = 0; i < cAdapters; i++)
{
CFGNODE adapterNode = 0;
/* slot number (required) */
/* slot unicity is guaranteed by XML Schema */
/* type */
/* enabled (required) */
bool enabled = false;
/* MAC address (can be null) */
/* cable (required) */
bool cableConnected;
/* tracing (defaults to false) */
bool traceEnabled;
else
CFGNODE attachmentNode = 0;
{
}
else
{
/* Host Interface Networking */
#ifdef __WIN__
/* @name can be empty on Win32, but not null */
#endif
#endif // VBOX_WITH_UNIXY_TAP_NETWORKING
}
else
{
/* Internal Networking */
}
else
{
/* Adapter has no children */
}
if (attachmentNode)
}
return rc;
}
/* AudioAdapter node (required) */
/// @todo (dmik) move the code to AudioAdapter
{
CFGNODE audioAdapterNode = 0;
// is the adapter enabled?
bool enabled = false;
// now check the audio driver
if (driver == L"null")
; // Null has been set above
#ifdef __WIN__
else if (driver == L"winmm")
#ifdef VBOX_WITH_WINMM
#else
// fall back to dsound
#endif
else if (driver == L"dsound")
#endif // __WIN__
#ifdef __LINUX__
else if (driver == L"oss")
else if (driver == L"alsa")
#ifdef VBOX_WITH_ALSA
#else
// fall back to OSS
#endif
#endif // __LINUX__
else
}
/* Shared folders (optional) */
/// @todo (dmik) make required on next format change!
do
{
CFGNODE sharedFoldersNode = 0;
if (!sharedFoldersNode)
break;
unsigned cFolders = 0;
for (unsigned i = 0; i < cFolders; i++)
{
CFGNODE folderNode = 0;
// folder logical name (required)
// folder host path (required)
break;
}
return rc;
}
while (0);
/* Clipboard node (currently not required) */
/// @todo (dmik) make required on next format change!
{
/* default value in case the node is not there */
if (clipNode)
{
if (mode == L"Disabled")
else if (mode == L"HostToGuest")
else if (mode == L"GuestToHost")
else if (mode == L"Bidirectional")
else
}
}
return S_OK;
}
/**
* @param aNode <HardDiskAttachments> node
* @param aRegistered true when the machine is being loaded on VirtualBox
* startup, or when a snapshot is being loaded (wchich
* currently can happen on startup only)
* @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
*/
{
unsigned cbDisks = 0;
if (!aRegistered && cbDisks > 0)
{
/* when the machine is being loaded (opened) from a file, it cannot
* have hard disks attached (this should not happen normally,
* because we don't allow to attach hard disks to an unregistered
* VM at all */
tr ("Unregistered machine '%ls' cannot have hard disks attached "
"(found %d hard disk attachments)"),
}
{
do
{
/* hardDisk uuid (required) */
/* bus (controller) type (required) */
/* device (required) */
/* find a hard disk by UUID */
break;
{
tr ("Hard disk '%ls' with UUID {%s} is already "
"attached to a machine with UUID {%s} (see '%ls')"),
break;
}
{
tr ("Immutable hard disk '%ls' with UUID {%s} cannot be "
"directly attached to a machine (see '%ls')"),
break;
}
/* attach the device */
if (bus == L"ide0")
{
if (device == L"master")
dev = 0;
else if (device == L"slave")
dev = 1;
else
}
else if (bus == L"ide1")
{
if (device == L"master")
"device on the secondary controller"));
else if (device == L"slave")
dev = 1;
else
}
else
break;
/* associate the hard disk with this machine */
/* associate the hard disk with the given snapshot ID */
if (mType == IsSnapshotMachine)
}
while (0);
}
return rc;
}
/**
* Creates a config loader and loads the settings file.
*
* @param aIsNew |true| if a newly created settings file is to be opened
* (must be the case only when called from #saveSettings())
*
* @note
* XML Schema errors are not detected by this method because
* it assumes that it will load settings from an exclusively locked
* file (using a file handle) that was previously validated when opened
* for the first time. Thus, this method should be used only when
* it's necessary to modify (save) the settings file.
*
* @note The object must be locked at least for reading before calling
* this method.
*/
{
/* The settings file must be created and locked at this point */
/* load the config file */
NULL);
return S_OK;
}
/**
* Closes the config loader previously created by #openConfigLoader().
* If \a aSaveBeforeClose is true, then the config is saved to the settings file
* before closing. If saving fails, a proper error message is set.
*
* @param aSaveBeforeClose whether to save the config before closing or not
*/
{
if (aSaveBeforeClose)
{
char *loaderError = NULL;
if (VBOX_FAILURE (vrc))
{
tr ("Could not save the settings file '%ls' (%Vrc)%s%s"),
if (loaderError)
}
}
return rc;
}
/**
* Searches for a <Snapshot> node for the given snapshot.
* If the search is successful, \a aSnapshotNode will contain the found node.
* In this case, \a aSnapshotsNode can be NULL meaning the found node is a
* direct child of \a aMachineNode.
*
* If the search fails, a failure is returned and both \a aSnapshotsNode and
* \a aSnapshotNode are set to 0.
*
* @param aSnapshot snapshot to search for
* @param aMachineNode <Machine> node to start from
* @param aSnapshotsNode <Snapshots> node containing the found <Snapshot> node
* (may be NULL if the caller is not interested)
* @param aSnapshotNode found <Snapshot> node
*/
{
if (aSnapshotsNode)
*aSnapshotsNode = 0;
*aSnapshotNode = 0;
// build the full uuid path (from the fist parent to the given snapshot)
{
while (parent)
{
}
}
CFGNODE snapshotNode = 0;
++ it)
{
if (snapshotNode)
{
// proceed to the nested <Snapshots> node
if (snapshotsNode != aMachineNode)
{
snapshotsNode = 0;
}
snapshotNode = 0;
}
unsigned count = 0, i = 0;
for (; i < count; ++ i)
{
snapshotNode = 0;
{
// we keep (don't release) snapshotNode and snapshotsNode
break;
}
snapshotNode = 0;
}
if (i == count)
{
// the next uuid is not found, no need to continue...
AssertFailed();
if (snapshotsNode != aMachineNode)
{
snapshotsNode = 0;
}
break;
}
}
// we must always succesfully find the node
if (aSnapshotsNode)
return S_OK;
}
/**
* Returns the snapshot with the given UUID or fails of no such snapshot.
*
* @param aId snapshot UUID to find (empty UUID refers the first snapshot)
* @param aSnapshot where to return the found snapshot
* @param aSetError true to set extended error info on failure
*/
bool aSetError /* = false */)
{
if (!mData->mFirstSnapshot)
{
if (aSetError)
tr ("This machine does not have any snapshots"));
return E_FAIL;
}
else
if (!aSnapshot)
{
if (aSetError)
tr ("Could not find a snapshot with UUID {%s}"),
return E_FAIL;
}
return S_OK;
}
/**
* Returns the snapshot with the given name or fails of no such snapshot.
*
* @param aName snapshot name to find
* @param aSnapshot where to return the found snapshot
* @param aSetError true to set extended error info on failure
*/
bool aSetError /* = false */)
{
if (!mData->mFirstSnapshot)
{
if (aSetError)
tr ("This machine does not have any snapshots"));
return E_FAIL;
}
if (!aSnapshot)
{
if (aSetError)
return E_FAIL;
}
return S_OK;
}
/**
* Searches for an attachment that contains the given hard disk.
* The hard disk must be associated with some VM and can be optionally
* associated with some snapshot. If the attachment is stored in the snapshot
* (i.e. the hard disk is associated with some snapshot), @a aSnapshot
* will point to a non-null object on output.
*
* @param aHd hard disk to search an attachment for
* @param aMachine where to store the hard disk's machine (can be NULL)
* @param aSnapshot where to store the hard disk's snapshot (can be NULL)
* @param aHda where to store the hard disk's attachment (can be NULL)
*
*
* @note
* It is assumed that the machine where the attachment is found,
* is already placed to the Discarding state, when this method is called.
* @note
* The object returned in @a aHda is the attachment from the snapshot
* machine if the hard disk is associated with the snapshot, not from the
* primary machine object returned returned in @a aMachine.
*/
{
{
m->findSnapshot (sid, s);
}
++ it)
{
{
return S_OK;
}
}
return E_FAIL;
}
/**
* Helper for #saveSettings. Cares about renaming the settings directory and
* file if the machine name was changed and about creating a new settings file
* if this is a new machine.
*
* @note Must be never called directly.
*
* @param aRenamed receives |true| if the name was changed and the settings
* file was renamed as a result, or |false| otherwise. The
* value makes sense only on success.
* @param aNew receives |true| if a virgin settings file was created.
*/
{
aRenamed = false;
/* if we're ready and isConfigLocked() is FALSE then it means
* that no config file exists yet (we will create a virgin one) */
aNew = !isConfigLocked();
/* attempt to rename the settings file if machine name is changed */
mUserData.isBackedUp() &&
{
aRenamed = true;
if (!aNew)
{
/* unlock the old config file */
rc = unlockConfig();
}
bool dirRenamed = false;
bool fileRenamed = false;
do
{
int vrc = VINF_SUCCESS;
/* first, rename the directory if it matches the machine name */
{
/* new dir and old dir cannot be equal here because of 'if'
* above and because name != newName */
if (!aNew)
{
/* perform real rename only if the machine is not new */
if (VBOX_FAILURE (vrc))
{
tr ("Could not rename the directory '%s' to '%s' "
"to save the settings file (%Vrc)"),
break;
}
dirRenamed = true;
}
}
/* then try to rename the settings file itself */
if (newConfigFile != configFile)
{
/* get the path to old settings file in renamed directory */
if (!aNew)
{
/* perform real rename only if the machine is not new */
if (VBOX_FAILURE (vrc))
{
tr ("Could not rename the settings file '%s' to '%s' "
"(%Vrc)"),
break;
}
fileRenamed = true;
}
}
/* update mConfigFileFull amd mConfigFile */
/* try to get the relative path for mConfigFile */
/* last, try to update the global settings with the new path */
if (mData->mRegistered)
{
{
/* revert to old values */
break;
}
}
/* update the snapshot folder */
{
}
/* update the saved state file path */
{
}
/* Update saved state file paths of all online snapshots.
* Note that saveSettings() will recognize name change
* and will save all snapshots in this case. */
if (mData->mFirstSnapshot)
}
while (0);
{
/* silently try to rename everything back */
if (fileRenamed)
if (dirRenamed)
}
if (!aNew)
{
/* lock the config again */
}
}
if (aNew)
{
/* create a virgin config file */
int vrc = VINF_SUCCESS;
/* ensure the settings directory exists */
if (!RTDirExists (path))
{
if (VBOX_FAILURE (vrc))
{
tr ("Could not create a directory '%s' "
"to save the settings file (%Vrc)"),
}
}
/* Note: open flags must correlated with RTFileOpen() in lockConfig() */
if (VBOX_SUCCESS (vrc))
{
(void *) DefaultMachineConfig,
sizeof (DefaultMachineConfig), NULL);
}
if (VBOX_FAILURE (vrc))
{
tr ("Could not create the settings file '%s' (%Vrc)"),
}
/* we do not close the file to simulate lockConfig() */
}
return rc;
}
/**
* Saves machine data, user data and hardware data.
*
* @param aMarkCurStateAsModified
* if true (default), mData->mCurrentStateModified will be set to
* what #isReallyModified() returns prior to saving settings to a file,
* otherwise the current value of mData->mCurrentStateModified will be
* saved.
* @param aInformCallbacksAnyway
* if true, callbacks will be informed even if #isReallyModified()
* returns false. This is necessary for cases when we change machine data
* diectly, not through the backup()/commit() mechanism.
*
* @note Locks mParent (only in some cases, and only when #isConfigLocked() is
* |TRUE|, see the #prepareSaveSettings() code for details) +
* this object + children for writing.
*/
bool aInformCallbacksAnyway /* = false */)
{
/// @todo (dmik) I guess we should lock all our child objects here
// (such as mVRDPServer etc.) to ensure they are not changed
// until completely saved to disk and committed
/// @todo (dmik) also, we need to delegate saving child objects' settings
// to objects themselves to ensure operations 'commit + save changes'
// are atomic (amd done from the object's lock so that nobody can change
// settings again until completely saved).
bool wasModified;
{
/*
* We ignore changes to user data when setting mCurrentStateModified
* because the current state will not differ from the current snapshot
* if only user data has been changed (user data is shared by all
* snapshots).
*/
}
else
{
}
/* First, prepare to save settings. It will will care about renaming the
* settings directory and file if the machine name was changed and about
* creating a new settings file if this is a new machine. */
bool isRenamed = false;
bool isNew = false;
/* then, open the settings file */
CFGHANDLE configLoader = 0;
/* save all snapshots when the machine name was changed since
* it may affect saved state file paths for online snapshots (see
* #openConfigLoader() for details) */
bool updateAllSnapshots = isRenamed;
/* commit before saving, since it may change settings
* (for example, perform fixup of lazy hard disk changes) */
{
return rc;
}
/* include hard disk changes to the modified flag */
CFGNODE machineNode = 0;
/* create if not exists */
do
{
/* uuid (required) */
/* name (required) */
/* nameSync (optional, default is true) */
else
/* Description node (optional) */
{
}
else
{
if (descNode)
}
/* OSType (required) */
{
}
/* stateFile (optional) */
{
/* try to make the file name relative to the settings file dir */
}
else
{
}
/* currentSnapshot ID (optional) */
{
}
else
{
}
/* snapshotFolder (optional) */
if (mUserData->mSnapshotFolder)
else
/* currentStateModified (optional, default is yes) */
if (!mData->mCurrentStateModified)
else
/* lastStateChange */
/* Hardware node (required) */
{
/* first, delete the entire node if exists */
if (hwNode)
/* then recreate it */
hwNode = 0;
break;
}
/* HardDiskAttachments node (required) */
{
/* first, delete the entire node if exists */
if (hdasNode)
/* then recreate it */
hdasNode = 0;
break;
}
/* update all snapshots if requested */
if (updateAllSnapshots)
}
while (0);
if (machineNode)
else
{
/*
* backup arbitrary data item to cause #isModified() to still return
* true in case of any error
*/
}
if (wasModified || aInformCallbacksAnyway)
{
/*
* Fire the data change event, even on failure (since we've already
* committed all data). This is done only for SessionMachines because
* mutable Machine instances are always not registered (i.e. private
* to the client process that creates them) and thus don't need to
* inform callbacks.
*/
if (mType == IsSessionMachine)
}
return rc;
}
/**
* Wrapper for #saveSnapshotSettingsWorker() that opens the settings file
* and locates the <Machine> node in there. See #saveSnapshotSettingsWorker()
* for more details.
*
* @param aSnapshot Snapshot to operate on
* @param aOpFlags Operation to perform, one of SaveSS_NoOp, SaveSS_AddOp
* or SaveSS_UpdateAttrsOp possibly combined with
* SaveSS_UpdateCurrentId.
*
* @note Locks this object for writing + other child objects.
*/
{
AutoCaller autoCaller (this);
/* load the config file */
CFGHANDLE configLoader = 0;
return rc;
CFGNODE machineNode = 0;
do
{
}
while (0);
else
return rc;
}
/**
* Performs the specified operation on the given snapshot
* in the settings file represented by \a aMachineNode.
*
* If \a aOpFlags = SaveSS_UpdateAllOp, \a aSnapshot can be NULL to indicate
* that the whole tree of the snapshots should be updated in <Machine>.
* One particular case is when the last (and the only) snapshot should be
* removed (it is so when both mCurrentSnapshot and mFirstSnapshot are NULL).
*
* \a aOp may be just SaveSS_UpdateCurrentId if only the currentSnapshot
* attribute of <Machine> needs to be updated.
*
* @param aMachineNode <Machine> node in the opened settings file
* @param aSnapshot Snapshot to operate on
* @param aOpFlags Operation to perform, one of SaveSS_NoOp, SaveSS_AddOp
* or SaveSS_UpdateAttrsOp possibly combined with
* SaveSS_UpdateCurrentId.
*
* @note Must be called with this object locked for writing.
* Locks child objects.
*/
{
op == SaveSS_UpdateAllOp)) ||
op == SaveSS_UpdateAllOp)),
E_FAIL);
bool recreateWholeTree = false;
do
{
if (op == SaveSS_NoOp)
break;
/* quick path: recreate the whole tree of the snapshots */
{
/* first, delete the entire root snapshot node if it exists */
CFGNODE snapshotNode = 0;
if (snapshotNode)
/*
* second, if we have any snapshots left, substitute aSnapshot with
* the first snapshot to recreate the whole tree, otherwise break
*/
if (mData->mFirstSnapshot)
{
recreateWholeTree = true;
}
else
break;
}
if (op == SaveSS_AddOp)
{
CFGNODE parentNode = 0;
if (parent)
{
break;
}
do
{
CFGNODE snapshotsNode = 0;
if (parentNode)
{
}
else
do
{
CFGNODE snapshotNode = 0;
break;
/*
* when a new snapshot is added, this means diffs were created
* save the current hard disk attachments
*/
if (hdasNode)
{
/*
* If we have one or more attachments then we definitely
* created diffs for them and associated new diffs with
* current settngs. So, since we don't use saveSettings(),
* we need to inform callbacks manually.
*/
if (mType == IsSessionMachine)
}
}
while (0);
if (snapshotsNode != aMachineNode)
}
while (0);
if (parentNode)
break;
}
op == SaveSS_UpdateAllOp);
CFGNODE snapshotsNode = 0;
CFGNODE snapshotNode = 0;
if (!recreateWholeTree)
{
break;
}
if (!snapshotsNode)
if (op == SaveSS_UpdateAttrsOp)
else do
{
if (snapshotNode)
{
snapshotNode = 0;
}
}
while (0);
if (snapshotsNode != aMachineNode)
}
while (0);
{
/* update currentSnapshot when appropriate */
if (aOpFlags & SaveSS_UpdateCurrentId)
{
else
}
{
if (!mData->mCurrentStateModified)
else
}
}
return rc;
}
/**
* Saves the given snapshot and all its children (unless \a aAttrsOnly is true).
* It is assumed that the given node is empty (unless \a aAttrsOnly is true).
*
* @param aNode <Snapshot> node to save the snapshot to
* @param aSnapshot snapshot to save
* @param aAttrsOnly if true, only updatge user-changeable attrs
*/
{
/* uuid (required) */
if (!aAttrsOnly)
/* name (required) */
/* timeStamp (required) */
/* Description node (optional) */
{
}
else
{
if (descNode)
}
if (aAttrsOnly)
return S_OK;
/* stateFile (optional) */
if (aSnapshot->stateFilePath())
{
/* try to make the file name relative to the settings file dir */
}
{
/* save hardware */
{
return rc;
}
/* save hard disks */
{
return rc;
}
}
/* save children */
{
{
CFGNODE snapshotsNode = 0;
++ it)
{
CFGNODE snapshotNode = 0;
}
return rc;
}
}
return S_OK;
}
/**
* Creates Saves the VM hardware configuration.
* It is assumed that the given node is empty.
*
* @param aNode <Hardware> node to save the VM hardware confguration to
*/
{
/* CPU */
{
CFGNODE hwVirtExNode = 0;
switch (mHWData->mHWVirtExEnabled)
{
case TriStateBool_False:
value = "false";
break;
case TriStateBool_True:
value = "true";
break;
default:
value = "default";
}
}
/* memory (required) */
{
CFGNODE memoryNode = 0;
}
/* boot (required) */
do
{
{
{
case DeviceType_NoDevice:
/* skip, this is allowed for <Order> nodes
* when loading, the default value NoDevice will remain */
continue;
default:
ComAssertMsgFailedBreak (("Invalid boot device: %d\n",
}
break;
}
}
while (0);
return rc;
/* display (required) */
{
CFGNODE displayNode = 0;
}
#ifdef VBOX_VRDP
/* VRDP settings (optional) */
/// @todo (dmik) move the code to VRDPServer
/// @todo r=sunlover: moved. dmik, please review.
{
CFGNODE remoteDisplayNode = 0;
if (remoteDisplayNode)
{
}
}
#endif
/* BIOS (required) */
{
{
/* ACPI */
/* IOAPIC */
CFGNODE ioapicNode = 0;
/* BIOS logo (optional) **/
if (logoPath)
else
/* boot menu (optional) */
CFGNODE bootMenuNode = 0;
switch (bootMenuMode)
{
bootMenuModeStr = "disabled";
break;
bootMenuModeStr = "menuonly";
break;
default:
bootMenuModeStr = "messageandmenu";
}
}
}
/* DVD drive (required) */
/// @todo (dmik) move the code to DVDDrive
do
{
{
case DriveState_ImageMounted:
{
break;
}
{
CFGNODE hostDriveNode = 0;
break;
}
case DriveState_NotMounted:
/* do nothing, i.e.leave the DVD drive node empty */
break;
default:
ComAssertMsgFailedBreak (("Invalid DVD drive state: %d\n",
}
}
while (0);
return rc;
/* Flooppy drive (required) */
/// @todo (dmik) move the code to DVDDrive
do
{
CFGNODE floppyNode = 0;
{
case DriveState_ImageMounted:
{
break;
}
{
CFGNODE hostDriveNode = 0;
break;
}
case DriveState_NotMounted:
/* do nothing, i.e.leave the Floppy drive node empty */
break;
default:
ComAssertMsgFailedBreak (("Invalid Floppy drive state: %d\n",
}
}
while (0);
return rc;
/* USB Controller (required) */
return rc;
/* Network adapters (required) */
do
{
{
{
break;
break;
default:
ComAssertMsgFailedBreak (("Invalid network adapter type: %d\n",
}
CFGNODE attachmentNode = 0;
{
{
/* do nothing -- empty content */
break;
}
{
break;
}
{
#ifdef __WIN__
#endif
#endif
const Bstr &tapSetupApp =
if (!tapSetupApp.isEmpty())
const Bstr &tapTerminateApp =
if (!tapTerminateApp.isEmpty())
#endif /* VBOX_WITH_UNIXY_TAP_NETWORKING */
break;
}
{
break;
}
default:
{
break;
}
}
if (attachmentNode)
}
}
while (0);
return rc;
/* Audio adapter */
do
{
CFGNODE adapterNode = 0;
{
{
break;
}
#ifdef __WIN__
#ifdef VBOX_WITH_WINMM
{
break;
}
#endif
{
break;
}
#endif /* __WIN__ */
#ifdef VBOX_WITH_ALSA
{
break;
}
#endif
#ifdef __LINUX__
{
break;
}
#endif /* __LINUX__ */
default:
ComAssertMsgFailedBreak (("Wrong audio driver type! driver = %d\n",
}
}
while (0);
return rc;
/* Shared folders */
do
{
CFGNODE sharedFoldersNode = 0;
++ it)
{
CFGNODE folderNode = 0;
/* all are mandatory */
}
}
while (0);
/* Clipboard */
{
char *mode = "Disabled";
switch (mHWData->mClipboardMode)
{
/* already assigned */
break;
mode = "HostToGuest";
break;
mode = "GuestToHost";
break;
mode = "Bidirectional";
break;
default:
AssertMsgFailed (("Clipboard mode %d is invalid",
break;
}
}
return rc;
}
/**
* Saves the hard disk confguration.
* It is assumed that the given node is empty.
*
* @param aNode <HardDiskAttachments> node to save the hard disk confguration to
*/
{
++ it)
{
do
{
switch (att->controller())
{
default:
}
break;
switch (att->deviceNumber())
{
case 0: dev = "master"; break;
default:
}
break;
}
while (0);
}
return rc;
}
/**
* Saves machine state settings as defined by aFlags
* (SaveSTS_* values).
*
* @param aFlags a combination of SaveSTS_* flags
*
* @note Locks objects!
*/
{
if (aFlags == 0)
return S_OK;
AutoCaller autoCaller (this);
/* load the config file */
CFGHANDLE configLoader = 0;
return rc;
CFGNODE machineNode = 0;
do
{
if (aFlags & SaveSTS_CurStateModified)
{
if (!mData->mCurrentStateModified)
else
}
if (aFlags & SaveSTS_StateFilePath)
{
if (mSSData->mStateFilePath)
else
}
if (aFlags & SaveSTS_StateTimeStamp)
{
// set the aborted attribute when appropriate
else
}
}
while (0);
if (machineNode)
else
return rc;
}
/**
* Cleans up all differencing hard disks based on immutable hard disks.
*
* @note Locks objects!
*/
{
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
++ it)
{
if(hd->isParentImmutable())
{
/// @todo (dmik) no error handling for now
// (need async error reporting for this)
}
}
return S_OK;
}
/**
* Fixes up lazy hard disk attachments by creating or deleting differencing
* hard disks when machine settings are being committed.
* Must be called only from #commit().
*
* @note Locks objects!
*/
{
AutoCaller autoCaller (this);
if (!mHDData.isBackedUp())
{
mHDData->mHDAttachmentsChanged = false;
return S_OK;
}
if (aCommit)
{
/*
* changes are being committed,
* perform actual diff image creation, deletion etc.
*/
/* take a copy of backed up attachments (will modify it) */
/* list of new diffs created */
/* go through current attachments */
++ it)
{
{
/*
* not dirty, therefore was either attached before backing up
* or doesn't need any fixup (already fixed up); try to locate
* this hard disk among backed up attachments and remove from
* there to prevent it from being deassociated/deleted
*/
break;
{
/* remove from there */
// LogTraceMsg (("FC: %ls found in old\n", hd->toString().raw()));
}
}
else
{
/* dirty, determine what to do */
bool needDiff = false;
bool searchAmongSnapshots = false;
{
{
/* decrease readers increased in AttachHardDisk() */
hd->releaseReader();
// LogTraceMsg (("FC: %ls released\n", hd->toString().raw()));
/* indicate we need a diff (indirect attachment) */
needDiff = true;
break;
}
{
/* reset the dirty flag */
// LogTraceMsg (("FC: %ls updated\n", hd->toString().raw()));
break;
}
{
{
/* reset the dirty flag */
// LogTraceMsg (("FC: %ls updated\n", hd->toString().raw()));
}
else
{
/* decrease readers increased in AttachHardDisk() */
hd->releaseReader();
// LogTraceMsg (("FC: %ls released\n", hd->toString().raw()));
/* indicate we need a diff (indirect attachment) */
needDiff = true;
/* search for the most recent base among snapshots */
searchAmongSnapshots = true;
}
break;
}
}
if (!needDiff)
continue;
bool createDiff = false;
/*
* see whether any previously attached hard disk has the
* the currently attached one (Normal or Independent) as
* the root
*/
++ it)
{
{
/*
* matched dev and ctl (i.e. attached to the same place)
* will win and immediately stop the search; otherwise
* the first attachment that matched the hd only will
* be used
*/
{
break;
}
else
{
/*
* not an exact match; ensure there is no exact match
* among other current attachments referring the same
* root (to prevent this attachmend from reusing the
* hard disk of the other attachment that will later
* give the exact match or already gave it before)
*/
bool canReuse = true;
++ it2)
{
{
/*
* the exact match, either non-dirty or dirty
* one refers the same root: in both cases
* we cannot reuse the hard disk, so break
*/
canReuse = false;
break;
}
}
if (canReuse)
}
}
}
{
/* found either one or another, reuse the diff */
false /* aDirty */);
// LogTraceMsg (("FC: %ls reused as %ls\n", hd->toString().raw(),
// (*foundIt)->hardDisk()->toString().raw()));
/* remove from there */
}
else
{
/* was not attached, need a diff */
createDiff = true;
}
if (!createDiff)
continue;
if (searchAmongSnapshots)
{
/*
* find the most recent diff based on the currently
* attached root (Normal hard disk) among snapshots
*/
while (snap)
{
{
{
/*
* matched dev and ctl (i.e. attached to the same place)
* will win and immediately stop the search; otherwise
* the first attachment that matched the hd only will
* be used
*/
{
break;
}
else
}
}
{
/* the most recent diff has been found, use as a base */
// LogTraceMsg (("FC: %ls: recent found %ls\n",
// hd->toString().raw(), baseHd->toString().raw()));
break;
}
}
}
/* create a new diff for the hard disk being indirectly attached */
baseHd->releaseReader();
/* update the attachment and reset the dirty flag */
false /* aDirty */);
// LogTraceMsg (("FC: %ls: diff created %ls\n",
// baseHd->toString().raw(), vdi->toString().raw()));
}
}
{
/* delete diffs we created */
{
/*
* unregisterDiffHardDisk() is supposed to delete and uninit
* the differencing hard disk
*/
/* too bad if we fail here, but nothing to do, just continue */
}
/* the best is to rollback the changes... */
mHDData->mHDAttachmentsChanged = false;
// LogTraceMsg (("FC: ROLLED BACK\n"));
return rc;
}
/*
* go through the rest of old attachments and delete diffs
* or deassociate hard disks from machines (they will become detached)
*/
{
if (hd->isDifferencing())
{
/*
* unregisterDiffHardDisk() is supposed to delete and uninit
* the differencing hard disk
*/
// LogTraceMsg (("FC: %ls diff deleted\n", hd->toString().raw()));
/*
* too bad if we fail here, but nothing to do, just continue
* (the last rc will be returned to the caller though)
*/
}
else
{
/* deassociate from this machine */
// LogTraceMsg (("FC: %ls deassociated\n", hd->toString().raw()));
}
}
/* commit all the changes */
// LogTraceMsg (("FC: COMMITTED\n"));
return rc;
}
/*
* changes are being rolled back,
* go trhough all current attachments and fix up dirty ones
* the way it is done in DetachHardDisk()
*/
++ it)
{
{
{
{
/* decrease readers increased in AttachHardDisk() */
hd->releaseReader();
// LogTraceMsg (("FR: %ls released\n", hd->toString().raw()));
break;
}
{
/* deassociate from this machine */
// LogTraceMsg (("FR: %ls deassociated\n", hd->toString().raw()));
break;
}
{
{
/* deassociate from this machine */
// LogTraceMsg (("FR: %ls deassociated\n", hd->toString().raw()));
}
else
{
/* decrease readers increased in AttachHardDisk() */
hd->releaseReader();
// LogTraceMsg (("FR: %ls released\n", hd->toString().raw()));
}
break;
}
}
}
}
/* rollback all the changes */
// LogTraceMsg (("FR: ROLLED BACK\n"));
return S_OK;
}
/**
* Creates differencing hard disks for all normal hard disks
* and replaces attachments to refer to created disks.
* Used when taking a snapshot or when discarding the current state.
*
* @param aSnapshotId ID of the snapshot being taken
* or NULL if the current state is being discarded
* @param aFolder folder where to create diff. hard disks
* @param aProgress progress object to run (must contain at least as
* many operations left as the number of VDIs attached)
* @param aOnline whether the machine is online (i.e., when the EMT
* thread is paused, OR when current hard disks are
* marked as busy for some other reason)
*
* @note
* The progress object is not marked as completed, neither on success
* nor on failure. This is a responsibility of the caller.
*
* @note Locks mParent + this object for writing
*/
bool aOnline)
{
AutoCaller autoCaller (this);
/* accessing mParent methods below needs mParent lock */
// first pass: check accessibility before performing changes
if (!aOnline)
{
++ it)
{
if (!accessError.isNull())
{
tr ("Hard disk '%ls' is not accessible (%ls)"),
break;
}
}
}
// second pass: perform changes
++ it)
{
// clear busy flag if the VM is online
if (aOnline)
// increase readers
if (hd->isParentImmutable())
{
tr ("Preserving immutable hard disk '%ls'"),
// create a copy of the independent diff
parentHdLock.lock();
// decrease readers (hd is no more used for reading in any case)
hd->releaseReader();
}
else
{
// checked in the first pass
tr ("Creating a differencing hard disk for '%ls'"),
// create a new diff for the image being attached
parentHdLock.lock();
{
// if online, hd must keep a reader referece
if (!aOnline)
hd->releaseReader();
}
else
{
// decrease readers
hd->releaseReader();
}
}
{
false /* aDirty */);
{
// associate the snapshot id with the old hard disk
// add the new attachment
// if online, newHd must be marked as busy
if (aOnline)
}
}
{
// set busy flag back if the VM is online
if (aOnline)
break;
}
}
{
// replace the whole list of attachments with the new one
}
else
{
// delete those diffs we've just created
++ it)
{
// unregisterDiffHardDisk() is supposed to delete and uninit
// the differencing hard disk
}
}
return rc;
}
/**
* Deletes differencing hard disks created by createSnapshotDiffs() in case
* if snapshot creation was failed.
*
* @param aSnapshot failed snapshot
*
* @note Locks mParent + this object for writing.
*/
{
AutoCaller autoCaller (this);
/* accessing mParent methods below needs mParent lock */
/* short cut: check whether attachments are all the same */
return S_OK;
++ it)
{
continue;
/* must not have children */
/* deassociate the old hard disk from the given snapshot's ID */
/* unregisterDiffHardDisk() is supposed to delete and uninit
* the differencing hard disk */
/* continue on error */
}
/* restore the whole list of attachments from the failed snapshot */
return rc;
}
/**
* Helper to lock the machine configuration for write access.
*
* @return S_OK or E_FAIL and sets error info on failure
*
* @note Doesn't lock anything (must be called from this object's lock)
*/
{
if (!isConfigLocked())
{
/* open the associated config file */
if (VBOX_FAILURE (vrc))
}
LogFlowThisFunc (("mConfigFile={%ls}, mHandleCfgFile=%d, rc=%08X\n",
return rc;
}
/**
* Helper to unlock the machine configuration from write access
*
* @return S_OK
*
* @note Doesn't lock anything.
* @note Not thread safe (must be called from this object's lock).
*/
{
if (isConfigLocked())
{
}
LogFlowThisFunc (("\n"));
return rc;
}
/**
* Returns true if the settings file is located in the directory named exactly
* as the machine. This will be true if the machine settings structure was
* created by default in #openConfigLoader().
*
* @param aSettingsDir if not NULL, the full machine settings file directory
* name will be assigned there.
*
* @note Doesn't lock anything.
* @note Not thread safe (must be called from this object's lock).
*/
{
AssertReturn (dirName, false);
/* if we don't rename anything on name change, return false shorlty */
return false;
if (aSettingsDir)
}
/**
* @note Locks objects for reading!
*/
bool Machine::isModified()
{
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return true;
return
mUserData.isBackedUp() ||
mHWData.isBackedUp() ||
mHDData.isBackedUp() ||
#ifdef VBOX_VRDP
#endif
}
/**
* @note This method doesn't check (ignores) actual changes to mHDData.
* Use mHDData.mHDAttachmentsChanged right after #commit() instead.
*
* @param aIgnoreUserData |true| to ignore changes to mUserData
*
* @note Locks objects for reading!
*/
{
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return true;
return
mHWData.hasActualChanges() ||
/* ignore mHDData */
//mHDData.hasActualChanges() ||
#ifdef VBOX_VRDP
#endif
}
/**
* Discards all changes to machine settings.
*
* @param aNotify whether to notify the direct session about changes or not
*
* @note Locks objects!
*/
{
AutoCaller autoCaller (this);
if (mHDData.isBackedUp())
fixupHardDisks (false /* aCommit */);
usbChanged = false;
if (mBIOSSettings)
#ifdef VBOX_VRDP
if (mVRDPServer)
#endif
if (mDVDDrive)
if (mFloppyDrive)
if (mAudioAdapter)
if (mUSBController)
if (mNetworkAdapters [slot])
if (aNotify)
{
// inform the direct session about changes
if (vrdpChanged)
if (dvdChanged)
that->onDVDDriveChange();
if (floppyChanged)
if (usbChanged)
if (networkAdapters [slot])
}
}
/**
* Commits all the changes to machine settings.
*
* Note that when committing fails at some stage, it still continues
* until the end. So, all data will either be actually committed or rolled
* back (for failed cases) and the returned result code will describe the
* first failure encountered. However, #isModified() will still return true
* in case of failure, to indicade that settings in memory and on disk are
* out of sync.
*
* @note Locks objects!
*/
{
AutoCaller autoCaller (this);
/*
* use safe commit to ensure Snapshot machines (that share mUserData)
* will still refer to a valid memory location
*/
if (mHDData.isBackedUp())
mBIOSSettings->commit();
#ifdef VBOX_VRDP
mVRDPServer->commit();
#endif
mFloppyDrive->commit();
mAudioAdapter->commit();
mUSBController->commit();
if (mType == IsSessionMachine)
{
/* attach new data to the primary machine and reshare it */
}
{
/*
* backup arbitrary data item to cause #isModified() to still return
* true in case of any error
*/
}
return rc;
}
/**
* Copies all the hardware data from the given machine.
*
* @note
* This method must be called from under this object's lock.
* @note
* This method doesn't call #commit(), so all data remains backed up
* and unsaved.
*/
{
// create copies of all shared folders (mHWData after attiching a copy
// contains just references to original objects)
++ it)
{
AssertComRC (rc);
}
#ifdef VBOX_VRDP
#endif
}
/////////////////////////////////////////////////////////////////////////////
// SessionMachine class
/////////////////////////////////////////////////////////////////////////////
/** Task structure for asynchronous VM operations */
struct SessionMachine::Task
{
, subTask (false), settingsChanged (false)
{}
void modifyLastState (MachineState_T s)
{
*const_cast <MachineState_T *> (&state) = s;
}
virtual void handler() = 0;
const MachineState_T state;
bool subTask : 1;
bool settingsChanged : 1;
};
/** Take snapshot task */
{
};
/** Discard snapshot task */
{
: Task (m, p)
, snapshot (s) {}
, snapshot (s) {}
};
/** Discard current state task */
{
bool discardCurSnapshot)
const bool discardCurrentSnapshot;
};
////////////////////////////////////////////////////////////////////////////////
{
LogFlowThisFunc (("\n"));
/* set the proper type to indicate we're the SessionMachine instance */
#if defined(__WIN__)
#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
mIPCSem = -1;
#endif
return S_OK;
}
void SessionMachine::FinalRelease()
{
LogFlowThisFunc (("\n"));
}
/**
* @note Must be called only by Machine::openSession() from its own write lock.
*/
{
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan (this);
/* create the interprocess semaphore */
#if defined(__WIN__)
if (mIPCSemName[i] == '\\')
mIPCSemName[i] = '/';
E_FAIL);
#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
char *pszConfigFile = NULL;
E_FAIL);
/* set the initial value to 1 */
E_FAIL);
#endif
/* memorize the peer Machine */
/* share the parent pointer */
/* take the pointers to data to share */
#ifdef VBOX_VRDP
/* create another VRDPServer object that will be mutable */
#endif
/* create another DVD drive object that will be mutable */
/* create another floppy drive object that will be mutable */
/* create another audio adapter object that will be mutable */
/* create another USB controller object that will be mutable */
/* create a list of network adapters that will be mutable */
{
}
/* Confirm a successful initialization when it's the case */
return S_OK;
}
/**
* Uninitializes this session object. If the reason is other than
* Uninit::Unexpected, then this method MUST be called from #checkForDeath().
*
* @param aReason uninitialization reason
*
* @note Locks mParent + this object for writing.
*/
{
/*
* Strongly reference ourselves to prevent this object deletion after
* mData->mSession.mMachine.setNull() below (which can release the last
* reference and call the destructor). Important: this must be done before
* accessing any members (and before AutoUninitSpan that does it as well).
* This self reference will be released as the very last step on return.
*/
/* Enclose the state transition Ready->InUninit->NotReady */
AutoUninitSpan autoUninitSpan (this);
if (autoUninitSpan.uninitDone())
{
LogFlowThisFunc (("Already uninitialized\n"));
return;
}
if (autoUninitSpan.initFailed())
{
/*
* We've been called by init() because it's failed. It's not really
* necessary (nor it's safe) to perform the regular uninit sequence
* below, the following is enough.
*/
LogFlowThisFunc (("Initialization failed\n"));
#if defined(__WIN__)
if (mIPCSem)
::CloseHandle (mIPCSem);
#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
if (mIPCSem >= 0)
mIPCSem = -1;
#endif
return;
}
/*
* We need to lock this object in uninit() because the lock is shared
* with mPeer (as well as data we modify below).
* mParent->addProcessToReap() and others need mParent lock.
*/
if (isModified())
{
LogWarningThisFunc (("Discarding unsaved settings changes!\n"));
rollback (false /* aNotify */);
}
{
LogWarningThisFunc (("canceling failed save state request!\n"));
}
else if (!!mSnapshotData.mSnapshot)
{
LogWarningThisFunc (("canceling untaken snapshot!\n"));
}
/* release all captured USB devices */
{
/* mType is not null when this machine's process has been started by
* VirtualBox::OpenRemoteSession(), therefore it is our child. We
* need to queue the PID to reap the process (and avoid zombies on
* Linux). */
}
{
/* Uninitialization didn't come from #checkForDeath(), so tell the
* client watcher thread to update the set of machines that have open
* sessions. */
}
/* uninitialize all remote controls */
{
LogFlowThisFunc (("Closing remote sessions (%d):\n",
{
LogFlowThisFunc ((" Calling remoteControl->Uninitialize()...\n"));
LogWarningThisFunc (("Forgot to close the remote session?\n"));
++ it;
}
}
/*
* An expected uninitialization can come only from #checkForDeath().
* Otherwise it means that something's got really wrong (for examlple,
* the Session implementation has released the VirtualBox reference
* before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
* etc). However, it's also possible, that the client releases the IPC
* semaphore correctly (i.e. before it releases the VirtualBox reference),
* but but the VirtualBox release event comes first to the server process.
* This case is practically possible, so we should not assert on an
* unexpected uninit, just log a warning.
*/
LogWarningThisFunc (("Unexpected SessionMachine uninitialization!\n"));
else
{
/* this must be null here (see #OnSessionEnd()) */
}
/* remove the association between the peer machine and this session machine */
/* reset the rest of session data */
/* close the interprocess semaphore before leaving the shared lock */
#if defined(__WIN__)
if (mIPCSem)
::CloseHandle (mIPCSem);
#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
if (mIPCSem >= 0)
mIPCSem = -1;
#endif
/* fire an event */
/* leave the shared lock before setting the above two to NULL */
}
// AutoLock::Lockable interface
////////////////////////////////////////////////////////////////////////////////
/**
* Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
* with the primary Machine instance (mPeer).
*/
{
return mPeer->lockHandle();
}
// IInternalMachineControl methods
////////////////////////////////////////////////////////////////////////////////
/**
* @note Locks the same as #setMachineState() does.
*/
{
return setMachineState (machineState);
}
/**
* @note Locks this object for reading.
*/
{
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
#if defined(__WIN__)
return S_OK;
#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
return S_OK;
#else
return S_FAIL;
#endif
}
/**
* @note Locks this object for reading.
*/
{
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
/**
* Goes through the USB filters of the given machine to see if the given
* device matches any filter or not.
*
* @note Locks the same as USBController::hasMatchingFilter() does.
*/
{
if (!aUSBDevice)
return E_INVALIDARG;
if (!aMatched)
return E_POINTER;
AutoCaller autoCaller (this);
return S_OK;
}
/**
* @note Locks the same as Host::captureUSBDevice() does.
*/
{
if (!aHostDevice)
return E_POINTER;
AutoCaller autoCaller (this);
// if cautureUSBDevice() fails, it must have set extended error info
}
/**
* @note Locks the same as Host::releaseUSBDevice() does.
*/
{
AutoCaller autoCaller (this);
}
/**
* @note Locks the same as Host::autoCaptureUSBDevices() does.
*/
{
AutoCaller autoCaller (this);
}
/**
* @note Locks the same as Host::releaseAllUSBDevices() does.
*/
{
AutoCaller autoCaller (this);
}
/**
* @note Locks mParent + this object for writing.
*/
{
AutoCaller autoCaller (this);
/*
* We don't assert below because it might happen that a non-direct session
* informs us it is closed right after we've been uninitialized -- it's ok.
*/
/* get IInternalSessionControl interface */
/* Progress::init() needs mParent lock */
{
/* The direct session is being normally closed by the client process
* ----------------------------------------------------------------- */
/* go to the closing state (essential for all open*Session() calls and
* for #checkForDeath()) */
/* set direct control to NULL to release the remote instance */
LogFlowThisFunc (("Direct control is set to NULL\n"));
/*
* Create the progress object the client will use to wait until
* #checkForDeath() is called to uninitialize this session object
* after it releases the IPC semaphore.
*/
FALSE /* aCancelable */);
}
else
{
/* the remote session is being normally closed */
{
break;
++it;
}
}
return S_OK;
}
/**
* @note Locks mParent + this object for writing.
*/
{
AutoCaller autoCaller (this);
/* mParent->addProgress() needs mParent lock */
E_FAIL);
/* memorize the progress ID and add it to the global collection */
/* stateFilePath is null when the machine is not running */
{
}
/* fill in the snapshot data */
/* set the state to Saving (this is expected by Console::SaveState()) */
return S_OK;
}
/**
* @note Locks mParent + this objects for writing.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
/* endSavingState() need mParent lock */
E_FAIL);
/*
* on success, set the state to Saved;
* on failure, set the state to the state we had when BeginSavingState() was
* called (this is expected by Console::SaveState() and
* Console::saveStateThread())
*/
if (aSuccess)
else
return endSavingState (aSuccess);
}
/**
* @note Locks mParent + this objects for writing.
*/
{
AutoCaller autoCaller (this);
/* Progress::init() needs mParent lock */
E_FAIL);
{
/*
* save all current settings to ensure current changes are committed
* and hard disks are fixed up
*/
}
/* check that there are no Writethrough hard disks attached */
++ it)
{
tr ("Cannot take a snapshot when there is a Writethrough hard "
}
/* create an ID for the snapshot */
snapshotId.create();
/* stateFilePath is null when the machine is not online nor saved */
snapshotId.ptr());
/* ensure the directory for the saved state file exists */
if (stateFilePath)
{
if (!RTDirExists (dir))
{
if (VBOX_FAILURE (vrc))
tr ("Could not create a directory '%s' to save the "
"VM state to (%Vrc)"),
}
}
/* create a snapshot machine object */
/*
* create a server-side progress object (it will be descriptionless
* when we need to combine it with the VM-side progress, i.e. when we're
* taking a snapshot online). The number of operations is:
* 1 (preparing) + # of VDIs + 1 (if the state is saved so we need to copy it)
*/
{
opCount ++;
if (takingSnapshotOnline)
else
}
/* create a combined server-side progress object when necessary */
if (takingSnapshotOnline)
{
}
/* create a snapshot object */
/*
* create and start the task on a separate thread
* (note that it will not start working until we release alock)
*/
(void *) task,
0, RTTHREADTYPE_MAIN_WORKER, 0, "TakeSnapshot");
if (VBOX_FAILURE (vrc))
{
delete task;
}
/* fill in the snapshot data */
/* set the state to Saving (this is expected by Console::TakeSnapshot()) */
if (takingSnapshotOnline)
else
*aStateFilePath = NULL;
return S_OK;
}
/**
* @note Locks mParent + this objects for writing.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
/* Lock mParent because of endTakingSnapshot() */
AssertReturn (!aSuccess ||
E_FAIL);
/*
* set the state to the state we had when BeginTakingSnapshot() was called
* (this is expected by Console::TakeSnapshot() and
* Console::saveStateThread())
*/
return endTakingSnapshot (aSuccess);
}
/**
* @note Locks mParent + this + children objects for writing!
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
/* Progress::init() needs mParent lock */
{
if (childrenCount > 1)
tr ("Cannot discard the snapshot '%ls' because it is the first "
"snapshot of the machine '%ls' and it has more than one "
"child snapshot (%d)"),
}
/*
* If the snapshot being discarded is the current one, ensure current
* settings are committed and saved.
*/
{
if (isModified())
{
rc = saveSettings();
}
}
/*
* create a progress object. The number of operations is:
* 1 (preparing) + # of VDIs
*/
FALSE /* aCancelable */,
/* create and start the task on a separate thread */
(void *) task,
0, RTTHREADTYPE_MAIN_WORKER, 0, "DiscardSnapshot");
if (VBOX_FAILURE (vrc))
delete task;
/* set the proper machine state (note: after creating a Task instance) */
/* return the progress to the caller */
/* return the new state to the caller */
return S_OK;
}
/**
* @note Locks mParent + this + children objects for writing!
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
/* Progress::init() needs mParent lock */
tr ("Could not discard the current state of the machine '%ls' "
"because it doesn't have any snapshots"),
/*
* create a progress object. The number of operations is:
* 1 (preparing) + # of VDIs + 1 (if we need to copy the saved state file)
*/
{
++ opCount;
}
/* create and start the task on a separate thread */
(void *) task,
0, RTTHREADTYPE_MAIN_WORKER, 0, "DiscardCurState");
if (VBOX_FAILURE (vrc))
delete task;
/* set the proper machine state (note: after creating a Task instance) */
/* return the progress to the caller */
/* return the new state to the caller */
return S_OK;
}
/**
* @note Locks mParent + other objects for writing!
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
/* Progress::init() needs mParent lock */
tr ("Could not discard the current state of the machine '%ls' "
"because it doesn't have any snapshots"),
/*
* create a progress object. The number of operations is:
* 1 (preparing) + # of VDIs in the current snapshot +
* # of VDIs in the previous snapshot +
* 1 (if we need to copy the saved state file of the previous snapshot)
* or (if there is no previous snapshot):
* 1 (preparing) + # of VDIs in the current snapshot * 2 +
* 1 (if we need to copy the saved state file of the current snapshot)
*/
{
if (prevSnapshot)
{
if (prevSnapshot->stateFilePath())
++ opCount;
}
else
{
if (curSnapshot->stateFilePath())
++ opCount;
}
}
/* create and start the task on a separate thread */
(void *) task,
0, RTTHREADTYPE_MAIN_WORKER, 0, "DiscardCurState");
if (VBOX_FAILURE (vrc))
delete task;
/* set the proper machine state (note: after creating a Task instance) */
/* return the progress to the caller */
/* return the new state to the caller */
return S_OK;
}
// public methods only for internal purposes
/////////////////////////////////////////////////////////////////////////////
/**
* Called from the client watcher thread to check for unexpected client
* process death.
*
* @note On Win32, this method is called only when we've got the semaphore
* (i.e. it has been signaled when we were waiting for it).
*
* On Win32, this method always returns true.
*
* On Linux, the method returns true if the client process has terminated
* still alive.
*
* @note Locks this object for writing.
*/
bool SessionMachine::checkForDeath()
{
bool doUninit = false;
bool rc = false;
/*
* Enclose autoCaller with a block because calling uninit()
* from under it will deadlock.
*/
{
AutoCaller autoCaller (this);
if (!autoCaller.isOk())
{
/*
* return true if not ready, to cause the client watcher to exclude
* the corresponding session from watching
*/
LogFlowThisFunc (("Already uninitialized!"));
return true;
}
/*
* Determine the reason of death: if the session state is Closing here,
* everything is fine. Otherwise it means that the client did not call
* OnSessionEnd() before it released the IPC semaphore.
* This may happen either because the client process has abnormally
* terminated, or because it simply forgot to call ISession::Close()
* before exiting. We threat the latter also as an abnormal termination
* (see Session::uninit() for details).
*/
#if defined(__WIN__)
{
LogWarningThisFunc (("ABNORMAL client termination! (wasRunning=%d)\n",
/* reset the state to Aborted */
}
/* release the IPC mutex */
::ReleaseMutex (mIPCSem);
doUninit = true;
rc = true;
#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
if (val > 0)
{
/* the semaphore is signaled, meaning the session is terminated */
{
LogWarningThisFunc (("ABNORMAL client termination! (wasRunning=%d)\n",
/* reset the state to Aborted */
}
doUninit = true;
}
#endif
} /* AutoCaller block */
if (doUninit)
return rc;
}
/**
* @note Locks this object for reading.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
{
AutoReaderLock alock (this);
}
/* ignore notifications sent after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
return directControl->OnDVDDriveChange();
}
/**
* @note Locks this object for reading.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
{
AutoReaderLock alock (this);
}
/* ignore notifications sent after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
return directControl->OnFloppyDriveChange();
}
/**
* @note Locks this object for reading.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
{
AutoReaderLock alock (this);
}
/* ignore notifications sent after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
}
/**
* @note Locks this object for reading.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
{
AutoReaderLock alock (this);
}
/* ignore notifications sent after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
return directControl->OnVRDPServerChange();
}
/**
* @note Locks this object for reading.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
{
AutoReaderLock alock (this);
}
/* ignore notifications sent after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
return directControl->OnUSBControllerChange();
}
/**
* @note Locks this object for reading.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
{
AutoReaderLock alock (this);
}
/* ignore notifications sent after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
}
/**
* @note Locks this object for reading.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
{
AutoReaderLock alock (this);
}
/* ignore notifications sent after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
}
// protected methods
/////////////////////////////////////////////////////////////////////////////
/**
* Helper method to finalize saving the state.
*
* @note Must be called from under this object's lock.
*
* @param aSuccess TRUE if the snapshot has been taken successfully
*
* @note Locks mParent + this objects for writing.
*/
{
AutoCaller autoCaller (this);
/* mParent->removeProgress() needs mParent lock */
if (aSuccess)
{
/* save all VM settings */
rc = saveSettings();
}
else
{
/* delete the saved state file (it might have been already created) */
}
/* remove the completed progress object */
/* clear out the temporary saved state data */
return rc;
}
/**
* Helper method to finalize taking a snapshot.
* Gets called only from #EndTakingSnapshot() that is expected to
* be called by the VM process when it finishes *all* the tasks related to
* taking a snapshot, either scucessfully or unsuccessfilly.
*
* @param aSuccess TRUE if the snapshot has been taken successfully
*
* @note Locks mParent + this objects for writing.
*/
{
AutoCaller autoCaller (this);
/* Progress object uninitialization needs mParent lock */
if (aSuccess)
{
/* the server progress must be completed on success */
/* memorize the first snapshot if necessary */
if (!mData->mFirstSnapshot)
{
/*
* the machine was powered off or saved when taking a snapshot,
* so reset the mCurrentStateModified flag
*/
}
}
{
if (mSnapshotData.mSnapshot)
{
/* wait for the completion of the server progress (diff VDI creation) */
/// @todo (dmik) later, we will definitely want to cancel it instead
// (when the cancel function is implemented)
/*
* delete all differencing VDIs created
* (this will attach their parents back)
*/
/* continue cleanup on error */
/* delete the saved state file (it might have been already created) */
}
}
/* inform callbacks */
/* clear out the snapshot data */
/* uninitialize the combined progress (to remove it from the VBox collection) */
{
}
return rc;
}
/**
* Take snapshot task handler.
* Must be called only by TakeSnapshotTask::handler()!
*
* The sole purpose of this task is to asynchronously create differencing VDIs
* and copy the saved state file (when necessary). The VM process will wait
* for this task to complete using the mSnapshotData.mServerProgress
* returned to it.
*
* @note Locks mParent + this objects for writing.
*/
{
AutoCaller autoCaller (this);
if (!autoCaller.isOk())
{
/*
* we might have been uninitialized because the session was
* accidentally closed by the client, so don't assert
*/
return;
}
/* endTakingSnapshot() needs mParent lock */
LogFlowThisFunc (("Creating differencing VDIs...\n"));
/* create new differencing hard disks and attach them to this machine */
true /* aOnline */);
{
LogFlowThisFunc (("Copying the execution state from '%s' to '%s'...\n",
/*
* We can safely leave the lock here:
* mMachineState is MachineState_Saving here
*/
/* copy the state file */
if (VBOX_FAILURE (vrc))
tr ("Could not copy the state file '%ls' to '%ls' (%Vrc)"),
}
/*
* we have to call endTakingSnapshot() here if the snapshot was taken
* offline, because the VM process will not do it in this case
*/
{
/* finalize the progress after setting the state, for consistency */
}
else
{
}
}
/**
* Discard snapshot task handler.
* Must be called only by DiscardSnapshotTask::handler()!
*
* When aTask.subTask is true, the associated progress object is left
* uncompleted on success. On failure, the progress is marked as completed
* regardless of this parameter.
*
* @note Locks mParent + this + child objects for writing!
*/
{
AutoCaller autoCaller (this);
if (!autoCaller.isOk())
{
/*
* we might have been uninitialized because the session was
* accidentally closed by the client, so don't assert
*/
tr ("The session has been accidentally closed"));
return;
}
/* mParent is locked because of Progress::notifyComplete(), etc. */
/* Safe locking in the direction parent->child */
/* save the snapshot ID (for callbacks) */
do
{
/* first pass: */
LogFlowThisFunc (("Check hard disk accessibility and affected machines...\n"));
++ it)
{
if (hd->hasForeignChildren())
{
tr ("One or more hard disks belonging to other machines are "
"based on the hard disk '%ls' stored in the snapshot '%ls'"),
break;
}
{
if (childrenCount > 1)
{
tr ("Normal hard disk '%ls' stored in the snapshot '%ls' "
"has more than one child hard disk (%d)"),
break;
}
}
else
{
}
if (!accessError.isNull())
{
tr ("Hard disk '%ls' stored in the snapshot '%ls' is not "
"accessible (%ls)"),
accessError.raw());
break;
}
{
/* reset the busy flag of all previous hard disks */
break;
}
}
/* second pass: */
LogFlowThisFunc (("Performing actual vdi merging...\n"));
++ it)
{
if (parent)
{
if (hd->isParentImmutable())
{
tr ("Discarding changes to immutable hard disk '%ls'"),
hdRootString.raw())));
/* clear the busy flag before unregistering */
/*
* unregisterDiffHardDisk() is supposed to delete and uninit
* the differencing hard disk
*/
continue;
}
else
{
/*
* differencing VDI:
* merge this image to all its children
*/
tr ("Merging changes to normal hard disk '%ls' to children"),
hdRootString.raw())));
snapshotLock.lock();
// debug code
// if (it != sm->mHDData->mHDAttachments.begin())
// {
// rc = setError (E_FAIL, "Simulated failure");
// break;
//}
else
}
}
{
/*
* normal vdi has the only child or none
* (checked in the first pass)
*/
{
}
{
tr ("Detaching normal hard disk '%ls'"),
hdRootString.raw())));
/* just deassociate the normal image from this machine */
/* clear the busy flag */
}
else
{
tr ("Preserving changes to normal hard disk '%ls'"),
hdRootString.raw())));
/* must be the same machine (checked in the first pass) */
/* merge the child to this basic image */
snapshotLock.lock();
else
/* replace the child image in the appropriate place */
if (!cs)
{
aTask.settingsChanged = true;
}
else
{
}
}
}
else
{
}
}
/* fetch the current error info */
{
/* clear the busy flag on the rest of hard disks */
}
/*
* we have to try to discard the snapshot even if merging failed
* because some images might have been already merged (and deleted)
*/
do
{
LogFlowThisFunc (("Discarding the snapshot (reparenting children)...\n"));
/// @todo (dmik):
// when we introduce clones later, discarding the snapshot
// will affect the current and first snapshots of clones, if they are
// direct children of this snapshot. So we will need to lock machines
// associated with child snapshots as well and update mCurrentSnapshot
{
/* currently, the parent snapshot must refer to the same machine */
!parentSnapshot ||
/* mark the current state as modified */
}
{
/*
* the first snapshot must have only one child when discarded,
* or no children at all
*/
{
}
else
}
/// @todo (dmik)
// if we implement some warning mechanism later, we'll have
// to return a warning if the state file path cannot be deleted
if (stateFilePath)
}
while (0);
/* restore the merge error if any */
{
}
}
while (0);
{
{
/* save current error info */
/* restore the machine state */
/*
* save settings anyway, since we've already changed the current
* machine configuration
*/
if (aTask.settingsChanged)
{
saveSettings (true /* aMarkCurStateAsModified */,
true /* aInformCallbacksAnyway */);
}
/* restore current error info */
}
/* set the result (this will try to fetch current error info on failure) */
}
}
/**
* Discard current state task handler.
* Must be called only by DiscardCurrentStateTask::handler()!
*
* @note Locks mParent + this object for writing.
*/
{
AutoCaller autoCaller (this);
if (!autoCaller.isOk())
{
/*
* we might have been uninitialized because the session was
* accidentally closed by the client, so don't assert
*/
tr ("The session has been accidentally closed"));
return;
}
/* mParent is locked because of Progress::notifyComplete(), etc. */
/*
* discard all current changes to mUserData (name, OSType etc.)
* (note that the machine is powered off, so there is no need
* to inform the direct session)
*/
if (isModified())
rollback (false /* aNotify */);
bool errorInSubtask = false;
bool stateRestored = false;
do
{
/*
* discard the saved state file if the machine was Saved prior
* to this operation
*/
{
}
{
/*
* the "discard current snapshot and state" task is in action,
* the current snapshot is not the last one.
* Discard the current snapshot first.
*/
{
/*
* the progress can be completed by a subtask only if there was
* a failure
*/
errorInSubtask = true;
break;
}
}
LONG64 snapshotTimeStamp = 0;
{
/* remember the timestamp of the snapshot we're restoring from */
/* copy all hardware data from the current snapshot */
LogFlowThisFunc (("Restoring VDIs from the snapshot...\n"));
/* restore the attachmends from the snapshot */
false /* aOnline */);
snapshotLock.lock();
{
/* here we can still safely rollback, so do it */
/* undo all changes */
rollback (false /* aNotify */);
break;
}
/*
* note: old VDIs will be deassociated/deleted on #commit() called
* either from #saveSettings() or directly at the end
*/
/* should not have a saved state file associated at this point */
if (curSnapshot->stateFilePath())
{
LogFlowThisFunc (("Copying saved state file from '%s' to '%s'...\n",
/* copy the state file */
snapshotLock.lock();
if (VBOX_SUCCESS (vrc))
{
}
else
{
tr ("Could not copy the state file '%s' to '%s' (%Vrc)"),
break;
}
}
}
bool informCallbacks = false;
{
/*
* discard the current snapshot and state task is in action,
* the current snapshot is the last one.
* Discard the current snapshot after discarding the current state.
*/
/* commit changes to fixup hard disks before discarding */
{
{
/*
* the progress can be completed by a subtask only if there
* was a failure
*/
errorInSubtask = true;
}
}
/*
* we've committed already, so inform callbacks anyway to ensure
* they don't miss some change
*/
informCallbacks = true;
}
/*
* we have already discarded the current state, so set the
* execution state accordingly no matter of the discard snapshot result
*/
if (mSSData->mStateFilePath)
else
stateRestored = true;
if (errorInSubtask)
break;
/* assign the timestamp from the snapshot */
Assert (snapshotTimeStamp != 0);
/* mark the current state as not modified */
/* save all settings and commit */
aTask.settingsChanged = false;
}
while (0);
{
if (!stateRestored)
{
/* restore the machine state */
}
/*
* save all settings and commit if still modified (there is no way to
* rollback properly). Note that isModified() will return true after
* copyFrom(). Also save the settings if requested by the subtask.
*/
{
if (aTask.settingsChanged)
saveSettings (true /* aMarkCurStateAsModified */,
true /* aInformCallbacksAnyway */);
else
saveSettings();
}
}
if (!errorInSubtask)
{
/* set the result (this will try to fetch current error info on failure) */
}
}
/**
* Helper to change the machine state (reimplementation).
*
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller (this);
("oldMachineState=%d, aMachineState=%d\n",
int stsFlags = 0;
bool deleteSavedState = false;
/* detect some state transitions */
if (oldMachineState < MachineState_Running &&
{
/*
* the EMT thread is about to start, so mark attached HDDs as busy
* and all its ancestors as being in use
*/
++ it)
{
}
}
else
if (oldMachineState >= MachineState_Running &&
{
/*
* the EMT thread stopped, so mark attached HDDs as no more busy
* and remove the in-use flag from all its ancestors
*/
++ it)
{
}
}
{
if (aMachineState != MachineState_Saved)
{
/*
* delete the saved state file once the machine has finished
* restoring from it (note that Console sets the state from
* Restoring to Saved if the VM couldn't restore successfully,
* to give the user an ability to fix an error and retry --
* we keep the saved state file in this case)
*/
deleteSavedState = true;
}
}
else
if (oldMachineState == MachineState_Saved &&
{
/*
* delete the saved state after Console::DiscardSavedState() is called
* or if the VM process (owning a direct VM session) crashed while the
* VM was Saved
*/
/// @todo (dmik)
// Not sure that deleting the saved state file just because of the
// client death before it attempted to restore the VM is a good
// thing. But when it crashes we need to go to the Aborted state
// which cannot have the saved state file associated... The only
// way to fix this is to make the Aborted condition not a VM state
// but a bool flag: i.e., when a crash occurs, set it to true and
// change the state to PoweredOff or Saved depending on the
// saved state presence.
deleteSavedState = true;
}
if (aMachineState == MachineState_Starting ||
{
/*
* set the current state modified flag to indicate that the
* current state is no more identical to the state in the
* current snapshot
*/
{
}
}
if (deleteSavedState == true)
{
}
/* redirect to the underlying peer machine */
if (aMachineState == MachineState_PoweredOff ||
{
}
if ((oldMachineState != MachineState_PoweredOff &&
{
/*
* clear differencing hard disks based on immutable hard disks
* once we've been shut down for any reason
*/
rc = wipeOutImmutableDiffs();
}
return rc;
}
/**
* Sends the current machine state value to the VM process.
*
* @note Locks this object for reading, then calls a client process.
*/
{
AutoCaller autoCaller (this);
{
AutoReaderLock alock (this);
/* directControl may be already set to NULL here in #OnSessionEnd()
* called too early by the direct session process while there is still
* some operation (like discarding the snapshot) in progress. The client
* process in this case is waiting inside Session::close() for the
* "end session" process object to complete, while #uninit() called by
* #checkForDeath() on the Watcher thread is waiting for the pending
* operation to complete. For now, we accept this inconsitent behavior
* and simply do nothing here. */
return S_OK;
}
}
/* static */
{
// it's our responsibility to delete the task
delete task;
return 0;
}
/////////////////////////////////////////////////////////////////////////////
// SnapshotMachine class
/////////////////////////////////////////////////////////////////////////////
{
LogFlowThisFunc (("\n"));
/* set the proper type to indicate we're the SnapshotMachine instance */
return S_OK;
}
void SnapshotMachine::FinalRelease()
{
LogFlowThisFunc (("\n"));
uninit();
}
/**
* Initializes the SnapshotMachine object when taking a snapshot.
*
* @param aSessionMachine machine to take a snapshot from
* @param aSnapshotId snapshot ID of this snapshot machine
* @param aStateFilePath file where the execution state will be later saved
* (or NULL for the offline snapshot)
*
* @note Locks aSessionMachine object for reading.
*/
{
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan (this);
/* memorize the primary Machine instance (i.e. not SessionMachine!) */
/* share the parent pointer */
/* take the pointer to Data to share */
/*
* take the pointer to UserData to share
* (our UserData must always be the same as Machine's data)
*/
/* make a private copy of all other data (recent changes from SessionMachine) */
/* SSData is always unique for SnapshotMachine */
/*
* create copies of all shared folders (mHWData after attiching a copy
* contains just references to original objects)
*/
++ it)
{
}
/* create all other child objects that will be immutable private copies */
#ifdef VBOX_VRDP
#endif
{
}
/* Confirm a successful initialization when it's the case */
return S_OK;
}
/**
* Initializes the SnapshotMachine object when loading from the settings file.
*
* @param aMachine machine the snapshot belngs to
* @param aHWNode <Hardware> node
* @param aHDAsNode <HardDiskAttachments> node
* @param aSnapshotId snapshot ID of this snapshot machine
* @param aStateFilePath file where the execution state is saved
* (or NULL for the offline snapshot)
*
* @note Locks aMachine object for reading.
*/
{
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan (this);
/* memorize the primary Machine instance */
/* share the parent pointer */
/* take the pointer to Data to share */
/*
* take the pointer to UserData to share
* (our UserData must always be the same as Machine's data)
*/
/* allocate private copies of all other data (will be loaded from settings) */
/* SSData is always unique for SnapshotMachine */
/* create all other child objects that will be immutable private copies */
mBIOSSettings->init (this);
#ifdef VBOX_VRDP
mVRDPServer->init (this);
#endif
mFloppyDrive->init (this);
mAudioAdapter->init (this);
mUSBController->init (this);
{
}
/* load hardware and harddisk settings */
{
/* commit all changes made during the initialization */
commit();
}
/* Confirm a successful initialization when it's the case */
return rc;
}
/**
* Uninitializes this SnapshotMachine object.
*/
void SnapshotMachine::uninit()
{
/* Enclose the state transition Ready->InUninit->NotReady */
AutoUninitSpan autoUninitSpan (this);
if (autoUninitSpan.uninitDone())
return;
}
// AutoLock::Lockable interface
////////////////////////////////////////////////////////////////////////////////
/**
* Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
* with the primary Machine instance (mPeer).
*/
{
return mPeer->lockHandle();
}
// public methods only for internal purposes
////////////////////////////////////////////////////////////////////////////////
/**
* Called by the snapshot object associated with this SnapshotMachine when
* snapshot data such as name or description is changed.
*
* @note Locks this object for writing.
*/
{
/* inform callbacks */
return S_OK;
}