ConsoleImpl.cpp revision 84f633d28fd1840520118fcc4ff7c726aeaa9184
/* $Id$ */
/** @file
* VBox Console COM Class implementation
*/
/*
* Copyright (C) 2005-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.
*/
/** @todo Move the TAP mess back into the driver! */
#if defined(RT_OS_WINDOWS)
#elif defined(RT_OS_LINUX)
# include <errno.h>
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
#elif defined(RT_OS_FREEBSD)
# include <errno.h>
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
#elif defined(RT_OS_SOLARIS)
# include <iprt/coredumper.h>
#endif
#include "ConsoleImpl.h"
#include "Global.h"
#include "VirtualBoxErrorInfoImpl.h"
#include "GuestImpl.h"
#include "KeyboardImpl.h"
#include "MouseImpl.h"
#include "DisplayImpl.h"
#include "MachineDebuggerImpl.h"
#include "USBDeviceImpl.h"
#include "RemoteUSBDeviceImpl.h"
#include "SharedFolderImpl.h"
#ifdef VBOX_WITH_PDM_AUDIO_DRIVER
#include "DrvAudioVRDE.h"
#else
#include "AudioSnifferInterface.h"
#endif
#include "Nvram.h"
#ifdef VBOX_WITH_USB_CARDREADER
# include "UsbCardReader.h"
#endif
#include "ProgressImpl.h"
#include "ConsoleVRDPServer.h"
#include "VMMDev.h"
#ifdef VBOX_WITH_EXTPACK
# include "ExtPackManagerImpl.h"
#endif
#include "BusAssignmentManager.h"
#include "EmulatedUSBImpl.h"
#include "VBoxEvents.h"
#include "AutoCaller.h"
#include "Logging.h"
#include "VBox/com/ErrorInfo.h"
#include <iprt/buildconfig.h>
#ifdef VBOX_WITH_USB
#endif
#ifdef VBOX_WITH_NETSHAPER
#endif /* VBOX_WITH_NETSHAPER */
#ifdef VBOX_WITH_GUEST_PROPS
#endif
#ifdef VBOX_OPENSSL_FIPS
#endif
#include <set>
#include <algorithm>
#include <memory> // for auto_ptr
#include <vector>
// VMTask and friends
////////////////////////////////////////////////////////////////////////////////
/**
* Task structure for asynchronous VM operations.
*
* Once created, the task structure adds itself as a Console caller. This means:
*
* 1. The user must check for #rc() before using the created structure
* (e.g. passing it as a thread function argument). If #rc() returns a
* failure, the Console object may not be used by the task (see
* Console::addCaller() for more details).
* 2. On successful initialization, the structure keeps the Console caller
* until destruction (to ensure Console remains in the Ready state and won't
* be accidentally uninitialized). Forgetting to delete the created task
* will lead to Console::uninit() stuck waiting for releasing all added
* callers.
*
* If \a aUsesVMPtr parameter is true, the task structure will also add itself
* as a Console::mpUVM caller with the same meaning as above. See
* Console::addVMCaller() for more info.
*/
struct VMTask
{
bool aUsesVMPtr)
{
return;
if (aUsesVMPtr)
{
if (mpSafeVMPtr->isOk())
else
}
}
~VMTask()
{
}
/** Releases the VM caller before destruction. Not normally necessary. */
void releaseVMCaller()
{
if (mpSafeVMPtr)
{
delete mpSafeVMPtr;
mpSafeVMPtr = NULL;
}
}
private:
};
struct VMTakeSnapshotTask : public VMTask
{
false /* aUsesVMPtr */),
{}
bool fTakingSnapshotOnline;
};
struct VMPowerUpTask : public VMTask
{
false /* aUsesVMPtr */),
mStartPaused(false),
{}
bool mStartPaused;
/* array of progress objects for hard disk reset operations */
};
struct VMPowerDownTask : public VMTask
{
true /* aUsesVMPtr */)
{}
};
struct VMSaveTask : public VMTask
{
const Utf8Str &aSavedStateFile,
true /* aUsesVMPtr */),
{}
/* The local machine state we had before. Required if something fails */
/* The reason for saving state */
};
// Handler for global events
////////////////////////////////////////////////////////////////////////////////
class VmEventListener {
public:
{}
{
return S_OK;
}
void uninit()
{
}
virtual ~VmEventListener()
{
}
{
switch(aType)
{
{
if (id != interestedId)
break;
/* now we can operate with redirects */
break;
mConsole->i_onNATRedirectRuleChange(ulSlot, fRemove, proto, hostIp.raw(), hostPort, guestIp.raw(), guestPort);
}
break;
{
// handle if needed
break;
}
{
break;
}
default:
AssertFailed();
}
return S_OK;
}
private:
};
// constructor / destructor
/////////////////////////////////////////////////////////////////////////////
: mSavedStateDataLoaded(false)
, mfVRDEChangeInProcess(false)
, mfVRDEChangePending(false)
, mVMCallers(0)
, mVMDestroying(false)
, mVMPoweredOff(false)
, mVMIsAlreadyPoweringOff(false)
, mfSnapshotFolderSizeWarningShown(false)
, mfSnapshotFolderExt4WarningShown(false)
, mfSnapshotFolderDiskTypeShown(false)
, mfVMHasUsbController(false)
, mfPowerOffCausedByReset(false)
#ifndef VBOX_WITH_PDM_AUDIO_DRIVER
#endif
#ifdef VBOX_WITH_USB_CARDREADER
#endif
, mpIfSecKey(NULL)
, mVMStateChangeCallbackDisabled(false)
, mfUseHostClipboard(true)
{
}
{}
{
LogFlowThisFunc(("\n"));
for (unsigned i = 0; i < RT_ELEMENTS(maStorageDevType); ++i)
MYVMM2USERMETHODS *pVmm2UserMethods = (MYVMM2USERMETHODS *)RTMemAllocZ(sizeof(*mpVmm2UserMethods) + sizeof(Console *));
if (!pVmm2UserMethods)
return E_OUTOFMEMORY;
pVmm2UserMethods->pfnNotifyResetTurnedIntoPowerOff = Console::i_vmm2User_NotifyResetTurnedIntoPowerOff;
pVmm2UserMethods->pConsole = this;
if (!pIfSecKey)
return E_OUTOFMEMORY;
return BaseFinalConstruct();
}
void Console::FinalRelease()
{
LogFlowThisFunc(("\n"));
uninit();
}
// public initializer/uninitializer for internal purposes only
/////////////////////////////////////////////////////////////////////////////
{
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan(this);
/* Cache essential properties and objects, and create child objects */
#ifdef VBOX_WITH_EXTPACK
#endif
// Event source may be needed by other children
mcAudioRefs = 0;
mcVRDPClients = 0;
mcGuestCredentialsProvided = false;
/* Now the VM specific parts */
if (aLockType == LockType_VM)
{
/* Grab global and machine shared folder lists */
/* Create other child objects */
/* Figure out size of meAttachmentType vector */
if (pVirtualBox)
ULONG maxNetworkAdapters = 0;
if (pSystemProperties)
// VirtualBox 4.0: We no longer initialize the VMMDev instance here,
// which starts the HGCM thread. Instead, this is now done in the
// power-up thread when a VM is actually being powered up to avoid
// having HGCM threads all over the place every time a session is
// opened, even if that session will not run a VM.
// unconst(m_pVMMDev) = new VMMDev(this);
// AssertReturn(mVMMDev, E_FAIL);
#ifdef VBOX_WITH_PDM_AUDIO_DRIVER
#else
#endif
if ( enmFirmwareType == FirmwareType_EFI
{
}
#ifdef VBOX_WITH_USB_CARDREADER
#endif
/* VirtualBox events registration. */
{
}
}
/* Confirm a successful initialization when it's the case */
#ifdef VBOX_WITH_EXTPACK
/* Let the extension packs have a go at things (hold no locks). */
#endif
return S_OK;
}
/**
* Uninitializes the Console object.
*/
{
/* Enclose the state transition Ready->InUninit->NotReady */
AutoUninitSpan autoUninitSpan(this);
if (autoUninitSpan.uninitDone())
{
LogFlowThisFunc(("Already uninitialized.\n"));
return;
}
if (mVmListener)
{
{
{
}
}
}
/* power down the VM if necessary */
if (mpUVM)
{
i_powerDown();
}
if (mVMZeroCallersSem != NIL_RTSEMEVENT)
{
}
if (mpVmm2UserMethods)
{
RTMemFree((void *)mpVmm2UserMethods);
}
if (mpIfSecKey)
{
RTMemFree((void *)mpIfSecKey);
mpIfSecKey = NULL;
}
if (mNvram)
{
delete mNvram;
}
#ifdef VBOX_WITH_USB_CARDREADER
if (mUsbCardReader)
{
delete mUsbCardReader;
}
#endif
#ifndef VBOX_WITH_PDM_AUDIO_DRIVER
if (mAudioSniffer)
{
delete mAudioSniffer;
}
#endif
// if the VM had a VMMDev with an HGCM thread, then remove that here
if (m_pVMMDev)
{
delete m_pVMMDev;
}
if (mBusMgr)
{
}
mUSBDevices.clear();
it++)
if (mVRDEServerInfo)
{
}
if (mEmulatedUSB)
{
mEmulatedUSB->uninit();
}
if (mDebugger)
{
}
if (mDisplay)
{
}
if (mMouse)
{
}
if (mKeyboard)
{
}
if (mGuest)
{
}
if (mConsoleVRDPServer)
{
delete mConsoleVRDPServer;
}
// we don't perform uninit() as it's possible that some pending event refers to this source
#ifdef CONSOLE_WITH_EVENT_CACHE
#endif
}
#ifdef VBOX_WITH_GUEST_PROPS
/**
* Handles guest properties on a VM reset.
*
* We must delete properties that are flagged TRANSRESET.
*
* @todo r=bird: Would be more efficient if we added a request to the HGCM
* service to do this instead of detouring thru VBoxSVC.
* (IMachine::SetGuestProperty ends up in VBoxSVC, which in turns calls
* back into the VM process and the HGCM service.)
*/
void Console::i_guestPropertiesHandleVMReset(void)
{
{
{
/* Delete all properties which have the flag "TRANSRESET". */
{
LogRel(("RESET: Could not delete transient property \"%ls\", rc=%Rhrc\n",
}
}
}
else
}
bool Console::i_guestPropertiesVRDPEnabled(void)
{
value.asOutParam());
&& value == "1")
return true;
return false;
}
void Console::i_guestPropertiesVRDPUpdateLogon(uint32_t u32ClientId, const char *pszUser, const char *pszDomain)
{
if (!i_guestPropertiesVRDPEnabled())
return;
LogFlowFunc(("\n"));
char szPropNm[256];
clientName.raw(),
bstrReadOnlyGuest.raw());
bstrReadOnlyGuest.raw());
bstrReadOnlyGuest.raw());
char szClientId[64];
bstrReadOnlyGuest.raw());
return;
}
{
if (!i_guestPropertiesVRDPEnabled())
return;
char szClientId[64];
return;
}
{
if (!i_guestPropertiesVRDPEnabled())
return;
LogFlowFunc(("\n"));
char szPropNm[256];
clientName.raw(),
bstrReadOnlyGuest.raw());
}
{
if (!i_guestPropertiesVRDPEnabled())
return;
LogFlowFunc(("\n"));
char szPropNm[256];
clientIPAddr.raw(),
bstrReadOnlyGuest.raw());
}
void Console::i_guestPropertiesVRDPUpdateLocationChange(uint32_t u32ClientId, const char *pszLocation)
{
if (!i_guestPropertiesVRDPEnabled())
return;
LogFlowFunc(("\n"));
char szPropNm[256];
RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Location", u32ClientId);
bstrReadOnlyGuest.raw());
}
void Console::i_guestPropertiesVRDPUpdateOtherInfoChange(uint32_t u32ClientId, const char *pszOtherInfo)
{
if (!i_guestPropertiesVRDPEnabled())
return;
LogFlowFunc(("\n"));
char szPropNm[256];
RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/OtherInfo", u32ClientId);
bstrReadOnlyGuest.raw());
}
{
if (!i_guestPropertiesVRDPEnabled())
return;
LogFlowFunc(("\n"));
char szPropNm[256];
bstrReadOnlyGuest.raw());
}
{
if (!i_guestPropertiesVRDPEnabled())
return;
LogFlowFunc(("\n"));
char szPropNm[256];
bstrReadOnlyGuest.raw());
bstrReadOnlyGuest.raw());
bstrReadOnlyGuest.raw());
bstrReadOnlyGuest.raw());
char szClientId[64];
bstrReadOnlyGuest.raw());
return;
}
#endif /* VBOX_WITH_GUEST_PROPS */
bool Console::i_isResetTurnedIntoPowerOff(void)
{
value.asOutParam());
&& value == "1")
return true;
return false;
}
#ifdef VBOX_WITH_EXTPACK
/**
* Used by VRDEServer and others to talke to the extension pack manager.
*
* @returns The extension pack manager.
*/
{
return mptrExtPackManager;
}
#endif
int Console::i_VRDPClientLogon(uint32_t u32ClientId, const char *pszUser, const char *pszPassword, const char *pszDomain)
{
AutoCaller autoCaller(this);
if (!autoCaller.isOk())
{
/* Console has been already uninitialized, deny request */
LogRel(("AUTH: Access denied (Console uninitialized).\n"));
return VERR_ACCESS_DENIED;
}
ULONG authTimeout = 0;
LogRel(("AUTH: User: [%s]. Domain: [%s]. Authentication type: [%s]\n",
"Null":
"External":
(authType == AuthType_Guest?
"Guest":
"INVALID"
)
)
));
switch (authType)
{
case AuthType_Null:
{
break;
}
case AuthType_External:
{
/* Call the external library. */
result = mConsoleVRDPServer->Authenticate(uuid, guestJudgement, pszUser, pszPassword, pszDomain, u32ClientId);
if (result != AuthResultDelegateToGuest)
{
break;
}
LogRel(("AUTH: Delegated to guest.\n"));
LogFlowFunc(("External auth asked for guest judgement\n"));
} /* pass through */
case AuthType_Guest:
{
// @todo r=dj locking required here for m_pVMMDev?
if ( (m_pVMMDev)
)
{
/* Issue the request to guest. Assume that the call does not require EMT. It should not. */
/* Ask the guest to judge these credentials. */
if (RT_SUCCESS(rc))
{
/* Wait for guest. */
if (RT_SUCCESS(rc))
{
{
default:
}
}
else
{
}
}
else
{
}
}
if (authType == AuthType_External)
{
result = mConsoleVRDPServer->Authenticate(uuid, guestJudgement, pszUser, pszPassword, pszDomain, u32ClientId);
}
else
{
switch (guestJudgement)
{
case AuthGuestAccessGranted:
break;
default:
break;
}
}
} break;
default:
AssertFailed();
}
if (result != AuthResultAccessGranted)
{
/* Reject. */
LogRel(("AUTH: Access denied.\n"));
return VERR_ACCESS_DENIED;
}
LogRel(("AUTH: Access granted.\n"));
/* Multiconnection check must be made after authentication, so bad clients would not interfere with a good one. */
LogFlowFunc(("allowMultiConnection %d, reuseSingleConnection = %d, mcVRDPClients = %d, mu32SingleRDPClientId = %d\n",
if (allowMultiConnection == FALSE)
{
/* Note: the 'mcVRDPClients' variable is incremented in ClientConnect callback, which is called when the client
* is successfully connected, that is after the ClientLogon callback. Therefore the mcVRDPClients
* value is 0 for first client.
*/
if (mcVRDPClients != 0)
{
/* There is a client already.
* If required drop the existing client connection and let the connecting one in.
*/
{
LogRel(("AUTH: Multiple connections are not enabled. Disconnecting existing client.\n"));
}
else
{
/* Reject. */
LogRel(("AUTH: Multiple connections are not enabled. Access denied.\n"));
return VERR_ACCESS_DENIED;
}
}
/* Save the connected client id. From now on it will be necessary to disconnect this one. */
}
#ifdef VBOX_WITH_GUEST_PROPS
#endif /* VBOX_WITH_GUEST_PROPS */
/* Check if the successfully verified credentials are to be sent to the guest. */
value.asOutParam());
{
/* Provide credentials only if there are no logged in users. */
LONG64 ul64Timestamp = 0;
{
/* And only if there are no connected clients. */
if (ASMAtomicCmpXchgBool(&mcGuestCredentialsProvided, true, false))
{
}
}
}
// @todo r=dj locking required here for m_pVMMDev?
&& m_pVMMDev)
{
if (pDevPort)
{
}
}
return VINF_SUCCESS;
}
{
AutoCaller autoCaller(this);
#ifdef VBOX_WITH_GUEST_PROPS
/* Parse the status string. */
{
}
{
}
{
}
{
}
{
}
{
}
#endif
}
{
AutoCaller autoCaller(this);
if ( (u32Clients == 1)
&& ((pDev = i_getVMMDev()))
)
{
true,
VRDP_EXPERIENCE_LEVEL_FULL); // @todo configurable
}
mDisplay->VideoAccelVRDP(true);
#ifdef VBOX_WITH_GUEST_PROPS
#endif /* VBOX_WITH_GUEST_PROPS */
return;
}
{
AutoCaller autoCaller(this);
if ( (u32Clients == 0)
&& ((pDev = i_getVMMDev()))
)
{
false,
0);
}
mDisplay->VideoAccelVRDP(false);
{
}
{
}
{
mcAudioRefs--;
if (mcAudioRefs <= 0)
{
#ifndef VBOX_WITH_PDM_AUDIO_DRIVER
if (mAudioSniffer)
{
if (port)
{
}
}
#endif
}
}
if (authType == AuthType_External)
#ifdef VBOX_WITH_GUEST_PROPS
if (u32Clients == 0)
#endif /* VBOX_WITH_GUEST_PROPS */
if (u32Clients == 0)
mcGuestCredentialsProvided = false;
return;
}
{
AutoCaller autoCaller(this);
#ifndef VBOX_WITH_PDM_AUDIO_DRIVER
LogFlowFunc(("mAudioSniffer %p, u32ClientId %d.\n",
#endif
++mcAudioRefs;
if (mcAudioRefs == 1)
{
#ifndef VBOX_WITH_PDM_AUDIO_DRIVER
if (mAudioSniffer)
{
if (port)
{
}
}
#endif
}
return;
}
{
AutoCaller autoCaller(this);
return;
}
{
AutoCaller autoCaller(this);
return;
}
//static
//static
{
switch (adapterType)
{
return "pcnet";
#ifdef VBOX_WITH_E1000
return "e1000";
#endif
#ifdef VBOX_WITH_VIRTIO
return "virtio-net";
#endif
default:
AssertFailed();
return "unknown";
}
return NULL;
}
/**
* Loads various console data stored in the saved state file.
* This method does validation of the state file and returns an error info
* when appropriate.
*
* The method does nothing if the machine is not in the Saved file or if
* console data from it has already been loaded.
*
* @note The caller must lock this object for writing.
*/
{
return S_OK;
return rc;
if (RT_SUCCESS(vrc))
{
{
if (RT_SUCCESS(vrc))
else if (vrc == VERR_SSM_UNIT_NOT_FOUND)
vrc = VINF_SUCCESS;
}
else
}
if (RT_FAILURE(vrc))
tr("The saved state file '%ls' is invalid (%Rrc). Delete the saved state and try again"),
mSavedStateDataLoaded = true;
return rc;
}
/**
* Callback handler to save various console data to the state file,
* called when the user saves the VM state.
*
* @param pvUser pointer to Console
*
* @note Locks the Console object for reading.
*/
//static
{
LogFlowFunc(("\n"));
++it)
{
}
return;
}
/**
* Callback handler to load various console data from the state file.
* Called when the VM is being restored from the saved state.
*
* @param pvUser pointer to Console
* @param uVersion Console unit version.
* Should match sSSMConsoleVer.
* @param uPass The data pass.
*
* @note Should locks the Console object for writing, if necessary.
*/
//static
DECLCALLBACK(int)
{
LogFlowFunc(("\n"));
return VERR_VERSION_MISMATCH;
/* Currently, nothing to do when we've been called from VMR3Load*. */
return SSMR3SkipToEndOfUnit(pSSM);
}
/**
* Method to load various console data from the state file.
* Called from #loadDataFromSavedState.
*
* @param pvUser pointer to Console
* @param u32Version Console unit version.
* Should match sSSMConsoleVer.
*
* @note Locks the Console object for writing.
*/
{
AutoCaller autoCaller(this);
{
bool writable = true;
bool autoMount = false;
delete[] buf;
strHostPath = buf;
delete[] buf;
if (u32Version > 0x00010000)
false /* fFailOnError */);
}
return VINF_SUCCESS;
}
#ifdef VBOX_WITH_GUEST_PROPS
// static
void *pvParms,
{
using namespace guestProp;
/*
* No locking, as this is purely a notification which does not make any
* changes to the object state.
*/
LogFlow(("Console::doGuestPropNotification: pCBData={.pcszName=%s, .pcszValue=%s, .pcszFlags=%s}\n",
int rc;
rc = VINF_SUCCESS;
else
{
LogFlow(("Console::doGuestPropNotification: hrc=%Rhrc pCBData={.pcszName=%s, .pcszValue=%s, .pcszFlags=%s}\n",
}
return rc;
}
{
using namespace guestProp;
/*
* Now things get slightly complicated. Due to a race with the guest adding
* properties, there is no good way to know how much to enlarge a buffer for
* the service to enumerate into. We choose a decent starting size and loop a
* few times, each time retrying with the size suggested by the service plus
* one Kb.
*/
int vrc = VERR_BUFFER_OVERFLOW;
{
try
{
}
catch(...)
{
return E_OUTOFMEMORY;
}
&parm[0]);
}
if (VERR_BUFFER_OVERFLOW == vrc)
return setError(E_UNEXPECTED,
tr("Temporary failure due to guest activity, please retry"));
/*
* Finally we have to unpack the data returned by the service into the safe
* arrays supplied by the caller. We start by counting the number of entries.
*/
const char *pszBuf
unsigned cEntries = 0;
/* The list is terminated by a zero-length string at the end of a set
* of four strings. */
{
/* We are counting sets of four strings. */
for (unsigned j = 0; j < 4; ++j)
++cEntries;
}
/*
* And now we create the COM safe arrays and fill them in.
*/
/* Rely on the service to have formated the data correctly. */
for (unsigned i = 0; i < cEntries; ++i)
{
}
return S_OK;
}
#endif /* VBOX_WITH_GUEST_PROPS */
// IConsole properties
/////////////////////////////////////////////////////////////////////////////
{
/* mMachine is constant during life time, no need to lock */
/* callers expect to get a valid reference, better fail than crash them */
return E_FAIL;
return S_OK;
}
{
/* we return our local state (since it's always the same as on the server) */
*aState = mMachineState;
return S_OK;
}
{
/* mGuest is constant during life time, no need to lock */
return S_OK;
}
{
/* mKeyboard is constant during life time, no need to lock */
return S_OK;
}
{
/* mMouse is constant during life time, no need to lock */
return S_OK;
}
{
/* mDisplay is constant during life time, no need to lock */
return S_OK;
}
{
/* we need a write lock because of the lazy mDebugger initialization*/
/* check if we have to create the debugger object */
if (!mDebugger)
{
}
return S_OK;
}
{
size_t i = 0;
return S_OK;
}
{
size_t i = 0;
for (RemoteUSBDeviceList::const_iterator it = mRemoteUSBDevices.begin(); it != mRemoteUSBDevices.end(); ++i, ++it)
return S_OK;
}
{
/* mVRDEServerInfo is constant during life time, no need to lock */
return S_OK;
}
{
/* mEmulatedUSB is constant during life time, no need to lock */
return S_OK;
}
{
/* loadDataFromSavedState() needs a write lock */
/* Read console data stored in the saved state file (if not yet done) */
size_t i = 0;
for (SharedFolderMap::const_iterator it = m_mapSharedFolders.begin(); it != m_mapSharedFolders.end(); ++i, ++it)
return S_OK;
}
{
// no need to lock - lifetime constant
return S_OK;
}
HRESULT Console::getAttachedPCIDevices(std::vector<ComPtr<IPCIDeviceAttachment> > &aAttachedPCIDevices)
{
if (mBusMgr)
else
return S_OK;
}
{
return S_OK;
}
{
return S_OK;
}
// IConsole methods
/////////////////////////////////////////////////////////////////////////////
{
return S_OK;
}
{
return S_OK;
}
{
switch (mMachineState)
{
case MachineState_Running:
case MachineState_Paused:
case MachineState_Stuck:
break;
/* Try cancel the teleportation. */
case MachineState_Teleporting:
if (!mptrCancelableProgress.isNull())
{
break;
}
/* Try cancel the live snapshot. */
if (!mptrCancelableProgress.isNull())
{
break;
}
/* Try cancel the FT sync. */
if (!mptrCancelableProgress.isNull())
{
break;
}
return setError(VBOX_E_INVALID_VM_STATE, tr("Cannot power down at this point in a fault tolerant sync"));
/* extra nice error message for a common case */
case MachineState_Saved:
case MachineState_Stopping:
default:
return setError(VBOX_E_INVALID_VM_STATE,
tr("Invalid machine state: %s (must be Running, Paused or Stuck)"),
}
LogFlowThisFunc(("Initiating SHUTDOWN request...\n"));
/* memorize the current machine state */
bool fBeganPowerDown = false;
do
{
#ifdef VBOX_WITH_GUEST_PROPS
if (i_isResetTurnedIntoPowerOff())
{
mMachine->SaveSettings();
}
#endif
/*
* request a progress object from the server
* (this will set the machine state to Stopping on the server to block
* others from accessing this machine)
*/
break;
fBeganPowerDown = true;
/* sync the state with the server */
/* setup task object and thread to carry out the operation asynchronously */
"VMPwrDwn");
if (RT_FAILURE(vrc))
{
break;
}
/* task is now owned by powerDownThread(), so release it */
/* pass the progress to the caller */
}
while (0);
{
/* preserve existing error info */
if (fBeganPowerDown)
{
/*
* cancel the requested power down procedure.
* This will reset the machine state to the state it had right
* before calling mControl->BeginPoweringDown().
*/
}
return rc;
}
{
if ( mMachineState != MachineState_Running
/** @todo r=bird: This should be allowed on paused VMs as well. Later. */
)
return i_setInvalidMachineStateError();
/* protect mpUVM */
/* release the lock before a VMR3* call (EMT will call us back)! */
tr("Could not reset the machine (%Rrc)"),
vrc);
return rc;
}
{
return vrc;
}
{
AutoCaller autoCaller(this);
if ( mMachineState != MachineState_Running
)
return i_setInvalidMachineStateError();
/* Check if the CPU is present */
return rc;
if (!fCpuAttached)
bool fLocked = true;
/* Check if the CPU is unlocked */
if (RT_SUCCESS(vrc))
{
/* Notify the guest if possible. */
if (RT_SUCCESS(vrc))
if (RT_SUCCESS(vrc))
{
unsigned cTries = 100;
do
{
/* It will take some time until the event is processed in the guest. Wait... */
break;
/* Sleep a bit */
RTThreadSleep(100);
} while (cTries-- > 0);
}
else if (vrc == VERR_CPU_HOTPLUG_NOT_MONITORED_BY_GUEST)
{
/* Query one time. It is possible that the user ejected the CPU. */
}
}
/* If the CPU was unlocked we can detach it now. */
{
/*
* Call worker in EMT, that's faster and safer than doing everything
* using VMR3ReqCall.
*/
{
if (RT_SUCCESS(vrc))
}
if (RT_SUCCESS(vrc))
{
/* Detach it from the VM */
}
else
}
else
return rc;
}
{
/* nuke anything which might have been left behind. */
/*
* Attach the driver.
*/
return VINF_SUCCESS;
}
{
AutoCaller autoCaller(this);
if ( mMachineState != MachineState_Running
/** @todo r=bird: This should be allowed on paused VMs as well. Later. */
)
return i_setInvalidMachineStateError();
/* Check if the CPU is present */
if (fCpuAttached)
/*
* Call worker in EMT, that's faster and safer than doing everything
* using VMR3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
* here to make requests from under the lock in order to serialize them.
*/
/* release the lock before a VMR3* call (EMT will call us back)! */
{
if (RT_SUCCESS(vrc))
}
tr("Could not add CPU to the machine (%Rrc)"),
vrc);
if (RT_SUCCESS(vrc))
{
/* Notify the guest if possible. */
if (RT_SUCCESS(vrc))
/** @todo warning if the guest doesn't support it */
}
return rc;
}
{
return rc;
}
{
return rc;
}
{
if ( mMachineState != MachineState_Running
)
return i_setInvalidMachineStateError();
/* get the VM handle. */
// no need to release lock, as there are no cross-thread callbacks
/* get the acpi device interface and press the button. */
if (RT_SUCCESS(vrc))
{
if (pPort)
else
}
tr("Controlled power off failed (%Rrc)"),
vrc);
return rc;
}
{
if ( mMachineState != MachineState_Running
)
return i_setInvalidMachineStateError();
/* get the VM handle. */
// no need to release lock, as there are no cross-thread callbacks
/* get the acpi device interface and check if the button press was handled. */
if (RT_SUCCESS(vrc))
{
if (pPort)
{
bool fHandled = false;
if (RT_SUCCESS(vrc))
}
else
}
tr("Checking if the ACPI Power Button event was handled by the guest OS failed (%Rrc)"),
vrc);
return rc;
}
{
if ( mMachineState != MachineState_Running
)
return setError(VBOX_E_INVALID_VM_STATE,
tr("Invalid machine state %s when checking if the guest entered the ACPI mode)"),
/* get the VM handle. */
// no need to release lock, as there are no cross-thread callbacks
/* get the acpi device interface and query the information. */
if (RT_SUCCESS(vrc))
{
if (pPort)
{
bool fEntered = false;
if (RT_SUCCESS(vrc))
}
else
}
return S_OK;
}
{
if ( mMachineState != MachineState_Running
return i_setInvalidMachineStateError();
/* get the VM handle. */
// no need to release lock, as there are no cross-thread callbacks
/* get the acpi device interface and press the sleep button. */
if (RT_SUCCESS(vrc))
{
if (pPort)
else
}
tr("Sending sleep button event failed (%Rrc)"),
vrc);
return rc;
}
{
return rc;
}
{
if ( mMachineState != MachineState_PoweredOff
)
return setError(VBOX_E_INVALID_VM_STATE,
tr("Cannot adopt the saved machine state as the machine is not in Powered Off, Teleported or Aborted state (machine state: %s)"),
}
{
if (mMachineState != MachineState_Saved)
return setError(VBOX_E_INVALID_VM_STATE,
tr("Cannot delete the machine state as the machine is not in the saved state (machine state: %s)"),
/*
* Saved -> PoweredOff transition will be detected in the SessionMachine
* and properly handled.
*/
return rc;
}
/** read the value of a LED. */
{
if (!pLed)
return 0;
return u32;
}
{
/*
* Note: we don't lock the console object here because
* readAndClearLed() should be thread safe.
*/
/* Get LED array to read */
PDMLEDCORE SumLed = {0};
switch (aType)
{
case DeviceType_Floppy:
case DeviceType_DVD:
case DeviceType_HardDisk:
{
for (unsigned i = 0; i < RT_ELEMENTS(mapStorageLeds); ++i)
if (maStorageDevType[i] == aType)
break;
}
case DeviceType_Network:
{
for (unsigned i = 0; i < RT_ELEMENTS(mapNetworkLeds); ++i)
break;
}
case DeviceType_USB:
{
for (unsigned i = 0; i < RT_ELEMENTS(mapUSBLed); ++i)
break;
}
case DeviceType_SharedFolder:
{
break;
}
case DeviceType_Graphics3D:
{
break;
}
default:
return setError(E_INVALIDARG,
tr("Invalid device type: %d"),
aType);
}
/* Compose the result */
{
case 0:
break;
case PDMLED_READING:
break;
case PDMLED_WRITING:
case PDMLED_READING | PDMLED_WRITING:
break;
}
return S_OK;
}
{
#ifdef VBOX_WITH_USB
if ( mMachineState != MachineState_Running
&& mMachineState != MachineState_Paused)
return setError(VBOX_E_INVALID_VM_STATE,
tr("Cannot attach a USB device to the machine which is not running or paused (machine state: %s)"),
/* Get the VM handle. */
/* Don't proceed unless we have a USB controller. */
if (!mfVMHasUsbController)
return setError(VBOX_E_PDM_ERROR,
tr("The virtual machine does not have a USB controller"));
/* release the lock because the USB Proxy service may call us back
* (via onUSBDeviceAttach()) */
/* Request the device capture */
#else /* !VBOX_WITH_USB */
return setError(VBOX_E_PDM_ERROR,
tr("The virtual machine does not have a USB controller"));
#endif /* !VBOX_WITH_USB */
}
{
#ifdef VBOX_WITH_USB
/* Find it. */
{
{
pUSBDevice = *it;
break;
}
++it;
}
if (!pUSBDevice)
return setError(E_INVALIDARG,
tr("USB device with UUID {%RTuuid} is not attached to this machine"),
/* Remove the device from the collection, it is re-added below for failures */
/*
* Inform the USB device and USB proxy about what's cooking.
*/
{
/* Re-add the device to the collection */
return rc;
}
/* Request the PDM to detach the USB device. */
{
/* Request the device release. Even if it fails, the device will
* remain as held by proxy, which is OK for us (the VM process). */
}
else
{
/* Re-add the device to the collection */
}
return rc;
#else /* !VBOX_WITH_USB */
return setError(VBOX_E_PDM_ERROR,
tr("The virtual machine does not have a USB controller"));
#endif /* !VBOX_WITH_USB */
}
{
#ifdef VBOX_WITH_USB
{
{
}
}
return setErrorNoLog(VBOX_E_OBJECT_NOT_FOUND,
tr("Could not find a USB device with address '%s'"),
#else /* !VBOX_WITH_USB */
return E_NOTIMPL;
#endif /* !VBOX_WITH_USB */
}
{
#ifdef VBOX_WITH_USB
{
{
}
}
return setErrorNoLog(VBOX_E_OBJECT_NOT_FOUND,
tr("Could not find a USB device with uuid {%RTuuid}"),
#else /* !VBOX_WITH_USB */
return E_NOTIMPL;
#endif /* !VBOX_WITH_USB */
}
HRESULT Console::createSharedFolder(const com::Utf8Str &aName, const com::Utf8Str &aHostPath, BOOL aWritable, BOOL aAutomount)
{
/// @todo see @todo in AttachUSBDevice() about the Paused state
if (mMachineState == MachineState_Saved)
return setError(VBOX_E_INVALID_VM_STATE,
tr("Cannot create a transient shared folder on the machine in the saved state"));
if ( mMachineState != MachineState_PoweredOff
)
return setError(VBOX_E_INVALID_VM_STATE,
tr("Cannot create a transient shared folder on the machine while it is changing the state (machine state: %s)"),
return setError(VBOX_E_FILE_ERROR,
tr("Shared folder named '%s' already exists"),
!!aWritable,
!!aAutomount,
true /* fFailOnError */);
/* If the VM is online and supports shared folders, share this folder
* under the specified name. (Ignore any failure to obtain the VM handle.) */
SafeVMPtrQuiet ptrVM(this);
&& m_pVMMDev
&& m_pVMMDev->isShFlActive()
)
{
/* first, remove the machine or the global folder if there is any */
{
return rc;
}
/* second, create the given folder */
return rc;
}
/* Notify console callbacks after the folder is added to the list. */
return rc;
}
{
/// @todo see @todo in AttachUSBDevice() about the Paused state
if (mMachineState == MachineState_Saved)
return setError(VBOX_E_INVALID_VM_STATE,
tr("Cannot remove a transient shared folder from the machine in the saved state"));
if ( mMachineState != MachineState_PoweredOff
)
return setError(VBOX_E_INVALID_VM_STATE,
tr("Cannot remove a transient shared folder from the machine while it is changing the state (machine state: %s)"),
/* protect the VM handle (if not NULL) */
SafeVMPtrQuiet ptrVM(this);
&& m_pVMMDev
&& m_pVMMDev->isShFlActive()
)
{
/* if the VM is online and supports shared folders, UNshare this
* folder. */
/* first, remove the given folder */
/* first, remove the machine or the global folder if there is any */
{
/* don't check rc here because we need to remove the console
* folder from the collection even on failure */
}
}
/* Notify console callbacks after the folder is removed from the list. */
return rc;
}
{
return setError(VBOX_E_INVALID_VM_STATE,
tr("Cannot take a snapshot of the machine while it is changing the state (machine state: %s)"),
/* prepare the progress object:
a) count the no. of hard disk attachments to get a matching no. of progress sub-operations */
return rc;
for (size_t i = 0;
i < aMediumAttachments.size();
++i)
{
return rc;
if (type == DeviceType_HardDisk)
{
++cOperations;
// assume that creating a diff image takes as long as saving a 1MB state
// (note, the same value must be used in SessionMachine::BeginTakingSnapshot() on the server!)
ulTotalOperationsWeight += 1;
}
}
// b) one extra sub-operations for online snapshots OR offline snapshots that have a saved state (needs to be copied)
LogFlowFunc(("fTakingSnapshotOnline = %d, mMachineState = %d\n", fTakingSnapshotOnline, mMachineState));
{
++cOperations;
}
// finally, create the progress object
1); // ulFirstOperationWeight
return rc;
if (!(pTask = new VMTakeSnapshotTask(this, pProgress, Bstr(aName).raw(), Bstr(aDescription).raw())))
return E_OUTOFMEMORY;
try
{
/*
* If we fail here it means a PowerDown() call happened on another
* thread while we were doing Pause() (which releases the Console lock).
* We assign PowerDown() a higher precedence than TakeSnapshot(),
* therefore just return the error to the caller.
*/
/* memorize the current machine state */
(void *)pTask,
0,
0,
"TakeSnap");
tr("Could not create VMTakeSnap thread (%Rrc)"),
vrc);
}
{
delete pTask;
}
return rc;
}
{
return setError(VBOX_E_INVALID_VM_STATE,
tr("Cannot delete a snapshot of the machine while it is changing the state (machine state: %s)"),
HRESULT rc = mControl->DeleteSnapshot((IConsole *)this, Bstr(aId.toString()).raw(), Bstr(aId.toString()).raw(), FALSE /* fDeleteAllChildren */, &machineState, iProgress.asOutParam());
return S_OK;
}
{
return setError(VBOX_E_INVALID_VM_STATE,
tr("Cannot delete a snapshot of the machine while it is changing the state (machine state: %s)"),
HRESULT rc = mControl->DeleteSnapshot((IConsole *)this, Bstr(aId.toString()).raw(), Bstr(aId.toString()).raw(), TRUE /* fDeleteAllChildren */, &machineState, iProgress.asOutParam());
return S_OK;
}
HRESULT Console::deleteSnapshotRange(const com::Guid &aStartId, const com::Guid &aEndId, ComPtr<IProgress> &aProgress)
{
return setError(VBOX_E_INVALID_VM_STATE,
tr("Cannot delete a snapshot of the machine while it is changing the state (machine state: %s)"),
HRESULT rc = mControl->DeleteSnapshot((IConsole *)this, Bstr(aStartId.toString()).raw(), Bstr(aEndId.toString()).raw(), FALSE /* fDeleteAllChildren */, &machineState, iProgress.asOutParam());
return S_OK;
}
{
return setError(VBOX_E_INVALID_VM_STATE,
tr("Cannot delete the current state of the running machine (machine state: %s)"),
HRESULT rc = mControl->RestoreSnapshot((IConsole*)this, iSnapshot, &machineState, iProgress.asOutParam());
return S_OK;
}
// Non-interface public methods
/////////////////////////////////////////////////////////////////////////////
/*static*/
{
false /* aWarning */,
true /* aLogIt */);
return rc;
}
{
return setError(VBOX_E_INVALID_VM_STATE,
tr("Invalid machine state: %s"),
}
/* static */
{
switch (enmCtrlType)
{
return "lsilogicscsi";
return "buslogic";
return "lsilogicsas";
return "ahci";
return "piix3ide";
return "i82078";
return "Msd";
default:
return NULL;
}
}
HRESULT Console::i_convertBusPortDeviceToLun(StorageBus_T enmBus, LONG port, LONG device, unsigned &uLun)
{
switch (enmBus)
{
case StorageBus_IDE:
case StorageBus_Floppy:
{
return S_OK;
}
case StorageBus_SATA:
case StorageBus_SCSI:
case StorageBus_SAS:
{
return S_OK;
}
case StorageBus_USB:
{
/*
* It is always the first lun, the port denotes the device instance
* for the Msd device.
*/
uLun = 0;
return S_OK;
}
default:
uLun = 0;
}
}
// private methods
/////////////////////////////////////////////////////////////////////////////
/**
* Suspend the VM before we do any medium or network attachment change.
*
* @param pUVM Safe VM handle.
* @param pAlock The automatic lock instance. This is for when we have
* to leave it in order to avoid deadlocks.
* @param pfSuspend where to store the information if we need to resume
* afterwards.
*/
{
*pfResume = false;
switch (enmVMState)
{
case VMSTATE_RESETTING:
case VMSTATE_RUNNING:
{
LogFlowFunc(("Suspending the VM...\n"));
/* disable the callback to prevent Console-level state change */
mVMStateChangeCallbackDisabled = true;
if (pAlock)
if (pAlock)
mVMStateChangeCallbackDisabled = false;
if (RT_FAILURE(rc))
false /*aWarning*/,
true /*aLogIt*/);
*pfResume = true;
break;
}
case VMSTATE_SUSPENDED:
break;
default:
Utf8StrFmt("Invalid state '%s' for changing medium",
false /*aWarning*/,
true /*aLogIt*/);
}
return S_OK;
}
/**
* Resume the VM after we did any medium or network attachment change.
* This is the counterpart to Console::suspendBeforeConfigChange().
*
* @param pUVM Safe VM handle.
*/
{
LogFlowFunc(("Resuming the VM...\n"));
/* disable the callback to prevent Console-level state change */
mVMStateChangeCallbackDisabled = true;
mVMStateChangeCallbackDisabled = false;
if (RT_FAILURE(rc))
{
if (enmVMState == VMSTATE_SUSPENDED)
{
/* too bad, we failed. try to sync the console state with the VMM state */
}
}
}
/**
* Process a medium change.
*
* @param aMediumAttachment The medium attachment with the new medium state.
* @param fForce Force medium chance, if it is locked or not.
* @param pUVM Safe VM handle.
*
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller(this);
/* We will need to release the write lock before calling EMT */
if (pMedium)
{
}
{
if (attCtrlName == ctrlName)
{
pStorageController = ctrls[i];
break;
}
}
if (pStorageController.isNull())
/*
* Suspend the VM first. The VM must not be running since it might have
* pending I/O to the drive which is being changed.
*/
bool fResume = false;
return rc;
/*
* Call worker in EMT, that's faster and safer than doing everything
* using VMR3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
* here to make requests from under the lock in order to serialize them.
*/
/* release the lock before waiting for a result (EMT will call us back!) */
{
if (RT_SUCCESS(vrc))
}
if (fResume)
if (RT_SUCCESS(vrc))
{
LogFlowThisFunc(("Returns S_OK\n"));
return S_OK;
}
if (pMedium)
vrc);
}
/**
* Performs the medium change in EMT.
*
* @returns VBox status code.
*
* @param pThis Pointer to the Console object.
* @param pUVM The VM handle.
* @param pcszDevice The PDM device name.
* @param uInstance The PDM device instance.
* @param uLun The PDM LUN number of the drive.
* @param fHostDrive True if this is a host drive attachment.
* @param pszPath The path to the media / drive which is now being mounted / captured.
* If NULL no media or drive is attached and the LUN will be configured with
* the default block driver with no media. This will also be the state if
* mounting / capturing the specified media / drive fails.
* @param pszFormat Medium format string, usually "RAW".
* @param fPassthrough Enables using passthrough mode of the host DVD drive if applicable.
*
* @thread EMT
* @note The VM must not be running since it might have pending I/O to the drive which is being changed.
*/
const char *pcszDevice,
unsigned uInstance,
bool fUseHostIOCache,
bool fForce)
{
LogFlowFunc(("pThis=%p uInstance=%u pszDevice=%p:{%s} enmBus=%u, aMediumAtt=%p, fForce=%d\n",
/*
* Check the VM for correct state.
*/
/* Determine the base path for the device instance. */
else
false /* fSetupMerge */,
false /* fBuiltinIOCache */,
0 /* uMergeSource */,
0 /* uMergeTarget */,
NULL /* phrc */,
true /* fAttachDetach */,
fForce /* fForceUnmount */,
false /* fHotplug */,
pUVM,
NULL /* paLedDevType */,
&pLunL0);
/* Dump the changed LUN if possible, dump the complete device otherwise */
return rc;
}
/**
* Attach a new storage device to the VM.
*
* @param aMediumAttachment The medium attachment which is added.
* @param pUVM Safe VM handle.
* @param fSilent Flag whether to notify the guest about the attached device.
*
* @note Locks this object for writing.
*/
HRESULT Console::i_doStorageDeviceAttach(IMediumAttachment *aMediumAttachment, PUVM pUVM, bool fSilent)
{
AutoCaller autoCaller(this);
/* We will need to release the write lock before calling EMT */
if (pMedium)
{
}
{
if (attCtrlName == ctrlName)
{
pStorageController = ctrls[i];
break;
}
}
if (pStorageController.isNull())
/*
* Suspend the VM first. The VM must not be running since it might have
* pending I/O to the drive which is being changed.
*/
bool fResume = false;
return rc;
/*
* Call worker in EMT, that's faster and safer than doing everything
* using VMR3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
* here to make requests from under the lock in order to serialize them.
*/
/* release the lock before waiting for a result (EMT will call us back!) */
{
if (RT_SUCCESS(vrc))
}
if (fResume)
if (RT_SUCCESS(vrc))
{
LogFlowThisFunc(("Returns S_OK\n"));
return S_OK;
}
if (!pMedium)
vrc);
}
/**
* Performs the storage attach operation in EMT.
*
* @returns VBox status code.
*
* @param pThis Pointer to the Console object.
* @param pUVM The VM handle.
* @param pcszDevice The PDM device name.
* @param uInstance The PDM device instance.
* @param fSilent Flag whether to inform the guest about the attached device.
*
* @thread EMT
* @note The VM must not be running since it might have pending I/O to the drive which is being changed.
*/
const char *pcszDevice,
unsigned uInstance,
bool fUseHostIOCache,
bool fSilent)
{
LogFlowFunc(("pThis=%p uInstance=%u pszDevice=%p:{%s} enmBus=%u, aMediumAtt=%p\n",
/*
* Check the VM for correct state.
*/
/*
* Determine the base path for the device instance. USB Msd devices are handled different
* because the PDM USB API requires a differnet CFGM tree when attaching a new USB device.
*/
if (enmBus == StorageBus_USB)
else
false /* fSetupMerge */,
false /* fBuiltinIOCache */,
0 /* uMergeSource */,
0 /* uMergeTarget */,
NULL /* phrc */,
true /* fAttachDetach */,
false /* fForceUnmount */,
!fSilent /* fHotplug */,
pUVM,
NULL /* paLedDevType */,
&pLunL0);
/* Dump the changed LUN if possible, dump the complete device otherwise */
if (enmBus != StorageBus_USB)
return rc;
}
/**
* Attach a new storage device to the VM.
*
* @param aMediumAttachment The medium attachment which is added.
* @param pUVM Safe VM handle.
* @param fSilent Flag whether to notify the guest about the detached device.
*
* @note Locks this object for writing.
*/
HRESULT Console::i_doStorageDeviceDetach(IMediumAttachment *aMediumAttachment, PUVM pUVM, bool fSilent)
{
AutoCaller autoCaller(this);
/* We will need to release the write lock before calling EMT */
if (pMedium)
{
}
{
if (attCtrlName == ctrlName)
{
pStorageController = ctrls[i];
break;
}
}
if (pStorageController.isNull())
/*
* Suspend the VM first. The VM must not be running since it might have
* pending I/O to the drive which is being changed.
*/
bool fResume = false;
return rc;
/*
* Call worker in EMT, that's faster and safer than doing everything
* using VMR3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
* here to make requests from under the lock in order to serialize them.
*/
/* release the lock before waiting for a result (EMT will call us back!) */
{
if (RT_SUCCESS(vrc))
}
if (fResume)
if (RT_SUCCESS(vrc))
{
LogFlowThisFunc(("Returns S_OK\n"));
return S_OK;
}
if (!pMedium)
vrc);
}
/**
* Performs the storage detach operation in EMT.
*
* @returns VBox status code.
*
* @param pThis Pointer to the Console object.
* @param pUVM The VM handle.
* @param pcszDevice The PDM device name.
* @param uInstance The PDM device instance.
* @param fSilent Flag whether to notify the guest about the detached device.
*
* @thread EMT
* @note The VM must not be running since it might have pending I/O to the drive which is being changed.
*/
const char *pcszDevice,
unsigned uInstance,
bool fSilent)
{
LogFlowFunc(("pThis=%p uInstance=%u pszDevice=%p:{%s} enmBus=%u, pMediumAtt=%p\n",
/*
* Check the VM for correct state.
*/
/* Determine the base path for the device instance. */
int rc = VINF_SUCCESS;
int rcRet = VINF_SUCCESS;
unsigned uLUN;
#undef H
if (enmBus != StorageBus_USB)
{
/* First check if the LUN really exists. */
if (pLunL0)
{
if (fSilent)
if (rc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
rc = VINF_SUCCESS;
}
else
}
else
{
/* Find the correct USB device in the list. */
{
break;
}
}
return rcRet;
}
/**
* Called by IInternalSessionControl::OnNetworkAdapterChange().
*
* @note Locks this object for writing.
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
/* don't trigger network changes if the VM isn't running */
SafeVMPtrQuiet ptrVM(this);
{
/* Get the properties we need from the adapter */
{
}
{
{
/*
* Find the adapter instance, get the config interface and update
* the link state.
*/
// prevent cross-thread deadlocks, don't need the lock any more
if (RT_SUCCESS(vrc))
{
if (pINetCfg)
{
Log(("Console::onNetworkAdapterChange: setting link state to %d\n",
}
{
correctly with the _LS variants */
|| enmVMState == VMSTATE_SUSPENDED)
{
{
}
{
}
}
}
}
else if (vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
else
if (RT_FAILURE(vrc))
}
}
}
// definitely don't need the lock any more
/* notify console callbacks on success */
return rc;
}
/**
* Called by IInternalSessionControl::OnNATEngineChange().
*
* @note Locks this object for writing.
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
/* don't trigger NAT engine changes if the VM isn't running */
SafeVMPtrQuiet ptrVM(this);
{
do
{
|| pNetworkAdapter.isNull())
break;
/*
* Find the adapter instance, get the config interface and update
* the link state.
*/
{
break;
}
if (RT_FAILURE(vrc))
{
break;
}
{
break;
}
/* look down for PDMINETWORKNATCONFIG interface */
while (pBase)
{
if (pNetNatCfg)
break;
/** @todo r=bird: This stinks! */
}
if (!pNetNatCfg)
break;
if (RT_FAILURE(vrc))
} while (0); /* break loop */
}
return rc;
}
{
return m_pVMMDev;
}
{
return mDisplay;
}
/**
* Parses one key value pair.
*
* @returns VBox status code.
* @param psz Configuration string.
* @param ppszEnd Where to store the pointer to the string following the key value pair.
* @param ppszKey Where to store the key on success.
* @param ppszVal Where to store the value on success.
*/
{
int rc = VINF_SUCCESS;
const char *pszKeyStart = psz;
const char *pszValStart = NULL;
while ( *psz != '='
&& *psz)
psz++;
/* End of string at this point is invalid. */
if (*psz == '\0')
return VERR_INVALID_PARAMETER;
psz++; /* Skip = character */
pszValStart = psz;
while ( *psz != ','
&& *psz != '\n'
&& *psz != '\r'
&& *psz)
psz++;
{
if (*ppszKey)
{
if (!*ppszVal)
{
rc = VERR_NO_MEMORY;
}
}
else
rc = VERR_NO_MEMORY;
}
else
if (RT_SUCCESS(rc))
return rc;
}
/**
* Removes the key interfaces from all disk attachments, useful when
* changing the key store or dropping it.
*/
{
AutoCaller autoCaller(this);
/* Get the VM - must be done before the read-locking. */
/* Find the correct attachment. */
for (unsigned i = 0; i < sfaAttachments.size(); i++)
{
/*
* Query storage controller, port and device
* to identify the correct driver.
*/
unsigned uLUN;
if (RT_SUCCESS(rc))
{
if (pIBase)
{
if (pIMedium)
{
}
}
}
}
return hrc;
}
/**
* Configures the encryption support for the disk identified by the gien UUID with
* the given key.
*
* @returns COM status code.
* @param pszUuid The UUID of the disk to configure encryption for.
*/
{
AutoCaller autoCaller(this);
/* Get the VM - must be done before the read-locking. */
return hrc;
/* Find the correct attachment. */
for (unsigned i = 0; i < sfaAttachments.size(); i++)
{
break;
/* Skip non hard disk attachments. */
continue;
/* Get the UUID of the base medium and compare. */
break;
break;
{
/*
* Found the matching medium, query storage controller, port and device
* to identify the correct driver.
*/
break;
break;
break;
break;
break;
unsigned uLUN;
if (RT_SUCCESS(rc))
{
if (pIBase)
{
if (!pIMedium)
else
{
if (RT_FAILURE(rc))
}
}
else
}
}
}
return hrc;
}
/**
* Parses the encryption configuration for one disk.
*
* @returns Pointer to the string following encryption configuration.
* @param psz Pointer to the configuration for the encryption of one disk.
*/
{
int rc = VINF_SUCCESS;
while ( *psz
&& RT_SUCCESS(rc))
{
if (RT_SUCCESS(rc))
{
else
if (*pszEnd == ',')
else
{
/*
* End of the configuration for the current disk, skip linefeed and
* carriage returns.
*/
while ( *pszEnd == '\n'
|| *pszEnd == '\r')
pszEnd++;
break; /* Stop parsing */
}
}
}
if ( RT_SUCCESS(rc)
&& pszUuid
&& pszKeyEnc)
{
/* Decode the key. */
if (cbKey != -1)
{
if (pbKey)
{
if (RT_SUCCESS(rc))
{
/* Add the key to the map */
}
else
tr("Failed to decode the key (%Rrc)"),
rc);
}
else
tr("Failed to allocate secure memory for the key"));
}
else
tr("The base64 encoding of the passed key is incorrect"));
}
else if (RT_SUCCESS(rc))
tr("The encryption configuration is incomplete"));
if (pszUuid)
if (pszKeyEnc)
{
}
if (ppszEnd)
return hrc;
}
{
while ( *pszCfg
{
}
return hrc;
}
/**
* Process a network adaptor change.
*
* @returns COM status code.
*
* @parma pUVM The VM handle (caller hold this safely).
* @param pszDevice The PDM device name.
* @param uInstance The PDM device instance.
* @param uLun The PDM LUN number of the drive.
* @param aNetworkAdapter The network adapter whose attachment needs to be changed
*/
const char *pszDevice,
unsigned uInstance,
unsigned uLun,
{
LogFlowThisFunc(("pszDevice=%p:{%s} uInstance=%u uLun=%u aNetworkAdapter=%p\n",
AutoCaller autoCaller(this);
/*
* Suspend the VM first.
*/
bool fResume = false;
return rc;
/*
* Call worker in EMT, that's faster and safer than doing everything
* using VM3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
* here to make requests from under the lock in order to serialize them.
*/
{
if (RT_SUCCESS(vrc))
}
if (fResume)
if (RT_SUCCESS(vrc))
{
LogFlowThisFunc(("Returns S_OK\n"));
return S_OK;
}
tr("Could not change the network adaptor attachement type (%Rrc)"),
vrc);
}
/**
* Performs the Network Adaptor change in EMT.
*
* @returns VBox status code.
*
* @param pThis Pointer to the Console object.
* @param pUVM The VM handle.
* @param pszDevice The PDM device name.
* @param uInstance The PDM device instance.
* @param uLun The PDM LUN number of the drive.
* @param aNetworkAdapter The network adapter whose attachment needs to be changed
*
* @thread EMT
* @note Locks the Console object for writing.
* @note The VM must not be running.
*/
const char *pszDevice,
unsigned uInstance,
unsigned uLun,
{
LogFlowFunc(("pThis=%p pszDevice=%p:{%s} uInstance=%u uLun=%u aNetworkAdapter=%p\n",
if (pVirtualBox)
ULONG maxNetworkAdapters = 0;
if (pSystemProperties)
&& uLun == 0
&& uInstance < maxNetworkAdapters,
/*
* Check the VM for correct state.
*/
true /*fAttachDetach*/, false /*fIgnoreConnectFailure*/);
return rc;
}
/**
* Called by IInternalSessionControl::OnSerialPortChange().
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
return S_OK;
}
/**
* Called by IInternalSessionControl::OnParallelPortChange().
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
return S_OK;
}
/**
* Called by IInternalSessionControl::OnStorageControllerChange().
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
return S_OK;
}
/**
* Called by IInternalSessionControl::OnMediumChange().
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
/* don't trigger medium changes if the VM isn't running */
SafeVMPtrQuiet ptrVM(this);
{
}
/* notify console callbacks on success */
return rc;
}
/**
* Called by IInternalSessionControl::OnCPUChange().
*
* @note Locks this object for writing.
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
/* don't trigger CPU changes if the VM isn't running */
SafeVMPtrQuiet ptrVM(this);
{
if (aRemove)
else
}
/* notify console callbacks on success */
return rc;
}
/**
* Called by IInternalSessionControl::OnCpuExecutionCapChange().
*
* @note Locks this object for writing.
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
/* don't trigger the CPU priority change if the VM isn't running */
SafeVMPtrQuiet ptrVM(this);
{
if ( mMachineState == MachineState_Running
)
{
/* No need to call in the EMT thread. */
}
else
}
/* notify console callbacks on success */
{
}
return rc;
}
/**
* Called by IInternalSessionControl::OnClipboardModeChange().
*
* @note Locks this object for writing.
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
/* don't trigger the clipboard mode change if the VM isn't running */
SafeVMPtrQuiet ptrVM(this);
{
if ( mMachineState == MachineState_Running
else
}
/* notify console callbacks on success */
{
}
return rc;
}
/**
* Called by IInternalSessionControl::OnDnDModeChange().
*
* @note Locks this object for writing.
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
/* don't trigger the drag'n'drop mode change if the VM isn't running */
SafeVMPtrQuiet ptrVM(this);
{
if ( mMachineState == MachineState_Running
else
}
/* notify console callbacks on success */
{
}
return rc;
}
/**
* Called by IInternalSessionControl::OnVRDEServerChange().
*
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller(this);
/* don't trigger VRDE server changes if the VM isn't running */
SafeVMPtrQuiet ptrVM(this);
{
/* Serialize. */
mfVRDEChangePending = true;
else
{
do {
mfVRDEChangeInProcess = true;
mfVRDEChangePending = false;
if ( mVRDEServer
&& ( mMachineState == MachineState_Running
)
)
{
if (aRestart)
{
/* VRDP server may call this Console object back from other threads (VRDP INPUT or OUTPUT). */
if (vrdpEnabled)
{
// If there was no VRDP server started the 'stop' will do nothing.
// However if a server was started and this notification was called,
// we have to restart the server.
else
}
else
}
}
else
mfVRDEChangeInProcess = false;
}
}
/* notify console callbacks on success */
{
}
return rc;
}
void Console::i_onVRDEServerInfoChange()
{
AutoCaller autoCaller(this);
}
{
AutoCaller autoCaller(this);
/* don't trigger video capture changes if the VM isn't running */
SafeVMPtrQuiet ptrVM(this);
{
if (mDisplay)
{
int vrc = VINF_SUCCESS;
if (RT_SUCCESS(vrc))
{
if (fEnabled)
{
if (RT_FAILURE(vrc))
}
else
}
else
}
}
/* notify console callbacks on success */
{
}
return rc;
}
/**
* Called by IInternalSessionControl::OnUSBControllerChange().
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
return S_OK;
}
/**
* Called by IInternalSessionControl::OnSharedFolderChange().
*
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller(this);
/* notify console callbacks on success */
{
fireSharedFolderChangedEvent(mEventSource, aGlobal ? (Scope_T)Scope_Global : (Scope_T)Scope_Machine);
}
return rc;
}
/**
* Called by IInternalSessionControl::OnUSBDeviceAttach() or locally by
* processRemoteUSBDevices() after IInternalMachineControl::RunUSBDeviceFilters()
* returns TRUE for a given remote USB device.
*
* @return S_OK if the device was attached to the VM.
* @return failure if not attached.
*
* @param aDevice
* The device in question.
* @param aMaskedIfs
* The interfaces to hide from the guest.
*
* @note Locks this object for writing.
*/
HRESULT Console::i_onUSBDeviceAttach(IUSBDevice *aDevice, IVirtualBoxErrorInfo *aError, ULONG aMaskedIfs)
{
#ifdef VBOX_WITH_USB
AutoCaller autoCaller(this);
/* Get the VM pointer (we don't need error info, since it's a callback). */
SafeVMPtrQuiet ptrVM(this);
{
/* The VM may be no more operational when this message arrives
* (e.g. it may be Saving or Stopping or just PoweredOff) --
* autoVMCaller.rc() will return a failure in this case. */
LogFlowThisFunc(("Attach request ignored (mMachineState=%d).\n",
}
{
/* notify callbacks about the error */
return S_OK;
}
/* Don't proceed unless there's at least one USB hub. */
{
LogFlowThisFunc(("Attach request ignored (no USB controller).\n"));
return E_FAIL;
}
{
/* take the current error info */
/* the error must be a VirtualBoxErrorInfo instance */
{
/* notify callbacks about the error */
}
}
return rc;
#else /* !VBOX_WITH_USB */
return E_FAIL;
#endif /* !VBOX_WITH_USB */
}
/**
* Called by IInternalSessionControl::OnUSBDeviceDetach() and locally by
* processRemoteUSBDevices().
*
* @note Locks this object for writing.
*/
{
#ifdef VBOX_WITH_USB
AutoCaller autoCaller(this);
/* Find the device. */
{
{
pUSBDevice = *it;
break;
}
++it;
}
if (pUSBDevice.isNull())
{
LogFlowThisFunc(("USB device not found.\n"));
/* The VM may be no more operational when this message arrives
* (e.g. it may be Saving or Stopping or just PoweredOff). Use
* AutoVMCaller to detect it -- AutoVMCaller::rc() will return a
* failure in this case. */
AutoVMCallerQuiet autoVMCaller(this);
{
LogFlowThisFunc(("Detach request ignored (mMachineState=%d).\n",
return autoVMCaller.rc();
}
/* the device must be in the list otherwise */
}
{
/* notify callback about an error */
return S_OK;
}
/* Remove the device from the collection, it is re-added below for failures */
{
/* Re-add the device to the collection */
/* take the current error info */
/* the error must be a VirtualBoxErrorInfo instance */
{
/* notify callbacks about the error */
}
}
return rc;
#else /* !VBOX_WITH_USB */
return E_FAIL;
#endif /* !VBOX_WITH_USB */
}
/**
* Called by IInternalSessionControl::OnBandwidthGroupChange().
*
* @note Locks this object for writing.
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
/* don't trigger bandwidth group changes if the VM isn't running */
SafeVMPtrQuiet ptrVM(this);
{
if ( mMachineState == MachineState_Running
)
{
/* No need to call in the EMT thread. */
{
int vrc = VINF_SUCCESS;
if (enmType == BandwidthGroupType_Disk)
vrc = PDMR3AsyncCompletionBwMgrSetMaxForFile(ptrVM.rawUVM(), Utf8Str(strName).c_str(), (uint32_t)cMax);
#ifdef VBOX_WITH_NETSHAPER
else if (enmType == BandwidthGroupType_Network)
else
#endif /* VBOX_WITH_NETSHAPER */
}
}
else
}
/* notify console callbacks on success */
{
}
return rc;
}
/**
* Called by IInternalSessionControl::OnStorageDeviceChange().
*
* @note Locks this object for writing.
*/
HRESULT Console::i_onStorageDeviceChange(IMediumAttachment *aMediumAttachment, BOOL aRemove, BOOL aSilent)
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
/* don't trigger medium changes if the VM isn't running */
SafeVMPtrQuiet ptrVM(this);
{
if (aRemove)
else
}
/* notify console callbacks on success */
return rc;
}
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
return autoCaller.rc();
if (!aMachineId)
return S_OK;
return hrc;
/* don't do anything if the VM isn't running */
SafeVMPtrQuiet ptrVM(this);
{
if (strKey == "VBoxInternal2/TurnResetIntoPowerOff")
{
}
}
/* notify console callbacks on success */
return hrc;
}
/**
* @note Temporarily locks this object for writing.
*/
{
#ifndef VBOX_WITH_GUEST_PROPS
#else /* VBOX_WITH_GUEST_PROPS */
return E_INVALIDARG;
return E_POINTER;
return E_POINTER;
return E_POINTER;
AutoCaller autoCaller(this);
/* protect mpUVM (if not NULL) */
SafeVMPtrQuiet ptrVM(this);
/* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
* ptrVM, so there is no need to hold a lock of this */
using namespace guestProp;
try
{
/* The + 1 is the null terminator */
4, &parm[0]);
/* The returned string should never be able to be greater than our buffer */
{
if (vrc != VERR_NOT_FOUND)
{
if (aTimestamp)
if (aFlags)
{
}
}
else
}
else
tr("The service call failed with the error %Rrc"),
vrc);
}
{
rc = E_OUTOFMEMORY;
}
return rc;
#endif /* VBOX_WITH_GUEST_PROPS */
}
/**
* @note Temporarily locks this object for writing.
*/
{
#ifndef VBOX_WITH_GUEST_PROPS
#else /* VBOX_WITH_GUEST_PROPS */
if (!RT_VALID_PTR(aName))
AutoCaller autoCaller(this);
/* protect mpUVM (if not NULL) */
SafeVMPtrQuiet ptrVM(this);
/* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
* ptrVM, so there is no need to hold a lock of this */
using namespace guestProp;
/* The + 1 is the null terminator */
{
/* The + 1 is the null terminator */
}
{
/* The + 1 is the null terminator */
}
int vrc;
3, &parm[0]);
2, &parm[0]);
else
1, &parm[0]);
if (RT_SUCCESS(vrc))
else
return hrc;
#endif /* VBOX_WITH_GUEST_PROPS */
}
/**
* @note Temporarily locks this object for writing.
*/
{
#ifndef VBOX_WITH_GUEST_PROPS
#else /* VBOX_WITH_GUEST_PROPS */
return E_POINTER;
if (ComSafeArrayOutIsNull(aNames))
return E_POINTER;
if (ComSafeArrayOutIsNull(aValues))
return E_POINTER;
return E_POINTER;
if (ComSafeArrayOutIsNull(aFlags))
return E_POINTER;
AutoCaller autoCaller(this);
/* protect mpUVM (if not NULL) */
AutoVMCallerWeak autoVMCaller(this);
return autoVMCaller.rc();
/* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
* autoVMCaller, so there is no need to hold a lock of this */
#endif /* VBOX_WITH_GUEST_PROPS */
}
/*
* Internal: helper function for connecting progress reporting
*/
{
if (pProgress)
}
/**
*/
{
AutoCaller autoCaller(this);
int vrc = VINF_SUCCESS;
/* Get the VM - must be done before the read-locking. */
/* We will need to release the lock before doing the actual merge */
/* paranoia - we don't want merges to happen while teleporting etc. */
switch (mMachineState)
{
break;
default:
return i_setInvalidMachineStateError();
}
/** @todo AssertComRC -> AssertComRCReturn! Could potentially end up
* using uninitialized variables here. */
if (pMedium)
{
}
{
if (attCtrlName == ctrlName)
{
pStorageController = ctrls[i];
break;
}
}
if (pStorageController.isNull())
tr("Could not find storage controller '%ls'"),
attCtrlName.raw());
unsigned uLUN;
/* Pause the VM, as it might have pending IO on this drive */
{
LogFlowFunc(("Suspending the VM...\n"));
/* disable the callback to prevent Console-level state change */
mVMStateChangeCallbackDisabled = true;
mVMStateChangeCallbackDisabled = false;
}
/* error handling is after resuming the VM */
{
LogFlowFunc(("Resuming the VM...\n"));
/* disable the callback to prevent Console-level state change */
mVMStateChangeCallbackDisabled = true;
mVMStateChangeCallbackDisabled = false;
if (RT_FAILURE(vrc2))
{
/* too bad, we failed. try to sync the console state with the VMM state */
}
}
if (RT_FAILURE(vrc))
return rc;
if (RT_SUCCESS(vrc))
{
if (pIBase)
{
if (!pIMedium)
}
else
}
/* Finally trigger the merge. */
if (RT_FAILURE(vrc))
/* Pause the VM, as it might have pending IO on this drive */
{
LogFlowFunc(("Suspending the VM...\n"));
/* disable the callback to prevent Console-level state change */
mVMStateChangeCallbackDisabled = true;
mVMStateChangeCallbackDisabled = false;
}
/* Update medium chain and state now, so that the VM can continue. */
/* error handling is after resuming the VM */
{
LogFlowFunc(("Resuming the VM...\n"));
/* disable the callback to prevent Console-level state change */
mVMStateChangeCallbackDisabled = true;
mVMStateChangeCallbackDisabled = false;
if (RT_FAILURE(vrc2))
{
/* too bad, we failed. try to sync the console state with the VMM state */
}
}
if (RT_FAILURE(vrc))
return rc;
return rc;
}
/**
* Load an HGCM service.
*
* Main purpose of this method is to allow extension packs to load HGCM
* service modules, which they can't, because the HGCM functionality lives
* in module VBoxC (and ConsoleImpl.cpp is part of it and thus can call it).
* Extension modules must not link directly against VBoxC, (XP)COM is
* handling this.
*/
{
/* Everyone seems to delegate all HGCM calls to VMMDev, so stick to this
* convention. Adds one level of indirection for no obvious reason. */
}
/**
* Merely passes the call to Guest::enableVMMStatistics().
*/
{
if (mGuest)
}
/**
* Worker for Console::Pause and internal entry point for pausing a VM for
* a specific reason.
*/
{
AutoCaller autoCaller(this);
switch (mMachineState)
{
case MachineState_Running:
case MachineState_Teleporting:
break;
case MachineState_Paused:
case MachineState_Saving:
default:
return i_setInvalidMachineStateError();
}
/* get the VM handle. */
/* release the lock before a VMR3* call (EMT will call us back)! */
LogFlowThisFunc(("Sending PAUSE request...\n"));
if (aReason != Reason_Unspecified)
/** @todo r=klaus make use of aReason */
if (aReason == Reason_HostSuspend)
else if (aReason == Reason_HostBatteryLow)
if (RT_FAILURE(vrc))
else
{
/* Unconfigure disk encryption from all attachments. */
/* Clear any keys we have stored. */
it++)
}
return hrc;
}
/**
* Worker for Console::Resume and internal entry point for resuming a VM for
* a specific reason.
*/
{
AutoCaller autoCaller(this);
if (mMachineState != MachineState_Paused)
return setError(VBOX_E_INVALID_VM_STATE,
tr("Cannot resume the machine as it is not paused (machine state: %s)"),
/* get the VM handle. */
/* release the lock before a VMR3* call (EMT will call us back)! */
LogFlowThisFunc(("Sending RESUME request...\n"));
if (aReason != Reason_Unspecified)
int vrc;
{
#ifdef VBOX_WITH_EXTPACK
#else
vrc = VINF_SUCCESS;
#endif
if (RT_SUCCESS(vrc))
}
else
{
if (aReason == Reason_HostResume)
}
tr("Could not resume the machine execution (%Rrc)"),
vrc);
return rc;
}
/**
* Worker for Console::SaveState and internal entry point for saving state of
* a VM for a specific reason.
*/
{
AutoCaller autoCaller(this);
if ( mMachineState != MachineState_Running
&& mMachineState != MachineState_Paused)
{
return setError(VBOX_E_INVALID_VM_STATE,
tr("Cannot save the execution state as the machine is not running or paused (machine state: %s)"),
}
if (aReason != Reason_Unspecified)
/* memorize the current machine state */
if (mMachineState == MachineState_Running)
{
/* get the VM handle. */
/* release the lock before a VMR3* call (EMT will call us back)! */
if (aReason == Reason_HostSuspend)
else if (aReason == Reason_HostBatteryLow)
if (RT_FAILURE(vrc))
return hrc;
}
bool fBeganSavingState = false;
bool fTaskCreationFailed = false;
do
{
/*
* request a saved state file path from the server
* (this will set the machine state to Saving on the server to block
* others from accessing this machine)
*/
break;
fBeganSavingState = true;
/* sync the state with the server */
/* ensure the directory for the saved state file exists */
{
dir.stripFilename();
{
if (RT_FAILURE(vrc))
{
tr("Could not create a directory '%s' to save the state to (%Rrc)"),
break;
}
}
}
/* Create a task object early to ensure mpUVM protection is successful. */
aReason));
/*
* If we fail here it means a PowerDown() call happened on another
* thread while we were doing Pause() (which releases the Console lock).
* We assign PowerDown() a higher precedence than SaveState(),
* therefore just return the error to the caller.
*/
{
fTaskCreationFailed = true;
break;
}
/* create a thread to wait until the VM state is saved */
0, RTTHREADTYPE_MAIN_WORKER, 0, "VMSave");
if (RT_FAILURE(vrc))
{
break;
}
/* task is now owned by saveStateThread(), so release it */
/* return the progress to the caller */
} while (0);
{
/* preserve existing error info */
if (fBeganSavingState)
{
/*
* cancel the requested save state procedure.
* This will reset the machine state to the state it had right
* before calling mControl->BeginSavingState().
*/
}
if (lastMachineState == MachineState_Running)
{
/* restore the paused state if appropriate */
/* restore the running state if appropriate */
{
}
}
else
}
return rc;
}
/**
* Gets called by Session::UpdateMachineState()
* (IInternalSessionControl::updateMachineState()).
*
* Must be called only in certain cases (see the implementation).
*
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller(this);
, E_FAIL);
return i_setMachineStateLocally(aMachineState);
}
#ifdef CONSOLE_WITH_EVENT_CACHE
/**
* @note Locks this object for writing.
*/
#endif
{
#if 0
LogFlowThisFunc(("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, height=%d, shape=%p\n",
#endif
AutoCaller autoCaller(this);
#ifdef CONSOLE_WITH_EVENT_CACHE
{
/* We need a write lock because we alter the cached callback data */
/* Save the callback arguments */
/* start with not valid */
else
}
#endif
fireMousePointerShapeChangedEvent(mEventSource, fVisible, fAlpha, xHot, yHot, width, height, ComSafeArrayInArg(pShape));
#if 0
#endif
}
#ifdef CONSOLE_WITH_EVENT_CACHE
/**
* @note Locks this object for writing.
*/
#endif
{
LogFlowThisFunc(("supportsAbsolute=%d supportsRelative=%d needsHostCursor=%d\n",
AutoCaller autoCaller(this);
#ifdef CONSOLE_WITH_EVENT_CACHE
{
/* We need a write lock because we alter the cached callback data */
/* save the callback arguments */
}
#endif
fireMouseCapabilityChangedEvent(mEventSource, supportsAbsolute, supportsRelative, supportsMT, needsHostCursor);
}
{
AutoCaller autoCaller(this);
}
void Console::i_onAdditionsStateChange()
{
AutoCaller autoCaller(this);
}
/**
* @remarks This notification only is for reporting an incompatible
* Guest Additions interface, *not* the Guest Additions version!
*
* The user will be notified inside the guest if new Guest
* Additions are available (via VBoxTray/VBoxClient).
*/
void Console::i_onAdditionsOutdated()
{
AutoCaller autoCaller(this);
/** @todo implement this */
}
#ifdef CONSOLE_WITH_EVENT_CACHE
/**
* @note Locks this object for writing.
*/
#endif
{
AutoCaller autoCaller(this);
#ifdef CONSOLE_WITH_EVENT_CACHE
{
/* We need a write lock because we alter the cached callback data */
/* save the callback arguments */
}
#endif
}
{
AutoCaller autoCaller(this);
}
{
AutoCaller autoCaller(this);
}
{
*aWinId = 0;
AutoCaller autoCaller(this);
if (aCheck)
{
//Assert(fDelivered);
if (fDelivered)
{
// bit clumsy
if (pCanShowEvent)
{
}
else
{
AssertFailed();
}
}
else
}
else
{
//Assert(fDelivered);
if (fDelivered)
{
if (pShowEvent)
{
}
else
AssertFailed();
}
}
return S_OK;
}
// private methods
////////////////////////////////////////////////////////////////////////////////
/**
* Increases the usage counter of the mpUVM pointer.
*
* Guarantees that VMR3Destroy() will not be called on it at least until
* releaseVMCaller() is called.
*
* If this method returns a failure, the caller is not allowed to use mpUVM and
* may return the failed result code to the upper level. This method sets the
* extended error info on failure if \a aQuiet is false.
*
* Setting \a aQuiet to true is useful for methods that don't want to return
* the failed result code to the caller when this method fails (e.g. need to
* silently check for the mpUVM availability).
*
* When mpUVM is NULL but \a aAllowNullVM is true, a corresponding error will be
* returned instead of asserting. Having it false is intended as a sanity check
* for methods that have checked mMachineState and expect mpUVM *NOT* to be
* NULL.
*
* @param aQuiet true to suppress setting error info
* @param aAllowNullVM true to accept mpUVM being NULL and return a failure
* (otherwise this method will assert if mpUVM is NULL)
*
* @note Locks this object for writing.
*/
bool aAllowNullVM /* = false */)
{
AutoCaller autoCaller(this);
* comment 25. */
return autoCaller.rc();
if (mVMDestroying)
{
/* powerDown() is waiting for all callers to finish */
tr("The virtual machine is being powered down"));
}
{
Assert(aAllowNullVM == true);
/* The machine is not powered up */
tr("The virtual machine is not powered up"));
}
++mVMCallers;
return S_OK;
}
/**
* Decreases the usage counter of the mpUVM pointer.
*
* Must always complete the addVMCaller() call after the mpUVM pointer is no
* more necessary.
*
* @note Locks this object for writing.
*/
void Console::i_releaseVMCaller()
{
AutoCaller autoCaller(this);
Assert(mVMCallers > 0);
--mVMCallers;
if (mVMCallers == 0 && mVMDestroying)
{
/* inform powerDown() there are no more callers */
}
}
{
AutoCaller autoCaller(this);
/*
* Repeat the checks done by addVMCaller.
*/
if (mVMDestroying) /* powerDown() is waiting for all callers to finish */
return a_Quiet
if (!pUVM)
return a_Quiet
/*
* Retain a reference to the user mode VM handle and get the global handle.
*/
if (cRefs == UINT32_MAX)
return a_Quiet
/* done */
return S_OK;
}
{
if (*a_ppUVM)
}
/**
* Initialize the release logging facility. In case something
* goes wrong, there will be no release logging. Maybe in the future
* we can add some logic to use different file names in this case.
* Note that the logic must be in sync with Machine::DeleteSettings().
*/
{
return hrc;
/* make sure the Logs folder exists */
/*
* Age the old log files
* Rename .(n-1) to .(n), .(n-2) to .(n-1), ..., and the last log file to .1
* Overwrite target files in case they exist.
*/
if (cHistoryFiles)
{
for (int i = cHistoryFiles-1; i >= 0; i--)
{
for (unsigned int j = 0; j < RT_ELEMENTS(files); ++j)
{
if (i > 0)
else
/* If the old file doesn't exist, delete the new file (if it
* exists) to provide correct rotation even if the sequence is
* broken */
}
}
}
"all all.restrict -default.restrict",
"VBOX_RELEASE_LOG", RTLOGDEST_FILE,
32768 /* cMaxEntriesPerGroup */,
0 /* cHistory */, 0 /* uHistoryFileTime */,
if (RT_FAILURE(vrc))
/* If we've made any directory changes, flush the directory to increase
the likelihood that the log file will be usable after a system panic.
Tip: Try 'export VBOX_RELEASE_LOG_FLAGS=flush' if the last bits of the log
is missing. Just don't have too high hopes for this to help. */
return hrc;
}
/**
* Common worker for PowerUp and PowerUpPaused.
*
* @returns COM status code.
*
* @param aProgress Where to return the progress object.
* @param aPaused true if PowerUpPaused called.
*/
{
AutoCaller autoCaller(this);
bool fBeganPoweringUp = false;
try
{
throw setError(VBOX_E_INVALID_VM_STATE,
tr("The virtual machine is already running or busy (machine state: %s)"),
/* Set up release logging as early as possible after the check if
* there is already a running VM which we shouldn't disturb. */
throw rc;
#ifdef VBOX_OPENSSL_FIPS
#endif
/* test and clear the TeleporterEnabled property */
throw rc;
#if 0 /** @todo we should save it afterwards, but that isn't necessarily a good idea. Find a better place for this (VBoxSVC). */
if (fTeleporterEnabled)
{
throw rc;
}
#endif
/* test the FaultToleranceState property */
throw rc;
/* Create a progress object to track progress of this operation. Must
* be done as early as possible (together with BeginPowerUp()) as this
* is vital for communicating as much as possible early powerup
* failure information to the API caller */
if (mMachineState == MachineState_Saved)
else if (fTeleporterEnabled)
else if (fFaultToleranceSyncEnabled)
else
/*
* Saved VMs will have to prove that their saved states seem kosher.
*/
if (mMachineState == MachineState_Saved)
{
throw rc;
if (RT_FAILURE(vrc))
throw setError(VBOX_E_FILE_ERROR,
tr("VM cannot start because the saved state file '%ls' is invalid (%Rrc). Delete the saved state prior to starting the VM"),
}
/* Read console data, including console shared folders, stored in the
* saved state file (if not yet done).
*/
throw rc;
/* Check all types of shared folders and compose a single list */
{
/* first, insert global folders */
++it)
{
}
/* second, insert machine folders */
++it)
{
}
/* third, insert console folders */
++it)
{
pSF->i_isWritable(),
pSF->i_isAutoMounted());
}
}
/* Setup task object and thread to carry out the operaton
* Asycnhronously */
if (mMachineState == MachineState_Saved)
/* Reset differencing hard disks for which autoReset is true,
* but only if the machine has no snapshots OR the current snapshot
* is an OFFLINE snapshot; otherwise we would reset the current
* differencing image of an ONLINE snapshot which contains the disk
* state of the machine while it was previously running, but without
* the corresponding machine state, which is equivalent to powering
* off a running machine and not good idea
*/
throw rc;
BOOL fCurrentSnapshotIsOnline = false;
if (pCurrentSnapshot)
{
throw rc;
}
if (!fCurrentSnapshotIsOnline)
{
LogFlowThisFunc(("Looking for immutable images to reset\n"));
throw rc;
for (size_t i = 0;
++i)
{
/** @todo later applies to floppies as well */
if (devType == DeviceType_HardDisk)
{
throw rc;
/* needs autoreset? */
throw rc;
if (autoReset)
{
throw rc;
/* save for later use on the powerup thread */
}
}
}
}
else
LogFlowThisFunc(("Machine has a current snapshot which is online, skipping immutable images reset\n"));
/* setup task object and thread to carry out the operation
* asynchronously */
#ifdef VBOX_WITH_EXTPACK
#endif
#ifdef RT_OS_SOLARIS
/* setup host core dumper for the VM */
HRESULT hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpEnabled").raw(), value.asOutParam());
{
mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpReplaceSystemDump").raw(), coreDumpReplaceSys.asOutParam());
uint32_t fCoreFlags = 0;
if ( coreDumpReplaceSys.isEmpty() == false
if ( coreDumpLive.isEmpty() == false
if ( pszDumpDir
&& *pszDumpDir == '\0')
pszDumpDir = NULL;
int vrc;
if ( pszDumpDir
&& !RTDirExists(pszDumpDir))
{
/*
* Try create the directory.
*/
if (RT_FAILURE(vrc))
pszDumpDir, vrc);
}
if (RT_FAILURE(vrc))
else
LogRel(("CoreDumper setup successful. pszDumpDir=%s fFlags=%#x\n", pszDumpDir ? pszDumpDir : ".", fCoreFlags));
}
#endif
// If there is immutable drive the process that.
for (VMPowerUpTask::ProgressList::const_iterator it = progresses.begin(); it != progresses.end(); ++it)
{
++cOperations;
ulTotalOperationsWeight += 1;
}
progressDesc.raw(),
TRUE, // Cancelable
1);
}
else if ( mMachineState == MachineState_Saved
|| (!fTeleporterEnabled && !fFaultToleranceSyncEnabled))
{
progressDesc.raw(),
FALSE /* aCancelable */);
}
else if (fTeleporterEnabled)
{
progressDesc.raw(),
TRUE /* aCancelable */,
3 /* cOperations */,
10 /* ulTotalOperationsWeight */,
1 /* ulFirstOperationWeight */);
}
else if (fFaultToleranceSyncEnabled)
{
progressDesc.raw(),
TRUE /* aCancelable */,
3 /* cOperations */,
10 /* ulTotalOperationsWeight */,
1 /* ulFirstOperationWeight */);
}
throw rc;
/* Tell VBoxSVC and Machine about the progress object so they can
LogFlowThisFunc(("Calling BeginPowerUp...\n"));
{
LogFlowThisFunc(("BeginPowerUp failed\n"));
throw rc;
}
fBeganPoweringUp = true;
LogFlowThisFunc(("Checking if canceled...\n"));
throw rc;
if (fCanceled)
{
LogFlowThisFunc(("Canceled in BeginPowerUp\n"));
}
LogFlowThisFunc(("Not canceled yet.\n"));
/** @todo this code prevents starting a VM with unavailable bridged
* networking interface. The only benefit is a slightly better error
* message, which should be moved to the driver code. This is the
* only reason why I left the code in for now. The driver allows
* unavailable bridged networking interfaces in certain circumstances,
* and this is sabotaged by this check. The VM will initially have no
* network connectivity, but the user can fix this at runtime. */
#if 0
/* the network cards will undergo a quick consistency check */
++slot)
{
if (!enabled)
continue;
switch (netattach)
{
{
/* a valid host interface must have been set */
{
throw setError(VBOX_E_HOST_ERROR,
tr("VM cannot start because host interface networking requires a host interface name to be set"));
}
pHostInterface.asOutParam())))
{
throw setError(VBOX_E_HOST_ERROR,
tr("VM cannot start because the host interface '%ls' does not exist"),
}
break;
}
default:
break;
}
}
#endif // 0
/* setup task object and thread to carry out the operation
* asynchronously */
if (aProgress){
}
RTTHREADTYPE_MAIN_WORKER, 0, "VMPwrUp");
if (RT_FAILURE(vrc))
/* task is now owned by powerUpThread(), so release it */
/* finally, set the state: no right to fail in this method afterwards
* since we've already started the thread and it is now responsible for
* any error reporting and appropriate state change! */
if (mMachineState == MachineState_Saved)
else if (fTeleporterEnabled)
else if (enmFaultToleranceState == FaultToleranceState_Standby)
else
}
{
/* The progress object will fetch the current error info */
if (!pPowerupProgress.isNull())
/* Save the error info across the IPC below. Can't be done before the
* progress notification above, as saving the error info deletes it
* from the current context, and thus the progress object wouldn't be
* updated correctly. */
/* signal end of operation */
}
return rc;
}
/**
* Internal power off worker routine.
*
* This method may be called only at certain places with the following meaning
* as shown below:
*
* - if the machine state is either Running or Paused, a normal
* Console-initiated powerdown takes place (e.g. PowerDown());
* - if the machine state is Saving, saveStateThread() has successfully done its
* job;
* - if the machine state is Starting or Restoring, powerUpThread() has failed
* - if the machine state is Stopping, the VM has powered itself off (i.e. not
* as a result of the powerDown() call).
*
* Calling it in situations other than the above will cause unexpected behavior.
*
* Note that this method should be the only one that destroys mpUVM and sets it
* to NULL.
*
* @param aProgress Progress object to run (may be NULL).
*
* @note Locks this object for writing.
*
* @note Never call this method from a thread that called addVMCaller() or
* instantiated an AutoVMCaller object; first call releaseVMCaller() or
* release(). Otherwise it will deadlock.
*/
{
AutoCaller autoCaller(this);
/* Total # of steps for the progress object. Must correspond to the
* number of "advance percent count" comments in this method! */
enum { StepCount = 7 };
/* current step */
int vrc = VINF_SUCCESS;
/* sanity */
Assert(mVMDestroying == false);
LogRel(("Console::powerDown(): A request to power off the VM has been issued (mMachineState=%s, InUninit=%d)\n",
Global::stringifyMachineState(mMachineState), getObjectState().getState() == ObjectState::InUninit));
/* Check if we need to power off the VM. In case of mVMPoweredOff=true, the
* VM has already powered itself off in vmstateChangeCallback() and is just
* notifying Console about that. In case of Starting or Restoring,
* powerUpThread() is calling us on failure, so the VM is already off at
* that point. */
if ( !mVMPoweredOff
&& ( mMachineState == MachineState_Starting
)
mVMPoweredOff = true;
/*
* Go to Stopping state if not already there.
*
* vmstateChangeCallback() needs it to set the state to Saved on
* VMSTATE_TERMINATED. In terms of protecting from inappropriate operations
* while leaving the lock below, Saving or Restoring should be fine too.
* Ditto for TeleportingPausedVM -> Teleported.
*/
if ( mMachineState != MachineState_Saving
)
/* ----------------------------------------------------------------------
* DONE with necessary state changes, perform the power down actions (it's
* safe to release the object lock now if needed)
* ---------------------------------------------------------------------- */
if (mDisplay)
{
}
/* Stop the VRDP server to prevent new clients connection while VM is being
* powered off. */
if (mConsoleVRDPServer)
{
LogFlowThisFunc(("Stopping VRDP server...\n"));
/* Leave the lock since EMT could call us back as addVMCaller() */
}
/* advance percent count */
if (aProgress)
/* ----------------------------------------------------------------------
* Now, wait for all mpUVM callers to finish their work if there are still
* some on other threads. NO methods that need mpUVM (or initiate other calls
* that need it) may be called after this point
* ---------------------------------------------------------------------- */
/* go to the destroying state to prevent from adding new callers */
mVMDestroying = true;
if (mVMCallers > 0)
{
/* lazy creation */
if (mVMZeroCallersSem == NIL_RTSEMEVENT)
}
/* advance percent count */
if (aProgress)
vrc = VINF_SUCCESS;
/*
* Power off the VM if not already done that.
* Leave the lock since EMT will call vmstateChangeCallback.
*
* Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
* VM-(guest-)initiated power off happened in parallel a ms before this
* call. So far, we let this error pop up on the user's side.
*/
if (!mVMPoweredOff)
{
LogFlowThisFunc(("Powering off the VM...\n"));
#ifdef VBOX_WITH_EXTPACK
#endif
}
/* advance percent count */
if (aProgress)
#ifdef VBOX_WITH_HGCM
/* Shutdown HGCM services before destroying the VM. */
if (m_pVMMDev)
{
LogFlowThisFunc(("Shutdown HGCM...\n"));
/* Leave the lock since EMT will call us back as addVMCaller() */
}
/* advance percent count */
if (aProgress)
#endif /* VBOX_WITH_HGCM */
LogFlowThisFunc(("Ready for VM destruction.\n"));
/* If we are called from Console::uninit(), then try to destroy the VM even
* on failure (this will most likely fail too, but what to do?..) */
{
/* If the machine has a USB controller, release all USB devices
* (symmetric to the code in captureUSBDevices()) */
if (mfVMHasUsbController)
{
i_detachAllUSBDevices(false /* aDone */);
}
/* Now we've got to destroy the VM as well. (mpUVM is not valid beyond
* this point). We release the lock before calling VMR3Destroy() because
* it will result into calling destructors of drivers associated with
* Console children which may in turn try to lock Console (e.g. by
* instantiating SafeVMPtr to access mpUVM). It's safe here because
* mVMDestroying is set which should prevent any activity. */
/* Set mpUVM to NULL early just in case if some old code is not using
* addVMCaller()/releaseVMCaller(). (We have our own ref on pUVM.) */
LogFlowThisFunc(("Destroying the VM...\n"));
/* take the lock again */
/* advance percent count */
if (aProgress)
if (RT_SUCCESS(vrc))
{
LogFlowThisFunc(("Machine has been destroyed (mMachineState=%d)\n",
/* Note: the Console-level machine state change happens on the
* VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
* powerDown() is called from EMT (i.e. from vmstateChangeCallback()
* on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
* occurred yet. This is okay, because mMachineState is already
* Stopping in this case, so any other attempt to call PowerDown()
* will be rejected. */
}
else
{
/* bad bad bad, but what to do? (Give Console our UVM ref.) */
tr("Could not destroy the machine. (Error: %Rrc)"),
vrc);
}
/* Complete the detaching of the USB devices. */
if (mfVMHasUsbController)
{
i_detachAllUSBDevices(true /* aDone */);
}
/* advance percent count */
if (aProgress)
}
else
{
tr("Could not power off the machine. (Error: %Rrc)"),
vrc);
}
/*
* Finished with the destruction.
*
* Note that if something impossible happened and we've failed to destroy
* the VM, mVMDestroying will remain true and mMachineState will be
* something like Stopping, so most Console methods will return an error
* to the caller.
*/
else
mVMDestroying = false;
#ifdef CONSOLE_WITH_EVENT_CACHE
#endif
return rc;
}
/**
* @note Locks this object for writing.
*/
bool aUpdateServer /* = true */)
{
AutoCaller autoCaller(this);
if (mMachineState != aMachineState)
{
LogThisFunc(("machineState=%s -> %s aUpdateServer=%RTbool\n",
Global::stringifyMachineState(mMachineState), Global::stringifyMachineState(aMachineState), aUpdateServer));
/// @todo (dmik)
// possibly, we need to redo onStateChange() using the dedicated
// Event thread, like it is done in VirtualBox. This will make it
// much safer (no deadlocks possible if someone tries to use the
// console from the callback), however, listeners will lose the
// ability to synchronously react to state changes (is it really
// necessary??)
LogFlowThisFunc(("Doing onStateChange()...\n"));
LogFlowThisFunc(("Done onStateChange()\n"));
if (aUpdateServer)
{
/* Server notification MUST be done from under the lock; otherwise
* the machine state here and on the server might go out of sync
* which can lead to various unexpected results (like the machine
* state being >= MachineState_Running on the server, while the
* session state is already SessionState_Unlocked at the same time
* there).
*
* Cross-lock conditions should be carefully watched out: calling
* UpdateState we will require Machine and SessionMachine locks
* (remember that here we're holding the Console lock here, and also
* all locks that have been acquire by the thread before calling
* this method).
*/
LogFlowThisFunc(("Doing mControl->UpdateState()...\n"));
}
}
return rc;
}
/**
* Searches for a shared folder with the given logical name
* in the collection of shared folders.
*
* @param aName logical name of the shared folder
* @param aSharedFolder where to return the found object
* @param aSetError whether to set the error info if the folder is
* not found
* @return
* S_OK when found or E_INVALIDARG when not found
*
* @note The caller must lock this object for writing.
*/
bool aSetError /* = false */)
{
/* sanity check */
{
return S_OK;
}
if (aSetError)
tr("Could not find a shared folder named '%s'."),
return VBOX_E_FILE_ERROR;
}
/**
* Fetches the list of global or machine shared folders from the server.
*
* @param aGlobal true to fetch global folders.
*
* @note The caller must lock this object for writing.
*/
{
/* sanity check */
|| isWriteLockOnCurrentThread(), E_FAIL);
LogFlowThisFunc(("Entering\n"));
/* Check if we're online and keep it that way. */
SafeVMPtrQuiet ptrVM(this);
&& m_pVMMDev
&& m_pVMMDev->isShFlActive();
try
{
if (aGlobal)
{
/// @todo grab & process global folders when they are done
}
else
{
if (online)
{
/* send changes to HGCM if the VM is running */
if (online)
{
{
/* a new machine folder is added or
* the existing machine folder is changed */
; /* the console folder exists, nothing to do */
else
{
/* remove the old machine folder (when changed)
* or the global folder if any (when new) */
)
{
}
/* create the new machine folder */
}
}
/* forget the processed (or identical) folder */
}
}
/* process outdated (removed) folders */
if (online)
{
{
; /* the console folder exists, nothing to do */
else
{
/* remove the outdated machine folder */
/* create the global folder if there is any */
{
}
}
}
}
}
}
{
if (online)
i_setVMRuntimeErrorCallbackF(0, "BrokenSharedFolder",
N_("Broken shared folder!"));
}
LogFlowThisFunc(("Leaving\n"));
return rc;
}
/**
* Searches for a shared folder with the given name in the list of machine
* shared folders and then in the list of the global shared folders.
*
* @param aName Name of the folder to search for.
* @param aIt Where to store the pointer to the found folder.
* @return @c true if the folder was found and @c false otherwise.
*
* @note The caller must lock this object for reading.
*/
{
/* sanity check */
AssertReturn(isWriteLockOnCurrentThread(), false);
/* first, search machine folders */
return true;
/* second, search machine folders */
return true;
return false;
}
/**
* Calls the HGCM service to add a shared folder definition.
*
* @param aName Shared folder name.
* @param aHostPath Shared folder path.
*
* @note Must be called from under AutoVMCaller and when mpUVM != NULL!
* @note Doesn't lock anything.
*/
{
/* sanity checks */
value.asOutParam());
// check whether the path is valid and exists
char hostPathFull[RTPATH_MAX];
sizeof(hostPathFull));
bool fMissing = false;
if (RT_FAILURE(vrc))
return setError(E_INVALIDARG,
tr("Invalid shared folder path: '%s' (%Rrc)"),
if (!RTPathExists(hostPathFull))
fMissing = true;
/* Check whether the path is full (absolute) */
return setError(E_INVALIDARG,
tr("Shared folder path '%s' is not absolute"),
// now that we know the path is good, give it to HGCM
if (cbString >= UINT16_MAX)
if (cbString >= UINT16_MAX)
{
}
| (fMissing ? SHFL_ADD_MAPPING_F_MISSING : 0)
;
SHFL_CPARMS_ADD_MAPPING, &parms[0]);
if (RT_FAILURE(vrc))
tr("Could not create a shared folder '%s' mapped to '%s' (%Rrc)"),
if (fMissing)
return setError(E_INVALIDARG,
tr("Shared folder path '%s' does not exist on the host"),
return S_OK;
}
/**
* Calls the HGCM service to remove the shared folder definition.
*
* @param aName Shared folder name.
*
* @note Must be called from under AutoVMCaller and when mpUVM != NULL!
* @note Doesn't lock anything.
*/
{
/* sanity checks */
if (cbString >= UINT16_MAX)
1, &parms);
if (RT_FAILURE(vrc))
tr("Could not remove the shared folder '%s' (%Rrc)"),
return S_OK;
}
/** @callback_method_impl{FNVMATSTATE}
*
* @note Locks the Console object for writing.
* @remarks The @a pUVM parameter can be NULL in one case where powerUpThread()
* calls after the VM was destroyed.
*/
DECLCALLBACK(void) Console::i_vmstateChangeCallback(PUVM pUVM, VMSTATE enmState, VMSTATE enmOldState, void *pvUser)
{
LogFlowFunc(("Changing state from %s to %s (pUVM=%p)\n",
/* Note that we must let this method proceed even if Console::uninit() has
* been already called. In such case this VMSTATE change is a result of:
* 1) powerDown() called from uninit() itself, or
* 2) VM-(guest-)initiated power off. */
switch (enmState)
{
/*
* The VM has terminated
*/
case VMSTATE_OFF:
{
#ifdef VBOX_WITH_GUEST_PROPS
if (that->i_isResetTurnedIntoPowerOff())
{
if (that->mfPowerOffCausedByReset)
else
}
#endif
return;
/* Do we still think that it is running? It may happen if this is a
*/
)
{
LogFlowFunc(("VM has powered itself off but Console still thinks it is running. Notifying.\n"));
/*
* Prevent powerDown() from calling VMR3PowerOff() again if this was called from
* the power off state change.
* When called from the Reset state make sure to call VMR3PowerOff() first.
*/
that->mVMPoweredOff = true;
/*
* request a progress object from the server
* (this will set the machine state to Stopping on the server
* to block others from accessing this machine)
*/
/* sync the state with the server */
/* Setup task object and thread to carry out the operation
* asynchronously (if we call powerDown() right here but there
* is one or more mpUVM callers (added with addVMCaller()) we'll
* deadlock).
*/
/* If creating a task failed, this can currently mean one of
* two: either Console::uninit() has been called just a ms
* before (so a powerDown() call is already on the way), or
* powerDown() itself is being already executed. Just do
* nothing.
*/
{
LogFlowFunc(("Console is already being uninitialized.\n"));
return;
}
"VMPwrDwn");
/* task is now owned by powerDownThread(), so release it */
}
break;
}
/* The VM has been completely destroyed.
*
* Note: This state change can happen at two points:
* 1) At the end of VMR3Destroy() if it was not called from EMT.
* 2) At the end of vmR3EmulationThread if VMR3Destroy() was
* called by EMT.
*/
case VMSTATE_TERMINATED:
{
break;
/* Terminate host interface networking. If pUVM is NULL, we've been
* manually called from powerUpThread() either before calling
* VMR3Create() or after VMR3Create() failed, so no need to touch
* networking.
*/
if (pUVM)
/* From now on the machine is officially powered down or remains in
* the Saved state.
*/
switch (that->mMachineState)
{
default:
AssertFailed();
/* fall through */
case MachineState_Stopping:
/* successfully powered down */
break;
case MachineState_Saving:
/* successfully saved */
break;
case MachineState_Starting:
/* failed to start, but be patient: set back to PoweredOff
* (for similarity with the below) */
break;
case MachineState_Restoring:
/* failed to load the saved state file, but be patient: set
* back to Saved (to preserve the saved state file) */
break;
/* Teleportation failed or was canceled. Back to powered off. */
break;
/* Successfully teleported the VM. */
break;
/* Fault tolerant sync failed or was canceled. Back to powered off. */
break;
}
break;
}
case VMSTATE_RESETTING:
{
#ifdef VBOX_WITH_GUEST_PROPS
#endif
break;
}
case VMSTATE_SUSPENDED:
{
break;
switch (that->mMachineState)
{
case MachineState_Teleporting:
break;
break;
case MachineState_Saving:
case MachineState_Restoring:
case MachineState_Stopping:
/* The worker thread handles the transition. */
break;
default:
case MachineState_Running:
break;
case MachineState_Paused:
/* Nothing to do. */
break;
}
break;
}
case VMSTATE_SUSPENDED_LS:
case VMSTATE_SUSPENDED_EXT_LS:
{
break;
switch (that->mMachineState)
{
case MachineState_Teleporting:
break;
break;
case MachineState_Saving:
/* ignore */
break;
default:
break;
}
break;
}
case VMSTATE_RUNNING:
{
if ( enmOldState == VMSTATE_POWERING_ON
|| enmOldState == VMSTATE_RESUMING
|| enmOldState == VMSTATE_RUNNING_FT)
{
break;
&& enmOldState == VMSTATE_POWERING_ON)
)
&& enmOldState == VMSTATE_RESUMING)
&& enmOldState == VMSTATE_RUNNING_FT));
}
break;
}
case VMSTATE_RUNNING_LS:
break;
case VMSTATE_RUNNING_FT:
break;
case VMSTATE_FATAL_ERROR:
{
break;
/* Fatal errors are only for running VMs. */
/* Note! 'Pause' is used here in want of something better. There
* are currently only two places where fatal errors might be
* raised, so it is not worth adding a new externally
* visible state for this yet. */
break;
}
case VMSTATE_GURU_MEDITATION:
{
break;
/* Guru are only for running VMs */
break;
}
default: /* shut up gcc */
break;
}
}
/**
* Changes the clipboard mode.
*
* @param aClipboardMode new clipboard mode.
*/
{
switch (aClipboardMode)
{
default:
case ClipboardMode_Disabled:
LogRel(("Shared clipboard mode: Off\n"));
break;
LogRel(("Shared clipboard mode: Guest to Host\n"));
break;
LogRel(("Shared clipboard mode: Host to Guest\n"));
break;
LogRel(("Shared clipboard mode: Bidirectional\n"));
break;
}
}
/**
* Changes the drag'n_drop mode.
*
* @param aDnDMode new drag'n'drop mode.
*/
{
switch (aDnDMode)
{
default:
case DnDMode_Disabled:
LogRel(("Changed drag'n drop mode to: Off\n"));
break;
case DnDMode_GuestToHost:
LogRel(("Changed drag'n drop mode to: Guest to Host\n"));
break;
case DnDMode_HostToGuest:
LogRel(("Changed drag'n drop mode to: Host to Guest\n"));
break;
case DnDMode_Bidirectional:
LogRel(("Changed drag'n drop mode to: Bidirectional\n"));
break;
}
return rc;
}
#ifdef VBOX_WITH_USB
/**
* Sends a request to VMM to attach the given host device.
* After this method succeeds, the attached device will appear in the
* mUSBDevices collection.
*
* @param aHostDevice device to attach
*
* @note Synchronously calls EMT.
*/
{
/*
* Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
* method in EMT (using usbAttachCallback()).
*/
/* Get the VM handle. */
LogFlowThisFunc(("Proxying USB device '%s' {%RTuuid}...\n",
void *pvRemoteBackend = NULL;
if (fRemote)
{
pvRemoteBackend = i_consoleVRDPServer()->USBBackendRequestPointer(pRemoteUSBDevice->clientId(), &uuid);
if (!pvRemoteBackend)
return E_INVALIDARG; /* The clientId is invalid then. */
}
if (RT_SUCCESS(vrc))
{
/* Create a OUSBDevice and add it to the device list */
/* notify callbacks */
}
else
{
LogWarningThisFunc(("Failed to create proxy device for '%s' {%RTuuid} (%Rrc)\n",
switch (vrc)
{
case VERR_VUSB_NO_PORTS:
hrc = setError(E_FAIL, tr("Failed to attach the USB device. (No available ports on the USB controller)."));
break;
break;
default:
hrc = setError(E_FAIL, tr("Failed to create a proxy device for the USB device. (Error: %Rrc)"), vrc);
break;
}
}
return hrc;
}
/**
* USB device attach callback used by AttachUSBDevice().
* Note that AttachUSBDevice() doesn't return until this callback is executed,
* so we don't use AutoCaller and don't care about reference counters of
* interface pointers passed in.
*
* @thread EMT
* @note Locks the console object for writing.
*/
//static
DECLCALLBACK(int)
Console::i_usbAttachCallback(Console *that, PUVM pUVM, IUSBDevice *aHostDevice, PCRTUUID aUuid, bool aRemote,
{
return vrc;
}
/**
* Sends a request to VMM to detach the given host device. After this method
* succeeds, the detached device will disappear from the mUSBDevices
* collection.
*
* @param aHostDevice device to attach
*
* @note Synchronously calls EMT.
*/
{
/* Get the VM handle. */
/* if the device is attached, then there must at least one USB hub. */
LogFlowThisFunc(("Detaching USB proxy device {%RTuuid}...\n",
/*
* If this was a remote device, release the backend pointer.
* The pointer was requested in usbAttachCallback.
*/
if (fRemote)
{
}
if (RT_SUCCESS(vrc))
{
/* notify callbacks */
}
return S_OK;
}
/**
* USB device detach callback used by DetachUSBDevice().
*
* Note that DetachUSBDevice() doesn't return until this callback is executed,
* so we don't use AutoCaller and don't care about reference counters of
* interface pointers passed in.
*
* @thread EMT
*/
//static
DECLCALLBACK(int)
{
return vrc;
}
#endif /* VBOX_WITH_USB */
/* Note: FreeBSD needs this whether netflt is used or not. */
/**
* Helper function to handle host interface device creation and attachment.
*
* @param networkAdapter the network adapter which attachment should be reset
* @return COM status code
*
* @note The caller must lock this object for writing.
*
* @todo Move this back into the driver!
*/
{
LogFlowThisFunc(("\n"));
/* sanity check */
# ifdef VBOX_STRICT
/* paranoia */
# endif /* VBOX_STRICT */
# ifdef RT_OS_LINUX
/*
* Allocate a host interface device
*/
if (RT_SUCCESS(rcVBox))
{
/*
*/
/* The name of the TAP interface we are using */
if (tapDeviceName.isEmpty())
{
LogRel(("No TAP device name was supplied.\n"));
}
{
/* If we are using a static TAP device then try to open it. */
RTStrCopy(IfReq.ifr_name, sizeof(IfReq.ifr_name), str.c_str()); /** @todo bitch about names which are too long... */
if (rcVBox != 0)
{
tr("Failed to open the host network interface %ls"),
tapDeviceName.raw());
}
}
{
/*
* Make it pollable.
*/
{
/*
* Here is the right place to communicate the TAP file descriptor and
* necessary.
*/
}
else
{
LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
tr("could not set up the host networking device for non blocking access: %s"),
}
}
}
else
{
switch (rcVBox)
{
case VERR_ACCESS_DENIED:
/* will be handled by our caller */
break;
default:
tr("Could not set up the host networking device: %Rrc"),
rcVBox);
break;
}
}
# elif defined(RT_OS_FREEBSD)
/*
*/
/* The name of the TAP interface we are using */
if (tapDeviceName.isEmpty())
{
LogRel(("No TAP device name was supplied.\n"));
}
/* If we are using a static TAP device then try to open it. */
else
if (RT_SUCCESS(rcVBox))
else
{
switch (rcVBox)
{
case VERR_ACCESS_DENIED:
/* will be handled by our caller */
break;
default:
tr("Failed to open the host network interface %ls"),
tapDeviceName.raw());
break;
}
}
# else
# error "huh?"
# endif
/* in case of failure, cleanup. */
{
LogRel(("General failure attaching to host interface\n"));
tr("General failure attaching to host interface"));
}
return rc;
}
/**
* Helper function to handle detachment from a host interface
*
* @param networkAdapter the network adapter which attachment should be reset
* @return COM status code
*
* @note The caller must lock this object for writing.
*
* @todo Move this back into the driver!
*/
{
/* sanity check */
LogFlowThisFunc(("\n"));
# ifdef VBOX_STRICT
/* paranoia */
# endif /* VBOX_STRICT */
/* is there an open TAP device? */
{
/*
* Close the file handle.
*/
bool isStatic = true;
{
/* If the name is empty, this is a dynamic TAP device, so close it now,
so that the termination script can remove the interface. Otherwise we still
need the FD to pass to the termination script. */
isStatic = false;
}
if (isStatic)
{
/* If we are using a static TAP device, we close it now, after having called the
termination script. */
}
/* the TAP device name and handle are no longer valid */
}
return rc;
}
#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
/**
* Called at power down to terminate host interface networking.
*
* @note The caller must lock this object for writing.
*/
{
LogFlowThisFunc(("\n"));
/* sanity check */
/*
* host interface termination handling
*/
if (pVirtualBox)
ULONG maxNetworkAdapters = 0;
if (pSystemProperties)
{
if (!enabled)
continue;
{
#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
}
}
return rc;
}
/**
* Process callback handler for VMR3LoadFromFile, VMR3LoadFromStream, VMR3Save
* and VMR3Teleport.
*
* @param pUVM The user mode VM handle.
* @param uPercent Completion percentage (0-100).
* @param pvUser Pointer to an IProgress instance.
* @return VINF_SUCCESS.
*/
/*static*/
{
/* update the progress object */
if (pProgress)
return VINF_SUCCESS;
}
/**
* @copydoc FNVMATERROR
*
* @remarks Might be some tiny serialization concerns with access to the string
* object here...
*/
/*static*/ DECLCALLBACK(void)
{
/* We ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users. */
/* Append to any the existing error message. */
if (pErrorText->length())
else
}
/**
* VM runtime error callback function.
* See VMSetRuntimeError for the detailed description of parameters.
*
* @param pUVM The user mode VM handle. Ignored, so passing NULL
* is fine.
* @param pvUser The user argument, pointer to the Console instance.
* @param fFlags The action flags. See VMSETRTERR_FLAGS_*.
* @param pszErrorId Error ID string.
* @param pszFormat Error message format string.
* @param va Error message arguments.
* @thread EMT.
*/
/* static */ DECLCALLBACK(void)
const char *pszErrorId,
{
LogRel(("Console: VM runtime error: fatal=%RTbool, errorID=%s message=\"%s\"\n",
/* Set guest property if the reason of the error is a missing DEK for a disk. */
{
}
}
/**
* Captures USB devices that match filters of the VM.
* Called at VM startup.
*
* @param pUVM The VM handle.
*/
{
LogFlowThisFunc(("\n"));
/* sanity check */
/* If the machine has a USB controller, ask the USB proxy service to
* capture devices */
if (mfVMHasUsbController)
{
/* release the lock before calling Host in VBoxSVC since Host may call
* us back from under its lock (e.g. onUSBDeviceAttach()) which would
* produce an inter-process dead-lock otherwise. */
}
return S_OK;
}
/**
* Detach all USB device which are attached to the VM for the
* purpose of clean up and such like.
*/
{
/* sanity check */
mUSBDevices.clear();
/* release the lock before calling Host in VBoxSVC since Host may call
* us back from under its lock (e.g. onUSBDeviceAttach()) which would
* produce an inter-process dead-lock otherwise. */
}
/**
* @note Locks this object for writing.
*/
void Console::i_processRemoteUSBDevices(uint32_t u32ClientId, VRDEUSBDEVICEDESC *pDevList, uint32_t cbDevList, bool fDescExt)
{
LogFlowThisFunc(("u32ClientId = %d, pDevList=%p, cbDevList = %d, fDescExt = %d\n",
AutoCaller autoCaller(this);
if (!autoCaller.isOk())
{
/* Console has been already uninitialized, deny request */
AssertMsgFailed(("Console is already uninitialized\n"));
LogFlowThisFunc(("Console is already uninitialized\n"));
return;
}
/*
* Mark all existing remote USB devices as dirty.
*/
++it)
{
}
/*
* Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
*/
/** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
VRDEUSBDEVICEDESC *e = pDevList;
/* The cbDevList condition must be checked first, because the function can
* receive pDevList = NULL and cbDevList = 0 on client disconnect.
*/
{
/* Sanitize incoming strings in case they aren't valid UTF-8. */
if (e->oManufacturer)
RTStrPurgeEncoding((char *)e + e->oManufacturer);
if (e->oProduct)
RTStrPurgeEncoding((char *)e + e->oProduct);
if (e->oSerialNumber)
RTStrPurgeEncoding((char *)e + e->oSerialNumber);
LogFlowThisFunc(("vendor %04X, product %04X, name = %s\n",
bool fNewDevice = true;
++it)
{
{
/* The device is already in the list. */
fNewDevice = false;
break;
}
}
if (fNewDevice)
{
LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
/* Create the device object and add the new device to list. */
/* Check if the device is ok for current USB filters. */
ULONG fMaskedIfs = 0;
if (fMatched)
{
/// @todo (r=dmik) warning reporting subsystem
{
LogFlowThisFunc(("Device attached\n"));
pUSBDevice->captured(true);
}
}
}
{
LogWarningThisFunc(("cbDevList %d > oNext %d\n",
break;
}
}
/*
* Remove dirty devices, that is those which are not reported by the server anymore.
*/
for (;;)
{
{
{
pUSBDevice = *it;
break;
}
++it;
}
if (!pUSBDevice)
{
break;
}
LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
/* Detach the device from VM. */
if (pUSBDevice->captured())
{
}
/* And remove it from the list. */
}
}
/**
* Progress cancelation callback for fault tolerance VM poweron
*/
static void faultToleranceProgressCancelCallback(void *pvUser)
{
if (pUVM)
}
/**
* Thread function which starts the VM (also from saved state) and
* track progress.
*
* @param Thread The thread id.
* @param pvUser Pointer to a VMPowerUpTask structure.
* @return VINF_SUCCESS (ignored).
*
* @note Locks the Console object for writing.
*/
/*static*/
{
int vrc = VINF_SUCCESS;
/* Set up a build identifier so that it can be seen from core dumps what
* exact build was used to produce the core. */
static char saBuildID[40];
/* Note: no need to use addCaller() because VMPowerUpTask does that */
/* The lock is also used as a signal from the task initiator (which
* releases it only after RTThreadCreate()) that we can start the job */
/* sanity */
try
{
// Create the VMM device object, which starts the HGCM thread; do this only
// once for the console, for the pathological case that the same console
// object is used to power up a VM twice. VirtualBox 4.0: we now do that
// here instead of the Console constructor (see Console::init())
{
}
/* wait for auto reset ops to complete so that we can successfully lock
* the attached hard disks by calling LockMedia() below */
{
rc = task->mProgress->SetNextOperation(BstrFmt(tr("Disk Image Reset Operation - Immutable Image")).raw(), 1);
}
/*
* Lock attached media. This method will also check their accessibility.
* If we're a teleporter, we'll have to postpone this action so we can
* migrate between local processes.
*
* Note! The media will be unlocked automatically by
* SessionMachine::i_setMachineState() when the VM is powered down.
*/
if ( !task->mTeleporterEnabled
{
}
/* Create the VRDP server. In case of headless operation, this will
* also create the framebuffer, required at VM creation.
*/
/* Does VRDP server call Console from the other thread?
* Not sure (and can change), so release the lock just in case.
*/
if (vrc == VERR_NET_ADDRESS_IN_USE)
{
LogRel(("VRDE: Warning: failed to launch VRDE server (%Rrc): '%s'\n",
}
else if (vrc == VINF_NOT_SUPPORTED)
{
/* This means that the VRDE is not installed. */
LogRel(("VRDE: VirtualBox Remote Desktop Extension is not available.\n"));
}
else if (RT_FAILURE(vrc))
{
/* Fail, if the server is installed but can't start. */
switch (vrc)
{
case VERR_FILE_NOT_FOUND:
{
/* VRDE library file is missing. */
break;
}
default:
vrc);
}
LogRel(("VRDE: Failed: (%Rrc), error message: '%s'\n",
}
/*
* Create the VM
*
* Note! Release the lock since EMT will call Console. It's safe because
* mMachineState is either Starting or Restoring state here.
*/
/* Enable client connections to the server. */
if (RT_SUCCESS(vrc))
{
do
{
/*
*/
vrc = SSMR3RegisterExternal(pConsole->mpUVM, sSSMConsoleUnit, 0 /*iInstance*/, sSSMConsoleVer, 0 /* cbGuess */,
if (RT_FAILURE(vrc))
break;
/*
* Synchronize debugger settings
*/
if (machineDebugger)
/*
* Shared Folders
*/
{
/* Does the code below call Console from the other thread?
* Not sure, so release the lock just in case. */
++it)
{
{
N_("The shared folder '%s' could not be set up: %ls.\n"
"The shared folder setup will not be complete. It is recommended to power down the virtual "
"machine and fix the shared folder settings while the machine is not running"),
}
}
/* acquire the lock again */
}
/* release the lock before a lengthy operation */
/*
* Capture USB devices.
*/
break;
/* Load saved state? */
{
LogFlowFunc(("Restoring saved state from '%s'...\n",
if (RT_SUCCESS(vrc))
{
if (task->mStartPaused)
/* done */
else
{
#ifdef VBOX_WITH_EXTPACK
#endif
if (RT_SUCCESS(vrc))
}
}
/* Power off in case we failed loading or resuming the VM */
if (RT_FAILURE(vrc))
{
#ifdef VBOX_WITH_EXTPACK
#endif
}
}
else if (task->mTeleporterEnabled)
{
/* -> ConsoleImplTeleporter.cpp */
bool fPowerOffOnFailure;
{
#ifdef VBOX_WITH_EXTPACK
#endif
}
}
{
/*
* Get the config.
*/
{
}
{
{
/* Power on the FT enabled VM. */
#ifdef VBOX_WITH_EXTPACK
#endif
if (RT_SUCCESS(vrc))
}
}
else
}
else if (task->mStartPaused)
/* done */
else
{
/* Power on the VM (i.e. start executing) */
#ifdef VBOX_WITH_EXTPACK
#endif
if (RT_SUCCESS(vrc))
}
/* acquire the lock again */
}
while (0);
/* On failure, destroy the VM */
{
/* preserve existing error info */
/* powerDown() will call VMR3Destroy() and do all necessary
* cleanup (VRDP, USB devices) */
}
else
{
/*
* Deregister the VMSetError callback. This is necessary as the
* pfnVMAtError() function passed to VMR3Create() is supposed to
* be sticky but our error callback isn't.
*/
/** @todo register another VMSetError callback? */
}
}
else
{
/*
* If VMR3Create() failed it has released the VM memory.
*/
}
{
/* If VMR3Create() or one of the other calls in this function fail,
* an appropriate error message has been set in task->mErrorMsg.
* However since that happens via a callback, the rc status code in
* this function is not updated.
*/
{
/* If the error message is not set but we've got a failure,
* convert the VBox status code into a meaningful error message.
* This becomes unused once all the sources of errors set the
* appropriate error message themselves.
*/
vrc);
}
/* Set the error message as the COM error.
* Progress::notifyComplete() will pick it up later. */
}
}
)
{
*
* 1) we failed before VMR3Create() was called;
* 2) VMR3Create() failed.
*
* In both cases, there is no need to call powerDown(), but we still
* need to go back to the PoweredOff/Saved state. Reuse
* vmstateChangeCallback() for that purpose.
*/
/* preserve existing error info */
}
/*
* Evaluate the final result. Note that the appropriate mMachineState value
* is already set by vmstateChangeCallback() in all cases.
*/
/* release the lock, don't need it any more */
{
/* Notify the progress object of the success */
}
else
{
/* The progress object will fetch the current error info */
}
/* Notify VBoxSVC and any waiting openRemoteSession progress object. */
#if defined(RT_OS_WINDOWS)
/* uninitialize COM */
#endif
return VINF_SUCCESS;
}
/**
* Reconfigures a medium attachment (part of taking or deleting an online snapshot).
*
* @param pThis Reference to the console object.
* @param pUVM The VM handle.
* @param lInstance The instance of the controller.
* @param pcszDevice The name of the controller type.
* @param enmBus The storage bus type of the controller.
* @param fSetupMerge Whether to set up a medium merge
* @param uMergeSource Merge source image index
* @param uMergeTarget Merge target image index
* @param aMediumAtt The medium attachment.
* @param aMachineState The current machine state.
* @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
* @return VBox status code.
*/
/* static */
const char *pcszDevice,
unsigned uInstance,
bool fUseHostIOCache,
bool fBuiltinIOCache,
bool fSetupMerge,
unsigned uMergeSource,
unsigned uMergeTarget,
{
#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%Rhrc (%#x)\n", hrc, hrc)); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
/* Ignore attachments other than hard disks, since at the moment they are
* not subject to snapshotting in general. */
if (lType != DeviceType_HardDisk)
return VINF_SUCCESS;
/* Determine the base path for the device instance. */
if (enmBus == StorageBus_USB)
else
/* Update the device instance configuration. */
phrc,
true /* fAttachDetach */,
false /* fForceUnmount */,
false /* fHotplug */,
pUVM,
NULL /* paLedDevType */,
&pLunL0);
/* Dump the changed LUN if possible, dump the complete device otherwise */
if (RT_FAILURE(rc))
{
return rc;
}
#undef H
LogFlowFunc(("Returns success\n"));
return VINF_SUCCESS;
}
/**
* Progress cancelation callback employed by Console::fntTakeSnapshotWorker.
*/
static void takesnapshotProgressCancelCallback(void *pvUser)
{
}
/**
* Worker thread created by Console::TakeSnapshot.
* @param Thread The current thread (ignored).
* @param pvUser The task.
* @return VINF_SUCCESS (ignored).
*/
/*static*/
{
// taking a snapshot consists of the following:
// 1) creating a diff image for each virtual hard disk, into which write operations go after
// the snapshot has been created (done in VBoxSVC, in SessionMachine::BeginTakingSnapshot)
// 2) creating a Snapshot object with the state of the machine (hardware + storage,
// done in VBoxSVC, also in SessionMachine::BeginTakingSnapshot)
// 3) saving the state of the virtual machine (here, in the VM process, if the machine is online)
bool fBeganTakingSnapshot = false;
bool fSuspenededBySave = false;
{
return autoCaller.rc();
}
try
{
/* STEP 1 + 2:
* request creating the diff images on the server and create the snapshot object
* (this will set the machine state to Saving on the server to block
* others from accessing this machine)
*/
throw rc;
fBeganTakingSnapshot = true;
/* Check sanity: for offline snapshots there must not be a saved state
* file name. All other combinations are valid (even though online
* snapshots without saved state file seems inconsistent - there are
* some exotic use cases, which need to be explicitly enabled, see the
* code of SessionMachine::BeginTakingSnapshot. */
if ( !pTask->fTakingSnapshotOnline
/* sync the state with the server */
else
// STEP 3: save the VM state (if online)
if (pTask->fTakingSnapshotOnline)
{
int vrc;
// when setting up progress object
{
LogFlowFunc(("VMR3Save...\n"));
true /*fContinueAfterwards*/,
if (RT_FAILURE(vrc))
throw i_setErrorStatic(E_FAIL,
tr("Failed to save the machine state to '%s' (%Rrc)"),
}
else
LogRel(("Console: skipped saving state as part of online snapshot\n"));
// STEP 4: reattach hard disks
LogFlowFunc(("Reattaching new differencing hard disks...\n"));
1); // operation weight, same as computed when setting up progress object
throw rc;
for (size_t i = 0;
++i)
{
/*
* We can't pass a storage controller object directly
* (g++ complains about not being able to pass non POD types through '...')
* so we have to query needed values here and pass them.
*/
throw rc;
throw rc;
throw rc;
throw rc;
throw rc;
throw rc;
throw rc;
/*
* don't release the lock since reconfigureMediumAttachment
* isn't going to need the Console lock.
*/
if (RT_FAILURE(vrc))
throw rc;
}
}
/*
* finalize the requested snapshot object.
* This will reset the machine state to the state it had right
* before calling mControl->BeginTakingSnapshot().
*/
// do not throw rc here because we can't call EndTakingSnapshot() twice
LogFlowFunc(("EndTakingSnapshot -> %Rhrc [mMachineState=%s]\n", rc, Global::stringifyMachineState(that->mMachineState)));
}
{
/* preserve existing error info */
if (fBeganTakingSnapshot)
LogFunc(("Caught %Rhrc [mMachineState=%s]\n", rc, Global::stringifyMachineState(that->mMachineState)));
}
/*
* Fix up the machine state.
*
* For live snapshots we do all the work, for the two other variations we
* just update the local copy.
*/
{
if (!pTask->fTakingSnapshotOnline)
{
{
LogFlowFunc(("VMR3Resume...\n"));
if (RT_FAILURE(vrc))
{
}
}
else
}
else
{
/** @todo this could probably be made more generic and reused elsewhere. */
/* paranoid cleanup on for a failed online snapshot. */
switch (enmVMState)
{
case VMSTATE_RUNNING:
case VMSTATE_RUNNING_LS:
case VMSTATE_DEBUGGING:
case VMSTATE_DEBUGGING_LS:
case VMSTATE_POWERING_OFF:
case VMSTATE_POWERING_OFF_LS:
case VMSTATE_RESETTING:
case VMSTATE_RESETTING_LS:
break;
case VMSTATE_GURU_MEDITATION:
break;
case VMSTATE_FATAL_ERROR:
case VMSTATE_FATAL_ERROR_LS:
else
break;
default:
case VMSTATE_SUSPENDED:
case VMSTATE_SUSPENDED_LS:
case VMSTATE_SUSPENDING:
case VMSTATE_SUSPENDING_LS:
if (fSuspenededBySave)
{
LogFlowFunc(("VMR3Resume (on failure)...\n"));
if (RT_FAILURE(vrc))
}
else
break;
}
}
}
/*else: somebody else has change the state... Leave it. */
/* check the remote state to see that we got it right. */
delete pTask;
return VINF_SUCCESS;
}
/**
* Thread for executing the saved state operation.
*
* @param Thread The thread handle.
* @param pvUser Pointer to a VMSaveTask structure.
* @return VINF_SUCCESS (ignored).
*
* @note Locks the Console object for writing.
*/
/*static*/
{
bool fSuspenededBySave;
false, /*fContinueAfterwards*/
if (RT_FAILURE(vrc))
{
}
/* lock the console once we're going to access it */
/* synchronize the state with the server */
{
/*
* The machine has been successfully saved, so power it down
* (vmstateChangeCallback() will set state to Saved on success).
* Note: we release the task's VM caller, otherwise it will
* deadlock.
*/
task->releaseVMCaller();
}
/*
* If we failed, reset the local machine state.
*/
/*
* Finalize the requested save state procedure. In case of failure it will
* reset the machine state to the state it had right before calling
* mControl->BeginSavingState(). This must be the last thing because it
* will set the progress to completed, and that means that the frontend
* can immediately uninit the associated console object.
*/
return VINF_SUCCESS;
}
/**
* Thread for powering down the Console.
*
* @param Thread The thread handle.
* @param pvUser Pointer to the VMTask structure.
* @return VINF_SUCCESS (ignored).
*
* @note Locks the Console object for writing.
*/
/*static*/
{
/* Note: no need to use addCaller() to protect Console because VMTask does
* that */
/* wait until the method tat started us returns */
/* release VM caller to avoid the powerDown() deadlock */
task->releaseVMCaller();
/* complete the operation */
return VINF_SUCCESS;
}
/**
* @interface_method_impl{VMM2USERMETHODS,pfnSaveState}
*/
/*static*/ DECLCALLBACK(int)
{
/*
* For now, just call SaveState. We should probably try notify the GUI so
* it can pop up a progress object and stuff.
*/
}
/**
* @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtInit}
*/
/*static*/ DECLCALLBACK(void)
{
}
/**
* @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtTerm}
*/
/*static*/ DECLCALLBACK(void)
{
}
/**
* @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtInit}
*/
/*static*/ DECLCALLBACK(void)
{
}
/**
* @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtTerm}
*/
/*static*/ DECLCALLBACK(void)
{
}
/**
* @interface_method_impl{VMM2USERMETHODS,pfnNotifyResetTurnedIntoPowerOff}
*/
/*static*/ DECLCALLBACK(void)
{
pConsole->mfPowerOffCausedByReset = true;
}
/**
* @interface_method_impl{PDMISECKEY,pfnKeyRetain}
*/
/*static*/ DECLCALLBACK(int)
{
{
return VINF_SUCCESS;
}
return VERR_NOT_FOUND;
}
/**
* @interface_method_impl{PDMISECKEY,pfnKeyRelease}
*/
/*static*/ DECLCALLBACK(int)
{
{
return VINF_SUCCESS;
}
return VERR_NOT_FOUND;
}
/**
* The Main status driver instance data.
*/
typedef struct DRVMAINSTATUS
{
/** The LED connectors. */
/** Pointer to the LED ports interface above us. */
/** Pointer to the array of LED pointers. */
/** The unit number corresponding to the first entry in the LED array. */
/** The unit number corresponding to the last entry in the LED array.
* (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
/** Pointer to the driver instance. */
/** The Media Notify interface. */
/** Map for translating PDM storage controller/LUN information to
* IMediumAttachment references. */
/** Device name+instance for mapping */
char *pszDeviceInstance;
/** Pointer to the Console object, for driver triggered activities. */
/**
* Notification about a unit which have been changed.
*
* The driver must discard any pointers to data owned by
* the unit and requery it.
*
* @param pInterface Pointer to the interface structure containing the called function pointer.
* @param iLUN The unit number.
*/
{
{
if (RT_FAILURE(rc))
}
}
/**
* Notification about a medium eject.
*
* @returns VBox status.
* @param pInterface Pointer to the interface structure containing the called function pointer.
* @param uLUN The unit number.
*/
{
if (pThis->pmapMediumAttachments)
{
if (!pMediumAtt.isNull())
{
{
if (!fHostDrive)
{
if (pNewMediumAtt != pMediumAtt)
{
}
}
}
}
}
return VINF_SUCCESS;
}
/**
* @interface_method_impl{PDMIBASE,pfnQueryInterface}
*/
{
return NULL;
}
/**
* Destruct a status driver instance.
*
* @returns VBox status.
* @param pDrvIns The driver instance data.
*/
{
{
while (iLed-- > 0)
}
}
/**
* Construct a status driver instance.
*
* @copydoc FNPDMDRVCONSTRUCT
*/
DECLCALLBACK(int) Console::i_drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
{
/*
* Validate configuration.
*/
if (!CFGMR3AreValuesValid(pCfg, "papLeds\0pmapMediumAttachments\0DeviceInstance\0pConsole\0First\0Last\0"))
("Configuration error: Not possible to attach anything to this driver!\n"),
/*
* Data.
*/
/*
* Read config.
*/
if (RT_FAILURE(rc))
{
return rc;
}
rc = CFGMR3QueryPtrDef(pCfg, "pmapMediumAttachments", (void **)&pThis->pmapMediumAttachments, NULL);
if (RT_FAILURE(rc))
{
AssertMsgFailed(("Configuration error: Failed to query the \"pmapMediumAttachments\" value! rc=%Rrc\n", rc));
return rc;
}
if (pThis->pmapMediumAttachments)
{
if (RT_FAILURE(rc))
{
AssertMsgFailed(("Configuration error: Failed to query the \"DeviceInstance\" value! rc=%Rrc\n", rc));
return rc;
}
if (RT_FAILURE(rc))
{
return rc;
}
}
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
else if (RT_FAILURE(rc))
{
return rc;
}
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
else if (RT_FAILURE(rc))
{
return rc;
}
{
AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pThis->iFirstLUN, pThis->iLastLUN));
return VERR_GENERAL_FAILURE;
}
/*
* query the LEDs we want.
*/
return VINF_SUCCESS;
}
/**
* Console status driver (LED) registration record.
*/
{
/* u32Version */
/* szName */
"MainStatus",
/* szRCMod */
"",
/* szR0Mod */
"",
/* pszDescription */
"Main status driver (Main as in the API).",
/* fFlags */
/* fClass. */
/* cMaxInstances */
~0U,
/* cbInstance */
sizeof(DRVMAINSTATUS),
/* pfnConstruct */
/* pfnDestruct */
/* pfnRelocate */
NULL,
/* pfnIOCtl */
NULL,
/* pfnPowerOn */
NULL,
/* pfnReset */
NULL,
/* pfnSuspend */
NULL,
/* pfnResume */
NULL,
/* pfnAttach */
NULL,
/* pfnDetach */
NULL,
/* pfnPowerOff */
NULL,
/* pfnSoftReset */
NULL,
/* u32EndVersion */
};
/* vi: set tabstop=4 shiftwidth=4 expandtab: */