ConsoleImpl.cpp revision 832610bd2047de625db4d4e3b72c70466f40c5c1
/** @file
*
* VBox Console COM Class implementation
*/
/*
* Copyright (C) 2006 InnoTek Systemberatung GmbH
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* General Public License as published by the Free Software Foundation,
* in version 2 as it comes in the "COPYING" file of the VirtualBox OSE
* distribution. VirtualBox OSE is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY of any kind.
*
* If you received this file as part of a commercial VirtualBox
* distribution, then only the terms of your commercial VirtualBox
* license agreement apply instead of the previous paragraph.
*/
#if defined(__WIN__)
# include <errno.h>
#endif
#include "ConsoleImpl.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"
#include "AudioSnifferInterface.h"
#include "ConsoleVRDPServer.h"
#include "VMMDev.h"
// generated header
#include "SchemaDefs.h"
#include "Logging.h"
#include <set>
#include <algorithm>
#include <memory> // for auto_ptr
// 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 accidentially 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::mpVM caller with the same meaning as above. See
* Console::addVMCaller() for more info.
*/
struct VMTask
{
{
{
mCallerAdded = true;
if (aUsesVMPtr)
{
mVMCallerAdded = true;
}
}
}
~VMTask()
{
if (mVMCallerAdded)
if (mCallerAdded)
}
/** Releases the Console caller before destruction. Not normally necessary. */
void releaseCaller()
{
mCallerAdded = false;
}
/** Releases the VM caller before destruction. Not normally necessary. */
void releaseVMCaller()
{
mVMCallerAdded = false;
}
private:
bool mCallerAdded : 1;
bool mVMCallerAdded : 1;
};
struct VMProgressTask : public VMTask
{
};
struct VMPowerUpTask : public VMProgressTask
{
};
struct VMSaveTask : public VMProgressTask
{
, mIsSnapshot (false)
bool mIsSnapshot;
};
// constructor / desctructor
/////////////////////////////////////////////////////////////////////////////
: mSavedStateDataLoaded (false)
, mVMCallers (0)
, mVMDestroying (false)
, mAudioSniffer (NULL)
, mVMStateChangeCallbackDisabled (false)
{}
{}
{
LogFlowThisFunc (("\n"));
{
maTapFD[i] = NIL_RTFILE;
maTAPDeviceName[i] = "";
}
#endif
return S_OK;
}
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 */
#ifdef VBOX_VRDP
#endif
/* Create associated child COM objects */
/* Create other child objects */
#ifdef VRDP_MC
m_cAudioRefs = 0;
#endif /* VRDP_MC */
/* Confirm a successful initialization when it's the case */
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;
}
/*
* Uninit all children that ise addDependentChild()/removeDependentChild()
* in their init()/uninit() methods.
*/
/* This should be the first, since this may cause detaching remote USB devices. */
if (mConsoleVRDPServer)
{
delete mConsoleVRDPServer;
}
/* power down the VM if necessary */
if (mpVM)
{
powerDown();
}
if (mVMZeroCallersSem != NIL_RTSEMEVENT)
{
}
if (mAudioSniffer)
{
delete mAudioSniffer;
}
if (mVMMDev)
{
delete mVMMDev;
}
mUSBDevices.clear();
if (mRemoteDisplayInfo)
{
}
if (mDebugger)
{
}
if (mDisplay)
{
}
if (mMouse)
{
}
if (mKeyboard)
{
}
if (mGuest)
{
}
#ifdef VBOX_VRDP
#endif
/* Release all callbacks. Do this after uninitializing the components,
* as some of them are well-behaved and unregister their callbacks.
* These would trigger error messages complaining about trying to
* unregister a non-registered callback. */
mCallbacks.clear();
/* dynamically allocated members of mCallbackData are uninitialized
* at the end of powerDown() */
}
#ifdef VRDP_MC
const char *pszUser,
const char *pszPassword,
const char *pszDomain)
#else
const char *pszPassword,
const char *pszDomain)
#endif /* VRDP_MC */
{
#ifdef VRDP_MC
#else
#endif /* VRDP_MC */
if (!autoCaller.isOk())
{
/* Console has been already uninitialized, deny request */
LogRel(("VRDPAUTH: Access denied (Console uninitialized).\n"));
return VERR_ACCESS_DENIED;
}
ULONG authTimeout = 0;
LogRel (("VRDPAUTH: User: [%s]. Domain: [%s]. Authentication type: [%s]\n",
"null":
"external":
"guest":
"INVALID"
)
)
));
switch (authType)
{
{
break;
}
{
/* Call the external library. */
result = console->mConsoleVRDPServer->Authenticate (uuid, guestJudgement, pszUser, pszPassword, pszDomain);
if (result != VRDPAuthDelegateToGuest)
{
break;
}
LogRel(("VRDPAUTH: Delegated to guest.\n"));
LogFlowFunc (("External auth asked for guest judgement\n"));
} /* pass through */
{
{
/* Issue the request to guest. Assume that the call does not require EMT. It should not. */
/* Ask the guest to judge these credentials. */
if (VBOX_SUCCESS (rc))
{
/* Wait for guest. */
if (VBOX_SUCCESS (rc))
{
switch (u32GuestFlags & (VMMDEV_CREDENTIALS_JUDGE_OK | VMMDEV_CREDENTIALS_JUDGE_DENY | VMMDEV_CREDENTIALS_JUDGE_NOJUDGEMENT))
{
default:
}
}
else
{
}
}
else
{
}
}
{
result = console->mConsoleVRDPServer->Authenticate (uuid, guestJudgement, pszUser, pszPassword, pszDomain);
}
else
{
switch (guestJudgement)
{
break;
default:
break;
}
}
} break;
default:
AssertFailed();
}
if (result == VRDPAuthAccessGranted)
{
LogRel(("VRDPAUTH: Access granted.\n"));
return VINF_SUCCESS;
}
/* Reject. */
LogRel(("VRDPAUTH: Access denied.\n"));
return VERR_ACCESS_DENIED;
}
#ifdef VRDP_MC
#else
#endif /* VRDP_MC */
{
#ifdef VBOX_VRDP
#ifdef VRDP_MC
#else
#endif /* VRDP_MC */
#endif /* VBOX_VRDP */
return;
}
#ifdef VRDP_MC
#else
#endif /* VRDP_MC */
{
#ifdef VBOX_VRDP
#ifdef VRDP_MC
#else
#endif /* VRDP_MC */
#endif /* VBOX_VRDP */
#ifdef VRDP_MC
{
}
#else
#endif /* VRDP_MC */
#ifdef VBOX_VRDP
#ifdef VRDP_MC
{
console->m_cAudioRefs--;
if (console->m_cAudioRefs <= 0)
{
if (console->mAudioSniffer)
{
if (port)
{
}
}
}
}
#else
if (console->mAudioSniffer)
{
if (port)
{
}
}
#endif /* VRDP_MC */
#endif /* VBOX_VRDP */
return;
}
#ifdef VRDP_MC
#else
#endif /* VRDP_MC */
{
#ifdef VRDP_MC
LogFlowFunc (("mAudioSniffer %p, u32ClientId %d.\n",
#else
LogFlowFunc (("mAudioSniffer %p, keepHostAudio %d.\n",
#endif /* VRDP_MC */
#ifdef VBOX_VRDP
#ifdef VRDP_MC
console->m_cAudioRefs++;
{
if (console->mAudioSniffer)
{
if (port)
{
}
}
}
#else
if (console->mAudioSniffer)
{
if (port)
{
}
}
#endif /* VRDP_MC */
#endif
return;
}
#ifdef VRDP_MC
void **ppv)
#else
#endif /* VRDP_MC */
{
#ifdef VRDP_MC
#else
#endif /* VRDP_MC */
return;
}
// static
{
};
//static
//static
/**
* 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 (VBOX_SUCCESS (vrc))
{
if (version == sSSMConsoleVer)
{
if (VBOX_SUCCESS (vrc))
else if (vrc == VERR_SSM_UNIT_NOT_FOUND)
vrc = VINF_SUCCESS;
}
else
SSMR3Close (ssm);
}
if (VBOX_FAILURE (vrc))
tr ("The saved state file '%ls' is invalid (%Vrc). "
"Discard 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
DECLCALLBACK(void)
{
LogFlowFunc (("\n"));
++ it)
{
}
return;
}
/**
* Callback handler to load various console data from the state file.
* When \a u32Version is 0, this method is called from #loadDataFromSavedState,
* otherwise it is called when the VM is being restored from the saved state.
*
* @param pvUser pointer to Console
* @param u32Version Console unit version.
* When not 0, should match sSSMConsoleVer.
*
* @note Locks the Console object for writing.
*/
//static
DECLCALLBACK(int)
{
LogFlowFunc (("\n"));
return VERR_VERSION_MISMATCH;
if (u32Version != 0)
{
/* currently, nothing to do when we've been called from VMR3Load */
return VINF_SUCCESS;
}
{
delete[] buf;
delete[] buf;
return rc;
}
return VINF_SUCCESS;
}
// IConsole properties
/////////////////////////////////////////////////////////////////////////////
{
if (!aMachine)
return E_POINTER;
AutoCaller autoCaller (this);
/* mMachine is constant during life time, no need to lock */
return S_OK;
}
{
if (!aMachineState)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
/* we return our local state (since it's always the same as on the server) */
return S_OK;
}
{
if (!aGuest)
return E_POINTER;
AutoCaller autoCaller (this);
/* mGuest is constant during life time, no need to lock */
return S_OK;
}
{
if (!aKeyboard)
return E_POINTER;
AutoCaller autoCaller (this);
/* mKeyboard is constant during life time, no need to lock */
return S_OK;
}
{
if (!aMouse)
return E_POINTER;
AutoCaller autoCaller (this);
/* mMouse is constant during life time, no need to lock */
return S_OK;
}
{
if (!aDisplay)
return E_POINTER;
AutoCaller autoCaller (this);
/* mDisplay is constant during life time, no need to lock */
return S_OK;
}
{
if (!aDebugger)
return E_POINTER;
AutoCaller autoCaller (this);
/* 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;
}
{
if (!aUSBDevices)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
if (!aRemoteUSBDevices)
return E_POINTER;
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
return S_OK;
}
{
if (!aRemoteDisplayInfo)
return E_POINTER;
AutoCaller autoCaller (this);
/* mDisplay is constant during life time, no need to lock */
return S_OK;
}
{
if (!aSharedFolders)
return E_POINTER;
AutoCaller autoCaller (this);
/* loadDataFromSavedState() needs a write lock */
/* Read console data stored in the saved state file (if not yet done) */
coll.createObject();
return S_OK;
}
// IConsole methods
/////////////////////////////////////////////////////////////////////////////
{
AutoCaller autoCaller (this);
if (mMachineState >= MachineState_Running)
return setError(E_FAIL, tr ("Cannot power up the machine as it is already running. (Machine state: %d)"), mMachineState);
/*
* First check whether all disks are accessible. This is not a 100%
* bulletproof approach (race condition, it might become inaccessible
* right after the check) but it's convenient as it will cover 99.9%
* of the cases and here, we're able to provide meaningful error
* information.
*/
{
if (!fAccessible)
{
tr ("VM cannot start because the hard disk '%ls' is not accessible "
"(%ls)"),
}
}
/* now perform the same check if a ISO is mounted */
if (dvdImage)
{
if (!fAccessible)
{
/// @todo (r=dmik) grab the last access error once
// IDVDImage::lastAccessError is there
tr ("VM cannot start because the DVD image '%ls' is not accessible"),
}
}
/* now perform the same check if a floppy is mounted */
if (floppyImage)
{
if (!fAccessible)
{
/// @todo (r=dmik) grab the last access error once
// IDVDImage::lastAccessError is there
tr ("VM cannot start because the floppy image '%ls' is not accessible"),
}
}
/* now the network cards will undergo a quick consistency check */
{
if (!enabled)
continue;
switch (netattach)
{
{
#ifdef __WIN__
/* a valid host interface must have been set */
if (!hostif)
{
tr ("VM cannot start because host interface networking "
"requires a host interface name to be set"));
}
{
tr ("VM cannot start because the host interface '%ls' "
"does not exist"),
}
#endif /* __WIN__ */
break;
}
default:
break;
}
}
/* Read console data stored in the saved state file (if not yet done) */
{
}
/* Check all types of shared folders and compose a single list */
{
/// @todo (dmik) check and add globally shared folders when they are
// done
{
if (!accessible)
{
tr ("Host path '%ls' of the shared folder '%ls' is not accessible"),
}
/// @todo (dmik) later, do this:
// if (!sharedFolders.insert (std::pair <name, folder>).second)
// return setError (E_FAIL,
// tr ("Could not accept a permanently shared folder named '%ls' "
// "because a globally shared folder with the same name "
// "already exists"),
// name.raw());
}
{
tr ("Could not create a transient shared folder named '%ls' "
"because a global or a permanent shared folder with "
"the same name already exists"),
}
}
/*
* Saved VMs will have to prove that their saved states are kosher.
*/
if (mMachineState == MachineState_Saved)
{
if (VBOX_FAILURE (vrc))
tr ("VM cannot start because the saved state file '%ls' is invalid (%Vrc). "
"Discard the saved state prior to starting the VM"),
}
/* create an IProgress object to track progress of this operation */
if (mMachineState == MachineState_Saved)
else
/* pass reference to caller if requested */
if (aProgress)
/* setup task object and thread to carry out the operation asynchronously */
if (mMachineState == MachineState_Saved)
0, RTTHREADTYPE_MAIN_WORKER, 0, "VMPowerUp");
E_FAIL);
/* task is now owned by powerUpThread(), so release it */
if (mMachineState == MachineState_Saved)
else
return S_OK;
}
{
AutoCaller autoCaller (this);
if (mMachineState != MachineState_Running &&
{
/* extra nice error message for a common case */
if (mMachineState == MachineState_Saved)
else
return setError(E_FAIL, tr ("Cannot power off the machine as it is not running or paused. (Machine state: %d)"), mMachineState);
}
LogFlowThisFunc (("Sending SHUTDOWN request...\n"));
return rc;
}
{
AutoCaller autoCaller (this);
if (mMachineState != MachineState_Running)
return setError(E_FAIL, tr ("Cannot reset the machine as it is not running. (Machine state: %d)"), mMachineState);
/* protect mpVM */
AutoVMCaller autoVMCaller (this);
/* leave the lock before a VMR3* call (EMT will call us back)! */
return rc;
}
{
AutoCaller autoCaller (this);
if (mMachineState != MachineState_Running)
return setError (E_FAIL, tr ("Cannot pause the machine as it is not running. (Machine state: %d)"), mMachineState);
/* protect mpVM */
AutoVMCaller autoVMCaller (this);
LogFlowThisFunc (("Sending PAUSE request...\n"));
/* leave the lock before a VMR3* call (EMT will call us back)! */
return rc;
}
{
AutoCaller autoCaller (this);
if (mMachineState != MachineState_Paused)
return setError (E_FAIL, tr ("Cannot resume the machine as it is not paused. (Machine state: %d)"), mMachineState);
/* protect mpVM */
AutoVMCaller autoVMCaller (this);
LogFlowThisFunc (("Sending RESUME request...\n"));
/* leave the lock before a VMR3* call (EMT will call us back)! */
return rc;
}
{
AutoCaller autoCaller (this);
if (mMachineState != MachineState_Running)
return setError (E_FAIL, tr ("Cannot power off the machine as it is not running. (Machine state: %d)"), mMachineState);
/* protect mpVM */
AutoVMCaller autoVMCaller (this);
if (VBOX_SUCCESS (vrc))
{
}
return rc;
}
{
if (!aProgress)
return E_POINTER;
AutoCaller autoCaller (this);
if (mMachineState != MachineState_Running &&
{
tr ("Cannot save the machine state as the machine is not running or paused. (Machine state: %d)"), mMachineState);
}
/* memorize the current machine state */
if (mMachineState == MachineState_Running)
{
}
/* create a progress object to track operation completion */
FALSE /* aCancelable */);
bool beganSavingState = false;
bool taskCreationFailed = false;
do
{
/* create a task object early to ensure mpVM protection is successful */
/*
* If we fail here it means a PowerDown() call happened on another
* thread while we were doing Pause() (which leaves the Console lock).
* We assign PowerDown() a higher precendence than SaveState(),
* therefore just return the error to the caller.
*/
{
taskCreationFailed = true;
break;
}
/*
* 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)
*/
beganSavingState = true;
/* sync the state with the server */
/* ensure the directory for the saved state file exists */
{
if (!RTDirExists (dir))
{
if (VBOX_FAILURE (vrc))
{
tr ("Could not create a directory '%s' to save the state to. (Error: %Vrc)"),
break;
}
}
}
/* setup task object and thread to carry out the operation asynchronously */
task->mIsSnapshot = false;
/* set the state the operation thread will restore when it is finished */
/* create a thread to wait until the VM state is saved */
0, RTTHREADTYPE_MAIN_WORKER, 0, "VMSave");
/* task is now owned by saveStateThread(), so release it */
/* return the progress to the caller */
}
while (0);
{
/* fetch any existing error info */
if (beganSavingState)
{
/*
* 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 */
Resume();
}
else
/* restore fetched error info */
}
return rc;
}
{
AutoCaller autoCaller (this);
if (mMachineState != MachineState_Saved)
tr ("Cannot discard the machine state as the machine is not in the saved state. (Machine state: %d"), mMachineState);
/*
* Saved -> PoweredOff transition will be detected in the SessionMachine
* and properly handled.
*/
return S_OK;
}
/** read the value of a LEd. */
{
if (!pLed)
return 0;
return u32;
}
{
if (!aDeviceActivity)
return E_INVALIDARG;
AutoCaller autoCaller (this);
/*
* Note: we don't lock the console object here because
* readAndClearLed() should be thread safe.
*/
/* Get LED array to read */
PDMLEDCORE SumLed = {0};
switch (aDeviceType)
{
case DeviceType_FloppyDevice:
{
break;
}
case DeviceType_DVDDevice:
{
break;
}
{
break;
}
case DeviceType_NetworkDevice:
{
for (unsigned i = 0; i < ELEMENTS(mapNetworkLeds); i++)
break;
}
case DeviceType_USBDevice:
{
/// @todo (r=dmik)
// USB_DEVICE_ACTIVITY
break;
}
default:
return setError (E_INVALIDARG,
}
/* Compose the result */
{
case 0:
break;
case PDMLED_READING:
break;
case PDMLED_WRITING:
case PDMLED_READING | PDMLED_WRITING:
break;
}
return S_OK;
}
{
AutoCaller autoCaller (this);
/// @todo (r=dmik) is it legal to attach USB devices when the machine is
// Paused, Starting, Saving, Stopping, etc? if not, we should make a
// stricter check (mMachineState != MachineState_Running).
tr ("Cannot attach a USB device to a machine which is not running "
"(machine state: %d)"), mMachineState);
/* protect mpVM */
AutoVMCaller autoVMCaller (this);
/* Don't proceed unless we've found the usb controller. */
if (VBOX_FAILURE (vrc))
tr ("The virtual machine does not have a USB controller"));
/// @todo (dmik) REMOTE_USB
// when remote USB devices are ready, first search for a device with the
// given UUID in mRemoteUSBDevices. If found, request a capture from
// a remote client. If not found, search it on the local host as done below
/*
* Try attach the given host USB device (a proper errror message should
* be returned in case of error).
*/
}
{
if (!aDevice)
return E_POINTER;
AutoCaller autoCaller (this);
/* Find it. */
{
{
break;
}
++ it;
}
if (!device)
return setError (E_INVALIDARG,
tr ("Cannot detach the USB device (UUID: %s) as it is not attached here."),
/* protect mpVM */
AutoVMCaller autoVMCaller (this);
/* if the device is attached, then there must be a USB controller */
/* leave the lock before a VMR3* call (EMT will call us back)! */
if (VBOX_SUCCESS (vrc))
VMR3ReqFree (pReq);
if (VBOX_SUCCESS (vrc))
else
return hrc;
}
{
return E_INVALIDARG;
AutoCaller autoCaller (this);
if (mMachineState == MachineState_Saved)
tr ("Cannot create a transient shared folder on a "
"machine in the saved state."));
/// @todo (dmik) check globally shared folders when they are done
/* check machine's shared folders */
{
return rc;
tr ("A permanent shared folder named '%ls' already "
"exists."), aName);
}
if (!accessible)
/// @todo (r=sander?) should move this into the shared folder class */
{
/*
* if the VM is online and supports shared folders, share this folder
* under the specified name. On error, return it to the caller.
*/
/* protect mpVM */
AutoVMCaller autoVMCaller (this);
int cbString;
if (rc != VINF_SUCCESS)
}
return S_OK;
}
{
if (!aName)
return E_INVALIDARG;
AutoCaller autoCaller (this);
if (mMachineState == MachineState_Saved)
tr ("Cannot remove a transient shared folder when the "
"machine is in the saved state."));
/* protect mpVM */
AutoVMCaller autoVMCaller (this);
{
/*
* if the VM is online and supports shared folders, UNshare this folder.
* On error, return it to the caller.
*/
int cbString;
if (rc != VINF_SUCCESS)
}
return rc;
}
{
if (!aName)
return E_INVALIDARG;
if (!aProgress)
return E_POINTER;
AutoCaller autoCaller (this);
if (mMachineState > MachineState_Running &&
{
tr ("Cannot take a snapshot of a machine while it is changing state. (Machine state: %d)"), mMachineState);
}
/* memorize the current machine state */
if (mMachineState == MachineState_Running)
{
}
/*
* create a descriptionless VM-side progress object
* (only when creating a snapshot online)
*/
if (takingSnapshotOnline)
{
}
bool beganTakingSnapshot = false;
bool taskCreationFailed = false;
do
{
/* create a task object early to ensure mpVM protection is successful */
if (takingSnapshotOnline)
{
/*
* If we fail here it means a PowerDown() call happened on another
* thread while we were doing Pause() (which leaves the Console lock).
* We assign PowerDown() a higher precendence than TakeSnapshot(),
* therefore just return the error to the caller.
*/
{
taskCreationFailed = true;
break;
}
}
/*
* request taking a new snapshot object on the server
* (this will set the machine state to Saving on the server to block
* others from accessing this machine)
*/
break;
/*
* state file is non-null only when the VM is paused
* (i.e. createing a snapshot online)
*/
beganTakingSnapshot = true;
/* sync the state with the server */
/*
* create a combined VM-side progress object and start the save task
* (only when creating a snapshot online)
*/
if (takingSnapshotOnline)
{
/* setup task object and thread to carry out the operation asynchronously */
task->mIsSnapshot = true;
/* set the state the operation thread will restore when it is finished */
/* create a thread to wait until the VM state is saved */
0, RTTHREADTYPE_MAIN_WORKER, 0, "VMTakeSnap");
/* task is now owned by saveStateThread(), so release it */
}
{
/* return the correct progress to the caller */
if (combinedProgress)
else
}
}
while (0);
{
/* fetch any existing error info */
{
/*
* cancel the requested snapshot (only when creating a snapshot
* online, otherwise the server will cancel the snapshot itself).
* This will reset the machine state to the state it had right
* before calling mControl->BeginTakingSnapshot().
*/
}
if (lastMachineState == MachineState_Running)
{
/* restore the paused state if appropriate */
/* restore the running state if appropriate */
Resume();
}
else
/* restore fetched error info */
}
return rc;
}
{
return E_INVALIDARG;
if (!aProgress)
return E_POINTER;
AutoCaller autoCaller (this);
if (mMachineState >= MachineState_Running)
return S_OK;
}
{
AutoCaller autoCaller (this);
if (mMachineState >= MachineState_Running)
return S_OK;
}
{
AutoCaller autoCaller (this);
if (mMachineState >= MachineState_Running)
tr ("Cannot discard the current snapshot and state on a running machine. (Machine state: %d)"), mMachineState);
return S_OK;
}
{
if (!aCallback)
return E_INVALIDARG;
AutoCaller autoCaller (this);
/* Inform the callback about the current status (for example, the new
* callback must know the current mouse capabilities and the pointer
* shape in order to properly integrate the mouse pointer). */
return S_OK;
}
{
if (!aCallback)
return E_INVALIDARG;
AutoCaller autoCaller (this);
mCallbacks.end(),
return setError (E_INVALIDARG,
tr ("The given callback handler is not registered"));
return S_OK;
}
// Non-interface public methods
/////////////////////////////////////////////////////////////////////////////
/**
* Called by IInternalSessionControl::OnDVDDriveChange().
*
* @note Locks this object for reading.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
/* Ignore callbacks when there's no VM around */
if (!mpVM)
return S_OK;
/* protect mpVM */
AutoVMCaller autoVMCaller (this);
/* Get the current DVD state */
/* Paranoia */
if ( eState == DriveState_NotMounted
&& meDVDState == DriveState_NotMounted)
{
LogFlowThisFunc (("Returns (NotMounted -> NotMounted)\n"));
return S_OK;
}
/* Get the path string and other relevant properties */
bool fPassthrough = false;
switch (eState)
{
case DriveState_ImageMounted:
{
break;
}
{
fPassthrough = !!enabled;
break;
}
case DriveState_NotMounted:
break;
default:
break;
}
AssertComRC (rc);
{
return rc;
}
}
/**
* Called by IInternalSessionControl::OnFloppyDriveChange().
*
* @note Locks this object for reading.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
/* Ignore callbacks when there's no VM around */
if (!mpVM)
return S_OK;
/* protect mpVM */
AutoVMCaller autoVMCaller (this);
/* Get the current floppy state */
/* If the floppy drive is disabled, we're not interested */
if (!fEnabled)
return S_OK;
/* Paranoia */
if ( eState == DriveState_NotMounted
{
LogFlowThisFunc (("Returns (NotMounted -> NotMounted)\n"));
return S_OK;
}
/* Get the path string and other relevant properties */
switch (eState)
{
case DriveState_ImageMounted:
{
break;
}
{
break;
}
case DriveState_NotMounted:
break;
default:
break;
}
AssertComRC (rc);
{
return rc;
}
}
/**
* Process a floppy or dvd change.
*
* @returns COM status code.
*
* @param pszDevice The PDM device name.
* @param uInstance The PDM device instance.
* @param uLun The PDM LUN number of the drive.
* @param eState The new state.
* @param peState Pointer to the variable keeping the actual state of the drive.
* This will be both read and updated to eState or other appropriate state.
* @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 fPassthrough Enables using passthrough mode of the host DVD drive if applicable.
*
* @note Locks this object for reading.
*/
HRESULT Console::doDriveChange (const char *pszDevice, unsigned uInstance, unsigned uLun, DriveState_T eState,
{
LogFlowThisFunc (("pszDevice=%p:{%s} uInstance=%u uLun=%u eState=%d "
"peState=%p:{%d} pszPath=%p:{%s} fPassthrough=%d\n",
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
/* protect mpVM */
AutoVMCaller autoVMCaller (this);
/*
* 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.
*/
/// @todo (r=dmik) bird, it would be nice to have a special VMR3Req method
// for that purpose, that doesn't return useless VERR_TIMEOUT
if (vrc == VERR_TIMEOUT)
vrc = VINF_SUCCESS;
/* leave the lock before waiting for a result (EMT will call us back!) */
if (VBOX_SUCCESS (vrc))
{
if (VBOX_SUCCESS (vrc))
}
VMR3ReqFree (pReq);
if (VBOX_SUCCESS (vrc))
{
LogFlowThisFunc (("Returns S_OK\n"));
return S_OK;
}
if (pszPath)
}
/**
*
* @returns VBox status code.
*
* @param pThis Pointer to the Console object.
* @param pszDevice The PDM device name.
* @param uInstance The PDM device instance.
* @param uLun The PDM LUN number of the drive.
* @param eState The new state.
* @param peState Pointer to the variable keeping the actual state of the drive.
* This will be both read and updated to eState or other appropriate state.
* @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 fPassthrough Enables using passthrough mode of the host DVD drive if applicable.
*
* @thread EMT
* @note Locks the Console object for writing
*/
DECLCALLBACK(int) Console::changeDrive (Console *pThis, const char *pszDevice, unsigned uInstance, unsigned uLun,
const char *pszPath, bool fPassthrough)
{
LogFlowFunc (("pThis=%p pszDevice=%p:{%s} uInstance=%u uLun=%u eState=%d "
"peState=%p:{%d} pszPath=%p:{%s} fPassthrough=%d\n",
/*
* Locking the object before doing VMR3* calls is quite safe here,
* since we're on EMT. Write lock is necessary because we're indirectly
* modify the meDVDState/meFloppyState members (pointed to by peState).
*/
/* protect mpVM */
/*
* 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;
switch (enmVMState)
{
case VMSTATE_RESETTING:
case VMSTATE_RUNNING:
{
LogFlowFunc (("Suspending the VM...\n"));
/* disable the callback to prevent Console-level state change */
pThis->mVMStateChangeCallbackDisabled = true;
pThis->mVMStateChangeCallbackDisabled = false;
fResume = true;
break;
}
case VMSTATE_SUSPENDED:
case VMSTATE_CREATED:
case VMSTATE_OFF:
fResume = false;
break;
default:
}
int rc = VINF_SUCCESS;
int rcRet = VINF_SUCCESS;
do
{
/*
* Unmount existing media / detach host drive.
*/
switch (*peState)
{
case DriveState_ImageMounted:
{
/*
* Resolve the interface.
*/
if (VBOX_FAILURE (rc))
{
if (rc == VERR_PDM_LUN_NOT_FOUND)
rc = VINF_SUCCESS;
break;
}
/*
* Unmount the media.
*/
if (rc == VERR_PDM_MEDIA_NOT_MOUNTED)
rc = VINF_SUCCESS;
break;
}
{
if (rc == VINF_PDM_NO_DRIVER_ATTACHED_TO_LUN)
rc = VINF_SUCCESS;
break;
}
case DriveState_NotMounted:
break;
default:
break;
}
if (VBOX_FAILURE (rc))
{
break;
}
/*
* Nothing is currently mounted.
*/
/*
* Process the HostDriveCaptured state first, as the fallback path
* means mounting the normal block driver without media.
*/
if (eState == DriveState_HostDriveCaptured)
{
/*
* Detach existing driver chain (block).
*/
if (VBOX_FAILURE (rc))
{
if (rc == VERR_PDM_LUN_NOT_FOUND)
rc = VINF_SUCCESS;
break; /* we're toast */
}
/*
* Construct a new driver configuration.
*/
/* nuke anything which might have been left behind. */
/* create a new block driver config */
&& VBOX_SUCCESS (rc = CFGMR3InsertString (pLunL0, "Driver", !strcmp (pszDevice, "i82078") ? "HostFloppy" : "HostDVD"))
&& VBOX_SUCCESS (rc = !strcmp (pszDevice, "i82078") ? VINF_SUCCESS : CFGMR3InsertInteger(pCfg, "Passthrough", fPassthrough)))
{
/*
* Attempt to attach the driver.
*/
}
if (VBOX_FAILURE (rc))
}
/*
* Process the ImageMounted, NotMounted and failed HostDriveCapture cases.
*/
rc = VINF_SUCCESS;
switch (eState)
{
if (VBOX_SUCCESS (rcRet))
break;
/* fallback: umounted block driver. */
/* fallthru */
case DriveState_ImageMounted:
case DriveState_NotMounted:
{
/*
* Resolve the drive interface / create the driver.
*/
if (!pIMount)
{
if (rc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
{
/*
* We have to create it, so we'll do the full config setup and everything.
*/
/* nuke anything which might have been left behind. */
/* create a new block driver config */
RC_CHECK();
/*
* Attach the driver.
*/
RC_CHECK();
}
else if (VBOX_FAILURE(rc))
{
return rc;
}
if (!pIMount)
{
AssertFailed();
return rc;
}
}
/*
* If we've got an image, let's mount it.
*/
{
if (VBOX_FAILURE (rc))
}
break;
}
default:
break;
}
}
while (0);
/*
* Resume the VM if necessary.
*/
if (fResume)
{
LogFlowFunc (("Resuming the VM...\n"));
/* disable the callback to prevent Console-level state change */
pThis->mVMStateChangeCallbackDisabled = true;
pThis->mVMStateChangeCallbackDisabled = false;
if (VBOX_FAILURE (rc))
{
/* too bad, we failed. try to sync the console state with the VMM state */
}
/// @todo (r=dmik) if we failed with drive mount, then the VMR3Resume
// error (if any) will be hidden from the caller. For proper reporting
// of such multiple errors to the caller we need to enhance the
// IVurtualBoxError interface. For now, give the first error the higher
// priority.
if (VBOX_SUCCESS (rcRet))
}
return rcRet;
}
/**
* Called by IInternalSessionControl::OnNetworkAdapterChange().
*
* @note Locks this object for writing.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
/* Don't do anything if the VM isn't running */
if (!mpVM)
return S_OK;
/* protect mpVM */
AutoVMCaller autoVMCaller (this);
/* Get the properties we need from the adapter */
{
{
/*
* Find the pcnet instance, get the config interface and update the link state.
*/
if (VBOX_SUCCESS(rcVBox))
{
PPDMINETWORKCONFIG pINetCfg = (PPDMINETWORKCONFIG)pBase->pfnQueryInterface(pBase, PDMINTERFACE_NETWORK_CONFIG);
if (pINetCfg)
{
rcVBox = pINetCfg->pfnSetLinkState(pINetCfg, fCableConnected ? PDMNETWORKLINKSTATE_UP : PDMNETWORKLINKSTATE_DOWN);
}
}
}
}
return rc;
}
/**
* Called by IInternalSessionControl::OnVRDPServerChange().
*
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller (this);
{
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.
mConsoleVRDPServer->Stop ();
{
}
else
{
}
}
else
{
mConsoleVRDPServer->Stop ();
}
}
return rc;
}
/**
* Called by IInternalSessionControl::OnUSBControllerChange().
*
* @note Locks this object for writing.
*/
{
LogFlowThisFunc (("\n"));
AutoCaller autoCaller (this);
/* Ignore if no VM is running yet. */
if (!mpVM)
return S_OK;
/// @todo (dmik)
// check for the Enabled state and disable virtual USB controller??
// Anyway, if we want to query the machine's USB Controller we need to cache
// it to to mUSBController in #init() (as it is done with mDVDDrive).
//
// bird: While the VM supports hot-plugging, I doubt any guest can handle it at this time... :-)
//
// /* protect mpVM */
// AutoVMCaller autoVMCaller (this);
// CheckComRCReturnRC (autoVMCaller.rc());
return S_OK;
}
/**
* 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.
*
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller (this);
/* VM might have been stopped when this message arrives */
{
LogFlowThisFunc (("Attach request ignored (mMachineState=%d).\n",
return E_FAIL;
}
/* protect mpVM */
AutoVMCaller autoVMCaller (this);
/* Don't proceed unless we've found the usb controller. */
if (VBOX_FAILURE (vrc))
{
LogFlowThisFunc (("Attach request ignored (no USB controller).\n"));
return E_FAIL;
}
}
/**
* Called by IInternalSessionControl::OnUSBDeviceDetach() and locally by
* processRemoteUSBDevices().
*
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller (this);
/* Find the device. */
{
{
break;
}
++ it;
}
/* VM might have been stopped when this message arrives */
{
LogFlowThisFunc (("Device not found.\n"));
{
LogFlowThisFunc (("Detach request ignored (mMachineState=%d).\n",
return E_FAIL;
}
/* the device must be in the list */
}
/* protect mpVM */
AutoVMCaller autoVMCaller (this);
/* if the device is attached, then there must be a USB controller */
/* leave the lock before a VMR3* call (EMT will call us back)! */
if (VBOX_SUCCESS (vrc))
VMR3ReqFree (pReq);
}
/**
* 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 setMachineStateLocally (aMachineState);
}
/**
* @note Locks this object for writing.
*/
void *pShape)
{
LogFlowThisFunc (("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, "
"height=%d, shape=%p\n",
AutoCaller autoCaller (this);
/* We need a write lock because we alter the cached callback data */
/* save the callback arguments */
{
}
else
}
/**
* @note Locks this object for writing.
*/
{
LogFlowThisFunc (("supportsAbsolute=%d needsHostCursor=%d\n",
AutoCaller autoCaller (this);
/* We need a write lock because we alter the cached callback data */
/* save the callback arguments */
{
}
}
/**
* @note Locks this object for reading.
*/
{
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
}
/**
* @note Locks this object for reading.
*/
void Console::onAdditionsStateChange()
{
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
(*it++)->OnAdditionsStateChange();
}
/**
* @note Locks this object for reading.
*/
void Console::onAdditionsOutdated()
{
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
/** @todo Use the On-Screen Display feature to report the fact.
* The user should be told to install additions that are
* provided with the current VBox build:
* VBOX_VERSION_MAJOR.VBOX_VERSION_MINOR.VBOX_VERSION_BUILD
*/
}
/**
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller (this);
/* We need a write lock because we alter the cached callback data */
/* save the callback arguments */
}
/**
* @note Locks this object for reading.
*/
{
AutoCaller autoCaller (this);
AutoReaderLock alock (this);
}
// private mehtods
////////////////////////////////////////////////////////////////////////////////
/**
* Increases the usage counter of the mpVM 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 mpVM
* 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 mpVM avaliability).
*
* When mpVM 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 mpVM *NOT* to be NULL.
*
* @param aQuiet true to suppress setting error info
* @param aAllowNullVM true to accept mpVM being NULL and return a failure
* (otherwise this method will assert if mpVM is NULL)
*
* @note Locks this object for writing.
*/
bool aAllowNullVM /* = false */)
{
AutoCaller autoCaller (this);
if (mVMDestroying)
{
/* powerDown() is waiting for all callers to finish */
tr ("Virtual machine is being powered down"));
}
{
Assert (aAllowNullVM == true);
/* The machine is not powered up */
tr ("Virtual machine is not powered up"));
}
++ mVMCallers;
return S_OK;
}
/**
* Decreases the usage counter of the mpVM pointer. Must always complete
* the addVMCaller() call after the mpVM pointer is no more necessary.
*
* @note Locks this object for writing.
*/
void Console::releaseVMCaller()
{
AutoCaller autoCaller (this);
Assert (mVMCallers > 0);
-- mVMCallers;
if (mVMCallers == 0 && mVMDestroying)
{
/* inform powerDown() there are no more callers */
}
}
/**
* Internal power off worker routine.
*
* This method may be called only at certain places with the folliwing 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
* - 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 mpVM and sets
* it to 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);
/* sanity */
LogRel (("Console::powerDown(): a request to power off the VM has been issued "
"(mMachineState=%d, InUninit=%d)\n",
/* First, wait for all mpVM callers to finish their work if necessary */
if (mVMCallers > 0)
{
/* go to the destroying state to prevent from adding new callers */
mVMDestroying = true;
/* lazy creation */
if (mVMZeroCallersSem == NIL_RTSEMEVENT)
LogFlowThisFunc (("Waiting for mpVM callers (%d) to drop to zero...\n",
mVMCallers));
}
("Invalid machine state: %d\n", mMachineState));
int vrc = VINF_SUCCESS;
/*
* Power off the VM if not already done that. In case of Stopping, the VM
* has powered itself off and notified Console in vmstateChangeCallback().
* In case of Starting or Restoring, powerUpThread() is calling us on
* failure, so the VM is already off at that point.
*/
if (mMachineState != MachineState_Stopping &&
{
/*
* don't go from Saving to Stopping, vmstateChangeCallback needs it
* to set the state to Saved on VMSTATE_TERMINATED.
*/
if (mMachineState != MachineState_Saving)
LogFlowThisFunc (("Powering off the VM...\n"));
/* Leave the lock since EMT will call us back on VMR3PowerOff() */
/*
* 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.
*/
}
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?..)
*/
{
/*
* Stop the VRDP server and release all USB device.
* (When called from uninit mConsoleVRDPServer is already destroyed.)
*/
if (mConsoleVRDPServer)
{
LogFlowThisFunc (("Stopping VRDP server...\n"));
/* Leave the lock since EMT will call us back as addVMCaller in updateDisplayData(). */
}
/*
* Now we've got to destroy the VM as well. (mpVM is not valid
* beyond this point). We leave 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 mpVM). It's safe
* here because mVMDestroying is set which should prevent any activity.
*/
/*
* Set mpVM to NULL early just in case if some old code is not using
* addVMCaller()/releaseVMCaller().
*/
LogFlowThisFunc (("Destroying the VM...\n"));
/* take the lock again */
if (VBOX_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
* occured 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? */
}
}
else
{
}
/*
* Finished with destruction. Note that if something impossible happened
* and we've failed to destroy the VM, mVMDestroying will remain false and
* mMachineState will be something like Stopping, so most Console methods
* will return an error to the caller.
*/
mVMDestroying = false;
{
/* uninit dynamically allocated members of mCallbackData */
{
}
}
return rc;
}
/**
* @note Locks this object for writing.
*/
bool aUpdateServer /* = true */)
{
AutoCaller autoCaller (this);
if (mMachineState != aMachineState)
{
/// @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, that
* can lead to various unexpected results (like the machine state being
* >= MachineState_Running on the server, while the session state is
* already SessionState_SessionClosed 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 entered 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 */
bool found = false;
++ it)
{
if (found)
aSharedFolder = *it;
}
return rc;
}
/**
* VM state callback function. Called by the VMM
* using its state machine states.
*
* Primarily used to handle VM initiated power off, suspend and state saving,
* but also for doing termination completed work (VMSTATE_TERMINATE).
*
* In general this function is called in the context of the EMT.
*
* @param aVM The VM handle.
* @param aState The new state.
* @param aOldState The old state.
* @param aUser The user argument (pointer to the Console object).
*
* @note Locks the Console object for writing.
*/
DECLCALLBACK(void)
void *aUser)
{
LogFlowFunc (("Changing state from %d to %d (aVM=%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 (aState)
{
/*
* The VM has terminated
*/
case VMSTATE_OFF:
{
break;
/*
* Do we still think that it is running? It may happen if this is
*/
{
LogFlowFunc (("VM has powered itself off but Console still "
"thinks it is running. Notifying.\n"));
/* prevent powerDown() from calling VMR3PowerOff() again */
/*
* Setup task object and thread to carry out the operation
* asynchronously (if we call powerDown() right here but there
* is one or more mpVM callers (added with addVMCaller()) we'll
* deadlock.
*/
/*
* If creating a task is falied, 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"));
break;
}
"VMPowerDowm");
if (VBOX_FAILURE (vrc))
break;
/* 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 aVM is NULL, we've been
* manually called from powerUpThread() either before calling
* VMR3Create() or after VMR3Create() failed, so no need to touch
* networking.
*/
if (aVM)
/*
* 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 (note that the machine is already
* in the Saved state on the server due to EndSavingState()
* called from saveStateThread(), so only change the local
* state)
*/
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;
}
break;
}
case VMSTATE_SUSPENDED:
{
if (aOldState == VMSTATE_RUNNING)
{
break;
/* Change the machine state from Running to Paused */
}
}
case VMSTATE_RUNNING:
{
if (aOldState == VMSTATE_CREATED ||
{
break;
/*
* Change the machine state from Starting, Restoring or Paused
* to Running
*/
aOldState == VMSTATE_CREATED) ||
aOldState == VMSTATE_SUSPENDED));
}
}
default: /* shut up gcc */
break;
}
}
/**
* Sends a request to VMM to attach the given host device.
* After this method succeeds, the attached device will appear in the
* mUSBDevices collection.
*
* If \a aManual is true and a failure occures, the given device
* will be returned back to the USB proxy manager.
*
* @param aHostDevice device to attach
* @param aManual true if device is being manually attached
*
* @note Locks this object for writing.
* @note Synchronously calls EMT.
*/
{
/*
* Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
* method in EMT (using usbAttachCallback()).
*/
#ifndef VRDP_MC
if (fRemote)
{
}
#endif /* !VRDP_MC */
/* protect mpVM */
AutoVMCaller autoVMCaller (this);
LogFlowThisFunc (("Proxying USB device '%s' {%Vuuid}...\n",
/* leave the lock before a VMR3* call (EMT will call us back)! */
this, aHostDevice,
if (VBOX_SUCCESS (vrc))
VMR3ReqFree (pReq);
/* restore the lock */
/* hrc is S_OK here */
if (VBOX_FAILURE (vrc))
{
LogWarningThisFunc (("Failed to create proxy device for '%s' {%Vuuid} (%Vrc)\n",
if (aManual)
{
/*
* Neither SessionMachine::ReleaseUSBDevice() nor Host::releaseUSBDevice()
* should call the Console back, so keep the lock to provide atomicity
* (to protect Host reapplying USB filters)
*/
AssertComRC (hrc);
}
switch (vrc)
{
case VERR_VUSB_NO_PORTS:
tr ("Failed to attach the USB device. (No available ports on the USB controller)."));
break;
tr ("Not permitted to open the USB device, check usbfs options"));
break;
default:
break;
}
}
return hrc;
}
/**
* USB device attack 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)
const char *aAddress, void *aRemoteBackend)
{
#ifdef VRDP_MC
if (aRemote)
{
/* @todo aRemoteBackend input parameter is not needed. */
aRemoteBackend = that->consoleVRDPServer ()->USBBackendRequestPointer (pRemoteUSBDevice->clientId (), &guid);
if (aRemoteBackend == NULL)
{
/* The clientId is invalid then. */
return VERR_INVALID_PARAMETER;
}
}
#endif /* VRDP_MC */
if (VBOX_SUCCESS (vrc))
{
/* Create a OUSBDevice and add it to the device list */
AssertComRC (hrc);
}
return vrc;
}
/**
* USB device attack 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)
{
#ifdef VRDP_MC
/*
* If that was a remote device, release the backend pointer.
* The pointer was requested in usbAttachCallback.
*/
if (fRemote)
{
}
#endif /* VRDP_MC */
if (VBOX_SUCCESS (vrc))
{
/* Remove the device from the collection */
/// @todo (dmik) REMOTE_USB
// if the device is remote, notify a remote client that we have
// detached the device
/* If it's a manual detach, give it back to the USB Proxy */
if (aManual)
{
/*
* Neither SessionMachine::ReleaseUSBDevice() nor Host::releaseUSBDevice()
* should call the Console back, so keep the lock to provide atomicity
* (to protect Host reapplying USB filters)
*/
LogFlowFunc (("Giving it back it to USB proxy...\n"));
AssertComRC (hrc);
}
}
return vrc;
}
/**
* Construct the VM configuration tree (CFGM).
*
* This is a callback for VMR3Create() call. It is called from CFGMR3Init()
* is done here.
*
* @param pVM VM handle.
* @param pvTask Pointer to the VMPowerUpTask object.
* @return VBox status code.
*
* @note Locks the Console object for writing.
*/
{
/* Note: the task pointer is owned by powerUpThread() */
#if defined(__WIN__)
{
/* initialize COM */
}
#endif
/* lock the console because we widely use internal fields and methods */
int rc;
unsigned i;
#define STR_FREE() do { if (str) { SysFreeString(str); str = NULL; } if (psz) { RTStrFree(psz); psz = NULL; } } while (0)
#define RC_CHECK() do { if (VBOX_FAILURE(rc)) { AssertMsgFailed(("rc=%Vrc\n", rc)); STR_FREE(); return rc; } } while (0)
#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%#x\n", hrc)); STR_FREE(); return VERR_GENERAL_FAILURE; } } while (0)
/* Get necessary objects */
/*
* Get root node first.
* This is the only node in the tree.
*/
/*
* Set the root level values.
*/
STR_CONV();
STR_FREE();
/** @todo Config: RawR0, PATMEnabled and CASMEnabled needs attention later. */
/* hardware virtualization extensions */
if (hwVirtExEnabled == TriStateBool_Default)
{
/* check the default value */
}
else
if (fHWVirtExEnabled)
{
}
/*
* PDM config.
* Load drivers in VBoxC.[so|dll]
*/
#ifdef VBOX_WITH_XPCOM
// VBoxC is located in the components subdirectory
#else
#endif
/*
* Devices
*/
/*
* PC Arch.
*/
/*
* PC Bios.
*/
{
AssertMsgFailed (("Too many boot devices %d\n",
return VERR_INVALID_PARAMETER;
}
{
char szParamName[] = "BootDeviceX";
const char *pszBootDevice;
switch (bootDevice)
{
case DeviceType_NoDevice:
pszBootDevice = "NONE";
break;
pszBootDevice = "IDE";
break;
case DeviceType_DVDDevice:
pszBootDevice = "DVD";
break;
case DeviceType_FloppyDevice:
pszBootDevice = "FLOPPY";
break;
case DeviceType_NetworkDevice:
pszBootDevice = "LAN";
break;
default:
return VERR_INVALID_PARAMETER;
}
}
/*
* BIOS logo
*/
/*
* Boot menu
*/
int value;
switch (bootMenuMode)
{
value = 0;
break;
value = 1;
break;
default:
value = 2;
}
/*
* ACPI
*/
if (fACPI)
{
}
/*
* DMA
*/
/*
* PCI bus.
*/
/*
* PS/2 keyboard & mouse.
*/
/*
* i82078 Floppy drive controller
*/
if (fFloppyEnabled)
{
/* Attach the status driver */
if (floppyImage)
{
STR_CONV();
STR_FREE();
}
else
{
if (hostFloppyDrive)
{
STR_CONV();
STR_FREE();
}
else
{
}
}
}
/*
* i8254 Programmable Interval Timer And Dummy Speaker
*/
#ifdef DEBUG
#endif
/*
* i8259 Programmable Interrupt Controller.
*/
/*
* Advanced Programmable Interrupt Controller.
*/
if (fIOAPIC)
{
/*
* I/O Advanced Programmable Interrupt Controller.
*/
}
/*
* RTC MC146818.
*/
#if 0
/*
* Serial ports
*/
#endif
/*
* VGA.
*/
/* Custom VESA mode list */
unsigned cModes = 0;
{
char szExtraDataKey[sizeof("CustomVideoModeXX")];
break;
STR_CONV();
STR_FREE();
cModes++;
}
/* VESA height reduction */
/* Attach the display. */
/*
* IDE (update this when the main interface changes)
*/
/* Attach the status driver */
/* Attach the harddisks */
&& fMore)
{
switch (enmCtl)
{
i = 0;
break;
i = 2;
break;
default:
return VERR_GENERAL_FAILURE;
}
{
return VERR_GENERAL_FAILURE;
}
i = i + lDev;
char szLUN[16];
{
/// @todo (dmik) we temporarily use the location property to
// determine the image file name. This is subject to change
// when iSCSI disks are here (we should either query a
// storage-specific interface from IHardDisk, or "standardize"
// the location property)
STR_CONV();
STR_FREE();
/* Create an inversed tree of parents. */
{
if (!curHardDisk)
break;
/// @todo (dmik) we temporarily use the location property to
// determine the image file name. This is subject to change
// when iSCSI disks are here (we should either query a
// storage-specific interface from IHardDisk, or "standardize"
// the location property)
STR_CONV();
STR_FREE();
/* next */
}
}
else if (hddType == HardDiskStorageType_ISCSIHardDisk)
{
/* Set up the iSCSI initiator driver configuration. */
STR_CONV();
STR_FREE();
// @todo currently there is no Initiator name config.
STR_CONV();
if (port != 0)
{
char *pszTN;
}
else
{
}
STR_FREE();
if (str)
{
STR_CONV();
STR_FREE();
}
if (str)
{
STR_CONV();
STR_FREE();
}
// @todo currently there is no target username config.
//rc = CFGMR3InsertString(pCfg, "TargetUsername", ""); RC_CHECK();
// @todo currently there is no target password config.
//rc = CFGMR3InsertString(pCfg, "TargetSecret", ""); RC_CHECK();
/* The iSCSI initiator needs an attached iSCSI transport driver. */
/* Currently the transport driver has no config options. */
}
else
AssertFailed();
}
H();
if (dvdDrive)
{
// ASSUME: DVD drive is always attached to LUN#2 (i.e. secondary IDE master)
if (hostDvdDrive)
{
STR_CONV();
STR_FREE();
}
else
{
if (dvdImage)
{
STR_CONV();
STR_FREE();
}
}
}
/*
* Network adapters
*/
//rc = CFGMR3InsertNode(pDevices, "ne2000", &pDev); RC_CHECK();
{
if (!fEnabled)
continue;
/* the first network card gets the PCI ID 3, the followings starting from 8 */
/*
* The virtual hardware type.
*/
switch (adapterType)
{
break;
break;
default:
AssertMsgFailed(("Invalid network adapter type '%d' for slot '%d'",
return VERR_GENERAL_FAILURE;
}
/*
* Get the MAC address and convert it to binary representation
*/
for (uint32_t i = 0; i < 6; i++)
{
if (c1 > 9)
c1 -= 7;
if (c2 > 9)
c2 -= 7;
}
/*
* Check if the cable is supposed to be unplugged
*/
/*
* Attach the status driver.
*/
rc = CFGMR3InsertInteger(pCfg, "papLeds", (uintptr_t)&pConsole->mapNetworkLeds[ulInstance]); RC_CHECK();
/*
* Enable the packet sniffer if requested.
*/
if (fSniffer)
{
/* insert the sniffer filter driver. */
if (str) /* check convention for indicating default file. */
{
STR_CONV();
STR_FREE();
}
}
switch (networkAttachment)
{
break;
{
if (fSniffer)
{
}
else
{
}
/* (Port forwarding goes here.) */
break;
}
{
/*
* Perform the attachment if required (don't return on error!)
*/
{
{
if (fSniffer)
{
}
else
{
}
}
if (fSniffer)
{
}
else
{
}
{
}
else
{
char szDriverGUID[256] = {0};
/* add curly brackets */
szDriverGUID[0] = '{';
}
#else
# error "Port me"
#endif
}
else
{
switch (hrc)
{
#ifdef __LINUX__
case VERR_ACCESS_DENIED:
"change the group of that node and get member of that group. Make "
"sure that these changes are permanently in particular if you are "
"using udev"));
#endif /* __LINUX__ */
default:
AssertMsgFailed(("Could not attach to host interface! Bad!\n"));
"Failed to initialize Host Interface Networking"));
}
}
break;
}
{
STR_CONV();
{
if (fSniffer)
{
}
else
{
}
}
STR_FREE();
break;
}
default:
AssertMsgFailed(("should not get here!\n"));
break;
}
}
/*
* VMM Device
*/
/* the VMM device's Main driver */
/*
* Audio Sniffer Device
*/
/* the Audio Sniffer device's Main driver */
/*
* AC'97 ICH audio
*/
if (audioAdapter)
{
}
if (enabled)
{
/* the Audio driver */
switch (audioDriver)
{
{
break;
}
#ifdef __WIN__
{
break;
}
{
break;
}
#endif /* !__LINUX__ */
#ifdef __LINUX__
{
break;
}
#ifdef VBOX_WITH_ALSA
{
break;
}
#endif
#endif /* __LINUX__ */
}
}
/*
* The USB Controller.
*/
if (USBCtlPtr)
{
if (fEnabled)
{
}
}
/*
* Clipboard
*/
{
if (mode != ClipboardMode_ClipDisabled)
{
/* Load the service */
if (VBOX_FAILURE (rc))
{
/* That is not a fatal failure. */
rc = VINF_SUCCESS;
}
else
{
/* Setup the service. */
switch (mode)
{
default:
{
LogRel(("VBoxSharedClipboard mode: Off\n"));
break;
}
{
LogRel(("VBoxSharedClipboard mode: Guest to Host\n"));
break;
}
{
LogRel(("VBoxSharedClipboard mode: Host to Guest\n"));
break;
}
{
LogRel(("VBoxSharedClipboard mode: Bidirectional\n"));
break;
}
}
pConsole->mVMMDev->hgcmHostCall ("VBoxSharedClipboard", VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE, 1, &parm);
Log(("Set VBoxSharedClipboard mode\n"));
}
}
}
/*
* CFGM overlay handling.
*
* Here we check the extra data entries for CFGM values
* and create the nodes and insert the values on the fly. Existing
* values will be removed and reinserted. If a value is a valid number,
* it will be inserted as a number, otherwise as a string.
*
* We first perform a run on global extra data, then on the machine
* extra data to support global settings with local overrides.
*
*/
bool fGlobalExtraData = true;
for (;;)
{
/* get the next key */
if (fGlobalExtraData)
else
/* stop if for some reason there's nothing more to request */
{
/* if we're out of global keys, continue with machine, otherwise we're done */
if (fGlobalExtraData)
{
fGlobalExtraData = false;
continue;
}
break;
}
/* we only care about keys starting with "VBoxInternal/" */
continue;
if (pszCFGMValueName)
{
/* terminate the node and advance to the value */
*pszCFGMValueName = '\0';
/* does the node already exist? */
if (pNode)
{
/* the value might already exist, remove it to be safe */
}
else
{
/* create the node */
continue;
}
}
else
{
/* the value might already exist, remove it to be safe */
}
/* now let's have a look at the value */
/* empty value means remove value which we've already done */
if (pszCFGMValue && *pszCFGMValue)
{
/* if it's a valid number, we'll insert it as such, otherwise string */
{
}
else
{
}
}
}
#undef H
/* Register VM state change handler */
if (VBOX_SUCCESS (rc))
/* Register VM runtime error handler */
if (VBOX_SUCCESS (rc))
/* Save the VM pointer in the machine object */
return rc;
}
/**
* 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.
*/
{
/* sanity check */
#ifdef DEBUG
/* paranoia */
#endif /* DEBUG */
/*
* Try get the FD.
*/
else
/*
* Are we supposed to use an existing TAP interface?
*/
{
/* nothing to do */
}
else
#endif /* VBOX_WITH_UNIXY_TAP_NETWORKING */
{
/*
* Allocate a host interface device
*/
#ifdef __WIN__
/* nothing to do */
int rcVBox = VINF_SUCCESS;
if (VBOX_SUCCESS(rcVBox))
{
/*
*/
else
{
else
memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
}
if (!rcVBox)
{
/*
* Make it pollable.
*/
{
if (tapDeviceName)
{
/*
* Here is the right place to communicate the TAP file descriptor and
* necessary.
*/
}
else
}
else
{
AssertMsgFailed(("Configuration error: Failed to configure /dev/net/tun non blocking. errno=%d\n", errno));
}
}
else
{
}
}
else
{
switch (rcVBox)
{
case VERR_ACCESS_DENIED:
/* will be handled by our caller */
LogRel(("HERE\n"));
break;
default:
break;
}
}
#elif defined(__DARWIN__)
/** @todo Implement tap networking for Darwin. */
int rcVBox = VERR_NOT_IMPLEMENTED;
#elif defined(VBOX_WITH_UNIXY_TAP_NETWORKING)
#else
# error "Unknown host OS"
#endif
/* in case of failure, cleanup. */
{
}
}
{
/*
* Call the initialization program.
*
* The initialization program is passed the device name as the first param.
* The second parameter is the decimal value of the file handle of the device
* which it inherits.
*/
if (tapSetupApplication)
{
/*
* Create the argument list.
*/
const char *apszArgs[4];
/* 0. The program name. */
/* 1. The file descriptor. */
char szFD[32];
/* 2. The device name (optional). */
/* 3. The end. */
/*
* Create the process and wait for it to complete.
*/
if (VBOX_SUCCESS(rcVBox))
{
/* wait for the process to exit */
if (VBOX_SUCCESS(rcVBox))
{
&& ProcStatus.iStatus == 0)
else
rcVBox = VMSetError(mpVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_("Failed to initialize Host Interface Networking"));
}
}
else
{
AssertMsgFailed(("Configuration error: Failed to start init program \"%s\", rc=%Vra\n", tapSetupApp.raw(), rcVBox));
rc = setError(E_FAIL, "Failed to start init program \"%s\", rc = %Vra\n", tapSetupApp.raw(), rcVBox);
}
/* in case of failure, cleanup. */
{
}
}
}
#endif /* VBOX_WITH_UNIXY_TAP_NETWORKING */
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.
*/
{
/* sanity check */
#ifdef DEBUG
/* paranoia */
#endif /* DEBUG */
/* is there an open TAP device? */
{
/*
* Execute term command and close the file handle.
*/
{
/*
* Create the argument list
*/
const char *apszArgs[4];
/* 0. The program name. */
/* 1. The file descriptor. */
char szFD[32];
/* 2. Device name (optional). */
/* 3. The end. */
/*
* Create the process and wait for it to complete.
*/
if (VBOX_SUCCESS(rcVBox))
{
/* wait for the process to exit */
/* ignore return code? */
}
else
AssertMsgFailed(("Configuration error: Failed to start terminate program \"%s\", rc=%Vra\n", apszArgs[0], rcVBox)); /** @todo last error candidate. */
if (VBOX_FAILURE(rcVBox))
}
/*
* Now we can close the file handle.
*/
/* the TAP device name and handle are no longer valid */
}
#endif
return rc;
}
/**
* 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 (!enabled)
continue;
{
}
}
return rc;
}
/**
* Process callback handler for VMR3Load and VMR3Save.
*
* @param pVM The VM handle.
* @param uPercent Completetion precentage (0-100).
* @param pvUser Pointer to the VMProgressTask structure.
* @return VINF_SUCCESS.
*/
/*static*/ DECLCALLBACK (int)
{
/* update the progress object */
return VINF_SUCCESS;
}
/**
* VM error callback function. Called by the various VM components.
*
* @param pVM The VM handle. Can be NULL if an error occurred before
* successfully creating a VM.
* @param pvUser Pointer to the VMProgressTask structure.
* @param rc VBox status code.
* @param pszFormat The error message.
* @thread EMT.
*/
/* static */ DECLCALLBACK (void)
{
/* we ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users */
"VBox status code: %d (%Vrc)"),
}
/**
* VM runtime error callback function.
* See VMSetRuntimeError for the detailed description of parameters.
*
* @param pVM The VM handle.
* @param pvUser The user argument.
* @param fFatal Whether it is a fatal error or not.
* @param pszErrorID Error ID string.
* @param pszFormat Error message format string.
* @param args Error message arguments.
* @thread EMT.
*/
/* static */ DECLCALLBACK(void)
const char *pszErrorID,
{
LogRel (("Console: VM runtime error: fatal=%RTbool, "
"errorID=%s message=\"%s\"\n",
}
/**
* Captures and attaches USB devices to a newly created VM.
*
* @param pVM The VM handle.
*
* @note The caller must lock this object for writing.
*/
{
LogFlowThisFunc (("\n"));
/* sanity check */
/*
* If the machine has an USB controller, capture devices and attach
* them to it.
*/
if (VBOX_SUCCESS (vrc))
{
/*
* Get the list of USB devices that should be captured and attached to
* the newly created machine.
*/
/*
* Enumerate the devices and attach them.
* Failing to attach an device is currently ignored and the device
* released.
*/
{
/// @todo (r=dmik) warning reporting subsystem
}
}
else if ( vrc == VERR_PDM_DEVICE_NOT_FOUND
vrc = VINF_SUCCESS;
else
}
/**
* Releases all USB device which is attached to the VM for the
* purpose of clean up and such like.
*
* @note The caller must lock this object for writing.
*/
void Console::releaseAllUSBDevices (void)
{
LogFlowThisFunc (("\n"));
/* sanity check */
mUSBDevices.clear();
}
/**
* @note Locks this object for writing.
*/
#ifdef VRDP_MC
void Console::processRemoteUSBDevices (uint32_t u32ClientId, VRDPUSBDEVICEDESC *pDevList, uint32_t cbDevList)
#else
#endif /* VRDP_MC */
{
#ifdef VRDP_MC
LogFlowThisFunc (("u32ClientId = %d, pDevList=%p, cbDevList = %d\n", u32ClientId, pDevList, cbDevList));
#else
#endif /* VRDP_MC */
AutoCaller autoCaller (this);
if (!autoCaller.isOk())
{
/* Console has been already uninitialized, deny request */
AssertMsgFailed (("Temporary assertion to prove that it happens, "
"please report to dmik\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. */
VRDPUSBDEVICEDESC *e = pDevList;
/* The cbDevList condition must be checked first, because the function can
* receive pDevList = NULL and cbDevList = 0 on client disconnect.
*/
{
LogFlowThisFunc (("vendor %04X, product %04X, name = %s\n",
bool fNewDevice = true;
{
#ifdef VRDP_MC
#else
#endif /* VRDP_MC */
{
/* The device is already in the list. */
fNewDevice = false;
break;
}
++ it;
}
if (fNewDevice)
{
LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
));
/* Create the device object and add the new device to list. */
#ifdef VRDP_MC
#else
#endif /* VRDP_MC */
/* Check if the device is ok for current USB filters. */
AssertComRC (hrc);
if (fMatched)
{
/// @todo (r=dmik) warning reporting subsystem
{
LogFlowThisFunc (("Device attached\n"));
}
}
}
{
LogWarningThisFunc (("cbDevList %d > oNext %d\n",
break;
}
}
/*
* Remove dirty devices, that is those which are not reported by the server anymore.
*/
for (;;)
{
{
{
break;
}
++ it;
}
if (!device)
{
break;
}
LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
));
/* Detach the device from VM. */
{
}
/* And remove it from the list. */
}
}
/**
* 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*/
{
#if defined(__WIN__)
{
/* initialize COM */
}
#endif
int vrc = VINF_SUCCESS;
/* Note: no need to use addCaller() because VMPowerUpTask does that */
/* sanity */
do
{
/*
* 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().
*/
/* make sure the Logs folder exists */
if (!RTDirExists (logDir))
/*
* Age the old log files
* Rename .2 to .3, .1 to .2 and the last log file to .1
* Overwrite target files in case they exist;
*/
for (int i = 2; i >= 0; i--)
{
if (i > 0)
else
}
static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
#ifdef __WIN__
#endif /* __WIN__ */
if (VBOX_SUCCESS(vrc))
{
/* some introductory information */
char nowUct[64];
RTLogRelLogger(loggerRelease, 0, ~0U,
"VirtualBox %d.%d.%d (%s %s) release log\n"
"Log opened %s\n",
nowUct);
/* register this logger as the release logger */
}
else
{
tr ("Failed to open release log file '%s' (%Vrc)"),
break;
}
#ifdef VBOX_VRDP
if (VBOX_SUCCESS (vrc))
{
/* Create the VRDP server. In case of headless operation, this will
* also create the framebuffer, required at VM creation.
*/
/// @todo (dmik)
// does VRDP server call Console from the other thread?
// Not sure, so leave the lock just in case
if (VBOX_FAILURE (vrc))
{
switch (vrc)
{
case VERR_NET_ADDRESS_IN_USE:
{
port);
break;
}
default:
vrc);
}
LogRel (("Failed to launch VRDP server (%Vrc), error message: '%s'\n",
break;
}
}
#endif /* VBOX_VRDP */
/*
* Create the VM
*/
/*
* leave the lock since EMT will call Console. It's safe because
* mMachineState is either Starting or Restoring state here.
*/
&pVM);
#ifdef VBOX_VRDP
{
/* Enable client connections to the server. */
server->SetCallback ();
}
#endif /* VBOX_VRDP */
if (VBOX_SUCCESS (vrc))
{
do
{
/*
*/
0 /* cbGuess */,
if (VBOX_FAILURE (vrc))
break;
/*
* Synchronize debugger settings
*/
if (machineDebugger)
{
}
{
/// @todo (dmik)
// does the code below call Console from the other thread?
// Not sure, so leave the lock just in case
/*
* Shared Folders
*/
++ it)
{
LogFlowFunc (("Adding shared folder '%ls' -> '%ls'\n",
/** @todo should move this into the shared folder class */
int cbString;
if (VBOX_FAILURE (vrc))
{
tr ("Unable to add mapping '%ls' to '%ls' (%Vrc)"),
break;
}
}
/* enter the lock again */
}
/*
* Capture USB devices.
*/
/* leave the lock before a lengthy operation */
/* Load saved state? */
if (!!task->mSavedStateFile)
{
LogFlowFunc (("Restoring saved state from '%s'...\n",
if (VBOX_SUCCESS (vrc))
{
}
/* Power off in case we failed loading or resuming the VM */
if (VBOX_FAILURE (vrc))
{
}
}
else
{
/* Power on the VM (i.e. start executing) */
}
/* enter the lock again */
}
while (0);
/* On failure, destroy the VM */
{
/* preserve the current error info */
/*
* powerDown() will call VMR3Destroy() and do all necessary
* cleanup (VRDP, USB devices)
*/
AssertComRC (hrc2);
}
}
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 already set. However since
* that happens via a callback, the status code in this function is
* not updated.
*/
{
/*
* If the COM error info is not yet 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.
* Note that we don't use VMSetError() below because pVM is
* either invalid or NULL here.
*/
AssertMsgFailed (("Missing error message during powerup for "
"status code %Vrc\n", vrc));
}
else
break;
}
}
while (0);
{
/*
* 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 the current error info */
console);
}
/*
* Evaluate the final result.
* Note that the appropriate mMachineState value is already set by
* vmstateChangeCallback() in all cases.
*/
/* leave 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. This
* gets the errors signalled by using setError(). The ones
* signalled via VMSetError() immediately notify the progress
* object that the operation is completed. */
}
}
#if defined(__WIN__)
/* uninitialize COM */
#endif
return VINF_SUCCESS;
}
/**
* Reconfigures a VDI.
*
* @param pVM The VM handle.
* @param hda The harddisk attachment.
* @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
* @return VBox status code.
*/
{
int rc;
#define STR_FREE() do { if (str) { SysFreeString(str); str = NULL; } if (psz) { RTStrFree(psz); psz = NULL; } } while (0)
#define RC_CHECK() do { if (VBOX_FAILURE(rc)) { AssertMsgFailed(("rc=%Vrc\n", rc)); STR_FREE(); return rc; } } while (0)
#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%#x\n", hrc)); STR_FREE(); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
/*
* Figure out which IDE device this is.
*/
int i;
switch (enmCtl)
{
i = 0;
break;
i = 2;
break;
default:
return VERR_GENERAL_FAILURE;
}
{
return VERR_GENERAL_FAILURE;
}
i = i + lDev;
/*
* Is there an existing LUN? If not create it.
* We ASSUME that this will NEVER collide with the DVD.
*/
PCFGMNODE pLunL1 = CFGMR3GetChildF(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/LUN#%d/AttachedDriver/", i);
if (!pLunL1)
{
}
else
{
#ifdef VBOX_STRICT
char *pszDriver;
#endif
/*
* Check if things has changed.
*/
/* the image */
/// @todo (dmik) we temporarily use the location property to
// determine the image file name. This is subject to change
// when iSCSI disks are here (we should either query a
// storage-specific interface from IHardDisk, or "standardize"
// the location property)
STR_CONV();
char *pszPath;
{
/* parent images. */
{
STR_FREE();
/* get parent */
if (!pCur && !curHardDisk)
{
/* no change */
LogFlowFunc (("No change!\n"));
return VINF_SUCCESS;
}
if (!pCur || !curHardDisk)
break;
/* compare paths. */
/// @todo (dmik) we temporarily use the location property to
// determine the image file name. This is subject to change
// when iSCSI disks are here (we should either query a
// storage-specific interface from IHardDisk, or "standardize"
// the location property)
STR_CONV();
break;
/* next */
}
}
else
STR_FREE();
/*
* Detach the driver and replace the config node.
*/
}
/*
* Create the driver configuration.
*/
/// @todo (dmik) we temporarily use the location property to
// determine the image file name. This is subject to change
// when iSCSI disks are here (we should either query a
// storage-specific interface from IHardDisk, or "standardize"
// the location property)
STR_CONV();
STR_FREE();
/* Create an inversed tree of parents. */
{
if (!curHardDisk)
break;
/// @todo (dmik) we temporarily use the location property to
// determine the image file name. This is subject to change
// when iSCSI disks are here (we should either query a
// storage-specific interface from IHardDisk, or "standardize"
// the location property)
STR_CONV();
STR_FREE();
/* next */
}
/*
* Attach the new driver.
*/
LogFlowFunc (("Returns success\n"));
return rc;
}
/**
* 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*/
{
/*
* Note: no need to use addCaller() to protect Console or addVMCaller() to
* protect mpVM because VMSaveTask does that
*/
if (task->mIsSnapshot)
{
LogFlowFunc (("Waiting until the server creates differencing VDIs...\n"));
{
}
}
{
if (VBOX_FAILURE (vrc))
{
errMsg = Utf8StrFmt (
}
}
/* lock the console sonce we're going to access it */
{
if (task->mIsSnapshot)
do
{
LogFlowFunc (("Reattaching new differencing VDIs...\n"));
break;
break;
{
break;
/*
* don't leave the lock since reconfigureVDI isn't going to
* access Console.
*/
if (VBOX_SUCCESS (rc))
VMR3ReqFree (pReq);
break;
if (VBOX_FAILURE (vrc))
{
break;
}
}
}
while (0);
}
/* finalize the procedure regardless of the result */
if (task->mIsSnapshot)
{
/*
* finalize the requested snapshot object.
* This will reset the machine state to the state it had right
* before calling mControl->BeginTakingSnapshot().
*/
}
else
{
/*
* finalize the requested save state procedure.
* In case of success, the server will set the machine state to Saved;
* in case of failure it will reset the it to the state it had right
* before calling mControl->BeginSavingState().
*/
}
/* synchronize the state with the server */
{
{
/* restore the paused state if appropriate */
/* restore the running state if appropriate */
}
else
}
else
{
/*
* 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();
}
/* notify the progress object about operation completion */
else
{
else
}
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
*/
/* release VM caller to let powerDown() proceed */
task->releaseVMCaller();
AssertComRC (rc);
return VINF_SUCCESS;
}
/**
* 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.) */
/**
* 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 (VBOX_FAILURE(rc))
}
}
/**
* Queries an interface to the driver.
*
* @returns Pointer to interface.
* @returns NULL if the interface was not supported by the driver.
* @param pInterface Pointer to this interface structure.
* @param enmInterface The requested interface identification.
*/
DECLCALLBACK(void *) Console::drvStatus_QueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
{
switch (enmInterface)
{
case PDMINTERFACE_BASE:
return &pDrv->ILedConnectors;
default:
return NULL;
}
}
/**
* Destruct a status driver instance.
*
* @returns VBox status.
* @param pDrvIns The driver instance data.
*/
{
{
while (iLed-- > 0)
}
}
/**
* Construct a status driver instance.
*
* @returns VBox status.
* @param pDrvIns The driver instance data.
* If the registration structure is needed, pDrvIns->pDrvReg points to it.
* @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
* of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
* iInstance it's expected to be used a bit in this function.
*/
{
/*
* Validate configuration.
*/
if (rc != VERR_PDM_NO_ATTACHED_DRIVER)
{
AssertMsgFailed(("Configuration error: Not possible to attach anything to this driver!\n"));
return VERR_PDM_DRVINS_NO_ATTACH;
}
/*
* Data.
*/
/*
* Read config.
*/
if (VBOX_FAILURE(rc))
{
return rc;
}
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
else if (VBOX_FAILURE(rc))
{
return rc;
}
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
else if (VBOX_FAILURE(rc))
{
return rc;
}
{
AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pData->iFirstLUN, pData->iLastLUN));
return VERR_GENERAL_FAILURE;
}
/*
* query the LEDs we want.
*/
pData->pLedPorts = (PPDMILEDPORTS)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_LED_PORTS);
{
AssertMsgFailed(("Configuration error: No led ports interface above!\n"));
return VERR_PDM_MISSING_INTERFACE_ABOVE;
}
return VINF_SUCCESS;
}
/**
* Keyboard driver registration record.
*/
{
/* u32Version */
/* szDriverName */
"MainStatus",
/* pszDescription */
"Main status driver (Main as in the API).",
/* fFlags */
/* fClass. */
/* cMaxInstances */
~0,
/* cbInstance */
sizeof(DRVMAINSTATUS),
/* pfnConstruct */
/* pfnDestruct */
/* pfnIOCtl */
NULL,
/* pfnPowerOn */
NULL,
/* pfnReset */
NULL,
/* pfnSuspend */
NULL,
/* pfnResume */
NULL,
/* pfnDetach */
};