VirtualBox

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

Last change on this file since 4968 was 4859, checked in by vboxsync, 17 years ago

Main: Renamed <Machine>/<Guest> to <Machine>/<Hardware>/<Guest> in the settings file, for similarity with other elements. Please remove <Guest> elements from your existing machine .xml files, as this change breaks compatibility.

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