VirtualBox

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

Last change on this file since 5161 was 5118, checked in by vboxsync, 18 years ago

Main: Added checking for errors when initializing NetworkAdapter and AudioAdapter classes from the settings file; Improved inaccessible VM handling (could show a wrong message as a last access error).

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

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