VirtualBox

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

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

Main: GCC warning.

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

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