MachineImpl.cpp revision 6036d7832f84ca6a99cbf9d7e38526fdcf10a7f6
/* $Id$ */
/** @file
* Implementation of IMachine in VBoxSVC.
*/
/*
* Copyright (C) 2004-2014 Oracle Corporation
*
* 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.
*/
/* 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
#include "Logging.h"
#include "VirtualBoxImpl.h"
#include "MachineImpl.h"
#include "ClientToken.h"
#include "ProgressImpl.h"
#include "ProgressProxyImpl.h"
#include "MediumAttachmentImpl.h"
#include "MediumImpl.h"
#include "MediumLock.h"
#include "USBControllerImpl.h"
#include "USBDeviceFiltersImpl.h"
#include "HostImpl.h"
#include "SharedFolderImpl.h"
#include "GuestOSTypeImpl.h"
#include "VirtualBoxErrorInfoImpl.h"
#include "GuestImpl.h"
#include "StorageControllerImpl.h"
#include "DisplayImpl.h"
#include "DisplayUtils.h"
#include "MachineImplCloneVM.h"
#include "AutostartDb.h"
#include "SystemPropertiesImpl.h"
// generated header
#include "VBoxEvents.h"
#ifdef VBOX_WITH_USB
# include "USBProxyService.h"
#endif
#include "AutoCaller.h"
#include "HashedPw.h"
#include "Performance.h"
#include <iprt/lockvalidator.h>
#include <VBox/settings.h>
#ifdef VBOX_WITH_GUEST_PROPS
#endif
#include "VBox/com/MultiResult.h"
#include <algorithm>
#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
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// Machine::Data structure
/////////////////////////////////////////////////////////////////////////////
{
mRegistered = FALSE;
/* Contains hints on what has changed when the user is using the VM (config
* changes, running the VM, ...). This is used to decide if a config needs
* to be written to disk. */
flModifications = 0;
/* VM modification usually also trigger setting the current state to
* "Modified". Although this is not always the case. An e.g. is the VM
* initialization phase or when snapshot related data is changed. The
* actually behavior is controlled by the following flag. */
m_fAllowStateModification = false;
mAccessible = FALSE;
/* mUuid is initialized in Machine::init() */
mMachineStateDeps = 0;
}
{
{
}
if (pMachineConfigFile)
{
delete pMachineConfigFile;
}
}
/////////////////////////////////////////////////////////////////////////////
// Machine::HWData structure
/////////////////////////////////////////////////////////////////////////////
{
/* default values for a newly created machine */
mMemorySize = 128;
mCPUCount = 1;
mCPUHotPlugEnabled = false;
mMemoryBalloonSize = 0;
mPageFusionEnabled = false;
mVRAMSize = 8;
mAccelerate3DEnabled = false;
mAccelerate2DVideoEnabled = false;
mMonitorCount = 1;
mVideoCaptureWidth = 1024;
mVideoCaptureHeight = 768;
mVideoCaptureRate = 512;
mVideoCaptureFPS = 25;
mVideoCaptureEnabled = false;
for (unsigned i = 0; i < RT_ELEMENTS(maVideoCaptureScreens); ++i)
maVideoCaptureScreens[i] = true;
mHWVirtExEnabled = true;
mHWVirtExNestedPagingEnabled = true;
mHWVirtExLargePagesEnabled = true;
#else
/* Not supported on 32 bits hosts. */
mHWVirtExLargePagesEnabled = false;
#endif
mHWVirtExVPIDEnabled = true;
mHWVirtExUXEnabled = true;
mHWVirtExForceEnabled = false;
mPAEEnabled = true;
#else
mPAEEnabled = false;
#endif
mLongMode = HC_ARCH_BITS == 64 ? settings::Hardware::LongMode_Enabled : settings::Hardware::LongMode_Disabled;
mSyntheticCpu = false;
mTripleFaultReset = false;
mHPETEnabled = false;
/* default boot order: floppy - DVD - HDD */
mBootOrder[0] = DeviceType_Floppy;
mBootOrder[i] = DeviceType_Null;
mCPUAttached[i] = false;
mIOCacheEnabled = true;
/* Maximum CPU execution cap by default. */
mCpuExecutionCap = 100;
}
{
}
/////////////////////////////////////////////////////////////////////////////
// Machine::HDData structure
/////////////////////////////////////////////////////////////////////////////
{
}
{
}
/////////////////////////////////////////////////////////////////////////////
// Machine class
/////////////////////////////////////////////////////////////////////////////
// constructor / destructor
/////////////////////////////////////////////////////////////////////////////
#ifdef VBOX_WITH_RESOURCE_USAGE_API
#endif
mSerialPorts(),
{}
{}
{
LogFlowThisFunc(("\n"));
return BaseFinalConstruct();
}
void Machine::FinalRelease()
{
LogFlowThisFunc(("\n"));
uninit();
}
/**
* Initializes a new machine instance; this init() variant creates a new, empty machine.
* This gets called from VirtualBox::CreateMachine().
*
* @param aParent Associated parent object
* @param strConfigFile Local file system path to the VM settings file (can
* be relative to the VirtualBox config directory).
* @param strName name for the machine
* @param llGroups list of groups for the machine
* @param aOsType OS Type of this machine or NULL.
* @param aId UUID for the new machine.
* @param fForceOverwrite Whether to overwrite an existing machine settings file.
*
* @return Success indicator. if not S_OK, the machine object is invalid
*/
const Utf8Str &strConfigFile,
const StringsList &llGroups,
bool fForceOverwrite,
bool fDirectoryIncludesUUID)
{
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan(this);
{
// create an empty machine config
}
{
// set to true now to cause uninit() to call uninitDataAndChildObjects() on failure
// the "name sync" flag determines whether the machine directory gets renamed along
// with the machine file; say so if the settings file name is the same as the
// settings file parent directory (machine directory)
// initialize the default snapshots folder
if (aOsType)
{
/* Store OS type */
/* Apply BIOS defaults */
/* Apply network adapters defaults */
/* Apply serial port defaults */
/* Let the OS type select 64-bit ness. */
}
/* At this point the changing of the current state modification
* flag is allowed. */
/* commit all changes made during the initialization */
i_commit();
}
/* Confirm a successful initialization when it's the case */
{
if (mData->mAccessible)
else
}
LogFlowThisFunc(("mName='%s', mRegistered=%RTbool, mAccessible=%RTbool, rc=%08X\n",
rc));
return rc;
}
/**
* Initializes a new instance with data from machine XML (formerly Init_Registered).
* Gets called in two modes:
*
* -- from VirtualBox::initMachines() during VirtualBox startup; in that case, the
* UUID is specified and we mark the machine as "registered";
*
* -- from the public VirtualBox::OpenMachine() API, in which case the UUID is NULL
* and the machine remains unregistered until RegisterMachine() is called.
*
* @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 aId UUID of the machine or NULL (see above).
*
* @return Success indicator. if not S_OK, the machine object is invalid
*/
const Utf8Str &strConfigFile,
{
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan(this);
if (aId)
{
// loading a registered VM:
// now load the settings from XML:
rc = i_registeredInit();
// this calls initDataAndChildObjects() and loadSettings()
}
else
{
// opening an unregistered VM (VirtualBox::OpenMachine()):
{
// set to true now to cause uninit() to call uninitDataAndChildObjects() on failure
try
{
// load and parse machine XML; this will throw on XML or logic errors
// reject VM UUID duplicates, they can happen if someone
// tries to register an already known VM config again
true /* fPermitInaccessible */,
false /* aDoSetError */,
{
tr("Trying to open a VM config '%s' which has the same UUID as an existing virtual machine"),
}
// use UUID from machine config
NULL /* puuidRegistry */);
/* At this point the changing of the current state modification
* flag is allowed. */
i_commit();
}
{
/* we assume that error info is set by the thrower */
}
catch (...)
{
}
}
}
/* Confirm a successful initialization when it's the case */
{
if (mData->mAccessible)
else
{
// uninit media from this machine's media registry, or else
// reloading the settings will fail
}
}
LogFlowThisFunc(("mName='%s', mRegistered=%RTbool, mAccessible=%RTbool "
"rc=%08X\n",
return rc;
}
/**
* Initializes a new instance from a machine config that is already in memory
* (import OVF case). Since we are importing, the UUID in the machine
* config is ignored and we always generate a fresh one.
*
* @param strName Name for the new machine; this overrides what is specified in config and is used
* for the settings file as well.
* @param config Machine configuration loaded and parsed from XML.
*
* @return Success indicator. if not S_OK, the machine object is invalid
*/
{
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan(this);
{
// set to true now to cause uninit() to call uninitDataAndChildObjects() on failure
// create empty machine config for instance data
// generate fresh UUID, ignore machine config
// override VM name as well, it may be different
{
/* At this point the changing of the current state modification
* flag is allowed. */
/* commit all changes made during the initialization */
i_commit();
}
}
/* Confirm a successful initialization when it's the case */
{
if (mData->mAccessible)
else
{
/* Ignore all errors from unregistering, they would destroy
- * the more interesting error information we already have,
- * pinpointing the issue with the VM config. */
// uninit media from this machine's media registry, or else
// reloading the settings will fail
}
}
LogFlowThisFunc(("mName='%s', mRegistered=%RTbool, mAccessible=%RTbool "
"rc=%08X\n",
return rc;
}
/**
* Shared code between the various init() implementations.
* @param aParent
* @return
*/
const Utf8Str &strConfigFile)
{
/* share the parent weakly */
/* 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(vrc1))
return setError(VBOX_E_FILE_ERROR,
tr("Invalid machine settings file name '%s' (%Rrc)"),
vrc1);
return rc;
}
/**
* Tries to create a machine settings file in the path stored in the machine
* instance data. Used when a new machine is created to fail gracefully if
* the settings file could not be written (e.g. because machine dir is read-only).
* @return
*/
{
// when we create a new machine, we must be able to create the settings file
RTFILE f = NIL_RTFILE;
int vrc = RTFileOpen(&f, mData->m_strConfigFileFull.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
if ( RT_SUCCESS(vrc)
|| vrc == VERR_SHARING_VIOLATION
)
{
if (RT_SUCCESS(vrc))
RTFileClose(f);
if (!fForceOverwrite)
tr("Machine settings file '%s' already exists"),
else
{
/* try to delete the config file, as otherwise the creation
* of a new settings file will fail. */
if (RT_FAILURE(vrc2))
tr("Could not delete the existing settings file '%s' (%Rrc)"),
}
}
else if ( vrc != VERR_FILE_NOT_FOUND
&& vrc != VERR_PATH_NOT_FOUND
)
tr("Invalid machine settings file name '%s' (%Rrc)"),
vrc);
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). */
try
{
// load and parse machine XML; this will throw on XML or logic errors
tr("Machine UUID {%RTuuid} in '%s' doesn't match its UUID {%s} in the registry file '%s'"),
NULL /* const Guid *puuidRegistry */);
}
{
/* we assume that error info is set by the thrower */
}
catch (...)
{
}
/* Restore the registered flag (even on failure) */
}
{
/* Set mAccessible to TRUE only if we successfully locked and loaded
* the settings file */
/* commit all changes made during loading the settings file */
i_commit(); // @todo r=dj why do we need a commit during init?!? this is very expensive
/// @todo r=klaus for some reason the settings loading logic backs up
// the settings, and therefore a commit is needed. Should probably be changed.
}
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 */
i_rollback(false /* aNotify */);
// uninit media from this machine's media registry, or else
// reloading the settings will fail
/* 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.
*/
{
if (uRegistryNeedsSaving)
{
AutoCaller autoCaller(this);
{
}
}
/* Enclose the state transition Ready->InUninit->NotReady */
AutoUninitSpan autoUninitSpan(this);
if (autoUninitSpan.uninitDone())
return;
Assert(!i_isSessionMachine());
{
/* 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 */
}
// uninit media from this machine's media registry, if they're still there
/* the lock is no more necessary (SessionMachine is uninitialized) */
/* XXX This will fail with
* "cannot be closed because it is still attached to 1 virtual machines"
* because at this point we did not call uninitDataAndChildObjects() yet
* and therefore also removeBackReference() for all these mediums was not called! */
if (uuidMachine.isValid() && !uuidMachine.isZero()) // can be empty if we're called from a failure of Machine::init
// has machine been modified?
if (mData->flModifications)
{
LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
i_rollback(false /* aNotify */);
}
if (mData->mAccessible)
/* free the essential data structure last */
}
// Wrapped IMachine properties
/////////////////////////////////////////////////////////////////////////////
{
/* mParent is constant during life time, no need to lock */
return S_OK;
}
{
/* In some cases (medium registry related), it is necessary to be able to
* go through the list of all machines. Happens when an inaccessible VM
* has a sensible medium registry. */
if (!mData->mAccessible)
{
/* try to initialize the VM once more if not accessible */
AutoReinitSpan autoReinitSpan(this);
#ifdef DEBUG
LogFlowThisFunc(("Dumping media backreferences\n"));
#endif
if (mData->pMachineConfigFile)
{
// reset the XML file to force loadSettings() (called from registeredInit())
// to parse it again; the file might have changed
delete mData->pMachineConfigFile;
}
rc = i_registeredInit();
{
/* make sure interesting parties will notice the accessibility
* state change */
}
}
return rc;
}
{
{
/* return shortly */
aAccessError = NULL;
return S_OK;
}
{
}
return rc;
}
{
return S_OK;
}
{
// prohibit setting a UUID only as the machine name, or else it can
// never be found by findMachine()
return S_OK;
}
{
return S_OK;
}
{
// this can be done in principle in any state as it doesn't affect the VM
// significantly, but play safe by not messing around while complex
// activities are going on
return S_OK;
}
{
return S_OK;
}
{
size_t i = 0;
return S_OK;
}
{
return rc;
// changing machine groups is possible while the VM is offline
return S_OK;
}
{
return S_OK;
}
{
/* look up the object by Id to check it is valid */
/* when setting, always use the "etalon" value for consistency -- lookup
* by ID is case-insensitive and the input value may have different case */
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
{
// We must not throw away entries yet, otherwise settings are lost
// without a way to roll back.
{
{
}
}
}
return S_OK;
}
{
return S_OK;
}
{
{
}
return S_OK;
}
{
switch (mHWData->mParavirtProvider)
{
case ParavirtProvider_None:
case ParavirtProvider_HyperV:
case ParavirtProvider_Minimal:
break;
/* Resolve dynamic provider types to the effective types. */
default:
{
HRESULT hrc2 = mParent->GetGuestOSType(Bstr(mUserData->s.strOsType).raw(), ptrGuestOSType.asOutParam());
switch (mHWData->mParavirtProvider)
{
case ParavirtProvider_Legacy:
{
if (fOsXGuest)
else
break;
}
case ParavirtProvider_Default:
{
if (fOsXGuest)
#if 0 /* Activate this soon. */
{
}
#endif
else
break;
}
}
break;
}
}
|| *aParavirtProvider == ParavirtProvider_HyperV);
return S_OK;
}
{
return S_OK;
}
{
/* check known version */
return setError(E_INVALIDARG,
return S_OK;
}
{
else
return S_OK;
}
{
if (!aHardwareUUID.isValid())
return E_INVALIDARG;
else
return S_OK;
}
{
return S_OK;
}
{
/* check RAM limits */
if ( aMemorySize < MM_RAM_MIN_IN_MB
)
return setError(E_INVALIDARG,
tr("Invalid RAM size: %lu MB (must be in range [%lu, %lu] MB)"),
return S_OK;
}
{
return S_OK;
}
{
/* check CPU limits */
)
return setError(E_INVALIDARG,
tr("Invalid virtual CPU count: %lu (must be in range [%lu, %lu])"),
/* We cant go below the current number of CPUs attached if hotplug is enabled*/
if (mHWData->mCPUHotPlugEnabled)
{
{
return setError(E_INVALIDARG,
tr("There is still a CPU attached to socket %lu."
"Detach the CPU before removing the socket"),
}
}
return S_OK;
}
{
return S_OK;
}
{
/* check throttle limits */
if ( aCPUExecutionCap < 1
|| aCPUExecutionCap > 100
)
return setError(E_INVALIDARG,
tr("Invalid CPU execution cap value: %lu (must be in range [%lu, %lu])"),
/** Save settings if online - @todo why is this required? -- @bugref{6818} */
return S_OK;
}
{
return S_OK;
}
{
{
if (aCPUHotPlugEnabled)
{
/* Add the amount of CPUs currently attached */
mHWData->mCPUAttached[i] = true;
}
else
{
/*
* We can disable hotplug only if the amount of maximum CPUs is equal
* to the amount of attached CPUs
*/
unsigned cCpusAttached = 0;
unsigned iHighestId = 0;
for (unsigned i = 0; i < SchemaDefs::MaxCPUCount; ++i)
{
if (mHWData->mCPUAttached[i])
{
iHighestId = i;
}
}
return setError(E_INVALIDARG,
tr("CPU hotplugging can't be disabled because the maximum number of CPUs is not equal to the amount of CPUs attached"));
}
}
return rc;
}
{
#ifdef VBOX_WITH_USB_CARDREADER
return S_OK;
#else
return E_NOTIMPL;
#endif
}
{
#ifdef VBOX_WITH_USB_CARDREADER
return S_OK;
#else
return E_NOTIMPL;
#endif
}
{
return S_OK;
}
{
return rc;
}
{
return S_OK;
}
{
rc = i_onVideoCaptureChange();
{
/*
* Normally we would do the actual change _after_ i_onVideoCaptureChange() succeeded.
* We cannot do this because that function uses Machine::GetVideoCaptureEnabled to
* determine if it should start or stop capturing. Therefore we need to manually
* undo change.
*/
return rc;
}
/** Save settings if online - @todo why is this required? -- @bugref{6818} */
return rc;
}
{
for (unsigned i = 0; i < mHWData->mMonitorCount; ++i)
return S_OK;
}
{
bool fChanged = false;
{
{
fChanged = true;
}
}
if (fChanged)
{
/** Save settings if online - @todo why is this required? -- @bugref{6818} */
}
return S_OK;
}
{
else
return S_OK;
}
{
{
}
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
switch (aGraphicsControllerType)
{
#ifdef VBOX_WITH_VMSVGA
#endif
break;
default:
return setError(E_INVALIDARG, tr("The graphics controller type (%d) is invalid"), aGraphicsControllerType);
}
return S_OK;
}
{
return S_OK;
}
{
/* check VRAM limits */
return setError(E_INVALIDARG,
tr("Invalid VRAM size: %lu MB (must be in range [%lu, %lu] MB)"),
return S_OK;
}
/** @todo this method should not be public */
{
return S_OK;
}
/**
* Set the memory balloon size.
*
* This method is also called from IGuest::COMSETTER(MemoryBalloonSize) so
* we have to make sure that we never call IGuest from here.
*/
{
/* This must match GMMR0Init; currently we only support memory ballooning on all 64-bit hosts except Mac OS X */
#if HC_ARCH_BITS == 64 && (defined(RT_OS_WINDOWS) || defined(RT_OS_SOLARIS) || defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD))
/* check limits */
return setError(E_INVALIDARG,
tr("Invalid memory balloon size: %lu MB (must be in range [%lu, %lu] MB)"),
return S_OK;
#else
#endif
}
{
return S_OK;
}
{
#ifdef VBOX_WITH_PAGE_SHARING
/** @todo must support changes for running vms and keep this in sync with IGuest. */
return S_OK;
#else
#endif
}
{
return S_OK;
}
{
/** @todo check validity! */
return S_OK;
}
{
return S_OK;
}
{
/** @todo check validity! */
return S_OK;
}
{
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])"),
return S_OK;
}
{
/* mBIOSSettings is constant during life time, no need to lock */
return S_OK;
}
{
switch (aProperty)
{
case CPUPropertyType_PAE:
break;
break;
case CPUPropertyType_LongMode:
#if HC_ARCH_BITS == 64
else
#else
else
{
HRESULT hrc2 = mParent->GetGuestOSType(Bstr(mUserData->s.strOsType).raw(), ptrGuestOSType.asOutParam());
{
{
}
}
}
#endif
break;
break;
default:
return E_INVALIDARG;
}
return S_OK;
}
{
switch (aProperty)
{
case CPUPropertyType_PAE:
break;
break;
case CPUPropertyType_LongMode:
mHWData->mLongMode = !aValue ? settings::Hardware::LongMode_Disabled : settings::Hardware::LongMode_Enabled;
break;
break;
default:
return E_INVALIDARG;
}
return S_OK;
}
HRESULT Machine::getCPUIDLeaf(ULONG aId, ULONG *aValEax, ULONG *aValEbx, ULONG *aValEcx, ULONG *aValEdx)
{
switch(aId)
{
case 0x0:
case 0x1:
case 0x2:
case 0x3:
case 0x4:
case 0x5:
case 0x6:
case 0x7:
case 0x8:
case 0x9:
case 0xA:
return E_INVALIDARG;
break;
case 0x80000000:
case 0x80000001:
case 0x80000002:
case 0x80000003:
case 0x80000004:
case 0x80000005:
case 0x80000006:
case 0x80000007:
case 0x80000008:
case 0x80000009:
case 0x8000000A:
return E_INVALIDARG;
break;
default:
}
return S_OK;
}
HRESULT Machine::setCPUIDLeaf(ULONG aId, ULONG aValEax, ULONG aValEbx, ULONG aValEcx, ULONG aValEdx)
{
switch(aId)
{
case 0x0:
case 0x1:
case 0x2:
case 0x3:
case 0x4:
case 0x5:
case 0x6:
case 0x7:
case 0x8:
case 0x9:
case 0xA:
break;
case 0x80000000:
case 0x80000001:
case 0x80000002:
case 0x80000003:
case 0x80000004:
case 0x80000005:
case 0x80000006:
case 0x80000007:
case 0x80000008:
case 0x80000009:
case 0x8000000A:
break;
default:
}
return S_OK;
}
{
switch(aId)
{
case 0x0:
case 0x1:
case 0x2:
case 0x3:
case 0x4:
case 0x5:
case 0x6:
case 0x7:
case 0x8:
case 0x9:
case 0xA:
/* Invalidate leaf. */
break;
case 0x80000000:
case 0x80000001:
case 0x80000002:
case 0x80000003:
case 0x80000004:
case 0x80000005:
case 0x80000006:
case 0x80000007:
case 0x80000008:
case 0x80000009:
case 0x8000000A:
/* Invalidate leaf. */
break;
default:
}
return S_OK;
}
{
/* Invalidate all standard leafs. */
/* Invalidate all extended leafs. */
return S_OK;
}
{
switch(aProperty)
{
break;
break;
break;
break;
#endif
break;
break;
default:
return E_INVALIDARG;
}
return S_OK;
}
{
switch(aProperty)
{
break;
break;
break;
break;
break;
break;
default:
return E_INVALIDARG;
}
return S_OK;
}
{
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().
*/
tr("The snapshot folder of a machine with snapshots cannot be changed (please delete all snapshots first)"));
if (strSnapshotFolder.isEmpty())
strSnapshotFolder = "Snapshots";
if (RT_FAILURE(vrc))
tr("Invalid snapshot folder '%s' (%Rrc)"),
return S_OK;
}
{
size_t i = 0;
return S_OK;
}
{
Assert(!!mVRDEServer);
return S_OK;
}
{
return S_OK;
}
{
#ifdef VBOX_WITH_VUSB
clearError();
# ifdef VBOX_WITH_USB
# endif
size_t i = 0;
return S_OK;
#else
/* Note: The GUI depends on this method returning E_NOTIMPL with no
* extended error info to indicate that USB is simply not available
* (w/o treating it as a failure), for example, as in OSE */
#endif /* VBOX_WITH_VUSB */
}
{
#ifdef VBOX_WITH_VUSB
clearError();
# ifdef VBOX_WITH_USB
# endif
#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 treating it as a failure), for example, as in OSE */
#endif /* VBOX_WITH_VUSB */
}
{
return S_OK;
}
{
// this is a new machine, and no config file exists yet:
else
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
? 0
return S_OK;
}
{
/* Note: for machines with no snapshots, we always return FALSE
* (mData->mCurrentStateModified will be TRUE in this case, for historical
* reasons :) */
? FALSE
return S_OK;
}
{
size_t i = 0;
return S_OK;
}
{
return S_OK;
}
{
/** Save settings if online - @todo why is this required? -- @bugref{6818} */
return S_OK;
}
{
return S_OK;
}
{
/** Save settings if online - @todo why is this required? -- @bugref{6818} */
return S_OK;
}
HRESULT Machine::getGuestPropertyNotificationPatterns(com::Utf8Str &aGuestPropertyNotificationPatterns)
{
try
{
}
catch (...)
{
}
return S_OK;
}
HRESULT Machine::setGuestPropertyNotificationPatterns(const com::Utf8Str &aGuestPropertyNotificationPatterns)
{
return rc;
}
HRESULT Machine::getStorageControllers(std::vector<ComPtr<IStorageController> > &aStorageControllers)
{
size_t i = 0;
return S_OK;
}
{
return S_OK;
}
{
/* Only allow it to be set to true when PoweredOff or Aborted.
(Clearing it is always permitted.) */
if ( aTeleporterEnabled
&& mData->mRegistered
&& ( !i_isSessionMachine()
)
)
)
return setError(VBOX_E_INVALID_VM_STATE,
tr("The machine is not powered off (state is %s)"),
return S_OK;
}
{
return S_OK;
}
{
if (aTeleporterPort >= _64K)
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
/*
* Hash the password first.
*/
{
if (VBoxIsPasswordHashed(&aT))
return setError(E_INVALIDARG, tr("Cannot set an already hashed password, only plain text password please"));
}
/*
* Do the update.
*/
{
}
return hrc;
}
{
return S_OK;
}
{
/* @todo deal with running state change. */
return S_OK;
}
{
return S_OK;
}
{
/* @todo deal with running state change. */
return S_OK;
}
{
return S_OK;
}
{
/* @todo deal with running state change. */
return S_OK;
}
{
return S_OK;
}
{
/* @todo deal with running state change. */
return S_OK;
}
{
return S_OK;
}
{
/* @todo deal with running state change. */
return S_OK;
}
{
return S_OK;
}
{
/* Only allow it to be set to true when PoweredOff or Aborted.
(Clearing it is always permitted.) */
if ( aRTCUseUTC
&& mData->mRegistered
&& ( !i_isSessionMachine()
)
)
)
return setError(VBOX_E_INVALID_VM_STATE,
tr("The machine is not powered off (state is %s)"),
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
/**
* @note Locks objects!
*/
{
/* check the session state */
if (state != SessionState_Unlocked)
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("The given session is busy"));
// get the client's IInternalSessionControl interface
if (!mData->mRegistered)
return setError(E_UNEXPECTED,
tr("The machine '%s' is not registered"),
/* Hack: in case the session is closing and there is a progress object
* which allows waiting for the session to be closed, take the opportunity
* and do a limited wait (max. 1 second). This helps a lot when the system
* is busy and thus session closing can take a little while. */
{
LogFlowThisFunc(("after waiting: mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
}
// try again now
// (i.e. session machine exists)
// existing session that holds the write lock:
)
{
// OK, share the session... we are now dealing with three processes:
// 1) VBoxSVC (where this code runs);
// 2) process C: the caller's client process (who wants a shared session);
// 3) process W: the process which already holds the write lock on the machine (write-locking session)
// copy pointers to W (the write-locking session) before leaving lock (these must not be NULL)
/*
* Release 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).
*/
// get the console of the session holding the write lock (this is a remote call)
LogFlowThisFunc(("Calling GetRemoteConsole()...\n"));
// the failure may occur w/o any error info (from RPC), so provide one
return setError(VBOX_E_VM_ERROR,
// share the session machine and W's console with the caller's session
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 acquiring the lock again
{
return setError(VBOX_E_INVALID_SESSION_STATE,
tr("The machine '%s' was unlocked unexpectedly while attempting to share its session"),
}
// add the caller's session to the list
}
)
{
// sharing not permitted, or machine still unlocking:
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("The machine '%s' is already locked for a session (or being unlocked)"),
}
else
{
// machine is not locked: then write-lock the machine (create the session machine)
// must not be busy
// get the caller's session PID
if (fLaunchingVMProcess)
{
{
// two or more clients racing for a lock, the one which set the
// session state to Spawning will win, the others will get an
// error as we can't decide here if waiting a little would help
// (only for shared locks this would avoid an error)
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("The machine '%s' already has a lock request pending"),
}
// this machine is awaiting for a spawning session to be opened:
// then the calling process must be the one that got started by
// LaunchVMProcess()
#if defined(VBOX_WITH_HARDENING) && defined(RT_OS_WINDOWS)
/* Hardened windows builds have spawns two processes when a VM is
launched, the 2nd one is the one that will end up here. */
|| rc == VERR_ACCESS_DENIED)
{
LogFlowThisFunc(("mSession.mPID => %d(%#x) - windows hardening stub\n", mData->mSession.mPID, pid));
}
#endif
return setError(E_ACCESSDENIED,
tr("An unexpected process (PID=0x%08X) has tried to lock the "
"machine '%s', while only the process started by LaunchVMProcess (PID=0x%08X) is allowed"),
}
// create the mutable SessionMachine from the current machine
/* NOTE: doing return from this function after this point but
* before the end is forbidden since it may call SessionMachine::uninit()
* (through the ComObjPtr's destructor) which requests the VirtualBox write
* lock while still holding the Machine lock in alock so that a deadlock
* is possible due to the wrong lock order. */
{
/*
* Set the session state to Spawning to protect against subsequent
* attempts to open a session and to unregister the machine after
* we release the lock.
*/
/* Get the client token ID to be passed to the client process */
#else /* VBOX_WITH_GENERIC_SESSION_WATCHER */
/* Get the client token to be passed to the client process */
/* The token is now "owned" by pToken, fix refcount */
#endif /* VBOX_WITH_GENERIC_SESSION_WATCHER */
/*
* Release the lock before calling the client process -- it will call
* Machine/SessionMachine methods. Releasing the lock here is quite safe
* because the state is Spawning, so that LaunchVMProcess() and
* LockMachine() calls will fail. This method, called before we
* acquire 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"));
#else /* VBOX_WITH_GENERIC_SESSION_WATCHER */
/* Now the token is owned by the client process. */
#endif /* VBOX_WITH_GENERIC_SESSION_WATCHER */
/* 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 */
{
}
/* assign machine & console to the remote session */
{
/*
* after LaunchVMProcess(), 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 */
}
}
/* acquire the lock again */
/* Restore the session state */
}
// finalize spawning anyway (this is why we don't return on errors above)
if (fLaunchingVMProcess)
{
/* Note that the progress object is finalized later */
/** @todo Consider checking mData->mSession.mProgress for cancellation
* around here. */
/* 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 checkForSpawnFailure()). */
{
}
}
}
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) */
}
/* Release the lock since SessionMachine::uninit() locks VirtualBox which
* would break the lock order */
/* uninitialize the created session machine on failure */
sessionMachine->uninit();
}
{
/*
* tell the client watcher thread to update the set of
* machines that have open sessions
*/
if (oldState != SessionState_Locked)
/* fire an event */
}
return rc;
}
/**
* @note Locks objects!
*/
{
* retrieval. This code doesn't quite fit in here, but introducing a
* special API method would be even more effort, and would require explicit
* support by every API client. It's better to hide the feature a bit. */
if (strFrontend != "emergencystop")
if (strFrontend.isEmpty())
{
return rc;
if (strFrontend.isEmpty())
{
return rc;
return rc;
}
/* paranoia - emergencystop is not a valid default */
if (strFrontend == "emergencystop")
}
/* default frontend: Qt GUI */
if (strFrontend.isEmpty())
strFrontend = "GUI/Qt";
if (strFrontend != "emergencystop")
{
/* check the session state */
return rc;
if (state != SessionState_Unlocked)
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("The given session is busy"));
/* get the IInternalSessionControl interface */
("No IInternalSessionControl interface"),
/* get the teleporter enable state for the progress object init. */
return rc;
/* create a progress object */
static_cast<IMachine*>(this),
TRUE /* aCancelable */,
2 /* uFirstOperationWeight */,
{
{
/* signal the client watcher thread */
/* fire an event */
}
}
}
else
{
/* no progress object - either instant success or failure */
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("The machine '%s' is not locked by a session"),
/* must have a VM process associated - do not kill normal API clients
* with an open session */
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("The machine '%s' does not have a VM process"),
/* forcibly terminate the VM process */
/* signal the client watcher thread, as most likely the client has
* been terminated */
}
return rc;
}
{
return setError(E_INVALIDARG,
tr("Invalid boot position: %lu (must be in range [1, %lu])"),
if (aDevice == DeviceType_USB)
tr("Booting from USB device is currently not supported"));
return S_OK;
}
{
return setError(E_INVALIDARG,
tr("Invalid boot position: %lu (must be in range [1, %lu])"),
return S_OK;
}
{
LogFlowThisFunc(("aControllerName=\"%s\" aControllerPort=%d aDevice=%d aType=%d aMedium=%p\n",
// request the host lock first, since might be calling Host methods for getting host drives;
// next, protect the media tree all the while we're in here, as well as our member variables
/// @todo NEWMEDIA implicit machine registration
if (!mData->mRegistered)
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("Cannot attach storage devices to an unregistered machine"));
/* Check for an existing controller. */
tr("Could not get type of controller '%s'"),
bool fSilent = false;
/* Check whether the flag to allow silent storage attachment reconfiguration is set. */
&& strReconfig == "1")
fSilent = true;
/* Check that the controller can do hotplugging if we detach the device while the VM is running. */
bool fHotplug = false;
fHotplug = true;
return setError(VBOX_E_INVALID_VM_STATE,
tr("Controller '%s' does not support hotplugging"),
// check that the port and device are not out of range
/* check if the device slot is already busy */
aDevice)))
{
if (pMedium)
{
return setError(VBOX_E_OBJECT_IN_USE,
tr("Medium '%s' is already attached to port %d, device %d of controller '%s' of this virtual machine"),
}
else
return setError(VBOX_E_OBJECT_IN_USE,
tr("Device is already attached to port %d, device %d of controller '%s' of this virtual machine"),
}
)
return setError(VBOX_E_OBJECT_IN_USE,
tr("Medium '%s' is already attached to this virtual machine"),
{
// MediumType_Readonly is also new, but only applies to DVDs and floppies.
// For DVDs it's not written to the config file, so needs no global config
// version bump. For floppies it's a new attribute "type", which is ignored
// by older VirtualBox version, so needs no global config version bump either.
// For hard disks this type is not accepted.
if (mtype == MediumType_MultiAttach)
{
// This type is new with VirtualBox 4.0 and therefore requires settings
// version 1.11 in the settings backend. Unfortunately it is not enough to do
// the usual routine in MachineConfigFile::bumpSettingsVersionIfNeeded() for
// two reasons: The medium type is a property of the media registry tree, which
// can reside in the global config file (for pre-4.0 media); we would therefore
// possibly need to bump the global config version. We don't want to do that though
// because that might make downgrading to pre-4.0 impossible.
// As a result, we can only use these two new types if the medium is NOT in the
// global registry:
)
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("Cannot attach medium '%s': the media type 'MultiAttach' can only be attached "
"to machines that were created with VirtualBox 4.0 or later"),
}
}
bool fIndirect = false;
bool associate = true;
do
{
if ( aType == DeviceType_HardDisk
&& mMediaData.isBackedUp())
{
/* check if the medium was attached to the VM before we started
* changing attachments in which case the attachment just needs to
* be restored */
{
{
/* the simplest case: restore the whole attachment
* and return, nothing else to do */
/* Reattach the medium to the VM. */
{
true /* fMediumLockWrite */,
NULL,
delete pMediumLockList;
else
{
}
{
/* Remove lock list in case of error. */
{
}
}
}
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 (!fIndirect)
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 (mMediaData.isBackedUp())
{
uint32_t foundLevel = 0;
{
continue;
{
/* skip the hard disk if its currently attached (we
* cannot attach the same hard disk twice) */
pMedium))
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 medium will be used
*/
{
/* the simplest case: restore the whole attachment
* and return, nothing else to do */
/* Reattach the medium to the VM. */
{
true /* fMediumLockWrite */,
NULL,
delete pMediumLockList;
else
{
}
{
/* Remove lock list in case of error. */
{
}
}
}
return S_OK;
}
)
{
foundLevel = level;
}
}
}
{
/* use the previously attached hard disk */
/* not implicit, doesn't require association with this VM */
fIndirect = false;
associate = false;
/* go right to the MediumAttachment creation */
break;
}
}
/* must give up the medium lock and medium tree lock as below we
* go over snapshots, which needs a lock with higher lock order. */
/* 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;
{
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 medium will be used
*/
)
{
break;
}
else if ( !pAttachFound
)
{
foundLevel = level;
}
}
}
if (pAttachFound)
{
break;
}
}
/* re-lock medium tree and the medium, as we need it below */
/* found a suitable diff, use it as a base */
{
}
}
diff.createObject();
// store this diff in the same registry as the parent
{
// parent image has no registry: this can happen if we're attaching a new immutable
// image that has not yet been attached (medium then points to the base and we're
// creating the diff image for the immutable, and the parent is not yet registered);
// put the parent in the machine registry then
}
/* Apply the normal locking logic to the entire chain. */
true /* fMediumLockWrite */,
{
tr("Could not lock medium when creating diff '%s'"),
else
{
/* will release the lock before the potentially lengthy
* operation, so protect with the special state */
NULL /* aProgress */,
true /* aWait */);
}
}
/* Unlock the media and free the associated memory. */
delete pMediumLockList;
/* use the created diff for the actual attachment */
}
while (0);
false /* fPassthrough */,
false /* fTempEject */,
false /* fNonRotational */,
false /* fDiscard */,
fHotplug /* fHotPluggable */,
{
// as the last step, associate the medium to the VM
// here we can fail because of Deleting, or being in process of creating a Diff
}
/* success: finally remember the attachment */
mMediaData.backup();
{
{
true /* fMediumLockWrite */,
NULL,
delete pMediumLockList;
else
{
}
}
{
/* Remove lock list in case of error. */
{
}
}
}
return rc;
}
{
LogFlowThisFunc(("aControllerName=\"%s\" aControllerPort=%d aDevice=%d\n",
/* Check for an existing controller. */
tr("Could not get type of controller '%s'"),
bool fSilent = false;
/* Check whether the flag to allow silent storage attachment reconfiguration is set. */
&& strReconfig == "1")
fSilent = true;
/* Check that the controller can do hotplugging if we detach the device while the VM is running. */
bool fHotplug = false;
fHotplug = true;
return setError(VBOX_E_INVALID_VM_STATE,
tr("Controller '%s' does not support hotplugging"),
aDevice);
if (!pAttach)
return setError(VBOX_E_OBJECT_NOT_FOUND,
tr("No storage device attached to device slot %d on port %d of controller '%s'"),
return setError(VBOX_E_NOT_SUPPORTED,
tr("The device slot %d on port %d of controller '%s' does not support hotplugging"),
/*
* The VM has to detach the device before we delete any implicit diffs.
* If this fails we can roll back without loosing data.
*/
{
}
/* If we are here everything went well and we can delete the implicit now. */
return rc;
}
{
LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aPassthrough=%d\n",
return setError(VBOX_E_INVALID_VM_STATE,
tr("Invalid machine state: %s"),
aDevice);
if (!pAttach)
return setError(VBOX_E_OBJECT_NOT_FOUND,
tr("No storage device attached to device slot %d on port %d of controller '%s'"),
mMediaData.backup();
return setError(E_INVALIDARG,
tr("Setting passthrough rejected as the device attached to device slot %d on port %d of controller '%s' is not a DVD"),
return S_OK;
}
{
LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aTemporaryEject=%d\n",
aDevice);
if (!pAttach)
return setError(VBOX_E_OBJECT_NOT_FOUND,
tr("No storage device attached to device slot %d on port %d of controller '%s'"),
mMediaData.backup();
return setError(E_INVALIDARG,
tr("Setting temporary eject flag rejected as the device attached to device slot %d on port %d of controller '%s' is not a DVD"),
return S_OK;
}
{
LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aNonRotational=%d\n",
return setError(VBOX_E_INVALID_VM_STATE,
tr("Invalid machine state: %s"),
aDevice);
if (!pAttach)
return setError(VBOX_E_OBJECT_NOT_FOUND,
tr("No storage device attached to device slot %d on port %d of controller '%s'"),
mMediaData.backup();
return setError(E_INVALIDARG,
tr("Setting the non-rotational medium flag rejected as the device attached to device slot %d on port %d of controller '%s' is not a hard disk"),
return S_OK;
}
{
LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aDiscard=%d\n",
return setError(VBOX_E_INVALID_VM_STATE,
tr("Invalid machine state: %s"),
aDevice);
if (!pAttach)
return setError(VBOX_E_OBJECT_NOT_FOUND,
tr("No storage device attached to device slot %d on port %d of controller '%s'"),
mMediaData.backup();
return setError(E_INVALIDARG,
tr("Setting the discard medium flag rejected as the device attached to device slot %d on port %d of controller '%s' is not a hard disk"),
return S_OK;
}
{
LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aHotPluggable=%d\n",
return setError(VBOX_E_INVALID_VM_STATE,
tr("Invalid machine state: %s"),
aDevice);
if (!pAttach)
return setError(VBOX_E_OBJECT_NOT_FOUND,
tr("No storage device attached to device slot %d on port %d of controller '%s'"),
/* Check for an existing controller. */
tr("Could not get type of controller '%s'"),
return setError(VBOX_E_NOT_SUPPORTED,
tr("Controller '%s' does not support changing the hot-pluggable device flag"),
mMediaData.backup();
return setError(E_INVALIDARG,
tr("Setting the hot-pluggable device flag rejected as the device attached to device slot %d on port %d of controller '%s' is a floppy drive"),
return S_OK;
}
{
LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d\n",
return rc;
}
{
LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d\n",
return setError(VBOX_E_INVALID_VM_STATE,
tr("Invalid machine state: %s"),
aDevice);
if (!pAttach)
return setError(VBOX_E_OBJECT_NOT_FOUND,
tr("No storage device attached to device slot %d on port %d of controller '%s'"),
mMediaData.backup();
if (strBandwidthGroupOld.isNotEmpty())
{
/* Get the bandwidth group object and release it - this must not fail. */
}
{
group->i_reference();
}
return S_OK;
}
{
LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aType=%d aMedium=%p\n",
return rc;
}
{
LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d",
return rc;
}
{
LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d aForce=%d\n",
// request the host lock first, since might be calling Host methods for getting host drives;
// next, protect the media tree all the while we're in here, as well as our member variables
this->lockHandle(),
aDevice);
return setError(VBOX_E_OBJECT_NOT_FOUND,
tr("No drive attached to device slot %d on port %d of controller '%s'"),
/* Remember previously mounted medium. The medium before taking the
* backup is not necessarily the same thing. */
if (pMedium)
{
switch (mediumType)
{
case DeviceType_DVD:
case DeviceType_Floppy:
break;
default:
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("The device at port %d, device %d of controller '%s' of this virtual machine is not removeable"),
}
}
mMediaData.backup();
{
// The backup operation makes the pAttach reference point to the
// old settings. Re-get the correct reference.
aDevice);
{
}
}
/* On error roll back this change only. */
{
aDevice);
/* If the attachment is gone in the meantime, bail out. */
return rc;
}
return rc;
}
{
LogFlowThisFunc(("aName=\"%s\" aControllerPort=%d aDevice=%d\n",
aDevice);
return setError(VBOX_E_OBJECT_NOT_FOUND,
tr("No storage device attached to device slot %d on port %d of controller '%s'"),
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
/* Do not assert if slot is out of range, just return the advertised
status. testdriver/vbox.py triggers this in logVmInfo. */
return setError(E_INVALIDARG,
tr("No network adapter in slot %RU32 (total %RU32 adapters)"),
return S_OK;
}
{
size_t i = 0;
for (settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.begin();
++it, ++i)
return S_OK;
}
/**
* @note Locks this object for reading.
*/
{
/* start with nothing found */
aValue = "";
// found:
/* return the result to caller (may be empty) */
return S_OK;
}
/**
* @note Locks mParent for writing + this object for writing.
*/
{
// locking note: we only hold the read lock briefly to look up the old value,
// then release it and call the onExtraCanChange callbacks. There is a small
// chance of a race insofar as the callback might be called twice if two callers
// change the same key at the same time, but that's a much better solution
// than the deadlock we had here before. The actual changing of the extradata
// is then performed under the write lock and race-free.
// look up the old value first; if nothing has changed then we need not do anything
{
}
bool fChanged;
{
// ask for permission from all listeners outside the locks;
// i_onExtraDataCanChange() only briefly requests the VirtualBox
// lock to copy the list of callbacks to invoke
{
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 '%s' to '%s'%s%ls"),
sep,
err);
}
// data is changing and change not vetoed: then write it out under the lock
if (i_isSnapshotMachine())
{
}
else
// creates a new key if needed
bool fNeedsGlobalSaveSettings = false;
{
// save the global settings; for that we should hold only the VirtualBox lock
}
}
// fire notification outside the lock
if (fChanged)
return S_OK;
}
HRESULT Machine::setSettingsFilePath(const com::Utf8Str &aSettingsFilePath, ComPtr<IProgress> &aProgress)
{
}
{
/* 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 */
bool fNeedsGlobalSaveSettings = false;
{
// save the global settings; for that we should hold only the VirtualBox lock
}
return rc;
}
{
/*
* during this rollback, the session will be notified if data has
* been actually changed
*/
i_rollback(true /* aNotify */);
return S_OK;
}
/** @note Locks objects! */
{
// use AutoLimitedCaller because this call is valid on inaccessible machines as well
AutoLimitedCaller autoCaller(this);
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("Cannot unregister the machine '%s' while it is locked"),
// wait for state dependents to drop to zero
if (!mData->mAccessible)
{
// inaccessible maschines 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();
// calls VirtualBox::i_saveSettings()
return S_OK;
}
// discard saved state
{
// add the saved state file to the list of files the caller should delete
// unconditionally set the machine state to powered off, we now
// know no session has locked the machine
}
size_t cSnapshots = 0;
if (mData->mFirstSnapshot)
// fail now before we start detaching media
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("Cannot unregister the machine '%s' because it has %d snapshots"),
// This list collects the medium objects from all medium attachments
// which we will detach from the machine and its snapshots, in a specific
// order which allows for closing all media without getting "media in use"
// errors, simply by going through the list from the front to the back:
// 1) first media from machine attachments (these have the "leaf" attachments with snapshots
// and must be closed before the parent media from the snapshots, or closing the parents
// will fail because they still have children);
// 2) media from the youngest snapshots followed by those from the parent snapshots until
// the root ("first") snapshot of the machine.
)
{
// we have media attachments: detach them all and add the Medium objects to our list
else
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("Cannot unregister the machine '%s' because it has %d media attachments"),
}
if (cSnapshots)
{
// autoCleanup must be true here, or we would have failed above
// add the media from the medium attachments of the snapshots to llMedia
// as well, after the "main" machine media; Snapshot::uninitRecursively()
// calls Machine::detachAllMedia() for the snapshot machine, recursing
// into the children first
// Snapshot::beginDeletingSnapshot() asserts if the machine state is not this
// make a copy of the first snapshot so the refcount does not drop to 0
// in beginDeletingSnapshot, which sets pFirstSnapshot to 0 (that hangs
// because of the AutoCaller voodoo)
// GO!
}
{
return rc;
}
// commit all the media changes made above
mData->mRegistered = false;
// machine lock no longer needed
// return media to caller
size_t i = 0;
// calls VirtualBox::i_saveSettings() and VirtualBox::saveModifiedRegistries()
return S_OK;
}
struct Machine::DeleteTask
{
};
HRESULT Machine::deleteConfig(const std::vector<ComPtr<IMedium> > &aMedia, ComPtr<IProgress> &aProgress)
{
if (mData->mRegistered)
return setError(VBOX_E_INVALID_VM_STATE,
tr("Cannot delete settings of a registered machine"));
// collect files to delete
{
/* At this point the medium should not have any back references
* anymore. If it has it is attached to another VM and *must* not
* deleted. */
}
static_cast<IMachine*>(this) /* aInitiator */,
true /* fCancellable */,
(void*)pTask,
0,
0,
"MachineDelete");
if (RT_FAILURE(vrc))
{
delete pTask;
}
return S_OK;
}
/**
* Static task wrapper passed to RTThreadCreate() in Machine::Delete() which then
* calls Machine::deleteTaskWorker() on the actual machine object.
* @param Thread
* @param pvUser
* @return
*/
/*static*/
{
delete pTask;
return VINF_SUCCESS;
}
/**
* Task thread implementation for Machine::Delete(), called from Machine::deleteThread().
* @param task
* @return
*/
{
AutoCaller autoCaller(this);
try
{
if (!systemProperties.isNull())
{
}
{
{
}
/* Check the result of the asynchronous process. */
/* If the thread of the progress object has an error, then
* retrieve the error info from there, or it'll be lost. */
/* Close the medium, deliberately without checking the return
- * code, and without leaving any trace in the error info, as
- * a failure here is a very minor issue, which shouldn't happen
- * as above we even managed to delete the medium. */
{
}
}
// delete the files pushed on the task list by Machine::Delete()
// (this includes saved states of the machine and snapshots and
// medium storage files from the IMedium list passed in, and the
// machine XML file)
{
if (RT_FAILURE(vrc))
throw setError(VBOX_E_IPRT_ERROR,
++it;
{
break;
}
}
/* delete the settings only when the file actually exists */
{
/* Delete any backup or uncommitted XML files. Ignore failures.
See the fSafe parameter of xml::XmlFileWriter::write for details. */
Utf8Str otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszTmpSuff);
otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszPrevSuff);
/* 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) */
{
/* 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. */
for (int i = uLogHistoryCount; i > 0; i--)
{
}
}
/* 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) */
// delete the directory that contains the settings file, but only
// if it matches the VM name
if (i_isInOwnDir(&settingsDir))
}
}
return rc;
}
{
// null case (caller wants root snapshot): i_findSnapshotById() handles this
else
{
else
}
return rc;
}
HRESULT Machine::createSharedFolder(const com::Utf8Str &aName, const com::Utf8Str &aHostPath, BOOL aWritable, BOOL aAutomount)
{
return setError(VBOX_E_OBJECT_IN_USE,
tr("Shared folder named '%s' already exists"),
!!aWritable,
!!aAutomount,
true /* fFailOnError */);
/* inform the direct session if any */
return S_OK;
}
{
/* inform the direct session if any */
return S_OK;
}
{
/* start with No */
{
return setError(VBOX_E_INVALID_VM_STATE,
tr("Machine is not locked for session (session state: %s)"),
}
/* ignore calls made after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
}
{
{
tr("Machine is not locked for session (session state: %s)"),
}
/* ignore calls made after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
}
#ifdef VBOX_WITH_GUEST_PROPS
/**
* Look up a guest property in VBoxSVC's internal structures.
*/
{
using namespace guestProp;
{
}
return S_OK;
}
/**
* Query the VM that a guest property belongs to for the property.
* @returns E_ACCESSDENIED if the VM process is not available or not
* currently handling queries and the lookup should then be done in
* VBoxSVC.
*/
{
/* fail if we were called after #OnSessionEnd() is called. This is a
* silly race condition. */
/** @todo This code is bothering API clients (like python script clients) with
* the AccessGuestProperty call, creating unncessary IPC. Need to
* have a way of figuring out which kind of direct session it is... */
if (!directControl)
rc = E_ACCESSDENIED;
else
false /* isSetter */,
return rc;
}
#endif // VBOX_WITH_GUEST_PROPS
{
#ifndef VBOX_WITH_GUEST_PROPS
#else // VBOX_WITH_GUEST_PROPS
if (rc == E_ACCESSDENIED)
/* The VM is not running or the service is not (yet) accessible */
return rc;
#endif // VBOX_WITH_GUEST_PROPS
}
{
return rc;
}
{
return rc;
}
#ifdef VBOX_WITH_GUEST_PROPS
/**
* Set a guest property in VBoxSVC's internal structures.
*/
{
using namespace guestProp;
try
{
{
if (!fDelete)
{
}
}
else
{
{
rc = setError(E_ACCESSDENIED, tr("The property '%s' cannot be changed by the host"), aName.c_str());
}
else
{
/* The backupEx() operation invalidates our iterator,
* so get a new one. */
if (!fDelete)
{
}
else
}
}
NULL)
)
)
{
}
}
{
rc = E_OUTOFMEMORY;
}
return rc;
}
/**
* Set a property on the VM that that property belongs to.
* @returns E_ACCESSDENIED if the VM process is not available or not
* currently handling queries and the setting should then be done in
* VBoxSVC.
*/
{
try
{
if (!directControl)
rc = E_ACCESSDENIED;
else
/** @todo Fix when adding DeleteGuestProperty(), see defect. */
true /* isSetter */,
}
{
rc = E_OUTOFMEMORY;
}
return rc;
}
#endif // VBOX_WITH_GUEST_PROPS
{
#ifndef VBOX_WITH_GUEST_PROPS
#else // VBOX_WITH_GUEST_PROPS
if (rc == E_ACCESSDENIED)
/* The VM is not running or the service is not (yet) accessible */
return rc;
#endif // VBOX_WITH_GUEST_PROPS
}
{
}
{
}
#ifdef VBOX_WITH_GUEST_PROPS
/**
* Enumerate the guest properties in VBoxSVC's internal structures.
*/
{
using namespace guestProp;
/*
* Look for matching patterns and build up a list.
*/
{
if ( strPatterns.isEmpty()
NULL)
)
it++;
}
/*
* And build up the arrays for returning the property information.
*/
size_t i= 0;
{
}
return S_OK;
}
/**
* Enumerate the properties managed by a VM.
* @returns E_ACCESSDENIED if the VM process is not available or not
* currently handling queries and the setting should then be done in
* VBoxSVC.
*/
{
if (!directControl)
rc = E_ACCESSDENIED;
else
size_t i;
for (i = 0; i < bTimestamps.size(); ++i)
aTimestamps[i] = bTimestamps[i];
return rc;
}
#endif // VBOX_WITH_GUEST_PROPS
{
#ifndef VBOX_WITH_GUEST_PROPS
#else // VBOX_WITH_GUEST_PROPS
if (rc == E_ACCESSDENIED)
/* The VM is not running or the service is not (yet) accessible */
return rc;
#endif // VBOX_WITH_GUEST_PROPS
}
{
size_t i = 0;
return S_OK;
}
{
LogFlowThisFunc(("aControllerName=\"%s\" aControllerPort=%d aDevice=%d\n",
aAttachment = NULL;
aDevice);
return setError(VBOX_E_OBJECT_NOT_FOUND,
tr("No storage device attached to device slot %d on port %d of controller '%s'"),
return S_OK;
}
{
if ( (aConnectionType <= StorageBus_Null)
|| (aConnectionType > StorageBus_USB))
return setError(E_INVALIDARG,
tr("Invalid connection type: %d"),
/* try to find one with the name first. */
return setError(VBOX_E_OBJECT_IN_USE,
tr("Storage controller named '%s' already exists"),
ctrl.createObject();
/* get a new instance number for the storage controller */
ULONG ulInstance = 0;
bool fBootable = true;
++it)
{
{
if (ulCurInst >= ulInstance)
/* Only one controller of each type can be marked as bootable. */
if ((*it)->i_getBootable())
fBootable = false;
}
}
/* inform the direct session if any */
return S_OK;
}
{
return rc;
}
{
++it)
{
{
return S_OK;
}
}
return setError(VBOX_E_OBJECT_NOT_FOUND,
tr("Could not find a storage controller with instance number '%lu'"),
}
{
{
/* Ensure that only one controller of each type is marked as bootable. */
{
++it)
{
{
break;
}
}
}
{
}
}
{
/* inform the direct session if any */
}
return rc;
}
{
{
/* find all attached devices to the appropriate storage controller and detach them all */
// make a temporary list because detachDevice invalidates iterators into
// mMediaData->mAttachments
++it)
{
{
}
}
}
/* We can remove it now. */
/* inform the direct session if any */
return S_OK;
}
{
if ( (aType <= USBControllerType_Null)
|| (aType >= USBControllerType_Last))
return setError(E_INVALIDARG,
tr("Invalid USB controller type: %d"),
aType);
/* try to find one with the same type first. */
return setError(VBOX_E_OBJECT_IN_USE,
tr("USB controller named '%s' already exists"),
/* Check that we don't exceed the maximum number of USB controllers for the given type. */
rc = mParent->i_getSystemProperties()->GetMaxInstancesOfUSBControllerType(mHWData->mChipsetType, aType, &maxInstances);
return rc;
if (cInstances >= maxInstances)
return setError(E_INVALIDARG,
tr("Too many USB controllers of this type"));
ctrl.createObject();
/* inform the direct session if any */
return S_OK;
}
HRESULT Machine::getUSBControllerByName(const com::Utf8Str &aName, ComPtr<IUSBController> &aController)
{
return rc;
}
{
if ( (aType <= USBControllerType_Null)
|| (aType >= USBControllerType_Last))
return setError(E_INVALIDARG,
tr("Invalid USB controller type: %d"),
aType);
return S_OK;
}
{
/* inform the direct session if any */
return S_OK;
}
{
uint32_t u32OriginX= 0;
uint32_t u32OriginY= 0;
if (RT_FAILURE(vrc))
{
#ifdef RT_OS_WINDOWS
/* HACK: GUI sets *pfEnabled to 'true' and expects it to stay so if the API fails.
* This works with XPCOM. But Windows COM sets all output parameters to zero.
* So just assign fEnable to TRUE again.
* The right fix would be to change GUI API wrappers to make sure that parameters
* are changed only if API succeeds.
*/
#endif
return setError(VBOX_E_IPRT_ERROR,
tr("Saved guest size is not available (%Rrc)"),
vrc);
}
*aOriginX = u32OriginX;
*aOriginY = u32OriginY;
return S_OK;
}
HRESULT Machine::querySavedThumbnailSize(ULONG aScreenId, ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
{
if (aScreenId != 0)
return E_NOTIMPL;
int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
if (RT_FAILURE(vrc))
return setError(VBOX_E_IPRT_ERROR,
tr("Saved screenshot data is not available (%Rrc)"),
vrc);
return S_OK;
}
HRESULT Machine::readSavedThumbnailToArray(ULONG aScreenId, BOOL aBGR, ULONG *aWidth, ULONG *aHeight, std::vector<BYTE> &aData)
{
if (aScreenId != 0)
return E_NOTIMPL;
int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
if (RT_FAILURE(vrc))
return setError(VBOX_E_IPRT_ERROR,
tr("Saved screenshot data is not available (%Rrc)"),
vrc);
/* Convert pixels to format expected by the API caller. */
if (aBGR)
{
/* [0] B, [1] G, [2] R, [3] A. */
for (unsigned i = 0; i < cbData; i += 4)
{
}
}
else
{
/* [0] R, [1] G, [2] B, [3] A. */
for (unsigned i = 0; i < cbData; i += 4)
{
}
}
return S_OK;
}
HRESULT Machine::readSavedThumbnailPNGToArray(ULONG aScreenId, ULONG *aWidth, ULONG *aHeight, std::vector<BYTE> &aData)
{
if (aScreenId != 0)
return E_NOTIMPL;
int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
if (RT_FAILURE(vrc))
return setError(VBOX_E_IPRT_ERROR,
tr("Saved screenshot data is not available (%Rrc)"),
vrc);
if (RT_SUCCESS(vrc))
{
if (pu8PNG)
aData[i] = screenData[i];
}
else
{
if (pu8PNG)
return setError(VBOX_E_IPRT_ERROR,
tr("Could not convert screenshot to PNG (%Rrc)"),
vrc);
}
return rc;
}
HRESULT Machine::querySavedScreenshotPNGSize(ULONG aScreenId, ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
{
if (aScreenId != 0)
return E_NOTIMPL;
int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
if (RT_FAILURE(vrc))
return setError(VBOX_E_IPRT_ERROR,
tr("Saved screenshot data is not available (%Rrc)"),
vrc);
return S_OK;
}
HRESULT Machine::readSavedScreenshotPNGToArray(ULONG aScreenId, ULONG *aWidth, ULONG *aHeight, std::vector<BYTE> &aData)
{
if (aScreenId != 0)
return E_NOTIMPL;
int vrc = readSavedDisplayScreenshot(mSSData->strStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
if (RT_FAILURE(vrc))
return setError(VBOX_E_IPRT_ERROR,
tr("Saved screenshot thumbnail data is not available (%Rrc)"),
vrc);
return S_OK;
}
{
if (!mHWData->mCPUHotPlugEnabled)
return setError(E_INVALIDARG, tr("CPU id exceeds number of possible CPUs [0:%lu]"), mHWData->mCPUCount-1);
/** Save settings if online - @todo why is this required? -- @bugref{6818} */
return S_OK;
}
{
if (!mHWData->mCPUHotPlugEnabled)
return setError(E_INVALIDARG,
tr("CPU index exceeds maximum CPU count (must be in range [0:%lu])"),
/* CPU 0 can't be detached */
if (aCpu == 0)
/** Save settings if online - @todo why is this required? -- @bugref{6818} */
return S_OK;
}
{
*aAttached = false;
/* If hotplug is enabled the CPU is always enabled. */
if (!mHWData->mCPUHotPlugEnabled)
{
*aAttached = true;
}
else
{
}
return S_OK;
}
{
return S_OK;
}
{
if (aSize < 0)
/* do not unnecessarily hold the lock while doing something which does
* not need the lock and potentially takes a long time. */
/* Limit the chunk size to 32K for now, as that gives better performance
* over (XP)COM, and keeps the SOAP reply size under 1M for the webservice.
* One byte expands to approx. 25 bytes of breathtaking XML. */
if (RT_SUCCESS(vrc))
{
if (RT_SUCCESS(vrc))
else
tr("Could not read log file '%s' (%Rrc)"),
}
else
tr("Could not open log file '%s' (%Rrc)"),
return rc;
}
/**
* Currently this method doesn't attach device to the running VM,
* just makes sure it's plugged on next VM start.
*/
HRESULT Machine::attachHostPCIDevice(LONG aHostAddress, LONG aDesiredGuestAddress, BOOL /* aTryToUnbind */)
{
// lock scope
{
if (aChipset != ChipsetType_ICH9)
{
return setError(E_INVALIDARG,
tr("Host PCI attachment only supported with ICH9 chipset"));
}
// check if device with this host PCI address already attached
++it)
{
if (iHostAddress == aHostAddress)
return setError(E_INVALIDARG,
tr("Device with host PCI address already attached to this VM"));
}
char name[32];
pda.createObject();
}
return S_OK;
}
/**
* Currently this method doesn't detach device from the running VM,
* just makes sure it's not plugged on next VM start.
*/
{
bool fRemoved = false;
// lock scope
{
++it)
{
{
fRemoved = true;
break;
}
}
}
/* Fire event outside of the lock */
if (fRemoved)
{
fireHostPCIDevicePlugEvent(es, mid.raw(), false /* unplugged */, true /* success */, pAttach, NULL);
}
tr("No host PCI device %08x attached"),
);
}
HRESULT Machine::getPCIDeviceAssignments(std::vector<ComPtr<IPCIDeviceAttachment> > &aPCIDeviceAssignments)
{
size_t i = 0;
for (std::list<ComObjPtr<PCIDeviceAttachment> >::const_iterator it = mHWData->mPCIDeviceAssignments.begin();
++i, ++it)
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
{
{
{
}
}
return hrc;
}
{
return S_OK;
}
{
{
{
}
}
return hrc;
}
{
return S_OK;
}
{
{
{
}
}
return hrc;
}
{
return S_OK;
}
{
{
int vrc;
if (aAutostartEnabled)
else
if (RT_SUCCESS(vrc))
{
{
}
}
else if (vrc == VERR_NOT_SUPPORTED)
tr("The VM autostart feature is not supported on this platform"));
else if (vrc == VERR_PATH_NOT_FOUND)
tr("The path to the autostart database is not set"));
else
tr("%s machine '%s' to the autostart database failed with %Rrc"),
}
return hrc;
}
{
return S_OK;
}
{
{
{
}
}
return hrc;
}
{
return S_OK;
}
{
{
int vrc;
if (aAutostopType != AutostopType_Disabled)
else
if (RT_SUCCESS(vrc))
{
{
}
}
else if (vrc == VERR_NOT_SUPPORTED)
tr("The VM autostop feature is not supported on this platform"));
else if (vrc == VERR_PATH_NOT_FOUND)
tr("The path to the autostart database is not set"));
else
tr("%s machine '%s' to the autostop database failed with %Rrc"),
}
return hrc;
}
{
return S_OK;
}
{
{
{
}
}
return hrc;
}
{
return S_OK;
}
{
{
}
return hrc;
}
{
#ifdef VBOX_WITH_USB
*aUSBProxyAvailable = true;
#else
*aUSBProxyAvailable = false;
#endif
return S_OK;
}
HRESULT Machine::cloneTo(const ComPtr<IMachine> &aTarget, CloneMode_T aMode, const std::vector<CloneOptions_T> &aOptions,
{
/* Convert the options. */
{
if (!i_isSnapshotMachine())
return setError(E_INVALIDARG,
tr("Linked clone can only be created from a snapshot"));
if (aMode != CloneMode_MachineState)
return setError(E_INVALIDARG,
tr("Linked clone can only be created for a single machine state"));
}
AssertReturn(!(optList.contains(CloneOptions_KeepAllMACs) && optList.contains(CloneOptions_KeepNATMACs)), E_INVALIDARG);
return rc;
}
// public methods for internal purposes
/////////////////////////////////////////////////////////////////////////////
/**
* Adds the given IsModified_* flag to the dirty flags of the machine.
* This must be called either during i_loadSettings or under the machine write lock.
* @param fl
*/
{
mData->mCurrentStateModified = true;
}
/**
* Adds the given IsModified_* flag to the dirty flags of the machine, taking
* care of the write locking.
*
* @param fModifications The flag to add.
*/
{
}
/**
* 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);
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);
char folder[RTPATH_MAX];
if (RT_SUCCESS(vrc))
return vrc;
}
/**
* Copies strSource to strTarget, making it relative to the machine folder
* if it is a subdirectory thereof, or simply copying it otherwise.
*
* @param strSource Path to evaluate and copy.
* @param strTarget Buffer to receive target path.
*
* @note Locks this object for reading.
*/
{
AutoCaller autoCaller(this);
// use strTarget as a temporary buffer to hold the machine settings dir
{
// is relative: then append what's left
// for empty paths (only possible for subdirs) use "." to avoid
// triggering default settings for not present config attributes.
strTarget = ".";
}
else
// is not relative: then overwrite
}
/**
* Returns the full path to the machine's log folder in the
* \a aLogFolder argument.
*/
{
AutoCaller autoCaller(this);
char szTmp[RTPATH_MAX];
if (RT_SUCCESS(vrc))
{
{
char szTmp2[RTPATH_MAX];
if (RT_SUCCESS(vrc))
}
else
}
if (RT_FAILURE(vrc))
{
// fallback if VBOX_USER_LOGHOME is not set or invalid
}
}
/**
* Returns the full path to the machine's log file for an given index.
*/
{
if (idx == 0)
else
return log;
}
/**
* Composes a unique saved state filename based on the current system time. The filename is
* granular to the second so this will work so long as no more than one snapshot is taken on
* a machine per second.
*
* Before version 4.1, we used this formula for saved state files:
* Utf8StrFmt("%s%c{%RTuuid}.sav", strFullSnapshotFolder.c_str(), RTPATH_DELIMITER, mData->mUuid.raw())
* which no longer works because saved state files can now be shared between the saved state of the
* "saved" machine and an online snapshot, and the following would cause problems:
* 1) save machine
* 2) create online snapshot from that machine state --> reusing saved state file
* 3) save machine again --> filename would be reused, breaking the online snapshot
*
* So instead we now use a timestamp.
*
* @param str
*/
{
AutoCaller autoCaller(this);
{
}
}
/**
* Returns the full path to the default video capture file.
*/
{
AutoCaller autoCaller(this);
}
/**
* Returns whether at least one USB controller is present for the VM.
*/
bool Machine::i_isUSBControllerPresent()
{
AutoCaller autoCaller(this);
return (mUSBControllers->size() > 0);
}
/**
* @note Locks this object for writing, calls the client process
* (inside the lock).
*/
const Utf8Str &strFrontend,
const Utf8Str &strEnvironment,
{
AutoCaller autoCaller(this);
if (!mData->mRegistered)
return setError(E_UNEXPECTED,
tr("The machine '%s' is not registered"),
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("The machine '%s' is already locked by a session (or being locked or unlocked)"),
/* may not be busy */
/* get the path to the executable */
char szPath[RTPATH_MAX];
int vrc = VINF_SUCCESS;
if (!strEnvironment.isEmpty())
{
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);
}
#ifdef VBOX_WITH_QTGUI
{
# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
/* Modify the base path so that we don't need to use ".." below. */
#define OSX_APP_NAME "VirtualBoxVM"
#define OSX_APP_PATH_FMT "/Resources/%s.app/Contents/MacOS/VirtualBoxVM"
if (!strAppOverride.isEmpty())
{
/* there is a race, but people using this deserve the failure */
}
if (strAppOverride.isEmpty())
# else
# endif
}
#else /* !VBOX_WITH_QTGUI */
if (0)
;
#endif /* VBOX_WITH_QTGUI */
else
#ifdef VBOX_WITH_VBOXSDL
{
const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), 0 };
}
#else /* !VBOX_WITH_VBOXSDL */
if (0)
;
#endif /* !VBOX_WITH_VBOXSDL */
else
#ifdef VBOX_WITH_HEADLESS
if ( strFrontend == "headless"
|| strFrontend == "capture"
)
{
/* On pre-4.0 the "headless" type was used for passing "--vrdp off" to VBoxHeadless to let it work in OSE,
* which did not contain VRDP server. In VBox 4.0 the remote desktop server (VRDE) is optional,
* and a VM works even if the server has not been installed.
* So in 4.0 the "headless" behavior remains the same for default VBox installations.
* Only if a VRDE has been installed and the VM enables it, the "headless" will work
* differently in 4.0 and 3.x.
*/
/* Leave space for "--capture" arg. */
"--vrde", "config",
0, /* For "--capture". */
0 };
if (strFrontend == "capture")
{
}
#ifdef RT_OS_WINDOWS
#else
0
#endif
, &pid);
}
#else /* !VBOX_WITH_HEADLESS */
if (0)
;
#endif /* !VBOX_WITH_HEADLESS */
else
{
return setError(E_INVALIDARG,
tr("Invalid frontend name: '%s'"),
strFrontend.c_str());
}
if (RT_FAILURE(vrc))
return setError(VBOX_E_IPRT_ERROR,
tr("Could not launch a process for the machine '%s' (%Rrc)"),
/*
* Note that we don't release the lock here before calling the client,
* because it doesn't need to call us back if called with a NULL argument.
* Releasing the lock here 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 LockMachine() 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"));
#else /* VBOX_WITH_GENERIC_SESSION_WATCHER */
#endif /* VBOX_WITH_GENERIC_SESSION_WATCHER */
{
/* 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;
}
/**
* Returns @c true if the given session machine instance has an open direct
* session (and optionally also for direct sessions which are closing) and
* returns the session control machine instance 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 aAllowClosing If true then additionally a session which is currently
* being closed will also be allowed.
*
* @note locks this object for reading.
*/
bool aAllowClosing /*= false*/)
{
AutoLimitedCaller autoCaller(this);
/* just return false for inaccessible machines */
return false;
)
{
return true;
}
return false;
}
/**
* Returns @c true if the given machine has an spawning direct session.
*
* @note locks this object for reading.
*/
bool Machine::i_isSessionSpawning()
{
AutoLimitedCaller autoCaller(this);
/* just return false for inaccessible machines */
return false;
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::i_checkForSpawnFailure()
{
AutoCaller autoCaller(this);
if (!autoCaller.isOk())
{
/* nothing to do */
LogFlowThisFunc(("Already uninitialized!\n"));
return true;
}
{
/* nothing to do */
LogFlowThisFunc(("Not spawning any more!\n"));
return true;
}
/* PID not yet initialized, skip check. */
return false;
if (vrc != VERR_PROCESS_RUNNING)
{
tr("The virtual machine '%s' has terminated unexpectedly during startup with exit code %d"),
tr("The virtual machine '%s' has terminated unexpectedly during startup because of signal %d"),
tr("The virtual machine '%s' has terminated abnormally"),
else
tr("The virtual machine '%s' has terminated unexpectedly during startup (%Rrc)"),
}
{
/* 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 LockMachine()). */
{
}
/* finalize the progress after setting the state */
{
}
return true;
}
return false;
}
/**
* Checks whether the machine can be registered. If so, commits and saves
* all settings.
*
* @note Must be called from mParent's write lock. Locks this object and
* children for writing.
*/
{
AutoLimitedCaller autoCaller(this);
/* wait for state dependents to drop to zero */
if (!mData->mAccessible)
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("The machine '%s' with UUID {%s} is inaccessible and cannot be registered"),
if (mData->mRegistered)
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("The machine '%s' with UUID {%s} is already registered"),
// Ensure the settings are saved. If we are going to be registered and
// no config file exists yet, create it by calling i_saveSettings() too.
if ( (mData->flModifications)
)
{
// no need to check whether VirtualBox.xml needs saving too since
// we can't have a machine XML file rename pending
}
/* more config checking goes here */
{
/* we may have had implicit modifications we want to fix on success */
i_commit();
mData->mRegistered = true;
}
else
{
/* we may have had implicit modifications we want to cancel on failure*/
i_rollback(false /* aNotify */);
}
return rc;
}
/**
* 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);
{
if (mData->mMachineStateChangePending != 0)
{
/* i_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."));
}
}
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::i_releaseStateDependency()
{
AutoCaller autoCaller(this);
/* releaseStateDependency() w/o addStateDependency()? */
-- mData->mMachineStateDeps;
if (mData->mMachineStateDeps == 0)
{
/* inform i_ensureNoStateDependencies() that there are no more deps */
if (mData->mMachineStateChangePending != 0)
{
}
}
}
{
/* start with nothing found */
settings::StringsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(strKey);
// found:
return strResult;
}
// 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 immediately 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.
*
* When @a aDepType is OfflineStateDep, this method returns S_OK if the
* state is one of the 4 offline states (PoweredOff, Saved, Teleported,
* Aborted).
*
* @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
&& ( !i_isSessionMachine() /** @todo This was just converted raw; Check if Running and
Paused should actually be included here... (Live Migration) */
)
)
)
return setError(VBOX_E_INVALID_VM_STATE,
tr("The machine is not mutable (state is %s)"),
break;
}
case MutableOrSavedStateDep:
{
if ( mData->mRegistered
&& ( !i_isSessionMachine() /** @todo This was just converted raw; Check if Running and
Paused should actually be included here... (Live Migration) */
)
)
)
return setError(VBOX_E_INVALID_VM_STATE,
tr("The machine is not mutable (state is %s)"),
break;
}
case OfflineStateDep:
{
if ( mData->mRegistered
&& ( !i_isSessionMachine()
)
)
)
return setError(VBOX_E_INVALID_VM_STATE,
tr("The machine is not offline (state is %s)"),
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);
/* create an associated VRDE object (default is disabled) */
mVRDEServer->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 device filters object (always present) */
mUSBDeviceFilters->init(this);
/* create associated network adapter objects */
{
}
/* create the bandwidth control */
mBandwidthControl->init(this);
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);
/* tell all our other child objects we've been uninitialized */
if (mBandwidthControl)
{
}
{
if (mNetworkAdapters[slot])
{
}
}
if (mUSBDeviceFilters)
{
}
if (mAudioAdapter)
{
mAudioAdapter->uninit();
}
{
if (mParallelPorts[slot])
{
}
}
{
if (mSerialPorts[slot])
{
}
}
if (mVRDEServer)
{
mVRDEServer->uninit();
}
if (mBIOSSettings)
{
mBIOSSettings->uninit();
}
/* Deassociate media (only when a real Machine or a SnapshotMachine
* instance is uninitialized; SessionMachine instances refer to real
* Machine media). 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 deleting the snapshot), outdated media
* attachments will already be uninitialized and deleted, so this
* code will not affect them. */
if ( !!mMediaData
&& (!i_isSessionMachine())
)
{
++it)
{
continue;
}
}
if (!i_isSessionMachine() && !i_isSnapshotMachine())
{
// clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
if (mData->mFirstSnapshot)
{
// snapshots tree is protected by machine write lock; strictly
// this isn't necessary here since we're deleting the entire
// machine, but otherwise we assert in Snapshot::uninit()
}
}
/* free data structures (the essential mData structure is not freed here
* since it may be still in use) */
mMediaData.free();
}
/**
* Returns a pointer to the Machine object for this machine that acts like a
* parent for complex machine data objects such as shared folders, etc.
*
* For primary Machine objects and for SnapshotMachine objects, returns this
* object's pointer itself. For SessionMachine objects, returns the peer
* (primary) machine pointer.
*/
{
if (i_isSessionMachine())
return this;
}
/**
* Makes sure that there are no machine state dependents. If necessary, waits
* for the number of dependents to drop to zero.
*
* Make sure this method is called from under this object's write lock to
* guarantee that no new dependents 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::i_ensureNoStateDependencies()
{
/* Wait for all state dependents 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 dependent 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);
/* wait for state dependents 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 VBOX_E_OBJECT_NOT_FOUND when not found
*
* @note
* must be called from under the object's lock!
*/
bool aSetError /* = false */)
{
++it)
{
{
aSharedFolder = pSF;
break;
}
}
return rc;
}
/**
* Initializes all machine instance data from the given settings structures
* from XML. The exception is the machine UUID which needs special handling
* depending on the caller's use case, so the caller needs to set that herself.
*
* This gets called in several contexts during machine initialization:
*
* -- When machine XML exists on disk already and needs to be loaded into memory,
* for example, from registeredInit() to load all registered machines on
* VirtualBox startup. In this case, puuidRegistry is NULL because the media
* attached to the machine should be part of some media registry already.
*
* -- During OVF import, when a machine config has been constructed from an
* OVF file. In this case, puuidRegistry is set to the machine UUID to
* ensure that the media listed as attachments in the config (which have
* been imported from the OVF) receive the correct registry ID.
*
* -- During VM cloning.
*
* @param config Machine settings from XML.
* @param puuidRegistry If != NULL, Medium::setRegistryIdIfFirst() gets called with this registry ID
* for each attached medium in the config.
* @return
*/
const Guid *puuidRegistry)
{
// copy name, description, OS type, teleporter, UTC etc.
// Decode the Icon overide data from config userdata and set onto Machine.
#define DECODE_STR_MAX _1M
if (cbOut > DECODE_STR_MAX)
tr("Icon Data too long.'%d' > '%d'"),
tr("Failure to Decode Icon Data. '%s' (%d)"),
rc);
// look up the object by Id to check it is valid
// stateFile (optional)
else
{
if (RT_FAILURE(vrc))
tr("Invalid saved state file path '%s' (%Rrc)"),
vrc);
}
// snapshot folder needs special processing so set it again
/* Copy the extra data items (Not in any case config is already the same as
* mData->pMachineConfigFile, like when the xml files are read from disk. So
* make sure the extra data map is copied). */
/* currentStateModified (optional, default is true) */
/*
* note: all mUserData members must be assigned prior this point because
* we need to commit changes in order to let mUserData be shared by all
* snapshot machine instances.
*/
// machine registry, if present (must be loaded before snapshots)
if (config.canHaveOwnMediaRegistry())
{
// determine machine folder
}
/* Snapshot node (optional) */
{
// there must be only one root snapshot
NULL); // no parent == first snapshot
}
// hardware data
// load storage controllers
NULL /* puuidSnapshot */);
/*
* NOTE: the assignment below must be the last thing to do,
* otherwise it will be not possible to change the settings
* somewhere in the code above because all setters will be
* blocked by i_checkStateDependency(MutableStateDep).
*/
/* set the machine state to Aborted or Saved when appropriate */
{
/* no need to use i_setMachineState() during init() */
}
{
/* no need to use i_setMachineState() during init() */
}
// after loading settings, we are no longer different from the XML on disk
mData->flModifications = 0;
return S_OK;
}
/**
* 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,
{
{
/* optional */
if (RT_FAILURE(vrc))
tr("Invalid saved state file path '%s' (%Rrc)"),
vrc);
}
/* create a snapshot machine object */
/* create a snapshot object */
/* initialize the snapshot */
/* memorize the first snapshot if necessary */
if (!mData->mFirstSnapshot)
/* memorize the current snapshot when appropriate */
if ( !mData->mCurrentSnapshot
)
// now create the children
++it)
{
// recurse
pSnapshot); // parent = the one we created above
}
return rc;
}
/**
* Loads settings into mHWData.
*
* @param data Reference to the hardware settings.
* @param pDbg Pointer to the debugging settings.
* @param pAutostart Pointer to the autostart settings.
*/
{
try
{
/* The hardware version attribute (optional). */
// cpu
if (mHWData->mCPUHotPlugEnabled)
{
++it)
{
}
}
// cpuid leafs
++it)
{
{
case 0x0:
case 0x1:
case 0x2:
case 0x3:
case 0x4:
case 0x5:
case 0x6:
case 0x7:
case 0x8:
case 0x9:
case 0xA:
break;
case 0x80000000:
case 0x80000001:
case 0x80000002:
case 0x80000003:
case 0x80000004:
case 0x80000005:
case 0x80000006:
case 0x80000007:
case 0x80000008:
case 0x80000009:
case 0x8000000A:
break;
default:
/* just ignore */
break;
}
}
// boot order
{
else
}
AssertCompile(RT_ELEMENTS(mHWData->maVideoCaptureScreens) == sizeof(data.u64VideoCaptureScreens) * 8);
else
/* VRDEServer */
/* BIOS */
// Bandwidth control (must come before network adapters)
/* Shared folders */
++it)
{
}
/* USB device filters */
// network adapters
{
{
}
}
++it)
{
/* slot unicity is guaranteed by XML Schema */
}
// serial ports
++it)
{
}
// parallel ports (optional)
++it)
{
}
/* AudioAdapter */
/* Shared folders */
++it)
{
/* Check for double entries. Not allowed! */
return setError(VBOX_E_OBJECT_IN_USE,
tr("Shared folder named '%s' already exists"),
/* Create the new shared folder. Don't break on error. This will be
* reported when the machine starts. */
false /* fFailOnError */);
}
// Clipboard
// drag'n'drop
// guest settings
// IO settings
// Host PCI devices
++it)
{
pda.createObject();
}
/*
* (The following isn't really real hardware, but it lives in HWData
* for reasons of convenience.)
*/
#ifdef VBOX_WITH_GUEST_PROPS
/* Guest properties (optional) */
++it)
{
}
#endif /* VBOX_WITH_GUEST_PROPS defined */
return rc;
/* default frontend */
}
{
return E_OUTOFMEMORY;
}
return rc;
}
/**
* Called from Machine::loadHardware() to load the debugging settings of the
* machine.
*
* @param pDbg Pointer to the settings.
*/
{
/* no more processing currently required, this will probably change. */
return S_OK;
}
/**
* Called from i_loadMachineDataFromSettings() for the storage controller data, including media.
*
* @param data
* @param puuidRegistry media registry ID to set media to or NULL; see Machine::i_loadMachineDataFromSettings()
* @param puuidSnapshot
* @return
*/
const Guid *puuidRegistry,
const Guid *puuidSnapshot)
{
++it)
{
/* Try to find one with the name first. */
return setError(VBOX_E_OBJECT_IN_USE,
tr("Storage controller named '%s' already exists"),
pCtl.createObject();
/* Set IDE emulation settings (only for AHCI controller). */
{
)
return rc;
}
/* Load the attached devices now. */
}
return S_OK;
}
/**
* Called from i_loadStorageControllers for a controller's devices.
*
* @param aStorageController
* @param data
* @param puuidRegistry media registry ID to set media to or NULL; see Machine::i_loadMachineDataFromSettings()
* @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
* @return
*/
const Guid *puuidRegistry,
const Guid *puuidSnapshot)
{
/* paranoia: detect duplicate attachments */
++it)
{
++it2)
{
continue;
{
tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%s'"),
}
}
}
++it)
{
switch (dev.deviceType)
{
case DeviceType_Floppy:
case DeviceType_DVD:
false /* fRefresh */, medium);
else
false /* fRefresh */,
false /* aSetError */,
medium);
if (rc == VBOX_E_OBJECT_NOT_FOUND)
// This is not an error. The host drive or UUID might have vanished, so just go
// ahead without this removeable medium attachment
break;
case DeviceType_HardDisk:
{
/* find a hard disk by UUID */
{
if (i_isSnapshotMachine())
{
// wrap another error message around the "cannot find hard disk" set by findHardDisk
// so the user knows that the bad disk is in a snapshot somewhere
tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
puuidSnapshot->raw(),
}
else
return rc;
}
{
if (i_isSnapshotMachine())
tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
"of the virtual machine '%s' ('%s')"),
puuidSnapshot->raw(),
tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
}
{
if (i_isSnapshotMachine())
tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
"of the virtual machine '%s' ('%s')"),
puuidSnapshot->raw(),
tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
}
if ( !i_isSnapshotMachine()
)
tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s') "
"because it has %d differencing child hard disks"),
medium))
tr("Hard disk '%s' with UUID {%RTuuid} is already attached to the virtual machine '%s' ('%s')"),
break;
}
default:
tr("Device '%s' with unknown type is attached to the virtual machine '%s' ('%s')"),
}
break;
/* Bandwidth groups are loaded at this point. */
{
tr("Device '%s' with unknown bandwidth group '%s' is attached to the virtual machine '%s' ('%s')"),
pBwGroup->i_reference();
}
false,
/* associate the medium with this machine and snapshot */
{
if (i_isSnapshotMachine())
else
/* If the medium->addBackReference fails it sets an appropriate
* error message, so no need to do any guesswork here. */
if (puuidRegistry)
// caller wants registry ID to be set on all attached media (OVF import case)
}
break;
/* back up mMediaData to let registeredInit() properly rollback on failure
* (= limited accessibility) */
mMediaData.backup();
}
return rc;
}
/**
* Returns the snapshot with the given UUID or fails of no such snapshot exists.
*
* @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)
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)
return setError(VBOX_E_OBJECT_NOT_FOUND,
tr("This machine does not have any snapshots"));
return VBOX_E_OBJECT_NOT_FOUND;
}
if (!aSnapshot)
{
if (aSetError)
return setError(VBOX_E_OBJECT_NOT_FOUND,
return VBOX_E_OBJECT_NOT_FOUND;
}
return S_OK;
}
/**
* Returns a storage controller object with the given name.
*
* @param aName storage controller name to find
* @param aStorageController where to return the found storage controller
* @param aSetError true to set extended error info on failure
*/
bool aSetError /* = false */)
{
++it)
{
{
aStorageController = (*it);
return S_OK;
}
}
if (aSetError)
return setError(VBOX_E_OBJECT_NOT_FOUND,
tr("Could not find a storage controller named '%s'"),
return VBOX_E_OBJECT_NOT_FOUND;
}
/**
* Returns a USB controller object with the given name.
*
* @param aName USB controller name to find
* @param aUSBController where to return the found USB controller
* @param aSetError true to set extended error info on failure
*/
bool aSetError /* = false */)
{
++it)
{
{
aUSBController = (*it);
return S_OK;
}
}
if (aSetError)
return setError(VBOX_E_OBJECT_NOT_FOUND,
tr("Could not find a storage controller named '%s'"),
return VBOX_E_OBJECT_NOT_FOUND;
}
/**
* Returns the number of USB controller instance of the given type.
*
* @param enmType USB controller type.
*/
{
++it)
{
cCtrls++;
}
return cCtrls;
}
{
AutoCaller autoCaller(this);
++it)
{
// should never happen, but deal with NULL pointers in the list.
// getControllerName() needs caller+read lock
{
return autoAttCaller.rc();
}
}
return S_OK;
}
/**
* Helper for #i_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().
*/
{
/// @todo need to handle primary group change, too
/* attempt to rename the settings file if machine name is changed */
&& mUserData.isBackedUp()
)
{
bool dirRenamed = false;
bool fileRenamed = false;
do
{
int vrc = VINF_SUCCESS;
if (group == "/")
if (newGroup == "/")
/* first, rename the directory if it matches the group and machine name */
/** @todo hack, make somehow use of ComposeMachineFilename */
if (mUserData->s.fDirectoryIncludesUUID)
/** @todo hack, make somehow use of ComposeMachineFilename */
if (mUserData->s.fDirectoryIncludesUUID)
&& !RTPathCompare(configDir.substr(configDir.length() - groupPlusName.length(), groupPlusName.length()).c_str(),
groupPlusName.c_str()))
{
/* consistency: use \ if appropriate on the platform */
/* new dir and old dir cannot be equal here because of 'if'
* above and because name != newName */
if (!fSettingsFileIsNew)
{
/* perform real rename only if the machine is not new */
if ( vrc == VERR_FILE_NOT_FOUND
|| vrc == VERR_PATH_NOT_FOUND)
{
/* create the parent directory, then retry renaming */
}
if (RT_FAILURE(vrc))
{
tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
vrc);
break;
}
/* delete subdirectories which are no longer needed */
dir.stripFilename();
{
if (RT_FAILURE(vrc))
break;
dir.stripFilename();
}
dirRenamed = true;
}
}
/* then try to rename the settings file itself */
if (newConfigFile != configFile)
{
/* get the path to old settings file in renamed directory */
if (!fSettingsFileIsNew)
{
/* 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)"),
configFile.c_str(),
vrc);
break;
}
fileRenamed = true;
configFilePrev += "-prev";
newConfigFilePrev += "-prev";
}
}
// update m_strConfigFileFull amd mConfigFile
// compute the relative path too
// store the old and new so that VirtualBox::i_saveSettings() can update
// the media registry
if ( mData->mRegistered
{
*pfNeedsGlobalSaveSettings = true;
}
// in the saved state file path, replace the old directory with the new directory
mSSData->strStateFilePath = newConfigDir.append(mSSData->strStateFilePath.c_str() + configDir.length());
// and do the same thing for the saved state file paths of all the online snapshots
if (mData->mFirstSnapshot)
newConfigDir.c_str());
}
while (0);
{
/* silently try to rename everything back */
if (fileRenamed)
{
}
if (dirRenamed)
}
}
if (fSettingsFileIsNew)
{
/* create a virgin config file */
int vrc = VINF_SUCCESS;
/* ensure the settings directory exists */
{
if (RT_FAILURE(vrc))
{
tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
vrc);
}
}
/* Note: open flags must correlate with RTFileOpen() in lockConfig() */
RTFILE f = NIL_RTFILE;
if (RT_FAILURE(vrc))
tr("Could not create the settings file '%s' (%Rrc)"),
vrc);
RTFileClose(f);
}
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 directly, not through the backup()/commit() mechanism.
* - SaveS_Force: settings will be saved without doing a deep compare of the
* settings structures. This is used when this is called because snapshots
* have changed to avoid the overhead of the deep compare.
*
* @note Must be called from under this object's write lock. Locks children for
* writing.
*
* @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
* initialized to false and that will be set to true by this function if
* the caller must invoke VirtualBox::i_saveSettings() because the global
* settings have changed. This will happen if a machine rename has been
* saved and the global machine and media registries will therefore need
* updating.
*/
int aFlags /*= 0*/)
{
/* make sure child objects are unable to modify the settings while we are
* saving them */
E_FAIL);
bool fNeedsWrite = false;
/* 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. */
// keep a pointer to the current settings structures
try
{
// make a fresh one to have everyone write stuff into
// now go and copy all the settings data from COM to the settings structures
// (this calles i_saveSettings() on all the COM objects in the machine)
{
// this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
fNeedsWrite = true; // always, no need to compare
}
else if (aFlags & SaveS_Force)
{
fNeedsWrite = true; // always, no need to compare
}
else
{
if (!mData->mCurrentStateModified)
{
// do a deep compare of the settings that we just saved with the settings
// previously stored in the config file; this invokes MachineConfigFile::operator==
// which does a deep compare of all the settings, which is expensive but less expensive
// than writing out XML in vain
// could still be modified if any settings changed
}
else
fNeedsWrite = true;
}
if (fNeedsWrite)
// now spit it all out!
delete pOldConfig;
i_commit();
// after saving settings, we are no longer different from the XML on disk
mData->flModifications = 0;
}
{
// we assume that error info is set by the thrower
// restore old config
delete pNewConfig;
}
catch (...)
{
}
{
/* 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 (i_isSessionMachine())
}
return rc;
}
/**
* Implementation for saving the machine settings into the given
* settings::MachineConfigFile instance. This copies machine extradata
* from the previous machine config file in the instance data, if any.
*
* This gets called from two locations:
*
* -- Machine::i_saveSettings(), during the regular XML writing;
*
* -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
* exported to OVF and we write the VirtualBox proprietary XML
* into a <vbox:Machine> tag.
*
* This routine fills all the fields in there, including snapshots, *except*
* for the following:
*
* -- fCurrentStateModified. There is some special logic associated with that.
*
* The caller can then call MachineConfigFile::write() or do something else
* with it.
*
* Caller must hold the machine lock!
*
* This throws XML errors and HRESULT, so the caller must have a catch block!
*/
{
// deep copy extradata
// copy name, description, OS type, teleport, UTC etc.
// Encode the Icon Override data from Machine and store on config userdata.
if (cbData > 0)
{
NULL);
if (RT_FAILURE(vrc))
throw setError(E_FAIL, tr("Failure to Encode Icon Data. '%s' (%Rrc)"), strIconData.mutableRaw(), vrc);
strIconData.jolt();
}
else
// when deleting a snapshot we may or may not have a saved state in the current state,
// so let's not assert here please
)
)
{
/* try to make the file name relative to the settings file dir */
}
else
{
}
if (mData->mCurrentSnapshot)
else
/// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
// save machine's media registry if this is VirtualBox 4.0 or later
if (config.canHaveOwnMediaRegistry())
{
// determine machine folder
i_getId(), // only media with registry ID == machine UUID
// this throws HRESULT
}
// save snapshots
}
/**
* Saves all snapshots of the machine into the given machine config file. Called
* from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
* @param config
* @return
*/
{
try
{
if (mData->mFirstSnapshot)
{
// get reference to the fresh copy of the snapshot on the list and
// work on that copy directly to avoid excessive copying later
}
// if (mType == IsSessionMachine)
// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
}
{
/* we assume that error info is set by the thrower */
}
catch (...)
{
}
return rc;
}
/**
* Saves the VM hardware configuration. It is assumed that the
* given node is empty.
*
* @param data Reference to the settings object for the hardware config.
* @param pDbg Pointer to the settings object for the debugging config
* which happens to live in mHWData.
* @param pAutostart Pointer to the settings object for the autostart config
* which happens to live in mHWData.
*/
{
try
{
/* The hardware version attribute (optional).
Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
)
other point needs to be found where this can be done. */
// CPU
/* Standard and Extended CPUID leafs. */
{
}
{
}
if (data.fCpuHotPlug)
{
{
{
}
}
}
// memory
// firmware
// HID
// chipset
// paravirt
// HPET
// boot order
// display
{
if (mHWData->maVideoCaptureScreens[i])
else
}
/* store relative video capture file if possible */
/* VRDEServer settings (optional) */
/* BIOS (required) */
/* USB Controller (required) */
for (USBControllerList::const_iterator it = mUSBControllers->begin(); it != mUSBControllers->end(); ++it)
{
}
/* USB device filters (required) */
/* Network adapters (required) */
uint32_t uMaxNICs = RT_MIN(Global::getMaxNetworkAdapters(mHWData->mChipsetType), mNetworkAdapters.size());
/* Write out only the nominal number of network adapters for this
* chipset type. Since Machine::commit() hasn't been called there
* may be extra NIC settings in the vector. */
{
/* paranoia check... must not be NULL, but must not crash either. */
if (mNetworkAdapters[slot])
{
}
}
/* Serial ports */
{
settings::SerialPort s;
}
/* Parallel ports */
{
settings::ParallelPort p;
}
/* Audio adapter */
/* Shared folders */
++it)
{
}
// clipboard
// drag'n'drop
/* Guest */
// IO settings
/* BandwidthControl (required) */
/* Host PCI devices */
++it)
{
}
// guest properties
#ifdef VBOX_WITH_GUEST_PROPS
++it)
{
/* Remove transient guest properties at shutdown unless we
* are saving state */
continue;
}
/* I presume this doesn't require a backup(). */
#endif /* VBOX_WITH_GUEST_PROPS defined */
}
{
return E_OUTOFMEMORY;
}
return rc;
}
/**
* Saves the storage controller configuration.
*
* @param aNode <StorageControllers> node to save the VM hardware configuration to.
*/
{
++it)
{
/* Save the port count. */
/* Save fUseHostIOCache */
/* Save IDE emulation settings. */
{
)
}
/* save the devices now. */
}
return S_OK;
}
/**
* Saves the hard disk configuration.
*/
{
++it)
{
if (pMedium)
{
if (pMedium->i_isHostDrive())
else
}
}
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) */
try
{
if (aFlags & SaveSTS_CurStateModified)
if (aFlags & SaveSTS_StateFilePath)
{
/* try to make the file name relative to the settings file dir */
else
}
if (aFlags & SaveSTS_StateTimeStamp)
{
//@todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
}
}
catch (...)
{
}
return rc;
}
/**
* Ensures that the given medium is added to a media registry. If this machine
* was created with 4.0 or later, then the machine registry is used. Otherwise
* the global VirtualBox media registry is used.
*
* Caller must NOT hold machine lock, media tree or any medium locks!
*
* @param pMedium
*/
{
/* Paranoia checks: do not hold machine or media tree locks. */
{
}
/* Paranoia checks: do not hold medium locks. */
// decide which medium registry to use now that the medium is attached:
// machine XML is VirtualBox 4.0 or higher:
else
/* For more complex hard disk structures it can happen that the base
* medium isn't yet associated with any medium registry. Do that now. */
{
}
}
/**
* 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 deleting the current state. Gets called
* from SessionMachine::BeginTakingSnapshot() and SessionMachine::restoreSnapshotHandler().
*
* This method assumes that mMediaData 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 mMediaData 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 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 and the media tree for writing.
*/
bool aOnline)
{
AutoCaller autoCaller(this);
/* must be in a protective state because we release the lock below */
, E_FAIL);
// use appropriate locked media map (online or offline)
if (aOnline)
else
try
{
if (!aOnline)
{
/* lock all attached hard disks early to detect "in use"
* situations before creating actual diffs */
++it)
{
{
false /* fMediumLockWrite */,
NULL,
{
delete pMediumLockList;
throw rc;
}
{
tr("Collecting locking information for all attached media failed"));
}
}
}
/* Now lock all media. If this fails, nothing is locked. */
{
tr("Locking of attached media failed"));
}
}
/* remember the current list (note that we don't use backup() since
* mMediaData may be already backed up) */
/* start from scratch */
/* go through remembered attachments and create diffs for normal hard
* disks and attach them */
++it)
{
if ( devType != DeviceType_HardDisk
{
/* copy the attachment as is */
/** @todo the progress object created in Console::TakeSnaphot
* only expects operations for hard disks. Later other
* device types need to show up in the progress as well. */
if (devType == DeviceType_HardDisk)
{
aWeight); // weight
else
aWeight); // weight
}
continue;
}
/* need a diff */
aWeight); // weight
diff.createObject();
// store the diff in the same registry as the parent
// (this cannot fail here because we can't create implicit diffs for
// unregistered images)
/** @todo r=bird: How is the locking and diff image cleaned up if we fail before
* the push_back? Looks like we're going to release medium with the
* wrong kind of lock (general issue with if we fail anywhere at all)
* and an orphaned VDI in the snapshots folder. */
/* update the appropriate lock list */
if (aOnline)
{
/* The currently attached medium will be read-only, change
* the lock type to read. */
}
/* release the locks before the potentially lengthy operation */
NULL /* aProgress */,
true /* aWait */);
/* actual lock list update is done in Medium::commitMedia */
/* add a new attachment */
diff,
pAtt->i_getDevice(),
true /* aImplicit */,
false /* aPassthrough */,
false /* aTempEject */,
pAtt->i_getDiscard(),
pAtt->i_getBandwidthGroup());
}
}
/* unlock all hard disks we locked when there is no VM */
if (!aOnline)
{
}
return rc;
}
/**
* Deletes implicit differencing hard disks created either by
* #createImplicitDiffs() or by #AttachDevice() and rolls back mMediaData.
*
* Note that to delete hard disks created by #AttachDevice() this method is
* called from #fixupMedia() when the changes are rolled back.
*
* @note Locks this object and the media tree for writing.
*/
{
AutoCaller autoCaller(this);
/* We absolutely must have backed up state. */
/* Check if there are any implicitly created diff images. */
bool fImplicitDiffs = false;
++it)
{
if (pAtt->i_isImplicit())
{
fImplicitDiffs = true;
break;
}
}
/* If there is nothing to do, leave early. This saves lots of image locking
* effort. It also avoids a MachineStateChanged event without real reason.
* This is important e.g. when loading a VM config, because there should be
* no events. Otherwise API clients can become thoroughly confused for
* inaccessible VMs (the code for loading VM configs uses this method for
* cleanup if the config makes no sense), as they take such events as an
* indication that the VM is alive, and they would force the VM config to
* be reread, leading to an endless loop. */
if (!fImplicitDiffs)
return S_OK;
/* will release the lock before the potentially lengthy operation,
* so protect with the special state (unless already protected) */
if ( oldState != MachineState_Saving
)
// use appropriate locked media map (online or offline)
if (aOnline)
else
try
{
if (!aOnline)
{
/* lock all attached hard disks early to detect "in use"
* situations before deleting actual diffs */
++it)
{
{
false /* fMediumLockWrite */,
NULL,
{
delete pMediumLockList;
throw rc;
}
throw rc;
}
}
throw rc;
} // end of offline
/* Lock lists are now up to date and include implicitly created media */
/* Go through remembered attachments and delete all implicitly created
* diffs and fix up the attachment information */
++it)
{
continue;
// Implicit attachments go on the list for deletion and back references are removed.
if (pAtt->i_isImplicit())
{
/* Deassociate and mark for deletion */
throw rc;
continue;
}
/* Was this medium attached before? */
{
/* no: de-associate */
throw rc;
continue;
}
}
/* If there are implicit attachments to delete, throw away the lock
* map contents (which will unlock all media) since the medium
* attachments will be rolled back. Below we need to completely
* recreate the lock map anyway since it is infinitely complex to
* do this incrementally (would need reconstructing each attachment
* change, which would be extremely hairy). */
if (implicitAtts.size() != 0)
{
}
/* rollback hard disk changes */
// Delete unused implicit diffs.
if (implicitAtts.size() != 0)
{
for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin(); it != implicitAtts.end(); ++it)
{
// Remove medium associated with this attachment.
// continue on delete failure, just collect error messages
}
/* if there is a VM recreate media lock map as mentioned above,
* otherwise it is a waste of time and we leave things unlocked */
if (aOnline)
{
/* must never be NULL, but better safe than sorry */
{
throw rc;
}
}
}
}
/* unlock all hard disks we locked when there is no VM */
if (!aOnline)
{
}
return rc;
}
/**
* Looks through the given list of media attachments for one with the given parameters
* and returns it, or NULL if not found. The list is a parameter so that backup lists
* can be searched as well if needed.
*
* @param list
* @param aControllerName
* @param aControllerPort
* @param aDevice
* @return
*/
{
{
return pAttach;
}
return NULL;
}
/**
* Looks through the given list of media attachments for one with the given parameters
* and returns it, or NULL if not found. The list is a parameter so that backup lists
* can be searched as well if needed.
*
* @param list
* @param aControllerName
* @param aControllerPort
* @param aDevice
* @return
*/
{
{
if (pMediumThis == pMedium)
return pAttach;
}
return NULL;
}
/**
* Looks through the given list of media attachments for one with the given parameters
* and returns it, or NULL if not found. The list is a parameter so that backup lists
* can be searched as well if needed.
*
* @param list
* @param aControllerName
* @param aControllerPort
* @param aDevice
* @return
*/
{
{
return pAttach;
}
return NULL;
}
/**
* Main implementation for Machine::DetachDevice. This also gets called
* from Machine::prepareUnregister() so it has been taken out for simplicity.
*
* @param pAttach Medium attachment to detach.
* @param writeLock Machine write lock which the caller must have locked once. This may be released temporarily in here.
* @param pSnapshot If NULL, then the detachment is for the current machine. Otherwise this is for a
* SnapshotMachine, and this must be its snapshot.
* @return
*/
{
LogFlowThisFunc(("Entering, medium of attachment is %s\n", oldmedium ? oldmedium->i_getLocationFull().c_str() : "NULL"));
if (pAttach->i_isImplicit())
{
/* attempt to implicitly delete the implicitly created diff */
/// @todo move the implicit flag from MediumAttachment to Medium
/// 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 release the lock before the potentially lengthy operation, so
* protect with the special state */
true /*aWait*/);
}
mMediaData.backup();
{
// if this is from a snapshot, do not defer detachment to commitMedia()
if (pSnapshot)
// else if non-hard disk media, do not defer detachment to commitMedia() either
else if (mediumType != DeviceType_HardDisk)
}
return S_OK;
}
/**
* Goes thru all media of the given list and
*
* 1) calls i_detachDevice() on each of them for this machine and
* 2) adds all Medium objects found in the process to the given list,
* depending on cleanupMode.
*
* If cleanupMode is CleanupMode_DetachAllReturnHardDisksOnly, this only
* adds hard disks to the list. If it is CleanupMode_Full, this adds all
* media to the list.
*
* This gets called from Machine::Unregister, both for the actual Machine and
* the SnapshotMachine objects that might be found in the snapshots.
*
* Requires caller and locking. The machine lock must be passed in because it
* will be passed on to i_detachDevice which needs it for temporary unlocking.
*
* @param writeLock Machine lock from top-level caller; this gets passed to i_detachDevice.
* @param pSnapshot Must be NULL when called for a "real" Machine or a snapshot object if called for a SnapshotMachine.
* @param cleanupMode If DetachAllReturnHardDisksOnly, only hard disk media get added to llMedia; if
* Full, then all media get added;
* otherwise no media get added.
* @param llMedia Caller's list to receive Medium objects which got detached so caller can close() them, depending on cleanupMode.
* @return
*/
{
// make a temporary list because i_detachDevice invalidates iterators into
// mMediaData->mAttachments
for (MediaData::AttachmentList::iterator it = llAttachments2.begin(); it != llAttachments2.end(); ++it)
{
{
&& devType == DeviceType_HardDisk)
|| (cleanupMode == CleanupMode_Full)
)
{
/*
* Search for medias which are not attached to any machine, but
* in the chain to an attached disk. Mediums are only consided
* if they are:
* - have only one child
* - no references to any machines
* - are of normal medium type
*/
{
{
if ( pParent->i_getMachineBackRefCount() == 0
}
else
break;
}
}
}
// real machine: then we need to use the proper method
return rc;
}
return S_OK;
}
/**
* Perform deferred hard disk detachments.
*
* Does nothing if the hard disk attachment data (mMediaData) is not changed (not
* backed up).
*
* If @a aOnline is @c true then this method will also unlock the old hard disks
* for which the new implicit diffs were created and will lock these new diffs for
* writing.
*
* @param aOnline Whether the VM was online prior to this operation.
*
* @note Locks this object for writing!
*/
{
AutoCaller autoCaller(this);
if (!mMediaData.isBackedUp())
return;
bool fMediaNeedsLocking = false;
/* enumerate new attachments */
++it)
{
LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
fImplicit));
/** @todo convert all this Machine-based voodoo to MediumAttachment
* based commit logic. */
if (fImplicit)
{
/* convert implicit attachment to normal */
pAttach->i_setImplicit(false);
if ( aOnline
&& pMedium
)
{
/* update the appropriate lock list */
if (pMediumLockList)
{
/* unlock if there's a need to change the locking */
if (!fMediaNeedsLocking)
{
fMediaNeedsLocking = true;
}
}
}
continue;
}
if (pMedium)
{
/* was this medium attached before? */
{
{
LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->i_getName().c_str()));
/* yes: remove from old to avoid de-association */
break;
}
}
}
}
/* enumerate remaining old attachments and de-associate from the
* current machine state */
{
* instantly in MountMedium. */
{
/* now de-associate from the current machine state */
if (aOnline)
{
/* unlock since medium is not used anymore */
{
/* this happens for online snapshots, there the attachment
* is changing, but only to a diff image created under
* the old one, so there is no separate lock list */
}
else
{
if (pMediumLockList)
{
}
}
}
}
}
/* take media locks again so that the locking state is consistent */
if (fMediaNeedsLocking)
{
}
/* commit the hard disk changes */
mMediaData.commit();
if (i_isSessionMachine())
{
/*
* Update the parent machine to point to the new owner.
* This is necessary because the stored parent will point to the
* session machine otherwise and cause crashes or errors later
* when the session machine gets invalid.
*/
/** @todo Change the MediumAttachment class to behave like any other
* class in this regard by creating peer MediumAttachment
* objects for session machines and share the data with the peer
* machine.
*/
++it)
/* attach new data to the primary machine and reshare it */
}
return;
}
/**
* Perform deferred deletion of implicitly created diffs.
*
* Does nothing if the hard disk attachment data (mMediaData) is not changed (not
* backed up).
*
* @note Locks this object for writing!
*/
void Machine::i_rollbackMedia()
{
AutoCaller autoCaller(this);
// AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
LogFlowThisFunc(("Entering rollbackMedia\n"));
if (!mMediaData.isBackedUp())
return;
/* enumerate new attachments */
++it)
{
{
if (pMedium)
{
}
}
(*it)->i_rollback();
{
if (pMedium)
{
}
}
}
/** @todo convert all this Machine-based voodoo to MediumAttachment
* based rollback logic. */
return;
}
/**
* Returns true if the settings file is located in the directory named exactly
* as the machine; this means, among other things, that the machine directory
* should be auto-renamed.
*
* @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).
*/
{
if (aSettingsDir)
.stripSuffix(); // vmname
/** @todo hack, make somehow use of ComposeMachineFilename */
if (mUserData->s.fDirectoryIncludesUUID)
return strMachineDirName == strConfigFileOnly;
}
/**
* Discards all changes to machine settings.
*
* @param aNotify Whether to notify the direct session about changes or not.
*
* @note Locks objects for writing!
*/
{
AutoCaller autoCaller(this);
if (!mStorageControllers.isNull())
{
if (mStorageControllers.isBackedUp())
{
/* unitialize all new devices (absent in the backed up list). */
{
== backedList->end()
)
{
}
++it;
}
/* restore the list */
}
/* rollback any changes to devices after restoring the list */
{
{
(*it)->i_rollback();
++it;
}
}
}
if (!mUSBControllers.isNull())
{
if (mUSBControllers.isBackedUp())
{
/* unitialize all new devices (absent in the backed up list). */
{
== backedList->end()
)
{
}
++it;
}
/* restore the list */
}
/* rollback any changes to devices after restoring the list */
{
{
(*it)->i_rollback();
++it;
}
}
}
if (mBIOSSettings)
if (mAudioAdapter)
if ( mNetworkAdapters[slot]
{
}
if ( mSerialPorts[slot]
{
}
if ( mParallelPorts[slot]
{
}
if (aNotify)
{
/* inform the direct session about changes */
if (flModifications & IsModified_USB)
if (networkAdapters[slot])
if (serialPorts[slot])
if (parallelPorts[slot])
#if 0
#endif
}
}
/**
* 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);
/*
* use safe commit to ensure Snapshot machines (that share mUserData)
* will still refer to a valid memory location
*/
if (mMediaData.isBackedUp())
mVRDEServer->i_commit();
/* Since mNetworkAdapters is a list which might have been changed (resized)
* without using the Backupable<> template we need to handle the copying
* of the list entries manually, including the creation of peers for the
* new objects. */
bool commitNetworkAdapters = false;
if (mPeer)
{
/* commit everything, even the ones which will go away */
/* copy over the new entries, creating a peer and uninit the original */
{
/* look if this adapter has a peer device */
if (!peer)
{
/* no peer means the adapter is a newly created one;
* create a peer owning data this data share it with */
peer.createObject();
}
}
/* uninit any no longer needed network adapters */
{
}
/* Keep the original network adapter count until this point, so that
* discarding a chipset type change will not lose settings. */
}
else
{
/* we have no peer (our parent is the newly created machine);
* just commit changes to the network adapters */
commitNetworkAdapters = true;
}
bool commitStorageControllers = false;
if (mStorageControllers.isBackedUp())
{
if (mPeer)
{
/* Commit all changes to new controllers (this will reshare data with
* peers for those who have peers) */
{
/* look if this controller has a peer device */
if (!peer)
{
/* no peer means the device is a newly created one;
* create a peer owning data this device share it with */
peer.createObject();
}
else
{
/* remove peer from the old list */
}
/* and add it to the new list */
++it;
}
/* uninit old peer's controllers that are left */
{
++it;
}
/* attach new list of controllers to our peer */
}
else
{
/* we have no peer (our parent is the newly created machine);
* just commit changes to devices */
commitStorageControllers = true;
}
}
else
{
/* the list of controllers itself is not changed,
* just commit changes to controllers themselves */
commitStorageControllers = true;
}
{
{
++it;
}
}
bool commitUSBControllers = false;
if (mUSBControllers.isBackedUp())
{
if (mPeer)
{
/* Commit all changes to new controllers (this will reshare data with
* peers for those who have peers) */
{
/* look if this controller has a peer device */
if (!peer)
{
/* no peer means the device is a newly created one;
* create a peer owning data this device share it with */
peer.createObject();
}
else
{
/* remove peer from the old list */
}
/* and add it to the new list */
++it;
}
/* uninit old peer's controllers that are left */
{
++it;
}
/* attach new list of controllers to our peer */
}
else
{
/* we have no peer (our parent is the newly created machine);
* just commit changes to devices */
commitUSBControllers = true;
}
}
else
{
/* the list of controllers itself is not changed,
* just commit changes to controllers themselves */
commitUSBControllers = true;
}
if (commitUSBControllers)
{
{
++it;
}
}
if (i_isSessionMachine())
{
/* attach new data to the primary machine and reshare it */
/* mMediaData is reshared by fixupMedia */
// mPeer->mMediaData.attach(mMediaData);
}
}
/**
* Copies all the hardware data from the given machine.
*
* Currently, only called when the VM is being restored from a snapshot. In
* particular, this implies that the VM is not running during this method's
* call.
*
* @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 attaching a copy
// contains just references to original objects)
++it)
{
}
/* create private copies of all controllers */
++it)
{
ctrl.createObject();
}
/* create private copies of all USB controllers */
mUSBControllers->clear();
++it)
{
ctrl.createObject();
}
}
/**
* Returns whether the given storage controller is hotplug capable.
*
* @returns true if the controller supports hotplugging
* false otherwise.
* @param enmCtrlType The controller type to check for.
*/
{
return false;
return RT_BOOL(aHotplugCapable);
}
#ifdef VBOX_WITH_RESOURCE_USAGE_API
{
++it)
{
/* just in case */
AssertStmt(pAttach, continue);
}
}
{
/* Create sub metrics */
"Percentage of processor time spent in user mode by the VM process.");
"Percentage of processor time spent in kernel mode by the VM process.");
"Size of resident portion of VM process in memory.");
"Actual size of all VM disks combined.");
"Network receive rate.");
"Network transmit rate.");
/* 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()));
new pm::AggregateAvg()));
new pm::AggregateMin()));
new pm::AggregateMax()));
/* Guest metrics collector */
this, __PRETTY_FUNCTION__, mCollectorGuest));
/* Create sub metrics */
"Percentage of processor time spent in user mode as seen by the guest.");
"Percentage of processor time spent in kernel mode as seen by the guest.");
"Percentage of processor time spent idling as seen by the guest.");
/* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
/* Create and register base metrics */
}
{
if (aCollector)
{
}
}
#endif /* VBOX_WITH_RESOURCE_USAGE_API */
////////////////////////////////////////////////////////////////////////////////
{
LogFlowThisFunc(("\n"));
mClientToken = NULL;
return BaseFinalConstruct();
}
void SessionMachine::FinalRelease()
{
LogFlowThisFunc(("\n"));
/* paranoia, should not hang around any more */
if (mClientToken)
{
delete mClientToken;
mClientToken = NULL;
}
}
/**
* @note Must be called only by Machine::LockMachine() from its own write lock.
*/
{
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan(this);
/* create the machine client token */
try
{
if (!mClientToken->isReady())
{
delete mClientToken;
mClientToken = NULL;
}
}
{
rc = E_OUTOFMEMORY;
}
return rc;
/* memorize the peer Machine */
/* share the parent pointer */
/* take the pointers to data to share */
++it)
{
ctl.createObject();
}
++it)
{
ctl.createObject();
}
/* create another VRDEServer 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 device filters object that will be mutable */
/* create a list of network adapters that will be mutable */
{
}
/* create another bandwidth control object that will be mutable */
/* default is to delete saved state on Saved -> PoweredOff transition */
mRemoveSavedState = true;
/* Confirm a successful initialization when it's the case */
miNATNetworksStarted = 0;
return rc;
}
/**
* Uninitializes this session object. If the reason is other than
* Uninit::Unexpected, then this method MUST be called from #checkForDeath()
* or the client watcher code.
*
* @param aReason uninitialization reason
*
* @note Locks mParent + this object for writing.
*/
{
/*
* Strongly reference ourselves to prevent this object deletion after
* mData->mSession.mMachine.setNull() below (which can release the last
* reference and call the destructor). Important: this must be done before
* accessing any members (and before AutoUninitSpan that does it as well).
* This self reference will be released as the very last step on return.
*/
/* Enclose the state transition Ready->InUninit->NotReady */
AutoUninitSpan autoUninitSpan(this);
if (autoUninitSpan.uninitDone())
{
LogFlowThisFunc(("Already uninitialized\n"));
return;
}
if (autoUninitSpan.initFailed())
{
/* We've been called by init() because it's failed. It's not really
* necessary (nor it's safe) to perform the regular uninit sequence
* below, the following is enough.
*/
LogFlowThisFunc(("Initialization failed.\n"));
/* destroy the machine client token */
if (mClientToken)
{
delete mClientToken;
mClientToken = NULL;
}
return;
}
{
}
#ifdef VBOX_WITH_USB
// release all captured USB devices, but do this before requesting the locks below
{
/* 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. */
if (service)
}
#endif /* VBOX_WITH_USB */
// we need to lock this object in uninit() because the lock is shared
// with mPeer (as well as data we modify below). mParent lock is needed
// by several calls to it, and USB needs host lock.
#ifdef VBOX_WITH_RESOURCE_USAGE_API
/*
* It is safe to call Machine::i_unregisterMetrics() here because
* PerformanceCollector::samplerCallback no longer accesses guest methods
* holding the lock.
*/
/* The guest must be unregistered after its metrics (@bugref{5949}). */
this, __PRETTY_FUNCTION__, mCollectorGuest));
if (mCollectorGuest)
{
// delete mCollectorGuest; => CollectorGuestManager::destroyUnregistered()
}
#endif
{
LogWarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n",
/* reset the state to Aborted */
}
// any machine settings modified?
if (mData->flModifications)
{
LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
i_rollback(false /* aNotify */);
}
|| !mConsoleTaskData.mSnapshot);
{
LogWarningThisFunc(("canceling failed save state request!\n"));
}
{
LogWarningThisFunc(("canceling untaken snapshot!\n"));
/* delete all differencing hard disks created (this will also attach
* their parents back by rolling back mMediaData) */
// delete the saved state file (it might have been already created)
// AFTER killing the snapshot so that releaseSavedStateFile() won't
// think it's still in use
}
{
/* 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;
}
}
/* Remove all references to the NAT network service. The service will stop
* if all references (also from other VMs) are removed. */
for (; miNATNetworksStarted > 0; miNATNetworksStarted--)
{
{
{
{
LogRel(("VM '%s' stops using NAT network '%ls'\n",
}
}
}
}
/*
* An expected uninitialization can come only from #checkForDeath().
* Otherwise it means that something's gone really wrong (for example,
* 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()) */
}
{
else
tr("The VM session was aborted"));
}
/* remove the association between the peer machine and this session machine */
/* reset the rest of session data */
/* destroy the machine client token before leaving the exclusive lock */
if (mClientToken)
{
delete mClientToken;
mClientToken = NULL;
}
/* fire an event */
/* free the essential data structure last */
/* release the exclusive 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
////////////////////////////////////////////////////////////////////////////////
/**
* Passes collected guest statistics to performance collector object
*/
{
#ifdef VBOX_WITH_RESOURCE_USAGE_API
if (mCollectorGuest)
return S_OK;
#else
return E_NOTIMPL;
#endif
}
/**
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller(this);
return S_OK;
}
/**
* @note Locks the same as #i_setMachineState() does.
*/
{
return i_setMachineState(aMachineState);
}
/**
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller(this);
return VBOX_E_INVALID_OBJECT_STATE;
/* If we didn't reference the NAT network service yet, add a reference to
* force a start */
if (miNATNetworksStarted < 1)
{
{
{
{
LogRel(("VM '%s' starts using NAT network '%ls'\n",
#ifdef RT_LOCK_STRICT
#else
#endif
}
}
}
}
LogFlowThisFunc(("returns S_OK.\n"));
return S_OK;
}
/**
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller(this);
return VBOX_E_INVALID_OBJECT_STATE;
/* Finalize the LaunchVMProcess progress object. */
{
}
{
#ifdef VBOX_WITH_RESOURCE_USAGE_API
/* The VM has been powered up successfully, so it makes sense
* now to offer the performance metrics for a running machine
* object. Doing it earlier wouldn't be safe. */
#endif /* VBOX_WITH_RESOURCE_USAGE_API */
}
return S_OK;
}
/**
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller(this);
E_FAIL);
/* create a progress object to track operation completion */
static_cast<IMachine *>(this) /* aInitiator */,
FALSE /* aCancelable */);
/* fill in the console task data */
/* set the state to Stopping (this is expected by Console::PowerDown()) */
return S_OK;
}
/**
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller(this);
E_FAIL);
/*
* On failure, set the state to the state we had when BeginPoweringDown()
* was called (this is expected by Console::PowerDown() and the associated
* task). On success the VM process already changed the state to
* MachineState_PoweredOff, so no need to do anything.
*/
/* notify the progress object about operation completion */
else
{
else
}
/* clear out the temporary saved state data */
return S_OK;
}
/**
* Goes through the USB filters of the given machine to see if the given
* device matches any filter or not.
*
* @note Locks the same as USBController::hasMatchingFilter() does.
*/
{
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 */
clearError();
#else
return E_NOTIMPL;
#endif
}
/**
* @note Locks the same as Host::detachUSBDevice() does.
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
#ifdef VBOX_WITH_USB
#else
return E_NOTIMPL;
#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
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
#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 */
/* Creating a Progress object requires the VirtualBox lock, and
* thus locking it here is required by the lock order rules. */
{
/* 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"));
{
/* finalize the progress, someone might wait if a frontend
* closes the session before powering on the VM. */
tr("The VM session was closed before any attempt to power it on"));
}
/* 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.
* Note! Because we're "reusing" mProgress here, this must be a proxy
* object just like for LaunchVMProcess. */
FALSE /* aCancelable */);
}
else
{
/* the remote session is being normally closed */
{
break;
++it;
}
// This MUST be erase(it), not remove(*it) as the latter triggers a
// very nasty use after free due to the place where the value "lives".
}
/* signal the client watcher thread, because the client is going away */
return S_OK;
}
/**
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller(this);
E_FAIL);
/* create a progress object to track operation completion */
static_cast<IMachine *>(this) /* aInitiator */,
FALSE /* aCancelable */);
/* stateFilePath is null when the machine is not running */
/* fill in the console task 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 failure, set the state to the state we had when BeginSavingState()
* was called (this is expected by Console::SaveState() and the associated
* task). On success the VM process already changed the state to
* MachineState_Saved, so no need to do anything.
*/
}
/**
* @note Locks this object for writing.
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
, E_FAIL); /** @todo setError. */
if (RT_FAILURE(vrc))
return setError(VBOX_E_FILE_ERROR,
tr("Invalid saved state file path '%ls' (%Rrc)"),
vrc);
/* The below i_setMachineState() will detect the state transition and will
* update the settings file */
return i_setMachineState(MachineState_Saved);
}
{
LogFlowThisFunc(("\n"));
#ifdef VBOX_WITH_GUEST_PROPS
using namespace guestProp;
AutoCaller autoCaller(this);
unsigned i = 0;
++it)
{
/* If it is NULL, keep it NULL. */
{
}
else
++i;
}
return S_OK;
#else
#endif
}
{
LogFlowThisFunc(("\n"));
#ifdef VBOX_WITH_GUEST_PROPS
using namespace guestProp;
try
{
/*
* Convert input up front.
*/
if (aFlags)
{
}
/*
* Now grab the object lock, validate the state and do the update.
*/
AutoCaller autoCaller(this);
switch (mData->mMachineState)
{
case MachineState_Paused:
case MachineState_Running:
case MachineState_Teleporting:
case MachineState_Saving:
case MachineState_Stopping:
break;
default:
}
{
if (!fDelete)
{
}
else
}
else if (!fDelete)
{
}
/*
* Send a callback notification if appropriate
*/
)
{
aFlags);
}
}
catch (...)
{
}
return S_OK;
#else
#endif
}
{
AutoCaller autoCaller(this);
clearError();
return lockMedia();
}
{
return hrc;
}
{
AutoCaller autoCaller(this);
// request the host lock first, since might be calling Host methods for getting host drives;
// next, protect the media tree all the while we're in here, as well as our member variables
this->lockHandle(),
bool fTempEject;
{
AutoCaller autoAttachCaller(this);
/* Need to query the details first, as the IMediumAttachment reference
* might be to the original settings, which we are going to change. */
}
if (!fTempEject)
{
/* Remember previously mounted medium. The medium before taking the
* backup is not necessarily the same thing. */
mMediaData.backup();
// The backup operation makes the pAttach reference point to the
// old settings. Re-get the correct reference.
lDevice);
{
AutoCaller autoAttachCaller(this);
}
}
else
{
{
}
}
return S_OK;
}
// 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::i_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!\n"));
return true;
}
/* Determine the reason of death: if the session state is Closing here,
* everything is fine. Otherwise it means that the client did not call
* OnSessionEnd() before it released the IPC semaphore. This may happen
* either because the client process has abnormally terminated, or
* because it simply forgot to call ISession::Close() before exiting. We
* threat the latter also as an abnormal termination (see
* Session::uninit() for details). */
if (mClientToken)
} /* AutoCaller block */
if (terminated)
return terminated;
}
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
if (mClientToken)
}
#else /* VBOX_WITH_GENERIC_SESSION_WATCHER */
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
if (mClientToken)
return mClientToken->getToken();
else
return NULL;
}
#endif /* VBOX_WITH_GENERIC_SESSION_WATCHER */
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
return mClientToken;
}
/**
* @note Locks this object for reading.
*/
HRESULT SessionMachine::i_onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
{
}
/* ignore notifications sent after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
}
/**
* @note Locks this object for reading.
*/
HRESULT SessionMachine::i_onNATRedirectRuleChange(ULONG ulSlot, BOOL aNatRuleRemove, IN_BSTR aRuleName,
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
{
}
/* ignore notifications sent after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
/*
* instead acting like callback we ask IVirtualBox deliver corresponding event
*/
mParent->i_onNatRedirectChange(i_getId(), ulSlot, RT_BOOL(aNatRuleRemove), aRuleName, aProto, aHostIp,
return S_OK;
}
/**
* @note Locks this object for reading.
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
{
}
/* ignore notifications sent after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
}
/**
* @note Locks this object for reading.
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
{
}
/* ignore notifications sent after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
}
/**
* @note Locks this object for reading.
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
{
}
/* ignore notifications sent after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
return directControl->OnStorageControllerChange();
}
/**
* @note Locks this object for reading.
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
{
}
/* ignore notifications sent after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
}
/**
* @note Locks this object for reading.
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
{
}
/* ignore notifications sent after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
}
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
{
}
/* ignore notifications sent after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
}
/**
* @note Locks this object for reading.
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
{
}
/* ignore notifications sent after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
}
/**
* @note Locks this object for reading.
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
{
}
/* ignore notifications sent after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
return directControl->OnVideoCaptureChange();
}
/**
* @note Locks this object for reading.
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(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);
{
}
/* ignore notifications sent after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
}
/**
* @note Locks this object for reading.
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
{
}
/* ignore notifications sent after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
}
/**
* @note Locks this object for reading.
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
{
}
/* ignore notifications sent after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
}
/**
* @note Locks this object for reading.
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
{
}
/* ignore notifications sent after #OnSessionEnd() is called */
if (!directControl)
return S_OK;
}
/**
* @note Locks this object for reading.
*/
HRESULT SessionMachine::i_onStorageDeviceChange(IMediumAttachment *aAttachment, BOOL aRemove, BOOL aSilent)
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(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::i_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;
#ifdef VBOX_WITH_USB
switch (mData->mMachineState)
{
case MachineState_Starting:
case MachineState_Restoring:
case MachineState_Paused:
case MachineState_Running:
/** @todo Live Migration: snapshoting & teleporting. Need to fend things of
* elsewhere... */
default: break;
}
#else
#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. */
{
}
/* 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(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(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. */
{
}
/* 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(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
}
// protected methods
/////////////////////////////////////////////////////////////////////////////
/**
* Helper method to finalize saving the state.
*
* @note Must be called from under this object's lock.
*
* @param aRc S_OK if the snapshot has been taken successfully
* @param aErrMsg human readable error message for failure
*
* @note Locks mParent + this objects for writing.
*/
{
AutoCaller autoCaller(this);
{
/* save all VM settings */
// no need to check whether VirtualBox.xml needs saving also since
// we can't have a name change pending at this point
}
else
{
// delete the saved state file (it might have been already created);
// we need not check whether this is shared with a snapshot here because
// we certainly created this saved state file here anew
}
/* notify the progress object about operation completion */
else
{
else
}
/* clear out the temporary saved state data */
return rc;
}
/**
* Deletes the given file if it is no longer in use by either the current machine state
* (if the machine is "saved") or any of the machine's snapshots.
*
* Note: This checks mSSData->strStateFilePath, which is shared by the Machine and SessionMachine
* but is different for each SnapshotMachine. When calling this, the order of calling this
* function on the one hand and changing that variable OR the snapshots tree on the other hand
* is therefore critical. I know, it's all rather messy.
*
* @param strStateFile
* @param pSnapshotToIgnore Passed to Snapshot::sharesSavedStateFile(); this snapshot is ignored in
* the test for whether the saved state file is in use.
*/
{
// it is safe to delete this saved state file if it is not currently in use by the machine ...
if ( (strStateFile.isNotEmpty())
)
// ... and it must also not be shared with other snapshots
if ( !mData->mFirstSnapshot
// this checks the SnapshotMachine's state file paths
)
}
/**
* Locks the attached media.
*
* reading. Parents of attached hard disks (if any) are locked for reading.
*
* This method also performs accessibility check of all media it locks: if some
* media is inaccessible, the method will return a failure and a bunch of
* extended error info objects per each inaccessible medium.
*
* Note that this method is atomic: if it returns a success, all media are
* locked as described above; on failure no media is locked at all (all
* succeeded individual locks will be undone).
*
* The caller is responsible for doing the necessary state sanity checks.
*
* The locks made by this method must be undone by calling #unlockMedia() when
* no more needed.
*/
{
AutoCaller autoCaller(this);
/* bail out if trying to lock things with already set up locking */
/* Collect locking information for all medium objects attached to the VM. */
++it)
{
// it's impossible to create a medium lock list. It still makes sense
// to have the empty medium lock list in the map in case a medium is
// attached later.
{
|| mediumType == MediumType_Shareable;
!fIsReadOnlyLock /* fMediumLockWrite */,
NULL,
{
delete pMediumLockList;
break;
}
}
{
tr("Collecting locking information for all attached media failed"));
break;
}
}
{
/* Now lock all media. If this fails, nothing is locked. */
{
tr("Locking of attached media failed"));
}
}
return mrc;
}
/**
* Undoes the locks made by by #lockMedia().
*/
{
AutoCaller autoCaller(this);
/* we may be holding important error info on the current thread;
* preserve it */
return rc;
}
/**
* Helper to change the machine state (reimplementation).
*
* @note Locks this object for writing.
* @note This method must not call i_saveSettings or SaveSettings, otherwise
* it can cause crashes in random places due to unexpectedly committing
* the current settings. The caller is responsible for that. The call
* to saveStateSettings is fine, because this method does not commit.
*/
{
AutoCaller autoCaller(this);
("oldMachineState=%s, aMachineState=%s\n",
E_FAIL);
int stsFlags = 0;
bool deleteSavedState = false;
/* detect some state transitions */
if ( ( oldMachineState == MachineState_Saved
|| ( ( oldMachineState == MachineState_PoweredOff
)
)
)
)
{
/* 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
)
&& ( aMachineState == MachineState_PoweredOff
)
/* ignore PoweredOff->Saving->PoweredOff transition when taking a
* snapshot */
|| mConsoleTaskData.mLastState >= MachineState_Running /** @todo Live Migration: clean up (lazy bird) */
)
)
{
/* The EMT thread has just stopped, unlock attached media. Note that as
* opposed to locking that is done from Console, we do unlocking here
* because the VM process may have aborted before having a chance to
* properly unlock all media it locked. */
unlockMedia();
}
{
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
&& ( aMachineState == MachineState_PoweredOff
)
)
{
/*
* delete the saved state after Console::ForgetSavedState() 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)
{
if (mRemoveSavedState)
{
// it is safe to delete the saved state file if ...
|| !mData->mFirstSnapshot->i_sharesSavedStateFile(mSSData->strStateFilePath, NULL /* pSnapshotToIgnore */)
// ... none of the snapshots share the saved state file
)
}
}
/* redirect to the underlying peer machine */
if ( aMachineState == MachineState_PoweredOff
|| aMachineState == MachineState_Saved)
{
/* the machine has stopped execution
* (or the saved state file was adopted) */
}
if ( ( oldMachineState == MachineState_PoweredOff
)
&& aMachineState == MachineState_Saved)
{
/* the saved state file was adopted */
}
#ifdef VBOX_WITH_GUEST_PROPS
if ( aMachineState == MachineState_PoweredOff
{
/* Make sure any transient guest properties get removed from the
* property store on shutdown. */
if (!fNeedsSaving)
{
fNeedsSaving = true;
break;
}
if (fNeedsSaving)
{
}
}
#endif
if ( ( oldMachineState != MachineState_PoweredOff
)
&& ( aMachineState == 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);
{
/* 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 deleting 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 inconsistent behavior
* and simply do nothing here. */
return S_OK;
}
}
{
}
{
}
{
}
{
}
{
}
{
}
{
}
{
}
{
}
{
}
{
}
{
}
{
}
{
}
{
}
{
}
{
}
{
}
{
}
{
}
{
}
{
}
{
}
{
}
{
}
{
}