VirtualBox

source: vbox/trunk/src/VBox/Main/MachineImpl.cpp@ 23599

Last change on this file since 23599 was 23599, checked in by vboxsync, 15 years ago

Main: Live migration work.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 346.9 KB
Line 
1/* $Id: MachineImpl.cpp 23599 2009-10-07 17:24:18Z vboxsync $ */
2
3/** @file
4 * Implementation of IMachine in VBoxSVC.
5 */
6
7/*
8 * Copyright (C) 2006-2009 Sun Microsystems, Inc.
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.virtualbox.org. This file is free software;
12 * you can redistribute it and/or modify it under the terms of the GNU
13 * General Public License (GPL) as published by the Free Software
14 * Foundation, in version 2 as it comes in the "COPYING" file of the
15 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
16 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
17 *
18 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
19 * Clara, CA 95054 USA or visit http://www.sun.com if you need
20 * additional information or have any questions.
21 */
22
23/* Make sure all the stdint.h macros are included - must come first! */
24#ifndef __STDC_LIMIT_MACROS
25# define __STDC_LIMIT_MACROS
26#endif
27#ifndef __STDC_CONSTANT_MACROS
28# define __STDC_CONSTANT_MACROS
29#endif
30
31#ifdef VBOX_WITH_SYS_V_IPC_SESSION_WATCHER
32# include <errno.h>
33# include <sys/types.h>
34# include <sys/stat.h>
35# include <sys/ipc.h>
36# include <sys/sem.h>
37#endif
38
39#include "VirtualBoxImpl.h"
40#include "MachineImpl.h"
41#include "ProgressImpl.h"
42#include "MediumAttachmentImpl.h"
43#include "MediumImpl.h"
44#include "USBControllerImpl.h"
45#include "HostImpl.h"
46#include "SharedFolderImpl.h"
47#include "GuestOSTypeImpl.h"
48#include "VirtualBoxErrorInfoImpl.h"
49#include "GuestImpl.h"
50#include "StorageControllerImpl.h"
51
52#ifdef VBOX_WITH_USB
53# include "USBProxyService.h"
54#endif
55
56#include "Logging.h"
57#include "Performance.h"
58
59#include <stdio.h>
60#include <stdlib.h>
61
62#include <iprt/path.h>
63#include <iprt/dir.h>
64#include <iprt/asm.h>
65#include <iprt/process.h>
66#include <iprt/cpputils.h>
67#include <iprt/env.h>
68#include <iprt/string.h>
69
70#include <VBox/com/array.h>
71
72#include <VBox/err.h>
73#include <VBox/param.h>
74#include <VBox/settings.h>
75
76#ifdef VBOX_WITH_GUEST_PROPS
77# include <VBox/HostServices/GuestPropertySvc.h>
78# include <VBox/com/array.h>
79#endif
80
81#include <algorithm>
82
83#include <typeinfo>
84
85#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
86#define HOSTSUFF_EXE ".exe"
87#else /* !RT_OS_WINDOWS */
88#define HOSTSUFF_EXE ""
89#endif /* !RT_OS_WINDOWS */
90
91// defines / prototypes
92/////////////////////////////////////////////////////////////////////////////
93
94// globals
95/////////////////////////////////////////////////////////////////////////////
96
97/**
98 * Progress callback handler for lengthy operations
99 * (corresponds to the FNRTPROGRESS typedef).
100 *
101 * @param uPercentage Completetion precentage (0-100).
102 * @param pvUser Pointer to the Progress instance.
103 */
104static DECLCALLBACK(int) progressCallback(unsigned uPercentage, void *pvUser)
105{
106 Progress *progress = static_cast<Progress*>(pvUser);
107
108 /* update the progress object */
109 if (progress)
110 progress->SetCurrentOperationProgress(uPercentage);
111
112 return VINF_SUCCESS;
113}
114
115/////////////////////////////////////////////////////////////////////////////
116// Machine::Data structure
117/////////////////////////////////////////////////////////////////////////////
118
119Machine::Data::Data()
120{
121 mRegistered = FALSE;
122 mAccessible = FALSE;
123 /* mUuid is initialized in Machine::init() */
124
125 mMachineState = MachineState_PoweredOff;
126 RTTimeNow(&mLastStateChange);
127
128 mMachineStateDeps = 0;
129 mMachineStateDepsSem = NIL_RTSEMEVENTMULTI;
130 mMachineStateChangePending = 0;
131
132 mCurrentStateModified = TRUE;
133 mHandleCfgFile = NIL_RTFILE;
134
135 mSession.mPid = NIL_RTPROCESS;
136 mSession.mState = SessionState_Closed;
137}
138
139Machine::Data::~Data()
140{
141 if (mMachineStateDepsSem != NIL_RTSEMEVENTMULTI)
142 {
143 RTSemEventMultiDestroy(mMachineStateDepsSem);
144 mMachineStateDepsSem = NIL_RTSEMEVENTMULTI;
145 }
146}
147
148/////////////////////////////////////////////////////////////////////////////
149// Machine::UserData structure
150/////////////////////////////////////////////////////////////////////////////
151
152Machine::UserData::UserData()
153{
154 /* default values for a newly created machine */
155
156 mNameSync = TRUE;
157 mLiveMigrationTarget = FALSE;
158 mLiveMigrationPort = 0;
159
160 /* mName, mOSTypeId, mSnapshotFolder, mSnapshotFolderFull are initialized in
161 * Machine::init() */
162}
163
164Machine::UserData::~UserData()
165{
166}
167
168/////////////////////////////////////////////////////////////////////////////
169// Machine::HWData structure
170/////////////////////////////////////////////////////////////////////////////
171
172Machine::HWData::HWData()
173{
174 /* default values for a newly created machine */
175 mHWVersion = "2"; /** @todo get the default from the schema if that is possible. */
176 mMemorySize = 128;
177 mCPUCount = 1;
178 mMemoryBalloonSize = 0;
179 mStatisticsUpdateInterval = 0;
180 mVRAMSize = 8;
181 mAccelerate3DEnabled = false;
182 mAccelerate2DVideoEnabled = false;
183 mMonitorCount = 1;
184 mHWVirtExEnabled = true;
185 mHWVirtExNestedPagingEnabled = false;
186 mHWVirtExVPIDEnabled = false;
187 mPAEEnabled = false;
188 mPropertyServiceActive = false;
189
190 /* default boot order: floppy - DVD - HDD */
191 mBootOrder [0] = DeviceType_Floppy;
192 mBootOrder [1] = DeviceType_DVD;
193 mBootOrder [2] = DeviceType_HardDisk;
194 for (size_t i = 3; i < RT_ELEMENTS (mBootOrder); ++i)
195 mBootOrder [i] = DeviceType_Null;
196
197 mClipboardMode = ClipboardMode_Bidirectional;
198 mGuestPropertyNotificationPatterns = "";
199
200 mFirmwareType = FirmwareType_BIOS;
201}
202
203Machine::HWData::~HWData()
204{
205}
206
207bool Machine::HWData::operator==(const HWData &that) const
208{
209 if (this == &that)
210 return true;
211
212 if (mHWVersion != that.mHWVersion ||
213 mMemorySize != that.mMemorySize ||
214 mMemoryBalloonSize != that.mMemoryBalloonSize ||
215 mStatisticsUpdateInterval != that.mStatisticsUpdateInterval ||
216 mVRAMSize != that.mVRAMSize ||
217 mFirmwareType != that.mFirmwareType ||
218 mAccelerate3DEnabled != that.mAccelerate3DEnabled ||
219 mAccelerate2DVideoEnabled != that.mAccelerate2DVideoEnabled ||
220 mMonitorCount != that.mMonitorCount ||
221 mHWVirtExEnabled != that.mHWVirtExEnabled ||
222 mHWVirtExNestedPagingEnabled != that.mHWVirtExNestedPagingEnabled ||
223 mHWVirtExVPIDEnabled != that.mHWVirtExVPIDEnabled ||
224 mPAEEnabled != that.mPAEEnabled ||
225 mCPUCount != that.mCPUCount ||
226 mClipboardMode != that.mClipboardMode)
227 return false;
228
229 for (size_t i = 0; i < RT_ELEMENTS (mBootOrder); ++i)
230 if (mBootOrder [i] != that.mBootOrder [i])
231 return false;
232
233 if (mSharedFolders.size() != that.mSharedFolders.size())
234 return false;
235
236 if (mSharedFolders.size() == 0)
237 return true;
238
239 /* Make copies to speed up comparison */
240 SharedFolderList folders = mSharedFolders;
241 SharedFolderList thatFolders = that.mSharedFolders;
242
243 SharedFolderList::iterator it = folders.begin();
244 while (it != folders.end())
245 {
246 bool found = false;
247 SharedFolderList::iterator thatIt = thatFolders.begin();
248 while (thatIt != thatFolders.end())
249 {
250 if ( (*it)->name() == (*thatIt)->name()
251 && RTPathCompare(Utf8Str((*it)->hostPath()).c_str(),
252 Utf8Str((*thatIt)->hostPath()).c_str()
253 ) == 0)
254 {
255 thatFolders.erase (thatIt);
256 found = true;
257 break;
258 }
259 else
260 ++thatIt;
261 }
262 if (found)
263 it = folders.erase (it);
264 else
265 return false;
266 }
267
268 Assert (folders.size() == 0 && thatFolders.size() == 0);
269
270 return true;
271}
272
273/////////////////////////////////////////////////////////////////////////////
274// Machine::HDData structure
275/////////////////////////////////////////////////////////////////////////////
276
277Machine::MediaData::MediaData()
278{
279}
280
281Machine::MediaData::~MediaData()
282{
283}
284
285bool Machine::MediaData::operator== (const MediaData &that) const
286{
287 if (this == &that)
288 return true;
289
290 if (mAttachments.size() != that.mAttachments.size())
291 return false;
292
293 if (mAttachments.size() == 0)
294 return true;
295
296 /* Make copies to speed up comparison */
297 AttachmentList atts = mAttachments;
298 AttachmentList thatAtts = that.mAttachments;
299
300 AttachmentList::iterator it = atts.begin();
301 while (it != atts.end())
302 {
303 bool found = false;
304 AttachmentList::iterator thatIt = thatAtts.begin();
305 while (thatIt != thatAtts.end())
306 {
307 if ((*it)->controller() == (*thatIt)->controller() &&
308 (*it)->port() == (*thatIt)->port() &&
309 (*it)->device() == (*thatIt)->device() &&
310 (*it)->passthrough() == (*thatIt)->passthrough() &&
311 (*it)->medium().equalsTo ((*thatIt)->medium()))
312 {
313 thatAtts.erase (thatIt);
314 found = true;
315 break;
316 }
317 else
318 ++thatIt;
319 }
320 if (found)
321 it = atts.erase (it);
322 else
323 return false;
324 }
325
326 Assert (atts.size() == 0 && thatAtts.size() == 0);
327
328 return true;
329}
330
331/////////////////////////////////////////////////////////////////////////////
332// Machine class
333/////////////////////////////////////////////////////////////////////////////
334
335// constructor / destructor
336/////////////////////////////////////////////////////////////////////////////
337
338Machine::Machine() : mType (IsMachine) {}
339
340Machine::~Machine() {}
341
342HRESULT Machine::FinalConstruct()
343{
344 LogFlowThisFunc(("\n"));
345 return S_OK;
346}
347
348void Machine::FinalRelease()
349{
350 LogFlowThisFunc(("\n"));
351 uninit();
352}
353
354/**
355 * Initializes the instance.
356 *
357 * @param aParent Associated parent object
358 * @param aConfigFile Local file system path to the VM settings file (can
359 * be relative to the VirtualBox config directory).
360 * @param aMode Init_New, Init_Existing or Init_Registered
361 * @param aName name for the machine when aMode is Init_New
362 * (ignored otherwise)
363 * @param aOsType OS Type of this machine
364 * @param aNameSync |TRUE| to automatically sync settings dir and file
365 * name with the machine name. |FALSE| is used for legacy
366 * machines where the file name is specified by the
367 * user and should never change. Used only in Init_New
368 * mode (ignored otherwise).
369 * @param aId UUID of the machine. Required for aMode==Init_Registered
370 * and optional for aMode==Init_New. Used for consistency
371 * check when aMode is Init_Registered; must match UUID
372 * stored in the settings file. Used for predefining the
373 * UUID of a VM when aMode is Init_New.
374 *
375 * @return Success indicator. if not S_OK, the machine object is invalid
376 */
377HRESULT Machine::init(VirtualBox *aParent,
378 const Utf8Str &strConfigFile,
379 InitMode aMode,
380 CBSTR aName /* = NULL */,
381 GuestOSType *aOsType /* = NULL */,
382 BOOL aNameSync /* = TRUE */,
383 const Guid *aId /* = NULL */)
384{
385 LogFlowThisFuncEnter();
386 LogFlowThisFunc (("aConfigFile='%s', aMode=%d\n", strConfigFile.raw(), aMode));
387
388 AssertReturn (aParent, E_INVALIDARG);
389 AssertReturn (!strConfigFile.isEmpty(), E_INVALIDARG);
390 AssertReturn(aMode != Init_New || (aName != NULL && *aName != '\0'),
391 E_INVALIDARG);
392 AssertReturn(aMode != Init_Registered || aId != NULL, E_FAIL);
393
394 /* Enclose the state transition NotReady->InInit->Ready */
395 AutoInitSpan autoInitSpan(this);
396 AssertReturn(autoInitSpan.isOk(), E_FAIL);
397
398 HRESULT rc = S_OK;
399
400 /* share the parent weakly */
401 unconst(mParent) = aParent;
402
403 /* register with parent early, since uninit() will unconditionally
404 * unregister on failure */
405 mParent->addDependentChild (this);
406
407 /* allocate the essential machine data structure (the rest will be
408 * allocated later by initDataAndChildObjects() */
409 mData.allocate();
410
411 mData->m_pMachineConfigFile = NULL;
412
413 /* memorize the config file name (as provided) */
414 mData->m_strConfigFile = strConfigFile;
415
416 /* get the full file name */
417 int vrc = mParent->calculateFullPath(strConfigFile, mData->m_strConfigFileFull);
418 if (RT_FAILURE(vrc))
419 return setError(VBOX_E_FILE_ERROR,
420 tr("Invalid machine settings file name '%s' (%Rrc)"),
421 strConfigFile.raw(),
422 vrc);
423
424 if (aMode == Init_Registered)
425 {
426 mData->mRegistered = TRUE;
427
428 /* store the supplied UUID (will be used to check for UUID consistency
429 * in loadSettings() */
430 unconst(mData->mUuid) = *aId;
431
432 // now load the settings from XML:
433 rc = registeredInit();
434 }
435 else
436 {
437 if (aMode == Init_Import)
438 {
439 // we're reading the settings file below
440 }
441 else if (aMode == Init_New)
442 {
443 /* check for the file existence */
444 RTFILE f = NIL_RTFILE;
445 int vrc = RTFileOpen(&f, mData->m_strConfigFileFull.c_str(), RTFILE_O_READ);
446 if ( RT_SUCCESS(vrc)
447 || vrc == VERR_SHARING_VIOLATION
448 )
449 {
450 rc = setError(VBOX_E_FILE_ERROR,
451 tr("Machine settings file '%s' already exists"),
452 mData->m_strConfigFileFull.raw());
453 if (RT_SUCCESS(vrc))
454 RTFileClose(f);
455 }
456 else
457 {
458 if ( vrc != VERR_FILE_NOT_FOUND
459 && vrc != VERR_PATH_NOT_FOUND
460 )
461 rc = setError(VBOX_E_FILE_ERROR,
462 tr("Invalid machine settings file name '%s' (%Rrc)"),
463 mData->m_strConfigFileFull.raw(),
464 vrc);
465 }
466
467 // create an empty machine config
468 mData->m_pMachineConfigFile = new settings::MachineConfigFile(NULL);
469 }
470 else
471 AssertFailed();
472
473 if (SUCCEEDED(rc))
474 rc = initDataAndChildObjects();
475
476 if (SUCCEEDED(rc))
477 {
478 /* set to true now to cause uninit() to call
479 * uninitDataAndChildObjects() on failure */
480 mData->mAccessible = TRUE;
481
482 if (aMode != Init_New)
483 {
484 rc = loadSettings(false /* aRegistered */);
485 }
486 else
487 {
488 /* create the machine UUID */
489 if (aId)
490 unconst(mData->mUuid) = *aId;
491 else
492 unconst(mData->mUuid).create();
493
494 /* memorize the provided new machine's name */
495 mUserData->mName = aName;
496 mUserData->mNameSync = aNameSync;
497
498 /* initialize the default snapshots folder
499 * (note: depends on the name value set above!) */
500 rc = COMSETTER(SnapshotFolder)(NULL);
501 AssertComRC(rc);
502
503 if (aOsType)
504 {
505 /* Store OS type */
506 mUserData->mOSTypeId = aOsType->id();
507
508 /* Apply BIOS defaults */
509 mBIOSSettings->applyDefaults (aOsType);
510
511 /* Apply network adapters defaults */
512 for (ULONG slot = 0; slot < RT_ELEMENTS (mNetworkAdapters); ++slot)
513 mNetworkAdapters [slot]->applyDefaults (aOsType);
514
515 /* Apply serial port defaults */
516 for (ULONG slot = 0; slot < RT_ELEMENTS (mSerialPorts); ++slot)
517 mSerialPorts [slot]->applyDefaults (aOsType);
518 }
519 }
520
521 /* commit all changes made during the initialization */
522 if (SUCCEEDED(rc))
523 commit();
524 }
525 }
526
527 /* Confirm a successful initialization when it's the case */
528 if (SUCCEEDED(rc))
529 {
530 if (mData->mAccessible)
531 autoInitSpan.setSucceeded();
532 else
533 autoInitSpan.setLimited();
534 }
535
536 LogFlowThisFunc(("mName='%ls', mRegistered=%RTbool, mAccessible=%RTbool "
537 "rc=%08X\n",
538 !!mUserData ? mUserData->mName.raw() : NULL,
539 mData->mRegistered, mData->mAccessible, rc));
540
541 LogFlowThisFuncLeave();
542
543 return rc;
544}
545
546/**
547 * Initializes the registered machine by loading the settings file.
548 * This method is separated from #init() in order to make it possible to
549 * retry the operation after VirtualBox startup instead of refusing to
550 * startup the whole VirtualBox server in case if the settings file of some
551 * registered VM is invalid or inaccessible.
552 *
553 * @note Must be always called from this object's write lock
554 * (unless called from #init() that doesn't need any locking).
555 * @note Locks the mUSBController method for writing.
556 * @note Subclasses must not call this method.
557 */
558HRESULT Machine::registeredInit()
559{
560 AssertReturn(mType == IsMachine, E_FAIL);
561 AssertReturn(!mData->mUuid.isEmpty(), E_FAIL);
562 AssertReturn(!mData->mAccessible, E_FAIL);
563
564 HRESULT rc = initDataAndChildObjects();
565
566 if (SUCCEEDED(rc))
567 {
568 /* Temporarily reset the registered flag in order to let setters
569 * potentially called from loadSettings() succeed (isMutable() used in
570 * all setters will return FALSE for a Machine instance if mRegistered
571 * is TRUE). */
572 mData->mRegistered = FALSE;
573
574 rc = loadSettings(true /* aRegistered */);
575
576 /* Restore the registered flag (even on failure) */
577 mData->mRegistered = TRUE;
578 }
579
580 if (SUCCEEDED(rc))
581 {
582 /* Set mAccessible to TRUE only if we successfully locked and loaded
583 * the settings file */
584 mData->mAccessible = TRUE;
585
586 /* commit all changes made during loading the settings file */
587 commit();
588 }
589 else
590 {
591 /* If the machine is registered, then, instead of returning a
592 * failure, we mark it as inaccessible and set the result to
593 * success to give it a try later */
594
595 /* fetch the current error info */
596 mData->mAccessError = com::ErrorInfo();
597 LogWarning(("Machine {%RTuuid} is inaccessible! [%ls]\n",
598 mData->mUuid.raw(),
599 mData->mAccessError.getText().raw()));
600
601 /* rollback all changes */
602 rollback (false /* aNotify */);
603
604 /* uninitialize the common part to make sure all data is reset to
605 * default (null) values */
606 uninitDataAndChildObjects();
607
608 rc = S_OK;
609 }
610
611 return rc;
612}
613
614/**
615 * Uninitializes the instance.
616 * Called either from FinalRelease() or by the parent when it gets destroyed.
617 *
618 * @note The caller of this method must make sure that this object
619 * a) doesn't have active callers on the current thread and b) is not locked
620 * by the current thread; otherwise uninit() will hang either a) due to
621 * AutoUninitSpan waiting for a number of calls to drop to zero or b) due to
622 * a dead-lock caused by this thread waiting for all callers on the other
623 * threads are done but preventing them from doing so by holding a lock.
624 */
625void Machine::uninit()
626{
627 LogFlowThisFuncEnter();
628
629 Assert (!isWriteLockOnCurrentThread());
630
631 /* Enclose the state transition Ready->InUninit->NotReady */
632 AutoUninitSpan autoUninitSpan(this);
633 if (autoUninitSpan.uninitDone())
634 return;
635
636 Assert (mType == IsMachine);
637 Assert (!!mData);
638
639 LogFlowThisFunc(("initFailed()=%d\n", autoUninitSpan.initFailed()));
640 LogFlowThisFunc(("mRegistered=%d\n", mData->mRegistered));
641
642 /* Enter this object lock because there may be a SessionMachine instance
643 * somewhere around, that shares our data and lock but doesn't use our
644 * addCaller()/removeCaller(), and it may be also accessing the same data
645 * members. mParent lock is necessary as well because of
646 * SessionMachine::uninit(), etc.
647 */
648 AutoMultiWriteLock2 alock (mParent, this);
649
650 if (!mData->mSession.mMachine.isNull())
651 {
652 /* Theoretically, this can only happen if the VirtualBox server has been
653 * terminated while there were clients running that owned open direct
654 * sessions. Since in this case we are definitely called by
655 * VirtualBox::uninit(), we may be sure that SessionMachine::uninit()
656 * won't happen on the client watcher thread (because it does
657 * VirtualBox::addCaller() for the duration of the
658 * SessionMachine::checkForDeath() call, so that VirtualBox::uninit()
659 * cannot happen until the VirtualBox caller is released). This is
660 * important, because SessionMachine::uninit() cannot correctly operate
661 * after we return from this method (it expects the Machine instance is
662 * still valid). We'll call it ourselves below.
663 */
664 LogWarningThisFunc(("Session machine is not NULL (%p), "
665 "the direct session is still open!\n",
666 (SessionMachine *) mData->mSession.mMachine));
667
668 if (Global::IsOnlineOrTransient (mData->mMachineState))
669 {
670 LogWarningThisFunc(("Setting state to Aborted!\n"));
671 /* set machine state using SessionMachine reimplementation */
672 static_cast <Machine *> (mData->mSession.mMachine)
673 ->setMachineState (MachineState_Aborted);
674 }
675
676 /*
677 * Uninitialize SessionMachine using public uninit() to indicate
678 * an unexpected uninitialization.
679 */
680 mData->mSession.mMachine->uninit();
681 /* SessionMachine::uninit() must set mSession.mMachine to null */
682 Assert (mData->mSession.mMachine.isNull());
683 }
684
685 /* the lock is no more necessary (SessionMachine is uninitialized) */
686 alock.leave();
687
688 if (isModified())
689 {
690 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
691 rollback (false /* aNotify */);
692 }
693
694 if (mData->mAccessible)
695 uninitDataAndChildObjects();
696
697 /* free the essential data structure last */
698 mData.free();
699
700 mParent->removeDependentChild (this);
701
702 LogFlowThisFuncLeave();
703}
704
705// IMachine properties
706/////////////////////////////////////////////////////////////////////////////
707
708STDMETHODIMP Machine::COMGETTER(Parent) (IVirtualBox **aParent)
709{
710 CheckComArgOutPointerValid(aParent);
711
712 AutoLimitedCaller autoCaller(this);
713 CheckComRCReturnRC(autoCaller.rc());
714
715 /* mParent is constant during life time, no need to lock */
716 mParent.queryInterfaceTo(aParent);
717
718 return S_OK;
719}
720
721STDMETHODIMP Machine::COMGETTER(Accessible) (BOOL *aAccessible)
722{
723 CheckComArgOutPointerValid(aAccessible);
724
725 AutoLimitedCaller autoCaller(this);
726 CheckComRCReturnRC(autoCaller.rc());
727
728 AutoWriteLock alock(this);
729
730 HRESULT rc = S_OK;
731
732 if (!mData->mAccessible)
733 {
734 /* try to initialize the VM once more if not accessible */
735
736 AutoReinitSpan autoReinitSpan(this);
737 AssertReturn(autoReinitSpan.isOk(), E_FAIL);
738
739 if (mData->m_pMachineConfigFile)
740 {
741 // @todo why are we parsing this several times?
742 // this is hugely inefficient
743 delete mData->m_pMachineConfigFile;
744 mData->m_pMachineConfigFile = NULL;
745 }
746
747 rc = registeredInit();
748
749 if (SUCCEEDED(rc) && mData->mAccessible)
750 {
751 autoReinitSpan.setSucceeded();
752
753 /* make sure interesting parties will notice the accessibility
754 * state change */
755 mParent->onMachineStateChange(mData->mUuid, mData->mMachineState);
756 mParent->onMachineDataChange(mData->mUuid);
757 }
758 }
759
760 if (SUCCEEDED(rc))
761 *aAccessible = mData->mAccessible;
762
763 return rc;
764}
765
766STDMETHODIMP Machine::COMGETTER(AccessError) (IVirtualBoxErrorInfo **aAccessError)
767{
768 CheckComArgOutPointerValid(aAccessError);
769
770 AutoLimitedCaller autoCaller(this);
771 CheckComRCReturnRC(autoCaller.rc());
772
773 AutoReadLock alock(this);
774
775 if (mData->mAccessible || !mData->mAccessError.isBasicAvailable())
776 {
777 /* return shortly */
778 aAccessError = NULL;
779 return S_OK;
780 }
781
782 HRESULT rc = S_OK;
783
784 ComObjPtr<VirtualBoxErrorInfo> errorInfo;
785 rc = errorInfo.createObject();
786 if (SUCCEEDED(rc))
787 {
788 errorInfo->init (mData->mAccessError.getResultCode(),
789 mData->mAccessError.getInterfaceID(),
790 mData->mAccessError.getComponent(),
791 mData->mAccessError.getText());
792 rc = errorInfo.queryInterfaceTo(aAccessError);
793 }
794
795 return rc;
796}
797
798STDMETHODIMP Machine::COMGETTER(Name) (BSTR *aName)
799{
800 CheckComArgOutPointerValid(aName);
801
802 AutoCaller autoCaller(this);
803 CheckComRCReturnRC(autoCaller.rc());
804
805 AutoReadLock alock(this);
806
807 mUserData->mName.cloneTo(aName);
808
809 return S_OK;
810}
811
812STDMETHODIMP Machine::COMSETTER(Name) (IN_BSTR aName)
813{
814 CheckComArgNotNull (aName);
815
816 if (!*aName)
817 return setError(E_INVALIDARG,
818 tr("Machine name cannot be empty"));
819
820 AutoCaller autoCaller(this);
821 CheckComRCReturnRC(autoCaller.rc());
822
823 AutoWriteLock alock(this);
824
825 HRESULT rc = checkStateDependency(MutableStateDep);
826 CheckComRCReturnRC(rc);
827
828 mUserData.backup();
829 mUserData->mName = aName;
830
831 return S_OK;
832}
833
834STDMETHODIMP Machine::COMGETTER(Description) (BSTR *aDescription)
835{
836 CheckComArgOutPointerValid(aDescription);
837
838 AutoCaller autoCaller(this);
839 CheckComRCReturnRC(autoCaller.rc());
840
841 AutoReadLock alock(this);
842
843 mUserData->mDescription.cloneTo(aDescription);
844
845 return S_OK;
846}
847
848STDMETHODIMP Machine::COMSETTER(Description) (IN_BSTR aDescription)
849{
850 AutoCaller autoCaller(this);
851 CheckComRCReturnRC(autoCaller.rc());
852
853 AutoWriteLock alock(this);
854
855 HRESULT rc = checkStateDependency(MutableStateDep);
856 CheckComRCReturnRC(rc);
857
858 mUserData.backup();
859 mUserData->mDescription = aDescription;
860
861 return S_OK;
862}
863
864STDMETHODIMP Machine::COMGETTER(Id) (BSTR *aId)
865{
866 CheckComArgOutPointerValid(aId);
867
868 AutoLimitedCaller autoCaller(this);
869 CheckComRCReturnRC(autoCaller.rc());
870
871 AutoReadLock alock(this);
872
873 mData->mUuid.toUtf16().cloneTo(aId);
874
875 return S_OK;
876}
877
878STDMETHODIMP Machine::COMGETTER(OSTypeId) (BSTR *aOSTypeId)
879{
880 CheckComArgOutPointerValid(aOSTypeId);
881
882 AutoCaller autoCaller(this);
883 CheckComRCReturnRC(autoCaller.rc());
884
885 AutoReadLock alock(this);
886
887 mUserData->mOSTypeId.cloneTo(aOSTypeId);
888
889 return S_OK;
890}
891
892STDMETHODIMP Machine::COMSETTER(OSTypeId) (IN_BSTR aOSTypeId)
893{
894 CheckComArgNotNull (aOSTypeId);
895
896 AutoCaller autoCaller(this);
897 CheckComRCReturnRC(autoCaller.rc());
898
899 /* look up the object by Id to check it is valid */
900 ComPtr<IGuestOSType> guestOSType;
901 HRESULT rc = mParent->GetGuestOSType (aOSTypeId,
902 guestOSType.asOutParam());
903 CheckComRCReturnRC(rc);
904
905 /* when setting, always use the "etalon" value for consistency -- lookup
906 * by ID is case-insensitive and the input value may have different case */
907 Bstr osTypeId;
908 rc = guestOSType->COMGETTER(Id) (osTypeId.asOutParam());
909 CheckComRCReturnRC(rc);
910
911 AutoWriteLock alock(this);
912
913 rc = checkStateDependency(MutableStateDep);
914 CheckComRCReturnRC(rc);
915
916 mUserData.backup();
917 mUserData->mOSTypeId = osTypeId;
918
919 return S_OK;
920}
921
922
923STDMETHODIMP Machine::COMGETTER(FirmwareType) (FirmwareType_T *aFirmwareType)
924{
925 CheckComArgOutPointerValid(aFirmwareType);
926
927 AutoCaller autoCaller(this);
928 CheckComRCReturnRC(autoCaller.rc());
929
930 AutoReadLock alock(this);
931
932 *aFirmwareType = mHWData->mFirmwareType;
933
934 return S_OK;
935}
936
937STDMETHODIMP Machine::COMSETTER(FirmwareType) (FirmwareType_T aFirmwareType)
938{
939 AutoCaller autoCaller(this);
940 CheckComRCReturnRC(autoCaller.rc());
941 AutoWriteLock alock(this);
942
943 int rc = checkStateDependency(MutableStateDep);
944 CheckComRCReturnRC(rc);
945
946 mHWData.backup();
947 mHWData->mFirmwareType = aFirmwareType;
948
949 return S_OK;
950}
951
952STDMETHODIMP Machine::COMGETTER(HardwareVersion) (BSTR *aHWVersion)
953{
954 if (!aHWVersion)
955 return E_POINTER;
956
957 AutoCaller autoCaller(this);
958 CheckComRCReturnRC(autoCaller.rc());
959
960 AutoReadLock alock(this);
961
962 mHWData->mHWVersion.cloneTo(aHWVersion);
963
964 return S_OK;
965}
966
967STDMETHODIMP Machine::COMSETTER(HardwareVersion) (IN_BSTR aHWVersion)
968{
969 /* check known version */
970 Utf8Str hwVersion = aHWVersion;
971 if ( hwVersion.compare ("1") != 0
972 && hwVersion.compare ("2") != 0)
973 return setError(E_INVALIDARG,
974 tr("Invalid hardware version: %ls\n"), aHWVersion);
975
976 AutoCaller autoCaller(this);
977 CheckComRCReturnRC(autoCaller.rc());
978
979 AutoWriteLock alock(this);
980
981 HRESULT rc = checkStateDependency(MutableStateDep);
982 CheckComRCReturnRC(rc);
983
984 mHWData.backup();
985 mHWData->mHWVersion = hwVersion;
986
987 return S_OK;
988}
989
990STDMETHODIMP Machine::COMGETTER(MemorySize) (ULONG *memorySize)
991{
992 if (!memorySize)
993 return E_POINTER;
994
995 AutoCaller autoCaller(this);
996 CheckComRCReturnRC(autoCaller.rc());
997
998 AutoReadLock alock(this);
999
1000 *memorySize = mHWData->mMemorySize;
1001
1002 return S_OK;
1003}
1004
1005STDMETHODIMP Machine::COMSETTER(MemorySize) (ULONG memorySize)
1006{
1007 /* check RAM limits */
1008 if ( memorySize < MM_RAM_MIN_IN_MB
1009 || memorySize > MM_RAM_MAX_IN_MB
1010 )
1011 return setError(E_INVALIDARG,
1012 tr("Invalid RAM size: %lu MB (must be in range [%lu, %lu] MB)"),
1013 memorySize, MM_RAM_MIN_IN_MB, MM_RAM_MAX_IN_MB);
1014
1015 AutoCaller autoCaller(this);
1016 CheckComRCReturnRC(autoCaller.rc());
1017
1018 AutoWriteLock alock(this);
1019
1020 HRESULT rc = checkStateDependency(MutableStateDep);
1021 CheckComRCReturnRC(rc);
1022
1023 mHWData.backup();
1024 mHWData->mMemorySize = memorySize;
1025
1026 return S_OK;
1027}
1028
1029STDMETHODIMP Machine::COMGETTER(CPUCount) (ULONG *CPUCount)
1030{
1031 if (!CPUCount)
1032 return E_POINTER;
1033
1034 AutoCaller autoCaller(this);
1035 CheckComRCReturnRC(autoCaller.rc());
1036
1037 AutoReadLock alock(this);
1038
1039 *CPUCount = mHWData->mCPUCount;
1040
1041 return S_OK;
1042}
1043
1044STDMETHODIMP Machine::COMSETTER(CPUCount) (ULONG CPUCount)
1045{
1046 /* check RAM limits */
1047 if ( CPUCount < SchemaDefs::MinCPUCount
1048 || CPUCount > SchemaDefs::MaxCPUCount
1049 )
1050 return setError(E_INVALIDARG,
1051 tr("Invalid virtual CPU count: %lu (must be in range [%lu, %lu])"),
1052 CPUCount, SchemaDefs::MinCPUCount, SchemaDefs::MaxCPUCount);
1053
1054 AutoCaller autoCaller(this);
1055 CheckComRCReturnRC(autoCaller.rc());
1056
1057 AutoWriteLock alock(this);
1058
1059 HRESULT rc = checkStateDependency(MutableStateDep);
1060 CheckComRCReturnRC(rc);
1061
1062 mHWData.backup();
1063 mHWData->mCPUCount = CPUCount;
1064
1065 return S_OK;
1066}
1067
1068STDMETHODIMP Machine::COMGETTER(VRAMSize) (ULONG *memorySize)
1069{
1070 if (!memorySize)
1071 return E_POINTER;
1072
1073 AutoCaller autoCaller(this);
1074 CheckComRCReturnRC(autoCaller.rc());
1075
1076 AutoReadLock alock(this);
1077
1078 *memorySize = mHWData->mVRAMSize;
1079
1080 return S_OK;
1081}
1082
1083STDMETHODIMP Machine::COMSETTER(VRAMSize) (ULONG memorySize)
1084{
1085 /* check VRAM limits */
1086 if (memorySize < SchemaDefs::MinGuestVRAM ||
1087 memorySize > SchemaDefs::MaxGuestVRAM)
1088 return setError(E_INVALIDARG,
1089 tr("Invalid VRAM size: %lu MB (must be in range [%lu, %lu] MB)"),
1090 memorySize, SchemaDefs::MinGuestVRAM, SchemaDefs::MaxGuestVRAM);
1091
1092 AutoCaller autoCaller(this);
1093 CheckComRCReturnRC(autoCaller.rc());
1094
1095 AutoWriteLock alock(this);
1096
1097 HRESULT rc = checkStateDependency(MutableStateDep);
1098 CheckComRCReturnRC(rc);
1099
1100 mHWData.backup();
1101 mHWData->mVRAMSize = memorySize;
1102
1103 return S_OK;
1104}
1105
1106/** @todo this method should not be public */
1107STDMETHODIMP Machine::COMGETTER(MemoryBalloonSize) (ULONG *memoryBalloonSize)
1108{
1109 if (!memoryBalloonSize)
1110 return E_POINTER;
1111
1112 AutoCaller autoCaller(this);
1113 CheckComRCReturnRC(autoCaller.rc());
1114
1115 AutoReadLock alock(this);
1116
1117 *memoryBalloonSize = mHWData->mMemoryBalloonSize;
1118
1119 return S_OK;
1120}
1121
1122/** @todo this method should not be public */
1123STDMETHODIMP Machine::COMSETTER(MemoryBalloonSize) (ULONG memoryBalloonSize)
1124{
1125 /* check limits */
1126 if (memoryBalloonSize >= VMMDEV_MAX_MEMORY_BALLOON (mHWData->mMemorySize))
1127 return setError(E_INVALIDARG,
1128 tr("Invalid memory balloon size: %lu MB (must be in range [%lu, %lu] MB)"),
1129 memoryBalloonSize, 0, VMMDEV_MAX_MEMORY_BALLOON (mHWData->mMemorySize));
1130
1131 AutoCaller autoCaller(this);
1132 CheckComRCReturnRC(autoCaller.rc());
1133
1134 AutoWriteLock alock(this);
1135
1136 HRESULT rc = checkStateDependency(MutableStateDep);
1137 CheckComRCReturnRC(rc);
1138
1139 mHWData.backup();
1140 mHWData->mMemoryBalloonSize = memoryBalloonSize;
1141
1142 return S_OK;
1143}
1144
1145/** @todo this method should not be public */
1146STDMETHODIMP Machine::COMGETTER(StatisticsUpdateInterval) (ULONG *statisticsUpdateInterval)
1147{
1148 if (!statisticsUpdateInterval)
1149 return E_POINTER;
1150
1151 AutoCaller autoCaller(this);
1152 CheckComRCReturnRC(autoCaller.rc());
1153
1154 AutoReadLock alock(this);
1155
1156 *statisticsUpdateInterval = mHWData->mStatisticsUpdateInterval;
1157
1158 return S_OK;
1159}
1160
1161/** @todo this method should not be public */
1162STDMETHODIMP Machine::COMSETTER(StatisticsUpdateInterval) (ULONG statisticsUpdateInterval)
1163{
1164 AutoCaller autoCaller(this);
1165 CheckComRCReturnRC(autoCaller.rc());
1166
1167 AutoWriteLock alock(this);
1168
1169 HRESULT rc = checkStateDependency(MutableStateDep);
1170 CheckComRCReturnRC(rc);
1171
1172 mHWData.backup();
1173 mHWData->mStatisticsUpdateInterval = statisticsUpdateInterval;
1174
1175 return S_OK;
1176}
1177
1178
1179STDMETHODIMP Machine::COMGETTER(Accelerate3DEnabled)(BOOL *enabled)
1180{
1181 if (!enabled)
1182 return E_POINTER;
1183
1184 AutoCaller autoCaller(this);
1185 CheckComRCReturnRC(autoCaller.rc());
1186
1187 AutoReadLock alock(this);
1188
1189 *enabled = mHWData->mAccelerate3DEnabled;
1190
1191 return S_OK;
1192}
1193
1194STDMETHODIMP Machine::COMSETTER(Accelerate3DEnabled)(BOOL enable)
1195{
1196 AutoCaller autoCaller(this);
1197 CheckComRCReturnRC(autoCaller.rc());
1198
1199 AutoWriteLock alock(this);
1200
1201 HRESULT rc = checkStateDependency(MutableStateDep);
1202 CheckComRCReturnRC(rc);
1203
1204 /** @todo check validity! */
1205
1206 mHWData.backup();
1207 mHWData->mAccelerate3DEnabled = enable;
1208
1209 return S_OK;
1210}
1211
1212
1213STDMETHODIMP Machine::COMGETTER(Accelerate2DVideoEnabled)(BOOL *enabled)
1214{
1215 if (!enabled)
1216 return E_POINTER;
1217
1218 AutoCaller autoCaller(this);
1219 CheckComRCReturnRC(autoCaller.rc());
1220
1221 AutoReadLock alock(this);
1222
1223 *enabled = mHWData->mAccelerate2DVideoEnabled;
1224
1225 return S_OK;
1226}
1227
1228STDMETHODIMP Machine::COMSETTER(Accelerate2DVideoEnabled)(BOOL enable)
1229{
1230 AutoCaller autoCaller(this);
1231 CheckComRCReturnRC(autoCaller.rc());
1232
1233 AutoWriteLock alock(this);
1234
1235 HRESULT rc = checkStateDependency(MutableStateDep);
1236 CheckComRCReturnRC(rc);
1237
1238 /** @todo check validity! */
1239
1240 mHWData.backup();
1241 mHWData->mAccelerate2DVideoEnabled = enable;
1242
1243 return S_OK;
1244}
1245
1246STDMETHODIMP Machine::COMGETTER(MonitorCount) (ULONG *monitorCount)
1247{
1248 if (!monitorCount)
1249 return E_POINTER;
1250
1251 AutoCaller autoCaller(this);
1252 CheckComRCReturnRC(autoCaller.rc());
1253
1254 AutoReadLock alock(this);
1255
1256 *monitorCount = mHWData->mMonitorCount;
1257
1258 return S_OK;
1259}
1260
1261STDMETHODIMP Machine::COMSETTER(MonitorCount) (ULONG monitorCount)
1262{
1263 /* make sure monitor count is a sensible number */
1264 if (monitorCount < 1 || monitorCount > SchemaDefs::MaxGuestMonitors)
1265 return setError(E_INVALIDARG,
1266 tr("Invalid monitor count: %lu (must be in range [%lu, %lu])"),
1267 monitorCount, 1, SchemaDefs::MaxGuestMonitors);
1268
1269 AutoCaller autoCaller(this);
1270 CheckComRCReturnRC(autoCaller.rc());
1271
1272 AutoWriteLock alock(this);
1273
1274 HRESULT rc = checkStateDependency(MutableStateDep);
1275 CheckComRCReturnRC(rc);
1276
1277 mHWData.backup();
1278 mHWData->mMonitorCount = monitorCount;
1279
1280 return S_OK;
1281}
1282
1283STDMETHODIMP Machine::COMGETTER(BIOSSettings)(IBIOSSettings **biosSettings)
1284{
1285 if (!biosSettings)
1286 return E_POINTER;
1287
1288 AutoCaller autoCaller(this);
1289 CheckComRCReturnRC(autoCaller.rc());
1290
1291 /* mBIOSSettings is constant during life time, no need to lock */
1292 mBIOSSettings.queryInterfaceTo(biosSettings);
1293
1294 return S_OK;
1295}
1296
1297STDMETHODIMP Machine::COMGETTER(HWVirtExEnabled)(BOOL *enabled)
1298{
1299 if (!enabled)
1300 return E_POINTER;
1301
1302 AutoCaller autoCaller(this);
1303 CheckComRCReturnRC(autoCaller.rc());
1304
1305 AutoReadLock alock(this);
1306
1307 *enabled = mHWData->mHWVirtExEnabled;
1308
1309 return S_OK;
1310}
1311
1312STDMETHODIMP Machine::COMSETTER(HWVirtExEnabled)(BOOL enable)
1313{
1314 AutoCaller autoCaller(this);
1315 CheckComRCReturnRC(autoCaller.rc());
1316
1317 AutoWriteLock alock(this);
1318
1319 HRESULT rc = checkStateDependency(MutableStateDep);
1320 CheckComRCReturnRC(rc);
1321
1322 /** @todo check validity! */
1323
1324 mHWData.backup();
1325 mHWData->mHWVirtExEnabled = enable;
1326
1327 return S_OK;
1328}
1329
1330STDMETHODIMP Machine::COMGETTER(HWVirtExNestedPagingEnabled)(BOOL *enabled)
1331{
1332 if (!enabled)
1333 return E_POINTER;
1334
1335 AutoCaller autoCaller(this);
1336 CheckComRCReturnRC(autoCaller.rc());
1337
1338 AutoReadLock alock(this);
1339
1340 *enabled = mHWData->mHWVirtExNestedPagingEnabled;
1341
1342 return S_OK;
1343}
1344
1345STDMETHODIMP Machine::COMSETTER(HWVirtExNestedPagingEnabled)(BOOL enable)
1346{
1347 AutoCaller autoCaller(this);
1348 CheckComRCReturnRC(autoCaller.rc());
1349
1350 AutoWriteLock alock(this);
1351
1352 HRESULT rc = checkStateDependency(MutableStateDep);
1353 CheckComRCReturnRC(rc);
1354
1355 /** @todo check validity! */
1356
1357 mHWData.backup();
1358 mHWData->mHWVirtExNestedPagingEnabled = enable;
1359
1360 return S_OK;
1361}
1362
1363STDMETHODIMP Machine::COMGETTER(HWVirtExVPIDEnabled)(BOOL *enabled)
1364{
1365 if (!enabled)
1366 return E_POINTER;
1367
1368 AutoCaller autoCaller(this);
1369 CheckComRCReturnRC(autoCaller.rc());
1370
1371 AutoReadLock alock(this);
1372
1373 *enabled = mHWData->mHWVirtExVPIDEnabled;
1374
1375 return S_OK;
1376}
1377
1378STDMETHODIMP Machine::COMSETTER(HWVirtExVPIDEnabled)(BOOL enable)
1379{
1380 AutoCaller autoCaller(this);
1381 CheckComRCReturnRC(autoCaller.rc());
1382
1383 AutoWriteLock alock(this);
1384
1385 HRESULT rc = checkStateDependency(MutableStateDep);
1386 CheckComRCReturnRC(rc);
1387
1388 /** @todo check validity! */
1389
1390 mHWData.backup();
1391 mHWData->mHWVirtExVPIDEnabled = enable;
1392
1393 return S_OK;
1394}
1395
1396STDMETHODIMP Machine::COMGETTER(PAEEnabled)(BOOL *enabled)
1397{
1398 if (!enabled)
1399 return E_POINTER;
1400
1401 AutoCaller autoCaller(this);
1402 CheckComRCReturnRC(autoCaller.rc());
1403
1404 AutoReadLock alock(this);
1405
1406 *enabled = mHWData->mPAEEnabled;
1407
1408 return S_OK;
1409}
1410
1411STDMETHODIMP Machine::COMSETTER(PAEEnabled)(BOOL enable)
1412{
1413 AutoCaller autoCaller(this);
1414 CheckComRCReturnRC(autoCaller.rc());
1415
1416 AutoWriteLock alock(this);
1417
1418 HRESULT rc = checkStateDependency(MutableStateDep);
1419 CheckComRCReturnRC(rc);
1420
1421 /** @todo check validity! */
1422
1423 mHWData.backup();
1424 mHWData->mPAEEnabled = enable;
1425
1426 return S_OK;
1427}
1428
1429STDMETHODIMP Machine::COMGETTER(SnapshotFolder) (BSTR *aSnapshotFolder)
1430{
1431 CheckComArgOutPointerValid(aSnapshotFolder);
1432
1433 AutoCaller autoCaller(this);
1434 CheckComRCReturnRC(autoCaller.rc());
1435
1436 AutoReadLock alock(this);
1437
1438 mUserData->mSnapshotFolderFull.cloneTo(aSnapshotFolder);
1439
1440 return S_OK;
1441}
1442
1443STDMETHODIMP Machine::COMSETTER(SnapshotFolder) (IN_BSTR aSnapshotFolder)
1444{
1445 /* @todo (r=dmik):
1446 * 1. Allow to change the name of the snapshot folder containing snapshots
1447 * 2. Rename the folder on disk instead of just changing the property
1448 * value (to be smart and not to leave garbage). Note that it cannot be
1449 * done here because the change may be rolled back. Thus, the right
1450 * place is #saveSettings().
1451 */
1452
1453 AutoCaller autoCaller(this);
1454 CheckComRCReturnRC(autoCaller.rc());
1455
1456 AutoWriteLock alock(this);
1457
1458 HRESULT rc = checkStateDependency(MutableStateDep);
1459 CheckComRCReturnRC(rc);
1460
1461 if (!mData->mCurrentSnapshot.isNull())
1462 return setError(E_FAIL,
1463 tr("The snapshot folder of a machine with snapshots cannot be changed (please discard all snapshots first)"));
1464
1465 Utf8Str snapshotFolder = aSnapshotFolder;
1466
1467 if (snapshotFolder.isEmpty())
1468 {
1469 if (isInOwnDir())
1470 {
1471 /* the default snapshots folder is 'Snapshots' in the machine dir */
1472 snapshotFolder = Utf8Str ("Snapshots");
1473 }
1474 else
1475 {
1476 /* the default snapshots folder is {UUID}, for backwards
1477 * compatibility and to resolve conflicts */
1478 snapshotFolder = Utf8StrFmt ("{%RTuuid}", mData->mUuid.raw());
1479 }
1480 }
1481
1482 int vrc = calculateFullPath(snapshotFolder, snapshotFolder);
1483 if (RT_FAILURE(vrc))
1484 return setError(E_FAIL,
1485 tr("Invalid snapshot folder '%ls' (%Rrc)"),
1486 aSnapshotFolder, vrc);
1487
1488 mUserData.backup();
1489 mUserData->mSnapshotFolder = aSnapshotFolder;
1490 mUserData->mSnapshotFolderFull = snapshotFolder;
1491
1492 return S_OK;
1493}
1494
1495STDMETHODIMP Machine::COMGETTER(MediumAttachments)(ComSafeArrayOut(IMediumAttachment*, aAttachments))
1496{
1497 if (ComSafeArrayOutIsNull(aAttachments))
1498 return E_POINTER;
1499
1500 AutoCaller autoCaller(this);
1501 CheckComRCReturnRC(autoCaller.rc());
1502
1503 AutoReadLock alock(this);
1504
1505 SafeIfaceArray<IMediumAttachment> attachments(mMediaData->mAttachments);
1506 attachments.detachTo(ComSafeArrayOutArg(aAttachments));
1507
1508 return S_OK;
1509}
1510
1511STDMETHODIMP Machine::COMGETTER(VRDPServer)(IVRDPServer **vrdpServer)
1512{
1513#ifdef VBOX_WITH_VRDP
1514 if (!vrdpServer)
1515 return E_POINTER;
1516
1517 AutoCaller autoCaller(this);
1518 CheckComRCReturnRC(autoCaller.rc());
1519
1520 AutoReadLock alock(this);
1521
1522 Assert (!!mVRDPServer);
1523 mVRDPServer.queryInterfaceTo(vrdpServer);
1524
1525 return S_OK;
1526#else
1527 NOREF(vrdpServer);
1528 ReturnComNotImplemented();
1529#endif
1530}
1531
1532STDMETHODIMP Machine::COMGETTER(AudioAdapter)(IAudioAdapter **audioAdapter)
1533{
1534 if (!audioAdapter)
1535 return E_POINTER;
1536
1537 AutoCaller autoCaller(this);
1538 CheckComRCReturnRC(autoCaller.rc());
1539
1540 AutoReadLock alock(this);
1541
1542 mAudioAdapter.queryInterfaceTo(audioAdapter);
1543 return S_OK;
1544}
1545
1546STDMETHODIMP Machine::COMGETTER(USBController) (IUSBController **aUSBController)
1547{
1548#ifdef VBOX_WITH_USB
1549 CheckComArgOutPointerValid(aUSBController);
1550
1551 AutoCaller autoCaller(this);
1552 CheckComRCReturnRC(autoCaller.rc());
1553
1554 MultiResult rc = mParent->host()->checkUSBProxyService();
1555 CheckComRCReturnRC(rc);
1556
1557 AutoReadLock alock(this);
1558
1559 return rc = mUSBController.queryInterfaceTo(aUSBController);
1560#else
1561 /* Note: The GUI depends on this method returning E_NOTIMPL with no
1562 * extended error info to indicate that USB is simply not available
1563 * (w/o treting it as a failure), for example, as in OSE */
1564 NOREF(aUSBController);
1565 ReturnComNotImplemented();
1566#endif
1567}
1568
1569STDMETHODIMP Machine::COMGETTER(SettingsFilePath) (BSTR *aFilePath)
1570{
1571 CheckComArgOutPointerValid(aFilePath);
1572
1573 AutoLimitedCaller autoCaller(this);
1574 CheckComRCReturnRC(autoCaller.rc());
1575
1576 AutoReadLock alock(this);
1577
1578 mData->m_strConfigFileFull.cloneTo(aFilePath);
1579 return S_OK;
1580}
1581
1582STDMETHODIMP Machine::COMGETTER(SettingsModified) (BOOL *aModified)
1583{
1584 CheckComArgOutPointerValid(aModified);
1585
1586 AutoCaller autoCaller(this);
1587 CheckComRCReturnRC(autoCaller.rc());
1588
1589 AutoWriteLock alock(this);
1590
1591 HRESULT rc = checkStateDependency(MutableStateDep);
1592 CheckComRCReturnRC(rc);
1593
1594 if (mData->mInitMode == Init_New)
1595 /*
1596 * if this is a new machine then no config file exists yet, so always return TRUE
1597 */
1598 *aModified = TRUE;
1599 else
1600 *aModified = isModified();
1601
1602 return S_OK;
1603}
1604
1605STDMETHODIMP Machine::COMGETTER(SessionState) (SessionState_T *aSessionState)
1606{
1607 CheckComArgOutPointerValid(aSessionState);
1608
1609 AutoCaller autoCaller(this);
1610 CheckComRCReturnRC(autoCaller.rc());
1611
1612 AutoReadLock alock(this);
1613
1614 *aSessionState = mData->mSession.mState;
1615
1616 return S_OK;
1617}
1618
1619STDMETHODIMP Machine::COMGETTER(SessionType) (BSTR *aSessionType)
1620{
1621 CheckComArgOutPointerValid(aSessionType);
1622
1623 AutoCaller autoCaller(this);
1624 CheckComRCReturnRC(autoCaller.rc());
1625
1626 AutoReadLock alock(this);
1627
1628 if (mData->mSession.mType.isNull())
1629 Bstr("").cloneTo(aSessionType);
1630 else
1631 mData->mSession.mType.cloneTo(aSessionType);
1632
1633 return S_OK;
1634}
1635
1636STDMETHODIMP Machine::COMGETTER(SessionPid) (ULONG *aSessionPid)
1637{
1638 CheckComArgOutPointerValid(aSessionPid);
1639
1640 AutoCaller autoCaller(this);
1641 CheckComRCReturnRC(autoCaller.rc());
1642
1643 AutoReadLock alock(this);
1644
1645 *aSessionPid = mData->mSession.mPid;
1646
1647 return S_OK;
1648}
1649
1650STDMETHODIMP Machine::COMGETTER(State) (MachineState_T *machineState)
1651{
1652 if (!machineState)
1653 return E_POINTER;
1654
1655 AutoCaller autoCaller(this);
1656 CheckComRCReturnRC(autoCaller.rc());
1657
1658 AutoReadLock alock(this);
1659
1660 *machineState = mData->mMachineState;
1661
1662 return S_OK;
1663}
1664
1665STDMETHODIMP Machine::COMGETTER(LastStateChange) (LONG64 *aLastStateChange)
1666{
1667 CheckComArgOutPointerValid(aLastStateChange);
1668
1669 AutoCaller autoCaller(this);
1670 CheckComRCReturnRC(autoCaller.rc());
1671
1672 AutoReadLock alock(this);
1673
1674 *aLastStateChange = RTTimeSpecGetMilli (&mData->mLastStateChange);
1675
1676 return S_OK;
1677}
1678
1679STDMETHODIMP Machine::COMGETTER(StateFilePath) (BSTR *aStateFilePath)
1680{
1681 CheckComArgOutPointerValid(aStateFilePath);
1682
1683 AutoCaller autoCaller(this);
1684 CheckComRCReturnRC(autoCaller.rc());
1685
1686 AutoReadLock alock(this);
1687
1688 if (mSSData->mStateFilePath.isEmpty())
1689 Bstr("").cloneTo(aStateFilePath);
1690 else
1691 mSSData->mStateFilePath.cloneTo(aStateFilePath);
1692
1693 return S_OK;
1694}
1695
1696STDMETHODIMP Machine::COMGETTER(LogFolder) (BSTR *aLogFolder)
1697{
1698 CheckComArgOutPointerValid(aLogFolder);
1699
1700 AutoCaller autoCaller(this);
1701 AssertComRCReturnRC(autoCaller.rc());
1702
1703 AutoReadLock alock(this);
1704
1705 Utf8Str logFolder;
1706 getLogFolder (logFolder);
1707
1708 Bstr (logFolder).cloneTo(aLogFolder);
1709
1710 return S_OK;
1711}
1712
1713STDMETHODIMP Machine::COMGETTER(CurrentSnapshot) (ISnapshot **aCurrentSnapshot)
1714{
1715 CheckComArgOutPointerValid(aCurrentSnapshot);
1716
1717 AutoCaller autoCaller(this);
1718 CheckComRCReturnRC(autoCaller.rc());
1719
1720 AutoReadLock alock(this);
1721
1722 mData->mCurrentSnapshot.queryInterfaceTo(aCurrentSnapshot);
1723
1724 return S_OK;
1725}
1726
1727STDMETHODIMP Machine::COMGETTER(SnapshotCount)(ULONG *aSnapshotCount)
1728{
1729 CheckComArgOutPointerValid(aSnapshotCount);
1730
1731 AutoCaller autoCaller(this);
1732 CheckComRCReturnRC(autoCaller.rc());
1733
1734 AutoReadLock alock(this);
1735
1736 *aSnapshotCount = mData->mFirstSnapshot.isNull()
1737 ? 0
1738 : mData->mFirstSnapshot->getAllChildrenCount() + 1;
1739
1740 return S_OK;
1741}
1742
1743STDMETHODIMP Machine::COMGETTER(CurrentStateModified) (BOOL *aCurrentStateModified)
1744{
1745 CheckComArgOutPointerValid(aCurrentStateModified);
1746
1747 AutoCaller autoCaller(this);
1748 CheckComRCReturnRC(autoCaller.rc());
1749
1750 AutoReadLock alock(this);
1751
1752 /* Note: for machines with no snapshots, we always return FALSE
1753 * (mData->mCurrentStateModified will be TRUE in this case, for historical
1754 * reasons :) */
1755
1756 *aCurrentStateModified = mData->mFirstSnapshot.isNull()
1757 ? FALSE
1758 : mData->mCurrentStateModified;
1759
1760 return S_OK;
1761}
1762
1763STDMETHODIMP Machine::COMGETTER(SharedFolders) (ComSafeArrayOut(ISharedFolder *, aSharedFolders))
1764{
1765 CheckComArgOutSafeArrayPointerValid(aSharedFolders);
1766
1767 AutoCaller autoCaller(this);
1768 CheckComRCReturnRC(autoCaller.rc());
1769
1770 AutoReadLock alock(this);
1771
1772 SafeIfaceArray<ISharedFolder> folders(mHWData->mSharedFolders);
1773 folders.detachTo(ComSafeArrayOutArg(aSharedFolders));
1774
1775 return S_OK;
1776}
1777
1778STDMETHODIMP Machine::COMGETTER(ClipboardMode) (ClipboardMode_T *aClipboardMode)
1779{
1780 CheckComArgOutPointerValid(aClipboardMode);
1781
1782 AutoCaller autoCaller(this);
1783 CheckComRCReturnRC(autoCaller.rc());
1784
1785 AutoReadLock alock(this);
1786
1787 *aClipboardMode = mHWData->mClipboardMode;
1788
1789 return S_OK;
1790}
1791
1792STDMETHODIMP
1793Machine::COMSETTER(ClipboardMode) (ClipboardMode_T aClipboardMode)
1794{
1795 AutoCaller autoCaller(this);
1796 CheckComRCReturnRC(autoCaller.rc());
1797
1798 AutoWriteLock alock(this);
1799
1800 HRESULT rc = checkStateDependency(MutableStateDep);
1801 CheckComRCReturnRC(rc);
1802
1803 mHWData.backup();
1804 mHWData->mClipboardMode = aClipboardMode;
1805
1806 return S_OK;
1807}
1808
1809STDMETHODIMP
1810Machine::COMGETTER(GuestPropertyNotificationPatterns) (BSTR *aPatterns)
1811{
1812 CheckComArgOutPointerValid(aPatterns);
1813
1814 AutoCaller autoCaller(this);
1815 CheckComRCReturnRC(autoCaller.rc());
1816
1817 AutoReadLock alock(this);
1818
1819 mHWData->mGuestPropertyNotificationPatterns.cloneTo(aPatterns);
1820
1821 return RT_LIKELY (aPatterns != NULL) ? S_OK : E_OUTOFMEMORY; /** @todo r=bird: this is wrong... :-) */
1822}
1823
1824STDMETHODIMP
1825Machine::COMSETTER(GuestPropertyNotificationPatterns) (IN_BSTR aPatterns)
1826{
1827 AssertLogRelReturn (VALID_PTR (aPatterns), E_POINTER);
1828 AutoCaller autoCaller(this);
1829 CheckComRCReturnRC(autoCaller.rc());
1830
1831 AutoWriteLock alock(this);
1832
1833 HRESULT rc = checkStateDependency(MutableStateDep);
1834 CheckComRCReturnRC(rc);
1835
1836 mHWData.backup();
1837 mHWData->mGuestPropertyNotificationPatterns = aPatterns;
1838
1839 return RT_LIKELY (!mHWData->mGuestPropertyNotificationPatterns.isNull())
1840 ? S_OK : E_OUTOFMEMORY;
1841}
1842
1843STDMETHODIMP
1844Machine::COMGETTER(StorageControllers) (ComSafeArrayOut(IStorageController *, aStorageControllers))
1845{
1846 CheckComArgOutSafeArrayPointerValid(aStorageControllers);
1847
1848 AutoCaller autoCaller(this);
1849 CheckComRCReturnRC(autoCaller.rc());
1850
1851 AutoReadLock alock(this);
1852
1853 SafeIfaceArray<IStorageController> ctrls (*mStorageControllers.data());
1854 ctrls.detachTo(ComSafeArrayOutArg(aStorageControllers));
1855
1856 return S_OK;
1857}
1858
1859STDMETHODIMP
1860Machine::COMGETTER(LiveMigrationTarget)(BOOL *aEnabled)
1861{
1862 CheckComArgOutPointerValid(aEnabled);
1863
1864 AutoCaller autoCaller(this);
1865 CheckComRCReturnRC(autoCaller.rc());
1866
1867 AutoReadLock alock(this);
1868
1869 *aEnabled = mUserData->mLiveMigrationTarget;
1870
1871 return S_OK;
1872}
1873
1874STDMETHODIMP
1875Machine::COMSETTER(LiveMigrationTarget)(BOOL aEnabled)
1876{
1877 AutoCaller autoCaller(this);
1878 CheckComRCReturnRC(autoCaller.rc());
1879
1880 AutoWriteLock alock(this);
1881
1882 /* Only allow it to be set to true when PoweredOff.
1883 (Clearing it is always permitted.) */
1884 if ( aEnabled
1885 && mData->mRegistered
1886 && ( mType != IsSessionMachine
1887 || mData->mMachineState > MachineState_PoweredOff)
1888 )
1889 return setError(VBOX_E_INVALID_VM_STATE,
1890 tr("The machine is not powered off (state is %d)"),
1891 mData->mMachineState);
1892
1893 mUserData.backup();
1894 mUserData->mLiveMigrationTarget = aEnabled;
1895
1896 return S_OK;
1897}
1898
1899STDMETHODIMP
1900Machine::COMGETTER(LiveMigrationPort)(ULONG *aPort)
1901{
1902 CheckComArgOutPointerValid(aPort);
1903
1904 AutoCaller autoCaller(this);
1905 CheckComRCReturnRC(autoCaller.rc());
1906
1907 AutoReadLock alock(this);
1908
1909 *aPort = mUserData->mLiveMigrationPort;
1910
1911 return S_OK;
1912}
1913
1914STDMETHODIMP
1915Machine::COMSETTER(LiveMigrationPort)(ULONG aPort)
1916{
1917 if (aPort >= _64K)
1918 return setError(E_INVALIDARG, tr("Invalid port number %d"), aPort);
1919
1920 AutoCaller autoCaller(this);
1921 CheckComRCReturnRC(autoCaller.rc());
1922
1923 AutoWriteLock alock(this);
1924
1925 HRESULT rc = checkStateDependency(MutableStateDep);
1926 CheckComRCReturnRC(rc);
1927
1928 mUserData.backup();
1929 mUserData->mLiveMigrationPort = aPort;
1930
1931 return S_OK;
1932}
1933
1934STDMETHODIMP
1935Machine::COMGETTER(LiveMigrationPassword)(BSTR *aPassword)
1936{
1937 CheckComArgOutPointerValid(aPassword);
1938
1939 AutoCaller autoCaller(this);
1940 CheckComRCReturnRC(autoCaller.rc());
1941
1942 AutoReadLock alock(this);
1943
1944 mUserData->mLiveMigrationPassword.cloneTo(aPassword);
1945
1946 return S_OK;
1947}
1948
1949STDMETHODIMP
1950Machine::COMSETTER(LiveMigrationPassword)(IN_BSTR aPassword)
1951{
1952 AutoCaller autoCaller(this);
1953 CheckComRCReturnRC(autoCaller.rc());
1954
1955 AutoWriteLock alock(this);
1956
1957 HRESULT rc = checkStateDependency(MutableStateDep);
1958 CheckComRCReturnRC(rc);
1959
1960 mUserData.backup();
1961 mUserData->mLiveMigrationPassword = aPassword;
1962
1963 return S_OK;
1964}
1965
1966
1967// IMachine methods
1968/////////////////////////////////////////////////////////////////////////////
1969
1970STDMETHODIMP Machine::SetBootOrder (ULONG aPosition, DeviceType_T aDevice)
1971{
1972 if (aPosition < 1 || aPosition > SchemaDefs::MaxBootPosition)
1973 return setError(E_INVALIDARG,
1974 tr ("Invalid boot position: %lu (must be in range [1, %lu])"),
1975 aPosition, SchemaDefs::MaxBootPosition);
1976
1977 if (aDevice == DeviceType_USB)
1978 return setError(E_NOTIMPL,
1979 tr("Booting from USB device is currently not supported"));
1980
1981 AutoCaller autoCaller(this);
1982 CheckComRCReturnRC(autoCaller.rc());
1983
1984 AutoWriteLock alock(this);
1985
1986 HRESULT rc = checkStateDependency(MutableStateDep);
1987 CheckComRCReturnRC(rc);
1988
1989 mHWData.backup();
1990 mHWData->mBootOrder [aPosition - 1] = aDevice;
1991
1992 return S_OK;
1993}
1994
1995STDMETHODIMP Machine::GetBootOrder (ULONG aPosition, DeviceType_T *aDevice)
1996{
1997 if (aPosition < 1 || aPosition > SchemaDefs::MaxBootPosition)
1998 return setError(E_INVALIDARG,
1999 tr("Invalid boot position: %lu (must be in range [1, %lu])"),
2000 aPosition, SchemaDefs::MaxBootPosition);
2001
2002 AutoCaller autoCaller(this);
2003 CheckComRCReturnRC(autoCaller.rc());
2004
2005 AutoReadLock alock(this);
2006
2007 *aDevice = mHWData->mBootOrder [aPosition - 1];
2008
2009 return S_OK;
2010}
2011
2012STDMETHODIMP Machine::AttachDevice(IN_BSTR aControllerName,
2013 LONG aControllerPort,
2014 LONG aDevice,
2015 DeviceType_T aType,
2016 IN_BSTR aId)
2017{
2018 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d\n",
2019 aControllerName, aControllerPort, aDevice));
2020
2021 AutoCaller autoCaller(this);
2022 CheckComRCReturnRC(autoCaller.rc());
2023
2024 /* VirtualBox::findHardDisk() and the corresponding other methods for
2025 * DVD and floppy media need *write* lock (for getting rid of unneeded
2026 * host drives which got enumerated); also we want to make sure the
2027 * media object we pick up doesn't get unregistered before we finish. */
2028 AutoMultiWriteLock2 alock(mParent, this);
2029
2030 HRESULT rc = checkStateDependency(MutableStateDep);
2031 CheckComRCReturnRC(rc);
2032
2033 /// @todo NEWMEDIA implicit machine registration
2034 if (!mData->mRegistered)
2035 return setError(VBOX_E_INVALID_OBJECT_STATE,
2036 tr("Cannot attach storage devices to an unregistered machine"));
2037
2038 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
2039
2040 if (Global::IsOnlineOrTransient(mData->mMachineState))
2041 return setError(VBOX_E_INVALID_VM_STATE,
2042 tr("Invalid machine state: %d"),
2043 mData->mMachineState);
2044
2045 /* Check for an existing controller. */
2046 ComObjPtr<StorageController> ctl;
2047 rc = getStorageControllerByName(aControllerName, ctl, true /* aSetError */);
2048 CheckComRCReturnRC(rc);
2049
2050 /* check that the port and device are not out of range. */
2051 ULONG portCount;
2052 ULONG devicesPerPort;
2053 rc = ctl->COMGETTER(PortCount)(&portCount);
2054 CheckComRCReturnRC(rc);
2055 rc = ctl->COMGETTER(MaxDevicesPerPortCount)(&devicesPerPort);
2056 CheckComRCReturnRC(rc);
2057
2058 if ( (aControllerPort < 0)
2059 || (aControllerPort >= (LONG)portCount)
2060 || (aDevice < 0)
2061 || (aDevice >= (LONG)devicesPerPort)
2062 )
2063 return setError(E_INVALIDARG,
2064 tr("The port and/or count parameter are out of range [%lu:%lu]"),
2065 portCount,
2066 devicesPerPort);
2067
2068 /* check if the device slot is already busy */
2069 MediumAttachment *pAttachTemp;
2070 if ((pAttachTemp = findAttachment(mMediaData->mAttachments,
2071 aControllerName,
2072 aControllerPort,
2073 aDevice)))
2074 {
2075 Medium *pMedium = pAttachTemp->medium();
2076 if (pMedium)
2077 {
2078 AutoReadLock mediumLock(pMedium);
2079 return setError(VBOX_E_OBJECT_IN_USE,
2080 tr("Medium '%ls' is already attached to device slot %d on port %d of controller '%ls' of this virtual machine"),
2081 pMedium->locationFull().raw(), aDevice, aControllerPort, aControllerName);
2082 }
2083 else
2084 return setError(VBOX_E_OBJECT_IN_USE,
2085 tr("Device is already attached to slot %d on port %d of controller '%ls' of this virtual machine"),
2086 aDevice, aControllerPort, aControllerName);
2087 }
2088
2089 Guid id(aId);
2090
2091 ComObjPtr<Medium> medium;
2092 switch (aType)
2093 {
2094 case DeviceType_HardDisk:
2095 /* find a hard disk by UUID */
2096 rc = mParent->findHardDisk(&id, NULL, true /* aSetError */, &medium);
2097 CheckComRCReturnRC(rc);
2098 break;
2099
2100 case DeviceType_DVD:
2101 if (!id.isEmpty())
2102 {
2103 /* first search for host drive */
2104 SafeIfaceArray<IMedium> drivevec;
2105 rc = mParent->host()->COMGETTER(DVDDrives)(ComSafeArrayAsOutParam(drivevec));
2106 if (SUCCEEDED(rc))
2107 {
2108 for (size_t i = 0; i < drivevec.size(); ++i)
2109 {
2110 /// @todo eliminate this conversion
2111 ComObjPtr<Medium> med = (Medium *)drivevec[i];
2112 if (med->id() == id)
2113 {
2114 medium = med;
2115 break;
2116 }
2117 }
2118 }
2119
2120 if (medium.isNull())
2121 {
2122 /* find a DVD image by UUID */
2123 rc = mParent->findDVDImage(&id, NULL, true /* aSetError */, &medium);
2124 CheckComRCReturnRC(rc);
2125 }
2126 }
2127 else
2128 {
2129 /* null UUID means null medium, which needs no code */
2130 }
2131 break;
2132
2133 case DeviceType_Floppy:
2134 if (!id.isEmpty())
2135 {
2136 /* first search for host drive */
2137 SafeIfaceArray<IMedium> drivevec;
2138 rc = mParent->host()->COMGETTER(FloppyDrives)(ComSafeArrayAsOutParam(drivevec));
2139 if (SUCCEEDED(rc))
2140 {
2141 for (size_t i = 0; i < drivevec.size(); ++i)
2142 {
2143 /// @todo eliminate this conversion
2144 ComObjPtr<Medium> med = (Medium *)drivevec[i];
2145 if (med->id() == id)
2146 {
2147 medium = med;
2148 break;
2149 }
2150 }
2151 }
2152
2153 if (medium.isNull())
2154 {
2155 /* find a floppy image by UUID */
2156 rc = mParent->findFloppyImage(&id, NULL, true /* aSetError */, &medium);
2157 CheckComRCReturnRC(rc);
2158 }
2159 }
2160 else
2161 {
2162 /* null UUID means null medium, which needs no code */
2163 }
2164 break;
2165
2166 default:
2167 return setError(E_INVALIDARG,
2168 tr("The device type %d is not recognized"),
2169 (int)aType);
2170 }
2171
2172 AutoCaller mediumCaller(medium);
2173 CheckComRCReturnRC(mediumCaller.rc());
2174
2175 AutoWriteLock mediumLock(medium);
2176
2177 if ( (pAttachTemp = findAttachment(mMediaData->mAttachments, medium))
2178 && !medium.isNull())
2179 {
2180 return setError(VBOX_E_OBJECT_IN_USE,
2181 tr("Medium '%ls' is already attached to this virtual machine"),
2182 medium->locationFull().raw());
2183 }
2184
2185 bool indirect = false;
2186 if (!medium.isNull())
2187 indirect = medium->isReadOnly();
2188 bool associate = true;
2189
2190 do
2191 {
2192 if (mMediaData.isBackedUp())
2193 {
2194 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
2195
2196 /* check if the medium was attached to the VM before we started
2197 * changing attachments in which case the attachment just needs to
2198 * be restored */
2199 if ((pAttachTemp = findAttachment(oldAtts, medium)))
2200 {
2201 AssertReturn(!indirect, E_FAIL);
2202
2203 /* see if it's the same bus/channel/device */
2204 if (pAttachTemp->matches(aControllerName, aControllerPort, aDevice))
2205 {
2206 /* the simplest case: restore the whole attachment
2207 * and return, nothing else to do */
2208 mMediaData->mAttachments.push_back(pAttachTemp);
2209 return S_OK;
2210 }
2211
2212 /* bus/channel/device differ; we need a new attachment object,
2213 * but don't try to associate it again */
2214 associate = false;
2215 break;
2216 }
2217 }
2218
2219 /* go further only if the attachment is to be indirect */
2220 if (!indirect)
2221 break;
2222
2223 /* perform the so called smart attachment logic for indirect
2224 * attachments. Note that smart attachment is only applicable to base
2225 * hard disks. */
2226
2227 if (medium->parent().isNull())
2228 {
2229 /* first, investigate the backup copy of the current hard disk
2230 * attachments to make it possible to re-attach existing diffs to
2231 * another device slot w/o losing their contents */
2232 if (mMediaData.isBackedUp())
2233 {
2234 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
2235
2236 MediaData::AttachmentList::const_iterator foundIt = oldAtts.end();
2237 uint32_t foundLevel = 0;
2238
2239 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
2240 it != oldAtts.end();
2241 ++it)
2242 {
2243 uint32_t level = 0;
2244 MediumAttachment *pAttach = *it;
2245 ComObjPtr<Medium> pMedium = pAttach->medium();
2246 Assert(!pMedium.isNull() || pAttach->type() != DeviceType_HardDisk);
2247 if (pMedium.isNull())
2248 continue;
2249
2250 if (pMedium->base(&level).equalsTo(medium))
2251 {
2252 /* skip the hard disk if its currently attached (we
2253 * cannot attach the same hard disk twice) */
2254 if (findAttachment(mMediaData->mAttachments,
2255 pMedium))
2256 continue;
2257
2258 /* matched device, channel and bus (i.e. attached to the
2259 * same place) will win and immediately stop the search;
2260 * otherwise the attachment that has the youngest
2261 * descendant of medium will be used
2262 */
2263 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
2264 {
2265 /* the simplest case: restore the whole attachment
2266 * and return, nothing else to do */
2267 mMediaData->mAttachments.push_back(*it);
2268 return S_OK;
2269 }
2270 else if ( foundIt == oldAtts.end()
2271 || level > foundLevel /* prefer younger */
2272 )
2273 {
2274 foundIt = it;
2275 foundLevel = level;
2276 }
2277 }
2278 }
2279
2280 if (foundIt != oldAtts.end())
2281 {
2282 /* use the previously attached hard disk */
2283 medium = (*foundIt)->medium();
2284 mediumCaller.attach(medium);
2285 CheckComRCReturnRC(mediumCaller.rc());
2286 mediumLock.attach(medium);
2287 /* not implicit, doesn't require association with this VM */
2288 indirect = false;
2289 associate = false;
2290 /* go right to the MediumAttachment creation */
2291 break;
2292 }
2293 }
2294
2295 /* then, search through snapshots for the best diff in the given
2296 * hard disk's chain to base the new diff on */
2297
2298 ComObjPtr<Medium> base;
2299 ComObjPtr<Snapshot> snap = mData->mCurrentSnapshot;
2300 while (snap)
2301 {
2302 AutoReadLock snapLock(snap);
2303
2304 const MediaData::AttachmentList &snapAtts = snap->getSnapshotMachine()->mMediaData->mAttachments;
2305
2306 MediaData::AttachmentList::const_iterator foundIt = snapAtts.end();
2307 uint32_t foundLevel = 0;
2308
2309 for (MediaData::AttachmentList::const_iterator it = snapAtts.begin();
2310 it != snapAtts.end();
2311 ++it)
2312 {
2313 MediumAttachment *pAttach = *it;
2314 ComObjPtr<Medium> pMedium = pAttach->medium();
2315 Assert(!pMedium.isNull() || pAttach->type() != DeviceType_HardDisk);
2316 if (pMedium.isNull())
2317 continue;
2318
2319 uint32_t level = 0;
2320 if (pMedium->base(&level).equalsTo(medium))
2321 {
2322 /* matched device, channel and bus (i.e. attached to the
2323 * same place) will win and immediately stop the search;
2324 * otherwise the attachment that has the youngest
2325 * descendant of medium will be used
2326 */
2327 if ( (*it)->device() == aDevice
2328 && (*it)->port() == aControllerPort
2329 && (*it)->controller() == aControllerName
2330 )
2331 {
2332 foundIt = it;
2333 break;
2334 }
2335 else if ( foundIt == snapAtts.end()
2336 || level > foundLevel /* prefer younger */
2337 )
2338 {
2339 foundIt = it;
2340 foundLevel = level;
2341 }
2342 }
2343 }
2344
2345 if (foundIt != snapAtts.end())
2346 {
2347 base = (*foundIt)->medium();
2348 break;
2349 }
2350
2351 snap = snap->parent();
2352 }
2353
2354 /* found a suitable diff, use it as a base */
2355 if (!base.isNull())
2356 {
2357 medium = base;
2358 mediumCaller.attach(medium);
2359 CheckComRCReturnRC(mediumCaller.rc());
2360 mediumLock.attach(medium);
2361 }
2362 }
2363
2364 ComObjPtr<Medium> diff;
2365 diff.createObject();
2366 rc = diff->init(mParent,
2367 medium->preferredDiffFormat().raw(),
2368 BstrFmt("%ls"RTPATH_SLASH_STR,
2369 mUserData->mSnapshotFolderFull.raw()).raw());
2370 CheckComRCReturnRC(rc);
2371
2372 /* make sure the hard disk is not modified before createDiffStorage() */
2373 rc = medium->LockRead(NULL);
2374 CheckComRCReturnRC(rc);
2375
2376 /* will leave the lock before the potentially lengthy operation, so
2377 * protect with the special state */
2378 MachineState_T oldState = mData->mMachineState;
2379 setMachineState(MachineState_SettingUp);
2380
2381 mediumLock.leave();
2382 alock.leave();
2383
2384 rc = medium->createDiffStorageAndWait(diff, MediumVariant_Standard);
2385
2386 alock.enter();
2387 mediumLock.enter();
2388
2389 setMachineState(oldState);
2390
2391 medium->UnlockRead(NULL);
2392
2393 CheckComRCReturnRC(rc);
2394
2395 /* use the created diff for the actual attachment */
2396 medium = diff;
2397 mediumCaller.attach(medium);
2398 CheckComRCReturnRC(mediumCaller.rc());
2399 mediumLock.attach(medium);
2400 }
2401 while (0);
2402
2403 ComObjPtr<MediumAttachment> attachment;
2404 attachment.createObject();
2405 rc = attachment->init(this, medium, aControllerName, aControllerPort, aDevice, aType, indirect);
2406 CheckComRCReturnRC(rc);
2407
2408 if (associate && !medium.isNull())
2409 {
2410 /* as the last step, associate the medium to the VM */
2411 rc = medium->attachTo(mData->mUuid);
2412 /* here we can fail because of Deleting, or being in process of
2413 * creating a Diff */
2414 CheckComRCReturnRC(rc);
2415 }
2416
2417 /* success: finally remember the attachment */
2418 mMediaData.backup();
2419 mMediaData->mAttachments.push_back(attachment);
2420
2421 return rc;
2422}
2423
2424STDMETHODIMP Machine::DetachDevice(IN_BSTR aControllerName, LONG aControllerPort,
2425 LONG aDevice)
2426{
2427 CheckComArgNotNull(aControllerName);
2428
2429 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld\n",
2430 aControllerName, aControllerPort, aDevice));
2431
2432 AutoCaller autoCaller(this);
2433 CheckComRCReturnRC(autoCaller.rc());
2434
2435 AutoWriteLock alock(this);
2436
2437 HRESULT rc = checkStateDependency(MutableStateDep);
2438 CheckComRCReturnRC(rc);
2439
2440 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
2441
2442 if (Global::IsOnlineOrTransient(mData->mMachineState))
2443 return setError(VBOX_E_INVALID_VM_STATE,
2444 tr("Invalid machine state: %d"), mData->mMachineState);
2445
2446 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
2447 aControllerName,
2448 aControllerPort,
2449 aDevice);
2450 if (!pAttach)
2451 return setError(VBOX_E_OBJECT_NOT_FOUND,
2452 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
2453 aDevice, aControllerPort, aControllerName);
2454
2455 ComObjPtr<Medium> hd = pAttach->medium();
2456
2457 if (pAttach->isImplicit())
2458 {
2459 /* attempt to implicitly delete the implicitly created diff */
2460
2461 /// @todo move the implicit flag from MediumAttachment to Medium
2462 /// and forbid any hard disk operation when it is implicit. Or maybe
2463 /// a special media state for it to make it even more simple.
2464
2465 Assert(mMediaData.isBackedUp());
2466
2467 /* will leave the lock before the potentially lengthy operation, so
2468 * protect with the special state */
2469 MachineState_T oldState = mData->mMachineState;
2470 setMachineState(MachineState_SettingUp);
2471
2472 alock.leave();
2473
2474 rc = hd->deleteStorageAndWait();
2475
2476 alock.enter();
2477
2478 setMachineState(oldState);
2479
2480 CheckComRCReturnRC(rc);
2481 }
2482
2483 mMediaData.backup();
2484
2485 /* we cannot use erase (it) below because backup() above will create
2486 * a copy of the list and make this copy active, but the iterator
2487 * still refers to the original and is not valid for the copy */
2488 mMediaData->mAttachments.remove(pAttach);
2489
2490 return S_OK;
2491}
2492
2493STDMETHODIMP Machine::MountMedium(IN_BSTR aControllerName,
2494 LONG aControllerPort,
2495 LONG aDevice,
2496 IN_BSTR aId)
2497{
2498 int rc = S_OK;
2499 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld\n",
2500 aControllerName, aControllerPort, aDevice));
2501
2502 CheckComArgNotNull(aControllerName);
2503
2504 AutoCaller autoCaller(this);
2505 CheckComRCReturnRC(autoCaller.rc());
2506
2507 AutoWriteLock alock(this);
2508
2509 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
2510 aControllerName,
2511 aControllerPort,
2512 aDevice);
2513 if (pAttach.isNull())
2514 return setError(VBOX_E_OBJECT_NOT_FOUND,
2515 tr("No drive attached to device slot %d on port %d of controller '%ls'"),
2516 aDevice, aControllerPort, aControllerName);
2517
2518 Guid id(aId);
2519 ComObjPtr<Medium> medium;
2520 switch (pAttach->type())
2521 {
2522 case DeviceType_DVD:
2523 if (!id.isEmpty())
2524 {
2525 /* find a DVD by host device UUID */
2526 SafeIfaceArray<IMedium> drivevec;
2527 rc = mParent->host()->COMGETTER(DVDDrives)(ComSafeArrayAsOutParam(drivevec));
2528 if (SUCCEEDED(rc))
2529 {
2530 for (size_t i = 0; i < drivevec.size(); ++i)
2531 {
2532 /// @todo eliminate this conversion
2533 ComObjPtr<Medium> med = (Medium *)drivevec[i];
2534 if (id == med->id())
2535 {
2536 medium = med;
2537 break;
2538 }
2539 }
2540 }
2541 /* find a DVD by UUID */
2542 if (medium.isNull())
2543 rc = mParent->findDVDImage(&id, NULL, true /* aDoSetError */, &medium);
2544 }
2545 CheckComRCReturnRC(rc);
2546 break;
2547 case DeviceType_Floppy:
2548 if (!id.isEmpty())
2549 {
2550 /* find a Floppy by host device UUID */
2551 SafeIfaceArray<IMedium> drivevec;
2552 rc = mParent->host()->COMGETTER(FloppyDrives)(ComSafeArrayAsOutParam(drivevec));
2553 if (SUCCEEDED(rc))
2554 {
2555 for (size_t i = 0; i < drivevec.size(); ++i)
2556 {
2557 /// @todo eliminate this conversion
2558 ComObjPtr<Medium> med = (Medium *)drivevec[i];
2559 if (id == med->id())
2560 {
2561 medium = med;
2562 break;
2563 }
2564 }
2565 }
2566 /* find a Floppy by UUID */
2567 if (medium.isNull())
2568 rc = mParent->findFloppyImage(&id, NULL, true /* aDoSetError */, &medium);
2569 }
2570 CheckComRCReturnRC(rc);
2571 break;
2572 default:
2573 return setError(VBOX_E_INVALID_OBJECT_STATE,
2574 tr("Cannot change medium attached to device slot %d on port %d of controller '%ls'"),
2575 aDevice, aControllerPort, aControllerName);
2576 }
2577
2578 if (SUCCEEDED(rc))
2579 {
2580 AutoWriteLock attLock(pAttach);
2581 pAttach->updateMedium(medium, false /* aImplicit */);
2582 }
2583
2584 alock.unlock();
2585 onMediumChange(pAttach);
2586
2587 return rc;
2588}
2589
2590STDMETHODIMP Machine::GetMedium(IN_BSTR aControllerName,
2591 LONG aControllerPort,
2592 LONG aDevice,
2593 IMedium **aMedium)
2594{
2595 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld\n",
2596 aControllerName, aControllerPort, aDevice));
2597
2598 CheckComArgNotNull(aControllerName);
2599 CheckComArgOutPointerValid(aMedium);
2600
2601 AutoCaller autoCaller(this);
2602 CheckComRCReturnRC(autoCaller.rc());
2603
2604 AutoReadLock alock(this);
2605
2606 *aMedium = NULL;
2607
2608 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
2609 aControllerName,
2610 aControllerPort,
2611 aDevice);
2612 if (pAttach.isNull())
2613 return setError(VBOX_E_OBJECT_NOT_FOUND,
2614 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
2615 aDevice, aControllerPort, aControllerName);
2616
2617 pAttach->medium().queryInterfaceTo(aMedium);
2618
2619 return S_OK;
2620}
2621
2622STDMETHODIMP Machine::GetSerialPort (ULONG slot, ISerialPort **port)
2623{
2624 CheckComArgOutPointerValid(port);
2625 CheckComArgExpr (slot, slot < RT_ELEMENTS (mSerialPorts));
2626
2627 AutoCaller autoCaller(this);
2628 CheckComRCReturnRC(autoCaller.rc());
2629
2630 AutoReadLock alock(this);
2631
2632 mSerialPorts [slot].queryInterfaceTo(port);
2633
2634 return S_OK;
2635}
2636
2637STDMETHODIMP Machine::GetParallelPort (ULONG slot, IParallelPort **port)
2638{
2639 CheckComArgOutPointerValid(port);
2640 CheckComArgExpr (slot, slot < RT_ELEMENTS (mParallelPorts));
2641
2642 AutoCaller autoCaller(this);
2643 CheckComRCReturnRC(autoCaller.rc());
2644
2645 AutoReadLock alock(this);
2646
2647 mParallelPorts [slot].queryInterfaceTo(port);
2648
2649 return S_OK;
2650}
2651
2652STDMETHODIMP Machine::GetNetworkAdapter (ULONG slot, INetworkAdapter **adapter)
2653{
2654 CheckComArgOutPointerValid(adapter);
2655 CheckComArgExpr (slot, slot < RT_ELEMENTS (mNetworkAdapters));
2656
2657 AutoCaller autoCaller(this);
2658 CheckComRCReturnRC(autoCaller.rc());
2659
2660 AutoReadLock alock(this);
2661
2662 mNetworkAdapters[slot].queryInterfaceTo(adapter);
2663
2664 return S_OK;
2665}
2666
2667STDMETHODIMP Machine::GetExtraDataKeys(ComSafeArrayOut(BSTR, aKeys))
2668{
2669 if (ComSafeArrayOutIsNull(aKeys))
2670 return E_POINTER;
2671
2672 AutoCaller autoCaller (this);
2673 CheckComRCReturnRC (autoCaller.rc());
2674
2675 AutoReadLock alock (this);
2676
2677 com::SafeArray<BSTR> saKeys(mData->m_pMachineConfigFile->mapExtraDataItems.size());
2678 int i = 0;
2679 for (settings::ExtraDataItemsMap::const_iterator it = mData->m_pMachineConfigFile->mapExtraDataItems.begin();
2680 it != mData->m_pMachineConfigFile->mapExtraDataItems.end();
2681 ++it, ++i)
2682 {
2683 const Utf8Str &strKey = it->first;
2684 strKey.cloneTo(&saKeys[i]);
2685 }
2686 saKeys.detachTo(ComSafeArrayOutArg(aKeys));
2687
2688 return S_OK;
2689 }
2690
2691 /**
2692 * @note Locks this object for reading.
2693 */
2694STDMETHODIMP Machine::GetExtraData(IN_BSTR aKey,
2695 BSTR *aValue)
2696{
2697 CheckComArgNotNull(aKey);
2698 CheckComArgOutPointerValid(aValue);
2699
2700 AutoCaller autoCaller (this);
2701 CheckComRCReturnRC (autoCaller.rc());
2702
2703 /* start with nothing found */
2704 Bstr("").cloneTo(aValue);
2705
2706 AutoReadLock alock (this);
2707
2708 settings::ExtraDataItemsMap::const_iterator it = mData->m_pMachineConfigFile->mapExtraDataItems.find(Utf8Str(aKey));
2709 if (it != mData->m_pMachineConfigFile->mapExtraDataItems.end())
2710 {
2711 // found:
2712 const Utf8Str &strValue = it->second;
2713 strValue.cloneTo(aValue);
2714 }
2715
2716 return S_OK;
2717}
2718
2719 /**
2720 * @note Locks mParent for writing + this object for writing.
2721 */
2722STDMETHODIMP Machine::SetExtraData(IN_BSTR aKey, IN_BSTR aValue)
2723{
2724 CheckComArgNotNull(aKey);
2725
2726 AutoCaller autoCaller(this);
2727 CheckComRCReturnRC (autoCaller.rc());
2728
2729 Utf8Str strKey(aKey);
2730 Utf8Str strValue(aValue);
2731 Utf8Str strOldValue; // empty
2732
2733 // locking note: we only hold the read lock briefly to look up the old value,
2734 // then release it and call the onExtraCanChange callbacks. There is a small
2735 // chance of a race insofar as the callback might be called twice if two callers
2736 // change the same key at the same time, but that's a much better solution
2737 // than the deadlock we had here before. The actual changing of the extradata
2738 // is then performed under the write lock and race-free.
2739
2740 // look up the old value first; if nothing's changed then we need not do anything
2741 {
2742 AutoReadLock alock(this); // hold read lock only while looking up
2743 settings::ExtraDataItemsMap::const_iterator it = mData->m_pMachineConfigFile->mapExtraDataItems.find(strKey);
2744 if (it != mData->m_pMachineConfigFile->mapExtraDataItems.end())
2745 strOldValue = it->second;
2746 }
2747
2748 bool fChanged;
2749 if ((fChanged = (strOldValue != strValue)))
2750 {
2751 // ask for permission from all listeners outside the locks;
2752 // onExtraDataCanChange() only briefly requests the VirtualBox
2753 // lock to copy the list of callbacks to invoke
2754 Bstr error;
2755 Bstr bstrValue;
2756 if (aValue)
2757 bstrValue = aValue;
2758 else
2759 bstrValue = (const char *)"";
2760
2761 if (!mParent->onExtraDataCanChange(mData->mUuid, aKey, bstrValue, error))
2762 {
2763 const char *sep = error.isEmpty() ? "" : ": ";
2764 CBSTR err = error.isNull() ? (CBSTR) L"" : error.raw();
2765 LogWarningFunc(("Someone vetoed! Change refused%s%ls\n",
2766 sep, err));
2767 return setError(E_ACCESSDENIED,
2768 tr("Could not set extra data because someone refused the requested change of '%ls' to '%ls'%s%ls"),
2769 aKey,
2770 bstrValue.raw(),
2771 sep,
2772 err);
2773 }
2774
2775 // data is changing and change not vetoed: then write it out under the locks
2776
2777 // saveSettings() needs VirtualBox write lock
2778 AutoMultiWriteLock2 alock(mParent, this);
2779
2780 if (mType == IsSnapshotMachine)
2781 {
2782 HRESULT rc = checkStateDependency(MutableStateDep);
2783 CheckComRCReturnRC (rc);
2784 }
2785
2786 if (strValue.isEmpty())
2787 mData->m_pMachineConfigFile->mapExtraDataItems.erase(strKey);
2788 else
2789 mData->m_pMachineConfigFile->mapExtraDataItems[strKey] = strValue;
2790 // creates a new key if needed
2791
2792 /* save settings on success */
2793 HRESULT rc = saveSettings();
2794 CheckComRCReturnRC (rc);
2795 }
2796
2797 // fire notification outside the lock
2798 if (fChanged)
2799 mParent->onExtraDataChange(mData->mUuid, aKey, aValue);
2800
2801 return S_OK;
2802}
2803
2804STDMETHODIMP Machine::SaveSettings()
2805{
2806 AutoCaller autoCaller(this);
2807 CheckComRCReturnRC(autoCaller.rc());
2808
2809 /* saveSettings() needs mParent lock */
2810 AutoMultiWriteLock2 alock(mParent, this);
2811
2812 /* when there was auto-conversion, we want to save the file even if
2813 * the VM is saved */
2814 HRESULT rc = checkStateDependency(MutableStateDep);
2815 CheckComRCReturnRC(rc);
2816
2817 /* the settings file path may never be null */
2818 ComAssertRet(!mData->m_strConfigFileFull.isEmpty(), E_FAIL);
2819
2820 /* save all VM data excluding snapshots */
2821 return saveSettings();
2822}
2823
2824STDMETHODIMP Machine::DiscardSettings()
2825{
2826 AutoCaller autoCaller(this);
2827 CheckComRCReturnRC(autoCaller.rc());
2828
2829 AutoWriteLock alock(this);
2830
2831 HRESULT rc = checkStateDependency(MutableStateDep);
2832 CheckComRCReturnRC(rc);
2833
2834 /*
2835 * during this rollback, the session will be notified if data has
2836 * been actually changed
2837 */
2838 rollback (true /* aNotify */);
2839
2840 return S_OK;
2841}
2842
2843STDMETHODIMP Machine::DeleteSettings()
2844{
2845 AutoCaller autoCaller(this);
2846 CheckComRCReturnRC(autoCaller.rc());
2847
2848 AutoWriteLock alock(this);
2849
2850 HRESULT rc = checkStateDependency(MutableStateDep);
2851 CheckComRCReturnRC(rc);
2852
2853 if (mData->mRegistered)
2854 return setError(VBOX_E_INVALID_VM_STATE,
2855 tr("Cannot delete settings of a registered machine"));
2856
2857 /* delete the settings only when the file actually exists */
2858 if (mData->m_pMachineConfigFile->fileExists())
2859 {
2860 int vrc = RTFileDelete(mData->m_strConfigFileFull.c_str());
2861 if (RT_FAILURE(vrc))
2862 return setError(VBOX_E_IPRT_ERROR,
2863 tr("Could not delete the settings file '%s' (%Rrc)"),
2864 mData->m_strConfigFileFull.raw(),
2865 vrc);
2866
2867 /* delete the Logs folder, nothing important should be left
2868 * there (we don't check for errors because the user might have
2869 * some private files there that we don't want to delete) */
2870 Utf8Str logFolder;
2871 getLogFolder(logFolder);
2872 Assert(logFolder.length());
2873 if (RTDirExists(logFolder.c_str()))
2874 {
2875 /* Delete all VBox.log[.N] files from the Logs folder
2876 * (this must be in sync with the rotation logic in
2877 * Console::powerUpThread()). Also, delete the VBox.png[.N]
2878 * files that may have been created by the GUI. */
2879 Utf8Str log = Utf8StrFmt("%s/VBox.log", logFolder.raw());
2880 RTFileDelete(log.c_str());
2881 log = Utf8StrFmt("%s/VBox.png", logFolder.raw());
2882 RTFileDelete(log.c_str());
2883 for (int i = 3; i >= 0; i--)
2884 {
2885 log = Utf8StrFmt("%s/VBox.log.%d", logFolder.raw(), i);
2886 RTFileDelete(log.c_str());
2887 log = Utf8StrFmt("%s/VBox.png.%d", logFolder.raw(), i);
2888 RTFileDelete(log.c_str());
2889 }
2890
2891 RTDirRemove(logFolder.c_str());
2892 }
2893
2894 /* delete the Snapshots folder, nothing important should be left
2895 * there (we don't check for errors because the user might have
2896 * some private files there that we don't want to delete) */
2897 Utf8Str snapshotFolder(mUserData->mSnapshotFolderFull);
2898 Assert(snapshotFolder.length());
2899 if (RTDirExists(snapshotFolder.c_str()))
2900 RTDirRemove(snapshotFolder.c_str());
2901
2902 /* delete the directory that contains the settings file, but only
2903 * if it matches the VM name (i.e. a structure created by default in
2904 * prepareSaveSettings()) */
2905 {
2906 Utf8Str settingsDir;
2907 if (isInOwnDir(&settingsDir))
2908 RTDirRemove(settingsDir.c_str());
2909 }
2910 }
2911
2912 return S_OK;
2913}
2914
2915STDMETHODIMP Machine::GetSnapshot (IN_BSTR aId, ISnapshot **aSnapshot)
2916{
2917 CheckComArgOutPointerValid(aSnapshot);
2918
2919 AutoCaller autoCaller(this);
2920 CheckComRCReturnRC(autoCaller.rc());
2921
2922 AutoReadLock alock(this);
2923
2924 Guid id(aId);
2925 ComObjPtr<Snapshot> snapshot;
2926
2927 HRESULT rc = findSnapshot (id, snapshot, true /* aSetError */);
2928 snapshot.queryInterfaceTo(aSnapshot);
2929
2930 return rc;
2931}
2932
2933STDMETHODIMP Machine::FindSnapshot (IN_BSTR aName, ISnapshot **aSnapshot)
2934{
2935 CheckComArgNotNull (aName);
2936 CheckComArgOutPointerValid(aSnapshot);
2937
2938 AutoCaller autoCaller(this);
2939 CheckComRCReturnRC(autoCaller.rc());
2940
2941 AutoReadLock alock(this);
2942
2943 ComObjPtr<Snapshot> snapshot;
2944
2945 HRESULT rc = findSnapshot (aName, snapshot, true /* aSetError */);
2946 snapshot.queryInterfaceTo(aSnapshot);
2947
2948 return rc;
2949}
2950
2951STDMETHODIMP Machine::SetCurrentSnapshot (IN_BSTR /* aId */)
2952{
2953 /// @todo (dmik) don't forget to set
2954 // mData->mCurrentStateModified to FALSE
2955
2956 return setError (E_NOTIMPL, "Not implemented");
2957}
2958
2959STDMETHODIMP Machine::CreateSharedFolder (IN_BSTR aName, IN_BSTR aHostPath, BOOL aWritable)
2960{
2961 CheckComArgNotNull(aName);
2962 CheckComArgNotNull(aHostPath);
2963
2964 AutoCaller autoCaller(this);
2965 CheckComRCReturnRC(autoCaller.rc());
2966
2967 AutoWriteLock alock(this);
2968
2969 HRESULT rc = checkStateDependency(MutableStateDep);
2970 CheckComRCReturnRC(rc);
2971
2972 ComObjPtr<SharedFolder> sharedFolder;
2973 rc = findSharedFolder (aName, sharedFolder, false /* aSetError */);
2974 if (SUCCEEDED(rc))
2975 return setError(VBOX_E_OBJECT_IN_USE,
2976 tr("Shared folder named '%ls' already exists"),
2977 aName);
2978
2979 sharedFolder.createObject();
2980 rc = sharedFolder->init (machine(), aName, aHostPath, aWritable);
2981 CheckComRCReturnRC(rc);
2982
2983 mHWData.backup();
2984 mHWData->mSharedFolders.push_back (sharedFolder);
2985
2986 /* inform the direct session if any */
2987 alock.leave();
2988 onSharedFolderChange();
2989
2990 return S_OK;
2991}
2992
2993STDMETHODIMP Machine::RemoveSharedFolder (IN_BSTR aName)
2994{
2995 CheckComArgNotNull (aName);
2996
2997 AutoCaller autoCaller(this);
2998 CheckComRCReturnRC(autoCaller.rc());
2999
3000 AutoWriteLock alock(this);
3001
3002 HRESULT rc = checkStateDependency(MutableStateDep);
3003 CheckComRCReturnRC(rc);
3004
3005 ComObjPtr<SharedFolder> sharedFolder;
3006 rc = findSharedFolder (aName, sharedFolder, true /* aSetError */);
3007 CheckComRCReturnRC(rc);
3008
3009 mHWData.backup();
3010 mHWData->mSharedFolders.remove (sharedFolder);
3011
3012 /* inform the direct session if any */
3013 alock.leave();
3014 onSharedFolderChange();
3015
3016 return S_OK;
3017}
3018
3019STDMETHODIMP Machine::CanShowConsoleWindow (BOOL *aCanShow)
3020{
3021 CheckComArgOutPointerValid(aCanShow);
3022
3023 /* start with No */
3024 *aCanShow = FALSE;
3025
3026 AutoCaller autoCaller(this);
3027 AssertComRCReturnRC(autoCaller.rc());
3028
3029 ComPtr<IInternalSessionControl> directControl;
3030 {
3031 AutoReadLock alock(this);
3032
3033 if (mData->mSession.mState != SessionState_Open)
3034 return setError(VBOX_E_INVALID_VM_STATE,
3035 tr("Machine session is not open (session state: %d)"),
3036 mData->mSession.mState);
3037
3038 directControl = mData->mSession.mDirectControl;
3039 }
3040
3041 /* ignore calls made after #OnSessionEnd() is called */
3042 if (!directControl)
3043 return S_OK;
3044
3045 ULONG64 dummy;
3046 return directControl->OnShowWindow (TRUE /* aCheck */, aCanShow, &dummy);
3047}
3048
3049STDMETHODIMP Machine::ShowConsoleWindow (ULONG64 *aWinId)
3050{
3051 CheckComArgOutPointerValid(aWinId);
3052
3053 AutoCaller autoCaller(this);
3054 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
3055
3056 ComPtr<IInternalSessionControl> directControl;
3057 {
3058 AutoReadLock alock(this);
3059
3060 if (mData->mSession.mState != SessionState_Open)
3061 return setError(E_FAIL,
3062 tr("Machine session is not open (session state: %d)"),
3063 mData->mSession.mState);
3064
3065 directControl = mData->mSession.mDirectControl;
3066 }
3067
3068 /* ignore calls made after #OnSessionEnd() is called */
3069 if (!directControl)
3070 return S_OK;
3071
3072 BOOL dummy;
3073 return directControl->OnShowWindow (FALSE /* aCheck */, &dummy, aWinId);
3074}
3075
3076STDMETHODIMP Machine::GetGuestProperty(IN_BSTR aName,
3077 BSTR *aValue,
3078 ULONG64 *aTimestamp,
3079 BSTR *aFlags)
3080{
3081#if !defined (VBOX_WITH_GUEST_PROPS)
3082 ReturnComNotImplemented();
3083#else
3084 CheckComArgNotNull(aName);
3085 CheckComArgOutPointerValid(aValue);
3086 CheckComArgOutPointerValid(aTimestamp);
3087 CheckComArgOutPointerValid(aFlags);
3088
3089 AutoCaller autoCaller(this);
3090 CheckComRCReturnRC(autoCaller.rc());
3091
3092 AutoReadLock alock(this);
3093
3094 using namespace guestProp;
3095 HRESULT rc = E_FAIL;
3096
3097 Utf8Str strName(aName);
3098
3099 if (!mHWData->mPropertyServiceActive)
3100 {
3101 bool found = false;
3102 for (HWData::GuestPropertyList::const_iterator it = mHWData->mGuestProperties.begin();
3103 (it != mHWData->mGuestProperties.end()) && !found;
3104 ++it)
3105 {
3106 if (it->strName == strName)
3107 {
3108 char szFlags[MAX_FLAGS_LEN + 1];
3109 it->strValue.cloneTo(aValue);
3110 *aTimestamp = it->mTimestamp;
3111 writeFlags(it->mFlags, szFlags);
3112 Bstr(szFlags).cloneTo(aFlags);
3113 found = true;
3114 }
3115 }
3116 rc = S_OK;
3117 }
3118 else
3119 {
3120 ComPtr<IInternalSessionControl> directControl =
3121 mData->mSession.mDirectControl;
3122
3123 /* just be on the safe side when calling another process */
3124 alock.unlock();
3125
3126 /* fail if we were called after #OnSessionEnd() is called. This is a
3127 * silly race condition. */
3128
3129 if (!directControl)
3130 rc = E_FAIL;
3131 else
3132 rc = directControl->AccessGuestProperty (aName, NULL, NULL,
3133 false /* isSetter */,
3134 aValue, aTimestamp, aFlags);
3135 }
3136 return rc;
3137#endif /* else !defined (VBOX_WITH_GUEST_PROPS) */
3138}
3139
3140STDMETHODIMP Machine::GetGuestPropertyValue (IN_BSTR aName, BSTR *aValue)
3141{
3142 ULONG64 dummyTimestamp;
3143 BSTR dummyFlags;
3144 return GetGuestProperty (aName, aValue, &dummyTimestamp, &dummyFlags);
3145}
3146
3147STDMETHODIMP Machine::GetGuestPropertyTimestamp (IN_BSTR aName, ULONG64 *aTimestamp)
3148{
3149 BSTR dummyValue;
3150 BSTR dummyFlags;
3151 return GetGuestProperty (aName, &dummyValue, aTimestamp, &dummyFlags);
3152}
3153
3154STDMETHODIMP Machine::SetGuestProperty(IN_BSTR aName,
3155 IN_BSTR aValue,
3156 IN_BSTR aFlags)
3157{
3158#if !defined (VBOX_WITH_GUEST_PROPS)
3159 ReturnComNotImplemented();
3160#else
3161 using namespace guestProp;
3162
3163 CheckComArgNotNull(aName);
3164 CheckComArgNotNull(aValue);
3165 if ((aFlags != NULL) && !VALID_PTR (aFlags))
3166 return E_INVALIDARG;
3167
3168 HRESULT rc = S_OK;
3169
3170 try
3171 {
3172 Utf8Str utf8Name(aName);
3173 Utf8Str utf8Flags(aFlags);
3174 Utf8Str utf8Patterns(mHWData->mGuestPropertyNotificationPatterns);
3175
3176 bool matchAll = false;
3177 if (utf8Patterns.isEmpty())
3178 matchAll = true;
3179
3180 uint32_t fFlags = NILFLAG;
3181 if ( (aFlags != NULL)
3182 && RT_FAILURE(validateFlags (utf8Flags.raw(), &fFlags))
3183 )
3184 return setError(E_INVALIDARG,
3185 tr("Invalid flag values: '%ls'"),
3186 aFlags);
3187
3188 AutoCaller autoCaller(this);
3189 CheckComRCReturnRC(autoCaller.rc());
3190
3191 AutoWriteLock alock(this);
3192
3193 rc = checkStateDependency(MutableStateDep);
3194 CheckComRCReturnRC(rc);
3195
3196 rc = S_OK;
3197
3198 if (!mHWData->mPropertyServiceActive)
3199 {
3200 bool found = false;
3201 HWData::GuestProperty property;
3202 property.mFlags = NILFLAG;
3203
3204 if (SUCCEEDED(rc))
3205 {
3206 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
3207 it != mHWData->mGuestProperties.end();
3208 ++it)
3209 if (it->strName == utf8Name)
3210 {
3211 property = *it;
3212 if (it->mFlags & (RDONLYHOST))
3213 rc = setError(E_ACCESSDENIED,
3214 tr("The property '%ls' cannot be changed by the host"),
3215 aName);
3216 else
3217 {
3218 mHWData.backup();
3219 /* The backup() operation invalidates our iterator, so
3220 * get a new one. */
3221 for (it = mHWData->mGuestProperties.begin();
3222 it->strName != utf8Name;
3223 ++it)
3224 ;
3225 mHWData->mGuestProperties.erase (it);
3226 }
3227 found = true;
3228 break;
3229 }
3230 }
3231 if (found && SUCCEEDED(rc))
3232 {
3233 if (*aValue)
3234 {
3235 RTTIMESPEC time;
3236 property.strValue = aValue;
3237 property.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
3238 if (aFlags != NULL)
3239 property.mFlags = fFlags;
3240 mHWData->mGuestProperties.push_back (property);
3241 }
3242 }
3243 else if (SUCCEEDED(rc) && *aValue)
3244 {
3245 RTTIMESPEC time;
3246 mHWData.backup();
3247 property.strName = aName;
3248 property.strValue = aValue;
3249 property.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
3250 property.mFlags = fFlags;
3251 mHWData->mGuestProperties.push_back (property);
3252 }
3253 if ( SUCCEEDED(rc)
3254 && ( matchAll
3255 || RTStrSimplePatternMultiMatch (utf8Patterns.raw(), RTSTR_MAX,
3256 utf8Name.raw(), RTSTR_MAX, NULL)
3257 )
3258 )
3259 mParent->onGuestPropertyChange (mData->mUuid, aName, aValue, aFlags);
3260 }
3261 else
3262 {
3263 ComPtr<IInternalSessionControl> directControl =
3264 mData->mSession.mDirectControl;
3265
3266 /* just be on the safe side when calling another process */
3267 alock.leave();
3268
3269 BSTR dummy = NULL;
3270 ULONG64 dummy64;
3271 if (!directControl)
3272 rc = E_FAIL;
3273 else
3274 rc = directControl->AccessGuestProperty(aName, aValue, aFlags,
3275 true /* isSetter */,
3276 &dummy, &dummy64, &dummy);
3277 }
3278 }
3279 catch (std::bad_alloc &)
3280 {
3281 rc = E_OUTOFMEMORY;
3282 }
3283
3284 return rc;
3285#endif /* else !defined (VBOX_WITH_GUEST_PROPS) */
3286}
3287
3288STDMETHODIMP Machine::SetGuestPropertyValue (IN_BSTR aName, IN_BSTR aValue)
3289{
3290 return SetGuestProperty (aName, aValue, NULL);
3291}
3292
3293STDMETHODIMP Machine::EnumerateGuestProperties(IN_BSTR aPatterns,
3294 ComSafeArrayOut(BSTR, aNames),
3295 ComSafeArrayOut(BSTR, aValues),
3296 ComSafeArrayOut(ULONG64, aTimestamps),
3297 ComSafeArrayOut(BSTR, aFlags))
3298{
3299#if !defined (VBOX_WITH_GUEST_PROPS)
3300 ReturnComNotImplemented();
3301#else
3302 if (!VALID_PTR (aPatterns) && (aPatterns != NULL))
3303 return E_POINTER;
3304
3305 CheckComArgOutSafeArrayPointerValid(aNames);
3306 CheckComArgOutSafeArrayPointerValid(aValues);
3307 CheckComArgOutSafeArrayPointerValid(aTimestamps);
3308 CheckComArgOutSafeArrayPointerValid(aFlags);
3309
3310 AutoCaller autoCaller(this);
3311 CheckComRCReturnRC(autoCaller.rc());
3312
3313 AutoReadLock alock(this);
3314
3315 using namespace guestProp;
3316 HRESULT rc = E_FAIL;
3317
3318 Utf8Str strPatterns(aPatterns);
3319
3320 bool matchAll = false;
3321 if ((NULL == aPatterns) || (0 == aPatterns[0]))
3322 matchAll = true;
3323 if (!mHWData->mPropertyServiceActive)
3324 {
3325
3326 /*
3327 * Look for matching patterns and build up a list.
3328 */
3329 HWData::GuestPropertyList propList;
3330 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
3331 it != mHWData->mGuestProperties.end();
3332 ++it)
3333 if ( matchAll
3334 || RTStrSimplePatternMultiMatch(strPatterns.raw(),
3335 RTSTR_MAX,
3336 it->strName.raw(),
3337 RTSTR_MAX, NULL)
3338 )
3339 propList.push_back(*it);
3340
3341 /*
3342 * And build up the arrays for returning the property information.
3343 */
3344 size_t cEntries = propList.size();
3345 SafeArray<BSTR> names (cEntries);
3346 SafeArray<BSTR> values (cEntries);
3347 SafeArray<ULONG64> timestamps (cEntries);
3348 SafeArray<BSTR> flags (cEntries);
3349 size_t iProp = 0;
3350 for (HWData::GuestPropertyList::iterator it = propList.begin();
3351 it != propList.end();
3352 ++it)
3353 {
3354 char szFlags[MAX_FLAGS_LEN + 1];
3355 it->strName.cloneTo(&names[iProp]);
3356 it->strValue.cloneTo(&values[iProp]);
3357 timestamps[iProp] = it->mTimestamp;
3358 writeFlags(it->mFlags, szFlags);
3359 Bstr(szFlags).cloneTo(&flags[iProp]);
3360 ++iProp;
3361 }
3362 names.detachTo(ComSafeArrayOutArg(aNames));
3363 values.detachTo(ComSafeArrayOutArg(aValues));
3364 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
3365 flags.detachTo(ComSafeArrayOutArg(aFlags));
3366 rc = S_OK;
3367 }
3368 else
3369 {
3370 ComPtr<IInternalSessionControl> directControl = mData->mSession.mDirectControl;
3371
3372 /* just be on the safe side when calling another process */
3373 alock.unlock();
3374
3375 if (!directControl)
3376 rc = E_FAIL;
3377 else
3378 rc = directControl->EnumerateGuestProperties(aPatterns,
3379 ComSafeArrayOutArg(aNames),
3380 ComSafeArrayOutArg(aValues),
3381 ComSafeArrayOutArg(aTimestamps),
3382 ComSafeArrayOutArg(aFlags));
3383 }
3384 return rc;
3385#endif /* else !defined (VBOX_WITH_GUEST_PROPS) */
3386}
3387
3388STDMETHODIMP Machine::GetMediumAttachmentsOfController(IN_BSTR aName,
3389 ComSafeArrayOut(IMediumAttachment*, aAttachments))
3390{
3391 MediaData::AttachmentList atts;
3392
3393 HRESULT rc = getMediumAttachmentsOfController(aName, atts);
3394 CheckComRCReturnRC(rc);
3395
3396 SafeIfaceArray<IMediumAttachment> attachments(atts);
3397 attachments.detachTo(ComSafeArrayOutArg(aAttachments));
3398
3399 return S_OK;
3400}
3401
3402STDMETHODIMP Machine::GetMediumAttachment(IN_BSTR aControllerName,
3403 LONG aControllerPort,
3404 LONG aDevice,
3405 IMediumAttachment **aAttachment)
3406{
3407 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d\n",
3408 aControllerName, aControllerPort, aDevice));
3409
3410 CheckComArgNotNull(aControllerName);
3411 CheckComArgOutPointerValid(aAttachment);
3412
3413 AutoCaller autoCaller(this);
3414 CheckComRCReturnRC(autoCaller.rc());
3415
3416 AutoReadLock alock(this);
3417
3418 *aAttachment = NULL;
3419
3420 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
3421 aControllerName,
3422 aControllerPort,
3423 aDevice);
3424 if (pAttach.isNull())
3425 return setError(VBOX_E_OBJECT_NOT_FOUND,
3426 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
3427 aDevice, aControllerPort, aControllerName);
3428
3429 pAttach.queryInterfaceTo(aAttachment);
3430
3431 return S_OK;
3432}
3433
3434STDMETHODIMP Machine::AddStorageController(IN_BSTR aName,
3435 StorageBus_T aConnectionType,
3436 IStorageController **controller)
3437{
3438 CheckComArgStrNotEmptyOrNull(aName);
3439
3440 if ( (aConnectionType <= StorageBus_Null)
3441 || (aConnectionType > StorageBus_Floppy))
3442 return setError (E_INVALIDARG,
3443 tr ("Invalid connection type: %d"),
3444 aConnectionType);
3445
3446 AutoCaller autoCaller(this);
3447 CheckComRCReturnRC(autoCaller.rc());
3448
3449 AutoWriteLock alock(this);
3450
3451 HRESULT rc = checkStateDependency(MutableStateDep);
3452 CheckComRCReturnRC(rc);
3453
3454 /* try to find one with the name first. */
3455 ComObjPtr<StorageController> ctrl;
3456
3457 rc = getStorageControllerByName (aName, ctrl, false /* aSetError */);
3458 if (SUCCEEDED(rc))
3459 return setError (VBOX_E_OBJECT_IN_USE,
3460 tr ("Storage controller named '%ls' already exists"), aName);
3461
3462 ctrl.createObject();
3463 rc = ctrl->init (this, aName, aConnectionType);
3464 CheckComRCReturnRC(rc);
3465
3466 mStorageControllers.backup();
3467 mStorageControllers->push_back (ctrl);
3468
3469 ctrl.queryInterfaceTo(controller);
3470
3471 /* inform the direct session if any */
3472 alock.leave();
3473 onStorageControllerChange();
3474
3475 return S_OK;
3476}
3477
3478STDMETHODIMP Machine::GetStorageControllerByName(IN_BSTR aName,
3479 IStorageController **aStorageController)
3480{
3481 CheckComArgStrNotEmptyOrNull(aName);
3482
3483 AutoCaller autoCaller(this);
3484 CheckComRCReturnRC(autoCaller.rc());
3485
3486 AutoReadLock alock(this);
3487
3488 ComObjPtr<StorageController> ctrl;
3489
3490 HRESULT rc = getStorageControllerByName (aName, ctrl, true /* aSetError */);
3491 if (SUCCEEDED(rc))
3492 ctrl.queryInterfaceTo(aStorageController);
3493
3494 return rc;
3495}
3496
3497STDMETHODIMP Machine::RemoveStorageController(IN_BSTR aName)
3498{
3499 CheckComArgStrNotEmptyOrNull(aName);
3500
3501 AutoCaller autoCaller(this);
3502 CheckComRCReturnRC(autoCaller.rc());
3503
3504 AutoWriteLock alock(this);
3505
3506 HRESULT rc = checkStateDependency(MutableStateDep);
3507 CheckComRCReturnRC(rc);
3508
3509 ComObjPtr<StorageController> ctrl;
3510 rc = getStorageControllerByName (aName, ctrl, true /* aSetError */);
3511 CheckComRCReturnRC(rc);
3512
3513 /* We can remove the controller only if there is no device attached. */
3514 /* check if the device slot is already busy */
3515 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
3516 it != mMediaData->mAttachments.end();
3517 ++it)
3518 {
3519 if ((*it)->controller() == aName)
3520 return setError(VBOX_E_OBJECT_IN_USE,
3521 tr("Storage controller named '%ls' has still devices attached"),
3522 aName);
3523 }
3524
3525 /* We can remove it now. */
3526 mStorageControllers.backup();
3527
3528 ctrl->unshare();
3529
3530 mStorageControllers->remove (ctrl);
3531
3532 /* inform the direct session if any */
3533 alock.leave();
3534 onStorageControllerChange();
3535
3536 return S_OK;
3537}
3538
3539// public methods for internal purposes
3540/////////////////////////////////////////////////////////////////////////////
3541
3542/**
3543 * Saves the registry entry of this machine to the given configuration node.
3544 *
3545 * @param aEntryNode Node to save the registry entry to.
3546 *
3547 * @note locks this object for reading.
3548 */
3549HRESULT Machine::saveRegistryEntry(settings::MachineRegistryEntry &data)
3550{
3551 AutoLimitedCaller autoCaller(this);
3552 AssertComRCReturnRC(autoCaller.rc());
3553
3554 AutoReadLock alock(this);
3555
3556 data.uuid = mData->mUuid;
3557 data.strSettingsFile = mData->m_strConfigFile;
3558
3559 return S_OK;
3560}
3561
3562/**
3563 * Calculates the absolute path of the given path taking the directory of the
3564 * machine settings file as the current directory.
3565 *
3566 * @param aPath Path to calculate the absolute path for.
3567 * @param aResult Where to put the result (used only on success, can be the
3568 * same Utf8Str instance as passed in @a aPath).
3569 * @return IPRT result.
3570 *
3571 * @note Locks this object for reading.
3572 */
3573int Machine::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
3574{
3575 AutoCaller autoCaller(this);
3576 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
3577
3578 AutoReadLock alock(this);
3579
3580 AssertReturn (!mData->m_strConfigFileFull.isEmpty(), VERR_GENERAL_FAILURE);
3581
3582 Utf8Str strSettingsDir = mData->m_strConfigFileFull;
3583
3584 strSettingsDir.stripFilename();
3585 char folder[RTPATH_MAX];
3586 int vrc = RTPathAbsEx(strSettingsDir.c_str(), strPath.c_str(), folder, sizeof(folder));
3587 if (RT_SUCCESS(vrc))
3588 aResult = folder;
3589
3590 return vrc;
3591}
3592
3593/**
3594 * Tries to calculate the relative path of the given absolute path using the
3595 * directory of the machine settings file as the base directory.
3596 *
3597 * @param aPath Absolute path to calculate the relative path for.
3598 * @param aResult Where to put the result (used only when it's possible to
3599 * make a relative path from the given absolute path; otherwise
3600 * left untouched).
3601 *
3602 * @note Locks this object for reading.
3603 */
3604void Machine::calculateRelativePath(const Utf8Str &strPath, Utf8Str &aResult)
3605{
3606 AutoCaller autoCaller(this);
3607 AssertComRCReturn (autoCaller.rc(), (void) 0);
3608
3609 AutoReadLock alock(this);
3610
3611 AssertReturnVoid (!mData->m_strConfigFileFull.isEmpty());
3612
3613 Utf8Str settingsDir = mData->m_strConfigFileFull;
3614
3615 settingsDir.stripFilename();
3616 if (RTPathStartsWith(strPath.c_str(), settingsDir.c_str()))
3617 {
3618 /* when assigning, we create a separate Utf8Str instance because both
3619 * aPath and aResult can point to the same memory location when this
3620 * func is called (if we just do aResult = aPath, aResult will be freed
3621 * first, and since its the same as aPath, an attempt to copy garbage
3622 * will be made. */
3623 aResult = Utf8Str(strPath.c_str() + settingsDir.length() + 1);
3624 }
3625}
3626
3627/**
3628 * Returns the full path to the machine's log folder in the
3629 * \a aLogFolder argument.
3630 */
3631void Machine::getLogFolder (Utf8Str &aLogFolder)
3632{
3633 AutoCaller autoCaller(this);
3634 AssertComRCReturnVoid (autoCaller.rc());
3635
3636 AutoReadLock alock(this);
3637
3638 Utf8Str settingsDir;
3639 if (isInOwnDir (&settingsDir))
3640 {
3641 /* Log folder is <Machines>/<VM_Name>/Logs */
3642 aLogFolder = Utf8StrFmt ("%s%cLogs", settingsDir.raw(), RTPATH_DELIMITER);
3643 }
3644 else
3645 {
3646 /* Log folder is <Machines>/<VM_SnapshotFolder>/Logs */
3647 Assert (!mUserData->mSnapshotFolderFull.isEmpty());
3648 aLogFolder = Utf8StrFmt ("%ls%cLogs", mUserData->mSnapshotFolderFull.raw(),
3649 RTPATH_DELIMITER);
3650 }
3651}
3652
3653/**
3654 * @note Locks this object for writing, calls the client process (outside the
3655 * lock).
3656 */
3657HRESULT Machine::openSession(IInternalSessionControl *aControl)
3658{
3659 LogFlowThisFuncEnter();
3660
3661 AssertReturn(aControl, E_FAIL);
3662
3663 AutoCaller autoCaller(this);
3664 CheckComRCReturnRC(autoCaller.rc());
3665
3666 AutoWriteLock alock(this);
3667
3668 if (!mData->mRegistered)
3669 return setError(E_UNEXPECTED,
3670 tr("The machine '%ls' is not registered"),
3671 mUserData->mName.raw());
3672
3673 LogFlowThisFunc(("mSession.mState=%d\n", mData->mSession.mState));
3674
3675 if (mData->mSession.mState == SessionState_Open ||
3676 mData->mSession.mState == SessionState_Closing)
3677 return setError(VBOX_E_INVALID_OBJECT_STATE,
3678 tr("A session for the machine '%ls' is currently open (or being closed)"),
3679 mUserData->mName.raw());
3680
3681 /* may not be busy */
3682 AssertReturn(!Global::IsOnlineOrTransient (mData->mMachineState), E_FAIL);
3683
3684 /* get the session PID */
3685 RTPROCESS pid = NIL_RTPROCESS;
3686 AssertCompile (sizeof (ULONG) == sizeof (RTPROCESS));
3687 aControl->GetPID ((ULONG *) &pid);
3688 Assert (pid != NIL_RTPROCESS);
3689
3690 if (mData->mSession.mState == SessionState_Spawning)
3691 {
3692 /* This machine is awaiting for a spawning session to be opened, so
3693 * reject any other open attempts from processes other than one
3694 * started by #openRemoteSession(). */
3695
3696 LogFlowThisFunc(("mSession.mPid=%d(0x%x)\n",
3697 mData->mSession.mPid, mData->mSession.mPid));
3698 LogFlowThisFunc(("session.pid=%d(0x%x)\n", pid, pid));
3699
3700 if (mData->mSession.mPid != pid)
3701 return setError(E_ACCESSDENIED,
3702 tr("An unexpected process (PID=0x%08X) has tried to open a direct "
3703 "session with the machine named '%ls', while only a process "
3704 "started by OpenRemoteSession (PID=0x%08X) is allowed"),
3705 pid, mUserData->mName.raw(), mData->mSession.mPid);
3706 }
3707
3708 /* create a SessionMachine object */
3709 ComObjPtr<SessionMachine> sessionMachine;
3710 sessionMachine.createObject();
3711 HRESULT rc = sessionMachine->init (this);
3712 AssertComRC (rc);
3713
3714 /* NOTE: doing return from this function after this point but
3715 * before the end is forbidden since it may call SessionMachine::uninit()
3716 * (through the ComObjPtr's destructor) which requests the VirtualBox write
3717 * lock while still holding the Machine lock in alock so that a deadlock
3718 * is possible due to the wrong lock order. */
3719
3720 if (SUCCEEDED(rc))
3721 {
3722#ifdef VBOX_WITH_RESOURCE_USAGE_API
3723 registerMetrics (mParent->performanceCollector(), this, pid);
3724#endif /* VBOX_WITH_RESOURCE_USAGE_API */
3725
3726 /*
3727 * Set the session state to Spawning to protect against subsequent
3728 * attempts to open a session and to unregister the machine after
3729 * we leave the lock.
3730 */
3731 SessionState_T origState = mData->mSession.mState;
3732 mData->mSession.mState = SessionState_Spawning;
3733
3734 /*
3735 * Leave the lock before calling the client process -- it will call
3736 * Machine/SessionMachine methods. Leaving the lock here is quite safe
3737 * because the state is Spawning, so that openRemotesession() and
3738 * openExistingSession() calls will fail. This method, called before we
3739 * enter the lock again, will fail because of the wrong PID.
3740 *
3741 * Note that mData->mSession.mRemoteControls accessed outside
3742 * the lock may not be modified when state is Spawning, so it's safe.
3743 */
3744 alock.leave();
3745
3746 LogFlowThisFunc(("Calling AssignMachine()...\n"));
3747 rc = aControl->AssignMachine (sessionMachine);
3748 LogFlowThisFunc(("AssignMachine() returned %08X\n", rc));
3749
3750 /* The failure may occur w/o any error info (from RPC), so provide one */
3751 if (FAILED (rc))
3752 setError (VBOX_E_VM_ERROR,
3753 tr ("Failed to assign the machine to the session (%Rrc)"), rc);
3754
3755 if (SUCCEEDED(rc) && origState == SessionState_Spawning)
3756 {
3757 /* complete the remote session initialization */
3758
3759 /* get the console from the direct session */
3760 ComPtr<IConsole> console;
3761 rc = aControl->GetRemoteConsole (console.asOutParam());
3762 ComAssertComRC (rc);
3763
3764 if (SUCCEEDED(rc) && !console)
3765 {
3766 ComAssert (!!console);
3767 rc = E_FAIL;
3768 }
3769
3770 /* assign machine & console to the remote session */
3771 if (SUCCEEDED(rc))
3772 {
3773 /*
3774 * after openRemoteSession(), the first and the only
3775 * entry in remoteControls is that remote session
3776 */
3777 LogFlowThisFunc(("Calling AssignRemoteMachine()...\n"));
3778 rc = mData->mSession.mRemoteControls.front()->
3779 AssignRemoteMachine (sessionMachine, console);
3780 LogFlowThisFunc(("AssignRemoteMachine() returned %08X\n", rc));
3781
3782 /* The failure may occur w/o any error info (from RPC), so provide one */
3783 if (FAILED(rc))
3784 setError(VBOX_E_VM_ERROR,
3785 tr("Failed to assign the machine to the remote session (%Rrc)"), rc);
3786 }
3787
3788 if (FAILED(rc))
3789 aControl->Uninitialize();
3790 }
3791
3792 /* enter the lock again */
3793 alock.enter();
3794
3795 /* Restore the session state */
3796 mData->mSession.mState = origState;
3797 }
3798
3799 /* finalize spawning anyway (this is why we don't return on errors above) */
3800 if (mData->mSession.mState == SessionState_Spawning)
3801 {
3802 /* Note that the progress object is finalized later */
3803
3804 /* We don't reset mSession.mPid here because it is necessary for
3805 * SessionMachine::uninit() to reap the child process later. */
3806
3807 if (FAILED(rc))
3808 {
3809 /* Close the remote session, remove the remote control from the list
3810 * and reset session state to Closed (@note keep the code in sync
3811 * with the relevant part in openSession()). */
3812
3813 Assert (mData->mSession.mRemoteControls.size() == 1);
3814 if (mData->mSession.mRemoteControls.size() == 1)
3815 {
3816 ErrorInfoKeeper eik;
3817 mData->mSession.mRemoteControls.front()->Uninitialize();
3818 }
3819
3820 mData->mSession.mRemoteControls.clear();
3821 mData->mSession.mState = SessionState_Closed;
3822 }
3823 }
3824 else
3825 {
3826 /* memorize PID of the directly opened session */
3827 if (SUCCEEDED(rc))
3828 mData->mSession.mPid = pid;
3829 }
3830
3831 if (SUCCEEDED(rc))
3832 {
3833 /* memorize the direct session control and cache IUnknown for it */
3834 mData->mSession.mDirectControl = aControl;
3835 mData->mSession.mState = SessionState_Open;
3836 /* associate the SessionMachine with this Machine */
3837 mData->mSession.mMachine = sessionMachine;
3838
3839 /* request an IUnknown pointer early from the remote party for later
3840 * identity checks (it will be internally cached within mDirectControl
3841 * at least on XPCOM) */
3842 ComPtr<IUnknown> unk = mData->mSession.mDirectControl;
3843 NOREF (unk);
3844 }
3845
3846 if (mData->mSession.mProgress)
3847 {
3848 /* finalize the progress after setting the state, for consistency */
3849 mData->mSession.mProgress->notifyComplete (rc);
3850 mData->mSession.mProgress.setNull();
3851 }
3852
3853 /* Leave the lock since SessionMachine::uninit() locks VirtualBox which
3854 * would break the lock order */
3855 alock.leave();
3856
3857 /* uninitialize the created session machine on failure */
3858 if (FAILED(rc))
3859 sessionMachine->uninit();
3860
3861 LogFlowThisFunc(("rc=%08X\n", rc));
3862 LogFlowThisFuncLeave();
3863 return rc;
3864}
3865
3866/**
3867 * @note Locks this object for writing, calls the client process
3868 * (inside the lock).
3869 */
3870HRESULT Machine::openRemoteSession(IInternalSessionControl *aControl,
3871 IN_BSTR aType,
3872 IN_BSTR aEnvironment,
3873 Progress *aProgress)
3874{
3875 LogFlowThisFuncEnter();
3876
3877 AssertReturn(aControl, E_FAIL);
3878 AssertReturn(aProgress, E_FAIL);
3879
3880 AutoCaller autoCaller(this);
3881 CheckComRCReturnRC(autoCaller.rc());
3882
3883 AutoWriteLock alock(this);
3884
3885 if (!mData->mRegistered)
3886 return setError(E_UNEXPECTED,
3887 tr("The machine '%ls' is not registered"),
3888 mUserData->mName.raw());
3889
3890 LogFlowThisFunc(("mSession.mState=%d\n", mData->mSession.mState));
3891
3892 if (mData->mSession.mState == SessionState_Open ||
3893 mData->mSession.mState == SessionState_Spawning ||
3894 mData->mSession.mState == SessionState_Closing)
3895 return setError(VBOX_E_INVALID_OBJECT_STATE,
3896 tr("A session for the machine '%ls' is currently open (or being opened or closed)"),
3897 mUserData->mName.raw());
3898
3899 /* may not be busy */
3900 AssertReturn(!Global::IsOnlineOrTransient (mData->mMachineState), E_FAIL);
3901
3902 /* get the path to the executable */
3903 char szPath[RTPATH_MAX];
3904 RTPathAppPrivateArch(szPath, RTPATH_MAX);
3905 size_t sz = strlen(szPath);
3906 szPath[sz++] = RTPATH_DELIMITER;
3907 szPath[sz] = 0;
3908 char *cmd = szPath + sz;
3909 sz = RTPATH_MAX - sz;
3910
3911 int vrc = VINF_SUCCESS;
3912 RTPROCESS pid = NIL_RTPROCESS;
3913
3914 RTENV env = RTENV_DEFAULT;
3915
3916 if (aEnvironment != NULL && *aEnvironment)
3917 {
3918 char *newEnvStr = NULL;
3919
3920 do
3921 {
3922 /* clone the current environment */
3923 int vrc2 = RTEnvClone(&env, RTENV_DEFAULT);
3924 AssertRCBreakStmt(vrc2, vrc = vrc2);
3925
3926 newEnvStr = RTStrDup(Utf8Str(aEnvironment).c_str());
3927 AssertPtrBreakStmt(newEnvStr, vrc = vrc2);
3928
3929 /* put new variables to the environment
3930 * (ignore empty variable names here since RTEnv API
3931 * intentionally doesn't do that) */
3932 char *var = newEnvStr;
3933 for (char *p = newEnvStr; *p; ++p)
3934 {
3935 if (*p == '\n' && (p == newEnvStr || *(p - 1) != '\\'))
3936 {
3937 *p = '\0';
3938 if (*var)
3939 {
3940 char *val = strchr (var, '=');
3941 if (val)
3942 {
3943 *val++ = '\0';
3944 vrc2 = RTEnvSetEx (env, var, val);
3945 }
3946 else
3947 vrc2 = RTEnvUnsetEx (env, var);
3948 if (RT_FAILURE(vrc2))
3949 break;
3950 }
3951 var = p + 1;
3952 }
3953 }
3954 if (RT_SUCCESS(vrc2) && *var)
3955 vrc2 = RTEnvPutEx (env, var);
3956
3957 AssertRCBreakStmt (vrc2, vrc = vrc2);
3958 }
3959 while (0);
3960
3961 if (newEnvStr != NULL)
3962 RTStrFree(newEnvStr);
3963 }
3964
3965 Bstr type (aType);
3966
3967 /* Qt is default */
3968#ifdef VBOX_WITH_QTGUI
3969 if (type == "gui" || type == "GUI/Qt")
3970 {
3971# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
3972 const char VirtualBox_exe[] = "../Resources/VirtualBoxVM.app/Contents/MacOS/VirtualBoxVM";
3973# else
3974 const char VirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
3975# endif
3976 Assert (sz >= sizeof (VirtualBox_exe));
3977 strcpy (cmd, VirtualBox_exe);
3978
3979 Utf8Str idStr = mData->mUuid.toString();
3980# ifdef RT_OS_WINDOWS /** @todo drop this once the RTProcCreate bug has been fixed */
3981 const char * args[] = {szPath, "--startvm", idStr.c_str(), 0 };
3982# else
3983 Utf8Str name = mUserData->mName;
3984 const char * args[] = {szPath, "--comment", name.c_str(), "--startvm", idStr.c_str(), 0 };
3985# endif
3986 vrc = RTProcCreate(szPath, args, env, 0, &pid);
3987 }
3988#else /* !VBOX_WITH_QTGUI */
3989 if (0)
3990 ;
3991#endif /* VBOX_WITH_QTGUI */
3992
3993 else
3994
3995#ifdef VBOX_WITH_VBOXSDL
3996 if (type == "sdl" || type == "GUI/SDL")
3997 {
3998 const char VBoxSDL_exe[] = "VBoxSDL" HOSTSUFF_EXE;
3999 Assert (sz >= sizeof (VBoxSDL_exe));
4000 strcpy (cmd, VBoxSDL_exe);
4001
4002 Utf8Str idStr = mData->mUuid.toString();
4003# ifdef RT_OS_WINDOWS
4004 const char * args[] = {szPath, "--startvm", idStr.c_str(), 0 };
4005# else
4006 Utf8Str name = mUserData->mName;
4007 const char * args[] = {szPath, "--comment", name.c_str(), "--startvm", idStr.c_str(), 0 };
4008# endif
4009 vrc = RTProcCreate(szPath, args, env, 0, &pid);
4010 }
4011#else /* !VBOX_WITH_VBOXSDL */
4012 if (0)
4013 ;
4014#endif /* !VBOX_WITH_VBOXSDL */
4015
4016 else
4017
4018#ifdef VBOX_WITH_HEADLESS
4019 if ( type == "headless"
4020 || type == "capture"
4021#ifdef VBOX_WITH_VRDP
4022 || type == "vrdp"
4023#endif
4024 )
4025 {
4026 const char VBoxHeadless_exe[] = "VBoxHeadless" HOSTSUFF_EXE;
4027 Assert (sz >= sizeof (VBoxHeadless_exe));
4028 strcpy (cmd, VBoxHeadless_exe);
4029
4030 Utf8Str idStr = mData->mUuid.toString();
4031 /* Leave space for 2 args, as "headless" needs --vrdp off on non-OSE. */
4032# ifdef RT_OS_WINDOWS
4033 const char * args[] = {szPath, "--startvm", idStr.c_str(), 0, 0, 0 };
4034# else
4035 Utf8Str name = mUserData->mName;
4036 const char * args[] ={szPath, "--comment", name.c_str(), "--startvm", idStr.c_str(), 0, 0, 0 };
4037# endif
4038#ifdef VBOX_WITH_VRDP
4039 if (type == "headless")
4040 {
4041 unsigned pos = RT_ELEMENTS(args) - 3;
4042 args[pos++] = "--vrdp";
4043 args[pos] = "off";
4044 }
4045#endif
4046 if (type == "capture")
4047 {
4048 unsigned pos = RT_ELEMENTS(args) - 3;
4049 args[pos] = "--capture";
4050 }
4051 vrc = RTProcCreate(szPath, args, env, 0, &pid);
4052 }
4053#else /* !VBOX_WITH_HEADLESS */
4054 if (0)
4055 ;
4056#endif /* !VBOX_WITH_HEADLESS */
4057 else
4058 {
4059 RTEnvDestroy (env);
4060 return setError (E_INVALIDARG,
4061 tr ("Invalid session type: '%ls'"), aType);
4062 }
4063
4064 RTEnvDestroy (env);
4065
4066 if (RT_FAILURE(vrc))
4067 return setError (VBOX_E_IPRT_ERROR,
4068 tr ("Could not launch a process for the machine '%ls' (%Rrc)"),
4069 mUserData->mName.raw(), vrc);
4070
4071 LogFlowThisFunc(("launched.pid=%d(0x%x)\n", pid, pid));
4072
4073 /*
4074 * Note that we don't leave the lock here before calling the client,
4075 * because it doesn't need to call us back if called with a NULL argument.
4076 * Leaving the lock herer is dangerous because we didn't prepare the
4077 * launch data yet, but the client we've just started may happen to be
4078 * too fast and call openSession() that will fail (because of PID, etc.),
4079 * so that the Machine will never get out of the Spawning session state.
4080 */
4081
4082 /* inform the session that it will be a remote one */
4083 LogFlowThisFunc(("Calling AssignMachine (NULL)...\n"));
4084 HRESULT rc = aControl->AssignMachine (NULL);
4085 LogFlowThisFunc(("AssignMachine (NULL) returned %08X\n", rc));
4086
4087 if (FAILED(rc))
4088 {
4089 /* restore the session state */
4090 mData->mSession.mState = SessionState_Closed;
4091 /* The failure may occur w/o any error info (from RPC), so provide one */
4092 return setError(VBOX_E_VM_ERROR,
4093 tr("Failed to assign the machine to the session (%Rrc)"), rc);
4094 }
4095
4096 /* attach launch data to the machine */
4097 Assert (mData->mSession.mPid == NIL_RTPROCESS);
4098 mData->mSession.mRemoteControls.push_back (aControl);
4099 mData->mSession.mProgress = aProgress;
4100 mData->mSession.mPid = pid;
4101 mData->mSession.mState = SessionState_Spawning;
4102 mData->mSession.mType = type;
4103
4104 LogFlowThisFuncLeave();
4105 return S_OK;
4106}
4107
4108/**
4109 * @note Locks this object for writing, calls the client process
4110 * (outside the lock).
4111 */
4112HRESULT Machine::openExistingSession (IInternalSessionControl *aControl)
4113{
4114 LogFlowThisFuncEnter();
4115
4116 AssertReturn(aControl, E_FAIL);
4117
4118 AutoCaller autoCaller(this);
4119 CheckComRCReturnRC(autoCaller.rc());
4120
4121 AutoWriteLock alock(this);
4122
4123 if (!mData->mRegistered)
4124 return setError (E_UNEXPECTED,
4125 tr ("The machine '%ls' is not registered"), mUserData->mName.raw());
4126
4127 LogFlowThisFunc(("mSession.state=%d\n", mData->mSession.mState));
4128
4129 if (mData->mSession.mState != SessionState_Open)
4130 return setError (VBOX_E_INVALID_SESSION_STATE,
4131 tr ("The machine '%ls' does not have an open session"),
4132 mUserData->mName.raw());
4133
4134 ComAssertRet (!mData->mSession.mDirectControl.isNull(), E_FAIL);
4135
4136 /*
4137 * Get the console from the direct session (note that we don't leave the
4138 * lock here because GetRemoteConsole must not call us back).
4139 */
4140 ComPtr<IConsole> console;
4141 HRESULT rc = mData->mSession.mDirectControl->
4142 GetRemoteConsole (console.asOutParam());
4143 if (FAILED (rc))
4144 {
4145 /* The failure may occur w/o any error info (from RPC), so provide one */
4146 return setError (VBOX_E_VM_ERROR,
4147 tr ("Failed to get a console object from the direct session (%Rrc)"), rc);
4148 }
4149
4150 ComAssertRet (!console.isNull(), E_FAIL);
4151
4152 ComObjPtr<SessionMachine> sessionMachine = mData->mSession.mMachine;
4153 AssertReturn(!sessionMachine.isNull(), E_FAIL);
4154
4155 /*
4156 * Leave the lock before calling the client process. It's safe here
4157 * since the only thing to do after we get the lock again is to add
4158 * the remote control to the list (which doesn't directly influence
4159 * anything).
4160 */
4161 alock.leave();
4162
4163 /* attach the remote session to the machine */
4164 LogFlowThisFunc(("Calling AssignRemoteMachine()...\n"));
4165 rc = aControl->AssignRemoteMachine (sessionMachine, console);
4166 LogFlowThisFunc(("AssignRemoteMachine() returned %08X\n", rc));
4167
4168 /* The failure may occur w/o any error info (from RPC), so provide one */
4169 if (FAILED(rc))
4170 return setError(VBOX_E_VM_ERROR,
4171 tr("Failed to assign the machine to the session (%Rrc)"),
4172 rc);
4173
4174 alock.enter();
4175
4176 /* need to revalidate the state after entering the lock again */
4177 if (mData->mSession.mState != SessionState_Open)
4178 {
4179 aControl->Uninitialize();
4180
4181 return setError(VBOX_E_INVALID_SESSION_STATE,
4182 tr("The machine '%ls' does not have an open session"),
4183 mUserData->mName.raw());
4184 }
4185
4186 /* store the control in the list */
4187 mData->mSession.mRemoteControls.push_back (aControl);
4188
4189 LogFlowThisFuncLeave();
4190 return S_OK;
4191}
4192
4193/**
4194 * Returns @c true if the given machine has an open direct session and returns
4195 * the session machine instance and additional session data (on some platforms)
4196 * if so.
4197 *
4198 * Note that when the method returns @c false, the arguments remain unchanged.
4199 *
4200 * @param aMachine Session machine object.
4201 * @param aControl Direct session control object (optional).
4202 * @param aIPCSem Mutex IPC semaphore handle for this machine (optional).
4203 *
4204 * @note locks this object for reading.
4205 */
4206#if defined (RT_OS_WINDOWS)
4207bool Machine::isSessionOpen (ComObjPtr<SessionMachine> &aMachine,
4208 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
4209 HANDLE *aIPCSem /*= NULL*/,
4210 bool aAllowClosing /*= false*/)
4211#elif defined (RT_OS_OS2)
4212bool Machine::isSessionOpen (ComObjPtr<SessionMachine> &aMachine,
4213 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
4214 HMTX *aIPCSem /*= NULL*/,
4215 bool aAllowClosing /*= false*/)
4216#else
4217bool Machine::isSessionOpen (ComObjPtr<SessionMachine> &aMachine,
4218 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
4219 bool aAllowClosing /*= false*/)
4220#endif
4221{
4222 AutoLimitedCaller autoCaller(this);
4223 AssertComRCReturn (autoCaller.rc(), false);
4224
4225 /* just return false for inaccessible machines */
4226 if (autoCaller.state() != Ready)
4227 return false;
4228
4229 AutoReadLock alock(this);
4230
4231 if (mData->mSession.mState == SessionState_Open ||
4232 (aAllowClosing && mData->mSession.mState == SessionState_Closing))
4233 {
4234 AssertReturn(!mData->mSession.mMachine.isNull(), false);
4235
4236 aMachine = mData->mSession.mMachine;
4237
4238 if (aControl != NULL)
4239 *aControl = mData->mSession.mDirectControl;
4240
4241#if defined (RT_OS_WINDOWS) || defined (RT_OS_OS2)
4242 /* Additional session data */
4243 if (aIPCSem != NULL)
4244 *aIPCSem = aMachine->mIPCSem;
4245#endif
4246 return true;
4247 }
4248
4249 return false;
4250}
4251
4252/**
4253 * Returns @c true if the given machine has an spawning direct session and
4254 * returns and additional session data (on some platforms) if so.
4255 *
4256 * Note that when the method returns @c false, the arguments remain unchanged.
4257 *
4258 * @param aPID PID of the spawned direct session process.
4259 *
4260 * @note locks this object for reading.
4261 */
4262#if defined (RT_OS_WINDOWS) || defined (RT_OS_OS2)
4263bool Machine::isSessionSpawning (RTPROCESS *aPID /*= NULL*/)
4264#else
4265bool Machine::isSessionSpawning()
4266#endif
4267{
4268 AutoLimitedCaller autoCaller(this);
4269 AssertComRCReturn (autoCaller.rc(), false);
4270
4271 /* just return false for inaccessible machines */
4272 if (autoCaller.state() != Ready)
4273 return false;
4274
4275 AutoReadLock alock(this);
4276
4277 if (mData->mSession.mState == SessionState_Spawning)
4278 {
4279#if defined (RT_OS_WINDOWS) || defined (RT_OS_OS2)
4280 /* Additional session data */
4281 if (aPID != NULL)
4282 {
4283 AssertReturn(mData->mSession.mPid != NIL_RTPROCESS, false);
4284 *aPID = mData->mSession.mPid;
4285 }
4286#endif
4287 return true;
4288 }
4289
4290 return false;
4291}
4292
4293/**
4294 * Called from the client watcher thread to check for unexpected client process
4295 * death during Session_Spawning state (e.g. before it successfully opened a
4296 * direct session).
4297 *
4298 * On Win32 and on OS/2, this method is called only when we've got the
4299 * direct client's process termination notification, so it always returns @c
4300 * true.
4301 *
4302 * On other platforms, this method returns @c true if the client process is
4303 * terminated and @c false if it's still alive.
4304 *
4305 * @note Locks this object for writing.
4306 */
4307bool Machine::checkForSpawnFailure()
4308{
4309 AutoCaller autoCaller(this);
4310 if (!autoCaller.isOk())
4311 {
4312 /* nothing to do */
4313 LogFlowThisFunc(("Already uninitialized!"));
4314 return true;
4315 }
4316
4317 /* VirtualBox::addProcessToReap() needs a write lock */
4318 AutoMultiWriteLock2 alock (mParent, this);
4319
4320 if (mData->mSession.mState != SessionState_Spawning)
4321 {
4322 /* nothing to do */
4323 LogFlowThisFunc(("Not spawning any more!"));
4324 return true;
4325 }
4326
4327 HRESULT rc = S_OK;
4328
4329#if defined (RT_OS_WINDOWS) || defined (RT_OS_OS2)
4330
4331 /* the process was already unexpectedly terminated, we just need to set an
4332 * error and finalize session spawning */
4333 rc = setError(E_FAIL,
4334 tr("Virtual machine '%ls' has terminated unexpectedly during startup"),
4335 name().raw());
4336#else
4337
4338 RTPROCSTATUS status;
4339 int vrc = ::RTProcWait (mData->mSession.mPid, RTPROCWAIT_FLAGS_NOBLOCK,
4340 &status);
4341
4342 if (vrc != VERR_PROCESS_RUNNING)
4343 rc = setError(E_FAIL,
4344 tr("Virtual machine '%ls' has terminated unexpectedly during startup"),
4345 name().raw());
4346#endif
4347
4348 if (FAILED(rc))
4349 {
4350 /* Close the remote session, remove the remote control from the list
4351 * and reset session state to Closed (@note keep the code in sync with
4352 * the relevant part in checkForSpawnFailure()). */
4353
4354 Assert (mData->mSession.mRemoteControls.size() == 1);
4355 if (mData->mSession.mRemoteControls.size() == 1)
4356 {
4357 ErrorInfoKeeper eik;
4358 mData->mSession.mRemoteControls.front()->Uninitialize();
4359 }
4360
4361 mData->mSession.mRemoteControls.clear();
4362 mData->mSession.mState = SessionState_Closed;
4363
4364 /* finalize the progress after setting the state, for consistency */
4365 mData->mSession.mProgress->notifyComplete (rc);
4366 mData->mSession.mProgress.setNull();
4367
4368 mParent->addProcessToReap (mData->mSession.mPid);
4369 mData->mSession.mPid = NIL_RTPROCESS;
4370
4371 mParent->onSessionStateChange (mData->mUuid, SessionState_Closed);
4372 return true;
4373 }
4374
4375 return false;
4376}
4377
4378/**
4379 * Checks that the registered flag of the machine can be set according to
4380 * the argument and sets it. On success, commits and saves all settings.
4381 *
4382 * @note When this machine is inaccessible, the only valid value for \a
4383 * aRegistered is FALSE (i.e. unregister the machine) because unregistered
4384 * inaccessible machines are not currently supported. Note that unregistering
4385 * an inaccessible machine will \b uninitialize this machine object. Therefore,
4386 * the caller must make sure there are no active Machine::addCaller() calls
4387 * on the current thread because this will block Machine::uninit().
4388 *
4389 * @note Must be called from mParent's write lock. Locks this object and
4390 * children for writing.
4391 */
4392HRESULT Machine::trySetRegistered (BOOL aRegistered)
4393{
4394 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
4395
4396 AutoLimitedCaller autoCaller(this);
4397 AssertComRCReturnRC(autoCaller.rc());
4398
4399 AutoWriteLock alock(this);
4400
4401 /* wait for state dependants to drop to zero */
4402 ensureNoStateDependencies();
4403
4404 ComAssertRet (mData->mRegistered != aRegistered, E_FAIL);
4405
4406 if (!mData->mAccessible)
4407 {
4408 /* A special case: the machine is not accessible. */
4409
4410 /* inaccessible machines can only be unregistered */
4411 AssertReturn(!aRegistered, E_FAIL);
4412
4413 /* Uninitialize ourselves here because currently there may be no
4414 * unregistered that are inaccessible (this state combination is not
4415 * supported). Note releasing the caller and leaving the lock before
4416 * calling uninit() */
4417
4418 alock.leave();
4419 autoCaller.release();
4420
4421 uninit();
4422
4423 return S_OK;
4424 }
4425
4426 AssertReturn(autoCaller.state() == Ready, E_FAIL);
4427
4428 if (aRegistered)
4429 {
4430 if (mData->mRegistered)
4431 return setError(VBOX_E_INVALID_OBJECT_STATE,
4432 tr("The machine '%ls' with UUID {%s} is already registered"),
4433 mUserData->mName.raw(),
4434 mData->mUuid.toString().raw());
4435 }
4436 else
4437 {
4438 if (mData->mMachineState == MachineState_Saved)
4439 return setError(VBOX_E_INVALID_VM_STATE,
4440 tr("Cannot unregister the machine '%ls' because it is in the Saved state"),
4441 mUserData->mName.raw());
4442
4443 size_t snapshotCount = 0;
4444 if (mData->mFirstSnapshot)
4445 snapshotCount = mData->mFirstSnapshot->getAllChildrenCount() + 1;
4446 if (snapshotCount)
4447 return setError(VBOX_E_INVALID_OBJECT_STATE,
4448 tr("Cannot unregister the machine '%ls' because it has %d snapshots"),
4449 mUserData->mName.raw(), snapshotCount);
4450
4451 if (mData->mSession.mState != SessionState_Closed)
4452 return setError(VBOX_E_INVALID_OBJECT_STATE,
4453 tr("Cannot unregister the machine '%ls' because it has an open session"),
4454 mUserData->mName.raw());
4455
4456 if (mMediaData->mAttachments.size() != 0)
4457 return setError(VBOX_E_INVALID_OBJECT_STATE,
4458 tr("Cannot unregister the machine '%ls' because it has %d medium attachments"),
4459 mUserData->mName.raw(),
4460 mMediaData->mAttachments.size());
4461
4462 /* Note that we do not prevent unregistration of a DVD or Floppy image
4463 * is attached: as opposed to hard disks detaching such an image
4464 * implicitly in this method (which we will do below) won't have any
4465 * side effects (like detached orphan base and diff hard disks etc).*/
4466 }
4467
4468 HRESULT rc = S_OK;
4469
4470 /* Ensure the settings are saved. If we are going to be registered and
4471 * isConfigLocked() is FALSE then it means that no config file exists yet,
4472 * so create it by calling saveSettings() too. */
4473 if ( isModified()
4474 || (aRegistered && !mData->m_pMachineConfigFile->fileExists())
4475 )
4476 {
4477 rc = saveSettings();
4478 CheckComRCReturnRC(rc);
4479 }
4480
4481 /* more config checking goes here */
4482
4483 if (SUCCEEDED(rc))
4484 {
4485 /* we may have had implicit modifications we want to fix on success */
4486 commit();
4487
4488 mData->mRegistered = aRegistered;
4489 }
4490 else
4491 {
4492 /* we may have had implicit modifications we want to cancel on failure*/
4493 rollback (false /* aNotify */);
4494 }
4495
4496 return rc;
4497}
4498
4499/**
4500 * Increases the number of objects dependent on the machine state or on the
4501 * registered state. Guarantees that these two states will not change at least
4502 * until #releaseStateDependency() is called.
4503 *
4504 * Depending on the @a aDepType value, additional state checks may be made.
4505 * These checks will set extended error info on failure. See
4506 * #checkStateDependency() for more info.
4507 *
4508 * If this method returns a failure, the dependency is not added and the caller
4509 * is not allowed to rely on any particular machine state or registration state
4510 * value and may return the failed result code to the upper level.
4511 *
4512 * @param aDepType Dependency type to add.
4513 * @param aState Current machine state (NULL if not interested).
4514 * @param aRegistered Current registered state (NULL if not interested).
4515 *
4516 * @note Locks this object for writing.
4517 */
4518HRESULT Machine::addStateDependency (StateDependency aDepType /* = AnyStateDep */,
4519 MachineState_T *aState /* = NULL */,
4520 BOOL *aRegistered /* = NULL */)
4521{
4522 AutoCaller autoCaller(this);
4523 AssertComRCReturnRC(autoCaller.rc());
4524
4525 AutoWriteLock alock(this);
4526
4527 HRESULT rc = checkStateDependency(aDepType);
4528 CheckComRCReturnRC(rc);
4529
4530 {
4531 if (mData->mMachineStateChangePending != 0)
4532 {
4533 /* ensureNoStateDependencies() is waiting for state dependencies to
4534 * drop to zero so don't add more. It may make sense to wait a bit
4535 * and retry before reporting an error (since the pending state
4536 * transition should be really quick) but let's just assert for
4537 * now to see if it ever happens on practice. */
4538
4539 AssertFailed();
4540
4541 return setError(E_ACCESSDENIED,
4542 tr("Machine state change is in progress. Please retry the operation later."));
4543 }
4544
4545 ++mData->mMachineStateDeps;
4546 Assert (mData->mMachineStateDeps != 0 /* overflow */);
4547 }
4548
4549 if (aState)
4550 *aState = mData->mMachineState;
4551 if (aRegistered)
4552 *aRegistered = mData->mRegistered;
4553
4554 return S_OK;
4555}
4556
4557/**
4558 * Decreases the number of objects dependent on the machine state.
4559 * Must always complete the #addStateDependency() call after the state
4560 * dependency is no more necessary.
4561 */
4562void Machine::releaseStateDependency()
4563{
4564 AutoCaller autoCaller(this);
4565 AssertComRCReturnVoid (autoCaller.rc());
4566
4567 AutoWriteLock alock(this);
4568
4569 AssertReturnVoid (mData->mMachineStateDeps != 0
4570 /* releaseStateDependency() w/o addStateDependency()? */);
4571 -- mData->mMachineStateDeps;
4572
4573 if (mData->mMachineStateDeps == 0)
4574 {
4575 /* inform ensureNoStateDependencies() that there are no more deps */
4576 if (mData->mMachineStateChangePending != 0)
4577 {
4578 Assert (mData->mMachineStateDepsSem != NIL_RTSEMEVENTMULTI);
4579 RTSemEventMultiSignal (mData->mMachineStateDepsSem);
4580 }
4581 }
4582}
4583
4584// protected methods
4585/////////////////////////////////////////////////////////////////////////////
4586
4587/**
4588 * Performs machine state checks based on the @a aDepType value. If a check
4589 * fails, this method will set extended error info, otherwise it will return
4590 * S_OK. It is supposed, that on failure, the caller will immedieately return
4591 * the return value of this method to the upper level.
4592 *
4593 * When @a aDepType is AnyStateDep, this method always returns S_OK.
4594 *
4595 * When @a aDepType is MutableStateDep, this method returns S_OK only if the
4596 * current state of this machine object allows to change settings of the
4597 * machine (i.e. the machine is not registered, or registered but not running
4598 * and not saved). It is useful to call this method from Machine setters
4599 * before performing any change.
4600 *
4601 * When @a aDepType is MutableOrSavedStateDep, this method behaves the same
4602 * as for MutableStateDep except that if the machine is saved, S_OK is also
4603 * returned. This is useful in setters which allow changing machine
4604 * properties when it is in the saved state.
4605 *
4606 * @param aDepType Dependency type to check.
4607 *
4608 * @note Non Machine based classes should use #addStateDependency() and
4609 * #releaseStateDependency() methods or the smart AutoStateDependency
4610 * template.
4611 *
4612 * @note This method must be called from under this object's read or write
4613 * lock.
4614 */
4615HRESULT Machine::checkStateDependency(StateDependency aDepType)
4616{
4617 switch (aDepType)
4618 {
4619 case AnyStateDep:
4620 {
4621 break;
4622 }
4623 case MutableStateDep:
4624 {
4625 if (mData->mRegistered &&
4626 (mType != IsSessionMachine ||
4627 mData->mMachineState > MachineState_Paused ||
4628 mData->mMachineState == MachineState_Saved))
4629 return setError(VBOX_E_INVALID_VM_STATE,
4630 tr("The machine is not mutable (state is %d)"),
4631 mData->mMachineState);
4632 break;
4633 }
4634 case MutableOrSavedStateDep:
4635 {
4636 if (mData->mRegistered &&
4637 (mType != IsSessionMachine ||
4638 mData->mMachineState > MachineState_Paused))
4639 return setError(VBOX_E_INVALID_VM_STATE,
4640 tr("The machine is not mutable (state is %d)"),
4641 mData->mMachineState);
4642 break;
4643 }
4644 }
4645
4646 return S_OK;
4647}
4648
4649/**
4650 * Helper to initialize all associated child objects and allocate data
4651 * structures.
4652 *
4653 * This method must be called as a part of the object's initialization procedure
4654 * (usually done in the #init() method).
4655 *
4656 * @note Must be called only from #init() or from #registeredInit().
4657 */
4658HRESULT Machine::initDataAndChildObjects()
4659{
4660 AutoCaller autoCaller(this);
4661 AssertComRCReturnRC(autoCaller.rc());
4662 AssertComRCReturn (autoCaller.state() == InInit ||
4663 autoCaller.state() == Limited, E_FAIL);
4664
4665 AssertReturn(!mData->mAccessible, E_FAIL);
4666
4667 /* allocate data structures */
4668 mSSData.allocate();
4669 mUserData.allocate();
4670 mHWData.allocate();
4671 mMediaData.allocate();
4672 mStorageControllers.allocate();
4673
4674 /* initialize mOSTypeId */
4675 mUserData->mOSTypeId = mParent->getUnknownOSType()->id();
4676
4677 /* create associated BIOS settings object */
4678 unconst(mBIOSSettings).createObject();
4679 mBIOSSettings->init (this);
4680
4681#ifdef VBOX_WITH_VRDP
4682 /* create an associated VRDPServer object (default is disabled) */
4683 unconst(mVRDPServer).createObject();
4684 mVRDPServer->init (this);
4685#endif
4686
4687 /* create associated serial port objects */
4688 for (ULONG slot = 0; slot < RT_ELEMENTS (mSerialPorts); slot ++)
4689 {
4690 unconst(mSerialPorts [slot]).createObject();
4691 mSerialPorts [slot]->init (this, slot);
4692 }
4693
4694 /* create associated parallel port objects */
4695 for (ULONG slot = 0; slot < RT_ELEMENTS (mParallelPorts); slot ++)
4696 {
4697 unconst(mParallelPorts [slot]).createObject();
4698 mParallelPorts [slot]->init (this, slot);
4699 }
4700
4701 /* create the audio adapter object (always present, default is disabled) */
4702 unconst(mAudioAdapter).createObject();
4703 mAudioAdapter->init (this);
4704
4705 /* create the USB controller object (always present, default is disabled) */
4706 unconst(mUSBController).createObject();
4707 mUSBController->init (this);
4708
4709 /* create associated network adapter objects */
4710 for (ULONG slot = 0; slot < RT_ELEMENTS (mNetworkAdapters); slot ++)
4711 {
4712 unconst(mNetworkAdapters [slot]).createObject();
4713 mNetworkAdapters [slot]->init (this, slot);
4714 }
4715
4716 return S_OK;
4717}
4718
4719/**
4720 * Helper to uninitialize all associated child objects and to free all data
4721 * structures.
4722 *
4723 * This method must be called as a part of the object's uninitialization
4724 * procedure (usually done in the #uninit() method).
4725 *
4726 * @note Must be called only from #uninit() or from #registeredInit().
4727 */
4728void Machine::uninitDataAndChildObjects()
4729{
4730 AutoCaller autoCaller(this);
4731 AssertComRCReturnVoid (autoCaller.rc());
4732 AssertComRCReturnVoid (autoCaller.state() == InUninit ||
4733 autoCaller.state() == Limited);
4734
4735 /* uninit all children using addDependentChild()/removeDependentChild()
4736 * in their init()/uninit() methods */
4737 uninitDependentChildren();
4738
4739 /* tell all our other child objects we've been uninitialized */
4740
4741 for (ULONG slot = 0; slot < RT_ELEMENTS (mNetworkAdapters); slot ++)
4742 {
4743 if (mNetworkAdapters [slot])
4744 {
4745 mNetworkAdapters [slot]->uninit();
4746 unconst(mNetworkAdapters [slot]).setNull();
4747 }
4748 }
4749
4750 if (mUSBController)
4751 {
4752 mUSBController->uninit();
4753 unconst(mUSBController).setNull();
4754 }
4755
4756 if (mAudioAdapter)
4757 {
4758 mAudioAdapter->uninit();
4759 unconst(mAudioAdapter).setNull();
4760 }
4761
4762 for (ULONG slot = 0; slot < RT_ELEMENTS (mParallelPorts); slot ++)
4763 {
4764 if (mParallelPorts [slot])
4765 {
4766 mParallelPorts [slot]->uninit();
4767 unconst(mParallelPorts [slot]).setNull();
4768 }
4769 }
4770
4771 for (ULONG slot = 0; slot < RT_ELEMENTS (mSerialPorts); slot ++)
4772 {
4773 if (mSerialPorts [slot])
4774 {
4775 mSerialPorts [slot]->uninit();
4776 unconst(mSerialPorts [slot]).setNull();
4777 }
4778 }
4779
4780#ifdef VBOX_WITH_VRDP
4781 if (mVRDPServer)
4782 {
4783 mVRDPServer->uninit();
4784 unconst(mVRDPServer).setNull();
4785 }
4786#endif
4787
4788 if (mBIOSSettings)
4789 {
4790 mBIOSSettings->uninit();
4791 unconst(mBIOSSettings).setNull();
4792 }
4793
4794 /* Deassociate hard disks (only when a real Machine or a SnapshotMachine
4795 * instance is uninitialized; SessionMachine instances refer to real
4796 * Machine hard disks). This is necessary for a clean re-initialization of
4797 * the VM after successfully re-checking the accessibility state. Note
4798 * that in case of normal Machine or SnapshotMachine uninitialization (as
4799 * a result of unregistering or discarding the snapshot), outdated hard
4800 * disk attachments will already be uninitialized and deleted, so this
4801 * code will not affect them. */
4802 if (!!mMediaData && (mType == IsMachine || mType == IsSnapshotMachine))
4803 {
4804 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
4805 it != mMediaData->mAttachments.end();
4806 ++it)
4807 {
4808 ComObjPtr<Medium> hd = (*it)->medium();
4809 if (hd.isNull() || (*it)->type() != DeviceType_HardDisk)
4810 continue;
4811 HRESULT rc = hd->detachFrom(mData->mUuid, snapshotId());
4812 AssertComRC (rc);
4813 }
4814 }
4815
4816 if (mType == IsMachine)
4817 {
4818 /* reset some important fields of mData */
4819 mData->mCurrentSnapshot.setNull();
4820 mData->mFirstSnapshot.setNull();
4821 }
4822
4823 /* free data structures (the essential mData structure is not freed here
4824 * since it may be still in use) */
4825 mMediaData.free();
4826 mStorageControllers.free();
4827 mHWData.free();
4828 mUserData.free();
4829 mSSData.free();
4830}
4831
4832/**
4833 * Makes sure that there are no machine state dependants. If necessary, waits
4834 * for the number of dependants to drop to zero.
4835 *
4836 * Make sure this method is called from under this object's write lock to
4837 * guarantee that no new dependants may be added when this method returns
4838 * control to the caller.
4839 *
4840 * @note Locks this object for writing. The lock will be released while waiting
4841 * (if necessary).
4842 *
4843 * @warning To be used only in methods that change the machine state!
4844 */
4845void Machine::ensureNoStateDependencies()
4846{
4847 AssertReturnVoid (isWriteLockOnCurrentThread());
4848
4849 AutoWriteLock alock(this);
4850
4851 /* Wait for all state dependants if necessary */
4852 if (mData->mMachineStateDeps != 0)
4853 {
4854 /* lazy semaphore creation */
4855 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
4856 RTSemEventMultiCreate (&mData->mMachineStateDepsSem);
4857
4858 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
4859 mData->mMachineStateDeps));
4860
4861 ++mData->mMachineStateChangePending;
4862
4863 /* reset the semaphore before waiting, the last dependant will signal
4864 * it */
4865 RTSemEventMultiReset (mData->mMachineStateDepsSem);
4866
4867 alock.leave();
4868
4869 RTSemEventMultiWait (mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
4870
4871 alock.enter();
4872
4873 -- mData->mMachineStateChangePending;
4874 }
4875}
4876
4877/**
4878 * Changes the machine state and informs callbacks.
4879 *
4880 * This method is not intended to fail so it either returns S_OK or asserts (and
4881 * returns a failure).
4882 *
4883 * @note Locks this object for writing.
4884 */
4885HRESULT Machine::setMachineState (MachineState_T aMachineState)
4886{
4887 LogFlowThisFuncEnter();
4888 LogFlowThisFunc(("aMachineState=%d\n", aMachineState));
4889
4890 AutoCaller autoCaller(this);
4891 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
4892
4893 AutoWriteLock alock(this);
4894
4895 /* wait for state dependants to drop to zero */
4896 ensureNoStateDependencies();
4897
4898 if (mData->mMachineState != aMachineState)
4899 {
4900 mData->mMachineState = aMachineState;
4901
4902 RTTimeNow (&mData->mLastStateChange);
4903
4904 mParent->onMachineStateChange(mData->mUuid, aMachineState);
4905 }
4906
4907 LogFlowThisFuncLeave();
4908 return S_OK;
4909}
4910
4911/**
4912 * Searches for a shared folder with the given logical name
4913 * in the collection of shared folders.
4914 *
4915 * @param aName logical name of the shared folder
4916 * @param aSharedFolder where to return the found object
4917 * @param aSetError whether to set the error info if the folder is
4918 * not found
4919 * @return
4920 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
4921 *
4922 * @note
4923 * must be called from under the object's lock!
4924 */
4925HRESULT Machine::findSharedFolder (CBSTR aName,
4926 ComObjPtr<SharedFolder> &aSharedFolder,
4927 bool aSetError /* = false */)
4928{
4929 bool found = false;
4930 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
4931 !found && it != mHWData->mSharedFolders.end();
4932 ++it)
4933 {
4934 AutoWriteLock alock(*it);
4935 found = (*it)->name() == aName;
4936 if (found)
4937 aSharedFolder = *it;
4938 }
4939
4940 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
4941
4942 if (aSetError && !found)
4943 setError(rc, tr("Could not find a shared folder named '%ls'"), aName);
4944
4945 return rc;
4946}
4947
4948/**
4949 * Loads all the VM settings by walking down the <Machine> node.
4950 *
4951 * @param aRegistered true when the machine is being loaded on VirtualBox
4952 * startup
4953 *
4954 * @note This method is intended to be called only from init(), so it assumes
4955 * all machine data fields have appropriate default values when it is called.
4956 *
4957 * @note Doesn't lock any objects.
4958 */
4959HRESULT Machine::loadSettings(bool aRegistered)
4960{
4961 LogFlowThisFuncEnter();
4962 AssertReturn(mType == IsMachine, E_FAIL);
4963
4964 AutoCaller autoCaller(this);
4965 AssertReturn(autoCaller.state() == InInit, E_FAIL);
4966
4967 HRESULT rc = S_OK;
4968
4969 try
4970 {
4971 Assert(mData->m_pMachineConfigFile == NULL);
4972
4973 // load and parse machine XML; this will throw on XML or logic errors
4974 mData->m_pMachineConfigFile = new settings::MachineConfigFile(&mData->m_strConfigFileFull);
4975
4976 /* If the stored UUID is not empty, it means the registered machine
4977 * is being loaded. Compare the loaded UUID with the stored one taken
4978 * from the global registry. */
4979 if (!mData->mUuid.isEmpty())
4980 {
4981 if (mData->mUuid != mData->m_pMachineConfigFile->uuid)
4982 {
4983 throw setError(E_FAIL,
4984 tr("Machine UUID {%RTuuid} in '%s' doesn't match its UUID {%s} in the registry file '%s'"),
4985 mData->m_pMachineConfigFile->uuid.raw(),
4986 mData->m_strConfigFileFull.raw(),
4987 mData->mUuid.toString().raw(),
4988 mParent->settingsFilePath().raw());
4989 }
4990 }
4991 else
4992 unconst (mData->mUuid) = mData->m_pMachineConfigFile->uuid;
4993
4994 /* name (required) */
4995 mUserData->mName = mData->m_pMachineConfigFile->strName;
4996
4997 /* nameSync (optional, default is true) */
4998 mUserData->mNameSync = mData->m_pMachineConfigFile->fNameSync;
4999
5000 mUserData->mDescription = mData->m_pMachineConfigFile->strDescription;
5001
5002 // guest OS type
5003 mUserData->mOSTypeId = mData->m_pMachineConfigFile->strOsType;
5004 /* look up the object by Id to check it is valid */
5005 ComPtr<IGuestOSType> guestOSType;
5006 rc = mParent->GetGuestOSType(mUserData->mOSTypeId,
5007 guestOSType.asOutParam());
5008 CheckComRCThrowRC(rc);
5009
5010 // stateFile (optional)
5011 if (mData->m_pMachineConfigFile->strStateFile.isEmpty())
5012 mSSData->mStateFilePath.setNull();
5013 else
5014 {
5015 Utf8Str stateFilePathFull(mData->m_pMachineConfigFile->strStateFile);
5016 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
5017 if (RT_FAILURE(vrc))
5018 throw setError(E_FAIL,
5019 tr("Invalid saved state file path '%s' (%Rrc)"),
5020 mData->m_pMachineConfigFile->strStateFile.raw(),
5021 vrc);
5022 mSSData->mStateFilePath = stateFilePathFull;
5023 }
5024
5025 /* snapshotFolder (optional) */
5026 rc = COMSETTER(SnapshotFolder)(Bstr(mData->m_pMachineConfigFile->strSnapshotFolder));
5027 CheckComRCThrowRC(rc);
5028
5029 /* currentStateModified (optional, default is true) */
5030 mData->mCurrentStateModified = mData->m_pMachineConfigFile->fCurrentStateModified;
5031
5032 mData->mLastStateChange = mData->m_pMachineConfigFile->timeLastStateChange;
5033
5034/** @todo LiveMigration: Load LiveMigration properties here. */
5035 /*
5036 * note: all mUserData members must be assigned prior this point because
5037 * we need to commit changes in order to let mUserData be shared by all
5038 * snapshot machine instances.
5039 */
5040 mUserData.commitCopy();
5041
5042 /* Snapshot node (optional) */
5043 if (mData->m_pMachineConfigFile->llFirstSnapshot.size())
5044 {
5045 // there can only be one root snapshot
5046 Assert(mData->m_pMachineConfigFile->llFirstSnapshot.size() == 1);
5047
5048 settings::Snapshot &snap = mData->m_pMachineConfigFile->llFirstSnapshot.front();
5049
5050 rc = loadSnapshot(snap,
5051 mData->m_pMachineConfigFile->uuidCurrentSnapshot,
5052 NULL); // no parent == first snapshot
5053 CheckComRCThrowRC(rc);
5054 }
5055
5056 /* Hardware node (required) */
5057 rc = loadHardware(mData->m_pMachineConfigFile->hardwareMachine);
5058 CheckComRCThrowRC(rc);
5059
5060 /* Load storage controllers */
5061 rc = loadStorageControllers(mData->m_pMachineConfigFile->storageMachine, aRegistered);
5062 CheckComRCThrowRC(rc);
5063
5064 /*
5065 * NOTE: the assignment below must be the last thing to do,
5066 * otherwise it will be not possible to change the settings
5067 * somewehere in the code above because all setters will be
5068 * blocked by checkStateDependency(MutableStateDep).
5069 */
5070
5071 /* set the machine state to Aborted or Saved when appropriate */
5072 if (mData->m_pMachineConfigFile->fAborted)
5073 {
5074 Assert(!mSSData->mStateFilePath);
5075 mSSData->mStateFilePath.setNull();
5076
5077 /* no need to use setMachineState() during init() */
5078 mData->mMachineState = MachineState_Aborted;
5079 }
5080 else if (mSSData->mStateFilePath)
5081 {
5082 /* no need to use setMachineState() during init() */
5083 mData->mMachineState = MachineState_Saved;
5084 }
5085 }
5086 catch (HRESULT err)
5087 {
5088 /* we assume that error info is set by the thrower */
5089 rc = err;
5090 }
5091 catch (...)
5092 {
5093 rc = VirtualBox::handleUnexpectedExceptions (RT_SRC_POS);
5094 }
5095
5096 LogFlowThisFuncLeave();
5097 return rc;
5098}
5099
5100/**
5101 * Recursively loads all snapshots starting from the given.
5102 *
5103 * @param aNode <Snapshot> node.
5104 * @param aCurSnapshotId Current snapshot ID from the settings file.
5105 * @param aParentSnapshot Parent snapshot.
5106 */
5107HRESULT Machine::loadSnapshot(const settings::Snapshot &data,
5108 const Guid &aCurSnapshotId,
5109 Snapshot *aParentSnapshot)
5110{
5111 AssertReturn (mType == IsMachine, E_FAIL);
5112
5113 HRESULT rc = S_OK;
5114
5115 Utf8Str strStateFile;
5116 if (!data.strStateFile.isEmpty())
5117 {
5118 /* optional */
5119 strStateFile = data.strStateFile;
5120 int vrc = calculateFullPath(strStateFile, strStateFile);
5121 if (RT_FAILURE(vrc))
5122 return setError(E_FAIL,
5123 tr("Invalid saved state file path '%s' (%Rrc)"),
5124 strStateFile.raw(),
5125 vrc);
5126 }
5127
5128 /* create a snapshot machine object */
5129 ComObjPtr<SnapshotMachine> pSnapshotMachine;
5130 pSnapshotMachine.createObject();
5131 rc = pSnapshotMachine->init(this,
5132 data.hardware,
5133 data.storage,
5134 data.uuid,
5135 strStateFile);
5136 CheckComRCReturnRC (rc);
5137
5138 /* create a snapshot object */
5139 ComObjPtr<Snapshot> pSnapshot;
5140 pSnapshot.createObject();
5141 /* initialize the snapshot */
5142 rc = pSnapshot->init(mParent, // VirtualBox object
5143 data.uuid,
5144 data.strName,
5145 data.strDescription,
5146 data.timestamp,
5147 pSnapshotMachine,
5148 aParentSnapshot);
5149 CheckComRCReturnRC (rc);
5150
5151 /* memorize the first snapshot if necessary */
5152 if (!mData->mFirstSnapshot)
5153 mData->mFirstSnapshot = pSnapshot;
5154
5155 /* memorize the current snapshot when appropriate */
5156 if ( !mData->mCurrentSnapshot
5157 && pSnapshot->getId() == aCurSnapshotId
5158 )
5159 mData->mCurrentSnapshot = pSnapshot;
5160
5161 // now create the children
5162 for (settings::SnapshotsList::const_iterator it = data.llChildSnapshots.begin();
5163 it != data.llChildSnapshots.end();
5164 ++it)
5165 {
5166 const settings::Snapshot &childData = *it;
5167 // recurse
5168 rc = loadSnapshot(childData,
5169 aCurSnapshotId,
5170 pSnapshot); // parent = the one we created above
5171 CheckComRCBreakRC(rc);
5172 }
5173
5174 return rc;
5175}
5176
5177/**
5178 * @param aNode <Hardware> node.
5179 */
5180HRESULT Machine::loadHardware(const settings::Hardware &data)
5181{
5182 AssertReturn(mType == IsMachine || mType == IsSnapshotMachine, E_FAIL);
5183
5184 HRESULT rc = S_OK;
5185
5186 try
5187 {
5188 /* The hardware version attribute (optional). */
5189 mHWData->mHWVersion = data.strVersion;
5190
5191 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
5192 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
5193 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
5194 mHWData->mPAEEnabled = data.fPAE;
5195
5196 mHWData->mCPUCount = data.cCPUs;
5197
5198 mHWData->mMemorySize = data.ulMemorySizeMB;
5199
5200 // boot order
5201 for (size_t i = 0;
5202 i < RT_ELEMENTS(mHWData->mBootOrder);
5203 i++)
5204 {
5205 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
5206 if (it == data.mapBootOrder.end())
5207 mHWData->mBootOrder[i] = DeviceType_Null;
5208 else
5209 mHWData->mBootOrder[i] = it->second;
5210 }
5211
5212 mHWData->mVRAMSize = data.ulVRAMSizeMB;
5213 mHWData->mMonitorCount = data.cMonitors;
5214 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
5215 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
5216 mHWData->mFirmwareType = data.firmwareType;
5217
5218#ifdef VBOX_WITH_VRDP
5219 /* RemoteDisplay */
5220 rc = mVRDPServer->loadSettings(data.vrdpSettings);
5221 CheckComRCReturnRC (rc);
5222#endif
5223
5224 /* BIOS */
5225 rc = mBIOSSettings->loadSettings(data.biosSettings);
5226 CheckComRCReturnRC (rc);
5227
5228 /* USB Controller */
5229 rc = mUSBController->loadSettings(data.usbController);
5230 CheckComRCReturnRC (rc);
5231
5232 // network adapters
5233 for (settings::NetworkAdaptersList::const_iterator it = data.llNetworkAdapters.begin();
5234 it != data.llNetworkAdapters.end();
5235 ++it)
5236 {
5237 const settings::NetworkAdapter &nic = *it;
5238
5239 /* slot unicity is guaranteed by XML Schema */
5240 AssertBreak(nic.ulSlot < RT_ELEMENTS(mNetworkAdapters));
5241 rc = mNetworkAdapters[nic.ulSlot]->loadSettings(nic);
5242 CheckComRCReturnRC (rc);
5243 }
5244
5245 // serial ports
5246 for (settings::SerialPortsList::const_iterator it = data.llSerialPorts.begin();
5247 it != data.llSerialPorts.end();
5248 ++it)
5249 {
5250 const settings::SerialPort &s = *it;
5251
5252 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
5253 rc = mSerialPorts[s.ulSlot]->loadSettings(s);
5254 CheckComRCReturnRC (rc);
5255 }
5256
5257 // parallel ports (optional)
5258 for (settings::ParallelPortsList::const_iterator it = data.llParallelPorts.begin();
5259 it != data.llParallelPorts.end();
5260 ++it)
5261 {
5262 const settings::ParallelPort &p = *it;
5263
5264 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
5265 rc = mParallelPorts[p.ulSlot]->loadSettings(p);
5266 CheckComRCReturnRC (rc);
5267 }
5268
5269 /* AudioAdapter */
5270 rc = mAudioAdapter->loadSettings(data.audioAdapter);
5271 CheckComRCReturnRC (rc);
5272
5273 for (settings::SharedFoldersList::const_iterator it = data.llSharedFolders.begin();
5274 it != data.llSharedFolders.end();
5275 ++it)
5276 {
5277 const settings::SharedFolder &sf = *it;
5278 rc = CreateSharedFolder(Bstr(sf.strName), Bstr(sf.strHostPath), sf.fWritable);
5279 CheckComRCReturnRC (rc);
5280 }
5281
5282 // Clipboard
5283 mHWData->mClipboardMode = data.clipboardMode;
5284
5285 // guest settings
5286 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
5287 mHWData->mStatisticsUpdateInterval = data.ulStatisticsUpdateInterval;
5288
5289#ifdef VBOX_WITH_GUEST_PROPS
5290 /* Guest properties (optional) */
5291 for (settings::GuestPropertiesList::const_iterator it = data.llGuestProperties.begin();
5292 it != data.llGuestProperties.end();
5293 ++it)
5294 {
5295 const settings::GuestProperty &prop = *it;
5296 uint32_t fFlags = guestProp::NILFLAG;
5297 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
5298 HWData::GuestProperty property = { prop.strName, prop.strValue, prop.timestamp, fFlags };
5299 mHWData->mGuestProperties.push_back(property);
5300 }
5301
5302 mHWData->mPropertyServiceActive = false;
5303 mHWData->mGuestPropertyNotificationPatterns = data.strNotificationPatterns;
5304#endif /* VBOX_WITH_GUEST_PROPS defined */
5305 }
5306 catch(std::bad_alloc &)
5307 {
5308 return E_OUTOFMEMORY;
5309 }
5310
5311 AssertComRC(rc);
5312 return rc;
5313}
5314
5315 /**
5316 * @param aNode <StorageControllers> node.
5317 */
5318HRESULT Machine::loadStorageControllers(const settings::Storage &data,
5319 bool aRegistered,
5320 const Guid *aSnapshotId /* = NULL */)
5321{
5322 AssertReturn (mType == IsMachine || mType == IsSnapshotMachine, E_FAIL);
5323
5324 HRESULT rc = S_OK;
5325
5326 /* Make sure the attached hard disks don't get unregistered until we
5327 * associate them with tis machine (important for VMs loaded (opened) after
5328 * VirtualBox startup) */
5329 AutoReadLock vboxLock(mParent);
5330
5331 for (settings::StorageControllersList::const_iterator it = data.llStorageControllers.begin();
5332 it != data.llStorageControllers.end();
5333 ++it)
5334 {
5335 const settings::StorageController &ctlData = *it;
5336
5337 ComObjPtr<StorageController> pCtl;
5338 /* Try to find one with the name first. */
5339 rc = getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
5340 if (SUCCEEDED(rc))
5341 return setError(VBOX_E_OBJECT_IN_USE,
5342 tr("Storage controller named '%s' already exists"),
5343 ctlData.strName.raw());
5344
5345 pCtl.createObject();
5346 rc = pCtl->init(this,
5347 ctlData.strName,
5348 ctlData.storageBus);
5349 CheckComRCReturnRC (rc);
5350
5351 mStorageControllers->push_back(pCtl);
5352
5353 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
5354 CheckComRCReturnRC (rc);
5355
5356 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
5357 CheckComRCReturnRC (rc);
5358
5359 /* Set IDE emulation settings (only for AHCI controller). */
5360 if (ctlData.controllerType == StorageControllerType_IntelAhci)
5361 {
5362 if ( (FAILED(rc = pCtl->SetIDEEmulationPort(0, ctlData.lIDE0MasterEmulationPort)))
5363 || (FAILED(rc = pCtl->SetIDEEmulationPort(1, ctlData.lIDE0SlaveEmulationPort)))
5364 || (FAILED(rc = pCtl->SetIDEEmulationPort(2, ctlData.lIDE1MasterEmulationPort)))
5365 || (FAILED(rc = pCtl->SetIDEEmulationPort(3, ctlData.lIDE1SlaveEmulationPort)))
5366 )
5367 return rc;
5368 }
5369
5370 /* Load the attached devices now. */
5371 rc = loadStorageDevices(pCtl,
5372 ctlData,
5373 aRegistered,
5374 aSnapshotId);
5375 CheckComRCReturnRC (rc);
5376 }
5377
5378 return S_OK;
5379}
5380
5381/**
5382 * @param aNode <HardDiskAttachments> node.
5383 * @param aRegistered true when the machine is being loaded on VirtualBox
5384 * startup, or when a snapshot is being loaded (wchich
5385 * currently can happen on startup only)
5386 * @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
5387 *
5388 * @note Lock mParent for reading and hard disks for writing before calling.
5389 */
5390HRESULT Machine::loadStorageDevices(StorageController *aStorageController,
5391 const settings::StorageController &data,
5392 bool aRegistered,
5393 const Guid *aSnapshotId /*= NULL*/)
5394{
5395 AssertReturn ((mType == IsMachine && aSnapshotId == NULL) ||
5396 (mType == IsSnapshotMachine && aSnapshotId != NULL), E_FAIL);
5397
5398 HRESULT rc = S_OK;
5399
5400 if (!aRegistered && data.llAttachedDevices.size() > 0)
5401 /* when the machine is being loaded (opened) from a file, it cannot
5402 * have hard disks attached (this should not happen normally,
5403 * because we don't allow to attach hard disks to an unregistered
5404 * VM at all */
5405 return setError(E_FAIL,
5406 tr("Unregistered machine '%ls' cannot have storage devices attached (found %d attachments)"),
5407 mUserData->mName.raw(),
5408 data.llAttachedDevices.size());
5409
5410 /* paranoia: detect duplicate attachments */
5411 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
5412 it != data.llAttachedDevices.end();
5413 ++it)
5414 {
5415 for (settings::AttachedDevicesList::const_iterator it2 = it;
5416 it2 != data.llAttachedDevices.end();
5417 ++it2)
5418 {
5419 if (it == it2)
5420 continue;
5421
5422 if ( (*it).lPort == (*it2).lPort
5423 && (*it).lDevice == (*it2).lDevice)
5424 {
5425 return setError(E_FAIL,
5426 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%ls'"),
5427 aStorageController->name().raw(), (*it).lPort, (*it).lDevice, mUserData->mName.raw());
5428 }
5429 }
5430 }
5431
5432 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
5433 it != data.llAttachedDevices.end();
5434 ++it)
5435 {
5436 const settings::AttachedDevice &dev = *it;
5437 ComObjPtr<Medium> medium;
5438
5439 switch (dev.deviceType)
5440 {
5441 case DeviceType_Floppy:
5442 /* find a floppy by UUID */
5443 if (!dev.uuid.isEmpty())
5444 rc = mParent->findFloppyImage(&dev.uuid, NULL, true /* aDoSetError */, &medium);
5445 /* find a floppy by host device name */
5446 else if (!dev.strHostDriveSrc.isEmpty())
5447 {
5448 SafeIfaceArray<IMedium> drivevec;
5449 rc = mParent->host()->COMGETTER(FloppyDrives)(ComSafeArrayAsOutParam(drivevec));
5450 if (SUCCEEDED(rc))
5451 {
5452 for (size_t i = 0; i < drivevec.size(); ++i)
5453 {
5454 Bstr hostDriveSrc(dev.strHostDriveSrc);
5455 /// @todo eliminate this conversion
5456 ComObjPtr<Medium> med = (Medium *)drivevec[i];
5457 if ( hostDriveSrc == med->name()
5458 || hostDriveSrc == med->location())
5459 {
5460 medium = med;
5461 break;
5462 }
5463 }
5464 }
5465 }
5466 break;
5467
5468 case DeviceType_DVD:
5469 /* find a DVD by UUID */
5470 if (!dev.uuid.isEmpty())
5471 rc = mParent->findDVDImage(&dev.uuid, NULL, true /* aDoSetError */, &medium);
5472 /* find a DVD by host device name */
5473 else if (!dev.strHostDriveSrc.isEmpty())
5474 {
5475 SafeIfaceArray<IMedium> drivevec;
5476 rc = mParent->host()->COMGETTER(DVDDrives)(ComSafeArrayAsOutParam(drivevec));
5477 if (SUCCEEDED(rc))
5478 {
5479 for (size_t i = 0; i < drivevec.size(); ++i)
5480 {
5481 Bstr hostDriveSrc(dev.strHostDriveSrc);
5482 /// @todo eliminate this conversion
5483 ComObjPtr<Medium> med = (Medium *)drivevec[i];
5484 if ( hostDriveSrc == med->name()
5485 || hostDriveSrc == med->location())
5486 {
5487 medium = med;
5488 break;
5489 }
5490 }
5491 }
5492 }
5493 break;
5494
5495 case DeviceType_HardDisk:
5496 {
5497 /* find a hard disk by UUID */
5498 rc = mParent->findHardDisk(&dev.uuid, NULL, true /* aDoSetError */, &medium);
5499 CheckComRCReturnRC(rc);
5500
5501 AutoWriteLock hdLock(medium);
5502
5503 if (medium->type() == MediumType_Immutable)
5504 {
5505 if (mType == IsSnapshotMachine)
5506 return setError(E_FAIL,
5507 tr("Immutable hard disk '%ls' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
5508 "of the virtual machine '%ls' ('%s')"),
5509 medium->locationFull().raw(),
5510 dev.uuid.raw(),
5511 aSnapshotId->raw(),
5512 mUserData->mName.raw(),
5513 mData->m_strConfigFileFull.raw());
5514
5515 return setError(E_FAIL,
5516 tr("Immutable hard disk '%ls' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%ls' ('%s')"),
5517 medium->locationFull().raw(),
5518 dev.uuid.raw(),
5519 mUserData->mName.raw(),
5520 mData->m_strConfigFileFull.raw());
5521 }
5522
5523 if ( mType != IsSnapshotMachine
5524 && medium->children().size() != 0
5525 )
5526 return setError(E_FAIL,
5527 tr("Hard disk '%ls' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%ls' ('%s') "
5528 "because it has %d differencing child hard disks"),
5529 medium->locationFull().raw(),
5530 dev.uuid.raw(),
5531 mUserData->mName.raw(),
5532 mData->m_strConfigFileFull.raw(),
5533 medium->children().size());
5534
5535 if (findAttachment(mMediaData->mAttachments,
5536 medium))
5537 return setError(E_FAIL,
5538 tr("Hard disk '%ls' with UUID {%RTuuid} is already attached to the virtual machine '%ls' ('%s')"),
5539 medium->locationFull().raw(),
5540 dev.uuid.raw(),
5541 mUserData->mName.raw(),
5542 mData->m_strConfigFileFull.raw());
5543
5544 break;
5545 }
5546
5547 default:
5548 return setError(E_FAIL,
5549 tr("Device with unknown type is attached to the virtual machine '%ls' ('%s')"),
5550 medium->locationFull().raw(),
5551 mUserData->mName.raw(),
5552 mData->m_strConfigFileFull.raw());
5553 }
5554
5555 if (rc)
5556 break;
5557
5558 const Bstr controllerName = aStorageController->name();
5559 ComObjPtr<MediumAttachment> pAttachment;
5560 pAttachment.createObject();
5561 rc = pAttachment->init(this,
5562 medium,
5563 controllerName,
5564 dev.lPort,
5565 dev.lDevice,
5566 dev.deviceType);
5567 CheckComRCBreakRC(rc);
5568
5569 if (dev.deviceType == DeviceType_HardDisk)
5570 {
5571 /* associate the hard disk with this machine and snapshot */
5572 if (mType == IsSnapshotMachine)
5573 rc = medium->attachTo(mData->mUuid, *aSnapshotId);
5574 else
5575 rc = medium->attachTo(mData->mUuid);
5576 AssertComRCBreakRC (rc);
5577 }
5578
5579 /* backup mMediaData to let registeredInit() properly rollback on failure
5580 * (= limited accessibility) */
5581
5582 mMediaData.backup();
5583 mMediaData->mAttachments.push_back(pAttachment);
5584 }
5585
5586 return rc;
5587}
5588
5589/**
5590 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
5591 *
5592 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
5593 * @param aSnapshot where to return the found snapshot
5594 * @param aSetError true to set extended error info on failure
5595 */
5596HRESULT Machine::findSnapshot(const Guid &aId,
5597 ComObjPtr<Snapshot> &aSnapshot,
5598 bool aSetError /* = false */)
5599{
5600 AutoReadLock chlock(snapshotsTreeLockHandle());
5601
5602 if (!mData->mFirstSnapshot)
5603 {
5604 if (aSetError)
5605 return setError(E_FAIL,
5606 tr("This machine does not have any snapshots"));
5607 return E_FAIL;
5608 }
5609
5610 if (aId.isEmpty())
5611 aSnapshot = mData->mFirstSnapshot;
5612 else
5613 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aId);
5614
5615 if (!aSnapshot)
5616 {
5617 if (aSetError)
5618 return setError(E_FAIL,
5619 tr("Could not find a snapshot with UUID {%s}"),
5620 aId.toString().raw());
5621 return E_FAIL;
5622 }
5623
5624 return S_OK;
5625}
5626
5627/**
5628 * Returns the snapshot with the given name or fails of no such snapshot.
5629 *
5630 * @param aName snapshot name to find
5631 * @param aSnapshot where to return the found snapshot
5632 * @param aSetError true to set extended error info on failure
5633 */
5634HRESULT Machine::findSnapshot(IN_BSTR aName,
5635 ComObjPtr<Snapshot> &aSnapshot,
5636 bool aSetError /* = false */)
5637{
5638 AssertReturn(aName, E_INVALIDARG);
5639
5640 AutoReadLock chlock(snapshotsTreeLockHandle());
5641
5642 if (!mData->mFirstSnapshot)
5643 {
5644 if (aSetError)
5645 return setError(VBOX_E_OBJECT_NOT_FOUND,
5646 tr("This machine does not have any snapshots"));
5647 return VBOX_E_OBJECT_NOT_FOUND;
5648 }
5649
5650 aSnapshot = mData->mFirstSnapshot->findChildOrSelf (aName);
5651
5652 if (!aSnapshot)
5653 {
5654 if (aSetError)
5655 return setError(VBOX_E_OBJECT_NOT_FOUND,
5656 tr("Could not find a snapshot named '%ls'"), aName);
5657 return VBOX_E_OBJECT_NOT_FOUND;
5658 }
5659
5660 return S_OK;
5661}
5662
5663/**
5664 * Returns a storage controller object with the given name.
5665 *
5666 * @param aName storage controller name to find
5667 * @param aStorageController where to return the found storage controller
5668 * @param aSetError true to set extended error info on failure
5669 */
5670HRESULT Machine::getStorageControllerByName(const Utf8Str &aName,
5671 ComObjPtr<StorageController> &aStorageController,
5672 bool aSetError /* = false */)
5673{
5674 AssertReturn (!aName.isEmpty(), E_INVALIDARG);
5675
5676 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
5677 it != mStorageControllers->end();
5678 ++it)
5679 {
5680 if ((*it)->name() == aName)
5681 {
5682 aStorageController = (*it);
5683 return S_OK;
5684 }
5685 }
5686
5687 if (aSetError)
5688 return setError(VBOX_E_OBJECT_NOT_FOUND,
5689 tr("Could not find a storage controller named '%s'"),
5690 aName.raw());
5691 return VBOX_E_OBJECT_NOT_FOUND;
5692}
5693
5694HRESULT Machine::getMediumAttachmentsOfController(CBSTR aName,
5695 MediaData::AttachmentList &atts)
5696{
5697 AutoCaller autoCaller(this);
5698 CheckComRCReturnRC(autoCaller.rc());
5699
5700 AutoReadLock alock(this);
5701
5702 for (MediaData::AttachmentList::iterator it = mMediaData->mAttachments.begin();
5703 it != mMediaData->mAttachments.end();
5704 ++it)
5705 {
5706 if ((*it)->controller() == aName)
5707 atts.push_back(*it);
5708 }
5709
5710 return S_OK;
5711}
5712
5713/**
5714 * Helper for #saveSettings. Cares about renaming the settings directory and
5715 * file if the machine name was changed and about creating a new settings file
5716 * if this is a new machine.
5717 *
5718 * @note Must be never called directly but only from #saveSettings().
5719 *
5720 * @param aRenamed receives |true| if the name was changed and the settings
5721 * file was renamed as a result, or |false| otherwise. The
5722 * value makes sense only on success.
5723 * @param aNew receives |true| if a virgin settings file was created.
5724 */
5725HRESULT Machine::prepareSaveSettings(bool &aRenamed,
5726 bool &aNew)
5727{
5728 /* Note: tecnhically, mParent needs to be locked only when the machine is
5729 * registered (see prepareSaveSettings() for details) but we don't
5730 * currently differentiate it in callers of saveSettings() so we don't
5731 * make difference here too. */
5732 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
5733 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
5734
5735 HRESULT rc = S_OK;
5736
5737 aRenamed = false;
5738
5739 /* if we're ready and isConfigLocked() is FALSE then it means
5740 * that no config file exists yet (we will create a virgin one) */
5741 aNew = !mData->m_pMachineConfigFile->fileExists();
5742
5743 /* attempt to rename the settings file if machine name is changed */
5744 if ( mUserData->mNameSync
5745 && mUserData.isBackedUp()
5746 && mUserData.backedUpData()->mName != mUserData->mName
5747 )
5748 {
5749 aRenamed = true;
5750
5751 bool dirRenamed = false;
5752 bool fileRenamed = false;
5753
5754 Utf8Str configFile, newConfigFile;
5755 Utf8Str configDir, newConfigDir;
5756
5757 do
5758 {
5759 int vrc = VINF_SUCCESS;
5760
5761 Utf8Str name = mUserData.backedUpData()->mName;
5762 Utf8Str newName = mUserData->mName;
5763
5764 configFile = mData->m_strConfigFileFull;
5765
5766 /* first, rename the directory if it matches the machine name */
5767 configDir = configFile;
5768 configDir.stripFilename();
5769 newConfigDir = configDir;
5770 if (!strcmp(RTPathFilename(configDir.c_str()), name.c_str()))
5771 {
5772 newConfigDir.stripFilename();
5773 newConfigDir = Utf8StrFmt ("%s%c%s",
5774 newConfigDir.raw(), RTPATH_DELIMITER, newName.raw());
5775 /* new dir and old dir cannot be equal here because of 'if'
5776 * above and because name != newName */
5777 Assert (configDir != newConfigDir);
5778 if (!aNew)
5779 {
5780 /* perform real rename only if the machine is not new */
5781 vrc = RTPathRename (configDir.raw(), newConfigDir.raw(), 0);
5782 if (RT_FAILURE(vrc))
5783 {
5784 rc = setError(E_FAIL,
5785 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
5786 configDir.raw(),
5787 newConfigDir.raw(),
5788 vrc);
5789 break;
5790 }
5791 dirRenamed = true;
5792 }
5793 }
5794
5795 newConfigFile = Utf8StrFmt ("%s%c%s.xml",
5796 newConfigDir.raw(), RTPATH_DELIMITER, newName.raw());
5797
5798 /* then try to rename the settings file itself */
5799 if (newConfigFile != configFile)
5800 {
5801 /* get the path to old settings file in renamed directory */
5802 configFile = Utf8StrFmt("%s%c%s",
5803 newConfigDir.raw(),
5804 RTPATH_DELIMITER,
5805 RTPathFilename(configFile.c_str()));
5806 if (!aNew)
5807 {
5808 /* perform real rename only if the machine is not new */
5809 vrc = RTFileRename (configFile.raw(), newConfigFile.raw(), 0);
5810 if (RT_FAILURE(vrc))
5811 {
5812 rc = setError(E_FAIL,
5813 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
5814 configFile.raw(),
5815 newConfigFile.raw(),
5816 vrc);
5817 break;
5818 }
5819 fileRenamed = true;
5820 }
5821 }
5822
5823 /* update m_strConfigFileFull amd mConfigFile */
5824 Utf8Str oldConfigFileFull = mData->m_strConfigFileFull;
5825 Utf8Str oldConfigFile = mData->m_strConfigFile;
5826 mData->m_strConfigFileFull = newConfigFile;
5827 /* try to get the relative path for mConfigFile */
5828 Utf8Str path = newConfigFile;
5829 mParent->calculateRelativePath (path, path);
5830 mData->m_strConfigFile = path;
5831
5832 /* last, try to update the global settings with the new path */
5833 if (mData->mRegistered)
5834 {
5835 rc = mParent->updateSettings(configDir.c_str(), newConfigDir.c_str());
5836 if (FAILED(rc))
5837 {
5838 /* revert to old values */
5839 mData->m_strConfigFileFull = oldConfigFileFull;
5840 mData->m_strConfigFile = oldConfigFile;
5841 break;
5842 }
5843 }
5844
5845 /* update the snapshot folder */
5846 path = mUserData->mSnapshotFolderFull;
5847 if (RTPathStartsWith(path.c_str(), configDir.c_str()))
5848 {
5849 path = Utf8StrFmt("%s%s", newConfigDir.raw(),
5850 path.raw() + configDir.length());
5851 mUserData->mSnapshotFolderFull = path;
5852 calculateRelativePath (path, path);
5853 mUserData->mSnapshotFolder = path;
5854 }
5855
5856 /* update the saved state file path */
5857 path = mSSData->mStateFilePath;
5858 if (RTPathStartsWith(path.c_str(), configDir.c_str()))
5859 {
5860 path = Utf8StrFmt("%s%s", newConfigDir.raw(),
5861 path.raw() + configDir.length());
5862 mSSData->mStateFilePath = path;
5863 }
5864
5865 /* Update saved state file paths of all online snapshots.
5866 * Note that saveSettings() will recognize name change
5867 * and will save all snapshots in this case. */
5868 if (mData->mFirstSnapshot)
5869 mData->mFirstSnapshot->updateSavedStatePaths(configDir.c_str(),
5870 newConfigDir.c_str());
5871 }
5872 while (0);
5873
5874 if (FAILED(rc))
5875 {
5876 /* silently try to rename everything back */
5877 if (fileRenamed)
5878 RTFileRename(newConfigFile.raw(), configFile.raw(), 0);
5879 if (dirRenamed)
5880 RTPathRename(newConfigDir.raw(), configDir.raw(), 0);
5881 }
5882
5883 CheckComRCReturnRC(rc);
5884 }
5885
5886 if (aNew)
5887 {
5888 /* create a virgin config file */
5889 int vrc = VINF_SUCCESS;
5890
5891 /* ensure the settings directory exists */
5892 Utf8Str path(mData->m_strConfigFileFull);
5893 path.stripFilename();
5894 if (!RTDirExists(path.c_str()))
5895 {
5896 vrc = RTDirCreateFullPath(path.c_str(), 0777);
5897 if (RT_FAILURE(vrc))
5898 {
5899 return setError(E_FAIL,
5900 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
5901 path.raw(),
5902 vrc);
5903 }
5904 }
5905
5906 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
5907 path = Utf8Str(mData->m_strConfigFileFull);
5908 vrc = RTFileOpen(&mData->mHandleCfgFile, path.c_str(),
5909 RTFILE_O_READWRITE | RTFILE_O_CREATE |
5910 RTFILE_O_DENY_WRITE);
5911 if (RT_FAILURE(vrc))
5912 {
5913 mData->mHandleCfgFile = NIL_RTFILE;
5914 return setError(E_FAIL,
5915 tr("Could not create the settings file '%s' (%Rrc)"),
5916 path.raw(),
5917 vrc);
5918 }
5919 RTFileClose(mData->mHandleCfgFile);
5920 }
5921
5922 return rc;
5923}
5924
5925/**
5926 * Saves and commits machine data, user data and hardware data.
5927 *
5928 * Note that on failure, the data remains uncommitted.
5929 *
5930 * @a aFlags may combine the following flags:
5931 *
5932 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
5933 * Used when saving settings after an operation that makes them 100%
5934 * correspond to the settings from the current snapshot.
5935 * - SaveS_InformCallbacksAnyway: Callbacks will be informed even if
5936 * #isReallyModified() returns false. This is necessary for cases when we
5937 * change machine data diectly, not through the backup()/commit() mechanism.
5938 *
5939 * @note Must be called from under mParent write lock (sometimes needed by
5940 * #prepareSaveSettings()) and this object's write lock. Locks children for
5941 * writing. There is one exception when mParent is unused and therefore may be
5942 * left unlocked: if this machine is an unregistered one.
5943 */
5944HRESULT Machine::saveSettings(int aFlags /*= 0*/)
5945{
5946 LogFlowThisFuncEnter();
5947
5948 /* Note: tecnhically, mParent needs to be locked only when the machine is
5949 * registered (see prepareSaveSettings() for details) but we don't
5950 * currently differentiate it in callers of saveSettings() so we don't
5951 * make difference here too. */
5952 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
5953 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
5954
5955 /* make sure child objects are unable to modify the settings while we are
5956 * saving them */
5957 ensureNoStateDependencies();
5958
5959 AssertReturn(mType == IsMachine || mType == IsSessionMachine, E_FAIL);
5960
5961 BOOL currentStateModified = mData->mCurrentStateModified;
5962 bool settingsModified;
5963
5964 if (!(aFlags & SaveS_ResetCurStateModified) && !currentStateModified)
5965 {
5966 /* We ignore changes to user data when setting mCurrentStateModified
5967 * because the current state will not differ from the current snapshot
5968 * if only user data has been changed (user data is shared by all
5969 * snapshots). */
5970 currentStateModified = isReallyModified (true /* aIgnoreUserData */);
5971 settingsModified = mUserData.hasActualChanges() || currentStateModified;
5972 }
5973 else
5974 {
5975 if (aFlags & SaveS_ResetCurStateModified)
5976 currentStateModified = FALSE;
5977 settingsModified = isReallyModified();
5978 }
5979
5980 HRESULT rc = S_OK;
5981
5982 /* First, prepare to save settings. It will care about renaming the
5983 * settings directory and file if the machine name was changed and about
5984 * creating a new settings file if this is a new machine. */
5985 bool isRenamed = false;
5986 bool isNew = false;
5987 rc = prepareSaveSettings(isRenamed, isNew);
5988 CheckComRCReturnRC(rc);
5989
5990 try
5991 {
5992 mData->m_pMachineConfigFile->uuid = mData->mUuid;
5993 mData->m_pMachineConfigFile->strName = mUserData->mName;
5994 mData->m_pMachineConfigFile->fNameSync = !!mUserData->mNameSync;
5995 mData->m_pMachineConfigFile->strDescription = mUserData->mDescription;
5996 mData->m_pMachineConfigFile->strOsType = mUserData->mOSTypeId;
5997
5998 if ( mData->mMachineState == MachineState_Saved
5999 || mData->mMachineState == MachineState_Restoring
6000 )
6001 {
6002 Assert(!mSSData->mStateFilePath.isEmpty());
6003 /* try to make the file name relative to the settings file dir */
6004 Utf8Str stateFilePath = mSSData->mStateFilePath;
6005 calculateRelativePath(stateFilePath, stateFilePath);
6006
6007 mData->m_pMachineConfigFile->strStateFile = stateFilePath;
6008 }
6009 else
6010 {
6011 Assert(mSSData->mStateFilePath.isNull());
6012 mData->m_pMachineConfigFile->strStateFile.setNull();
6013 }
6014
6015 if (mData->mCurrentSnapshot)
6016 mData->m_pMachineConfigFile->uuidCurrentSnapshot = mData->mCurrentSnapshot->getId();
6017 else
6018 mData->m_pMachineConfigFile->uuidCurrentSnapshot.clear();
6019
6020 mData->m_pMachineConfigFile->strSnapshotFolder = mUserData->mSnapshotFolder;
6021 mData->m_pMachineConfigFile->fCurrentStateModified = !!currentStateModified;
6022 mData->m_pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
6023 mData->m_pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
6024/** @todo LiveMigration: Save LiveMigration properties here. */
6025
6026 rc = saveHardware(mData->m_pMachineConfigFile->hardwareMachine);
6027 CheckComRCThrowRC(rc);
6028
6029 rc = saveStorageControllers(mData->m_pMachineConfigFile->storageMachine);
6030 CheckComRCThrowRC(rc);
6031
6032 // save snapshots
6033 rc = saveAllSnapshots();
6034 CheckComRCThrowRC(rc);
6035
6036 // now spit it all out
6037 mData->m_pMachineConfigFile->write(mData->m_strConfigFileFull);
6038 }
6039 catch (HRESULT err)
6040 {
6041 /* we assume that error info is set by the thrower */
6042 rc = err;
6043 }
6044 catch (...)
6045 {
6046 rc = VirtualBox::handleUnexpectedExceptions (RT_SRC_POS);
6047 }
6048
6049 if (SUCCEEDED(rc))
6050 {
6051 commit();
6052
6053 /* memorize the new modified state */
6054 mData->mCurrentStateModified = currentStateModified;
6055 }
6056
6057 if (settingsModified || (aFlags & SaveS_InformCallbacksAnyway))
6058 {
6059 /* Fire the data change event, even on failure (since we've already
6060 * committed all data). This is done only for SessionMachines because
6061 * mutable Machine instances are always not registered (i.e. private
6062 * to the client process that creates them) and thus don't need to
6063 * inform callbacks. */
6064 if (mType == IsSessionMachine)
6065 mParent->onMachineDataChange(mData->mUuid);
6066 }
6067
6068 LogFlowThisFunc(("rc=%08X\n", rc));
6069 LogFlowThisFuncLeave();
6070 return rc;
6071}
6072
6073HRESULT Machine::saveAllSnapshots()
6074{
6075 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
6076
6077 HRESULT rc = S_OK;
6078
6079 try
6080 {
6081 mData->m_pMachineConfigFile->llFirstSnapshot.clear();
6082
6083 if (mData->mFirstSnapshot)
6084 {
6085 settings::Snapshot snapNew;
6086 mData->m_pMachineConfigFile->llFirstSnapshot.push_back(snapNew);
6087
6088 // get reference to the fresh copy of the snapshot on the list and
6089 // work on that copy directly to avoid excessive copying later
6090 settings::Snapshot &snap = mData->m_pMachineConfigFile->llFirstSnapshot.front();
6091
6092 rc = mData->mFirstSnapshot->saveSnapshot(snap, false /*aAttrsOnly*/);
6093 CheckComRCThrowRC(rc);
6094 }
6095
6096// if (mType == IsSessionMachine)
6097// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
6098
6099 }
6100 catch (HRESULT err)
6101 {
6102 /* we assume that error info is set by the thrower */
6103 rc = err;
6104 }
6105 catch (...)
6106 {
6107 rc = VirtualBox::handleUnexpectedExceptions (RT_SRC_POS);
6108 }
6109
6110 return rc;
6111}
6112
6113/**
6114 * Saves the VM hardware configuration. It is assumed that the
6115 * given node is empty.
6116 *
6117 * @param aNode <Hardware> node to save the VM hardware confguration to.
6118 */
6119HRESULT Machine::saveHardware(settings::Hardware &data)
6120{
6121 HRESULT rc = S_OK;
6122
6123 try
6124 {
6125 /* The hardware version attribute (optional).
6126 Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
6127 if ( mHWData->mHWVersion == "1"
6128 && mSSData->mStateFilePath.isEmpty()
6129 )
6130 mHWData->mHWVersion = "2"; /** @todo Is this safe, to update mHWVersion here? If not some other point needs to be found where this can be done. */
6131
6132 data.strVersion = mHWData->mHWVersion;
6133
6134 // CPU
6135 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
6136 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
6137 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
6138 data.fPAE = !!mHWData->mPAEEnabled;
6139
6140 data.cCPUs = mHWData->mCPUCount;
6141
6142 // memory
6143 data.ulMemorySizeMB = mHWData->mMemorySize;
6144
6145 // firmware
6146 data.firmwareType = mHWData->mFirmwareType;
6147
6148 // boot order
6149 data.mapBootOrder.clear();
6150 for (size_t i = 0;
6151 i < RT_ELEMENTS(mHWData->mBootOrder);
6152 ++i)
6153 data.mapBootOrder[i] = mHWData->mBootOrder[i];
6154
6155 // display
6156 data.ulVRAMSizeMB = mHWData->mVRAMSize;
6157 data.cMonitors = mHWData->mMonitorCount;
6158 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
6159 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
6160
6161#ifdef VBOX_WITH_VRDP
6162 /* VRDP settings (optional) */
6163 rc = mVRDPServer->saveSettings(data.vrdpSettings);
6164 CheckComRCThrowRC(rc);
6165#endif
6166
6167 /* BIOS (required) */
6168 rc = mBIOSSettings->saveSettings(data.biosSettings);
6169 CheckComRCThrowRC(rc);
6170
6171 /* USB Controller (required) */
6172 rc = mUSBController->saveSettings(data.usbController);
6173 CheckComRCThrowRC(rc);
6174
6175 /* Network adapters (required) */
6176 data.llNetworkAdapters.clear();
6177 for (ULONG slot = 0;
6178 slot < RT_ELEMENTS(mNetworkAdapters);
6179 ++slot)
6180 {
6181 settings::NetworkAdapter nic;
6182 nic.ulSlot = slot;
6183 rc = mNetworkAdapters[slot]->saveSettings(nic);
6184 CheckComRCThrowRC(rc);
6185
6186 data.llNetworkAdapters.push_back(nic);
6187 }
6188
6189 /* Serial ports */
6190 data.llSerialPorts.clear();
6191 for (ULONG slot = 0;
6192 slot < RT_ELEMENTS(mSerialPorts);
6193 ++slot)
6194 {
6195 settings::SerialPort s;
6196 s.ulSlot = slot;
6197 rc = mSerialPorts[slot]->saveSettings(s);
6198 CheckComRCReturnRC (rc);
6199
6200 data.llSerialPorts.push_back(s);
6201 }
6202
6203 /* Parallel ports */
6204 data.llParallelPorts.clear();
6205 for (ULONG slot = 0;
6206 slot < RT_ELEMENTS(mParallelPorts);
6207 ++slot)
6208 {
6209 settings::ParallelPort p;
6210 p.ulSlot = slot;
6211 rc = mParallelPorts[slot]->saveSettings(p);
6212 CheckComRCReturnRC (rc);
6213
6214 data.llParallelPorts.push_back(p);
6215 }
6216
6217 /* Audio adapter */
6218 rc = mAudioAdapter->saveSettings(data.audioAdapter);
6219 CheckComRCReturnRC (rc);
6220
6221 /* Shared folders */
6222 data.llSharedFolders.clear();
6223 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
6224 it != mHWData->mSharedFolders.end();
6225 ++it)
6226 {
6227 ComObjPtr<SharedFolder> pFolder = *it;
6228 settings::SharedFolder sf;
6229 sf.strName = pFolder->name();
6230 sf.strHostPath = pFolder->hostPath();
6231 sf.fWritable = !!pFolder->writable();
6232
6233 data.llSharedFolders.push_back(sf);
6234 }
6235
6236 // clipboard
6237 data.clipboardMode = mHWData->mClipboardMode;
6238
6239 /* Guest */
6240 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
6241 data.ulStatisticsUpdateInterval = mHWData->mStatisticsUpdateInterval;
6242
6243 // guest properties
6244 data.llGuestProperties.clear();
6245#ifdef VBOX_WITH_GUEST_PROPS
6246 for (HWData::GuestPropertyList::const_iterator it = mHWData->mGuestProperties.begin();
6247 it != mHWData->mGuestProperties.end();
6248 ++it)
6249 {
6250 HWData::GuestProperty property = *it;
6251
6252 settings::GuestProperty prop;
6253 prop.strName = property.strName;
6254 prop.strValue = property.strValue;
6255 prop.timestamp = property.mTimestamp;
6256 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
6257 guestProp::writeFlags(property.mFlags, szFlags);
6258 prop.strFlags = szFlags;
6259
6260 data.llGuestProperties.push_back(prop);
6261 }
6262
6263 data.strNotificationPatterns = mHWData->mGuestPropertyNotificationPatterns;
6264#endif /* VBOX_WITH_GUEST_PROPS defined */
6265 }
6266 catch(std::bad_alloc &)
6267 {
6268 return E_OUTOFMEMORY;
6269 }
6270
6271 AssertComRC(rc);
6272 return rc;
6273}
6274
6275/**
6276 * Saves the storage controller configuration.
6277 *
6278 * @param aNode <StorageControllers> node to save the VM hardware confguration to.
6279 */
6280HRESULT Machine::saveStorageControllers(settings::Storage &data)
6281{
6282 data.llStorageControllers.clear();
6283
6284 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
6285 it != mStorageControllers->end();
6286 ++it)
6287 {
6288 HRESULT rc;
6289 ComObjPtr<StorageController> pCtl = *it;
6290
6291 settings::StorageController ctl;
6292 ctl.strName = pCtl->name();
6293 ctl.controllerType = pCtl->controllerType();
6294 ctl.storageBus = pCtl->storageBus();
6295
6296 /* Save the port count. */
6297 ULONG portCount;
6298 rc = pCtl->COMGETTER(PortCount)(&portCount);
6299 ComAssertComRCRet(rc, rc);
6300 ctl.ulPortCount = portCount;
6301
6302 /* Save IDE emulation settings. */
6303 if (ctl.controllerType == StorageControllerType_IntelAhci)
6304 {
6305 if ( (FAILED(rc = pCtl->GetIDEEmulationPort(0, (LONG*)&ctl.lIDE0MasterEmulationPort)))
6306 || (FAILED(rc = pCtl->GetIDEEmulationPort(1, (LONG*)&ctl.lIDE0SlaveEmulationPort)))
6307 || (FAILED(rc = pCtl->GetIDEEmulationPort(2, (LONG*)&ctl.lIDE1MasterEmulationPort)))
6308 || (FAILED(rc = pCtl->GetIDEEmulationPort(3, (LONG*)&ctl.lIDE1SlaveEmulationPort)))
6309 )
6310 ComAssertComRCRet(rc, rc);
6311 }
6312
6313 /* save the devices now. */
6314 rc = saveStorageDevices(pCtl, ctl);
6315 ComAssertComRCRet(rc, rc);
6316
6317 data.llStorageControllers.push_back(ctl);
6318 }
6319
6320 return S_OK;
6321}
6322
6323/**
6324 * Saves the hard disk confguration.
6325 */
6326HRESULT Machine::saveStorageDevices(ComObjPtr<StorageController> aStorageController,
6327 settings::StorageController &data)
6328{
6329 using namespace settings;
6330
6331 MediaData::AttachmentList atts;
6332
6333 HRESULT rc = getMediumAttachmentsOfController(Bstr(aStorageController->name()), atts);
6334 CheckComRCReturnRC (rc);
6335
6336 data.llAttachedDevices.clear();
6337 for (MediaData::AttachmentList::const_iterator it = atts.begin();
6338 it != atts.end();
6339 ++it)
6340 {
6341 settings::AttachedDevice dev;
6342
6343 dev.deviceType = (*it)->type();
6344 dev.lPort = (*it)->port();
6345 dev.lDevice = (*it)->device();
6346 if (!(*it)->medium().isNull())
6347 {
6348 BOOL fHostDrive = false;
6349 rc = (*it)->medium()->COMGETTER(HostDrive)(&fHostDrive);
6350 if (FAILED(rc))
6351 return rc;
6352 if (fHostDrive)
6353 dev.strHostDriveSrc = (*it)->medium()->location();
6354 else
6355 dev.uuid = (*it)->medium()->id();
6356 dev.fPassThrough = (*it)->passthrough();
6357 }
6358
6359 data.llAttachedDevices.push_back(dev);
6360 }
6361
6362 return S_OK;
6363}
6364
6365/**
6366 * Saves machine state settings as defined by aFlags
6367 * (SaveSTS_* values).
6368 *
6369 * @param aFlags Combination of SaveSTS_* flags.
6370 *
6371 * @note Locks objects for writing.
6372 */
6373HRESULT Machine::saveStateSettings(int aFlags)
6374{
6375 if (aFlags == 0)
6376 return S_OK;
6377
6378 AutoCaller autoCaller (this);
6379 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
6380
6381 /* This object's write lock is also necessary to serialize file access
6382 * (prevent concurrent reads and writes) */
6383 AutoWriteLock alock(this);
6384
6385 HRESULT rc = S_OK;
6386
6387 Assert(mData->m_pMachineConfigFile);
6388
6389 try
6390 {
6391 if (aFlags & SaveSTS_CurStateModified)
6392 mData->m_pMachineConfigFile->fCurrentStateModified = true;
6393
6394 if (aFlags & SaveSTS_StateFilePath)
6395 {
6396 if (mSSData->mStateFilePath)
6397 {
6398 /* try to make the file name relative to the settings file dir */
6399 Utf8Str stateFilePath = mSSData->mStateFilePath;
6400 calculateRelativePath(stateFilePath, stateFilePath);
6401 mData->m_pMachineConfigFile->strStateFile = stateFilePath;
6402 }
6403 else
6404 mData->m_pMachineConfigFile->strStateFile.setNull();
6405 }
6406
6407 if (aFlags & SaveSTS_StateTimeStamp)
6408 {
6409 Assert( mData->mMachineState != MachineState_Aborted
6410 || mSSData->mStateFilePath.isNull());
6411
6412 mData->m_pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
6413
6414 mData->m_pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
6415 }
6416
6417 mData->m_pMachineConfigFile->write(mData->m_strConfigFileFull);
6418 }
6419 catch (...)
6420 {
6421 rc = VirtualBox::handleUnexpectedExceptions (RT_SRC_POS);
6422 }
6423
6424 return rc;
6425}
6426
6427/**
6428 * Creates differencing hard disks for all normal hard disks attached to this
6429 * machine and a new set of attachments to refer to created disks.
6430 *
6431 * Used when taking a snapshot or when discarding the current state.
6432 *
6433 * This method assumes that mMediaData contains the original hard disk attachments
6434 * it needs to create diffs for. On success, these attachments will be replaced
6435 * with the created diffs. On failure, #deleteImplicitDiffs() is implicitly
6436 * called to delete created diffs which will also rollback mMediaData and restore
6437 * whatever was backed up before calling this method.
6438 *
6439 * Attachments with non-normal hard disks are left as is.
6440 *
6441 * If @a aOnline is @c false then the original hard disks that require implicit
6442 * diffs will be locked for reading. Otherwise it is assumed that they are
6443 * already locked for writing (when the VM was started). Note that in the latter
6444 * case it is responsibility of the caller to lock the newly created diffs for
6445 * writing if this method succeeds.
6446 *
6447 * @param aFolder Folder where to create diff hard disks.
6448 * @param aProgress Progress object to run (must contain at least as
6449 * many operations left as the number of hard disks
6450 * attached).
6451 * @param aOnline Whether the VM was online prior to this operation.
6452 *
6453 * @note The progress object is not marked as completed, neither on success nor
6454 * on failure. This is a responsibility of the caller.
6455 *
6456 * @note Locks this object for writing.
6457 */
6458HRESULT Machine::createImplicitDiffs(const Bstr &aFolder,
6459 IProgress *aProgress,
6460 ULONG aWeight,
6461 bool aOnline)
6462{
6463 AssertReturn(!aFolder.isEmpty(), E_FAIL);
6464
6465 LogFlowThisFunc(("aFolder='%ls', aOnline=%d\n", aFolder.raw(), aOnline));
6466
6467 AutoCaller autoCaller(this);
6468 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
6469
6470 AutoWriteLock alock(this);
6471
6472 /* must be in a protective state because we leave the lock below */
6473 AssertReturn( mData->mMachineState == MachineState_Saving
6474 || mData->mMachineState == MachineState_Discarding, E_FAIL);
6475
6476 HRESULT rc = S_OK;
6477
6478 typedef std::list< ComObjPtr<Medium> > LockedMedia;
6479 LockedMedia lockedMedia;
6480
6481 try
6482 {
6483 if (!aOnline)
6484 {
6485 /* lock all attached hard disks early to detect "in use"
6486 * situations before creating actual diffs */
6487 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
6488 it != mMediaData->mAttachments.end();
6489 ++it)
6490 {
6491 MediumAttachment* pAtt = *it;
6492 if (pAtt->type() == DeviceType_HardDisk)
6493 {
6494 Medium* pHD = pAtt->medium();
6495 Assert(pHD);
6496 rc = pHD->LockRead (NULL);
6497 CheckComRCThrowRC(rc);
6498 lockedMedia.push_back(pHD);
6499 }
6500 }
6501 }
6502
6503 /* remember the current list (note that we don't use backup() since
6504 * mMediaData may be already backed up) */
6505 MediaData::AttachmentList atts = mMediaData->mAttachments;
6506
6507 /* start from scratch */
6508 mMediaData->mAttachments.clear();
6509
6510 /* go through remembered attachments and create diffs for normal hard
6511 * disks and attach them */
6512 for (MediaData::AttachmentList::const_iterator it = atts.begin();
6513 it != atts.end();
6514 ++it)
6515 {
6516 MediumAttachment* pAtt = *it;
6517
6518 DeviceType_T devType = pAtt->type();
6519 Medium* medium = pAtt->medium();
6520
6521 if ( devType != DeviceType_HardDisk
6522 || medium == NULL
6523 || medium->type() != MediumType_Normal)
6524 {
6525 /* copy the attachment as is */
6526
6527 /** @todo the progress object created in Console::TakeSnaphot
6528 * only expects operations for hard disks. Later other
6529 * device types need to show up in the progress as well. */
6530 if (devType == DeviceType_HardDisk)
6531 {
6532 if (medium == NULL)
6533 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")),
6534 aWeight); // weight
6535 else
6536 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
6537 medium->base()->name().raw()),
6538 aWeight); // weight
6539 }
6540
6541 mMediaData->mAttachments.push_back(pAtt);
6542 continue;
6543 }
6544
6545 /* need a diff */
6546 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
6547 medium->base()->name().raw()),
6548 aWeight); // weight
6549
6550 ComObjPtr<Medium> diff;
6551 diff.createObject();
6552 rc = diff->init(mParent,
6553 medium->preferredDiffFormat().raw(),
6554 BstrFmt("%ls"RTPATH_SLASH_STR,
6555 mUserData->mSnapshotFolderFull.raw()).raw());
6556 CheckComRCThrowRC(rc);
6557
6558 /* leave the lock before the potentially lengthy operation */
6559 alock.leave();
6560
6561 rc = medium->createDiffStorageAndWait(diff,
6562 MediumVariant_Standard,
6563 NULL);
6564
6565 // at this point, the old image is still locked for writing, but instead
6566 // we need the new diff image locked for writing and lock the previously
6567 // current one for reading only
6568 if (aOnline)
6569 {
6570 diff->LockWrite(NULL);
6571 mData->mSession.mLockedMedia.push_back(Data::Session::LockedMedia::value_type(ComPtr<IMedium>(diff), true));
6572 medium->UnlockWrite(NULL);
6573 medium->LockRead(NULL);
6574 mData->mSession.mLockedMedia.push_back(Data::Session::LockedMedia::value_type(ComPtr<IMedium>(medium), false));
6575 }
6576
6577 alock.enter();
6578
6579 CheckComRCThrowRC(rc);
6580
6581 rc = diff->attachTo(mData->mUuid);
6582 AssertComRCThrowRC(rc);
6583
6584 /* add a new attachment */
6585 ComObjPtr<MediumAttachment> attachment;
6586 attachment.createObject();
6587 rc = attachment->init(this,
6588 diff,
6589 pAtt->controller(),
6590 pAtt->port(),
6591 pAtt->device(),
6592 DeviceType_HardDisk,
6593 true /* aImplicit */);
6594 CheckComRCThrowRC(rc);
6595
6596 mMediaData->mAttachments.push_back(attachment);
6597 }
6598 }
6599 catch (HRESULT aRC) { rc = aRC; }
6600
6601 /* unlock all hard disks we locked */
6602 if (!aOnline)
6603 {
6604 ErrorInfoKeeper eik;
6605
6606 for (LockedMedia::const_iterator it = lockedMedia.begin();
6607 it != lockedMedia.end();
6608 ++it)
6609 {
6610 HRESULT rc2 = (*it)->UnlockRead(NULL);
6611 AssertComRC(rc2);
6612 }
6613 }
6614
6615 if (FAILED(rc))
6616 {
6617 MultiResultRef mrc (rc);
6618
6619 mrc = deleteImplicitDiffs();
6620 }
6621
6622 return rc;
6623}
6624
6625/**
6626 * Deletes implicit differencing hard disks created either by
6627 * #createImplicitDiffs() or by #AttachMedium() and rolls back mMediaData.
6628 *
6629 * Note that to delete hard disks created by #AttachMedium() this method is
6630 * called from #fixupMedia() when the changes are rolled back.
6631 *
6632 * @note Locks this object for writing.
6633 */
6634HRESULT Machine::deleteImplicitDiffs()
6635{
6636 AutoCaller autoCaller(this);
6637 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
6638
6639 AutoWriteLock alock(this);
6640
6641 AssertReturn(mMediaData.isBackedUp(), E_FAIL);
6642
6643 HRESULT rc = S_OK;
6644
6645 MediaData::AttachmentList implicitAtts;
6646
6647 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
6648
6649 /* enumerate new attachments */
6650 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
6651 it != mMediaData->mAttachments.end();
6652 ++it)
6653 {
6654 ComObjPtr<Medium> hd = (*it)->medium();
6655 if (hd.isNull())
6656 continue;
6657
6658 if ((*it)->isImplicit())
6659 {
6660 /* deassociate and mark for deletion */
6661 rc = hd->detachFrom(mData->mUuid);
6662 AssertComRC(rc);
6663 implicitAtts.push_back (*it);
6664 continue;
6665 }
6666
6667 /* was this hard disk attached before? */
6668 if (!findAttachment(oldAtts, hd))
6669 {
6670 /* no: de-associate */
6671 rc = hd->detachFrom(mData->mUuid);
6672 AssertComRC(rc);
6673 continue;
6674 }
6675 }
6676
6677 /* rollback hard disk changes */
6678 mMediaData.rollback();
6679
6680 MultiResult mrc (S_OK);
6681
6682 /* delete unused implicit diffs */
6683 if (implicitAtts.size() != 0)
6684 {
6685 /* will leave the lock before the potentially lengthy
6686 * operation, so protect with the special state (unless already
6687 * protected) */
6688 MachineState_T oldState = mData->mMachineState;
6689 if (oldState != MachineState_Saving &&
6690 oldState != MachineState_Discarding)
6691 {
6692 setMachineState (MachineState_SettingUp);
6693 }
6694
6695 alock.leave();
6696
6697 for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin();
6698 it != implicitAtts.end();
6699 ++it)
6700 {
6701 ComObjPtr<Medium> hd = (*it)->medium();
6702 mrc = hd->deleteStorageAndWait();
6703 }
6704
6705 alock.enter();
6706
6707 if (mData->mMachineState == MachineState_SettingUp)
6708 {
6709 setMachineState (oldState);
6710 }
6711 }
6712
6713 return mrc;
6714}
6715
6716/**
6717 * Looks through the given list of media attachments for one with the given parameters
6718 * and returns it, or NULL if not found. The list is a parameter so that backup lists
6719 * can be searched as well if needed.
6720 *
6721 * @param list
6722 * @param aControllerName
6723 * @param aControllerPort
6724 * @param aDevice
6725 * @return
6726 */
6727MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
6728 IN_BSTR aControllerName,
6729 LONG aControllerPort,
6730 LONG aDevice)
6731{
6732 for (MediaData::AttachmentList::const_iterator it = ll.begin();
6733 it != ll.end();
6734 ++it)
6735 {
6736 MediumAttachment *pAttach = *it;
6737 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
6738 return pAttach;
6739 }
6740
6741 return NULL;
6742}
6743
6744/**
6745 * Looks through the given list of media attachments for one with the given parameters
6746 * and returns it, or NULL if not found. The list is a parameter so that backup lists
6747 * can be searched as well if needed.
6748 *
6749 * @param list
6750 * @param aControllerName
6751 * @param aControllerPort
6752 * @param aDevice
6753 * @return
6754 */
6755MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
6756 ComObjPtr<Medium> pMedium)
6757{
6758 for (MediaData::AttachmentList::const_iterator it = ll.begin();
6759 it != ll.end();
6760 ++it)
6761 {
6762 MediumAttachment *pAttach = *it;
6763 ComObjPtr<Medium> pMediumThis = pAttach->medium();
6764 if (pMediumThis.equalsTo(pMedium))
6765 return pAttach;
6766 }
6767
6768 return NULL;
6769}
6770
6771/**
6772 * Looks through the given list of media attachments for one with the given parameters
6773 * and returns it, or NULL if not found. The list is a parameter so that backup lists
6774 * can be searched as well if needed.
6775 *
6776 * @param list
6777 * @param aControllerName
6778 * @param aControllerPort
6779 * @param aDevice
6780 * @return
6781 */
6782MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
6783 Guid &id)
6784{
6785 for (MediaData::AttachmentList::const_iterator it = ll.begin();
6786 it != ll.end();
6787 ++it)
6788 {
6789 MediumAttachment *pAttach = *it;
6790 ComObjPtr<Medium> pMediumThis = pAttach->medium();
6791 if (pMediumThis->id() == id)
6792 return pAttach;
6793 }
6794
6795 return NULL;
6796}
6797
6798/**
6799 * Perform deferred hard disk detachments on success and deletion of implicitly
6800 * created diffs on failure.
6801 *
6802 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
6803 * backed up).
6804 *
6805 * When the data is backed up, this method will commit mMediaData if @a aCommit is
6806 * @c true and rollback it otherwise before returning.
6807 *
6808 * If @a aOnline is @c true then this method called with @a aCommit = @c true
6809 * will also unlock the old hard disks for which the new implicit diffs were
6810 * created and will lock these new diffs for writing. When @a aCommit is @c
6811 * false, this argument is ignored.
6812 *
6813 * @param aCommit @c true if called on success.
6814 * @param aOnline Whether the VM was online prior to this operation.
6815 *
6816 * @note Locks this object for writing!
6817 */
6818void Machine::fixupMedia(bool aCommit, bool aOnline /*= false*/)
6819{
6820 AutoCaller autoCaller(this);
6821 AssertComRCReturnVoid (autoCaller.rc());
6822
6823 AutoWriteLock alock(this);
6824
6825 HRESULT rc = S_OK;
6826
6827 /* no attach/detach operations -- nothing to do */
6828 if (!mMediaData.isBackedUp())
6829 return;
6830
6831 if (aCommit)
6832 {
6833 MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
6834
6835 /* enumerate new attachments */
6836 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
6837 it != mMediaData->mAttachments.end();
6838 ++it)
6839 {
6840 MediumAttachment *pAttach = *it;
6841
6842 if (pAttach->type() == DeviceType_HardDisk)
6843 {
6844 pAttach->commit();
6845
6846 Medium* pMedium = pAttach->medium();
6847
6848 /** @todo convert all this Machine-based voodoo to MediumAttachment
6849 * based commit logic. */
6850 if (pAttach->isImplicit())
6851 {
6852 /* convert implicit attachment to normal */
6853 pAttach->setImplicit(false);
6854
6855 if (aOnline)
6856 {
6857 rc = pMedium->LockWrite(NULL);
6858 AssertComRC(rc);
6859
6860 mData->mSession.mLockedMedia.push_back(
6861 Data::Session::LockedMedia::value_type(
6862 ComPtr<IMedium>(pMedium), true));
6863
6864 /* also, relock the old hard disk which is a base for the
6865 * new diff for reading if the VM is online */
6866
6867 ComObjPtr<Medium> parent = pMedium->parent();
6868 /* make the relock atomic */
6869 AutoWriteLock parentLock (parent);
6870 rc = parent->UnlockWrite(NULL);
6871 AssertComRC(rc);
6872 rc = parent->LockRead(NULL);
6873 AssertComRC(rc);
6874
6875 /* XXX actually we should replace the old entry in that
6876 * vector (write lock => read lock) but this would take
6877 * some effort. So lets just ignore the error code in
6878 * SessionMachine::unlockMedia(). */
6879 mData->mSession.mLockedMedia.push_back(
6880 Data::Session::LockedMedia::value_type (
6881 ComPtr<IMedium>(parent), false));
6882 }
6883
6884 continue;
6885 }
6886
6887 if (pMedium)
6888 {
6889 /* was this hard disk attached before? */
6890 for (MediaData::AttachmentList::iterator oldIt = oldAtts.begin();
6891 oldIt != oldAtts.end();
6892 ++oldIt)
6893 {
6894 MediumAttachment *pOldAttach = *it;
6895 if (pOldAttach->medium().equalsTo(pMedium))
6896 {
6897 /* yes: remove from old to avoid de-association */
6898 oldAtts.erase(oldIt);
6899 break;
6900 }
6901 }
6902 }
6903 }
6904 }
6905
6906 /* enumerate remaining old attachments and de-associate from the
6907 * current machine state */
6908 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
6909 it != oldAtts.end();
6910 ++it)
6911 {
6912 MediumAttachment *pAttach = *it;
6913
6914 if (pAttach->type() == DeviceType_HardDisk)
6915 {
6916 Medium* pMedium = pAttach->medium();
6917
6918 if (pMedium)
6919 {
6920 /* now de-associate from the current machine state */
6921 rc = pMedium->detachFrom(mData->mUuid);
6922 AssertComRC(rc);
6923
6924 if (aOnline)
6925 {
6926 /* unlock since not used anymore */
6927 MediumState_T state;
6928 rc = pMedium->UnlockWrite(&state);
6929 /* the disk may be alredy relocked for reading above */
6930 Assert (SUCCEEDED(rc) || state == MediumState_LockedRead);
6931 }
6932 }
6933 }
6934 }
6935
6936 /* commit the hard disk changes */
6937 mMediaData.commit();
6938
6939 if (mType == IsSessionMachine)
6940 {
6941 /* attach new data to the primary machine and reshare it */
6942 mPeer->mMediaData.attach(mMediaData);
6943 }
6944 }
6945 else
6946 {
6947 /* enumerate new attachments */
6948 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
6949 it != mMediaData->mAttachments.end();
6950 ++it)
6951 {
6952 (*it)->rollback();
6953 }
6954
6955 /** @todo convert all this Machine-based voodoo to MediumAttachment
6956 * based rollback logic. */
6957 // @todo r=dj the below totally fails if this gets called from Machine::rollback(),
6958 // which gets called if Machine::registeredInit() fails...
6959 deleteImplicitDiffs();
6960 }
6961
6962 return;
6963}
6964
6965/**
6966 * Returns true if the settings file is located in the directory named exactly
6967 * as the machine. This will be true if the machine settings structure was
6968 * created by default in #openConfigLoader().
6969 *
6970 * @param aSettingsDir if not NULL, the full machine settings file directory
6971 * name will be assigned there.
6972 *
6973 * @note Doesn't lock anything.
6974 * @note Not thread safe (must be called from this object's lock).
6975 */
6976bool Machine::isInOwnDir(Utf8Str *aSettingsDir /* = NULL */)
6977{
6978 Utf8Str settingsDir = mData->m_strConfigFileFull;
6979 settingsDir.stripFilename();
6980 char *dirName = RTPathFilename(settingsDir.c_str());
6981
6982 AssertReturn(dirName, false);
6983
6984 /* if we don't rename anything on name change, return false shorlty */
6985 if (!mUserData->mNameSync)
6986 return false;
6987
6988 if (aSettingsDir)
6989 *aSettingsDir = settingsDir;
6990
6991 return Bstr (dirName) == mUserData->mName;
6992}
6993
6994/**
6995 * @note Locks objects for reading!
6996 */
6997bool Machine::isModified()
6998{
6999 AutoCaller autoCaller(this);
7000 AssertComRCReturn (autoCaller.rc(), false);
7001
7002 AutoReadLock alock(this);
7003
7004 for (ULONG slot = 0; slot < RT_ELEMENTS (mNetworkAdapters); slot ++)
7005 if (mNetworkAdapters [slot] && mNetworkAdapters [slot]->isModified())
7006 return true;
7007
7008 for (ULONG slot = 0; slot < RT_ELEMENTS (mSerialPorts); slot ++)
7009 if (mSerialPorts [slot] && mSerialPorts [slot]->isModified())
7010 return true;
7011
7012 for (ULONG slot = 0; slot < RT_ELEMENTS (mParallelPorts); slot ++)
7013 if (mParallelPorts [slot] && mParallelPorts [slot]->isModified())
7014 return true;
7015
7016 if (!mStorageControllers.isNull())
7017 {
7018 for (StorageControllerList::const_iterator it =
7019 mStorageControllers->begin();
7020 it != mStorageControllers->end();
7021 ++it)
7022 {
7023 if ((*it)->isModified())
7024 return true;
7025 }
7026 }
7027
7028 return
7029 mUserData.isBackedUp() ||
7030 mHWData.isBackedUp() ||
7031 mMediaData.isBackedUp() ||
7032 mStorageControllers.isBackedUp() ||
7033#ifdef VBOX_WITH_VRDP
7034 (mVRDPServer && mVRDPServer->isModified()) ||
7035#endif
7036 (mAudioAdapter && mAudioAdapter->isModified()) ||
7037 (mUSBController && mUSBController->isModified()) ||
7038 (mBIOSSettings && mBIOSSettings->isModified());
7039}
7040
7041/**
7042 * Returns the logical OR of data.hasActualChanges() of this and all child
7043 * objects.
7044 *
7045 * @param aIgnoreUserData @c true to ignore changes to mUserData
7046 *
7047 * @note Locks objects for reading!
7048 */
7049bool Machine::isReallyModified (bool aIgnoreUserData /* = false */)
7050{
7051 AutoCaller autoCaller(this);
7052 AssertComRCReturn (autoCaller.rc(), false);
7053
7054 AutoReadLock alock(this);
7055
7056 for (ULONG slot = 0; slot < RT_ELEMENTS (mNetworkAdapters); slot ++)
7057 if (mNetworkAdapters [slot] && mNetworkAdapters [slot]->isReallyModified())
7058 return true;
7059
7060 for (ULONG slot = 0; slot < RT_ELEMENTS (mSerialPorts); slot ++)
7061 if (mSerialPorts [slot] && mSerialPorts [slot]->isReallyModified())
7062 return true;
7063
7064 for (ULONG slot = 0; slot < RT_ELEMENTS (mParallelPorts); slot ++)
7065 if (mParallelPorts [slot] && mParallelPorts [slot]->isReallyModified())
7066 return true;
7067
7068 if (!mStorageControllers.isBackedUp())
7069 {
7070 /* see whether any of the devices has changed its data */
7071 for (StorageControllerList::const_iterator
7072 it = mStorageControllers->begin();
7073 it != mStorageControllers->end();
7074 ++it)
7075 {
7076 if ((*it)->isReallyModified())
7077 return true;
7078 }
7079 }
7080 else
7081 {
7082 if (mStorageControllers->size() != mStorageControllers.backedUpData()->size())
7083 return true;
7084 }
7085
7086 return
7087 (!aIgnoreUserData && mUserData.hasActualChanges()) ||
7088 mHWData.hasActualChanges() ||
7089 mMediaData.hasActualChanges() ||
7090 mStorageControllers.hasActualChanges() ||
7091#ifdef VBOX_WITH_VRDP
7092 (mVRDPServer && mVRDPServer->isReallyModified()) ||
7093#endif
7094 (mAudioAdapter && mAudioAdapter->isReallyModified()) ||
7095 (mUSBController && mUSBController->isReallyModified()) ||
7096 (mBIOSSettings && mBIOSSettings->isReallyModified());
7097}
7098
7099/**
7100 * Discards all changes to machine settings.
7101 *
7102 * @param aNotify Whether to notify the direct session about changes or not.
7103 *
7104 * @note Locks objects for writing!
7105 */
7106void Machine::rollback (bool aNotify)
7107{
7108 AutoCaller autoCaller(this);
7109 AssertComRCReturn (autoCaller.rc(), (void) 0);
7110
7111 AutoWriteLock alock(this);
7112
7113 /* check for changes in own data */
7114
7115 bool sharedFoldersChanged = false, storageChanged = false;
7116
7117 if (aNotify && mHWData.isBackedUp())
7118 {
7119 if (mHWData->mSharedFolders.size() !=
7120 mHWData.backedUpData()->mSharedFolders.size())
7121 sharedFoldersChanged = true;
7122 else
7123 {
7124 for (HWData::SharedFolderList::iterator rit =
7125 mHWData->mSharedFolders.begin();
7126 rit != mHWData->mSharedFolders.end() && !sharedFoldersChanged;
7127 ++rit)
7128 {
7129 for (HWData::SharedFolderList::iterator cit =
7130 mHWData.backedUpData()->mSharedFolders.begin();
7131 cit != mHWData.backedUpData()->mSharedFolders.end();
7132 ++cit)
7133 {
7134 if ((*cit)->name() != (*rit)->name() ||
7135 (*cit)->hostPath() != (*rit)->hostPath())
7136 {
7137 sharedFoldersChanged = true;
7138 break;
7139 }
7140 }
7141 }
7142 }
7143 }
7144
7145 if (!mStorageControllers.isNull())
7146 {
7147 if (mStorageControllers.isBackedUp())
7148 {
7149 /* unitialize all new devices (absent in the backed up list). */
7150 StorageControllerList::const_iterator it = mStorageControllers->begin();
7151 StorageControllerList *backedList = mStorageControllers.backedUpData();
7152 while (it != mStorageControllers->end())
7153 {
7154 if (std::find (backedList->begin(), backedList->end(), *it ) ==
7155 backedList->end())
7156 {
7157 (*it)->uninit();
7158 }
7159 ++it;
7160 }
7161
7162 /* restore the list */
7163 mStorageControllers.rollback();
7164 }
7165
7166 /* rollback any changes to devices after restoring the list */
7167 StorageControllerList::const_iterator it = mStorageControllers->begin();
7168 while (it != mStorageControllers->end())
7169 {
7170 if ((*it)->isModified())
7171 (*it)->rollback();
7172
7173 ++it;
7174 }
7175 }
7176
7177 mUserData.rollback();
7178
7179 mHWData.rollback();
7180
7181 if (mMediaData.isBackedUp())
7182 fixupMedia(false /* aCommit */);
7183
7184 /* check for changes in child objects */
7185
7186 bool vrdpChanged = false, usbChanged = false;
7187
7188 ComPtr<INetworkAdapter> networkAdapters [RT_ELEMENTS (mNetworkAdapters)];
7189 ComPtr<ISerialPort> serialPorts [RT_ELEMENTS (mSerialPorts)];
7190 ComPtr<IParallelPort> parallelPorts [RT_ELEMENTS (mParallelPorts)];
7191
7192 if (mBIOSSettings)
7193 mBIOSSettings->rollback();
7194
7195#ifdef VBOX_WITH_VRDP
7196 if (mVRDPServer)
7197 vrdpChanged = mVRDPServer->rollback();
7198#endif
7199
7200 if (mAudioAdapter)
7201 mAudioAdapter->rollback();
7202
7203 if (mUSBController)
7204 usbChanged = mUSBController->rollback();
7205
7206 for (ULONG slot = 0; slot < RT_ELEMENTS (mNetworkAdapters); slot ++)
7207 if (mNetworkAdapters [slot])
7208 if (mNetworkAdapters [slot]->rollback())
7209 networkAdapters [slot] = mNetworkAdapters [slot];
7210
7211 for (ULONG slot = 0; slot < RT_ELEMENTS (mSerialPorts); slot ++)
7212 if (mSerialPorts [slot])
7213 if (mSerialPorts [slot]->rollback())
7214 serialPorts [slot] = mSerialPorts [slot];
7215
7216 for (ULONG slot = 0; slot < RT_ELEMENTS (mParallelPorts); slot ++)
7217 if (mParallelPorts [slot])
7218 if (mParallelPorts [slot]->rollback())
7219 parallelPorts [slot] = mParallelPorts [slot];
7220
7221 if (aNotify)
7222 {
7223 /* inform the direct session about changes */
7224
7225 ComObjPtr<Machine> that = this;
7226 alock.leave();
7227
7228 if (sharedFoldersChanged)
7229 that->onSharedFolderChange();
7230
7231 if (vrdpChanged)
7232 that->onVRDPServerChange();
7233 if (usbChanged)
7234 that->onUSBControllerChange();
7235
7236 for (ULONG slot = 0; slot < RT_ELEMENTS (networkAdapters); slot ++)
7237 if (networkAdapters [slot])
7238 that->onNetworkAdapterChange (networkAdapters [slot], FALSE);
7239 for (ULONG slot = 0; slot < RT_ELEMENTS (serialPorts); slot ++)
7240 if (serialPorts [slot])
7241 that->onSerialPortChange (serialPorts [slot]);
7242 for (ULONG slot = 0; slot < RT_ELEMENTS (parallelPorts); slot ++)
7243 if (parallelPorts [slot])
7244 that->onParallelPortChange (parallelPorts [slot]);
7245
7246 if (storageChanged)
7247 that->onStorageControllerChange();
7248 }
7249}
7250
7251/**
7252 * Commits all the changes to machine settings.
7253 *
7254 * Note that this operation is supposed to never fail.
7255 *
7256 * @note Locks this object and children for writing.
7257 */
7258void Machine::commit()
7259{
7260 AutoCaller autoCaller(this);
7261 AssertComRCReturnVoid (autoCaller.rc());
7262
7263 AutoCaller peerCaller (mPeer);
7264 AssertComRCReturnVoid (peerCaller.rc());
7265
7266 AutoMultiWriteLock2 alock (mPeer, this);
7267
7268 /*
7269 * use safe commit to ensure Snapshot machines (that share mUserData)
7270 * will still refer to a valid memory location
7271 */
7272 mUserData.commitCopy();
7273
7274 mHWData.commit();
7275
7276 if (mMediaData.isBackedUp())
7277 fixupMedia(true /* aCommit */);
7278
7279 mBIOSSettings->commit();
7280#ifdef VBOX_WITH_VRDP
7281 mVRDPServer->commit();
7282#endif
7283 mAudioAdapter->commit();
7284 mUSBController->commit();
7285
7286 for (ULONG slot = 0; slot < RT_ELEMENTS (mNetworkAdapters); slot ++)
7287 mNetworkAdapters [slot]->commit();
7288 for (ULONG slot = 0; slot < RT_ELEMENTS (mSerialPorts); slot ++)
7289 mSerialPorts [slot]->commit();
7290 for (ULONG slot = 0; slot < RT_ELEMENTS (mParallelPorts); slot ++)
7291 mParallelPorts [slot]->commit();
7292
7293 bool commitStorageControllers = false;
7294
7295 if (mStorageControllers.isBackedUp())
7296 {
7297 mStorageControllers.commit();
7298
7299 if (mPeer)
7300 {
7301 AutoWriteLock peerlock (mPeer);
7302
7303 /* Commit all changes to new controllers (this will reshare data with
7304 * peers for thos who have peers) */
7305 StorageControllerList *newList = new StorageControllerList();
7306 StorageControllerList::const_iterator it = mStorageControllers->begin();
7307 while (it != mStorageControllers->end())
7308 {
7309 (*it)->commit();
7310
7311 /* look if this controller has a peer device */
7312 ComObjPtr<StorageController> peer = (*it)->peer();
7313 if (!peer)
7314 {
7315 /* no peer means the device is a newly created one;
7316 * create a peer owning data this device share it with */
7317 peer.createObject();
7318 peer->init (mPeer, *it, true /* aReshare */);
7319 }
7320 else
7321 {
7322 /* remove peer from the old list */
7323 mPeer->mStorageControllers->remove (peer);
7324 }
7325 /* and add it to the new list */
7326 newList->push_back(peer);
7327
7328 ++it;
7329 }
7330
7331 /* uninit old peer's controllers that are left */
7332 it = mPeer->mStorageControllers->begin();
7333 while (it != mPeer->mStorageControllers->end())
7334 {
7335 (*it)->uninit();
7336 ++it;
7337 }
7338
7339 /* attach new list of controllers to our peer */
7340 mPeer->mStorageControllers.attach (newList);
7341 }
7342 else
7343 {
7344 /* we have no peer (our parent is the newly created machine);
7345 * just commit changes to devices */
7346 commitStorageControllers = true;
7347 }
7348 }
7349 else
7350 {
7351 /* the list of controllers itself is not changed,
7352 * just commit changes to controllers themselves */
7353 commitStorageControllers = true;
7354 }
7355
7356 if (commitStorageControllers)
7357 {
7358 StorageControllerList::const_iterator it = mStorageControllers->begin();
7359 while (it != mStorageControllers->end())
7360 {
7361 (*it)->commit();
7362 ++it;
7363 }
7364 }
7365
7366 if (mType == IsSessionMachine)
7367 {
7368 /* attach new data to the primary machine and reshare it */
7369 mPeer->mUserData.attach (mUserData);
7370 mPeer->mHWData.attach (mHWData);
7371 /* mMediaData is reshared by fixupMedia */
7372 // mPeer->mMediaData.attach(mMediaData);
7373 Assert(mPeer->mMediaData.data() == mMediaData.data());
7374 }
7375}
7376
7377/**
7378 * Copies all the hardware data from the given machine.
7379 *
7380 * Currently, only called when the VM is being restored from a snapshot. In
7381 * particular, this implies that the VM is not running during this method's
7382 * call.
7383 *
7384 * @note This method must be called from under this object's lock.
7385 *
7386 * @note This method doesn't call #commit(), so all data remains backed up and
7387 * unsaved.
7388 */
7389void Machine::copyFrom (Machine *aThat)
7390{
7391 AssertReturnVoid (mType == IsMachine || mType == IsSessionMachine);
7392 AssertReturnVoid (aThat->mType == IsSnapshotMachine);
7393
7394 AssertReturnVoid (!Global::IsOnline (mData->mMachineState));
7395
7396 mHWData.assignCopy (aThat->mHWData);
7397
7398 // create copies of all shared folders (mHWData after attiching a copy
7399 // contains just references to original objects)
7400 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
7401 it != mHWData->mSharedFolders.end();
7402 ++it)
7403 {
7404 ComObjPtr<SharedFolder> folder;
7405 folder.createObject();
7406 HRESULT rc = folder->initCopy (machine(), *it);
7407 AssertComRC (rc);
7408 *it = folder;
7409 }
7410
7411 mBIOSSettings->copyFrom (aThat->mBIOSSettings);
7412#ifdef VBOX_WITH_VRDP
7413 mVRDPServer->copyFrom (aThat->mVRDPServer);
7414#endif
7415 mAudioAdapter->copyFrom (aThat->mAudioAdapter);
7416 mUSBController->copyFrom (aThat->mUSBController);
7417
7418 /* create private copies of all controllers */
7419 mStorageControllers.backup();
7420 mStorageControllers->clear();
7421 for (StorageControllerList::iterator it = aThat->mStorageControllers->begin();
7422 it != aThat->mStorageControllers->end();
7423 ++it)
7424 {
7425 ComObjPtr<StorageController> ctrl;
7426 ctrl.createObject();
7427 ctrl->initCopy (this, *it);
7428 mStorageControllers->push_back(ctrl);
7429 }
7430
7431 for (ULONG slot = 0; slot < RT_ELEMENTS (mNetworkAdapters); slot ++)
7432 mNetworkAdapters [slot]->copyFrom (aThat->mNetworkAdapters [slot]);
7433 for (ULONG slot = 0; slot < RT_ELEMENTS (mSerialPorts); slot ++)
7434 mSerialPorts [slot]->copyFrom (aThat->mSerialPorts [slot]);
7435 for (ULONG slot = 0; slot < RT_ELEMENTS (mParallelPorts); slot ++)
7436 mParallelPorts [slot]->copyFrom (aThat->mParallelPorts [slot]);
7437}
7438
7439#ifdef VBOX_WITH_RESOURCE_USAGE_API
7440void Machine::registerMetrics (PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
7441{
7442 pm::CollectorHAL *hal = aCollector->getHAL();
7443 /* Create sub metrics */
7444 pm::SubMetric *cpuLoadUser = new pm::SubMetric ("CPU/Load/User",
7445 "Percentage of processor time spent in user mode by VM process.");
7446 pm::SubMetric *cpuLoadKernel = new pm::SubMetric ("CPU/Load/Kernel",
7447 "Percentage of processor time spent in kernel mode by VM process.");
7448 pm::SubMetric *ramUsageUsed = new pm::SubMetric ("RAM/Usage/Used",
7449 "Size of resident portion of VM process in memory.");
7450 /* Create and register base metrics */
7451 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw (hal, aMachine, pid,
7452 cpuLoadUser, cpuLoadKernel);
7453 aCollector->registerBaseMetric (cpuLoad);
7454 pm::BaseMetric *ramUsage = new pm::MachineRamUsage (hal, aMachine, pid,
7455 ramUsageUsed);
7456 aCollector->registerBaseMetric (ramUsage);
7457
7458 aCollector->registerMetric (new pm::Metric (cpuLoad, cpuLoadUser, 0));
7459 aCollector->registerMetric (new pm::Metric (cpuLoad, cpuLoadUser,
7460 new pm::AggregateAvg()));
7461 aCollector->registerMetric (new pm::Metric (cpuLoad, cpuLoadUser,
7462 new pm::AggregateMin()));
7463 aCollector->registerMetric (new pm::Metric (cpuLoad, cpuLoadUser,
7464 new pm::AggregateMax()));
7465 aCollector->registerMetric (new pm::Metric (cpuLoad, cpuLoadKernel, 0));
7466 aCollector->registerMetric (new pm::Metric (cpuLoad, cpuLoadKernel,
7467 new pm::AggregateAvg()));
7468 aCollector->registerMetric (new pm::Metric (cpuLoad, cpuLoadKernel,
7469 new pm::AggregateMin()));
7470 aCollector->registerMetric (new pm::Metric (cpuLoad, cpuLoadKernel,
7471 new pm::AggregateMax()));
7472
7473 aCollector->registerMetric (new pm::Metric (ramUsage, ramUsageUsed, 0));
7474 aCollector->registerMetric (new pm::Metric (ramUsage, ramUsageUsed,
7475 new pm::AggregateAvg()));
7476 aCollector->registerMetric (new pm::Metric (ramUsage, ramUsageUsed,
7477 new pm::AggregateMin()));
7478 aCollector->registerMetric (new pm::Metric (ramUsage, ramUsageUsed,
7479 new pm::AggregateMax()));
7480};
7481
7482void Machine::unregisterMetrics (PerformanceCollector *aCollector, Machine *aMachine)
7483{
7484 aCollector->unregisterMetricsFor (aMachine);
7485 aCollector->unregisterBaseMetricsFor (aMachine);
7486};
7487#endif /* VBOX_WITH_RESOURCE_USAGE_API */
7488
7489
7490/////////////////////////////////////////////////////////////////////////////
7491// SessionMachine class
7492/////////////////////////////////////////////////////////////////////////////
7493
7494/** Task structure for asynchronous VM operations */
7495struct SessionMachine::Task
7496{
7497 Task (SessionMachine *m, Progress *p)
7498 : machine (m), progress (p)
7499 , state (m->mData->mMachineState) // save the current machine state
7500 , subTask (false)
7501 {}
7502
7503 void modifyLastState (MachineState_T s)
7504 {
7505 *const_cast <MachineState_T *> (&state) = s;
7506 }
7507
7508 virtual void handler() = 0;
7509
7510 ComObjPtr<SessionMachine> machine;
7511 ComObjPtr<Progress> progress;
7512 const MachineState_T state;
7513
7514 bool subTask : 1;
7515};
7516
7517/** Discard snapshot task */
7518struct SessionMachine::DiscardSnapshotTask
7519 : public SessionMachine::Task
7520{
7521 DiscardSnapshotTask(SessionMachine *m, Progress *p, Snapshot *s)
7522 : Task (m, p),
7523 snapshot (s)
7524 {}
7525
7526 DiscardSnapshotTask (const Task &task, Snapshot *s)
7527 : Task (task)
7528 , snapshot (s)
7529 {}
7530
7531 void handler()
7532 {
7533 machine->discardSnapshotHandler(*this);
7534 }
7535
7536 ComObjPtr<Snapshot> snapshot;
7537};
7538
7539/** Discard current state task */
7540struct SessionMachine::DiscardCurrentStateTask
7541 : public SessionMachine::Task
7542{
7543 DiscardCurrentStateTask(SessionMachine *m, Progress *p, bool discardCurSnapshot)
7544 : Task(m, p),
7545 discardCurrentSnapshot(discardCurSnapshot)
7546 {}
7547
7548 void handler()
7549 {
7550 machine->discardCurrentStateHandler(*this);
7551 }
7552
7553 const bool discardCurrentSnapshot;
7554};
7555
7556////////////////////////////////////////////////////////////////////////////////
7557
7558DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
7559
7560HRESULT SessionMachine::FinalConstruct()
7561{
7562 LogFlowThisFunc(("\n"));
7563
7564 /* set the proper type to indicate we're the SessionMachine instance */
7565 unconst(mType) = IsSessionMachine;
7566
7567#if defined(RT_OS_WINDOWS)
7568 mIPCSem = NULL;
7569#elif defined(RT_OS_OS2)
7570 mIPCSem = NULLHANDLE;
7571#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
7572 mIPCSem = -1;
7573#else
7574# error "Port me!"
7575#endif
7576
7577 return S_OK;
7578}
7579
7580void SessionMachine::FinalRelease()
7581{
7582 LogFlowThisFunc(("\n"));
7583
7584 uninit (Uninit::Unexpected);
7585}
7586
7587/**
7588 * @note Must be called only by Machine::openSession() from its own write lock.
7589 */
7590HRESULT SessionMachine::init (Machine *aMachine)
7591{
7592 LogFlowThisFuncEnter();
7593 LogFlowThisFunc(("mName={%ls}\n", aMachine->mUserData->mName.raw()));
7594
7595 AssertReturn(aMachine, E_INVALIDARG);
7596
7597 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
7598
7599 /* Enclose the state transition NotReady->InInit->Ready */
7600 AutoInitSpan autoInitSpan(this);
7601 AssertReturn(autoInitSpan.isOk(), E_FAIL);
7602
7603 /* create the interprocess semaphore */
7604#if defined(RT_OS_WINDOWS)
7605 mIPCSemName = aMachine->mData->m_strConfigFileFull;
7606 for (size_t i = 0; i < mIPCSemName.length(); i++)
7607 if (mIPCSemName[i] == '\\')
7608 mIPCSemName[i] = '/';
7609 mIPCSem = ::CreateMutex (NULL, FALSE, mIPCSemName);
7610 ComAssertMsgRet (mIPCSem,
7611 ("Cannot create IPC mutex '%ls', err=%d",
7612 mIPCSemName.raw(), ::GetLastError()),
7613 E_FAIL);
7614#elif defined(RT_OS_OS2)
7615 Utf8Str ipcSem = Utf8StrFmt ("\\SEM32\\VBOX\\VM\\{%RTuuid}",
7616 aMachine->mData->mUuid.raw());
7617 mIPCSemName = ipcSem;
7618 APIRET arc = ::DosCreateMutexSem ((PSZ) ipcSem.raw(), &mIPCSem, 0, FALSE);
7619 ComAssertMsgRet (arc == NO_ERROR,
7620 ("Cannot create IPC mutex '%s', arc=%ld",
7621 ipcSem.raw(), arc),
7622 E_FAIL);
7623#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
7624# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
7625# if defined(RT_OS_FREEBSD) && (HC_ARCH_BITS == 64)
7626 /** @todo Check that this still works correctly. */
7627 AssertCompileSize(key_t, 8);
7628# else
7629 AssertCompileSize(key_t, 4);
7630# endif
7631 key_t key;
7632 mIPCSem = -1;
7633 mIPCKey = "0";
7634 for (uint32_t i = 0; i < 1 << 24; i++)
7635 {
7636 key = ((uint32_t)'V' << 24) | i;
7637 int sem = ::semget (key, 1, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
7638 if (sem >= 0 || (errno != EEXIST && errno != EACCES))
7639 {
7640 mIPCSem = sem;
7641 if (sem >= 0)
7642 mIPCKey = BstrFmt ("%u", key);
7643 break;
7644 }
7645 }
7646# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
7647 Utf8Str semName = aMachine->mData->m_strConfigFileFull;
7648 char *pszSemName = NULL;
7649 RTStrUtf8ToCurrentCP (&pszSemName, semName);
7650 key_t key = ::ftok (pszSemName, 'V');
7651 RTStrFree (pszSemName);
7652
7653 mIPCSem = ::semget (key, 1, S_IRWXU | S_IRWXG | S_IRWXO | IPC_CREAT);
7654# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
7655
7656 int errnoSave = errno;
7657 if (mIPCSem < 0 && errnoSave == ENOSYS)
7658 {
7659 setError(E_FAIL,
7660 tr("Cannot create IPC semaphore. Most likely your host kernel lacks "
7661 "support for SysV IPC. Check the host kernel configuration for "
7662 "CONFIG_SYSVIPC=y"));
7663 return E_FAIL;
7664 }
7665 ComAssertMsgRet (mIPCSem >= 0, ("Cannot create IPC semaphore, errno=%d", errnoSave),
7666 E_FAIL);
7667 /* set the initial value to 1 */
7668 int rv = ::semctl (mIPCSem, 0, SETVAL, 1);
7669 ComAssertMsgRet (rv == 0, ("Cannot init IPC semaphore, errno=%d", errno),
7670 E_FAIL);
7671#else
7672# error "Port me!"
7673#endif
7674
7675 /* memorize the peer Machine */
7676 unconst(mPeer) = aMachine;
7677 /* share the parent pointer */
7678 unconst(mParent) = aMachine->mParent;
7679
7680 /* take the pointers to data to share */
7681 mData.share (aMachine->mData);
7682 mSSData.share (aMachine->mSSData);
7683
7684 mUserData.share (aMachine->mUserData);
7685 mHWData.share (aMachine->mHWData);
7686 mMediaData.share(aMachine->mMediaData);
7687
7688 mStorageControllers.allocate();
7689 for (StorageControllerList::const_iterator it = aMachine->mStorageControllers->begin();
7690 it != aMachine->mStorageControllers->end();
7691 ++it)
7692 {
7693 ComObjPtr<StorageController> ctl;
7694 ctl.createObject();
7695 ctl->init(this, *it);
7696 mStorageControllers->push_back (ctl);
7697 }
7698
7699 unconst(mBIOSSettings).createObject();
7700 mBIOSSettings->init (this, aMachine->mBIOSSettings);
7701#ifdef VBOX_WITH_VRDP
7702 /* create another VRDPServer object that will be mutable */
7703 unconst(mVRDPServer).createObject();
7704 mVRDPServer->init (this, aMachine->mVRDPServer);
7705#endif
7706 /* create another audio adapter object that will be mutable */
7707 unconst(mAudioAdapter).createObject();
7708 mAudioAdapter->init (this, aMachine->mAudioAdapter);
7709 /* create a list of serial ports that will be mutable */
7710 for (ULONG slot = 0; slot < RT_ELEMENTS (mSerialPorts); slot ++)
7711 {
7712 unconst(mSerialPorts [slot]).createObject();
7713 mSerialPorts [slot]->init (this, aMachine->mSerialPorts [slot]);
7714 }
7715 /* create a list of parallel ports that will be mutable */
7716 for (ULONG slot = 0; slot < RT_ELEMENTS (mParallelPorts); slot ++)
7717 {
7718 unconst(mParallelPorts [slot]).createObject();
7719 mParallelPorts [slot]->init (this, aMachine->mParallelPorts [slot]);
7720 }
7721 /* create another USB controller object that will be mutable */
7722 unconst(mUSBController).createObject();
7723 mUSBController->init (this, aMachine->mUSBController);
7724
7725 /* create a list of network adapters that will be mutable */
7726 for (ULONG slot = 0; slot < RT_ELEMENTS (mNetworkAdapters); slot ++)
7727 {
7728 unconst(mNetworkAdapters [slot]).createObject();
7729 mNetworkAdapters [slot]->init (this, aMachine->mNetworkAdapters [slot]);
7730 }
7731
7732 /* default is to delete saved state on Saved -> PoweredOff transition */
7733 mRemoveSavedState = true;
7734
7735 /* Confirm a successful initialization when it's the case */
7736 autoInitSpan.setSucceeded();
7737
7738 LogFlowThisFuncLeave();
7739 return S_OK;
7740}
7741
7742/**
7743 * Uninitializes this session object. If the reason is other than
7744 * Uninit::Unexpected, then this method MUST be called from #checkForDeath().
7745 *
7746 * @param aReason uninitialization reason
7747 *
7748 * @note Locks mParent + this object for writing.
7749 */
7750void SessionMachine::uninit (Uninit::Reason aReason)
7751{
7752 LogFlowThisFuncEnter();
7753 LogFlowThisFunc(("reason=%d\n", aReason));
7754
7755 /*
7756 * Strongly reference ourselves to prevent this object deletion after
7757 * mData->mSession.mMachine.setNull() below (which can release the last
7758 * reference and call the destructor). Important: this must be done before
7759 * accessing any members (and before AutoUninitSpan that does it as well).
7760 * This self reference will be released as the very last step on return.
7761 */
7762 ComObjPtr<SessionMachine> selfRef = this;
7763
7764 /* Enclose the state transition Ready->InUninit->NotReady */
7765 AutoUninitSpan autoUninitSpan(this);
7766 if (autoUninitSpan.uninitDone())
7767 {
7768 LogFlowThisFunc(("Already uninitialized\n"));
7769 LogFlowThisFuncLeave();
7770 return;
7771 }
7772
7773 if (autoUninitSpan.initFailed())
7774 {
7775 /* We've been called by init() because it's failed. It's not really
7776 * necessary (nor it's safe) to perform the regular uninit sequense
7777 * below, the following is enough.
7778 */
7779 LogFlowThisFunc(("Initialization failed.\n"));
7780#if defined(RT_OS_WINDOWS)
7781 if (mIPCSem)
7782 ::CloseHandle (mIPCSem);
7783 mIPCSem = NULL;
7784#elif defined(RT_OS_OS2)
7785 if (mIPCSem != NULLHANDLE)
7786 ::DosCloseMutexSem (mIPCSem);
7787 mIPCSem = NULLHANDLE;
7788#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
7789 if (mIPCSem >= 0)
7790 ::semctl (mIPCSem, 0, IPC_RMID);
7791 mIPCSem = -1;
7792# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
7793 mIPCKey = "0";
7794# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
7795#else
7796# error "Port me!"
7797#endif
7798 uninitDataAndChildObjects();
7799 mData.free();
7800 unconst(mParent).setNull();
7801 unconst(mPeer).setNull();
7802 LogFlowThisFuncLeave();
7803 return;
7804 }
7805
7806 /* We need to lock this object in uninit() because the lock is shared
7807 * with mPeer (as well as data we modify below). mParent->addProcessToReap()
7808 * and others need mParent lock. */
7809 AutoMultiWriteLock2 alock (mParent, this);
7810
7811#ifdef VBOX_WITH_RESOURCE_USAGE_API
7812 unregisterMetrics (mParent->performanceCollector(), mPeer);
7813#endif /* VBOX_WITH_RESOURCE_USAGE_API */
7814
7815 MachineState_T lastState = mData->mMachineState;
7816 NOREF(lastState);
7817
7818 if (aReason == Uninit::Abnormal)
7819 {
7820 LogWarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n",
7821 Global::IsOnlineOrTransient (lastState)));
7822
7823 /* reset the state to Aborted */
7824 if (mData->mMachineState != MachineState_Aborted)
7825 setMachineState (MachineState_Aborted);
7826 }
7827
7828 if (isModified())
7829 {
7830 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
7831 rollback (false /* aNotify */);
7832 }
7833
7834 Assert (!mSnapshotData.mStateFilePath || !mSnapshotData.mSnapshot);
7835 if (mSnapshotData.mStateFilePath)
7836 {
7837 LogWarningThisFunc(("canceling failed save state request!\n"));
7838 endSavingState (FALSE /* aSuccess */);
7839 }
7840 else if (!mSnapshotData.mSnapshot.isNull())
7841 {
7842 LogWarningThisFunc(("canceling untaken snapshot!\n"));
7843 endTakingSnapshot (FALSE /* aSuccess */);
7844 }
7845
7846#ifdef VBOX_WITH_USB
7847 /* release all captured USB devices */
7848 if (aReason == Uninit::Abnormal && Global::IsOnline (lastState))
7849 {
7850 /* Console::captureUSBDevices() is called in the VM process only after
7851 * setting the machine state to Starting or Restoring.
7852 * Console::detachAllUSBDevices() will be called upon successful
7853 * termination. So, we need to release USB devices only if there was
7854 * an abnormal termination of a running VM.
7855 *
7856 * This is identical to SessionMachine::DetachAllUSBDevices except
7857 * for the aAbnormal argument. */
7858 HRESULT rc = mUSBController->notifyProxy (false /* aInsertFilters */);
7859 AssertComRC(rc);
7860 NOREF (rc);
7861
7862 USBProxyService *service = mParent->host()->usbProxyService();
7863 if (service)
7864 service->detachAllDevicesFromVM (this, true /* aDone */, true /* aAbnormal */);
7865 }
7866#endif /* VBOX_WITH_USB */
7867
7868 if (!mData->mSession.mType.isNull())
7869 {
7870 /* mType is not null when this machine's process has been started by
7871 * VirtualBox::OpenRemoteSession(), therefore it is our child. We
7872 * need to queue the PID to reap the process (and avoid zombies on
7873 * Linux). */
7874 Assert (mData->mSession.mPid != NIL_RTPROCESS);
7875 mParent->addProcessToReap (mData->mSession.mPid);
7876 }
7877
7878 mData->mSession.mPid = NIL_RTPROCESS;
7879
7880 if (aReason == Uninit::Unexpected)
7881 {
7882 /* Uninitialization didn't come from #checkForDeath(), so tell the
7883 * client watcher thread to update the set of machines that have open
7884 * sessions. */
7885 mParent->updateClientWatcher();
7886 }
7887
7888 /* uninitialize all remote controls */
7889 if (mData->mSession.mRemoteControls.size())
7890 {
7891 LogFlowThisFunc(("Closing remote sessions (%d):\n",
7892 mData->mSession.mRemoteControls.size()));
7893
7894 Data::Session::RemoteControlList::iterator it =
7895 mData->mSession.mRemoteControls.begin();
7896 while (it != mData->mSession.mRemoteControls.end())
7897 {
7898 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
7899 HRESULT rc = (*it)->Uninitialize();
7900 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
7901 if (FAILED (rc))
7902 LogWarningThisFunc(("Forgot to close the remote session?\n"));
7903 ++it;
7904 }
7905 mData->mSession.mRemoteControls.clear();
7906 }
7907
7908 /*
7909 * An expected uninitialization can come only from #checkForDeath().
7910 * Otherwise it means that something's got really wrong (for examlple,
7911 * the Session implementation has released the VirtualBox reference
7912 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
7913 * etc). However, it's also possible, that the client releases the IPC
7914 * semaphore correctly (i.e. before it releases the VirtualBox reference),
7915 * but the VirtualBox release event comes first to the server process.
7916 * This case is practically possible, so we should not assert on an
7917 * unexpected uninit, just log a warning.
7918 */
7919
7920 if ((aReason == Uninit::Unexpected))
7921 LogWarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
7922
7923 if (aReason != Uninit::Normal)
7924 {
7925 mData->mSession.mDirectControl.setNull();
7926 }
7927 else
7928 {
7929 /* this must be null here (see #OnSessionEnd()) */
7930 Assert (mData->mSession.mDirectControl.isNull());
7931 Assert (mData->mSession.mState == SessionState_Closing);
7932 Assert (!mData->mSession.mProgress.isNull());
7933
7934 mData->mSession.mProgress->notifyComplete (S_OK);
7935 mData->mSession.mProgress.setNull();
7936 }
7937
7938 /* remove the association between the peer machine and this session machine */
7939 Assert (mData->mSession.mMachine == this ||
7940 aReason == Uninit::Unexpected);
7941
7942 /* reset the rest of session data */
7943 mData->mSession.mMachine.setNull();
7944 mData->mSession.mState = SessionState_Closed;
7945 mData->mSession.mType.setNull();
7946
7947 /* close the interprocess semaphore before leaving the shared lock */
7948#if defined(RT_OS_WINDOWS)
7949 if (mIPCSem)
7950 ::CloseHandle (mIPCSem);
7951 mIPCSem = NULL;
7952#elif defined(RT_OS_OS2)
7953 if (mIPCSem != NULLHANDLE)
7954 ::DosCloseMutexSem (mIPCSem);
7955 mIPCSem = NULLHANDLE;
7956#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
7957 if (mIPCSem >= 0)
7958 ::semctl (mIPCSem, 0, IPC_RMID);
7959 mIPCSem = -1;
7960# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
7961 mIPCKey = "0";
7962# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
7963#else
7964# error "Port me!"
7965#endif
7966
7967 /* fire an event */
7968 mParent->onSessionStateChange (mData->mUuid, SessionState_Closed);
7969
7970 uninitDataAndChildObjects();
7971
7972 /* free the essential data structure last */
7973 mData.free();
7974
7975 /* leave the shared lock before setting the below two to NULL */
7976 alock.leave();
7977
7978 unconst(mParent).setNull();
7979 unconst(mPeer).setNull();
7980
7981 LogFlowThisFuncLeave();
7982}
7983
7984// util::Lockable interface
7985////////////////////////////////////////////////////////////////////////////////
7986
7987/**
7988 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
7989 * with the primary Machine instance (mPeer).
7990 */
7991RWLockHandle *SessionMachine::lockHandle() const
7992{
7993 AssertReturn(!mPeer.isNull(), NULL);
7994 return mPeer->lockHandle();
7995}
7996
7997// IInternalMachineControl methods
7998////////////////////////////////////////////////////////////////////////////////
7999
8000/**
8001 * @note Locks this object for writing.
8002 */
8003STDMETHODIMP SessionMachine::SetRemoveSavedState(BOOL aRemove)
8004{
8005 AutoCaller autoCaller(this);
8006 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8007
8008 AutoWriteLock alock(this);
8009
8010 mRemoveSavedState = aRemove;
8011
8012 return S_OK;
8013}
8014
8015/**
8016 * @note Locks the same as #setMachineState() does.
8017 */
8018STDMETHODIMP SessionMachine::UpdateState (MachineState_T aMachineState)
8019{
8020 return setMachineState (aMachineState);
8021}
8022
8023/**
8024 * @note Locks this object for reading.
8025 */
8026STDMETHODIMP SessionMachine::GetIPCId (BSTR *aId)
8027{
8028 AutoCaller autoCaller(this);
8029 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8030
8031 AutoReadLock alock(this);
8032
8033#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
8034 mIPCSemName.cloneTo(aId);
8035 return S_OK;
8036#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
8037# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
8038 mIPCKey.cloneTo(aId);
8039# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
8040 mData->m_strConfigFileFull.cloneTo(aId);
8041# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
8042 return S_OK;
8043#else
8044# error "Port me!"
8045#endif
8046}
8047
8048/**
8049 * Goes through the USB filters of the given machine to see if the given
8050 * device matches any filter or not.
8051 *
8052 * @note Locks the same as USBController::hasMatchingFilter() does.
8053 */
8054STDMETHODIMP SessionMachine::RunUSBDeviceFilters (IUSBDevice *aUSBDevice,
8055 BOOL *aMatched,
8056 ULONG *aMaskedIfs)
8057{
8058 LogFlowThisFunc(("\n"));
8059
8060 CheckComArgNotNull (aUSBDevice);
8061 CheckComArgOutPointerValid(aMatched);
8062
8063 AutoCaller autoCaller(this);
8064 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8065
8066#ifdef VBOX_WITH_USB
8067 *aMatched = mUSBController->hasMatchingFilter (aUSBDevice, aMaskedIfs);
8068#else
8069 NOREF(aUSBDevice);
8070 NOREF(aMaskedIfs);
8071 *aMatched = FALSE;
8072#endif
8073
8074 return S_OK;
8075}
8076
8077/**
8078 * @note Locks the same as Host::captureUSBDevice() does.
8079 */
8080STDMETHODIMP SessionMachine::CaptureUSBDevice (IN_BSTR aId)
8081{
8082 LogFlowThisFunc(("\n"));
8083
8084 AutoCaller autoCaller(this);
8085 AssertComRCReturnRC(autoCaller.rc());
8086
8087#ifdef VBOX_WITH_USB
8088 /* if captureDeviceForVM() fails, it must have set extended error info */
8089 MultiResult rc = mParent->host()->checkUSBProxyService();
8090 CheckComRCReturnRC(rc);
8091
8092 USBProxyService *service = mParent->host()->usbProxyService();
8093 AssertReturn(service, E_FAIL);
8094 return service->captureDeviceForVM (this, Guid(aId));
8095#else
8096 NOREF(aId);
8097 return E_NOTIMPL;
8098#endif
8099}
8100
8101/**
8102 * @note Locks the same as Host::detachUSBDevice() does.
8103 */
8104STDMETHODIMP SessionMachine::DetachUSBDevice (IN_BSTR aId, BOOL aDone)
8105{
8106 LogFlowThisFunc(("\n"));
8107
8108 AutoCaller autoCaller(this);
8109 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8110
8111#ifdef VBOX_WITH_USB
8112 USBProxyService *service = mParent->host()->usbProxyService();
8113 AssertReturn(service, E_FAIL);
8114 return service->detachDeviceFromVM (this, Guid(aId), !!aDone);
8115#else
8116 NOREF(aId);
8117 NOREF(aDone);
8118 return E_NOTIMPL;
8119#endif
8120}
8121
8122/**
8123 * Inserts all machine filters to the USB proxy service and then calls
8124 * Host::autoCaptureUSBDevices().
8125 *
8126 * Called by Console from the VM process upon VM startup.
8127 *
8128 * @note Locks what called methods lock.
8129 */
8130STDMETHODIMP SessionMachine::AutoCaptureUSBDevices()
8131{
8132 LogFlowThisFunc(("\n"));
8133
8134 AutoCaller autoCaller(this);
8135 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8136
8137#ifdef VBOX_WITH_USB
8138 HRESULT rc = mUSBController->notifyProxy (true /* aInsertFilters */);
8139 AssertComRC(rc);
8140 NOREF (rc);
8141
8142 USBProxyService *service = mParent->host()->usbProxyService();
8143 AssertReturn(service, E_FAIL);
8144 return service->autoCaptureDevicesForVM (this);
8145#else
8146 return S_OK;
8147#endif
8148}
8149
8150/**
8151 * Removes all machine filters from the USB proxy service and then calls
8152 * Host::detachAllUSBDevices().
8153 *
8154 * Called by Console from the VM process upon normal VM termination or by
8155 * SessionMachine::uninit() upon abnormal VM termination (from under the
8156 * Machine/SessionMachine lock).
8157 *
8158 * @note Locks what called methods lock.
8159 */
8160STDMETHODIMP SessionMachine::DetachAllUSBDevices (BOOL aDone)
8161{
8162 LogFlowThisFunc(("\n"));
8163
8164 AutoCaller autoCaller(this);
8165 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8166
8167#ifdef VBOX_WITH_USB
8168 HRESULT rc = mUSBController->notifyProxy (false /* aInsertFilters */);
8169 AssertComRC(rc);
8170 NOREF (rc);
8171
8172 USBProxyService *service = mParent->host()->usbProxyService();
8173 AssertReturn(service, E_FAIL);
8174 return service->detachAllDevicesFromVM (this, !!aDone, false /* aAbnormal */);
8175#else
8176 NOREF(aDone);
8177 return S_OK;
8178#endif
8179}
8180
8181/**
8182 * @note Locks this object for writing.
8183 */
8184STDMETHODIMP SessionMachine::OnSessionEnd (ISession *aSession,
8185 IProgress **aProgress)
8186{
8187 LogFlowThisFuncEnter();
8188
8189 AssertReturn(aSession, E_INVALIDARG);
8190 AssertReturn(aProgress, E_INVALIDARG);
8191
8192 AutoCaller autoCaller(this);
8193
8194 LogFlowThisFunc(("state=%d\n", autoCaller.state()));
8195 /*
8196 * We don't assert below because it might happen that a non-direct session
8197 * informs us it is closed right after we've been uninitialized -- it's ok.
8198 */
8199 CheckComRCReturnRC(autoCaller.rc());
8200
8201 /* get IInternalSessionControl interface */
8202 ComPtr<IInternalSessionControl> control (aSession);
8203
8204 ComAssertRet (!control.isNull(), E_INVALIDARG);
8205
8206 AutoWriteLock alock(this);
8207
8208 if (control.equalsTo (mData->mSession.mDirectControl))
8209 {
8210 ComAssertRet (aProgress, E_POINTER);
8211
8212 /* The direct session is being normally closed by the client process
8213 * ----------------------------------------------------------------- */
8214
8215 /* go to the closing state (essential for all open*Session() calls and
8216 * for #checkForDeath()) */
8217 Assert (mData->mSession.mState == SessionState_Open);
8218 mData->mSession.mState = SessionState_Closing;
8219
8220 /* set direct control to NULL to release the remote instance */
8221 mData->mSession.mDirectControl.setNull();
8222 LogFlowThisFunc(("Direct control is set to NULL\n"));
8223
8224 /* Create the progress object the client will use to wait until
8225 * #checkForDeath() is called to uninitialize this session object after
8226 * it releases the IPC semaphore. */
8227 ComObjPtr<Progress> progress;
8228 progress.createObject();
8229 progress->init (mParent, static_cast <IMachine *> (mPeer),
8230 Bstr (tr ("Closing session")), FALSE /* aCancelable */);
8231 progress.queryInterfaceTo(aProgress);
8232 mData->mSession.mProgress = progress;
8233 }
8234 else
8235 {
8236 /* the remote session is being normally closed */
8237 Data::Session::RemoteControlList::iterator it =
8238 mData->mSession.mRemoteControls.begin();
8239 while (it != mData->mSession.mRemoteControls.end())
8240 {
8241 if (control.equalsTo (*it))
8242 break;
8243 ++it;
8244 }
8245 BOOL found = it != mData->mSession.mRemoteControls.end();
8246 ComAssertMsgRet (found, ("The session is not found in the session list!"),
8247 E_INVALIDARG);
8248 mData->mSession.mRemoteControls.remove (*it);
8249 }
8250
8251 LogFlowThisFuncLeave();
8252 return S_OK;
8253}
8254
8255/**
8256 * @note Locks this object for writing.
8257 */
8258STDMETHODIMP SessionMachine::BeginSavingState (IProgress *aProgress, BSTR *aStateFilePath)
8259{
8260 LogFlowThisFuncEnter();
8261
8262 AssertReturn(aProgress, E_INVALIDARG);
8263 AssertReturn(aStateFilePath, E_POINTER);
8264
8265 AutoCaller autoCaller(this);
8266 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8267
8268 AutoWriteLock alock(this);
8269
8270 AssertReturn(mData->mMachineState == MachineState_Paused &&
8271 mSnapshotData.mLastState == MachineState_Null &&
8272 mSnapshotData.mProgressId.isEmpty() &&
8273 mSnapshotData.mStateFilePath.isNull(),
8274 E_FAIL);
8275
8276 /* memorize the progress ID and add it to the global collection */
8277 Bstr progressId;
8278 HRESULT rc = aProgress->COMGETTER(Id) (progressId.asOutParam());
8279 AssertComRCReturn (rc, rc);
8280 rc = mParent->addProgress (aProgress);
8281 AssertComRCReturn (rc, rc);
8282
8283 Bstr stateFilePath;
8284 /* stateFilePath is null when the machine is not running */
8285 if (mData->mMachineState == MachineState_Paused)
8286 {
8287 stateFilePath = Utf8StrFmt ("%ls%c{%RTuuid}.sav",
8288 mUserData->mSnapshotFolderFull.raw(),
8289 RTPATH_DELIMITER, mData->mUuid.raw());
8290 }
8291
8292 /* fill in the snapshot data */
8293 mSnapshotData.mLastState = mData->mMachineState;
8294 mSnapshotData.mProgressId = Guid(progressId);
8295 mSnapshotData.mStateFilePath = stateFilePath;
8296
8297 /* set the state to Saving (this is expected by Console::SaveState()) */
8298 setMachineState (MachineState_Saving);
8299
8300 stateFilePath.cloneTo(aStateFilePath);
8301
8302 return S_OK;
8303}
8304
8305/**
8306 * @note Locks mParent + this object for writing.
8307 */
8308STDMETHODIMP SessionMachine::EndSavingState (BOOL aSuccess)
8309{
8310 LogFlowThisFunc(("\n"));
8311
8312 AutoCaller autoCaller(this);
8313 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8314
8315 /* endSavingState() need mParent lock */
8316 AutoMultiWriteLock2 alock (mParent, this);
8317
8318 AssertReturn(mData->mMachineState == MachineState_Saving &&
8319 mSnapshotData.mLastState != MachineState_Null &&
8320 !mSnapshotData.mProgressId.isEmpty() &&
8321 !mSnapshotData.mStateFilePath.isNull(),
8322 E_FAIL);
8323
8324 /*
8325 * on success, set the state to Saved;
8326 * on failure, set the state to the state we had when BeginSavingState() was
8327 * called (this is expected by Console::SaveState() and
8328 * Console::saveStateThread())
8329 */
8330 if (aSuccess)
8331 setMachineState (MachineState_Saved);
8332 else
8333 setMachineState (mSnapshotData.mLastState);
8334
8335 return endSavingState (aSuccess);
8336}
8337
8338/**
8339 * @note Locks this object for writing.
8340 */
8341STDMETHODIMP SessionMachine::AdoptSavedState (IN_BSTR aSavedStateFile)
8342{
8343 LogFlowThisFunc(("\n"));
8344
8345 AssertReturn(aSavedStateFile, E_INVALIDARG);
8346
8347 AutoCaller autoCaller(this);
8348 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8349
8350 AutoWriteLock alock(this);
8351
8352 AssertReturn(mData->mMachineState == MachineState_PoweredOff ||
8353 mData->mMachineState == MachineState_Aborted,
8354 E_FAIL);
8355
8356 Utf8Str stateFilePathFull = aSavedStateFile;
8357 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
8358 if (RT_FAILURE(vrc))
8359 return setError(VBOX_E_FILE_ERROR,
8360 tr("Invalid saved state file path '%ls' (%Rrc)"),
8361 aSavedStateFile,
8362 vrc);
8363
8364 mSSData->mStateFilePath = stateFilePathFull;
8365
8366 /* The below setMachineState() will detect the state transition and will
8367 * update the settings file */
8368
8369 return setMachineState (MachineState_Saved);
8370}
8371
8372/**
8373 * @note Locks mParent + this object for writing.
8374 */
8375STDMETHODIMP SessionMachine::BeginTakingSnapshot(IConsole *aInitiator,
8376 IN_BSTR aName,
8377 IN_BSTR aDescription,
8378 IProgress *aConsoleProgress,
8379 BOOL fTakingSnapshotOnline,
8380 BSTR *aStateFilePath)
8381{
8382 LogFlowThisFuncEnter();
8383
8384 AssertReturn(aInitiator && aName, E_INVALIDARG);
8385 AssertReturn(aStateFilePath, E_POINTER);
8386
8387 LogFlowThisFunc(("aName='%ls'\n", aName));
8388
8389 AutoCaller autoCaller(this);
8390 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8391
8392 /* saveSettings() needs mParent lock */
8393 AutoMultiWriteLock2 alock(mParent, this);
8394
8395 AssertReturn( !Global::IsOnlineOrTransient(mData->mMachineState)
8396 || mData->mMachineState == MachineState_Running
8397 || mData->mMachineState == MachineState_Paused, E_FAIL);
8398 AssertReturn(mSnapshotData.mLastState == MachineState_Null, E_FAIL);
8399 AssertReturn(mSnapshotData.mSnapshot.isNull(), E_FAIL);
8400
8401 if ( !fTakingSnapshotOnline
8402 && mData->mMachineState != MachineState_Saved
8403 )
8404 {
8405 /* save all current settings to ensure current changes are committed and
8406 * hard disks are fixed up */
8407 HRESULT rc = saveSettings();
8408 CheckComRCReturnRC(rc);
8409 }
8410
8411 /* create an ID for the snapshot */
8412 Guid snapshotId;
8413 snapshotId.create();
8414
8415 Utf8Str strStateFilePath;
8416 /* stateFilePath is null when the machine is not online nor saved */
8417 if ( fTakingSnapshotOnline
8418 || mData->mMachineState == MachineState_Saved)
8419 {
8420 strStateFilePath = Utf8StrFmt("%ls%c{%RTuuid}.sav",
8421 mUserData->mSnapshotFolderFull.raw(),
8422 RTPATH_DELIMITER,
8423 snapshotId.ptr());
8424 /* ensure the directory for the saved state file exists */
8425 HRESULT rc = VirtualBox::ensureFilePathExists(strStateFilePath);
8426 CheckComRCReturnRC(rc);
8427 }
8428
8429 /* create a snapshot machine object */
8430 ComObjPtr<SnapshotMachine> snapshotMachine;
8431 snapshotMachine.createObject();
8432 HRESULT rc = snapshotMachine->init(this, snapshotId, strStateFilePath);
8433 AssertComRCReturn(rc, rc);
8434
8435 /* create a snapshot object */
8436 RTTIMESPEC time;
8437 ComObjPtr<Snapshot> pSnapshot;
8438 pSnapshot.createObject();
8439 rc = pSnapshot->init(mParent,
8440 snapshotId,
8441 aName,
8442 aDescription,
8443 *RTTimeNow(&time),
8444 snapshotMachine,
8445 mData->mCurrentSnapshot);
8446 AssertComRCReturnRC(rc);
8447
8448 /* fill in the snapshot data */
8449 mSnapshotData.mLastState = mData->mMachineState;
8450 mSnapshotData.mSnapshot = pSnapshot;
8451
8452 try
8453 {
8454 LogFlowThisFunc(("Creating differencing hard disks (online=%d)...\n",
8455 fTakingSnapshotOnline));
8456
8457 // backup the media data so we can recover if things goes wrong along the day;
8458 // the matching commit() is in fixupMedia() during endSnapshot()
8459 mMediaData.backup();
8460
8461 /* set the state to Saving (this is expected by Console::TakeSnapshot()) */
8462 setMachineState(MachineState_Saving);
8463
8464 /* create new differencing hard disks and attach them to this machine */
8465 rc = createImplicitDiffs(mUserData->mSnapshotFolderFull,
8466 aConsoleProgress,
8467 1, // operation weight; must be the same as in Console::TakeSnapshot()
8468 fTakingSnapshotOnline);
8469
8470 if (SUCCEEDED(rc) && mSnapshotData.mLastState == MachineState_Saved)
8471 {
8472 Utf8Str stateFrom = mSSData->mStateFilePath;
8473 Utf8Str stateTo = mSnapshotData.mSnapshot->stateFilePath();
8474
8475 LogFlowThisFunc(("Copying the execution state from '%s' to '%s'...\n",
8476 stateFrom.raw(), stateTo.raw()));
8477
8478 aConsoleProgress->SetNextOperation(Bstr(tr("Copying the execution state")),
8479 1); // weight
8480
8481 /* Leave the lock before a lengthy operation (mMachineState is
8482 * MachineState_Saving here) */
8483 alock.leave();
8484
8485 /* copy the state file */
8486 int vrc = RTFileCopyEx(stateFrom.c_str(),
8487 stateTo.c_str(),
8488 0,
8489 progressCallback,
8490 aConsoleProgress);
8491 alock.enter();
8492
8493 if (RT_FAILURE(vrc))
8494 throw setError(E_FAIL,
8495 tr("Could not copy the state file '%s' to '%s' (%Rrc)"),
8496 stateFrom.raw(),
8497 stateTo.raw(),
8498 vrc);
8499 }
8500 }
8501 catch (HRESULT rc)
8502 {
8503 pSnapshot->uninit();
8504 pSnapshot.setNull();
8505 }
8506
8507 if (fTakingSnapshotOnline)
8508 strStateFilePath.cloneTo(aStateFilePath);
8509 else
8510 *aStateFilePath = NULL;
8511
8512 LogFlowThisFuncLeave();
8513 return rc;
8514}
8515
8516/**
8517 * @note Locks this object for writing.
8518 */
8519STDMETHODIMP SessionMachine::EndTakingSnapshot(BOOL aSuccess)
8520{
8521 LogFlowThisFunc(("\n"));
8522
8523 AutoCaller autoCaller(this);
8524 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8525
8526 AutoWriteLock alock(this);
8527
8528 AssertReturn(!aSuccess ||
8529 (mData->mMachineState == MachineState_Saving &&
8530 mSnapshotData.mLastState != MachineState_Null &&
8531 !mSnapshotData.mSnapshot.isNull()),
8532 E_FAIL);
8533
8534 /*
8535 * Restore the state we had when BeginTakingSnapshot() was called,
8536 * Console::fntTakeSnapshotWorker restores its local copy when we return.
8537 * If the state was Running, then let Console::fntTakeSnapshotWorker it
8538 * all via Console::Resume().
8539 */
8540 if ( mData->mMachineState != mSnapshotData.mLastState
8541 && mSnapshotData.mLastState != MachineState_Running)
8542 setMachineState(mSnapshotData.mLastState);
8543
8544 return endTakingSnapshot(aSuccess);
8545}
8546
8547/**
8548 * @note Locks mParent + this + children objects for writing!
8549 */
8550STDMETHODIMP SessionMachine::DiscardSnapshot(IConsole *aInitiator,
8551 IN_BSTR aId,
8552 MachineState_T *aMachineState,
8553 IProgress **aProgress)
8554{
8555 LogFlowThisFunc(("\n"));
8556
8557 Guid id(aId);
8558 AssertReturn(aInitiator && !id.isEmpty(), E_INVALIDARG);
8559 AssertReturn(aMachineState && aProgress, E_POINTER);
8560
8561 AutoCaller autoCaller(this);
8562 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8563
8564 /* saveSettings() needs mParent lock */
8565 AutoMultiWriteLock2 alock(mParent, this);
8566
8567 ComAssertRet (!Global::IsOnlineOrTransient (mData->mMachineState), E_FAIL);
8568
8569 AutoWriteLock treeLock(snapshotsTreeLockHandle());
8570
8571 ComObjPtr<Snapshot> snapshot;
8572 HRESULT rc = findSnapshot(id, snapshot, true /* aSetError */);
8573 CheckComRCReturnRC(rc);
8574
8575 AutoWriteLock snapshotLock(snapshot);
8576
8577 size_t childrenCount = snapshot->getChildrenCount();
8578 if (childrenCount > 1)
8579 return setError(VBOX_E_INVALID_OBJECT_STATE,
8580 tr("Snapshot '%s' of the machine '%ls' has more than one child snapshot (%d)"),
8581 snapshot->getName().c_str(),
8582 mUserData->mName.raw(),
8583 childrenCount);
8584
8585 /* If the snapshot being discarded is the current one, ensure current
8586 * settings are committed and saved.
8587 */
8588 if (snapshot == mData->mCurrentSnapshot)
8589 {
8590 if (isModified())
8591 {
8592 rc = saveSettings();
8593 CheckComRCReturnRC (rc);
8594 }
8595 }
8596
8597 /* create a progress object. The number of operations is:
8598 * 1 (preparing) + # of hard disks + 1 if the snapshot is online
8599 */
8600 ComObjPtr<Progress> progress;
8601 progress.createObject();
8602 rc = progress->init (mParent, aInitiator,
8603 Bstr(Utf8StrFmt(tr("Discarding snapshot '%s'"),
8604 snapshot->getName().c_str())),
8605 FALSE /* aCancelable */,
8606 1 + (ULONG)snapshot->getSnapshotMachine()->mMediaData->mAttachments.size() +
8607 (snapshot->stateFilePath().isNull() ? 0 : 1),
8608 Bstr (tr ("Preparing to discard snapshot")));
8609 AssertComRCReturn (rc, rc);
8610
8611 /* create and start the task on a separate thread */
8612 DiscardSnapshotTask *task = new DiscardSnapshotTask (this, progress, snapshot);
8613 int vrc = RTThreadCreate (NULL, taskHandler,
8614 (void *) task,
8615 0, RTTHREADTYPE_MAIN_WORKER, 0, "DiscardSnapshot");
8616 if (RT_FAILURE(vrc))
8617 delete task;
8618 ComAssertRCRet (vrc, E_FAIL);
8619
8620 /* set the proper machine state (note: after creating a Task instance) */
8621 setMachineState(MachineState_Discarding);
8622
8623 /* return the progress to the caller */
8624 progress.queryInterfaceTo(aProgress);
8625
8626 /* return the new state to the caller */
8627 *aMachineState = mData->mMachineState;
8628
8629 return S_OK;
8630}
8631
8632/**
8633 * @note Locks this + children objects for writing!
8634 */
8635STDMETHODIMP SessionMachine::DiscardCurrentState (
8636 IConsole *aInitiator, MachineState_T *aMachineState, IProgress **aProgress)
8637{
8638 LogFlowThisFunc(("\n"));
8639
8640 AssertReturn(aInitiator, E_INVALIDARG);
8641 AssertReturn(aMachineState && aProgress, E_POINTER);
8642
8643 AutoCaller autoCaller(this);
8644 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8645
8646 AutoWriteLock alock(this);
8647
8648 ComAssertRet (!Global::IsOnlineOrTransient (mData->mMachineState), E_FAIL);
8649
8650 if (mData->mCurrentSnapshot.isNull())
8651 return setError(VBOX_E_INVALID_OBJECT_STATE,
8652 tr("Could not discard the current state of the machine '%ls' because it doesn't have any snapshots"),
8653 mUserData->mName.raw());
8654
8655 /* create a progress object. The number of operations is: 1 (preparing) + #
8656 * of hard disks + 1 (if we need to copy the saved state file) */
8657 ComObjPtr<Progress> progress;
8658 progress.createObject();
8659 {
8660 ULONG opCount = 1 + (ULONG)mData->mCurrentSnapshot->getSnapshotMachine()->mMediaData->mAttachments.size();
8661 if (mData->mCurrentSnapshot->stateFilePath())
8662 ++opCount;
8663 progress->init (mParent, aInitiator,
8664 Bstr (tr ("Discarding current machine state")),
8665 FALSE /* aCancelable */, opCount,
8666 Bstr (tr ("Preparing to discard current state")));
8667 }
8668
8669 /* create and start the task on a separate thread (note that it will not
8670 * start working until we release alock) */
8671 DiscardCurrentStateTask *task =
8672 new DiscardCurrentStateTask (this, progress, false /* discardCurSnapshot */);
8673 int vrc = RTThreadCreate (NULL, taskHandler,
8674 (void *) task,
8675 0, RTTHREADTYPE_MAIN_WORKER, 0, "DiscardCurState");
8676 if (RT_FAILURE(vrc))
8677 {
8678 delete task;
8679 ComAssertRCRet (vrc, E_FAIL);
8680 }
8681
8682 /* set the proper machine state (note: after creating a Task instance) */
8683 setMachineState (MachineState_Discarding);
8684
8685 /* return the progress to the caller */
8686 progress.queryInterfaceTo(aProgress);
8687
8688 /* return the new state to the caller */
8689 *aMachineState = mData->mMachineState;
8690
8691 return S_OK;
8692}
8693
8694/**
8695 * @note Locks thos object for writing!
8696 */
8697STDMETHODIMP SessionMachine::DiscardCurrentSnapshotAndState(IConsole *aInitiator,
8698 MachineState_T *aMachineState,
8699 IProgress **aProgress)
8700{
8701 LogFlowThisFunc(("\n"));
8702
8703 AssertReturn(aInitiator, E_INVALIDARG);
8704 AssertReturn(aMachineState && aProgress, E_POINTER);
8705
8706 AutoCaller autoCaller(this);
8707 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8708
8709 AutoWriteLock alock(this);
8710
8711 ComAssertRet (!Global::IsOnlineOrTransient (mData->mMachineState), E_FAIL);
8712
8713 if (mData->mCurrentSnapshot.isNull())
8714 return setError(VBOX_E_INVALID_OBJECT_STATE,
8715 tr("Could not discard the current state of the machine '%ls' "
8716 "because it doesn't have any snapshots"),
8717 mUserData->mName.raw());
8718
8719 /* create a progress object. The number of operations is:
8720 * 1 (preparing) + # of hard disks in the current snapshot +
8721 * # of hard disks in the previous snapshot +
8722 * 1 if we need to copy the saved state file of the previous snapshot +
8723 * 1 if the current snapshot is online
8724 * or (if there is no previous snapshot):
8725 * 1 (preparing) + # of hard disks in the current snapshot * 2 +
8726 * 1 if we need to copy the saved state file of the current snapshot * 2
8727 */
8728 ComObjPtr<Progress> progress;
8729 progress.createObject();
8730 {
8731 ComObjPtr<Snapshot> curSnapshot = mData->mCurrentSnapshot;
8732 ComObjPtr<Snapshot> prevSnapshot = mData->mCurrentSnapshot->parent();
8733
8734 ULONG opCount = 1;
8735 if (prevSnapshot)
8736 {
8737 opCount += (ULONG)curSnapshot->getSnapshotMachine()->mMediaData->mAttachments.size();
8738 opCount += (ULONG)prevSnapshot->getSnapshotMachine()->mMediaData->mAttachments.size();
8739 if (prevSnapshot->stateFilePath())
8740 ++opCount;
8741 if (curSnapshot->stateFilePath())
8742 ++opCount;
8743 }
8744 else
8745 {
8746 opCount +=
8747 (ULONG)curSnapshot->getSnapshotMachine()->mMediaData->mAttachments.size() * 2;
8748 if (curSnapshot->stateFilePath())
8749 opCount += 2;
8750 }
8751
8752 progress->init(mParent, aInitiator,
8753 Bstr (tr ("Discarding current machine snapshot and state")),
8754 FALSE /* aCancelable */, opCount,
8755 Bstr (tr ("Preparing to discard current snapshot and state")));
8756 }
8757
8758 /* create and start the task on a separate thread */
8759 DiscardCurrentStateTask *task =
8760 new DiscardCurrentStateTask (this, progress, true /* discardCurSnapshot */);
8761 int vrc = RTThreadCreate(NULL, taskHandler,
8762 (void *) task,
8763 0, RTTHREADTYPE_MAIN_WORKER, 0, "DiscardCurStSnp");
8764 if (RT_FAILURE(vrc))
8765 {
8766 delete task;
8767 ComAssertRCRet(vrc, E_FAIL);
8768 }
8769
8770 /* set the proper machine state (note: after creating a Task instance) */
8771 setMachineState(MachineState_Discarding);
8772
8773 /* return the progress to the caller */
8774 progress.queryInterfaceTo(aProgress);
8775
8776 /* return the new state to the caller */
8777 *aMachineState = mData->mMachineState;
8778
8779 return S_OK;
8780}
8781
8782STDMETHODIMP SessionMachine::PullGuestProperties(ComSafeArrayOut(BSTR, aNames),
8783 ComSafeArrayOut(BSTR, aValues),
8784 ComSafeArrayOut(ULONG64, aTimestamps),
8785 ComSafeArrayOut(BSTR, aFlags))
8786{
8787 LogFlowThisFunc(("\n"));
8788
8789#ifdef VBOX_WITH_GUEST_PROPS
8790 using namespace guestProp;
8791
8792 AutoCaller autoCaller(this);
8793 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8794
8795 AutoReadLock alock(this);
8796
8797 AssertReturn(!ComSafeArrayOutIsNull(aNames), E_POINTER);
8798 AssertReturn(!ComSafeArrayOutIsNull(aValues), E_POINTER);
8799 AssertReturn(!ComSafeArrayOutIsNull(aTimestamps), E_POINTER);
8800 AssertReturn(!ComSafeArrayOutIsNull(aFlags), E_POINTER);
8801
8802 size_t cEntries = mHWData->mGuestProperties.size();
8803 com::SafeArray<BSTR> names (cEntries);
8804 com::SafeArray<BSTR> values (cEntries);
8805 com::SafeArray<ULONG64> timestamps (cEntries);
8806 com::SafeArray<BSTR> flags (cEntries);
8807 unsigned i = 0;
8808 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
8809 it != mHWData->mGuestProperties.end();
8810 ++it)
8811 {
8812 char szFlags[MAX_FLAGS_LEN + 1];
8813 it->strName.cloneTo(&names[i]);
8814 it->strValue.cloneTo(&values[i]);
8815 timestamps[i] = it->mTimestamp;
8816 /* If it is NULL, keep it NULL. */
8817 if (it->mFlags)
8818 {
8819 writeFlags(it->mFlags, szFlags);
8820 Bstr(szFlags).cloneTo(&flags[i]);
8821 }
8822 else
8823 flags[i] = NULL;
8824 ++i;
8825 }
8826 names.detachTo(ComSafeArrayOutArg(aNames));
8827 values.detachTo(ComSafeArrayOutArg(aValues));
8828 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
8829 flags.detachTo(ComSafeArrayOutArg(aFlags));
8830 mHWData->mPropertyServiceActive = true;
8831 return S_OK;
8832#else
8833 ReturnComNotImplemented();
8834#endif
8835}
8836
8837STDMETHODIMP SessionMachine::PushGuestProperties(ComSafeArrayIn (IN_BSTR, aNames),
8838 ComSafeArrayIn (IN_BSTR, aValues),
8839 ComSafeArrayIn (ULONG64, aTimestamps),
8840 ComSafeArrayIn (IN_BSTR, aFlags))
8841{
8842 LogFlowThisFunc(("\n"));
8843
8844#ifdef VBOX_WITH_GUEST_PROPS
8845 using namespace guestProp;
8846
8847 AutoCaller autoCaller(this);
8848 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8849
8850 AutoWriteLock alock(this);
8851
8852 /* Temporarily reset the registered flag, so that our machine state
8853 * changes (i.e. mHWData.backup()) succeed. (isMutable() used in
8854 * all setters will return FALSE for a Machine instance if mRegistered
8855 * is TRUE). This is copied from registeredInit(), and may or may not be
8856 * the right way to handle this. */
8857 mData->mRegistered = FALSE;
8858 HRESULT rc = checkStateDependency(MutableStateDep);
8859 LogRel (("checkStateDependency(MutableStateDep) returned 0x%x\n", rc));
8860 CheckComRCReturnRC(rc);
8861
8862 // ComAssertRet (mData->mMachineState < MachineState_Running, E_FAIL);
8863
8864 AssertReturn(!ComSafeArrayInIsNull (aNames), E_POINTER);
8865 AssertReturn(!ComSafeArrayInIsNull (aValues), E_POINTER);
8866 AssertReturn(!ComSafeArrayInIsNull (aTimestamps), E_POINTER);
8867 AssertReturn(!ComSafeArrayInIsNull (aFlags), E_POINTER);
8868
8869 com::SafeArray<IN_BSTR> names (ComSafeArrayInArg (aNames));
8870 com::SafeArray<IN_BSTR> values (ComSafeArrayInArg (aValues));
8871 com::SafeArray<ULONG64> timestamps (ComSafeArrayInArg (aTimestamps));
8872 com::SafeArray<IN_BSTR> flags (ComSafeArrayInArg (aFlags));
8873 DiscardSettings();
8874 mHWData.backup();
8875 mHWData->mGuestProperties.erase (mHWData->mGuestProperties.begin(),
8876 mHWData->mGuestProperties.end());
8877 for (unsigned i = 0; i < names.size(); ++i)
8878 {
8879 uint32_t fFlags = NILFLAG;
8880 validateFlags (Utf8Str (flags[i]).raw(), &fFlags);
8881 HWData::GuestProperty property = { names[i], values[i], timestamps[i], fFlags };
8882 mHWData->mGuestProperties.push_back (property);
8883 }
8884 mHWData->mPropertyServiceActive = false;
8885 alock.unlock();
8886 SaveSettings();
8887 /* Restore the mRegistered flag. */
8888 mData->mRegistered = TRUE;
8889 return S_OK;
8890#else
8891 ReturnComNotImplemented();
8892#endif
8893}
8894
8895STDMETHODIMP SessionMachine::PushGuestProperty(IN_BSTR aName,
8896 IN_BSTR aValue,
8897 ULONG64 aTimestamp,
8898 IN_BSTR aFlags)
8899{
8900 LogFlowThisFunc(("\n"));
8901
8902#ifdef VBOX_WITH_GUEST_PROPS
8903 using namespace guestProp;
8904
8905 CheckComArgNotNull (aName);
8906 if ((aValue != NULL) && (!VALID_PTR (aValue) || !VALID_PTR (aFlags)))
8907 return E_POINTER; /* aValue can be NULL to indicate deletion */
8908
8909 try
8910 {
8911 Utf8Str utf8Name(aName);
8912 Utf8Str utf8Flags(aFlags);
8913 Utf8Str utf8Patterns(mHWData->mGuestPropertyNotificationPatterns);
8914
8915 uint32_t fFlags = NILFLAG;
8916 if ((aFlags != NULL) && RT_FAILURE(validateFlags (utf8Flags.raw(), &fFlags)))
8917 return E_INVALIDARG;
8918
8919 bool matchAll = false;
8920 if (utf8Patterns.isEmpty())
8921 matchAll = true;
8922
8923 AutoCaller autoCaller(this);
8924 CheckComRCReturnRC(autoCaller.rc());
8925
8926 AutoWriteLock alock(this);
8927
8928 HRESULT rc = checkStateDependency(MutableStateDep);
8929 CheckComRCReturnRC(rc);
8930
8931 mHWData.backup();
8932 for (HWData::GuestPropertyList::iterator iter = mHWData->mGuestProperties.begin();
8933 iter != mHWData->mGuestProperties.end();
8934 ++iter)
8935 if (utf8Name == iter->strName)
8936 {
8937 mHWData->mGuestProperties.erase(iter);
8938 break;
8939 }
8940 if (aValue != NULL)
8941 {
8942 HWData::GuestProperty property = { aName, aValue, aTimestamp, fFlags };
8943 mHWData->mGuestProperties.push_back (property);
8944 }
8945
8946 /* send a callback notification if appropriate */
8947 alock.leave();
8948 if ( matchAll
8949 || RTStrSimplePatternMultiMatch(utf8Patterns.raw(),
8950 RTSTR_MAX,
8951 utf8Name.raw(),
8952 RTSTR_MAX, NULL)
8953 )
8954 mParent->onGuestPropertyChange(mData->mUuid,
8955 aName,
8956 aValue,
8957 aFlags);
8958 }
8959 catch(std::bad_alloc &)
8960 {
8961 return E_OUTOFMEMORY;
8962 }
8963 return S_OK;
8964#else
8965 ReturnComNotImplemented();
8966#endif
8967}
8968
8969// public methods only for internal purposes
8970/////////////////////////////////////////////////////////////////////////////
8971
8972/**
8973 * Called from the client watcher thread to check for expected or unexpected
8974 * death of the client process that has a direct session to this machine.
8975 *
8976 * On Win32 and on OS/2, this method is called only when we've got the
8977 * mutex (i.e. the client has either died or terminated normally) so it always
8978 * returns @c true (the client is terminated, the session machine is
8979 * uninitialized).
8980 *
8981 * On other platforms, the method returns @c true if the client process has
8982 * terminated normally or abnormally and the session machine was uninitialized,
8983 * and @c false if the client process is still alive.
8984 *
8985 * @note Locks this object for writing.
8986 */
8987bool SessionMachine::checkForDeath()
8988{
8989 Uninit::Reason reason;
8990 bool terminated = false;
8991
8992 /* Enclose autoCaller with a block because calling uninit() from under it
8993 * will deadlock. */
8994 {
8995 AutoCaller autoCaller(this);
8996 if (!autoCaller.isOk())
8997 {
8998 /* return true if not ready, to cause the client watcher to exclude
8999 * the corresponding session from watching */
9000 LogFlowThisFunc(("Already uninitialized!"));
9001 return true;
9002 }
9003
9004 AutoWriteLock alock(this);
9005
9006 /* Determine the reason of death: if the session state is Closing here,
9007 * everything is fine. Otherwise it means that the client did not call
9008 * OnSessionEnd() before it released the IPC semaphore. This may happen
9009 * either because the client process has abnormally terminated, or
9010 * because it simply forgot to call ISession::Close() before exiting. We
9011 * threat the latter also as an abnormal termination (see
9012 * Session::uninit() for details). */
9013 reason = mData->mSession.mState == SessionState_Closing ?
9014 Uninit::Normal :
9015 Uninit::Abnormal;
9016
9017#if defined(RT_OS_WINDOWS)
9018
9019 AssertMsg (mIPCSem, ("semaphore must be created"));
9020
9021 /* release the IPC mutex */
9022 ::ReleaseMutex (mIPCSem);
9023
9024 terminated = true;
9025
9026#elif defined(RT_OS_OS2)
9027
9028 AssertMsg (mIPCSem, ("semaphore must be created"));
9029
9030 /* release the IPC mutex */
9031 ::DosReleaseMutexSem (mIPCSem);
9032
9033 terminated = true;
9034
9035#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9036
9037 AssertMsg (mIPCSem >= 0, ("semaphore must be created"));
9038
9039 int val = ::semctl (mIPCSem, 0, GETVAL);
9040 if (val > 0)
9041 {
9042 /* the semaphore is signaled, meaning the session is terminated */
9043 terminated = true;
9044 }
9045
9046#else
9047# error "Port me!"
9048#endif
9049
9050 } /* AutoCaller block */
9051
9052 if (terminated)
9053 uninit (reason);
9054
9055 return terminated;
9056}
9057
9058/**
9059 * @note Locks this object for reading.
9060 */
9061HRESULT SessionMachine::onNetworkAdapterChange (INetworkAdapter *networkAdapter, BOOL changeAdapter)
9062{
9063 LogFlowThisFunc(("\n"));
9064
9065 AutoCaller autoCaller(this);
9066 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9067
9068 ComPtr<IInternalSessionControl> directControl;
9069 {
9070 AutoReadLock alock(this);
9071 directControl = mData->mSession.mDirectControl;
9072 }
9073
9074 /* ignore notifications sent after #OnSessionEnd() is called */
9075 if (!directControl)
9076 return S_OK;
9077
9078 return directControl->OnNetworkAdapterChange (networkAdapter, changeAdapter);
9079}
9080
9081/**
9082 * @note Locks this object for reading.
9083 */
9084HRESULT SessionMachine::onSerialPortChange (ISerialPort *serialPort)
9085{
9086 LogFlowThisFunc(("\n"));
9087
9088 AutoCaller autoCaller(this);
9089 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9090
9091 ComPtr<IInternalSessionControl> directControl;
9092 {
9093 AutoReadLock alock(this);
9094 directControl = mData->mSession.mDirectControl;
9095 }
9096
9097 /* ignore notifications sent after #OnSessionEnd() is called */
9098 if (!directControl)
9099 return S_OK;
9100
9101 return directControl->OnSerialPortChange (serialPort);
9102}
9103
9104/**
9105 * @note Locks this object for reading.
9106 */
9107HRESULT SessionMachine::onParallelPortChange (IParallelPort *parallelPort)
9108{
9109 LogFlowThisFunc(("\n"));
9110
9111 AutoCaller autoCaller(this);
9112 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9113
9114 ComPtr<IInternalSessionControl> directControl;
9115 {
9116 AutoReadLock alock(this);
9117 directControl = mData->mSession.mDirectControl;
9118 }
9119
9120 /* ignore notifications sent after #OnSessionEnd() is called */
9121 if (!directControl)
9122 return S_OK;
9123
9124 return directControl->OnParallelPortChange (parallelPort);
9125}
9126
9127/**
9128 * @note Locks this object for reading.
9129 */
9130HRESULT SessionMachine::onStorageControllerChange ()
9131{
9132 LogFlowThisFunc(("\n"));
9133
9134 AutoCaller autoCaller(this);
9135 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9136
9137 ComPtr<IInternalSessionControl> directControl;
9138 {
9139 AutoReadLock alock(this);
9140 directControl = mData->mSession.mDirectControl;
9141 }
9142
9143 /* ignore notifications sent after #OnSessionEnd() is called */
9144 if (!directControl)
9145 return S_OK;
9146
9147 return directControl->OnStorageControllerChange ();
9148}
9149
9150/**
9151 * @note Locks this object for reading.
9152 */
9153HRESULT SessionMachine::onMediumChange(IMediumAttachment *aAttachment)
9154{
9155 LogFlowThisFunc(("\n"));
9156
9157 AutoCaller autoCaller(this);
9158 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9159
9160 ComPtr<IInternalSessionControl> directControl;
9161 {
9162 AutoReadLock alock(this);
9163 directControl = mData->mSession.mDirectControl;
9164 }
9165
9166 /* ignore notifications sent after #OnSessionEnd() is called */
9167 if (!directControl)
9168 return S_OK;
9169
9170 return directControl->OnMediumChange(aAttachment);
9171}
9172
9173/**
9174 * @note Locks this object for reading.
9175 */
9176HRESULT SessionMachine::onVRDPServerChange()
9177{
9178 LogFlowThisFunc(("\n"));
9179
9180 AutoCaller autoCaller(this);
9181 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9182
9183 ComPtr<IInternalSessionControl> directControl;
9184 {
9185 AutoReadLock alock(this);
9186 directControl = mData->mSession.mDirectControl;
9187 }
9188
9189 /* ignore notifications sent after #OnSessionEnd() is called */
9190 if (!directControl)
9191 return S_OK;
9192
9193 return directControl->OnVRDPServerChange();
9194}
9195
9196/**
9197 * @note Locks this object for reading.
9198 */
9199HRESULT SessionMachine::onUSBControllerChange()
9200{
9201 LogFlowThisFunc(("\n"));
9202
9203 AutoCaller autoCaller(this);
9204 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9205
9206 ComPtr<IInternalSessionControl> directControl;
9207 {
9208 AutoReadLock alock(this);
9209 directControl = mData->mSession.mDirectControl;
9210 }
9211
9212 /* ignore notifications sent after #OnSessionEnd() is called */
9213 if (!directControl)
9214 return S_OK;
9215
9216 return directControl->OnUSBControllerChange();
9217}
9218
9219/**
9220 * @note Locks this object for reading.
9221 */
9222HRESULT SessionMachine::onSharedFolderChange()
9223{
9224 LogFlowThisFunc(("\n"));
9225
9226 AutoCaller autoCaller(this);
9227 AssertComRCReturnRC(autoCaller.rc());
9228
9229 ComPtr<IInternalSessionControl> directControl;
9230 {
9231 AutoReadLock alock(this);
9232 directControl = mData->mSession.mDirectControl;
9233 }
9234
9235 /* ignore notifications sent after #OnSessionEnd() is called */
9236 if (!directControl)
9237 return S_OK;
9238
9239 return directControl->OnSharedFolderChange (FALSE /* aGlobal */);
9240}
9241
9242/**
9243 * Returns @c true if this machine's USB controller reports it has a matching
9244 * filter for the given USB device and @c false otherwise.
9245 *
9246 * @note Locks this object for reading.
9247 */
9248bool SessionMachine::hasMatchingUSBFilter (const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
9249{
9250 AutoCaller autoCaller(this);
9251 /* silently return if not ready -- this method may be called after the
9252 * direct machine session has been called */
9253 if (!autoCaller.isOk())
9254 return false;
9255
9256 AutoReadLock alock(this);
9257
9258#ifdef VBOX_WITH_USB
9259 switch (mData->mMachineState)
9260 {
9261 case MachineState_Starting:
9262 case MachineState_Restoring:
9263 case MachineState_Paused:
9264 case MachineState_Running:
9265 return mUSBController->hasMatchingFilter (aDevice, aMaskedIfs);
9266 default: break;
9267 }
9268#else
9269 NOREF(aDevice);
9270 NOREF(aMaskedIfs);
9271#endif
9272 return false;
9273}
9274
9275/**
9276 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
9277 */
9278HRESULT SessionMachine::onUSBDeviceAttach (IUSBDevice *aDevice,
9279 IVirtualBoxErrorInfo *aError,
9280 ULONG aMaskedIfs)
9281{
9282 LogFlowThisFunc(("\n"));
9283
9284 AutoCaller autoCaller(this);
9285
9286 /* This notification may happen after the machine object has been
9287 * uninitialized (the session was closed), so don't assert. */
9288 CheckComRCReturnRC(autoCaller.rc());
9289
9290 ComPtr<IInternalSessionControl> directControl;
9291 {
9292 AutoReadLock alock(this);
9293 directControl = mData->mSession.mDirectControl;
9294 }
9295
9296 /* fail on notifications sent after #OnSessionEnd() is called, it is
9297 * expected by the caller */
9298 if (!directControl)
9299 return E_FAIL;
9300
9301 /* No locks should be held at this point. */
9302 AssertMsg (RTThreadGetWriteLockCount (RTThreadSelf()) == 0, ("%d\n", RTThreadGetWriteLockCount (RTThreadSelf())));
9303 AssertMsg (RTThreadGetReadLockCount (RTThreadSelf()) == 0, ("%d\n", RTThreadGetReadLockCount (RTThreadSelf())));
9304
9305 return directControl->OnUSBDeviceAttach (aDevice, aError, aMaskedIfs);
9306}
9307
9308/**
9309 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
9310 */
9311HRESULT SessionMachine::onUSBDeviceDetach (IN_BSTR aId,
9312 IVirtualBoxErrorInfo *aError)
9313{
9314 LogFlowThisFunc(("\n"));
9315
9316 AutoCaller autoCaller(this);
9317
9318 /* This notification may happen after the machine object has been
9319 * uninitialized (the session was closed), so don't assert. */
9320 CheckComRCReturnRC(autoCaller.rc());
9321
9322 ComPtr<IInternalSessionControl> directControl;
9323 {
9324 AutoReadLock alock(this);
9325 directControl = mData->mSession.mDirectControl;
9326 }
9327
9328 /* fail on notifications sent after #OnSessionEnd() is called, it is
9329 * expected by the caller */
9330 if (!directControl)
9331 return E_FAIL;
9332
9333 /* No locks should be held at this point. */
9334 AssertMsg (RTThreadGetWriteLockCount (RTThreadSelf()) == 0, ("%d\n", RTThreadGetWriteLockCount (RTThreadSelf())));
9335 AssertMsg (RTThreadGetReadLockCount (RTThreadSelf()) == 0, ("%d\n", RTThreadGetReadLockCount (RTThreadSelf())));
9336
9337 return directControl->OnUSBDeviceDetach (aId, aError);
9338}
9339
9340// protected methods
9341/////////////////////////////////////////////////////////////////////////////
9342
9343/**
9344 * Helper method to finalize saving the state.
9345 *
9346 * @note Must be called from under this object's lock.
9347 *
9348 * @param aSuccess TRUE if the snapshot has been taken successfully
9349 *
9350 * @note Locks mParent + this objects for writing.
9351 */
9352HRESULT SessionMachine::endSavingState (BOOL aSuccess)
9353{
9354 LogFlowThisFuncEnter();
9355
9356 AutoCaller autoCaller(this);
9357 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9358
9359 /* saveSettings() needs mParent lock */
9360 AutoMultiWriteLock2 alock (mParent, this);
9361
9362 HRESULT rc = S_OK;
9363
9364 if (aSuccess)
9365 {
9366 mSSData->mStateFilePath = mSnapshotData.mStateFilePath;
9367
9368 /* save all VM settings */
9369 rc = saveSettings();
9370 }
9371 else
9372 {
9373 /* delete the saved state file (it might have been already created) */
9374 RTFileDelete(Utf8Str(mSnapshotData.mStateFilePath).c_str());
9375 }
9376
9377 /* remove the completed progress object */
9378 mParent->removeProgress (mSnapshotData.mProgressId);
9379
9380 /* clear out the temporary saved state data */
9381 mSnapshotData.mLastState = MachineState_Null;
9382 mSnapshotData.mProgressId.clear();
9383 mSnapshotData.mStateFilePath.setNull();
9384
9385 LogFlowThisFuncLeave();
9386 return rc;
9387}
9388
9389/**
9390 * Helper method to finalize taking a snapshot. Gets called to finalize the
9391 * "take snapshot" procedure, either from the public SessionMachine::EndTakingSnapshot()
9392 * if taking the snapshot failed/was aborted or from the takeSnapshotHandler thread
9393 * when taking the snapshot succeeded.
9394 *
9395 * Expected to be called after completing *all* the tasks related to taking the
9396 * snapshot, either successfully or unsuccessfilly.
9397 *
9398 * @param aSuccess TRUE if the snapshot has been taken successfully.
9399 *
9400 * @note Locks this objects for writing.
9401 */
9402HRESULT SessionMachine::endTakingSnapshot(BOOL aSuccess)
9403{
9404 LogFlowThisFuncEnter();
9405
9406 AutoCaller autoCaller(this);
9407 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9408
9409 AutoMultiWriteLock2 alock(mParent, this);
9410 // saveSettings needs VirtualBox lock
9411
9412 AssertReturn(!mSnapshotData.mSnapshot.isNull(), E_FAIL);
9413
9414 MultiResult rc(S_OK);
9415
9416 Snapshot *pOldFirstSnap = mData->mFirstSnapshot;
9417 Snapshot *pOldCurrentSnap = mData->mCurrentSnapshot;
9418
9419 bool fOnline = Global::IsOnline(mSnapshotData.mLastState);
9420
9421 if (aSuccess)
9422 {
9423 mData->mCurrentSnapshot = mSnapshotData.mSnapshot;
9424
9425 /* memorize the first snapshot if necessary */
9426 if (!mData->mFirstSnapshot)
9427 mData->mFirstSnapshot = mData->mCurrentSnapshot;
9428
9429 if (!fOnline)
9430 /* the machine was powered off or saved when taking a snapshot, so
9431 * reset the mCurrentStateModified flag */
9432 mData->mCurrentStateModified = FALSE;
9433
9434 rc = saveSettings();
9435 }
9436
9437 if (aSuccess && SUCCEEDED(rc))
9438 {
9439 /* associate old hard disks with the snapshot and do locking/unlocking*/
9440 fixupMedia(true /* aCommit */, fOnline);
9441
9442 /* inform callbacks */
9443 mParent->onSnapshotTaken(mData->mUuid,
9444 mSnapshotData.mSnapshot->getId());
9445 }
9446 else
9447 {
9448 /* delete all differencing hard disks created (this will also attach
9449 * their parents back by rolling back mMediaData) */
9450 fixupMedia(false /* aCommit */);
9451
9452 mData->mFirstSnapshot = pOldFirstSnap; // might have been changed above
9453 mData->mCurrentSnapshot = pOldCurrentSnap; // might have been changed above
9454
9455 /* delete the saved state file (it might have been already created) */
9456 if (mSnapshotData.mSnapshot->stateFilePath())
9457 RTFileDelete(Utf8Str(mSnapshotData.mSnapshot->stateFilePath()).c_str());
9458
9459 mSnapshotData.mSnapshot->uninit();
9460 }
9461
9462 /* clear out the snapshot data */
9463 mSnapshotData.mLastState = MachineState_Null;
9464 mSnapshotData.mSnapshot.setNull();
9465
9466 LogFlowThisFuncLeave();
9467 return rc;
9468}
9469
9470/**
9471 * Helper struct for SessionMachine::discardSnapshotHandler().
9472 */
9473struct MediumDiscardRec
9474{
9475 MediumDiscardRec() : chain (NULL) {}
9476
9477 MediumDiscardRec (const ComObjPtr<Medium> &aHd,
9478 Medium::MergeChain *aChain = NULL)
9479 : hd (aHd), chain (aChain) {}
9480
9481 MediumDiscardRec (const ComObjPtr<Medium> &aHd,
9482 Medium::MergeChain *aChain,
9483 const ComObjPtr<Medium> &aReplaceHd,
9484 const ComObjPtr<MediumAttachment> &aReplaceHda,
9485 const Guid &aSnapshotId)
9486 : hd (aHd), chain (aChain)
9487 , replaceHd (aReplaceHd), replaceHda (aReplaceHda)
9488 , snapshotId (aSnapshotId) {}
9489
9490 ComObjPtr<Medium> hd;
9491 Medium::MergeChain *chain;
9492 /* these are for the replace hard disk case: */
9493 ComObjPtr<Medium> replaceHd;
9494 ComObjPtr<MediumAttachment> replaceHda;
9495 Guid snapshotId;
9496};
9497
9498typedef std::list <MediumDiscardRec> MediumDiscardRecList;
9499
9500/**
9501 * Discard snapshot task handler. Must be called only by
9502 * DiscardSnapshotTask::handler()!
9503 *
9504 * When aTask.subTask is true, the associated progress object is left
9505 * uncompleted on success. On failure, the progress is marked as completed
9506 * regardless of this parameter.
9507 *
9508 * @note Locks mParent + this + child objects for writing!
9509 */
9510void SessionMachine::discardSnapshotHandler(DiscardSnapshotTask &aTask)
9511{
9512 LogFlowThisFuncEnter();
9513
9514 AutoCaller autoCaller(this);
9515
9516 LogFlowThisFunc(("state=%d\n", autoCaller.state()));
9517 if (!autoCaller.isOk())
9518 {
9519 /* we might have been uninitialized because the session was accidentally
9520 * closed by the client, so don't assert */
9521 aTask.progress->notifyComplete(E_FAIL,
9522 COM_IIDOF(IMachine),
9523 getComponentName(),
9524 tr("The session has been accidentally closed"));
9525 LogFlowThisFuncLeave();
9526 return;
9527 }
9528
9529 /* Locking order: */
9530 AutoMultiWriteLock3 alock(this->lockHandle(),
9531 this->snapshotsTreeLockHandle(),
9532 aTask.snapshot->lockHandle());
9533
9534 ComPtr<SnapshotMachine> sm = aTask.snapshot->getSnapshotMachine();
9535 /* no need to lock the snapshot machine since it is const by definiton */
9536
9537 HRESULT rc = S_OK;
9538
9539 /* save the snapshot ID (for callbacks) */
9540 Guid snapshotId = aTask.snapshot->getId();
9541
9542 MediumDiscardRecList toDiscard;
9543
9544 bool settingsChanged = false;
9545
9546 try
9547 {
9548 /* first pass: */
9549 LogFlowThisFunc(("1: Checking hard disk merge prerequisites...\n"));
9550
9551 for (MediaData::AttachmentList::const_iterator it = sm->mMediaData->mAttachments.begin();
9552 it != sm->mMediaData->mAttachments.end();
9553 ++it)
9554 {
9555 ComObjPtr<MediumAttachment> hda = *it;
9556 ComObjPtr<Medium> hd = hda->medium();
9557
9558 // medium can be NULL only for non-hard-disk types
9559 Assert( !hd.isNull()
9560 || hda->type() != DeviceType_HardDisk);
9561 if (hd.isNull())
9562 continue;
9563
9564 /* Medium::prepareDiscard() reqiuires a write lock */
9565 AutoWriteLock hdLock(hd);
9566
9567 if (hd->type() != MediumType_Normal)
9568 {
9569 /* skip writethrough hard disks */
9570 Assert(hd->type() == MediumType_Writethrough);
9571 rc = aTask.progress->SetNextOperation(BstrFmt(tr("Skipping writethrough hard disk '%s'"),
9572 hd->base()->name().raw()),
9573 1); // weight
9574 CheckComRCThrowRC(rc);
9575 continue;
9576 }
9577
9578 Medium::MergeChain *chain = NULL;
9579
9580 /* needs to be discarded (merged with the child if any), check
9581 * prerequisites */
9582 rc = hd->prepareDiscard(chain);
9583 CheckComRCThrowRC(rc);
9584
9585 if (hd->parent().isNull() && chain != NULL)
9586 {
9587 /* it's a base hard disk so it will be a backward merge of its
9588 * only child to it (prepareDiscard() does necessary checks). We
9589 * need then to update the attachment that refers to the child
9590 * to refer to the parent instead. Don't forget to detach the
9591 * child (otherwise mergeTo() called by discard() will assert
9592 * because it will be going to delete the child) */
9593
9594 /* The below assert would be nice but I don't want to move
9595 * Medium::MergeChain to the header just for that
9596 * Assert (!chain->isForward()); */
9597
9598 Assert(hd->children().size() == 1);
9599
9600 ComObjPtr<Medium> replaceHd = hd->children().front();
9601
9602 const Guid *pReplaceMachineId = replaceHd->getFirstMachineBackrefId();
9603 Assert(pReplaceMachineId && *pReplaceMachineId == mData->mUuid);
9604
9605 Guid snapshotId;
9606 const Guid *pSnapshotId = replaceHd->getFirstMachineBackrefSnapshotId();
9607 if (pSnapshotId)
9608 snapshotId = *pSnapshotId;
9609
9610 HRESULT rc2 = S_OK;
9611
9612 /* adjust back references */
9613 rc2 = replaceHd->detachFrom (mData->mUuid, snapshotId);
9614 AssertComRC(rc2);
9615
9616 rc2 = hd->attachTo (mData->mUuid, snapshotId);
9617 AssertComRC(rc2);
9618
9619 /* replace the hard disk in the attachment object */
9620 if (snapshotId.isEmpty())
9621 {
9622 /* in current state */
9623 AssertBreak(hda = findAttachment(mMediaData->mAttachments, replaceHd));
9624 }
9625 else
9626 {
9627 /* in snapshot */
9628 ComObjPtr<Snapshot> snapshot;
9629 rc2 = findSnapshot(snapshotId, snapshot);
9630 AssertComRC(rc2);
9631
9632 /* don't lock the snapshot; cannot be modified outside */
9633 MediaData::AttachmentList &snapAtts = snapshot->getSnapshotMachine()->mMediaData->mAttachments;
9634 AssertBreak(hda = findAttachment(snapAtts, replaceHd));
9635 }
9636
9637 AutoWriteLock attLock(hda);
9638 hda->updateMedium(hd, false /* aImplicit */);
9639
9640 toDiscard.push_back(MediumDiscardRec(hd,
9641 chain,
9642 replaceHd,
9643 hda,
9644 snapshotId));
9645 continue;
9646 }
9647
9648 toDiscard.push_back(MediumDiscardRec(hd, chain));
9649 }
9650
9651 /* Now we checked that we can successfully merge all normal hard disks
9652 * (unless a runtime error like end-of-disc happens). Prior to
9653 * performing the actual merge, we want to discard the snapshot itself
9654 * and remove it from the XML file to make sure that a possible merge
9655 * ruintime error will not make this snapshot inconsistent because of
9656 * the partially merged or corrupted hard disks */
9657
9658 /* second pass: */
9659 LogFlowThisFunc(("2: Discarding snapshot...\n"));
9660
9661 {
9662 ComObjPtr<Snapshot> parentSnapshot = aTask.snapshot->parent();
9663 Bstr stateFilePath = aTask.snapshot->stateFilePath();
9664
9665 /* Note that discarding the snapshot will deassociate it from the
9666 * hard disks which will allow the merge+delete operation for them*/
9667 aTask.snapshot->beginDiscard();
9668 aTask.snapshot->uninit();
9669
9670 rc = saveAllSnapshots();
9671 CheckComRCThrowRC(rc);
9672
9673 /// @todo (dmik)
9674 // if we implement some warning mechanism later, we'll have
9675 // to return a warning if the state file path cannot be deleted
9676 if (stateFilePath)
9677 {
9678 aTask.progress->SetNextOperation(Bstr(tr("Discarding the execution state")),
9679 1); // weight
9680
9681 RTFileDelete(Utf8Str(stateFilePath).c_str());
9682 }
9683
9684 /// @todo NEWMEDIA to provide a good level of fauilt tolerance, we
9685 /// should restore the shapshot in the snapshot tree if
9686 /// saveSnapshotSettings fails. Actually, we may call
9687 /// #saveSnapshotSettings() with a special flag that will tell it to
9688 /// skip the given snapshot as if it would have been discarded and
9689 /// only actually discard it if the save operation succeeds.
9690 }
9691
9692 /* here we come when we've irrevesibly discarded the snapshot which
9693 * means that the VM settigns (our relevant changes to mData) need to be
9694 * saved too */
9695 /// @todo NEWMEDIA maybe save everything in one operation in place of
9696 /// saveSnapshotSettings() above
9697 settingsChanged = true;
9698
9699 /* third pass: */
9700 LogFlowThisFunc(("3: Performing actual hard disk merging...\n"));
9701
9702 /* leave the locks before the potentially lengthy operation */
9703 alock.leave();
9704
9705 /// @todo NEWMEDIA turn the following errors into warnings because the
9706 /// snapshot itself has been already deleted (and interpret these
9707 /// warnings properly on the GUI side)
9708
9709 for (MediumDiscardRecList::iterator it = toDiscard.begin();
9710 it != toDiscard.end();)
9711 {
9712 rc = it->hd->discard (aTask.progress, it->chain);
9713 CheckComRCBreakRC(rc);
9714
9715 /* prevent from calling cancelDiscard() */
9716 it = toDiscard.erase (it);
9717 }
9718
9719 alock.enter();
9720
9721 CheckComRCThrowRC(rc);
9722 }
9723 catch (HRESULT aRC) { rc = aRC; }
9724
9725 if (FAILED(rc))
9726 {
9727 HRESULT rc2 = S_OK;
9728
9729 /* un-prepare the remaining hard disks */
9730 for (MediumDiscardRecList::const_iterator it = toDiscard.begin();
9731 it != toDiscard.end(); ++it)
9732 {
9733 it->hd->cancelDiscard (it->chain);
9734
9735 if (!it->replaceHd.isNull())
9736 {
9737 /* undo hard disk replacement */
9738
9739 rc2 = it->replaceHd->attachTo (mData->mUuid, it->snapshotId);
9740 AssertComRC(rc2);
9741
9742 rc2 = it->hd->detachFrom (mData->mUuid, it->snapshotId);
9743 AssertComRC(rc2);
9744
9745 AutoWriteLock attLock (it->replaceHda);
9746 it->replaceHda->updateMedium(it->replaceHd, false /* aImplicit */);
9747 }
9748 }
9749 }
9750
9751 if (!aTask.subTask || FAILED(rc))
9752 {
9753 if (!aTask.subTask)
9754 {
9755 /* saveSettings() below needs a VirtualBox write lock and we need to
9756 * leave this object's lock to do this to follow the {parent-child}
9757 * locking rule. This is the last chance to do that while we are
9758 * still in a protective state which allows us to temporarily leave
9759 * the lock */
9760 alock.unlock();
9761 AutoWriteLock vboxLock(mParent);
9762 alock.lock();
9763
9764 /* preserve existing error info */
9765 ErrorInfoKeeper eik;
9766
9767 /* restore the machine state */
9768 setMachineState(aTask.state);
9769 updateMachineStateOnClient();
9770
9771 if (settingsChanged)
9772 saveSettings(SaveS_InformCallbacksAnyway);
9773 }
9774
9775 /* set the result (this will try to fetch current error info on failure) */
9776 aTask.progress->notifyComplete (rc);
9777 }
9778
9779 if (SUCCEEDED(rc))
9780 mParent->onSnapshotDiscarded (mData->mUuid, snapshotId);
9781
9782 LogFlowThisFunc(("Done discarding snapshot (rc=%08X)\n", rc));
9783 LogFlowThisFuncLeave();
9784}
9785
9786/**
9787 * Discard current state task handler. Must be called only by
9788 * DiscardCurrentStateTask::handler()!
9789 *
9790 * @note Locks mParent + this object for writing.
9791 */
9792void SessionMachine::discardCurrentStateHandler (DiscardCurrentStateTask &aTask)
9793{
9794 LogFlowThisFuncEnter();
9795
9796 AutoCaller autoCaller(this);
9797
9798 LogFlowThisFunc(("state=%d\n", autoCaller.state()));
9799 if (!autoCaller.isOk())
9800 {
9801 /* we might have been uninitialized because the session was accidentally
9802 * closed by the client, so don't assert */
9803 aTask.progress->notifyComplete (
9804 E_FAIL, COM_IIDOF (IMachine), getComponentName(),
9805 tr ("The session has been accidentally closed"));
9806
9807 LogFlowThisFuncLeave();
9808 return;
9809 }
9810
9811 /* saveSettings() needs mParent lock */
9812 AutoWriteLock vboxLock (mParent);
9813
9814 /* @todo We don't need mParent lock so far so unlock() it. Better is to
9815 * provide an AutoWriteLock argument that lets create a non-locking
9816 * instance */
9817 vboxLock.unlock();
9818
9819 AutoWriteLock alock(this);
9820
9821 /* discard all current changes to mUserData (name, OSType etc.) (note that
9822 * the machine is powered off, so there is no need to inform the direct
9823 * session) */
9824 if (isModified())
9825 rollback (false /* aNotify */);
9826
9827 HRESULT rc = S_OK;
9828
9829 bool errorInSubtask = false;
9830 bool stateRestored = false;
9831
9832 const bool isLastSnapshot = mData->mCurrentSnapshot->parent().isNull();
9833
9834 try
9835 {
9836 /* discard the saved state file if the machine was Saved prior to this
9837 * operation */
9838 if (aTask.state == MachineState_Saved)
9839 {
9840 Assert (!mSSData->mStateFilePath.isEmpty());
9841 RTFileDelete(Utf8Str(mSSData->mStateFilePath).c_str());
9842 mSSData->mStateFilePath.setNull();
9843 aTask.modifyLastState (MachineState_PoweredOff);
9844 rc = saveStateSettings (SaveSTS_StateFilePath);
9845 CheckComRCThrowRC(rc);
9846 }
9847
9848 if (aTask.discardCurrentSnapshot && !isLastSnapshot)
9849 {
9850 /* the "discard current snapshot and state" task is in action, the
9851 * current snapshot is not the last one. Discard the current
9852 * snapshot first */
9853
9854 DiscardSnapshotTask subTask (aTask, mData->mCurrentSnapshot);
9855 subTask.subTask = true;
9856 discardSnapshotHandler (subTask);
9857
9858 AutoCaller progressCaller (aTask.progress);
9859 AutoReadLock progressLock (aTask.progress);
9860 if (aTask.progress->completed())
9861 {
9862 /* the progress can be completed by a subtask only if there was
9863 * a failure */
9864 rc = aTask.progress->resultCode();
9865 Assert (FAILED(rc));
9866 errorInSubtask = true;
9867 throw rc;
9868 }
9869 }
9870
9871 RTTIMESPEC snapshotTimeStamp;
9872 RTTimeSpecSetMilli (&snapshotTimeStamp, 0);
9873
9874 {
9875 ComObjPtr<Snapshot> curSnapshot = mData->mCurrentSnapshot;
9876 AutoReadLock snapshotLock (curSnapshot);
9877
9878 /* remember the timestamp of the snapshot we're restoring from */
9879 snapshotTimeStamp = curSnapshot->getTimeStamp();
9880
9881 ComPtr<SnapshotMachine> pSnapshotMachine(curSnapshot->getSnapshotMachine());
9882
9883 /* copy all hardware data from the current snapshot */
9884 copyFrom(pSnapshotMachine);
9885
9886 LogFlowThisFunc(("Restoring hard disks from the snapshot...\n"));
9887
9888 /* restore the attachmends from the snapshot */
9889 mMediaData.backup();
9890 mMediaData->mAttachments = pSnapshotMachine->mMediaData->mAttachments;
9891
9892 /* leave the locks before the potentially lengthy operation */
9893 snapshotLock.unlock();
9894 alock.leave();
9895
9896 rc = createImplicitDiffs(mUserData->mSnapshotFolderFull,
9897 aTask.progress,
9898 1,
9899 false /* aOnline */);
9900
9901 alock.enter();
9902 snapshotLock.lock();
9903
9904 CheckComRCThrowRC(rc);
9905
9906 /* Note: on success, current (old) hard disks will be
9907 * deassociated/deleted on #commit() called from #saveSettings() at
9908 * the end. On failure, newly created implicit diffs will be
9909 * deleted by #rollback() at the end. */
9910
9911 /* should not have a saved state file associated at this point */
9912 Assert (mSSData->mStateFilePath.isNull());
9913
9914 if (curSnapshot->stateFilePath())
9915 {
9916 Utf8Str snapStateFilePath = curSnapshot->stateFilePath();
9917
9918 Utf8Str stateFilePath = Utf8StrFmt ("%ls%c{%RTuuid}.sav",
9919 mUserData->mSnapshotFolderFull.raw(),
9920 RTPATH_DELIMITER, mData->mUuid.raw());
9921
9922 LogFlowThisFunc(("Copying saved state file from '%s' to '%s'...\n",
9923 snapStateFilePath.raw(), stateFilePath.raw()));
9924
9925 aTask.progress->SetNextOperation(Bstr(tr("Restoring the execution state")),
9926 1); // weight
9927
9928 /* leave the lock before the potentially lengthy operation */
9929 snapshotLock.unlock();
9930 alock.leave();
9931
9932 /* copy the state file */
9933 int vrc = RTFileCopyEx(snapStateFilePath.c_str(),
9934 stateFilePath.c_str(),
9935 0,
9936 progressCallback,
9937 aTask.progress);
9938
9939 alock.enter();
9940 snapshotLock.lock();
9941
9942 if (RT_SUCCESS(vrc))
9943 {
9944 mSSData->mStateFilePath = stateFilePath;
9945 }
9946 else
9947 {
9948 throw setError(E_FAIL,
9949 tr("Could not copy the state file '%s' to '%s' (%Rrc)"),
9950 snapStateFilePath.raw(),
9951 stateFilePath.raw(),
9952 vrc);
9953 }
9954 }
9955 }
9956
9957 /* grab differencing hard disks from the old attachments that will
9958 * become unused and need to be auto-deleted */
9959
9960 std::list< ComObjPtr<Medium> > diffs;
9961
9962 for (MediaData::AttachmentList::const_iterator it = mMediaData.backedUpData()->mAttachments.begin();
9963 it != mMediaData.backedUpData()->mAttachments.end();
9964 ++it)
9965 {
9966 ComObjPtr<Medium> hd = (*it)->medium();
9967
9968 /* while the hard disk is attached, the number of children or the
9969 * parent cannot change, so no lock */
9970 if (!hd.isNull() && !hd->parent().isNull() && hd->children().size() == 0)
9971 diffs.push_back (hd);
9972 }
9973
9974 int saveFlags = 0;
9975
9976 if (aTask.discardCurrentSnapshot && isLastSnapshot)
9977 {
9978 /* commit changes to have unused diffs deassociated from this
9979 * machine before deletion (see below) */
9980 commit();
9981
9982 /* delete the unused diffs now (and uninit them) because discard
9983 * may fail otherwise (too many children of the hard disk to be
9984 * discarded) */
9985 for (std::list< ComObjPtr<Medium> >::const_iterator
9986 it = diffs.begin(); it != diffs.end(); ++it)
9987 {
9988 /// @todo for now, we ignore errors since we've already
9989 /// and therefore cannot fail. Later, we may want to report a
9990 /// warning through the Progress object
9991 HRESULT rc2 = (*it)->deleteStorageAndWait();
9992 if (SUCCEEDED(rc2))
9993 (*it)->uninit();
9994 }
9995
9996 /* prevent further deletion */
9997 diffs.clear();
9998
9999 /* discard the current snapshot and state task is in action, the
10000 * current snapshot is the last one. Discard the current snapshot
10001 * after discarding the current state. */
10002
10003 DiscardSnapshotTask subTask (aTask, mData->mCurrentSnapshot);
10004 subTask.subTask = true;
10005 discardSnapshotHandler (subTask);
10006
10007 AutoCaller progressCaller (aTask.progress);
10008 AutoReadLock progressLock (aTask.progress);
10009 if (aTask.progress->completed())
10010 {
10011 /* the progress can be completed by a subtask only if there
10012 * was a failure */
10013 rc = aTask.progress->resultCode();
10014 Assert (FAILED(rc));
10015 errorInSubtask = true;
10016 }
10017
10018 /* we've committed already, so inform callbacks anyway to ensure
10019 * they don't miss some change */
10020 /// @todo NEWMEDIA check if we need this informCallbacks at all
10021 /// after updating discardCurrentSnapshot functionality
10022 saveFlags |= SaveS_InformCallbacksAnyway;
10023 }
10024
10025 /* @todo saveSettings() below needs a VirtualBox write lock and we need
10026 * to leave this object's lock to do this to follow the {parent-child}
10027 * locking rule. This is the last chance to do that while we are still
10028 * in a protective state which allows us to temporarily leave the lock*/
10029 alock.unlock();
10030 vboxLock.lock();
10031 alock.lock();
10032
10033 /* we have already discarded the current state, so set the execution
10034 * state accordingly no matter of the discard snapshot result */
10035 if (mSSData->mStateFilePath)
10036 setMachineState (MachineState_Saved);
10037 else
10038 setMachineState (MachineState_PoweredOff);
10039
10040 updateMachineStateOnClient();
10041 stateRestored = true;
10042
10043 /* assign the timestamp from the snapshot */
10044 Assert (RTTimeSpecGetMilli (&snapshotTimeStamp) != 0);
10045 mData->mLastStateChange = snapshotTimeStamp;
10046
10047 /* save all settings, reset the modified flag and commit. Note that we
10048 * do so even if the subtask failed (errorInSubtask=true) because we've
10049 * already committed machine data and deleted old diffs before
10050 * discarding the current snapshot so there is no way to rollback */
10051 HRESULT rc2 = saveSettings(SaveS_ResetCurStateModified | saveFlags);
10052
10053 /// @todo NEWMEDIA return multiple errors
10054 if (errorInSubtask)
10055 throw rc;
10056
10057 rc = rc2;
10058
10059 if (SUCCEEDED(rc))
10060 {
10061 /* now, delete the unused diffs (only on success!) and uninit them*/
10062 for (std::list< ComObjPtr<Medium> >::const_iterator
10063 it = diffs.begin(); it != diffs.end(); ++it)
10064 {
10065 /// @todo for now, we ignore errors since we've already
10066 /// discarded and therefore cannot fail. Later, we may want to
10067 /// report a warning through the Progress object
10068 HRESULT rc2 = (*it)->deleteStorageAndWait();
10069 if (SUCCEEDED(rc2))
10070 (*it)->uninit();
10071 }
10072 }
10073 }
10074 catch (HRESULT aRC) { rc = aRC; }
10075
10076 if (FAILED (rc))
10077 {
10078 /* preserve existing error info */
10079 ErrorInfoKeeper eik;
10080
10081 if (!errorInSubtask)
10082 {
10083 /* undo all changes on failure unless the subtask has done so */
10084 rollback (false /* aNotify */);
10085 }
10086
10087 if (!stateRestored)
10088 {
10089 /* restore the machine state */
10090 setMachineState (aTask.state);
10091 updateMachineStateOnClient();
10092 }
10093 }
10094
10095 if (!errorInSubtask)
10096 {
10097 /* set the result (this will try to fetch current error info on failure) */
10098 aTask.progress->notifyComplete (rc);
10099 }
10100
10101 if (SUCCEEDED(rc))
10102 mParent->onSnapshotDiscarded (mData->mUuid, Guid());
10103
10104 LogFlowThisFunc(("Done discarding current state (rc=%08X)\n", rc));
10105
10106 LogFlowThisFuncLeave();
10107}
10108
10109/**
10110 * Locks the attached media.
10111 *
10112 * All attached hard disks are locked for writing and DVD/floppy are locked for
10113 * reading. Parents of attached hard disks (if any) are locked for reading.
10114 *
10115 * This method also performs accessibility check of all media it locks: if some
10116 * media is inaccessible, the method will return a failure and a bunch of
10117 * extended error info objects per each inaccessible medium.
10118 *
10119 * Note that this method is atomic: if it returns a success, all media are
10120 * locked as described above; on failure no media is locked at all (all
10121 * succeeded individual locks will be undone).
10122 *
10123 * This method is intended to be called when the machine is in Starting or
10124 * Restoring state and asserts otherwise.
10125 *
10126 * The locks made by this method must be undone by calling #unlockMedia() when
10127 * no more needed.
10128 */
10129HRESULT SessionMachine::lockMedia()
10130{
10131 AutoCaller autoCaller(this);
10132 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
10133
10134 AutoWriteLock alock(this);
10135
10136 AssertReturn(mData->mMachineState == MachineState_Starting ||
10137 mData->mMachineState == MachineState_Restoring, E_FAIL);
10138
10139 typedef std::list <ComPtr<IMedium> > MediaList;
10140 MediaList mediaToCheck;
10141 MediumState_T mediaState;
10142
10143 try
10144 {
10145 HRESULT rc = S_OK;
10146
10147 /* lock all medium objects attached to the VM */
10148 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
10149 it != mMediaData->mAttachments.end();
10150 ++it)
10151 {
10152 DeviceType_T devType = (*it)->type();
10153 ComObjPtr<Medium> hd = (*it)->medium();
10154
10155 bool first = true;
10156
10157 /** @todo split out the media locking, and put it into
10158 * MediumImpl.cpp, as it needs this functionality too. */
10159 while (!hd.isNull())
10160 {
10161 if (first)
10162 {
10163 if (devType != DeviceType_DVD)
10164 {
10165 /* HardDisk and Floppy medium must be locked for writing */
10166 rc = hd->LockWrite(&mediaState);
10167 CheckComRCThrowRC(rc);
10168 }
10169 else
10170 {
10171 /* DVD medium must be locked for reading */
10172 rc = hd->LockRead(&mediaState);
10173 CheckComRCThrowRC(rc);
10174 }
10175
10176 mData->mSession.mLockedMedia.push_back (
10177 Data::Session::LockedMedia::value_type (
10178 ComPtr<IMedium> (hd), true));
10179
10180 first = false;
10181 }
10182 else
10183 {
10184 rc = hd->LockRead (&mediaState);
10185 CheckComRCThrowRC(rc);
10186
10187 mData->mSession.mLockedMedia.push_back (
10188 Data::Session::LockedMedia::value_type (
10189 ComPtr<IMedium> (hd), false));
10190 }
10191
10192 if (mediaState == MediumState_Inaccessible)
10193 mediaToCheck.push_back (ComPtr<IMedium> (hd));
10194
10195 /* no locks or callers here since there should be no way to
10196 * change the hard disk parent at this point (as it is still
10197 * attached to the machine) */
10198 hd = hd->parent();
10199 }
10200 }
10201
10202 /* SUCCEEDED locking all media, now check accessibility */
10203
10204 ErrorInfoKeeper eik (true /* aIsNull */);
10205 MultiResult mrc (S_OK);
10206
10207 /* perform a check of inaccessible media deferred above */
10208 for (MediaList::const_iterator
10209 it = mediaToCheck.begin();
10210 it != mediaToCheck.end(); ++it)
10211 {
10212 MediumState_T mediaState;
10213 rc = (*it)->COMGETTER(State) (&mediaState);
10214 CheckComRCThrowRC(rc);
10215
10216 Assert (mediaState == MediumState_LockedRead ||
10217 mediaState == MediumState_LockedWrite);
10218
10219 /* Note that we locked the medium already, so use the error
10220 * value to see if there was an accessibility failure */
10221
10222 Bstr error;
10223 rc = (*it)->COMGETTER(LastAccessError) (error.asOutParam());
10224 CheckComRCThrowRC(rc);
10225
10226 if (!error.isEmpty())
10227 {
10228 Bstr loc;
10229 rc = (*it)->COMGETTER(Location) (loc.asOutParam());
10230 CheckComRCThrowRC(rc);
10231
10232 /* collect multiple errors */
10233 eik.restore();
10234
10235 /* be in sync with MediumBase::setStateError() */
10236 Assert (!error.isEmpty());
10237 mrc = setError(E_FAIL,
10238 tr("Medium '%ls' is not accessible. %ls"),
10239 loc.raw(),
10240 error.raw());
10241
10242 eik.fetch();
10243 }
10244 }
10245
10246 eik.restore();
10247 CheckComRCThrowRC((HRESULT) mrc);
10248 }
10249 catch (HRESULT aRC)
10250 {
10251 /* Unlock all locked media on failure */
10252 unlockMedia();
10253 return aRC;
10254 }
10255
10256 return S_OK;
10257}
10258
10259/**
10260 * Undoes the locks made by by #lockMedia().
10261 */
10262void SessionMachine::unlockMedia()
10263{
10264 AutoCaller autoCaller(this);
10265 AssertComRCReturnVoid (autoCaller.rc());
10266
10267 AutoWriteLock alock(this);
10268
10269 /* we may be holding important error info on the current thread;
10270 * preserve it */
10271 ErrorInfoKeeper eik;
10272
10273 HRESULT rc = S_OK;
10274
10275 for (Data::Session::LockedMedia::const_iterator
10276 it = mData->mSession.mLockedMedia.begin();
10277 it != mData->mSession.mLockedMedia.end(); ++it)
10278 {
10279 MediumState_T state;
10280 if (it->second)
10281 rc = it->first->UnlockWrite (&state);
10282 else
10283 rc = it->first->UnlockRead (&state);
10284
10285 /* The second can happen if an object was re-locked in
10286 * Machine::fixupMedia(). The last can happen when e.g a DVD/Floppy
10287 * image was unmounted at runtime. */
10288 Assert (SUCCEEDED(rc) || state == MediumState_LockedRead || state == MediumState_Created);
10289 }
10290
10291 mData->mSession.mLockedMedia.clear();
10292}
10293
10294/**
10295 * Helper to change the machine state (reimplementation).
10296 *
10297 * @note Locks this object for writing.
10298 */
10299HRESULT SessionMachine::setMachineState (MachineState_T aMachineState)
10300{
10301 LogFlowThisFuncEnter();
10302 LogFlowThisFunc(("aMachineState=%d\n", aMachineState));
10303
10304 AutoCaller autoCaller(this);
10305 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
10306
10307 AutoWriteLock alock(this);
10308
10309 MachineState_T oldMachineState = mData->mMachineState;
10310
10311 AssertMsgReturn (oldMachineState != aMachineState,
10312 ("oldMachineState=%d, aMachineState=%d\n",
10313 oldMachineState, aMachineState), E_FAIL);
10314
10315 HRESULT rc = S_OK;
10316
10317 int stsFlags = 0;
10318 bool deleteSavedState = false;
10319
10320 /* detect some state transitions */
10321
10322 if ((oldMachineState == MachineState_Saved &&
10323 aMachineState == MachineState_Restoring) ||
10324 (oldMachineState < MachineState_Running /* any other OFF state */ &&
10325 aMachineState == MachineState_Starting))
10326 {
10327 /* The EMT thread is about to start */
10328
10329 /* Nothing to do here for now... */
10330
10331 /// @todo NEWMEDIA don't let mDVDDrive and other children
10332 /// change anything when in the Starting/Restoring state
10333 }
10334 else
10335 if (oldMachineState >= MachineState_Running &&
10336 oldMachineState != MachineState_Discarding &&
10337 oldMachineState != MachineState_SettingUp &&
10338 aMachineState < MachineState_Running &&
10339 /* ignore PoweredOff->Saving->PoweredOff transition when taking a
10340 * snapshot */
10341 (mSnapshotData.mSnapshot.isNull() ||
10342 mSnapshotData.mLastState >= MachineState_Running))
10343 {
10344 /* The EMT thread has just stopped, unlock attached media. Note that as
10345 * opposed to locking that is done from Console, we do unlocking here
10346 * because the VM process may have aborted before having a chance to
10347 * properly unlock all media it locked. */
10348
10349 unlockMedia();
10350 }
10351
10352 if (oldMachineState == MachineState_Restoring)
10353 {
10354 if (aMachineState != MachineState_Saved)
10355 {
10356 /*
10357 * delete the saved state file once the machine has finished
10358 * restoring from it (note that Console sets the state from
10359 * Restoring to Saved if the VM couldn't restore successfully,
10360 * to give the user an ability to fix an error and retry --
10361 * we keep the saved state file in this case)
10362 */
10363 deleteSavedState = true;
10364 }
10365 }
10366 else
10367 if (oldMachineState == MachineState_Saved &&
10368 (aMachineState == MachineState_PoweredOff ||
10369 aMachineState == MachineState_Aborted))
10370 {
10371 /*
10372 * delete the saved state after Console::DiscardSavedState() is called
10373 * or if the VM process (owning a direct VM session) crashed while the
10374 * VM was Saved
10375 */
10376
10377 /// @todo (dmik)
10378 // Not sure that deleting the saved state file just because of the
10379 // client death before it attempted to restore the VM is a good
10380 // thing. But when it crashes we need to go to the Aborted state
10381 // which cannot have the saved state file associated... The only
10382 // way to fix this is to make the Aborted condition not a VM state
10383 // but a bool flag: i.e., when a crash occurs, set it to true and
10384 // change the state to PoweredOff or Saved depending on the
10385 // saved state presence.
10386
10387 deleteSavedState = true;
10388 mData->mCurrentStateModified = TRUE;
10389 stsFlags |= SaveSTS_CurStateModified;
10390 }
10391
10392 if (aMachineState == MachineState_Starting ||
10393 aMachineState == MachineState_Restoring)
10394 {
10395 /* set the current state modified flag to indicate that the current
10396 * state is no more identical to the state in the
10397 * current snapshot */
10398 if (!mData->mCurrentSnapshot.isNull())
10399 {
10400 mData->mCurrentStateModified = TRUE;
10401 stsFlags |= SaveSTS_CurStateModified;
10402 }
10403 }
10404
10405 if (deleteSavedState)
10406 {
10407 if (mRemoveSavedState)
10408 {
10409 Assert (!mSSData->mStateFilePath.isEmpty());
10410 RTFileDelete(Utf8Str(mSSData->mStateFilePath).c_str());
10411 }
10412 mSSData->mStateFilePath.setNull();
10413 stsFlags |= SaveSTS_StateFilePath;
10414 }
10415
10416 /* redirect to the underlying peer machine */
10417 mPeer->setMachineState (aMachineState);
10418
10419 if (aMachineState == MachineState_PoweredOff ||
10420 aMachineState == MachineState_Aborted ||
10421 aMachineState == MachineState_Saved)
10422 {
10423 /* the machine has stopped execution
10424 * (or the saved state file was adopted) */
10425 stsFlags |= SaveSTS_StateTimeStamp;
10426 }
10427
10428 if ((oldMachineState == MachineState_PoweredOff ||
10429 oldMachineState == MachineState_Aborted) &&
10430 aMachineState == MachineState_Saved)
10431 {
10432 /* the saved state file was adopted */
10433 Assert (!mSSData->mStateFilePath.isNull());
10434 stsFlags |= SaveSTS_StateFilePath;
10435 }
10436
10437 rc = saveStateSettings (stsFlags);
10438
10439 if ((oldMachineState != MachineState_PoweredOff &&
10440 oldMachineState != MachineState_Aborted) &&
10441 (aMachineState == MachineState_PoweredOff ||
10442 aMachineState == MachineState_Aborted))
10443 {
10444 /* we've been shut down for any reason */
10445 /* no special action so far */
10446 }
10447
10448 LogFlowThisFunc(("rc=%08X\n", rc));
10449 LogFlowThisFuncLeave();
10450 return rc;
10451}
10452
10453/**
10454 * Sends the current machine state value to the VM process.
10455 *
10456 * @note Locks this object for reading, then calls a client process.
10457 */
10458HRESULT SessionMachine::updateMachineStateOnClient()
10459{
10460 AutoCaller autoCaller(this);
10461 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
10462
10463 ComPtr<IInternalSessionControl> directControl;
10464 {
10465 AutoReadLock alock(this);
10466 AssertReturn(!!mData, E_FAIL);
10467 directControl = mData->mSession.mDirectControl;
10468
10469 /* directControl may be already set to NULL here in #OnSessionEnd()
10470 * called too early by the direct session process while there is still
10471 * some operation (like discarding the snapshot) in progress. The client
10472 * process in this case is waiting inside Session::close() for the
10473 * "end session" process object to complete, while #uninit() called by
10474 * #checkForDeath() on the Watcher thread is waiting for the pending
10475 * operation to complete. For now, we accept this inconsitent behavior
10476 * and simply do nothing here. */
10477
10478 if (mData->mSession.mState == SessionState_Closing)
10479 return S_OK;
10480
10481 AssertReturn(!directControl.isNull(), E_FAIL);
10482 }
10483
10484 return directControl->UpdateMachineState (mData->mMachineState);
10485}
10486
10487/* static */
10488DECLCALLBACK(int) SessionMachine::taskHandler (RTTHREAD /* thread */, void *pvUser)
10489{
10490 AssertReturn(pvUser, VERR_INVALID_POINTER);
10491
10492 Task *task = static_cast <Task *> (pvUser);
10493 task->handler();
10494
10495 // it's our responsibility to delete the task
10496 delete task;
10497
10498 return 0;
10499}
10500
10501/////////////////////////////////////////////////////////////////////////////
10502// SnapshotMachine class
10503/////////////////////////////////////////////////////////////////////////////
10504
10505DEFINE_EMPTY_CTOR_DTOR (SnapshotMachine)
10506
10507HRESULT SnapshotMachine::FinalConstruct()
10508{
10509 LogFlowThisFunc(("\n"));
10510
10511 /* set the proper type to indicate we're the SnapshotMachine instance */
10512 unconst(mType) = IsSnapshotMachine;
10513
10514 return S_OK;
10515}
10516
10517void SnapshotMachine::FinalRelease()
10518{
10519 LogFlowThisFunc(("\n"));
10520
10521 uninit();
10522}
10523
10524/**
10525 * Initializes the SnapshotMachine object when taking a snapshot.
10526 *
10527 * @param aSessionMachine machine to take a snapshot from
10528 * @param aSnapshotId snapshot ID of this snapshot machine
10529 * @param aStateFilePath file where the execution state will be later saved
10530 * (or NULL for the offline snapshot)
10531 *
10532 * @note The aSessionMachine must be locked for writing.
10533 */
10534HRESULT SnapshotMachine::init(SessionMachine *aSessionMachine,
10535 IN_GUID aSnapshotId,
10536 const Utf8Str &aStateFilePath)
10537{
10538 LogFlowThisFuncEnter();
10539 LogFlowThisFunc(("mName={%ls}\n", aSessionMachine->mUserData->mName.raw()));
10540
10541 AssertReturn(aSessionMachine && !Guid (aSnapshotId).isEmpty(), E_INVALIDARG);
10542
10543 /* Enclose the state transition NotReady->InInit->Ready */
10544 AutoInitSpan autoInitSpan(this);
10545 AssertReturn(autoInitSpan.isOk(), E_FAIL);
10546
10547 AssertReturn(aSessionMachine->isWriteLockOnCurrentThread(), E_FAIL);
10548
10549 mSnapshotId = aSnapshotId;
10550
10551 /* memorize the primary Machine instance (i.e. not SessionMachine!) */
10552 unconst(mPeer) = aSessionMachine->mPeer;
10553 /* share the parent pointer */
10554 unconst(mParent) = mPeer->mParent;
10555
10556 /* take the pointer to Data to share */
10557 mData.share (mPeer->mData);
10558
10559 /* take the pointer to UserData to share (our UserData must always be the
10560 * same as Machine's data) */
10561 mUserData.share (mPeer->mUserData);
10562 /* make a private copy of all other data (recent changes from SessionMachine) */
10563 mHWData.attachCopy (aSessionMachine->mHWData);
10564 mMediaData.attachCopy(aSessionMachine->mMediaData);
10565
10566 /* SSData is always unique for SnapshotMachine */
10567 mSSData.allocate();
10568 mSSData->mStateFilePath = aStateFilePath;
10569
10570 HRESULT rc = S_OK;
10571
10572 /* create copies of all shared folders (mHWData after attiching a copy
10573 * contains just references to original objects) */
10574 for (HWData::SharedFolderList::iterator
10575 it = mHWData->mSharedFolders.begin();
10576 it != mHWData->mSharedFolders.end();
10577 ++it)
10578 {
10579 ComObjPtr<SharedFolder> folder;
10580 folder.createObject();
10581 rc = folder->initCopy (this, *it);
10582 CheckComRCReturnRC(rc);
10583 *it = folder;
10584 }
10585
10586 /* associate hard disks with the snapshot
10587 * (Machine::uninitDataAndChildObjects() will deassociate at destruction) */
10588 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
10589 it != mMediaData->mAttachments.end();
10590 ++it)
10591 {
10592 MediumAttachment *pAtt = *it;
10593 Medium *pMedium = pAtt->medium();
10594 if (pMedium) // can be NULL for non-harddisk
10595 {
10596 rc = pMedium->attachTo(mData->mUuid, mSnapshotId);
10597 AssertComRC(rc);
10598 }
10599 }
10600
10601 /* create copies of all storage controllers (mStorageControllerData
10602 * after attaching a copy contains just references to original objects) */
10603 mStorageControllers.allocate();
10604 for (StorageControllerList::const_iterator
10605 it = aSessionMachine->mStorageControllers->begin();
10606 it != aSessionMachine->mStorageControllers->end();
10607 ++it)
10608 {
10609 ComObjPtr<StorageController> ctrl;
10610 ctrl.createObject();
10611 ctrl->initCopy (this, *it);
10612 mStorageControllers->push_back(ctrl);
10613 }
10614
10615 /* create all other child objects that will be immutable private copies */
10616
10617 unconst(mBIOSSettings).createObject();
10618 mBIOSSettings->initCopy (this, mPeer->mBIOSSettings);
10619
10620#ifdef VBOX_WITH_VRDP
10621 unconst(mVRDPServer).createObject();
10622 mVRDPServer->initCopy (this, mPeer->mVRDPServer);
10623#endif
10624
10625 unconst(mAudioAdapter).createObject();
10626 mAudioAdapter->initCopy (this, mPeer->mAudioAdapter);
10627
10628 unconst(mUSBController).createObject();
10629 mUSBController->initCopy (this, mPeer->mUSBController);
10630
10631 for (ULONG slot = 0; slot < RT_ELEMENTS (mNetworkAdapters); slot ++)
10632 {
10633 unconst(mNetworkAdapters [slot]).createObject();
10634 mNetworkAdapters [slot]->initCopy (this, mPeer->mNetworkAdapters [slot]);
10635 }
10636
10637 for (ULONG slot = 0; slot < RT_ELEMENTS (mSerialPorts); slot ++)
10638 {
10639 unconst(mSerialPorts [slot]).createObject();
10640 mSerialPorts [slot]->initCopy (this, mPeer->mSerialPorts [slot]);
10641 }
10642
10643 for (ULONG slot = 0; slot < RT_ELEMENTS (mParallelPorts); slot ++)
10644 {
10645 unconst(mParallelPorts [slot]).createObject();
10646 mParallelPorts [slot]->initCopy (this, mPeer->mParallelPorts [slot]);
10647 }
10648
10649 /* Confirm a successful initialization when it's the case */
10650 autoInitSpan.setSucceeded();
10651
10652 LogFlowThisFuncLeave();
10653 return S_OK;
10654}
10655
10656/**
10657 * Initializes the SnapshotMachine object when loading from the settings file.
10658 *
10659 * @param aMachine machine the snapshot belngs to
10660 * @param aHWNode <Hardware> node
10661 * @param aHDAsNode <HardDiskAttachments> node
10662 * @param aSnapshotId snapshot ID of this snapshot machine
10663 * @param aStateFilePath file where the execution state is saved
10664 * (or NULL for the offline snapshot)
10665 *
10666 * @note Doesn't lock anything.
10667 */
10668HRESULT SnapshotMachine::init(Machine *aMachine,
10669 const settings::Hardware &hardware,
10670 const settings::Storage &storage,
10671 IN_GUID aSnapshotId,
10672 const Utf8Str &aStateFilePath)
10673{
10674 LogFlowThisFuncEnter();
10675 LogFlowThisFunc(("mName={%ls}\n", aMachine->mUserData->mName.raw()));
10676
10677 AssertReturn(aMachine && !Guid(aSnapshotId).isEmpty(), E_INVALIDARG);
10678
10679 /* Enclose the state transition NotReady->InInit->Ready */
10680 AutoInitSpan autoInitSpan(this);
10681 AssertReturn(autoInitSpan.isOk(), E_FAIL);
10682
10683 /* Don't need to lock aMachine when VirtualBox is starting up */
10684
10685 mSnapshotId = aSnapshotId;
10686
10687 /* memorize the primary Machine instance */
10688 unconst(mPeer) = aMachine;
10689 /* share the parent pointer */
10690 unconst(mParent) = mPeer->mParent;
10691
10692 /* take the pointer to Data to share */
10693 mData.share (mPeer->mData);
10694 /*
10695 * take the pointer to UserData to share
10696 * (our UserData must always be the same as Machine's data)
10697 */
10698 mUserData.share (mPeer->mUserData);
10699 /* allocate private copies of all other data (will be loaded from settings) */
10700 mHWData.allocate();
10701 mMediaData.allocate();
10702 mStorageControllers.allocate();
10703
10704 /* SSData is always unique for SnapshotMachine */
10705 mSSData.allocate();
10706 mSSData->mStateFilePath = aStateFilePath;
10707
10708 /* create all other child objects that will be immutable private copies */
10709
10710 unconst(mBIOSSettings).createObject();
10711 mBIOSSettings->init (this);
10712
10713#ifdef VBOX_WITH_VRDP
10714 unconst(mVRDPServer).createObject();
10715 mVRDPServer->init (this);
10716#endif
10717
10718 unconst(mAudioAdapter).createObject();
10719 mAudioAdapter->init (this);
10720
10721 unconst(mUSBController).createObject();
10722 mUSBController->init (this);
10723
10724 for (ULONG slot = 0; slot < RT_ELEMENTS (mNetworkAdapters); slot ++)
10725 {
10726 unconst(mNetworkAdapters [slot]).createObject();
10727 mNetworkAdapters [slot]->init (this, slot);
10728 }
10729
10730 for (ULONG slot = 0; slot < RT_ELEMENTS (mSerialPorts); slot ++)
10731 {
10732 unconst(mSerialPorts [slot]).createObject();
10733 mSerialPorts [slot]->init (this, slot);
10734 }
10735
10736 for (ULONG slot = 0; slot < RT_ELEMENTS (mParallelPorts); slot ++)
10737 {
10738 unconst(mParallelPorts [slot]).createObject();
10739 mParallelPorts [slot]->init (this, slot);
10740 }
10741
10742 /* load hardware and harddisk settings */
10743
10744 HRESULT rc = loadHardware(hardware);
10745 if (SUCCEEDED(rc))
10746 rc = loadStorageControllers(storage, true /* aRegistered */, &mSnapshotId);
10747
10748 if (SUCCEEDED(rc))
10749 /* commit all changes made during the initialization */
10750 commit();
10751
10752 /* Confirm a successful initialization when it's the case */
10753 if (SUCCEEDED(rc))
10754 autoInitSpan.setSucceeded();
10755
10756 LogFlowThisFuncLeave();
10757 return rc;
10758}
10759
10760/**
10761 * Uninitializes this SnapshotMachine object.
10762 */
10763void SnapshotMachine::uninit()
10764{
10765 LogFlowThisFuncEnter();
10766
10767 /* Enclose the state transition Ready->InUninit->NotReady */
10768 AutoUninitSpan autoUninitSpan(this);
10769 if (autoUninitSpan.uninitDone())
10770 return;
10771
10772 uninitDataAndChildObjects();
10773
10774 /* free the essential data structure last */
10775 mData.free();
10776
10777 unconst(mParent).setNull();
10778 unconst(mPeer).setNull();
10779
10780 LogFlowThisFuncLeave();
10781}
10782
10783// util::Lockable interface
10784////////////////////////////////////////////////////////////////////////////////
10785
10786/**
10787 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
10788 * with the primary Machine instance (mPeer).
10789 */
10790RWLockHandle *SnapshotMachine::lockHandle() const
10791{
10792 AssertReturn(!mPeer.isNull(), NULL);
10793 return mPeer->lockHandle();
10794}
10795
10796// public methods only for internal purposes
10797////////////////////////////////////////////////////////////////////////////////
10798
10799/**
10800 * Called by the snapshot object associated with this SnapshotMachine when
10801 * snapshot data such as name or description is changed.
10802 *
10803 * @note Locks this object for writing.
10804 */
10805HRESULT SnapshotMachine::onSnapshotChange (Snapshot *aSnapshot)
10806{
10807 AutoWriteLock alock(this);
10808
10809 // mPeer->saveAllSnapshots(); @todo
10810
10811 /* inform callbacks */
10812 mParent->onSnapshotChange(mData->mUuid, aSnapshot->getId());
10813
10814 return S_OK;
10815}
10816/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette