VirtualBox

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

Last change on this file since 18599 was 18572, checked in by vboxsync, 16 years ago

Main: fixed a problem where the machine directory is not deleted.
r45374 fixed #3548 but Machine::DeleteSettings() expects that
config file exists and are locked before they can be deleted,
and so lock them first.

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

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