VirtualBox

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

Last change on this file since 5659 was 5627, checked in by vboxsync, 17 years ago

Main: Improved Machine incapsulation by removing data(), userData(), hwData(), hdData() and other similar methods which also fixed the VBoxSVC crash when changing a setting of a valid VM through VBoxManage if there were one or more inaccessible VMs (#2466).

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