MachineImpl.cpp revision 16ab6cda9bc53bc791284d26da448bbccb11b7ff
/* $Id$ */
/** @file
* Implementation of IMachine in VBoxSVC.
*/
/*
* Copyright (C) 2006-2007 Sun Microsystems, Inc.
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 USA or visit http://www.sun.com if you need
* additional information or have any questions.
*/
/* Make sure all the stdint.h macros are included - must come first! */
#ifndef __STDC_LIMIT_MACROS
# define __STDC_LIMIT_MACROS
#endif
#ifndef __STDC_CONSTANT_MACROS
# define __STDC_CONSTANT_MACROS
#endif
#if defined(RT_OS_WINDOWS)
#elif defined(RT_OS_LINUX)
#endif
# include <errno.h>
#endif
#include "VirtualBoxImpl.h"
#include "MachineImpl.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 "GuestImpl.h"
#include "SATAControllerImpl.h"
#ifdef VBOX_WITH_USB
# include "USBProxyService.h"
#endif
#include "VirtualBoxXMLUtil.h"
#include "Logging.h"
#include <stdio.h>
#include <stdlib.h>
#include <iprt/cpputils.h>
#ifdef VBOX_WITH_GUEST_PROPS
#endif
#include <algorithm>
#include <typeinfo>
#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
#define HOSTSUFF_EXE ".exe"
#else /* !RT_OS_WINDOWS */
#define HOSTSUFF_EXE ""
#endif /* !RT_OS_WINDOWS */
// defines / prototypes
/////////////////////////////////////////////////////////////////////////////
// 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
"<!-- Sun xVM 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;
mAccessible = FALSE;
/* mUuid is initialized in Machine::init() */
mMachineStateDeps = 0;
}
{
{
}
}
/////////////////////////////////////////////////////////////////////////////
// Machine::UserData structure
/////////////////////////////////////////////////////////////////////////////
{
/* default values for a newly created machine */
/* mName, mOSTypeId, mSnapshotFolder, mSnapshotFolderFull are initialized in
* Machine::init() */
}
{
}
/////////////////////////////////////////////////////////////////////////////
// Machine::HWData structure
/////////////////////////////////////////////////////////////////////////////
{
/* default values for a newly created machine */
mMemorySize = 128;
mCPUCount = 1;
mMemoryBalloonSize = 0;
mVRAMSize = 8;
mAccelerate3DEnabled = false;
mMonitorCount = 1;
mHWVirtExNestedPagingEnabled = false;
mHWVirtExVPIDEnabled = false;
mPAEEnabled = false;
mPropertyServiceActive = false;
/* default boot order: floppy - DVD - HDD */
mBootOrder [0] = DeviceType_Floppy;
mBootOrder [i] = DeviceType_Null;
}
{
}
{
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
/////////////////////////////////////////////////////////////////////////////
{
}
{
}
{
if (this == &that)
return true;
return false;
if (mAttachments.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 aOsType OS Type of this machine
* @param aNameSync |TRUE| to automatically 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. Required for aMode==Init_Registered
* and optional for aMode==Init_New. Used for consistency
* check when aMode is Init_Registered; must match UUID
* stored in the settings file. Used for predefining the
* UUID of a VM when aMode is Init_New.
*
* @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);
/* allocate the essential machine data structure (the rest will be
* allocated later by initDataAndChildObjects() */
/* memorize the config file name (as provided) */
/* get the full file name */
if (RT_FAILURE (vrc))
return setError (VBOX_E_FILE_ERROR,
tr ("Invalid machine settings file name '%ls' (%Rrc)"),
aConfigFile, vrc);
if (aMode == Init_Registered)
{
/* store the supplied UUID (will be used to check for UUID consistency
* in loadSettings() */
rc = registeredInit();
}
else
{
if (aMode == Init_Existing)
{
/* lock the settings file */
rc = lockConfig();
}
{
/* check for the file existence */
RTFILE f = NIL_RTFILE;
{
tr ("Machine settings file '%s' already exists"),
configFileFull.raw());
if (RT_SUCCESS (vrc))
RTFileClose (f);
}
else
{
tr ("Invalid machine settings file name '%ls' (%Rrc)"),
}
}
else
AssertFailed();
{
/* set to true now to cause uninit() to call
* uninitDataAndChildObjects() on failure */
{
}
else
{
/* create the machine UUID */
if (aId)
else
/* memorize the provided new machine's name */
/* initialize the default snapshots folder
* (note: depends on the name value set above!) */
AssertComRC (rc);
if (aOsType)
{
/* Store OS type */
/* Apply machine defaults */
if (aOsType->recommendedVirtEx())
else
/* Apply BIOS defaults */
/* Apply network adapters defaults */
}
}
/* 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.
*/
{
{
/* 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). */
/* Restore the registered flag (even on failure) */
unlockConfig();
}
{
/* Set mAccessible to TRUE only if we successfully locked and loaded
* the settings file */
/* 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 {%RTuuid} is inaccessible! [%ls]\n",
/* rollback all changes */
rollback (false /* aNotify */);
/* uninitialize the common part to make sure all data is reset to
* default (null) values */
}
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 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 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 */);
}
if (mData->mAccessible)
/* free the essential data structure last */
mParent->removeDependentChild (this);
}
// IMachine properties
/////////////////////////////////////////////////////////////////////////////
{
AutoLimitedCaller autoCaller (this);
/* mParent is constant during life time, no need to lock */
return S_OK;
}
{
AutoLimitedCaller autoCaller (this);
AutoWriteLock alock (this);
if (!mData->mAccessible)
{
/* try to initialize the VM once more if not accessible */
AutoReinitSpan autoReinitSpan (this);
rc = registeredInit();
{
/* make sure interesting parties will notice the accessibility
* state change */
}
}
return rc;
}
{
AutoLimitedCaller autoCaller (this);
AutoReadLock alock (this);
{
/* return shortly */
aAccessError = NULL;
return S_OK;
}
{
}
return rc;
}
{
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
if (!*aName)
return setError (E_INVALIDARG,
tr ("Machine name cannot be empty"));
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
return S_OK;
}
{
AutoLimitedCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
/* look up the object by Id to check it is valid */
AutoWriteLock alock (this);
return S_OK;
}
{
if (!memorySize)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock 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);
AutoWriteLock alock (this);
return S_OK;
}
{
if (!CPUCount)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
/* check RAM limits */
return setError (E_INVALIDARG,
tr ("Invalid virtual CPU count: %lu (must be in range [%lu, %lu])"),
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
return S_OK;
}
{
if (!memorySize)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock 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);
AutoWriteLock alock (this);
return S_OK;
}
/** @todo this method should not be public */
{
if (!memoryBalloonSize)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
/** @todo this method should not be public */
{
/* check limits */
return setError (E_INVALIDARG,
tr ("Invalid memory balloon size: %lu MB (must be in range [%lu, %lu] MB)"),
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
return S_OK;
}
/** @todo this method should not be public */
{
if (!statisticsUpdateInterval)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
/** @todo this method should not be public */
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
return S_OK;
}
{
if (!enabled)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
/** @todo check validity! */
return S_OK;
}
{
if (!monitorCount)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
/* make sure monitor count is a sensible number */
return setError (E_INVALIDARG,
tr ("Invalid monitor count: %lu (must be in range [%lu, %lu])"),
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
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);
AutoReadLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
/** @todo check validity! */
return S_OK;
}
{
if (!enabled)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
/** @todo check validity! */
return S_OK;
}
{
if (!enabled)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
/** @todo check validity! */
return S_OK;
}
{
if (!enabled)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
/** @todo check validity! */
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoReadLock 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);
AutoWriteLock alock (this);
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 (RT_FAILURE (vrc))
tr ("Invalid snapshot folder '%ls' (%Rrc)"),
return S_OK;
}
{
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
#ifdef VBOX_WITH_VRDP
if (!vrdpServer)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
Assert (!!mVRDPServer);
return S_OK;
#else
#endif
}
{
if (!dvdDrive)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
if (!floppyDrive)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
Assert (!!mFloppyDrive);
return S_OK;
}
{
if (!audioAdapter)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
#ifdef VBOX_WITH_USB
AutoCaller autoCaller (this);
AutoReadLock alock (this);
#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 */
#endif
}
{
#ifdef VBOX_WITH_AHCI
AutoCaller autoCaller (this);
AutoReadLock alock (this);
#else
/* Note: The GUI depends on this method returning E_NOTIMPL with no
* extended error info to indicate that SATA is simply not available
* (w/o treting it as a failure), for example, as in OSE */
#endif
}
{
AutoLimitedCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
if (!isConfigLocked())
{
/*
* if we're ready and isConfigLocked() is FALSE then it means
* that no config file exists yet, so always return TRUE
*/
}
else
{
*aModified = isModified();
}
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
if (!machineState)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoReadLock 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;
}
{
AutoCaller autoCaller (this);
AutoReadLock alock (this);
coll.createObject();
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoReadLock alock (this);
}
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
? S_OK : E_OUTOFMEMORY;
}
// IMachine methods
/////////////////////////////////////////////////////////////////////////////
{
return setError (E_INVALIDARG,
tr ("Invalid boot position: %lu (must be in range [1, %lu])"),
if (aDevice == DeviceType_USB)
tr ("Booting from USB devices is not currently supported"));
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
return S_OK;
}
{
return setError (E_INVALIDARG,
tr ("Invalid boot position: %lu (must be in range [1, %lu])"),
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
if (aBus == StorageBus_SATA)
{
/* The device property is not used for SATA yet. Thus it is always zero. */
if (aDevice != 0)
return setError (E_INVALIDARG,
tr ("Invalid SATA device slot: %l (must be always 0)"),
aDevice);
/* We suport 30 ports, starting from 0 */
/// @todo: r=aeichner make max port count a system property
return setError (E_INVALIDARG,
tr ("Invalid SATA channel number: %l (must be in range "
"[0, 29])"),
aChannel);
}
else if (aBus == StorageBus_IDE)
{
tr ("Invalid IDE channel: %l (must be in range [0, 1])"),
aChannel);
if (aChannel == 0)
{
tr ("Invalid IDE device slot: %l (must be in range "
"[0, 1] for channel 0)"),
aDevice);
}
else
if (aChannel == 1)
{
if (aDevice != 1)
tr ("Invalid IDE device slot: %l (must be "
"1 for channel 1)"),
aDevice);
}
}
else
return E_INVALIDARG;
AutoCaller autoCaller (this);
/* VirtualBox::findHardDisk2() need read lock; also we want to make sure the
* hard disk object we pick up doesn't get unregistered before we finish. */
AutoWriteLock alock (this);
/// @todo NEWMEDIA implicit machine registration
if (!mData->mRegistered)
tr ("Cannot attach hard disks to an unregistered machine"));
/* check if the device slot is already busy */
{
tr ("Hard disk '%ls' is already attached to device slot %d on "
"channel %d of bus %d of this virtual machine"),
}
/* find a hard disk by UUID */
{
tr ("Hard disk '%ls' is already attached to this virtual machine"),
}
bool associate = true;
do
{
if (mHDData.isBackedUp())
{
/* check if the hard disk was attached to the VM before we started
* changing attachemnts in which case the attachment just needs to
* be restored */
{
{
/* the simplest case: restore the whole attachment
* and return, nothing else to do */
return S_OK;
}
* but don't try to associate it again */
associate = false;
break;
}
}
/* go further only if the attachment is to be indirect */
if (!indirect)
break;
/* perform the so called smart attachment logic for indirect
* attachments. Note that smart attachment is only applicable to base
* hard disks. */
{
/* first, investigate the backup copy of the current hard disk
* attachments to make it possible to re-attach existing diffs to
* another device slot w/o losing their contents */
if (mHDData.isBackedUp())
{
uint32_t foundLevel = 0;
{
{
/* skip the hard disk if its currently attached (we
* cannot attach the same hard disk twice) */
continue;
/* matched device, channel and bus (i.e. attached to the
* same place) will win and immediately stop the search;
* otherwise the attachment that has the youngest
* descendant of hd will be used
*/
{
/* the simplest case: restore the whole attachment
* and return, nothing else to do */
return S_OK;
}
else
{
foundLevel = level;
}
}
}
{
/* use the previously attached hard disk */
/* not implicit, doesn't require association with this VM */
indirect = false;
associate = false;
/* go right to the HardDisk2Attachment creation */
break;
}
}
/* then, search through snapshots for the best diff in the given
* hard disk's chain to base the new diff on */
while (snap)
{
uint32_t foundLevel = 0;
{
{
/* matched device, channel and bus (i.e. attached to the
* same place) will win and immediately stop the search;
* otherwise the attachment that has the youngest
* descendant of hd will be used
*/
{
break;
}
else
{
foundLevel = level;
}
}
}
{
break;
}
}
/* found a suitable diff, use it as a base */
{
}
}
diff.createObject();
/* make sure the hard disk is not modified before createDiffStorage() */
/* will leave the lock before the potentially lengthy operation, so
* protect with the special state */
/* use the created diff for the actual attachment */
}
while (0);
if (associate)
{
/* as the last step, associate the hard disk to the VM */
/* here we can fail because of Deleting, or being in process of
* creating a Diff */
}
/* sucsess: finally remember the attachment */
return rc;
}
{
if (aBus == StorageBus_Null)
return E_INVALIDARG;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return setError (E_INVALIDARG,
tr ("No hard disk attached to device slot %d on channel %d of bus %d"),
return S_OK;
}
{
if (aBus == StorageBus_Null)
return E_INVALIDARG;
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
return setError (E_INVALIDARG,
tr ("No hard disk attached to device slot %d on channel %d of bus %d"),
if (hda->isImplicit())
{
/* attempt to implicitly delete the implicitly created diff */
/// @todo move the implicit flag from HardDisk2Attachment to HardDisk2
/// and forbid any hard disk operation when it is implicit. Or maybe
/// a special media state for it to make it even more simple.
/* will leave the lock before the potentially lengthy operation, so
* protect with the special state */
}
/* 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 the copy */
return S_OK;
}
{
if (!port)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
if (!port)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
{
if (!adapter)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return S_OK;
}
/**
* @note Locks this object for reading.
*/
{
AutoCaller autoCaller (this);
/* serialize file access (prevent writes) */
AutoReadLock alock (this);
/* start with nothing found */
if (aNextValue)
*aNextValue = NULL;
/* 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;
try
{
using namespace settings;
using namespace xml;
/* load the settings file (we don't reuse the existing handle but
* request a new one to allow for concurrent multithreaded reads) */
if (!extraDataNode.isNull())
{
{
{
/* if we're supposed to return the first one */
{
if (aNextValue)
{
}
return S_OK;
}
/* did we find the key we're looking for? */
{
++ it;
/* is there another item? */
{
if (aNextValue)
{
}
}
/* else it's the last one, arguments are already NULL */
return S_OK;
}
}
}
}
/* Here we are when a) there are no items at all or b) there are items
* but none of them equals to the requested non-NULL key. b) is an
* error as well as a) if the key is non-NULL. When the key is NULL
* (which is the case only when there are no items), we just fall
* through to return NULLs and S_OK. */
}
catch (...)
{
}
return rc;
}
/**
* @note Locks this object for reading.
*/
{
AutoCaller autoCaller (this);
/* serialize file access (prevent writes) */
AutoReadLock 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;
try
{
using namespace settings;
using namespace xml;
/* load the settings file (we don't reuse the existing handle but
* request a new one to allow for concurrent multithreaded reads) */
if (!extraDataNode.isNull())
{
/* check if the key exists */
{
{
break;
}
}
}
}
catch (...)
{
}
return rc;
}
/**
* @note Locks mParent for writing + this object for writing.
*/
{
AutoCaller autoCaller (this);
/* VirtualBox::onExtraDataCanChange() and saveSettings() need mParent
* lock (saveSettings() needs a write one). This object's write lock is
* also necessary to serialize file access (prevent concurrent reads and
* writes). */
if (mType == IsSnapshotMachine)
{
}
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())
{
rc = saveSettings();
}
try
{
using namespace settings;
using namespace xml;
/* load the settings file */
{
{
extraDataItemNode = *it;
break;
}
}
/* When no key is found, oldVal is null */
if (changed)
{
/* ask for permission from all listeners */
{
LogWarningFunc (("Someone vetoed! Change refused%s%ls\n",
return setError (E_ACCESSDENIED,
tr ("Could not set extra data because someone refused "
"the requested change of '%ls' to '%ls'%s%ls"),
}
{
if (extraDataItemNode.isNull())
{
}
}
else
{
/* an old value does for sure exist here (XML schema
* guarantees that "value" may not absent in the
* <ExtraDataItem> element) */
}
/* save settings on success */
}
}
catch (...)
{
}
/* fire a notification */
return rc;
}
{
AutoCaller autoCaller (this);
/* saveSettings() needs mParent lock */
/* when there was auto-conversion, we want to save the file even if
* the VM is saved */
/* the settings file path may never be null */
/* save all VM data excluding snapshots */
return saveSettings();
}
{
AutoCaller autoCaller (this);
/* saveSettings() needs mParent lock */
/* when there was auto-conversion, we want to save the file even if
* the VM is saved */
/* the settings file path may never be null */
/* perform backup only when there was auto-conversion */
{
}
/* save all VM data excluding snapshots */
return saveSettings();
}
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
/*
* during this rollback, the session will be notified if data has
* been actually changed
*/
rollback (true /* aNotify */);
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
if (mData->mRegistered)
tr ("Cannot delete settings of a registered machine"));
/* delete the settings only when the file actually exists */
if (isConfigLocked())
{
unlockConfig();
if (RT_FAILURE (vrc))
tr ("Could not delete the settings file '%ls' (%Rrc)"),
/* 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()). Also, delete the VBox.png[.N]
* files that may have been created by the GUI. */
RTFileDelete (log);
RTFileDelete (log);
for (int i = 3; i >= 0; i--)
{
RTFileDelete (log);
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
* prepareSaveSettings()) */
{
if (isInOwnDir (&settingsDir))
}
}
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return rc;
}
{
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return rc;
}
{
/// @todo (dmik) don't forget to set
// mData->mCurrentStateModified to FALSE
}
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
if (!accessible)
return setWarning (E_FAIL,
/* inform the direct session if any */
return S_OK;
}
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
/* inform the direct session if any */
return S_OK;
}
{
/* start with No */
AutoCaller autoCaller (this);
{
AutoReadLock alock (this);
tr ("Machine session is not open (session state: %d)"),
}
/* ignore calls made after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
}
{
AutoCaller autoCaller (this);
{
AutoReadLock alock (this);
tr ("Machine session is not open (session state: %d)"),
}
/* ignore calls made after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
}
STDMETHODIMP Machine::GetGuestProperty (INPTR BSTR aName, BSTR *aValue, ULONG64 *aTimestamp, BSTR *aFlags)
{
#if !defined (VBOX_WITH_GUEST_PROPS)
#else
return E_INVALIDARG;
return E_POINTER;
if (!VALID_PTR (aTimestamp))
return E_POINTER;
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
using namespace guestProp;
if (!mHWData->mPropertyServiceActive)
{
bool found = false;
{
{
found = true;
}
}
}
else
{
/* just be on the safe side when calling another process */
false /* isSetter */,
}
return rc;
#endif /* else !defined (VBOX_WITH_GUEST_PROPS) */
}
{
}
{
}
{
#if !defined (VBOX_WITH_GUEST_PROPS)
#else
using namespace guestProp;
return E_INVALIDARG;
return E_INVALIDARG;
return E_INVALIDARG;
|| utf8Patterns.isNull()
)
return E_OUTOFMEMORY;
bool matchAll = false;
if (0 == utf8Patterns.length())
matchAll = true;
)
aFlags);
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
if (!mHWData->mPropertyServiceActive)
{
bool found = false;
rc = setError (E_INVALIDARG, tr ("Cannot set a transient property when the machine is not running"));
{
{
else
{
/* The backup() operation invalidates our iterator, so get a
* new one. */
;
}
found = true;
}
}
{
{
}
}
{
}
&& ( matchAll
)
)
}
else
{
/* just be on the safe side when calling another process */
true /* isSetter */,
}
return rc;
#endif /* else !defined (VBOX_WITH_GUEST_PROPS) */
}
{
}
STDMETHODIMP Machine::EnumerateGuestProperties (INPTR BSTR aPatterns, ComSafeArrayOut(BSTR, aNames), ComSafeArrayOut(BSTR, aValues), ComSafeArrayOut(ULONG64, aTimestamps), ComSafeArrayOut(BSTR, aFlags))
{
#if !defined (VBOX_WITH_GUEST_PROPS)
#else
return E_POINTER;
if (ComSafeArrayOutIsNull (aNames))
return E_POINTER;
if (ComSafeArrayOutIsNull (aValues))
return E_POINTER;
if (ComSafeArrayOutIsNull (aTimestamps))
return E_POINTER;
if (ComSafeArrayOutIsNull (aFlags))
return E_POINTER;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
using namespace guestProp;
bool matchAll = false;
matchAll = true;
if (!mHWData->mPropertyServiceActive)
{
/*
* Look for matching patterns and build up a list.
*/
if ( matchAll
)
/*
* And build up the arrays for returning the property information.
*/
{
++iProp;
}
}
else
{
/* just be on the safe side when calling another process */
}
return rc;
#endif /* else !defined (VBOX_WITH_GUEST_PROPS) */
}
// public methods for internal purposes
/////////////////////////////////////////////////////////////////////////////
/**
* Saves the registry entry of this machine to the given configuration node.
*
* @param aEntryNode Node to save the registry entry to.
*
* @note locks this object for reading.
*/
{
AutoLimitedCaller autoCaller (this);
AutoReadLock alock (this);
/* UUID */
/* settings file name (possibly, relative) */
return S_OK;
}
/**
* 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, can be the
* same Utf8Str instance as passed in @a aPath).
* @return IPRT result.
*
* @note Locks this object for reading.
*/
{
AutoCaller autoCaller (this);
AutoReadLock alock (this);
char folder [RTPATH_MAX];
if (RT_SUCCESS (vrc))
return vrc;
}
/**
* Tries to calculate the relative path of the given absolute path using the
* directory of the 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);
AutoReadLock 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);
AutoReadLock alock (this);
if (isInOwnDir (&settingsDir))
{
/* Log folder is <Machines>/<VM_Name>/Logs */
}
else
{
/* Log folder is <Machines>/<VM_SnapshotFolder>/Logs */
}
}
/**
* @note Locks this object for writing, calls the client process (outside the
* lock).
*/
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
if (!mData->mRegistered)
return setError (E_UNEXPECTED,
return setError (VBOX_E_INVALID_OBJECT_STATE,
tr ("A session for the machine '%ls' is currently open "
"(or being closed)"),
/* may not be Running */
/* get the session 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);
{
#ifdef VBOX_WITH_RESOURCE_USAGE_API
#endif /* VBOX_WITH_RESOURCE_USAGE_API */
/*
* 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 occur w/o any error info (from RPC), so provide one */
{
/* complete the remote session initialization */
/* get the console from the direct session */
ComAssertComRC (rc);
{
}
/* assign machine & console to the remote session */
{
/*
* after openRemoteSession(), the first and the only
* entry in remoteControls is that remote session
*/
LogFlowThisFunc (("Calling AssignRemoteMachine()...\n"));
/* The failure may occur w/o any error info (from RPC), so provide one */
}
aControl->Uninitialize();
}
/* enter the lock again */
/* Restore the session state */
}
/* finalize spawning anyway (this is why we don't return on errors above) */
{
/* Note that the progress object is finalized later */
/* We don't reset mSession.mPid here because it is necessary for
* SessionMachine::uninit() to reap the child process later. */
{
/* Close the remote session, remove the remote control from the list
* and reset session state to Closed (@note keep the code in sync
* with the relevant part in openSession()). */
{
}
}
}
else
{
/* memorize PID of the directly opened session */
}
{
/* memorize the direct session control and cache IUnknown for it */
/* associate the SessionMachine with this Machine */
/* request an IUnknown pointer early from the remote party for later
* identity checks (it will be internally cached within mDirectControl
* at least on XPCOM) */
}
{
/* 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);
AutoWriteLock alock (this);
if (!mData->mRegistered)
return setError (E_UNEXPECTED,
return setError (VBOX_E_INVALID_OBJECT_STATE,
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 (aEnvironment)
{
do
{
/* clone the current environment */
/* put new variables to the environment
* (ignore empty variable names here since RTEnv API
* intentionally doesn't do that) */
for (char *p = newEnvStr; *p; ++ p)
{
{
*p = '\0';
if (*var)
{
if (val)
{
*val++ = '\0';
}
else
if (RT_FAILURE (vrc2))
break;
}
var = p + 1;
}
}
}
while (0);
}
/* Qt4 is default */
#ifdef VBOX_WITH_QT4GUI
{
# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
const char VirtualBox_exe[] = "../Resources/VirtualBoxVM.app/Contents/MacOS/VirtualBoxVM";
# else
# endif
# ifdef RT_OS_WINDOWS /** @todo drop this once the RTProcCreate bug has been fixed */
# else
# endif
}
#else /* !VBOX_WITH_QT4GUI */
if (0)
;
#endif /* VBOX_WITH_QT4GUI */
else
/* Qt3 is used sometimes as well, OS/2 does not have Qt4 at all */
#ifdef VBOX_WITH_QTGUI
{
# ifdef RT_OS_DARWIN /* Avoid Lanuch Services confusing this with the selector by using a helper app. */
const char VirtualBox_exe[] = "../Resources/VirtualBoxVM.app/Contents/MacOS/VirtualBoxVM3";
# else
# endif
# ifdef RT_OS_WINDOWS /** @todo drop this once the RTProcCreate bug has been fixed */
# else
# endif
}
#else /* !VBOX_WITH_QTGUI */
if (0)
;
#endif /* !VBOX_WITH_QTGUI */
else
#ifdef VBOX_WITH_VRDP
if (type == "vrdp")
{
# ifdef RT_OS_WINDOWS
# else
# endif
}
#else /* !VBOX_WITH_VRDP */
if (0)
;
#endif /* !VBOX_WITH_VRDP */
else
#ifdef VBOX_WITH_HEADLESS
if (type == "capture")
{
# ifdef RT_OS_WINDOWS
# else
# endif
}
#else /* !VBOX_WITH_HEADLESS */
if (0)
;
#endif /* !VBOX_WITH_HEADLESS */
else
{
RTEnvDestroy (env);
return setError (E_INVALIDARG,
}
RTEnvDestroy (env);
if (RT_FAILURE (vrc))
return setError (VBOX_E_IPRT_ERROR,
tr ("Could not launch a process for the machine '%ls' (%Rrc)"),
/*
* 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 occur w/o any error info (from RPC), so provide one */
return setError (VBOX_E_VM_ERROR,
}
/* 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);
AutoWriteLock alock (this);
if (!mData->mRegistered)
return setError (E_UNEXPECTED,
return setError (VBOX_E_INVALID_SESSION_STATE,
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 occur w/o any error info (from RPC), so provide one */
return setError (VBOX_E_VM_ERROR,
}
/*
* 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 occur w/o any error info (from RPC), so provide one */
return setError (VBOX_E_VM_ERROR,
/* need to revalidate the state after entering the lock again */
{
aControl->Uninitialize();
return setError (VBOX_E_INVALID_SESSION_STATE,
tr ("The machine '%ls' does not have an open session"),
}
/* store the control in the list */
return S_OK;
}
/**
* Returns @c true if the given machine has an open direct session and returns
* the session machine instance and additional session data (on some platforms)
* if so.
*
* Note that when the method returns @c false, the arguments remain unchanged.
*
* @param aMachine Session machine object.
* @param aControl Direct session control object (optional).
* @param aIPCSem Mutex IPC semaphore handle for this machine (optional).
*
* @note locks this object for reading.
*/
#if defined (RT_OS_WINDOWS)
bool aAllowClosing /*= false*/)
bool aAllowClosing /*= false*/)
#else
bool aAllowClosing /*= false*/)
#endif
{
AutoLimitedCaller autoCaller (this);
/* just return false for inaccessible machines */
return false;
AutoReadLock alock (this);
{
#if defined (RT_OS_WINDOWS) || defined (RT_OS_OS2)
/* Additional session data */
#endif
return true;
}
return false;
}
/**
* Returns @c true if the given machine has an spawning direct session and
* returns and additional session data (on some platforms) if so.
*
* Note that when the method returns @c false, the arguments remain unchanged.
*
* @param aPID PID of the spawned direct session process.
*
* @note locks this object for reading.
*/
#if defined (RT_OS_WINDOWS) || defined (RT_OS_OS2)
#else
bool Machine::isSessionSpawning()
#endif
{
AutoLimitedCaller autoCaller (this);
/* just return false for inaccessible machines */
return false;
AutoReadLock alock (this);
{
#if defined (RT_OS_WINDOWS) || defined (RT_OS_OS2)
/* Additional session data */
{
}
#endif
return true;
}
return false;
}
/**
* Called from the client watcher thread to check for unexpected client process
* death during Session_Spawning state (e.g. before it successfully opened a
* direct session).
*
* On Win32 and on OS/2, this method is called only when we've got the
* direct client's process termination notification, so it always returns @c
* true.
*
* On other platforms, this method returns @c true if the client process is
* terminated and @c false if it's still alive.
*
* @note Locks this object for writing.
*/
bool Machine::checkForSpawnFailure()
{
AutoCaller autoCaller (this);
if (!autoCaller.isOk())
{
/* nothing to do */
LogFlowThisFunc (("Already uninitialized!"));
return true;
}
/* VirtualBox::addProcessToReap() needs a write lock */
{
/* nothing to do */
LogFlowThisFunc (("Not spawning any more!"));
return true;
}
#if defined (RT_OS_WINDOWS) || defined (RT_OS_OS2)
/* the process was already unexpectedly terminated, we just need to set an
* error and finalize session spawning */
tr ("Virtual machine '%ls' has terminated unexpectedly "
"during startup"),
#else
&status);
if (vrc != VERR_PROCESS_RUNNING)
tr ("Virtual machine '%ls' has terminated unexpectedly "
"during startup"),
#endif
{
/* Close the remote session, remove the remote control from the list
* and reset session state to Closed (@note keep the code in sync with
* the relevant part in checkForSpawnFailure()). */
{
}
/* finalize the progress after setting the state, for consistency */
return true;
}
return false;
}
/**
* 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 Must be called from mParent's write lock. Locks this object and
* children for writing.
*/
{
AutoLimitedCaller autoCaller (this);
AutoWriteLock alock (this);
/* wait for state dependants to drop to zero */
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)
return setError (VBOX_E_INVALID_OBJECT_STATE,
tr ("The machine '%ls' with UUID {%s} is already registered"),
}
else
{
return setError (VBOX_E_INVALID_VM_STATE,
tr ("Cannot unregister the machine '%ls' because it "
"is in the Saved state"),
size_t snapshotCount = 0;
if (mData->mFirstSnapshot)
if (snapshotCount)
return setError (VBOX_E_INVALID_OBJECT_STATE,
tr ("Cannot unregister the machine '%ls' because it "
"has %d snapshots"),
return setError (VBOX_E_INVALID_OBJECT_STATE,
tr ("Cannot unregister the machine '%ls' because it has an "
"open session"),
return setError (VBOX_E_INVALID_OBJECT_STATE,
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;
}
/**
* Increases the number of objects dependent on the machine state or on the
* registered state. Guarantees that these two states will not change at least
* until #releaseStateDependency() is called.
*
* Depending on the @a aDepType value, additional state checks may be made.
* These checks will set extended error info on failure. See
* #checkStateDependency() for more info.
*
* If this method returns a failure, the dependency is not added and the caller
* is not allowed to rely on any particular machine state or registration state
* value and may return the failed result code to the upper level.
*
* @param aDepType Dependency type to add.
* @param aState Current machine state (NULL if not interested).
* @param aRegistered Current registered state (NULL if not interested).
*
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
{
if (mData->mMachineStateChangePending != 0)
{
/* ensureNoStateDependencies() is waiting for state dependencies to
* drop to zero so don't add more. It may make sense to wait a bit
* and retry before reporting an error (since the pending state
* transition should be really quick) but let's just assert for
* now to see if it ever happens on practice. */
AssertFailed();
return setError (E_ACCESSDENIED,
tr ("Machine state change is in progress. "
"Please retry the operation later."));
}
++ mData->mMachineStateDeps;
}
if (aState)
if (aRegistered)
return S_OK;
}
/**
* Decreases the number of objects dependent on the machine state.
* Must always complete the #addStateDependency() call after the state
* dependency is no more necessary.
*/
void Machine::releaseStateDependency()
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
/* releaseStateDependency() w/o addStateDependency()? */);
-- mData->mMachineStateDeps;
if (mData->mMachineStateDeps == 0)
{
/* inform ensureNoStateDependencies() that there are no more deps */
if (mData->mMachineStateChangePending != 0)
{
}
}
}
// protected methods
/////////////////////////////////////////////////////////////////////////////
/**
* Performs machine state checks based on the @a aDepType value. If a check
* fails, this method will set extended error info, otherwise it will return
* S_OK. It is supposed, that on failure, the caller will immedieately return
* the return value of this method to the upper level.
*
* When @a aDepType is AnyStateDep, this method always returns S_OK.
*
* When @a aDepType is MutableStateDep, this method returns S_OK only if the
* current state of this machine object allows to change settings of the
* machine (i.e. the machine is not registered, or registered but not running
* and not saved). It is useful to call this method from Machine setters
* before performing any change.
*
* When @a aDepType is MutableOrSavedStateDep, this method behaves the same
* as for MutableStateDep except that if the machine is saved, S_OK is also
* returned. This is useful in setters which allow changing machine
* properties when it is in the saved state.
*
* @param aDepType Dependency type to check.
*
* @note Non Machine based classes should use #addStateDependency() and
* #releaseStateDependency() methods or the smart AutoStateDependency
* template.
*
* @note This method must be called from under this object's read or write
* lock.
*/
{
switch (aDepType)
{
case AnyStateDep:
{
break;
}
case MutableStateDep:
{
if (mData->mRegistered &&
(mType != IsSessionMachine ||
return setError (E_ACCESSDENIED,
tr ("The machine is not mutable (state is %d)"),
break;
}
case MutableOrSavedStateDep:
{
if (mData->mRegistered &&
(mType != IsSessionMachine ||
return setError (E_ACCESSDENIED,
tr ("The machine is not mutable (state is %d)"),
break;
}
}
return S_OK;
}
/**
* Helper to initialize all associated child objects and allocate data
* structures.
*
* This method must be called as a part of the object's initialization procedure
* (usually done in the #init() method).
*
* @note Must be called only from #init() or from #registeredInit().
*/
{
AutoCaller autoCaller (this);
/* allocate data structures */
/* initialize mOSTypeId */
/* create associated BIOS settings object */
mBIOSSettings->init (this);
#ifdef VBOX_WITH_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 associated serial port objects */
{
}
/* create associated parallel port objects */
{
}
/* 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 the SATA controller object (always present, default is disabled) */
mSATAController->init (this);
/* create associated network adapter objects */
{
}
return S_OK;
}
/**
* 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() or from #registeredInit().
*/
void Machine::uninitDataAndChildObjects()
{
AutoCaller autoCaller (this);
/* uninit all children using addDependentChild()/removeDependentChild()
* in their init()/uninit() methods */
/* tell all our other child objects we've been uninitialized */
{
if (mNetworkAdapters [slot])
{
}
}
if (mUSBController)
{
mUSBController->uninit();
}
if (mSATAController)
{
}
if (mAudioAdapter)
{
mAudioAdapter->uninit();
}
{
if (mParallelPorts [slot])
{
}
}
{
if (mSerialPorts [slot])
{
}
}
if (mFloppyDrive)
{
mFloppyDrive->uninit();
}
if (mDVDDrive)
{
}
#ifdef VBOX_WITH_VRDP
if (mVRDPServer)
{
mVRDPServer->uninit();
}
#endif
if (mBIOSSettings)
{
mBIOSSettings->uninit();
}
/* Deassociate hard disks (only when a real Machine or a SnapshotMachine
* instance is uninitialized; SessionMachine instances refer to real
* Machine hard disks). This is necessary for a clean re-initialization of
* the VM after successfully re-checking the accessibility state. Note
* that in case of normal Machine or SnapshotMachine uninitialization (as
* a result of unregistering or discarding the snapshot), outdated hard
* disk attachments will already be uninitialized and deleted, so this
* code will not affect them. */
{
++ it)
{
snapshotId());
AssertComRC (rc);
}
}
{
/* reset some important fields of mData */
}
/* free data structures (the essential mData structure is not freed here
* since it may be still in use) */
}
/**
* Makes sure that there are no machine state dependants. If necessary, waits
* for the number of dependants to drop to zero.
*
* Make sure this method is called from under this object's write lock to
* guarantee that no new dependants may be added when this method returns
* control to the caller.
*
* @note Locks this object for writing. The lock will be released while waiting
* (if necessary).
*
* @warning To be used only in methods that change the machine state!
*/
void Machine::ensureNoStateDependencies()
{
AutoWriteLock alock (this);
/* Wait for all state dependants if necessary */
if (mData->mMachineStateDeps != 0)
{
/* lazy semaphore creation */
LogFlowThisFunc (("Waiting for state deps (%d) to drop to zero...\n",
/* reset the semaphore before waiting, the last dependant will signal
* it */
}
}
/**
* Changes the machine state and informs callbacks.
*
* This method is not intended to fail so it either returns S_OK or asserts (and
* returns a failure).
*
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
/* wait for state dependants to drop to zero */
{
}
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);
try
{
using namespace settings;
using namespace xml;
/* no concurrent file access is possible in init() so open by handle */
/* 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 {%RTuuid} in '%ls' doesn't match its "
"UUID {%s} in the registry file '%ls'"),
}
}
else
/* name (required) */
/* nameSync (optional, default is true) */
/* Description (optional, default is null) */
{
else
}
/* OSType (required) */
{
/* look up the object by Id to check it is valid */
}
/* stateFile (optional) */
{
if (stateFilePath)
{
if (RT_FAILURE (vrc))
{
tr ("Invalid saved state file path '%ls' (%Rrc)"),
}
}
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
*/
Guid());
/* snapshotFolder (optional) */
{
}
/* currentStateModified (optional, default is true) */
/* lastStateChange (optional, defaults to now) */
{
}
/* aborted (optional, default is false) */
/*
* 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) */
{
if (!snapshotNode.isNull())
{
/* read all snapshots recursively */
}
}
/* Hardware node (required) */
/* HardDiskAttachments node (required) */
/*
* 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 checkStateDependency (MutableStateDep).
*/
/* set the machine state to Aborted or Saved when appropriate */
if (aborted)
{
/* no need to use setMachineState() during init() */
}
else if (mSSData->mStateFilePath)
{
/* no need to use setMachineState() during init() */
}
}
{
/* we assume that error info is set by the thrower */
}
catch (...)
{
}
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.
*/
const Guid &aCurSnapshotId,
{
using namespace settings;
/* create a snapshot machine object */
/* required */
{
/* optional */
if (stateFilePath)
{
if (RT_FAILURE (vrc))
tr ("Invalid saved state file path '%ls' (%Rrc)"),
}
/* Hardware node (required) */
/* HardDiskAttachments node (required) */
/* initialize the snapshot machine */
}
/* create a snapshot object */
{
/* required */
/* required */
/* optional */
{
}
/* initialize the snapshot */
}
/* memorize the first snapshot if necessary */
if (!mData->mFirstSnapshot)
/* memorize the current snapshot when appropriate */
/* Snapshots node (optional) */
{
if (!snapshotsNode.isNull())
{
{
}
}
}
return rc;
}
/**
* @param aNode <Hardware> node.
*/
{
using namespace settings;
/* CPU node (currently not required) */
{
/* default value in case the node is not there */
mHWData->mHWVirtExNestedPagingEnabled = false;
mHWData->mHWVirtExVPIDEnabled = false;
mHWData->mPAEEnabled = false;
{
if (!hwVirtExNode.isNull())
{
else
}
/* HardwareVirtExNestedPaging (optional, default is false) */
if (!HWVirtExNestedPagingNode.isNull())
{
}
/* HardwareVirtExVPID (optional, default is false) */
if (!HWVirtExVPIDNode.isNull())
{
}
/* PAE (optional, default is false) */
{
}
/* CPUCount (optional, default is 1) */
}
}
/* Memory node (required) */
{
}
/* Boot node (required) */
{
/* reset all boot order positions to NoDevice */
{
/* position (required) */
/* position unicity is guaranteed by XML Schema */
-- position;
/* device (required) */
else
}
}
/* Display node (required) */
{
}
#ifdef VBOX_WITH_VRDP
/* RemoteDisplay */
#endif
/* BIOS */
/* DVD drive */
/* Floppy drive */
/* USB Controller */
/* SATA Controller */
/* Network node (required) */
{
/* we assume that all network adapters are initially disabled
* and detached */
{
/* slot number (required) */
/* slot unicity is guaranteed by XML Schema */
}
}
/* Serial node (required) */
{
{
/* slot number (required) */
/* slot unicity is guaranteed by XML Schema */
}
}
/* Parallel node (optional) */
{
{
/* slot number (required) */
/* slot unicity is guaranteed by XML Schema */
}
}
/* AudioAdapter */
/* Shared folders (required) */
{
{
/* folder logical name (required) */
/* folder host path (required) */
}
}
/* Clipboard node (required) */
{
else
}
/* Guest node (required) */
{
/* optional, defaults to 0 */
/* optional, defaults to 0 */
}
#ifdef VBOX_WITH_GUEST_PROPS
/* Guest properties (optional) */
{
using namespace guestProp;
if (!guestPropertiesNode.isNull())
{
{
/* property name (required) */
/* property value (required) */
/* property timestamp (optional, defaults to 0) */
/* property flags (optional, defaults to empty) */
return E_OUTOFMEMORY;
/* This is just sanity, as the push_back() will probably have thrown
* an exception if we are out of memory. Note that if we run out
* allocating the Bstrs above, this will be caught here as well. */
)
return E_OUTOFMEMORY;
}
}
mHWData->mPropertyServiceActive = false;
return E_OUTOFMEMORY;
}
#endif /* VBOX_WITH_GUEST_PROPS defined */
AssertComRC (rc);
return rc;
}
/**
* @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
*
* @note May lock mParent for reading and hard disks for writing.
*/
{
using namespace settings;
{
/* 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)"),
}
/* Make sure the attached hard disks don't get unregistered until we
* associate them with tis machine (important for VMs loaded (opened) after
* VirtualBox startup) */
{
/* hard disk uuid (required) */
/* bus (controller) type (required) */
/* channel (required) */
/* device (required) */
/* find a hard disk by UUID */
{
if (mType == IsSnapshotMachine)
tr ("Immutable hard disk '%ls' with UUID {%RTuuid} cannot be "
"directly attached to snapshot with UUID {%RTuuid} "
"of the virtual machine '%ls' ('%ls')"),
aSnapshotId->raw(),
tr ("Immutable hard disk '%ls' with UUID {%RTuuid} cannot be "
"directly attached to the virtual machine '%ls' ('%ls')"),
}
tr ("Hard disk '%ls' with UUID {%RTuuid} cannot be directly "
"attached to the virtual machine '%ls' ('%ls') "
"because it has %d differencing child hard disks"),
{
tr ("Hard disk '%ls' with UUID {%RTuuid} is already attached "
"to the virtual machine '%ls' ('%ls')"),
}
else
/* associate the hard disk with this machine and snapshot */
if (mType == IsSnapshotMachine)
else
/* backup mHDData to let registeredInit() properly rollback on failure
* (= limited accessibility) */
}
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.
*/
{
using namespace settings;
if (aSnapshotsNode)
aSnapshotNode->setNull();
// build the full uuid path (from the top parent to the given snapshot)
{
while (parent)
{
}
}
++ it)
{
if (!snapshotNode.isNull())
{
/* proceed to the nested <Snapshots> node */
}
++ ch)
{
{
/* pass over to the outer loop */
snapshotNode = *ch;
break;
}
}
if (!snapshotNode.isNull())
continue;
/* the next uuid is not found, no need to continue... */
}
// we must always succesfully find the node
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;
}
/**
* 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 but only from #saveSettings().
*
* @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.
*/
{
/* Note: tecnhically, mParent needs to be locked only when the machine is
* registered (see prepareSaveSettings() for details) but we don't
* currently differentiate it in callers of saveSettings() so we don't
* make difference here too. */
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 (RT_FAILURE (vrc))
{
tr ("Could not rename the directory '%s' to '%s' "
"to save the settings file (%Rrc)"),
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 (RT_FAILURE (vrc))
{
tr ("Could not rename the settings file '%s' to '%s' "
"(%Rrc)"),
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 (RT_FAILURE (vrc))
{
tr ("Could not create a directory '%s' "
"to save the settings file (%Rrc)"),
}
}
/* Note: open flags must correlate with RTFileOpen() in lockConfig() */
if (RT_SUCCESS (vrc))
{
(void *) DefaultMachineConfig,
sizeof (DefaultMachineConfig), NULL);
}
if (RT_FAILURE (vrc))
{
tr ("Could not create the settings file '%s' (%Rrc)"),
}
/* we do not close the file to simulate lockConfig() */
}
return rc;
}
/**
* Saves and commits machine data, user data and hardware data.
*
* Note that on failure, the data remains uncommitted.
*
* @a aFlags may combine the following flags:
*
* - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
* Used when saving settings after an operation that makes them 100%
* correspond to the settings from the current snapshot.
* - SaveS_InformCallbacksAnyway: 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 Must be called from under mParent write lock (sometimes needed by
* #prepareSaveSettings()) and this object's write lock. Locks children for
* writing. There is one exception when mParent is unused and therefore may be
* left unlocked: if this machine is an unregistered one.
*/
{
/* Note: tecnhically, mParent needs to be locked only when the machine is
* registered (see prepareSaveSettings() for details) but we don't
* currently differentiate it in callers of saveSettings() so we don't
* make difference here too. */
/* make sure child objects are unable to modify the settings while we are
* saving them */
bool settingsModified;
{
/* 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 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;
try
{
using namespace settings;
using namespace xml;
/* this object is locked for writing to prevent concurrent reads and writes */
/* The newly created settings file is incomplete therefore we turn off
* validation. The rest is like in loadSettingsTree_ForUpdate().*/
!isNew /* aValidate */,
false /* aCatchLoadErrors */,
false /* aAddDefaults */);
/* uuid (required) */
/* name (required) */
/* nameSync (optional, default is true) */
/* Description node (optional) */
{
}
else
{
}
/* OSType (required) */
/* stateFile (optional) */
{
/* try to make the file name relative to the settings file dir */
}
else
{
}
/* currentSnapshot ID (optional) */
{
}
else
{
}
/* snapshotFolder (optional) */
/// @todo use the Bstr::NullOrEmpty constant and setValueOr
else
/* currentStateModified (optional, default is true) */
!!currentStateModified, true);
/* lastStateChange */
/* set the aborted attribute when appropriate, defaults to false */
false);
/* Hardware node (required) */
{
/* first, delete the entire node if exists */
/* then recreate it */
}
/* HardDiskAttachments node (required) */
{
/* first, delete the entire node if exists */
/* then recreate it */
}
/* ask to save all snapshots when the machine name was changed since
* it may affect saved state file paths for online snapshots (see
* #openConfigLoader() for details) */
if (isRenamed)
{
}
/* save the settings on success */
}
{
/* we assume that error info is set by the thrower */
}
catch (...)
{
}
{
commit();
/* memorize the new modified state */
}
{
/* 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);
/* This object's write lock is also necessary to serialize file access
* (prevent concurrent reads and writes) */
AutoWriteLock alock (this);
try
{
using namespace settings;
using namespace xml;
/* load the settings file */
/* save settings on success */
}
catch (...)
{
}
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.
*/
{
using namespace settings;
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 */
if (!snapshotNode.isNull())
snapshotNode.zap();
/* 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)
{
if (parent)
{
}
do
{
if (!parentNode.isNull())
else
do
{
/* when a new snapshot is added, this means diffs were created
* save the current hard disk attachments */
{
/* 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);
}
while (0);
break;
}
op == SaveSS_UpdateAllOp);
if (!recreateWholeTree)
{
}
if (snapshotsNode.isNull())
if (op == SaveSS_UpdateAttrsOp)
else
{
if (!snapshotNode.isNull())
snapshotNode.zap();
}
}
while (0);
{
/* update currentSnapshot when appropriate */
if (aOpFlags & SaveSS_CurrentId)
{
else
}
if (aOpFlags & SaveSS_CurStateModified)
{
/* defaults to true */
!!mData->mCurrentStateModified, true);
}
}
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.
*/
{
using namespace settings;
/* uuid (required) */
if (!aAttrsOnly)
/* name (required) */
/* timeStamp (required) */
/* Description node (optional) */
{
}
else
{
}
if (aAttrsOnly)
return S_OK;
/* stateFile (optional) */
if (aSnapshot->stateFilePath())
{
/* try to make the file name relative to the settings file dir */
}
{
/* save hardware */
{
}
/* save hard disks */
{
}
}
/* save children */
{
{
++ it)
{
}
}
}
return S_OK;
}
/**
* 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.
*/
{
using namespace settings;
/* CPU (optional, but always created atm) */
{
switch (mHWData->mHWVirtExEnabled)
{
case TSBool_False:
value = "false";
break;
case TSBool_True:
value = "true";
break;
case TSBool_Default:
value = "default";
break;
}
/* Nested paging (optional, default is false) */
{
}
/* VPID (optional, default is false) */
if (mHWData->mHWVirtExVPIDEnabled)
{
}
/* PAE (optional, default is false) */
if (mHWData->mPAEEnabled)
{
}
/* CPU count */
}
/* memory (required) */
{
}
/* boot (required) */
{
{
{
case DeviceType_Null:
/* skip, this is allowed for <Order> nodes
* when loading, the default value NoDevice will remain */
continue;
default:
{
ComAssertMsgFailedRet (("Invalid boot device: %d",
E_FAIL);
}
}
}
}
/* display (required) */
{
}
#ifdef VBOX_WITH_VRDP
/* VRDP settings (optional) */
#endif
/* BIOS (required) */
/* DVD drive (required) */
/* Flooppy drive (required) */
/* USB Controller (required) */
/* SATA Controller (required) */
/* Network adapters (required) */
{
{
}
}
/* Serial ports */
{
{
}
}
/* Parallel ports */
{
{
}
}
/* Audio adapter */
/* Shared folders */
{
++ it)
{
/* all are mandatory */
}
}
/* Clipboard */
{
const char *modeStr = "Disabled";
switch (mHWData->mClipboardMode)
{
case ClipboardMode_Disabled:
/* already assigned */
break;
modeStr = "HostToGuest";
break;
modeStr = "GuestToHost";
break;
modeStr = "Bidirectional";
break;
default:
ComAssertMsgFailedRet (("Clipboard mode %d is invalid",
E_FAIL);
}
}
/* Guest */
{
}
#ifdef VBOX_WITH_GUEST_PROPS
/* Guest properties */
try
{
using namespace guestProp;
{
return E_OUTOFMEMORY;
}
return E_OUTOFMEMORY;
emptyStr);
}
{
return E_OUTOFMEMORY;
}
#endif /* VBOX_WITH_GUEST_PROPS defined */
AssertComRC (rc);
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.
*/
{
using namespace settings;
++ it)
{
{
{
default:
}
/* hard disk uuid (required) */
/* bus (controller) type (required) */
/* channel (required) */
/* device (required) */
}
}
return S_OK;
}
/**
* Saves machine state settings as defined by aFlags
* (SaveSTS_* values).
*
* @param aFlags Combination of SaveSTS_* flags.
*
* @note Locks objects for writing.
*/
{
if (aFlags == 0)
return S_OK;
AutoCaller autoCaller (this);
/* This object's write lock is also necessary to serialize file access
* (prevent concurrent reads and writes) */
AutoWriteLock alock (this);
try
{
using namespace settings;
using namespace xml;
/* load the settings file */
if (aFlags & SaveSTS_CurStateModified)
{
/* defaults to true */
!!mData->mCurrentStateModified, true);
}
if (aFlags & SaveSTS_StateFilePath)
{
if (mSSData->mStateFilePath)
{
/* try to make the file name relative to the settings file dir */
}
else
}
if (aFlags & SaveSTS_StateTimeStamp)
{
/* set the aborted attribute when appropriate, defaults to false */
false);
}
/* save settings on success */
}
catch (...)
{
}
return rc;
}
/**
* Creates differencing hard disks for all normal hard disks attached to this
* machine and a new set of attachments to refer to created disks.
*
* Used when taking a snapshot or when discarding the current state.
*
* This method assumes that mHDData contains the original hard disk attachments
* it needs to create diffs for. On success, these attachments will be replaced
* with the created diffs. On failure, #deleteImplicitDiffs() is implicitly
* called to delete created diffs which will also rollback mHDData and restore
* whatever was backed up before calling this method.
*
* Attachments with non-normal hard disks are left as is.
*
* If @a aOnline is @c false then the original hard disks that require implicit
* diffs will be locked for reading. Otherwise it is assumed that they are
* already locked for writing (when the VM was started). Note that in the latter
* case it is responsibility of the caller to lock the newly created diffs for
* writing if this method succeeds.
*
* @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 hard disks
* attached).
* @param aOnline Whether the VM was online prior to this operation.
*
* @note The progress object is not marked as completed, neither on success nor
* on failure. This is a responsibility of the caller.
*
* @note Locks this object for writing.
*/
bool aOnline)
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
/* must be in a protective state because we leave the lock below */
try
{
if (!aOnline)
{
/* lock all attached hard disks early to detect "in use"
* situations before creating actual diffs */
++ it)
{
}
}
/* remember the current list (note that we don't use backup() since
* mHDData may be already backed up) */
/* start from scratch */
/* go through remembered attachments and create diffs for normal hard
* disks and attach them */
{
/* type cannot be changed while attached => no need to lock */
{
/* copy the attachment as is */
continue;
}
/* need a diff */
diff.createObject();
/* leave the lock before the potentially lengthy operation */
/* add a new attachment */
}
}
/* unlock all hard disks we locked */
if (!aOnline)
{
{
AssertComRC (rc2);
}
}
{
mrc = deleteImplicitDiffs();
}
return rc;
}
/**
* Deletes implicit differencing hard disks created either by
* #createImplicitDiffs() or by #AttachHardDisk2() and rolls back mHDData.
*
* Note that to delete hard disks created by #AttachHardDisk2() this method is
* called from #fixupHardDisks2() when the changes are rolled back.
*
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
/* enumerate new attachments */
{
if ((*it)->isImplicit())
{
continue;
}
/* was this hard disk attached before? */
{
/* no: de-associate */
AssertComRC (rc);
}
}
/* rollback hard disk changes */
/* delete unused implicit diffs */
if (implicitAtts.size() != 0)
{
/* will leave the lock before the potentially lengthy
* operation, so protect with the special state (unless already
* protected) */
if (oldState != MachineState_Saving &&
{
}
{
/// @todo NEWMEDIA report the error as a warning here. Note that
/// we cannot simply abort the rollback because parts of machine
/// data may have been already restored from backup and
/// overwrote the recent changes. The best we can do is to
/// deassociate the hard disk (to prevent the consistency) but
/// leave it undeleted.
{
AssertComRC (rc);
}
}
{
}
}
return rc;
}
/**
* Perform deferred hard disk detachments on success and deletion of implicitly
* created diffs on failure.
*
* Does nothing if the hard disk attachment data (mHDData) is not changed (not
* backed up).
*
* When the data is backed up, this method will commit mHDData if @a aCommit is
* @c true and rollback it otherwise before returning.
*
* If @a aOnline is @c true then this method called with @a aCommit = @c true
* will also unlock the old hard disks for which the new implicit diffs were
* created and will lock these new diffs for writing. When @a aCommit is @c
* false, this argument is ignored.
*
* @param aCommit @c true if called on success.
* @param aOnline Whether the VM was online prior to this operation.
*
* @note Locks this object for writing!
*/
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
if (!mHDData.isBackedUp())
return;
if (aCommit)
{
/* enumerate new attachments */
{
if ((*it)->isImplicit())
{
/* convert implicit attachment to normal */
(*it)->setImplicit (false);
if (aOnline)
{
AssertComRC (rc);
/* also, relock the old hard disk which is a base for the
* new diff for reading if the VM is online */
/* make the relock atomic */
AssertComRC (rc);
AssertComRC (rc);
}
continue;
}
/* was this hard disk attached before? */
{
/* yes: remove from old to avoid de-association */
}
}
/* enumerate remaining old attachments and de-associate from the
* current machine state */
{
/* now de-associate from the current machine state */
AssertComRC (rc);
if (aOnline)
{
/* unlock since not used anymore */
/* the disk may be alredy relocked for reading above */
}
}
/* commit the hard disk changes */
if (mType == IsSessionMachine)
{
/* attach new data to the primary machine and reshare it */
}
}
else
{
}
return;
}
/**
* 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 (RT_FAILURE (vrc))
{
tr ("Could not lock the settings file '%ls' (%Rrc)"),
}
}
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())
{
/** @todo flush the directory. */
}
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);
AutoReadLock alock (this);
return true;
return true;
return true;
return
mUserData.isBackedUp() ||
mHWData.isBackedUp() ||
mHDData.isBackedUp() ||
#ifdef VBOX_WITH_VRDP
#endif
}
/**
* Returns the logical OR of data.hasActualChanges() of this and all child
* objects.
*
* @param aIgnoreUserData @c true to ignore changes to mUserData
*
* @note Locks objects for reading!
*/
{
AutoCaller autoCaller (this);
AutoReadLock alock (this);
return true;
return true;
return true;
return
mHWData.hasActualChanges() ||
mHDData.hasActualChanges() ||
#ifdef VBOX_WITH_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);
AutoWriteLock alock (this);
/* check for changes in own data */
bool sharedFoldersChanged = false;
{
sharedFoldersChanged = true;
else
{
++ rit)
{
++ cit)
{
{
sharedFoldersChanged = true;
break;
}
}
}
}
}
if (mHDData.isBackedUp())
fixupHardDisks2 (false /* aCommit */);
/* check for changes in child objects */
usbChanged = false, sataChanged = false;
if (mBIOSSettings)
#ifdef VBOX_WITH_VRDP
if (mVRDPServer)
#endif
if (mDVDDrive)
if (mFloppyDrive)
if (mAudioAdapter)
if (mUSBController)
if (mSATAController)
if (mNetworkAdapters [slot])
if (mSerialPorts [slot])
if (mParallelPorts [slot])
if (aNotify)
{
/* inform the direct session about changes */
if (sharedFoldersChanged)
if (vrdpChanged)
if (dvdChanged)
that->onDVDDriveChange();
if (floppyChanged)
if (usbChanged)
if (sataChanged)
if (networkAdapters [slot])
if (serialPorts [slot])
if (parallelPorts [slot])
}
}
/**
* Commits all the changes to machine settings.
*
* Note that this operation is supposed to never fail.
*
* @note Locks this object and children for writing.
*/
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
/*
* use safe commit to ensure Snapshot machines (that share mUserData)
* will still refer to a valid memory location
*/
if (mHDData.isBackedUp())
fixupHardDisks2 (true /* aCommit */);
mBIOSSettings->commit();
#ifdef VBOX_WITH_VRDP
mVRDPServer->commit();
#endif
mFloppyDrive->commit();
mAudioAdapter->commit();
mUSBController->commit();
if (mType == IsSessionMachine)
{
/* attach new data to the primary machine and reshare it */
/* mHDData is reshared by fixupHardDisks2 */
// mPeer->mHDData.attach (mHDData);
}
}
/**
* 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_WITH_VRDP
#endif
}
#ifdef VBOX_WITH_RESOURCE_USAGE_API
{
/* Create sub metrics */
"Percentage of processor time spent in user mode by VM process.");
"Percentage of processor time spent in kernel mode by VM process.");
"Size of resident portion of VM process in memory.");
/* Create and register base metrics */
new pm::AggregateAvg()));
new pm::AggregateMin()));
new pm::AggregateMax()));
new pm::AggregateAvg()));
new pm::AggregateMin()));
new pm::AggregateMax()));
new pm::AggregateAvg()));
new pm::AggregateMin()));
new pm::AggregateMax()));
};
{
};
#endif /* VBOX_WITH_RESOURCE_USAGE_API */
/////////////////////////////////////////////////////////////////////////////
// SessionMachine class
/////////////////////////////////////////////////////////////////////////////
/** Task structure for asynchronous VM operations */
struct SessionMachine::Task
{
, subTask (false)
{}
void modifyLastState (MachineState_T s)
{
*const_cast <MachineState_T *> (&state) = s;
}
virtual void handler() = 0;
const MachineState_T state;
bool subTask : 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(RT_OS_WINDOWS)
#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
mIPCSem = -1;
#else
# error "Port me!"
#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(RT_OS_WINDOWS)
if (mIPCSemName[i] == '\\')
mIPCSemName[i] = '/';
("Cannot create IPC mutex '%ls', err=%d",
E_FAIL);
("Cannot create IPC mutex '%s', arc=%ld",
E_FAIL);
#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
char *configFileCP = NULL;
int error;
{
tr ("Cannot create IPC semaphore. Most likely your host kernel lacks "
"support for SysV IPC. Check the host kernel configuration for "
"CONFIG_SYSVIPC=y"));
return E_FAIL;
}
E_FAIL);
/* set the initial value to 1 */
E_FAIL);
#else
# error "Port me!"
#endif
/* memorize the peer Machine */
/* share the parent pointer */
/* take the pointers to data to share */
#ifdef VBOX_WITH_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 a list of serial ports that will be mutable */
{
}
/* create a list of parallel ports that will be mutable */
{
}
/* create another USB controller object that will be mutable */
/* create another SATA 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 sequense
* below, the following is enough.
*/
LogFlowThisFunc (("Initialization failed.\n"));
#if defined(RT_OS_WINDOWS)
if (mIPCSem)
::CloseHandle (mIPCSem);
if (mIPCSem != NULLHANDLE)
::DosCloseMutexSem (mIPCSem);
#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
if (mIPCSem >= 0)
mIPCSem = -1;
#else
# error "Port me!"
#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. */
#ifdef VBOX_WITH_RESOURCE_USAGE_API
#endif /* VBOX_WITH_RESOURCE_USAGE_API */
{
LogWarningThisFunc (("ABNORMAL client termination! (wasRunning=%d)\n",
/* reset the state to Aborted */
}
if (isModified())
{
LogWarningThisFunc (("Discarding unsaved settings changes!\n"));
rollback (false /* aNotify */);
}
{
LogWarningThisFunc (("canceling failed save state request!\n"));
}
{
LogWarningThisFunc (("canceling untaken snapshot!\n"));
}
#ifdef VBOX_WITH_USB
/* release all captured USB devices */
{
/* Console::captureUSBDevices() is called in the VM process only after
* setting the machine state to Starting or Restoring.
* Console::detachAllUSBDevices() will be called upon successful
* termination. So, we need to release USB devices only if there was
* an abnormal termination of a running VM.
*
* This is identical to SessionMachine::DetachAllUSBDevices except
* for the aAbnormal argument. */
AssertComRC (rc);
if (service)
}
#endif /* VBOX_WITH_USB */
{
/* 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 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(RT_OS_WINDOWS)
if (mIPCSem)
::CloseHandle (mIPCSem);
if (mIPCSem != NULLHANDLE)
::DosCloseMutexSem (mIPCSem);
#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
if (mIPCSem >= 0)
mIPCSem = -1;
#else
# error "Port me!"
#endif
/* fire an event */
/* free the essential data structure last */
/* leave the shared lock before setting the below two to NULL */
}
// util::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);
AutoReadLock alock (this);
#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
return S_OK;
#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
return S_OK;
#else
# error "Port me!"
#endif
}
/**
* 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.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
#ifdef VBOX_WITH_USB
#else
#endif
return S_OK;
}
/**
* @note Locks the same as Host::captureUSBDevice() does.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
#ifdef VBOX_WITH_USB
/* if captureDeviceForVM() fails, it must have set extended error info */
#else
return E_FAIL;
#endif
}
/**
* @note Locks the same as Host::detachUSBDevice() does.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
#ifdef VBOX_WITH_USB
#else
return E_FAIL;
#endif
}
/**
* Inserts all machine filters to the USB proxy service and then calls
* Host::autoCaptureUSBDevices().
*
* Called by Console from the VM process upon VM startup.
*
* @note Locks what called methods lock.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
#ifdef VBOX_WITH_USB
AssertComRC (rc);
return service->autoCaptureDevicesForVM (this);
#else
return S_OK;
#endif
}
/**
* Removes all machine filters from the USB proxy service and then calls
* Host::detachAllUSBDevices().
*
* Called by Console from the VM process upon normal VM termination or by
* SessionMachine::uninit() upon abnormal VM termination (from under the
* Machine/SessionMachine lock).
*
* @note Locks what called methods lock.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
#ifdef VBOX_WITH_USB
AssertComRC (rc);
#else
return S_OK;
#endif
}
/**
* @note Locks 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 */
AutoWriteLock alock (this);
{
/* 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. */
}
else
{
/* the remote session is being normally closed */
{
break;
++it;
}
}
return S_OK;
}
/**
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
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 object 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 this object for writing.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
E_FAIL);
if (RT_FAILURE (vrc))
tr ("Invalid saved state file path '%ls' (%Rrc)"),
/* The below setMachineState() will detect the state transition and will
* update the settings file */
return setMachineState (MachineState_Saved);
}
/**
* @note Locks mParent + this object for writing.
*/
{
AutoCaller autoCaller (this);
/* saveSettings() needs mParent lock */
E_FAIL);
{
/* save all current settings to ensure current changes are committed and
* hard disks are fixed up */
}
/// @todo NEWMEDIA so far, we decided to allow for Writhethrough hard disks
/// when taking snapshots putting all the responsibility to the user...
#if 0
/* check that there are no Writethrough hard disks attached */
++ it)
{
tr ("Cannot take a snapshot because the Writethrough hard disk "
"'%ls' is attached to this virtual machine"),
}
#endif
/* 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)
{
}
/* 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
* hard disks + 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 (RT_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 this object for writing.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
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);
/* saveSettings() needs mParent lock */
{
if (childrenCount > 1)
tr ("Snapshot '%ls' of the machine '%ls' 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 hard disks + 1 if the snapshot is online
*/
FALSE /* aCancelable */,
/* create and start the task on a separate thread */
(void *) task,
0, RTTHREADTYPE_MAIN_WORKER, 0, "DiscardSnapshot");
if (RT_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 this + children objects for writing!
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
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 hard disks + 1 (if we need to copy the saved state file) */
{
++ opCount;
}
/* 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, "DiscardCurState");
if (RT_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 thos object for writing!
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
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 hard disks in the current snapshot +
* # of hard disks in the previous snapshot +
* 1 if we need to copy the saved state file of the previous snapshot +
* 1 if the current snapshot is online
* or (if there is no previous snapshot):
* 1 (preparing) + # of hard disks in the current snapshot * 2 +
* 1 if we need to copy the saved state file of the current snapshot * 2
*/
{
if (prevSnapshot)
{
if (prevSnapshot->stateFilePath())
++ opCount;
if (curSnapshot->stateFilePath())
++ opCount;
}
else
{
opCount +=
if (curSnapshot->stateFilePath())
opCount += 2;
}
}
/* create and start the task on a separate thread */
(void *) task,
0, RTTHREADTYPE_MAIN_WORKER, 0, "DiscardCurStSnp");
if (RT_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;
}
STDMETHODIMP SessionMachine::PullGuestProperties (ComSafeArrayOut(BSTR, aNames), ComSafeArrayOut(BSTR, aValues),
{
LogFlowThisFunc (("\n"));
#ifdef VBOX_WITH_GUEST_PROPS
using namespace guestProp;
AutoCaller autoCaller (this);
AutoReadLock alock (this);
unsigned i = 0;
{
++i;
}
mHWData->mPropertyServiceActive = true;
return S_OK;
#else
#endif
}
{
LogFlowThisFunc (("\n"));
#ifdef VBOX_WITH_GUEST_PROPS
using namespace guestProp;
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
/* Temporarily reset the registered flag, so that our machine state
* changes (i.e. mHWData.backup()) succeed. (isMutable() used in
* all setters will return FALSE for a Machine instance if mRegistered
* is TRUE). This is copied from registeredInit(), and may or may not be
* the right way to handle this. */
// ComAssertRet (mData->mMachineState < MachineState_Running, E_FAIL);
{
}
mHWData->mPropertyServiceActive = false;
SaveSettings();
/* Restore the mRegistered flag. */
return S_OK;
#else
#endif
}
{
LogFlowThisFunc (("\n"));
#ifdef VBOX_WITH_GUEST_PROPS
using namespace guestProp;
return E_POINTER;
return E_POINTER; /* aValue can be NULL to indicate deletion */
|| utf8Patterns.isNull()
)
return E_OUTOFMEMORY;
return E_INVALIDARG;
bool matchAll = false;
if (0 == utf8Patterns.length())
matchAll = true;
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
{
break;
}
{
}
/* send a callback notification if appropriate */
if ( matchAll
)
return S_OK;
#else
#endif
}
// public methods only for internal purposes
/////////////////////////////////////////////////////////////////////////////
/**
* Called from the client watcher thread to check for expected or unexpected
* death of the client process that has a direct session to this machine.
*
* On Win32 and on OS/2, this method is called only when we've got the
* mutex (i.e. the client has either died or terminated normally) so it always
* returns @c true (the client is terminated, the session machine is
* uninitialized).
*
* On other platforms, the method returns @c true if the client process has
* terminated normally or abnormally and the session machine was uninitialized,
* and @c false if the client process is still alive.
*
* @note Locks this object for writing.
*/
bool SessionMachine::checkForDeath()
{
bool terminated = 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;
}
AutoWriteLock alock (this);
/* 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(RT_OS_WINDOWS)
/* release the IPC mutex */
::ReleaseMutex (mIPCSem);
terminated = true;
/* release the IPC mutex */
terminated = true;
#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
if (val > 0)
{
/* the semaphore is signaled, meaning the session is terminated */
terminated = true;
}
#else
# error "Port me!"
#endif
} /* AutoCaller block */
if (terminated)
return terminated;
}
/**
* @note Locks this object for reading.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
{
AutoReadLock 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);
{
AutoReadLock 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);
{
AutoReadLock 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);
{
AutoReadLock 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);
{
AutoReadLock 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);
{
AutoReadLock 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);
{
AutoReadLock 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);
{
AutoReadLock alock (this);
}
/* ignore notifications sent after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
}
/**
* Returns @c true if this machine's USB controller reports it has a matching
* filter for the given USB device and @c false otherwise.
*
* @note Locks this object for reading.
*/
bool SessionMachine::hasMatchingUSBFilter (const ComObjPtr <HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
{
AutoCaller autoCaller (this);
/* silently return if not ready -- this method may be called after the
* direct machine session has been called */
if (!autoCaller.isOk())
return false;
AutoReadLock alock (this);
#ifdef VBOX_WITH_USB
switch (mData->mMachineState)
{
case MachineState_Starting:
case MachineState_Restoring:
case MachineState_Paused:
case MachineState_Running:
default: break;
}
#endif
return false;
}
/**
* @note The calls shall hold no locks. Will temporarily lock this object for reading.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
/* This notification may happen after the machine object has been
* uninitialized (the session was closed), so don't assert. */
{
AutoReadLock alock (this);
}
/* fail on notifications sent after #OnSessionEnd() is called, it is
* expected by the caller */
if (!directControl)
return E_FAIL;
/* No locks should be held at this point. */
AssertMsg (RTThreadGetWriteLockCount (RTThreadSelf()) == 0, ("%d\n", RTThreadGetWriteLockCount (RTThreadSelf())));
AssertMsg (RTThreadGetReadLockCount (RTThreadSelf()) == 0, ("%d\n", RTThreadGetReadLockCount (RTThreadSelf())));
}
/**
* @note The calls shall hold no locks. Will temporarily lock this object for reading.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
/* This notification may happen after the machine object has been
* uninitialized (the session was closed), so don't assert. */
{
AutoReadLock alock (this);
}
/* fail on notifications sent after #OnSessionEnd() is called, it is
* expected by the caller */
if (!directControl)
return E_FAIL;
/* No locks should be held at this point. */
AssertMsg (RTThreadGetWriteLockCount (RTThreadSelf()) == 0, ("%d\n", RTThreadGetWriteLockCount (RTThreadSelf())));
AssertMsg (RTThreadGetReadLockCount (RTThreadSelf()) == 0, ("%d\n", RTThreadGetReadLockCount (RTThreadSelf())));
}
// 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);
/* saveSettings() 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 to finalize the
* "take snapshot" procedure.
*
* Expected to be called after completing *all* the tasks related to taking the
* snapshot, either successfully or unsuccessfilly.
*
* @param aSuccess TRUE if the snapshot has been taken successfully.
*
* @note Locks this objects for writing.
*/
{
AutoCaller autoCaller (this);
AutoWriteLock alock (this);
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 */
}
}
{
/* inform callbacks */
}
else
{
/* 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 hard disks created (this will also attach
* their parents back by rolling back mHDData) */
fixupHardDisks2 (false /* aCommit */);
/* delete the saved state file (it might have been already created) */
}
/* 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 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 */
return;
}
AutoWriteLock alock (this);
LogFlowThisFunc (("Creating differencing hard disks (online=%d)...\n",
online));
/* create new differencing hard disks and attach them to this machine */
online);
{
LogFlowThisFunc (("Copying the execution state from '%s' to '%s'...\n",
/* Leave the lock before a lengthy operation (mMachineState is
* MachineState_Saving here) */
/* copy the state file */
if (RT_FAILURE (vrc))
tr ("Could not copy the state file '%s' to '%s' (%Rrc)"),
}
/* we have to call endTakingSnapshot() ourselves if the snapshot was taken
* offline because the VM process will not do it in this case
*/
if (!online)
{
{
}
/* 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;
}
/* saveSettings() needs mParent lock */
/* @todo We don't need mParent lock so far so unlock() it. Better is to
* provide an AutoWriteLock argument that lets create a non-locking
* instance */
/* Preseve the {parent, child} lock order for this and snapshot stuff */
/* no need to lock the snapshot machine since it is const by definiton */
/* save the snapshot ID (for callbacks) */
bool settingsChanged = false;
try
{
/* first pass: */
LogFlowThisFunc (("1: Checking hard disk merge prerequisites...\n"));
++ it)
{
/* HardDisk2::prepareDiscard() reqiuires a write lock */
{
/* skip writethrough hard disks */
continue;
}
/* needs to be discarded (merged with the child if any), check
* prerequisites */
}
/* Now we checked that we can successfully merge all normal hard disks
* (unless a runtime error like end-of-disc happens). Prior to
* performing the actual merge, we want to discard the snapshot itself
* and remove it from the XML file to make sure that a possible merge
* ruintime error will not make this snapshot inconsistent because of
* the partially merged or corrupted hard disks */
/* second pass: */
LogFlowThisFunc (("2: Discarding snapshot...\n"));
{
/* for now, the snapshot must have only one child when discarded,
* or no children at all */
/// @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 */
/// @todo NEWMEDIA not really clear why
!parentSnapshot ||
E_FAIL);
/* we've changed the base of the current state so mark it as
* modified as it no longer guaranteed to be its copy */
}
{
{
E_FAIL);
}
else
}
/* Note that discarding the snapshot will deassociate it from the
* hard disks which will allow the merge+delete operation for them*/
/// @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)
{
}
/// @todo NEWMEDIA to provide a good level of fauilt tolerance, we
/// should restore the shapshot in the snapshot tree if
/// saveSnapshotSettings fails. Actually, we may call
/// #saveSnapshotSettings() with a special flag that will tell it to
/// skip the given snapshot as if it would have been discarded and
/// only actually discard it if the save operation succeeds.
}
/* here we come when we've irrevesibly discarded the snapshot which
* means that the VM settigns (our relevant changes to mData) need to be
* saved too */
/// @todo NEWMEDIA maybe save everything in one operation in place of
/// saveSnapshotSettings() above
settingsChanged = true;
/* third pass: */
LogFlowThisFunc (("3: Performing actual hard disk merging...\n"));
/* leave the locks before the potentially lengthy operation */
/// @todo NEWMEDIA turn the following errors into warnings because the
/// snapshot itself has been already deleted (and interpret these
/// warnings properly on the GUI side)
{
{
/* it's a base hard disk so it will be a backward merge of its
* only child to it. We need then to update the attachment that
* refers to the child so get it and detach the child
* (otherwise mergeTo() called by discard() will assert because
* it will be going to delete the child) */
AssertComRC (rc2);
}
{
/* attach the detached child again */
break;
}
{
/* replace the attachment on success */
if (snapshotId.isEmpty())
{
/* in current state */
}
else
{
/* in snapshot */
/* don't lock the snapshot; cannot be modified outside */
}
{
}
AssertComRC (rc2);
}
/* prevent from calling cancelDiscard() */
}
}
{
/* un-prepare the remaining hard disks */
}
{
{
/* saveSettings() below needs a VirtualBox write lock and we need to
* leave this object's lock to do this to follow the {parent-child}
* locking rule. This is the last chance to do that while we are
* still in a protective state which allows us to temporarily leave
* the lock */
/* preserve existing error info */
/* restore the machine state */
if (settingsChanged)
}
/* 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;
}
/* saveSettings() needs mParent lock */
/* @todo We don't need mParent lock so far so unlock() it. Better is to
* provide an AutoWriteLock argument that lets create a non-locking
* instance */
AutoWriteLock alock (this);
/* 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;
try
{
/* 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;
throw rc;
}
}
{
/* remember the timestamp of the snapshot we're restoring from */
/* copy all hardware data from the current snapshot */
LogFlowThisFunc (("Restoring hard disks from the snapshot...\n"));
/* restore the attachmends from the snapshot */
/* leave the locks before the potentially lengthy operation */
false /* aOnline */);
snapshotLock.lock();
/* Note: on success, current (old) hard disks will be
* deassociated/deleted on #commit() called from #saveSettings() at
* the end. On failure, newly created implicit diffs will be
* deleted by #rollback() 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",
/* leave the lock before the potentially lengthy operation */
/* copy the state file */
snapshotLock.lock();
if (RT_SUCCESS (vrc))
{
}
else
{
tr ("Could not copy the state file '%s' to '%s' (%Rrc)"),
}
}
}
/* grab differencing hard disks from the old attachments that will
* become unused and need to be auto-deleted */
{
/* while the hard disk is attached, the number of children or the
* parent cannot change, so no lock */
}
int saveFlags = 0;
{
/* commit changes to have unused diffs deassociated from this
* machine before deletion (see below) */
commit();
/* delete the unused diffs now (and uninit them) because discard
* may fail otherwise (too many children of the hard disk to be
* discarded) */
{
/// @todo for now, we ignore errors since we've already
/// and therefore cannot fail. Later, we may want to report a
/// warning through the Progress object
}
/* prevent further deletion */
/* 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. */
{
/* 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 */
/// @todo NEWMEDIA check if we need this informCallbacks at all
/// after updating discardCurrentSnapshot functionality
}
/* @todo saveSettings() below needs a VirtualBox write lock and we need
* to leave this object's lock to do this to follow the {parent-child}
* locking rule. This is the last chance to do that while we are still
* in a protective state which allows us to temporarily leave the lock*/
/* 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;
/* assign the timestamp from the snapshot */
/* save all settings, reset the modified flag and commit. Note that we
* do so even if the subtask failed (errorInSubtask=true) because we've
* already committed machine data and deleted old diffs before
* discarding the current snapshot so there is no way to rollback */
/// @todo NEWMEDIA return multiple errors
if (errorInSubtask)
throw rc;
{
/* now, delete the unused diffs (only on success!) and uninit them*/
{
/// @todo for now, we ignore errors since we've already
/// and therefore cannot fail. Later, we may want to report a
/// warning through the Progress object
}
}
}
{
/* preserve existing error info */
if (!errorInSubtask)
{
/* undo all changes on failure unless the subtask has done so */
rollback (false /* aNotify */);
}
if (!stateRestored)
{
/* restore the machine state */
}
}
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);
AutoWriteLock alock (this);
("oldMachineState=%d, aMachineState=%d\n",
int stsFlags = 0;
bool deleteSavedState = false;
/* detect some state transitions */
if ((oldMachineState == MachineState_Saved &&
{
/* The EMT thread is about to start */
/* Nothing to do here for now... */
/// @todo NEWMEDIA don't let mDVDDrive and other children
}
else
if (oldMachineState >= MachineState_Running &&
/* ignore PoweredOff->Saving->PoweredOff transition when taking a
* snapshot */
{
/* The EMT thread has just stopped, unlock attached media. Note that
* opposed to locking, we do unlocking here because the VM process may
* have just aborted before properly unlocking all media it locked. */
{
bool first = true;
{
if (first)
{
AssertComRC (rc);
first = false;
}
else
{
AssertComRC (rc);
}
/* no locks or callers here since there should be no way to
* change the hard disk parent at this point (as it is still
* attached to the machine) */
}
}
{
{
AssertComRC (rc);
}
}
{
{
AssertComRC (rc);
}
}
}
{
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 ||
{
/* the machine has stopped execution
* (or the saved state file was adopted) */
}
if ((oldMachineState == MachineState_PoweredOff ||
{
/* the saved state file was adopted */
}
if ((oldMachineState != MachineState_PoweredOff &&
{
/* we've been shut down for any reason */
/* no special action so far */
}
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);
{
AutoReadLock 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 The aSessionMachine must be locked for writing.
*/
{
/* 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)
{
}
/* associate hard disks with the snapshot
* (Machine::uninitDataAndChildObjects() will deassociate at destruction) */
++ it)
{
AssertComRC (rc);
}
/* create all other child objects that will be immutable private copies */
#ifdef VBOX_WITH_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 Doesn't lock anything.
*/
{
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan (this);
/* Don't need to lock aMachine when VirtualBox is starting up */
/* 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_WITH_VRDP
mVRDPServer->init (this);
#endif
mFloppyDrive->init (this);
mAudioAdapter->init (this);
mUSBController->init (this);
mSATAController->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;
/* free the essential data structure last */
}
// util::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.
*/
{
AutoWriteLock alock (this);
/* inform callbacks */
return S_OK;
}
/* vi: set tabstop=4 shiftwidth=4 expandtab: */