VirtualBox

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

Last change on this file since 5881 was 5777, checked in by vboxsync, 17 years ago

Main: Fixed a dedalock (Machine::AttachHardDisk() calledl VirtualBox with locking which violated the lock order (parents->self->children) and caused a deadlock when VirtualBox tried to lock Machine in clientWatcherThread()).

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

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