VirtualBox

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

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

Added custom line speed setting to XML/COM/CFGM. Hope I haven't forgotten anything.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 336.3 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.215389.xyz. 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 /* line speed (defaults to 100 Mbps) */
4378 uint32_t lineSpeed = 100000;
4379 CFGLDRQueryUInt32 (adapterNode, "speed", &lineSpeed);
4380 /* tracing (defaults to false) */
4381 bool traceEnabled;
4382 CFGLDRQueryBool (adapterNode, "trace", &traceEnabled);
4383 Bstr traceFile;
4384 CFGLDRQueryBSTR (adapterNode, "tracefile", traceFile.asOutParam());
4385
4386 mNetworkAdapters [slot]->COMSETTER(Enabled) (enabled);
4387 mNetworkAdapters [slot]->COMSETTER(MACAddress) (macAddr);
4388 mNetworkAdapters [slot]->COMSETTER(CableConnected) (cableConnected);
4389 mNetworkAdapters [slot]->COMSETTER(LineSpeed) (lineSpeed);
4390 mNetworkAdapters [slot]->COMSETTER(TraceEnabled) (traceEnabled);
4391 mNetworkAdapters [slot]->COMSETTER(TraceFile) (traceFile);
4392
4393 if (adapterType.compare(Bstr("Am79C970A")) == 0)
4394 mNetworkAdapters [slot]->COMSETTER(AdapterType)(NetworkAdapterType_NetworkAdapterAm79C970A);
4395 else if (adapterType.compare(Bstr("Am79C973")) == 0)
4396 mNetworkAdapters [slot]->COMSETTER(AdapterType)(NetworkAdapterType_NetworkAdapterAm79C973);
4397 else
4398 ComAssertBreak (0, rc = E_FAIL);
4399
4400 CFGNODE attachmentNode = 0;
4401 if (CFGLDRGetChildNode (adapterNode, "NAT", 0, &attachmentNode), attachmentNode)
4402 {
4403 mNetworkAdapters [slot]->AttachToNAT();
4404 }
4405 else
4406 if (CFGLDRGetChildNode (adapterNode, "HostInterface", 0, &attachmentNode), attachmentNode)
4407 {
4408 /* Host Interface Networking */
4409 Bstr name;
4410 CFGLDRQueryBSTR (attachmentNode, "name", name.asOutParam());
4411#ifdef RT_OS_WINDOWS
4412 /* @name can be empty on Win32, but not null */
4413 ComAssertBreak (!name.isNull(), rc = E_FAIL);
4414#endif
4415 mNetworkAdapters [slot]->COMSETTER(HostInterface) (name);
4416#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
4417 Bstr tapSetupApp;
4418 CFGLDRQueryBSTR (attachmentNode, "TAPSetup", tapSetupApp.asOutParam());
4419 Bstr tapTerminateApp;
4420 CFGLDRQueryBSTR (attachmentNode, "TAPTerminate", tapTerminateApp.asOutParam());
4421
4422 mNetworkAdapters [slot]->COMSETTER(TAPSetupApplication) (tapSetupApp);
4423 mNetworkAdapters [slot]->COMSETTER(TAPTerminateApplication) (tapTerminateApp);
4424#endif // VBOX_WITH_UNIXY_TAP_NETWORKING
4425 mNetworkAdapters [slot]->AttachToHostInterface();
4426 }
4427 else
4428 if (CFGLDRGetChildNode(adapterNode, "InternalNetwork", 0, &attachmentNode), attachmentNode)
4429 {
4430 /* Internal Networking */
4431 Bstr name;
4432 CFGLDRQueryBSTR (attachmentNode, "name", name.asOutParam());
4433 ComAssertBreak (!name.isNull(), rc = E_FAIL);
4434 mNetworkAdapters[slot]->AttachToInternalNetwork();
4435 mNetworkAdapters[slot]->COMSETTER(InternalNetwork) (name);
4436 }
4437 else
4438 {
4439 /* Adapter has no children */
4440 mNetworkAdapters [slot]->Detach();
4441 }
4442 if (attachmentNode)
4443 CFGLDRReleaseNode (attachmentNode);
4444
4445 CFGLDRReleaseNode (adapterNode);
4446 }
4447
4448 CFGLDRReleaseNode (networkNode);
4449 if (FAILED (rc))
4450 return rc;
4451 }
4452
4453 /* Serial node (optional) */
4454 CFGNODE serialNode = 0;
4455 CFGLDRGetChildNode (aNode, "Uart", 0, &serialNode);
4456 if (serialNode)
4457 {
4458 HRESULT rc = S_OK;
4459 unsigned cPorts = 0;
4460 CFGLDRCountChildren (serialNode, "Port", &cPorts);
4461 for (unsigned slot = 0; slot < cPorts; slot++)
4462 {
4463 rc = mSerialPorts [slot]->loadSettings (serialNode, slot);
4464 CheckComRCReturnRC (rc);
4465 }
4466 CFGLDRReleaseNode (serialNode);
4467 }
4468
4469 /* Parallel node (optional) */
4470 CFGNODE parallelNode = 0;
4471 CFGLDRGetChildNode (aNode, "Lpt", 0, &parallelNode);
4472 if (parallelNode)
4473 {
4474 HRESULT rc = S_OK;
4475 unsigned cPorts = 0;
4476 CFGLDRCountChildren (parallelNode, "Port", &cPorts);
4477 for (unsigned slot = 0; slot < cPorts; slot++)
4478 {
4479 rc = mParallelPorts [slot]->loadSettings (parallelNode, slot);
4480 CheckComRCReturnRC (rc);
4481 }
4482 CFGLDRReleaseNode (parallelNode);
4483 }
4484
4485 /* AudioAdapter node (required) */
4486 /// @todo (dmik) move the code to AudioAdapter
4487 {
4488 CFGNODE audioAdapterNode = 0;
4489 CFGLDRGetChildNode (aNode, "AudioAdapter", 0, &audioAdapterNode);
4490 ComAssertRet (audioAdapterNode, E_FAIL);
4491
4492 // is the adapter enabled?
4493 bool enabled = false;
4494 CFGLDRQueryBool (audioAdapterNode, "enabled", &enabled);
4495 mAudioAdapter->COMSETTER(Enabled) (enabled);
4496 // now check the audio driver
4497 Bstr driver;
4498 CFGLDRQueryBSTR (audioAdapterNode, "driver", driver.asOutParam());
4499 AudioDriverType_T audioDriver;
4500 audioDriver = AudioDriverType_NullAudioDriver;
4501 if (driver == L"null")
4502 ; // Null has been set above
4503#ifdef RT_OS_WINDOWS
4504 else if (driver == L"winmm")
4505#ifdef VBOX_WITH_WINMM
4506 audioDriver = AudioDriverType_WINMMAudioDriver;
4507#else
4508 // fall back to dsound
4509 audioDriver = AudioDriverType_DSOUNDAudioDriver;
4510#endif
4511 else if (driver == L"dsound")
4512 audioDriver = AudioDriverType_DSOUNDAudioDriver;
4513#endif // RT_OS_WINDOWS
4514#ifdef RT_OS_LINUX
4515 else if (driver == L"oss")
4516 audioDriver = AudioDriverType_OSSAudioDriver;
4517 else if (driver == L"alsa")
4518#ifdef VBOX_WITH_ALSA
4519 audioDriver = AudioDriverType_ALSAAudioDriver;
4520#else
4521 // fall back to OSS
4522 audioDriver = AudioDriverType_OSSAudioDriver;
4523#endif
4524#endif // RT_OS_LINUX
4525#ifdef RT_OS_DARWIN
4526 else if (driver == L"coreaudio")
4527 audioDriver = AudioDriverType_CoreAudioDriver;
4528#endif
4529#ifdef RT_OS_OS2
4530 else if (driver == L"mmpm")
4531 audioDriver = AudioDriverType_MMPMAudioDriver;
4532#endif
4533 else
4534 AssertMsgFailed (("Invalid driver: %ls\n", driver.raw()));
4535 mAudioAdapter->COMSETTER(AudioDriver) (audioDriver);
4536
4537 CFGLDRReleaseNode (audioAdapterNode);
4538 }
4539
4540 /* Shared folders (optional) */
4541 /// @todo (dmik) make required on next format change!
4542 do
4543 {
4544 CFGNODE sharedFoldersNode = 0;
4545 CFGLDRGetChildNode (aNode, "SharedFolders", 0, &sharedFoldersNode);
4546
4547 if (!sharedFoldersNode)
4548 break;
4549
4550 HRESULT rc = S_OK;
4551
4552 unsigned cFolders = 0;
4553 CFGLDRCountChildren (sharedFoldersNode, "SharedFolder", &cFolders);
4554
4555 for (unsigned i = 0; i < cFolders; i++)
4556 {
4557 CFGNODE folderNode = 0;
4558 CFGLDRGetChildNode (sharedFoldersNode, "SharedFolder", i, &folderNode);
4559 ComAssertBreak (folderNode, rc = E_FAIL);
4560
4561 // folder logical name (required)
4562 Bstr name;
4563 CFGLDRQueryBSTR (folderNode, "name", name.asOutParam());
4564
4565 // folder host path (required)
4566 Bstr hostPath;
4567 CFGLDRQueryBSTR (folderNode, "hostPath", hostPath.asOutParam());
4568
4569 rc = CreateSharedFolder (name, hostPath);
4570 if (FAILED (rc))
4571 break;
4572
4573 CFGLDRReleaseNode (folderNode);
4574 }
4575
4576 CFGLDRReleaseNode (sharedFoldersNode);
4577 if (FAILED (rc))
4578 return rc;
4579 }
4580 while (0);
4581
4582 /* Clipboard node (currently not required) */
4583 /// @todo (dmik) make required on next format change!
4584 {
4585 /* default value in case the node is not there */
4586 mHWData->mClipboardMode = ClipboardMode_ClipDisabled;
4587
4588 CFGNODE clipNode = 0;
4589 CFGLDRGetChildNode (aNode, "Clipboard", 0, &clipNode);
4590 if (clipNode)
4591 {
4592 Bstr mode;
4593 CFGLDRQueryBSTR (clipNode, "mode", mode.asOutParam());
4594 if (mode == L"Disabled")
4595 mHWData->mClipboardMode = ClipboardMode_ClipDisabled;
4596 else if (mode == L"HostToGuest")
4597 mHWData->mClipboardMode = ClipboardMode_ClipHostToGuest;
4598 else if (mode == L"GuestToHost")
4599 mHWData->mClipboardMode = ClipboardMode_ClipGuestToHost;
4600 else if (mode == L"Bidirectional")
4601 mHWData->mClipboardMode = ClipboardMode_ClipBidirectional;
4602 else
4603 AssertMsgFailed (("%ls clipboard mode is invalid\n", mode.raw()));
4604 CFGLDRReleaseNode (clipNode);
4605 }
4606 }
4607
4608 /* Guest node (optional) */
4609 /// @todo (dmik) make required on next format change!
4610 {
4611 CFGNODE guestNode = 0;
4612 CFGLDRGetChildNode (aNode, "Guest", 0, &guestNode);
4613 if (guestNode)
4614 {
4615 uint32_t memoryBalloonSize = 0;
4616 CFGLDRQueryUInt32 (guestNode, "MemoryBalloonSize",
4617 &memoryBalloonSize);
4618 mHWData->mMemoryBalloonSize = memoryBalloonSize;
4619
4620 uint32_t statisticsUpdateInterval = 0;
4621 CFGLDRQueryUInt32 (guestNode, "StatisticsUpdateInterval",
4622 &statisticsUpdateInterval);
4623 mHWData->mStatisticsUpdateInterval = statisticsUpdateInterval;
4624
4625 CFGLDRReleaseNode (guestNode);
4626 }
4627 }
4628
4629 return S_OK;
4630}
4631
4632/**
4633 * @param aNode <HardDiskAttachments> node
4634 * @param aRegistered true when the machine is being loaded on VirtualBox
4635 * startup, or when a snapshot is being loaded (wchich
4636 * currently can happen on startup only)
4637 * @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
4638 */
4639HRESULT Machine::loadHardDisks (CFGNODE aNode, bool aRegistered,
4640 const Guid *aSnapshotId /* = NULL */)
4641{
4642 AssertReturn (aNode, E_INVALIDARG);
4643 AssertReturn ((mType == IsMachine && aSnapshotId == NULL) ||
4644 (mType == IsSnapshotMachine && aSnapshotId != NULL), E_FAIL);
4645
4646 HRESULT rc = S_OK;
4647
4648 unsigned cbDisks = 0;
4649 CFGLDRCountChildren (aNode, "HardDiskAttachment", &cbDisks);
4650
4651 if (!aRegistered && cbDisks > 0)
4652 {
4653 /* when the machine is being loaded (opened) from a file, it cannot
4654 * have hard disks attached (this should not happen normally,
4655 * because we don't allow to attach hard disks to an unregistered
4656 * VM at all */
4657 return setError (E_FAIL,
4658 tr ("Unregistered machine '%ls' cannot have hard disks attached "
4659 "(found %d hard disk attachments)"),
4660 mUserData->mName.raw(), cbDisks);
4661 }
4662
4663 for (unsigned i = 0; i < cbDisks && SUCCEEDED (rc); ++ i)
4664 {
4665 CFGNODE hdNode;
4666 CFGLDRGetChildNode (aNode, "HardDiskAttachment", i, &hdNode);
4667 ComAssertRet (hdNode, E_FAIL);
4668
4669 do
4670 {
4671 /* hardDisk uuid (required) */
4672 Guid uuid;
4673 CFGLDRQueryUUID (hdNode, "hardDisk", uuid.ptr());
4674 /* bus (controller) type (required) */
4675 Bstr bus;
4676 CFGLDRQueryBSTR (hdNode, "bus", bus.asOutParam());
4677 /* device (required) */
4678 Bstr device;
4679 CFGLDRQueryBSTR (hdNode, "device", device.asOutParam());
4680
4681 /* find a hard disk by UUID */
4682 ComObjPtr <HardDisk> hd;
4683 rc = mParent->getHardDisk (uuid, hd);
4684 if (FAILED (rc))
4685 break;
4686
4687 AutoLock hdLock (hd);
4688
4689 if (!hd->machineId().isEmpty())
4690 {
4691 rc = setError (E_FAIL,
4692 tr ("Hard disk '%ls' with UUID {%s} is already "
4693 "attached to a machine with UUID {%s} (see '%ls')"),
4694 hd->toString().raw(), uuid.toString().raw(),
4695 hd->machineId().toString().raw(),
4696 mData->mConfigFileFull.raw());
4697 break;
4698 }
4699
4700 if (hd->type() == HardDiskType_ImmutableHardDisk)
4701 {
4702 rc = setError (E_FAIL,
4703 tr ("Immutable hard disk '%ls' with UUID {%s} cannot be "
4704 "directly attached to a machine (see '%ls')"),
4705 hd->toString().raw(), uuid.toString().raw(),
4706 mData->mConfigFileFull.raw());
4707 break;
4708 }
4709
4710 /* attach the device */
4711 DiskControllerType_T ctl = DiskControllerType_InvalidController;
4712 LONG dev = -1;
4713
4714 if (bus == L"ide0")
4715 {
4716 ctl = DiskControllerType_IDE0Controller;
4717 if (device == L"master")
4718 dev = 0;
4719 else if (device == L"slave")
4720 dev = 1;
4721 else
4722 ComAssertMsgFailedBreak (("Invalid device: %ls\n", device.raw()),
4723 rc = E_FAIL);
4724 }
4725 else if (bus == L"ide1")
4726 {
4727 ctl = DiskControllerType_IDE1Controller;
4728 if (device == L"master")
4729 rc = setError (E_FAIL, tr("Could not attach a disk as a master "
4730 "device on the secondary controller"));
4731 else if (device == L"slave")
4732 dev = 1;
4733 else
4734 ComAssertMsgFailedBreak (("Invalid device: %ls\n", device.raw()),
4735 rc = E_FAIL);
4736 }
4737 else
4738 ComAssertMsgFailedBreak (("Invalid bus: %ls\n", bus.raw()),
4739 rc = E_FAIL);
4740
4741 ComObjPtr <HardDiskAttachment> attachment;
4742 attachment.createObject();
4743 rc = attachment->init (hd, ctl, dev, false /* aDirty */);
4744 if (FAILED (rc))
4745 break;
4746
4747 /* associate the hard disk with this machine */
4748 hd->setMachineId (mData->mUuid);
4749
4750 /* associate the hard disk with the given snapshot ID */
4751 if (mType == IsSnapshotMachine)
4752 hd->setSnapshotId (*aSnapshotId);
4753
4754 mHDData->mHDAttachments.push_back (attachment);
4755 }
4756 while (0);
4757
4758 CFGLDRReleaseNode (hdNode);
4759 }
4760
4761 return rc;
4762}
4763
4764/**
4765 * Creates a config loader and loads the settings file.
4766 *
4767 * @param aIsNew |true| if a newly created settings file is to be opened
4768 * (must be the case only when called from #saveSettings())
4769 *
4770 * @note
4771 * XML Schema errors are not detected by this method because
4772 * it assumes that it will load settings from an exclusively locked
4773 * file (using a file handle) that was previously validated when opened
4774 * for the first time. Thus, this method should be used only when
4775 * it's necessary to modify (save) the settings file.
4776 *
4777 * @note The object must be locked at least for reading before calling
4778 * this method.
4779 */
4780HRESULT Machine::openConfigLoader (CFGHANDLE *aLoader, bool aIsNew /* = false */)
4781{
4782 AssertReturn (aLoader, E_FAIL);
4783
4784 /* The settings file must be created and locked at this point */
4785 ComAssertRet (isConfigLocked(), E_FAIL);
4786
4787 /* load the config file */
4788 int vrc = CFGLDRLoad (aLoader,
4789 Utf8Str (mData->mConfigFileFull), mData->mHandleCfgFile,
4790 aIsNew ? NULL : XmlSchemaNS, true, cfgLdrEntityResolver,
4791 NULL);
4792 ComAssertRCRet (vrc, E_FAIL);
4793
4794 return S_OK;
4795}
4796
4797/**
4798 * Closes the config loader previously created by #openConfigLoader().
4799 * If \a aSaveBeforeClose is true, then the config is saved to the settings file
4800 * before closing. If saving fails, a proper error message is set.
4801 *
4802 * @param aSaveBeforeClose whether to save the config before closing or not
4803 */
4804HRESULT Machine::closeConfigLoader (CFGHANDLE aLoader, bool aSaveBeforeClose)
4805{
4806 HRESULT rc = S_OK;
4807
4808 if (aSaveBeforeClose)
4809 {
4810 char *loaderError = NULL;
4811 int vrc = CFGLDRSave (aLoader, &loaderError);
4812 if (VBOX_FAILURE (vrc))
4813 {
4814 rc = setError (E_FAIL,
4815 tr ("Could not save the settings file '%ls' (%Vrc)%s%s"),
4816 mData->mConfigFileFull.raw(), vrc,
4817 loaderError ? ".\n" : "", loaderError ? loaderError : "");
4818 if (loaderError)
4819 RTMemTmpFree (loaderError);
4820 }
4821 }
4822
4823 CFGLDRFree (aLoader);
4824
4825 return rc;
4826}
4827
4828/**
4829 * Searches for a <Snapshot> node for the given snapshot.
4830 * If the search is successful, \a aSnapshotNode will contain the found node.
4831 * In this case, \a aSnapshotsNode can be NULL meaning the found node is a
4832 * direct child of \a aMachineNode.
4833 *
4834 * If the search fails, a failure is returned and both \a aSnapshotsNode and
4835 * \a aSnapshotNode are set to 0.
4836 *
4837 * @param aSnapshot snapshot to search for
4838 * @param aMachineNode <Machine> node to start from
4839 * @param aSnapshotsNode <Snapshots> node containing the found <Snapshot> node
4840 * (may be NULL if the caller is not interested)
4841 * @param aSnapshotNode found <Snapshot> node
4842 */
4843HRESULT Machine::findSnapshotNode (Snapshot *aSnapshot, CFGNODE aMachineNode,
4844 CFGNODE *aSnapshotsNode, CFGNODE *aSnapshotNode)
4845{
4846 AssertReturn (aSnapshot && aMachineNode && aSnapshotNode, E_FAIL);
4847
4848 if (aSnapshotsNode)
4849 *aSnapshotsNode = 0;
4850 *aSnapshotNode = 0;
4851
4852 // build the full uuid path (from the fist parent to the given snapshot)
4853 std::list <Guid> path;
4854 {
4855 ComObjPtr <Snapshot> parent = aSnapshot;
4856 while (parent)
4857 {
4858 path.push_front (parent->data().mId);
4859 parent = parent->parent();
4860 }
4861 }
4862
4863 CFGNODE snapshotsNode = aMachineNode;
4864 CFGNODE snapshotNode = 0;
4865
4866 for (std::list <Guid>::const_iterator it = path.begin();
4867 it != path.end();
4868 ++ it)
4869 {
4870 if (snapshotNode)
4871 {
4872 // proceed to the nested <Snapshots> node
4873 Assert (snapshotsNode);
4874 if (snapshotsNode != aMachineNode)
4875 {
4876 CFGLDRReleaseNode (snapshotsNode);
4877 snapshotsNode = 0;
4878 }
4879 CFGLDRGetChildNode (snapshotNode, "Snapshots", 0, &snapshotsNode);
4880 CFGLDRReleaseNode (snapshotNode);
4881 snapshotNode = 0;
4882 }
4883
4884 AssertReturn (snapshotsNode, E_FAIL);
4885
4886 unsigned count = 0, i = 0;
4887 CFGLDRCountChildren (snapshotsNode, "Snapshot", &count);
4888 for (; i < count; ++ i)
4889 {
4890 snapshotNode = 0;
4891 CFGLDRGetChildNode (snapshotsNode, "Snapshot", i, &snapshotNode);
4892 Guid id;
4893 CFGLDRQueryUUID (snapshotNode, "uuid", id.ptr());
4894 if (id == (*it))
4895 {
4896 // we keep (don't release) snapshotNode and snapshotsNode
4897 break;
4898 }
4899 CFGLDRReleaseNode (snapshotNode);
4900 snapshotNode = 0;
4901 }
4902
4903 if (i == count)
4904 {
4905 // the next uuid is not found, no need to continue...
4906 AssertFailed();
4907 if (snapshotsNode != aMachineNode)
4908 {
4909 CFGLDRReleaseNode (snapshotsNode);
4910 snapshotsNode = 0;
4911 }
4912 break;
4913 }
4914 }
4915
4916 // we must always succesfully find the node
4917 AssertReturn (snapshotNode, E_FAIL);
4918 AssertReturn (snapshotsNode, E_FAIL);
4919
4920 if (aSnapshotsNode)
4921 *aSnapshotsNode = snapshotsNode != aMachineNode ? snapshotsNode : 0;
4922 *aSnapshotNode = snapshotNode;
4923
4924 return S_OK;
4925}
4926
4927/**
4928 * Returns the snapshot with the given UUID or fails of no such snapshot.
4929 *
4930 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
4931 * @param aSnapshot where to return the found snapshot
4932 * @param aSetError true to set extended error info on failure
4933 */
4934HRESULT Machine::findSnapshot (const Guid &aId, ComObjPtr <Snapshot> &aSnapshot,
4935 bool aSetError /* = false */)
4936{
4937 if (!mData->mFirstSnapshot)
4938 {
4939 if (aSetError)
4940 return setError (E_FAIL,
4941 tr ("This machine does not have any snapshots"));
4942 return E_FAIL;
4943 }
4944
4945 if (aId.isEmpty())
4946 aSnapshot = mData->mFirstSnapshot;
4947 else
4948 aSnapshot = mData->mFirstSnapshot->findChildOrSelf (aId);
4949
4950 if (!aSnapshot)
4951 {
4952 if (aSetError)
4953 return setError (E_FAIL,
4954 tr ("Could not find a snapshot with UUID {%s}"),
4955 aId.toString().raw());
4956 return E_FAIL;
4957 }
4958
4959 return S_OK;
4960}
4961
4962/**
4963 * Returns the snapshot with the given name or fails of no such snapshot.
4964 *
4965 * @param aName snapshot name to find
4966 * @param aSnapshot where to return the found snapshot
4967 * @param aSetError true to set extended error info on failure
4968 */
4969HRESULT Machine::findSnapshot (const BSTR aName, ComObjPtr <Snapshot> &aSnapshot,
4970 bool aSetError /* = false */)
4971{
4972 AssertReturn (aName, E_INVALIDARG);
4973
4974 if (!mData->mFirstSnapshot)
4975 {
4976 if (aSetError)
4977 return setError (E_FAIL,
4978 tr ("This machine does not have any snapshots"));
4979 return E_FAIL;
4980 }
4981
4982 aSnapshot = mData->mFirstSnapshot->findChildOrSelf (aName);
4983
4984 if (!aSnapshot)
4985 {
4986 if (aSetError)
4987 return setError (E_FAIL,
4988 tr ("Could not find a snapshot named '%ls'"), aName);
4989 return E_FAIL;
4990 }
4991
4992 return S_OK;
4993}
4994
4995/**
4996 * Searches for an attachment that contains the given hard disk.
4997 * The hard disk must be associated with some VM and can be optionally
4998 * associated with some snapshot. If the attachment is stored in the snapshot
4999 * (i.e. the hard disk is associated with some snapshot), @a aSnapshot
5000 * will point to a non-null object on output.
5001 *
5002 * @param aHd hard disk to search an attachment for
5003 * @param aMachine where to store the hard disk's machine (can be NULL)
5004 * @param aSnapshot where to store the hard disk's snapshot (can be NULL)
5005 * @param aHda where to store the hard disk's attachment (can be NULL)
5006 *
5007 *
5008 * @note
5009 * It is assumed that the machine where the attachment is found,
5010 * is already placed to the Discarding state, when this method is called.
5011 * @note
5012 * The object returned in @a aHda is the attachment from the snapshot
5013 * machine if the hard disk is associated with the snapshot, not from the
5014 * primary machine object returned returned in @a aMachine.
5015 */
5016HRESULT Machine::findHardDiskAttachment (const ComObjPtr <HardDisk> &aHd,
5017 ComObjPtr <Machine> *aMachine,
5018 ComObjPtr <Snapshot> *aSnapshot,
5019 ComObjPtr <HardDiskAttachment> *aHda)
5020{
5021 AssertReturn (!aHd.isNull(), E_INVALIDARG);
5022
5023 Guid mid = aHd->machineId();
5024 Guid sid = aHd->snapshotId();
5025
5026 AssertReturn (!mid.isEmpty(), E_INVALIDARG);
5027
5028 ComObjPtr <Machine> m;
5029 mParent->getMachine (mid, m);
5030 ComAssertRet (!m.isNull(), E_FAIL);
5031
5032 HDData::HDAttachmentList *attachments = &m->mHDData->mHDAttachments;
5033
5034 ComObjPtr <Snapshot> s;
5035 if (!sid.isEmpty())
5036 {
5037 m->findSnapshot (sid, s);
5038 ComAssertRet (!s.isNull(), E_FAIL);
5039 attachments = &s->data().mMachine->mHDData->mHDAttachments;
5040 }
5041
5042 AssertReturn (attachments, E_FAIL);
5043
5044 for (HDData::HDAttachmentList::const_iterator it = attachments->begin();
5045 it != attachments->end();
5046 ++ it)
5047 {
5048 if ((*it)->hardDisk() == aHd)
5049 {
5050 if (aMachine) *aMachine = m;
5051 if (aSnapshot) *aSnapshot = s;
5052 if (aHda) *aHda = (*it);
5053 return S_OK;
5054 }
5055 }
5056
5057 ComAssertFailed();
5058 return E_FAIL;
5059}
5060
5061/**
5062 * Helper for #saveSettings. Cares about renaming the settings directory and
5063 * file if the machine name was changed and about creating a new settings file
5064 * if this is a new machine.
5065 *
5066 * @note Must be never called directly.
5067 *
5068 * @param aRenamed receives |true| if the name was changed and the settings
5069 * file was renamed as a result, or |false| otherwise. The
5070 * value makes sense only on success.
5071 * @param aNew receives |true| if a virgin settings file was created.
5072 */
5073HRESULT Machine::prepareSaveSettings (bool &aRenamed, bool &aNew)
5074{
5075 HRESULT rc = S_OK;
5076
5077 aRenamed = false;
5078
5079 /* if we're ready and isConfigLocked() is FALSE then it means
5080 * that no config file exists yet (we will create a virgin one) */
5081 aNew = !isConfigLocked();
5082
5083 /* attempt to rename the settings file if machine name is changed */
5084 if (mUserData->mNameSync &&
5085 mUserData.isBackedUp() &&
5086 mUserData.backedUpData()->mName != mUserData->mName)
5087 {
5088 aRenamed = true;
5089
5090 if (!aNew)
5091 {
5092 /* unlock the old config file */
5093 rc = unlockConfig();
5094 CheckComRCReturnRC (rc);
5095 }
5096
5097 bool dirRenamed = false;
5098 bool fileRenamed = false;
5099
5100 Utf8Str configFile, newConfigFile;
5101 Utf8Str configDir, newConfigDir;
5102
5103 do
5104 {
5105 int vrc = VINF_SUCCESS;
5106
5107 Utf8Str name = mUserData.backedUpData()->mName;
5108 Utf8Str newName = mUserData->mName;
5109
5110 configFile = mData->mConfigFileFull;
5111
5112 /* first, rename the directory if it matches the machine name */
5113 configDir = configFile;
5114 RTPathStripFilename (configDir.mutableRaw());
5115 newConfigDir = configDir;
5116 if (RTPathFilename (configDir) == name)
5117 {
5118 RTPathStripFilename (newConfigDir.mutableRaw());
5119 newConfigDir = Utf8StrFmt ("%s%c%s",
5120 newConfigDir.raw(), RTPATH_DELIMITER, newName.raw());
5121 /* new dir and old dir cannot be equal here because of 'if'
5122 * above and because name != newName */
5123 Assert (configDir != newConfigDir);
5124 if (!aNew)
5125 {
5126 /* perform real rename only if the machine is not new */
5127 vrc = RTPathRename (configDir.raw(), newConfigDir.raw(), 0);
5128 if (VBOX_FAILURE (vrc))
5129 {
5130 rc = setError (E_FAIL,
5131 tr ("Could not rename the directory '%s' to '%s' "
5132 "to save the settings file (%Vrc)"),
5133 configDir.raw(), newConfigDir.raw(), vrc);
5134 break;
5135 }
5136 dirRenamed = true;
5137 }
5138 }
5139
5140 newConfigFile = Utf8StrFmt ("%s%c%s.xml",
5141 newConfigDir.raw(), RTPATH_DELIMITER, newName.raw());
5142
5143 /* then try to rename the settings file itself */
5144 if (newConfigFile != configFile)
5145 {
5146 /* get the path to old settings file in renamed directory */
5147 configFile = Utf8StrFmt ("%s%c%s",
5148 newConfigDir.raw(), RTPATH_DELIMITER,
5149 RTPathFilename (configFile));
5150 if (!aNew)
5151 {
5152 /* perform real rename only if the machine is not new */
5153 vrc = RTFileRename (configFile.raw(), newConfigFile.raw(), 0);
5154 if (VBOX_FAILURE (vrc))
5155 {
5156 rc = setError (E_FAIL,
5157 tr ("Could not rename the settings file '%s' to '%s' "
5158 "(%Vrc)"),
5159 configFile.raw(), newConfigFile.raw(), vrc);
5160 break;
5161 }
5162 fileRenamed = true;
5163 }
5164 }
5165
5166 /* update mConfigFileFull amd mConfigFile */
5167 Bstr oldConfigFileFull = mData->mConfigFileFull;
5168 Bstr oldConfigFile = mData->mConfigFile;
5169 mData->mConfigFileFull = newConfigFile;
5170 /* try to get the relative path for mConfigFile */
5171 Utf8Str path = newConfigFile;
5172 mParent->calculateRelativePath (path, path);
5173 mData->mConfigFile = path;
5174
5175 /* last, try to update the global settings with the new path */
5176 if (mData->mRegistered)
5177 {
5178 rc = mParent->updateSettings (configDir, newConfigDir);
5179 if (FAILED (rc))
5180 {
5181 /* revert to old values */
5182 mData->mConfigFileFull = oldConfigFileFull;
5183 mData->mConfigFile = oldConfigFile;
5184 break;
5185 }
5186 }
5187
5188 /* update the snapshot folder */
5189 path = mUserData->mSnapshotFolderFull;
5190 if (RTPathStartsWith (path, configDir))
5191 {
5192 path = Utf8StrFmt ("%s%s", newConfigDir.raw(),
5193 path.raw() + configDir.length());
5194 mUserData->mSnapshotFolderFull = path;
5195 calculateRelativePath (path, path);
5196 mUserData->mSnapshotFolder = path;
5197 }
5198
5199 /* update the saved state file path */
5200 path = mSSData->mStateFilePath;
5201 if (RTPathStartsWith (path, configDir))
5202 {
5203 path = Utf8StrFmt ("%s%s", newConfigDir.raw(),
5204 path.raw() + configDir.length());
5205 mSSData->mStateFilePath = path;
5206 }
5207
5208 /* Update saved state file paths of all online snapshots.
5209 * Note that saveSettings() will recognize name change
5210 * and will save all snapshots in this case. */
5211 if (mData->mFirstSnapshot)
5212 mData->mFirstSnapshot->updateSavedStatePaths (configDir,
5213 newConfigDir);
5214 }
5215 while (0);
5216
5217 if (FAILED (rc))
5218 {
5219 /* silently try to rename everything back */
5220 if (fileRenamed)
5221 RTFileRename (newConfigFile.raw(), configFile.raw(), 0);
5222 if (dirRenamed)
5223 RTPathRename (newConfigDir.raw(), configDir.raw(), 0);
5224 }
5225
5226 if (!aNew)
5227 {
5228 /* lock the config again */
5229 HRESULT rc2 = lockConfig();
5230 if (SUCCEEDED (rc))
5231 rc = rc2;
5232 }
5233
5234 CheckComRCReturnRC (rc);
5235 }
5236
5237 if (aNew)
5238 {
5239 /* create a virgin config file */
5240 int vrc = VINF_SUCCESS;
5241
5242 /* ensure the settings directory exists */
5243 Utf8Str path = mData->mConfigFileFull;
5244 RTPathStripFilename (path.mutableRaw());
5245 if (!RTDirExists (path))
5246 {
5247 vrc = RTDirCreateFullPath (path, 0777);
5248 if (VBOX_FAILURE (vrc))
5249 {
5250 return setError (E_FAIL,
5251 tr ("Could not create a directory '%s' "
5252 "to save the settings file (%Vrc)"),
5253 path.raw(), vrc);
5254 }
5255 }
5256
5257 /* Note: open flags must correlated with RTFileOpen() in lockConfig() */
5258 path = Utf8Str (mData->mConfigFileFull);
5259 vrc = RTFileOpen (&mData->mHandleCfgFile, path,
5260 RTFILE_O_READWRITE | RTFILE_O_CREATE |
5261 RTFILE_O_DENY_WRITE);
5262 if (VBOX_SUCCESS (vrc))
5263 {
5264 vrc = RTFileWrite (mData->mHandleCfgFile,
5265 (void *) DefaultMachineConfig,
5266 sizeof (DefaultMachineConfig), NULL);
5267 }
5268 if (VBOX_FAILURE (vrc))
5269 {
5270 mData->mHandleCfgFile = NIL_RTFILE;
5271 return setError (E_FAIL,
5272 tr ("Could not create the settings file '%s' (%Vrc)"),
5273 path.raw(), vrc);
5274 }
5275 /* we do not close the file to simulate lockConfig() */
5276 }
5277
5278 return rc;
5279}
5280
5281/**
5282 * Saves machine data, user data and hardware data.
5283 *
5284 * @param aMarkCurStateAsModified
5285 * if true (default), mData->mCurrentStateModified will be set to
5286 * what #isReallyModified() returns prior to saving settings to a file,
5287 * otherwise the current value of mData->mCurrentStateModified will be
5288 * saved.
5289 * @param aInformCallbacksAnyway
5290 * if true, callbacks will be informed even if #isReallyModified()
5291 * returns false. This is necessary for cases when we change machine data
5292 * diectly, not through the backup()/commit() mechanism.
5293 *
5294 * @note Locks mParent (only in some cases, and only when #isConfigLocked() is
5295 * |TRUE|, see the #prepareSaveSettings() code for details) +
5296 * this object + children for writing.
5297 */
5298HRESULT Machine::saveSettings (bool aMarkCurStateAsModified /* = true */,
5299 bool aInformCallbacksAnyway /* = false */)
5300{
5301 LogFlowThisFuncEnter();
5302
5303 /// @todo (dmik) I guess we should lock all our child objects here
5304 // (such as mVRDPServer etc.) to ensure they are not changed
5305 // until completely saved to disk and committed
5306
5307 /// @todo (dmik) also, we need to delegate saving child objects' settings
5308 // to objects themselves to ensure operations 'commit + save changes'
5309 // are atomic (amd done from the object's lock so that nobody can change
5310 // settings again until completely saved).
5311
5312 AssertReturn (mType == IsMachine || mType == IsSessionMachine, E_FAIL);
5313
5314 bool wasModified;
5315
5316 if (aMarkCurStateAsModified)
5317 {
5318 /*
5319 * We ignore changes to user data when setting mCurrentStateModified
5320 * because the current state will not differ from the current snapshot
5321 * if only user data has been changed (user data is shared by all
5322 * snapshots).
5323 */
5324 mData->mCurrentStateModified = isReallyModified (true /* aIgnoreUserData */);
5325 wasModified = mUserData.hasActualChanges() || mData->mCurrentStateModified;
5326 }
5327 else
5328 {
5329 wasModified = isReallyModified();
5330 }
5331
5332 HRESULT rc = S_OK;
5333
5334 /* First, prepare to save settings. It will will care about renaming the
5335 * settings directory and file if the machine name was changed and about
5336 * creating a new settings file if this is a new machine. */
5337 bool isRenamed = false;
5338 bool isNew = false;
5339 rc = prepareSaveSettings (isRenamed, isNew);
5340 CheckComRCReturnRC (rc);
5341
5342 /* then, open the settings file */
5343 CFGHANDLE configLoader = 0;
5344 rc = openConfigLoader (&configLoader, isNew);
5345 CheckComRCReturnRC (rc);
5346
5347 /* save all snapshots when the machine name was changed since
5348 * it may affect saved state file paths for online snapshots (see
5349 * #openConfigLoader() for details) */
5350 bool updateAllSnapshots = isRenamed;
5351
5352 /* commit before saving, since it may change settings
5353 * (for example, perform fixup of lazy hard disk changes) */
5354 rc = commit();
5355 if (FAILED (rc))
5356 {
5357 closeConfigLoader (configLoader, false /* aSaveBeforeClose */);
5358 return rc;
5359 }
5360
5361 /* include hard disk changes to the modified flag */
5362 wasModified |= mHDData->mHDAttachmentsChanged;
5363 if (aMarkCurStateAsModified)
5364 mData->mCurrentStateModified |= BOOL (mHDData->mHDAttachmentsChanged);
5365
5366
5367 CFGNODE machineNode = 0;
5368 /* create if not exists */
5369 CFGLDRCreateNode (configLoader, "VirtualBox/Machine", &machineNode);
5370
5371 do
5372 {
5373 ComAssertBreak (machineNode, rc = E_FAIL);
5374
5375 /* uuid (required) */
5376 Assert (mData->mUuid);
5377 CFGLDRSetUUID (machineNode, "uuid", mData->mUuid.raw());
5378
5379 /* name (required) */
5380 Assert (!mUserData->mName.isEmpty());
5381 CFGLDRSetBSTR (machineNode, "name", mUserData->mName);
5382
5383 /* nameSync (optional, default is true) */
5384 if (!mUserData->mNameSync)
5385 CFGLDRSetBool (machineNode, "nameSync", false);
5386 else
5387 CFGLDRDeleteAttribute (machineNode, "nameSync");
5388
5389 /* Description node (optional) */
5390 if (!mUserData->mDescription.isNull())
5391 {
5392 CFGNODE descNode = 0;
5393 CFGLDRCreateChildNode (machineNode, "Description", &descNode);
5394 Assert (descNode);
5395 CFGLDRSetBSTR (descNode, NULL, mUserData->mDescription);
5396 CFGLDRReleaseNode (descNode);
5397 }
5398 else
5399 {
5400 CFGNODE descNode = 0;
5401 CFGLDRGetChildNode (machineNode, "Description", 0, &descNode);
5402 if (descNode)
5403 CFGLDRDeleteNode (descNode);
5404 }
5405
5406 /* OSType (required) */
5407 {
5408 CFGLDRSetBSTR (machineNode, "OSType", mUserData->mOSTypeId);
5409 }
5410
5411 /* stateFile (optional) */
5412 if (mData->mMachineState == MachineState_Saved)
5413 {
5414 Assert (!mSSData->mStateFilePath.isEmpty());
5415 /* try to make the file name relative to the settings file dir */
5416 Utf8Str stateFilePath = mSSData->mStateFilePath;
5417 calculateRelativePath (stateFilePath, stateFilePath);
5418 CFGLDRSetString (machineNode, "stateFile", stateFilePath);
5419 }
5420 else
5421 {
5422 Assert (mSSData->mStateFilePath.isNull());
5423 CFGLDRDeleteAttribute (machineNode, "stateFile");
5424 }
5425
5426 /* currentSnapshot ID (optional) */
5427 if (!mData->mCurrentSnapshot.isNull())
5428 {
5429 Assert (!mData->mFirstSnapshot.isNull());
5430 CFGLDRSetUUID (machineNode, "currentSnapshot",
5431 mData->mCurrentSnapshot->data().mId);
5432 }
5433 else
5434 {
5435 Assert (mData->mFirstSnapshot.isNull());
5436 CFGLDRDeleteAttribute (machineNode, "currentSnapshot");
5437 }
5438
5439 /* snapshotFolder (optional) */
5440 if (!mUserData->mSnapshotFolder.isEmpty())
5441 CFGLDRSetBSTR (machineNode, "snapshotFolder", mUserData->mSnapshotFolder);
5442 else
5443 CFGLDRDeleteAttribute (machineNode, "snapshotFolder");
5444
5445 /* currentStateModified (optional, default is yes) */
5446 if (!mData->mCurrentStateModified)
5447 CFGLDRSetBool (machineNode, "currentStateModified", false);
5448 else
5449 CFGLDRDeleteAttribute (machineNode, "currentStateModified");
5450
5451 /* lastStateChange */
5452 CFGLDRSetDateTime (machineNode, "lastStateChange",
5453 mData->mLastStateChange);
5454
5455 /* Hardware node (required) */
5456 {
5457 CFGNODE hwNode = 0;
5458 CFGLDRGetChildNode (machineNode, "Hardware", 0, &hwNode);
5459 /* first, delete the entire node if exists */
5460 if (hwNode)
5461 CFGLDRDeleteNode (hwNode);
5462 /* then recreate it */
5463 hwNode = 0;
5464 CFGLDRCreateChildNode (machineNode, "Hardware", &hwNode);
5465 ComAssertBreak (hwNode, rc = E_FAIL);
5466
5467 rc = saveHardware (hwNode);
5468
5469 CFGLDRReleaseNode (hwNode);
5470 if (FAILED (rc))
5471 break;
5472 }
5473
5474 /* HardDiskAttachments node (required) */
5475 {
5476 CFGNODE hdasNode = 0;
5477 CFGLDRGetChildNode (machineNode, "HardDiskAttachments", 0, &hdasNode);
5478 /* first, delete the entire node if exists */
5479 if (hdasNode)
5480 CFGLDRDeleteNode (hdasNode);
5481 /* then recreate it */
5482 hdasNode = 0;
5483 CFGLDRCreateChildNode (machineNode, "HardDiskAttachments", &hdasNode);
5484 ComAssertBreak (hdasNode, rc = E_FAIL);
5485
5486 rc = saveHardDisks (hdasNode);
5487
5488 CFGLDRReleaseNode (hdasNode);
5489 if (FAILED (rc))
5490 break;
5491 }
5492
5493 /* update all snapshots if requested */
5494 if (updateAllSnapshots)
5495 rc = saveSnapshotSettingsWorker (machineNode, NULL,
5496 SaveSS_UpdateAllOp);
5497 }
5498 while (0);
5499
5500 if (machineNode)
5501 CFGLDRReleaseNode (machineNode);
5502
5503 if (SUCCEEDED (rc))
5504 rc = closeConfigLoader (configLoader, true /* aSaveBeforeClose */);
5505 else
5506 closeConfigLoader (configLoader, false /* aSaveBeforeClose */);
5507
5508 if (FAILED (rc))
5509 {
5510 /*
5511 * backup arbitrary data item to cause #isModified() to still return
5512 * true in case of any error
5513 */
5514 mHWData.backup();
5515 }
5516
5517 if (wasModified || aInformCallbacksAnyway)
5518 {
5519 /*
5520 * Fire the data change event, even on failure (since we've already
5521 * committed all data). This is done only for SessionMachines because
5522 * mutable Machine instances are always not registered (i.e. private
5523 * to the client process that creates them) and thus don't need to
5524 * inform callbacks.
5525 */
5526 if (mType == IsSessionMachine)
5527 mParent->onMachineDataChange (mData->mUuid);
5528 }
5529
5530 LogFlowThisFunc (("rc=%08X\n", rc));
5531 LogFlowThisFuncLeave();
5532 return rc;
5533}
5534
5535/**
5536 * Wrapper for #saveSnapshotSettingsWorker() that opens the settings file
5537 * and locates the <Machine> node in there. See #saveSnapshotSettingsWorker()
5538 * for more details.
5539 *
5540 * @param aSnapshot Snapshot to operate on
5541 * @param aOpFlags Operation to perform, one of SaveSS_NoOp, SaveSS_AddOp
5542 * or SaveSS_UpdateAttrsOp possibly combined with
5543 * SaveSS_UpdateCurrentId.
5544 *
5545 * @note Locks this object for writing + other child objects.
5546 */
5547HRESULT Machine::saveSnapshotSettings (Snapshot *aSnapshot, int aOpFlags)
5548{
5549 AutoCaller autoCaller (this);
5550 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
5551
5552 AssertReturn (mType == IsMachine || mType == IsSessionMachine, E_FAIL);
5553
5554 AutoLock alock (this);
5555
5556 AssertReturn (isConfigLocked(), E_FAIL);
5557
5558 HRESULT rc = S_OK;
5559
5560 /* load the config file */
5561 CFGHANDLE configLoader = 0;
5562 rc = openConfigLoader (&configLoader);
5563 if (FAILED (rc))
5564 return rc;
5565
5566 CFGNODE machineNode = 0;
5567 CFGLDRGetNode (configLoader, "VirtualBox/Machine", 0, &machineNode);
5568
5569 do
5570 {
5571 ComAssertBreak (machineNode, rc = E_FAIL);
5572
5573 rc = saveSnapshotSettingsWorker (machineNode, aSnapshot, aOpFlags);
5574
5575 CFGLDRReleaseNode (machineNode);
5576 }
5577 while (0);
5578
5579 if (SUCCEEDED (rc))
5580 rc = closeConfigLoader (configLoader, true /* aSaveBeforeClose */);
5581 else
5582 closeConfigLoader (configLoader, false /* aSaveBeforeClose */);
5583
5584 return rc;
5585}
5586
5587/**
5588 * Performs the specified operation on the given snapshot
5589 * in the settings file represented by \a aMachineNode.
5590 *
5591 * If \a aOpFlags = SaveSS_UpdateAllOp, \a aSnapshot can be NULL to indicate
5592 * that the whole tree of the snapshots should be updated in <Machine>.
5593 * One particular case is when the last (and the only) snapshot should be
5594 * removed (it is so when both mCurrentSnapshot and mFirstSnapshot are NULL).
5595 *
5596 * \a aOp may be just SaveSS_UpdateCurrentId if only the currentSnapshot
5597 * attribute of <Machine> needs to be updated.
5598 *
5599 * @param aMachineNode <Machine> node in the opened settings file
5600 * @param aSnapshot Snapshot to operate on
5601 * @param aOpFlags Operation to perform, one of SaveSS_NoOp, SaveSS_AddOp
5602 * or SaveSS_UpdateAttrsOp possibly combined with
5603 * SaveSS_UpdateCurrentId.
5604 *
5605 * @note Must be called with this object locked for writing.
5606 * Locks child objects.
5607 */
5608HRESULT Machine::saveSnapshotSettingsWorker (CFGNODE aMachineNode,
5609 Snapshot *aSnapshot, int aOpFlags)
5610{
5611 AssertReturn (aMachineNode, E_FAIL);
5612
5613 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
5614
5615 int op = aOpFlags & SaveSS_OpMask;
5616 AssertReturn (
5617 (aSnapshot && (op == SaveSS_AddOp || op == SaveSS_UpdateAttrsOp ||
5618 op == SaveSS_UpdateAllOp)) ||
5619 (!aSnapshot && ((op == SaveSS_NoOp && (aOpFlags & SaveSS_UpdateCurrentId)) ||
5620 op == SaveSS_UpdateAllOp)),
5621 E_FAIL);
5622
5623 HRESULT rc = S_OK;
5624
5625 bool recreateWholeTree = false;
5626
5627 do
5628 {
5629 if (op == SaveSS_NoOp)
5630 break;
5631
5632 /* quick path: recreate the whole tree of the snapshots */
5633 if (op == SaveSS_UpdateAllOp && !aSnapshot)
5634 {
5635 /* first, delete the entire root snapshot node if it exists */
5636 CFGNODE snapshotNode = 0;
5637 CFGLDRGetChildNode (aMachineNode, "Snapshot", 0, &snapshotNode);
5638 if (snapshotNode)
5639 CFGLDRDeleteNode (snapshotNode);
5640
5641 /*
5642 * second, if we have any snapshots left, substitute aSnapshot with
5643 * the first snapshot to recreate the whole tree, otherwise break
5644 */
5645 if (mData->mFirstSnapshot)
5646 {
5647 aSnapshot = mData->mFirstSnapshot;
5648 recreateWholeTree = true;
5649 }
5650 else
5651 break;
5652 }
5653
5654 Assert (!!aSnapshot);
5655 ComObjPtr <Snapshot> parent = aSnapshot->parent();
5656
5657 if (op == SaveSS_AddOp)
5658 {
5659 CFGNODE parentNode = 0;
5660
5661 if (parent)
5662 {
5663 rc = findSnapshotNode (parent, aMachineNode, NULL, &parentNode);
5664 if (FAILED (rc))
5665 break;
5666 ComAssertBreak (parentNode, rc = E_FAIL);
5667 }
5668
5669 do
5670 {
5671 CFGNODE snapshotsNode = 0;
5672
5673 if (parentNode)
5674 {
5675 CFGLDRCreateChildNode (parentNode, "Snapshots", &snapshotsNode);
5676 ComAssertBreak (snapshotsNode, rc = E_FAIL);
5677 }
5678 else
5679 snapshotsNode = aMachineNode;
5680 do
5681 {
5682 CFGNODE snapshotNode = 0;
5683 CFGLDRAppendChildNode (snapshotsNode, "Snapshot", &snapshotNode);
5684 ComAssertBreak (snapshotNode, rc = E_FAIL);
5685 rc = saveSnapshot (snapshotNode, aSnapshot, false /* aAttrsOnly */);
5686 CFGLDRReleaseNode (snapshotNode);
5687
5688 if (FAILED (rc))
5689 break;
5690
5691 /*
5692 * when a new snapshot is added, this means diffs were created
5693 * for every normal/immutable hard disk of the VM, so we need to
5694 * save the current hard disk attachments
5695 */
5696
5697 CFGNODE hdasNode = 0;
5698 CFGLDRGetChildNode (aMachineNode, "HardDiskAttachments", 0, &hdasNode);
5699 if (hdasNode)
5700 CFGLDRDeleteNode (hdasNode);
5701 CFGLDRCreateChildNode (aMachineNode, "HardDiskAttachments", &hdasNode);
5702 ComAssertBreak (hdasNode, rc = E_FAIL);
5703
5704 rc = saveHardDisks (hdasNode);
5705
5706 if (mHDData->mHDAttachments.size() != 0)
5707 {
5708 /*
5709 * If we have one or more attachments then we definitely
5710 * created diffs for them and associated new diffs with
5711 * current settngs. So, since we don't use saveSettings(),
5712 * we need to inform callbacks manually.
5713 */
5714 if (mType == IsSessionMachine)
5715 mParent->onMachineDataChange (mData->mUuid);
5716 }
5717
5718 CFGLDRReleaseNode (hdasNode);
5719 }
5720 while (0);
5721
5722 if (snapshotsNode != aMachineNode)
5723 CFGLDRReleaseNode (snapshotsNode);
5724 }
5725 while (0);
5726
5727 if (parentNode)
5728 CFGLDRReleaseNode (parentNode);
5729
5730 break;
5731 }
5732
5733 Assert (op == SaveSS_UpdateAttrsOp && !recreateWholeTree ||
5734 op == SaveSS_UpdateAllOp);
5735
5736 CFGNODE snapshotsNode = 0;
5737 CFGNODE snapshotNode = 0;
5738
5739 if (!recreateWholeTree)
5740 {
5741 rc = findSnapshotNode (aSnapshot, aMachineNode,
5742 &snapshotsNode, &snapshotNode);
5743 if (FAILED (rc))
5744 break;
5745 ComAssertBreak (snapshotNode, rc = E_FAIL);
5746 }
5747
5748 if (!snapshotsNode)
5749 snapshotsNode = aMachineNode;
5750
5751 if (op == SaveSS_UpdateAttrsOp)
5752 rc = saveSnapshot (snapshotNode, aSnapshot, true /* aAttrsOnly */);
5753 else do
5754 {
5755 if (snapshotNode)
5756 {
5757 CFGLDRDeleteNode (snapshotNode);
5758 snapshotNode = 0;
5759 }
5760 CFGLDRAppendChildNode (snapshotsNode, "Snapshot", &snapshotNode);
5761 ComAssertBreak (snapshotNode, rc = E_FAIL);
5762 rc = saveSnapshot (snapshotNode, aSnapshot, false /* aAttrsOnly */);
5763 }
5764 while (0);
5765
5766 CFGLDRReleaseNode (snapshotNode);
5767 if (snapshotsNode != aMachineNode)
5768 CFGLDRReleaseNode (snapshotsNode);
5769 }
5770 while (0);
5771
5772 if (SUCCEEDED (rc))
5773 {
5774 /* update currentSnapshot when appropriate */
5775 if (aOpFlags & SaveSS_UpdateCurrentId)
5776 {
5777 if (!mData->mCurrentSnapshot.isNull())
5778 CFGLDRSetUUID (aMachineNode, "currentSnapshot",
5779 mData->mCurrentSnapshot->data().mId);
5780 else
5781 CFGLDRDeleteAttribute (aMachineNode, "currentSnapshot");
5782 }
5783 if (aOpFlags & SaveSS_UpdateCurStateModified)
5784 {
5785 if (!mData->mCurrentStateModified)
5786 CFGLDRSetBool (aMachineNode, "currentStateModified", false);
5787 else
5788 CFGLDRDeleteAttribute (aMachineNode, "currentStateModified");
5789 }
5790 }
5791
5792 return rc;
5793}
5794
5795/**
5796 * Saves the given snapshot and all its children (unless \a aAttrsOnly is true).
5797 * It is assumed that the given node is empty (unless \a aAttrsOnly is true).
5798 *
5799 * @param aNode <Snapshot> node to save the snapshot to
5800 * @param aSnapshot snapshot to save
5801 * @param aAttrsOnly if true, only updatge user-changeable attrs
5802 */
5803HRESULT Machine::saveSnapshot (CFGNODE aNode, Snapshot *aSnapshot, bool aAttrsOnly)
5804{
5805 AssertReturn (aNode && aSnapshot, E_INVALIDARG);
5806 AssertReturn (mType == IsMachine || mType == IsSessionMachine, E_FAIL);
5807
5808 /* uuid (required) */
5809 if (!aAttrsOnly)
5810 CFGLDRSetUUID (aNode, "uuid", aSnapshot->data().mId);
5811
5812 /* name (required) */
5813 CFGLDRSetBSTR (aNode, "name", aSnapshot->data().mName);
5814
5815 /* timeStamp (required) */
5816 CFGLDRSetDateTime (aNode, "timeStamp", aSnapshot->data().mTimeStamp);
5817
5818 /* Description node (optional) */
5819 if (!aSnapshot->data().mDescription.isNull())
5820 {
5821 CFGNODE descNode = 0;
5822 CFGLDRCreateChildNode (aNode, "Description", &descNode);
5823 Assert (descNode);
5824 CFGLDRSetBSTR (descNode, NULL, aSnapshot->data().mDescription);
5825 CFGLDRReleaseNode (descNode);
5826 }
5827 else
5828 {
5829 CFGNODE descNode = 0;
5830 CFGLDRGetChildNode (aNode, "Description", 0, &descNode);
5831 if (descNode)
5832 CFGLDRDeleteNode (descNode);
5833 }
5834
5835 if (aAttrsOnly)
5836 return S_OK;
5837
5838 /* stateFile (optional) */
5839 if (aSnapshot->stateFilePath())
5840 {
5841 /* try to make the file name relative to the settings file dir */
5842 Utf8Str stateFilePath = aSnapshot->stateFilePath();
5843 calculateRelativePath (stateFilePath, stateFilePath);
5844 CFGLDRSetString (aNode, "stateFile", stateFilePath);
5845 }
5846
5847 {
5848 ComObjPtr <SnapshotMachine> snapshotMachine = aSnapshot->data().mMachine;
5849 ComAssertRet (!snapshotMachine.isNull(), E_FAIL);
5850
5851 /* save hardware */
5852 {
5853 CFGNODE hwNode = 0;
5854 CFGLDRCreateChildNode (aNode, "Hardware", &hwNode);
5855
5856 HRESULT rc = snapshotMachine->saveHardware (hwNode);
5857
5858 CFGLDRReleaseNode (hwNode);
5859 if (FAILED (rc))
5860 return rc;
5861 }
5862
5863 /* save hard disks */
5864 {
5865 CFGNODE hdasNode = 0;
5866 CFGLDRCreateChildNode (aNode, "HardDiskAttachments", &hdasNode);
5867
5868 HRESULT rc = snapshotMachine->saveHardDisks (hdasNode);
5869
5870 CFGLDRReleaseNode (hdasNode);
5871 if (FAILED (rc))
5872 return rc;
5873 }
5874 }
5875
5876 /* save children */
5877 {
5878 AutoLock listLock (aSnapshot->childrenLock());
5879
5880 if (aSnapshot->children().size())
5881 {
5882 CFGNODE snapshotsNode = 0;
5883 CFGLDRCreateChildNode (aNode, "Snapshots", &snapshotsNode);
5884
5885 HRESULT rc = S_OK;
5886
5887 for (Snapshot::SnapshotList::const_iterator it = aSnapshot->children().begin();
5888 it != aSnapshot->children().end() && SUCCEEDED (rc);
5889 ++ it)
5890 {
5891 CFGNODE snapshotNode = 0;
5892 CFGLDRCreateChildNode (snapshotsNode, "Snapshot", &snapshotNode);
5893
5894 rc = saveSnapshot (snapshotNode, (*it), aAttrsOnly);
5895
5896 CFGLDRReleaseNode (snapshotNode);
5897 }
5898
5899 CFGLDRReleaseNode (snapshotsNode);
5900 if (FAILED (rc))
5901 return rc;
5902 }
5903 }
5904
5905 return S_OK;
5906}
5907
5908/**
5909 * Creates Saves the VM hardware configuration.
5910 * It is assumed that the given node is empty.
5911 *
5912 * @param aNode <Hardware> node to save the VM hardware confguration to
5913 */
5914HRESULT Machine::saveHardware (CFGNODE aNode)
5915{
5916 AssertReturn (aNode, E_INVALIDARG);
5917
5918 HRESULT rc = S_OK;
5919
5920 /* CPU */
5921 {
5922 CFGNODE cpuNode = 0;
5923 CFGLDRCreateChildNode (aNode, "CPU", &cpuNode);
5924 CFGNODE hwVirtExNode = 0;
5925 CFGLDRCreateChildNode (cpuNode, "HardwareVirtEx", &hwVirtExNode);
5926 const char *value = NULL;
5927 switch (mHWData->mHWVirtExEnabled)
5928 {
5929 case TriStateBool_False:
5930 value = "false";
5931 break;
5932 case TriStateBool_True:
5933 value = "true";
5934 break;
5935 default:
5936 value = "default";
5937 }
5938 CFGLDRSetString (hwVirtExNode, "enabled", value);
5939 CFGLDRReleaseNode (hwVirtExNode);
5940 CFGLDRReleaseNode (cpuNode);
5941 }
5942
5943 /* memory (required) */
5944 {
5945 CFGNODE memoryNode = 0;
5946 CFGLDRCreateChildNode (aNode, "Memory", &memoryNode);
5947 CFGLDRSetUInt32 (memoryNode, "RAMSize", mHWData->mMemorySize);
5948 CFGLDRReleaseNode (memoryNode);
5949 }
5950
5951 /* boot (required) */
5952 do
5953 {
5954 CFGNODE bootNode = 0;
5955 CFGLDRCreateChildNode (aNode, "Boot", &bootNode);
5956
5957 for (ULONG pos = 0; pos < ELEMENTS (mHWData->mBootOrder); pos ++)
5958 {
5959 const char *device = NULL;
5960 switch (mHWData->mBootOrder [pos])
5961 {
5962 case DeviceType_NoDevice:
5963 /* skip, this is allowed for <Order> nodes
5964 * when loading, the default value NoDevice will remain */
5965 continue;
5966 case DeviceType_FloppyDevice: device = "Floppy"; break;
5967 case DeviceType_DVDDevice: device = "DVD"; break;
5968 case DeviceType_HardDiskDevice: device = "HardDisk"; break;
5969 case DeviceType_NetworkDevice: device = "Network"; break;
5970 default:
5971 ComAssertMsgFailedBreak (("Invalid boot device: %d\n",
5972 mHWData->mBootOrder [pos]),
5973 rc = E_FAIL);
5974 }
5975 if (FAILED (rc))
5976 break;
5977
5978 CFGNODE orderNode = 0;
5979 CFGLDRAppendChildNode (bootNode, "Order", &orderNode);
5980
5981 CFGLDRSetUInt32 (orderNode, "position", pos + 1);
5982 CFGLDRSetString (orderNode, "device", device);
5983
5984 CFGLDRReleaseNode (orderNode);
5985 }
5986
5987 CFGLDRReleaseNode (bootNode);
5988 }
5989 while (0);
5990
5991 CheckComRCReturnRC (rc);
5992
5993 /* display (required) */
5994 {
5995 CFGNODE displayNode = 0;
5996 CFGLDRCreateChildNode (aNode, "Display", &displayNode);
5997 CFGLDRSetUInt32 (displayNode, "VRAMSize", mHWData->mVRAMSize);
5998 CFGLDRSetUInt32 (displayNode, "MonitorCount", mHWData->mMonitorCount);
5999 CFGLDRReleaseNode (displayNode);
6000 }
6001
6002#ifdef VBOX_VRDP
6003 /* VRDP settings (optional) */
6004 {
6005 CFGNODE remoteDisplayNode = 0;
6006 CFGLDRCreateChildNode (aNode, "RemoteDisplay", &remoteDisplayNode);
6007 if (remoteDisplayNode)
6008 {
6009 rc = mVRDPServer->saveSettings (remoteDisplayNode);
6010 CFGLDRReleaseNode (remoteDisplayNode);
6011 CheckComRCReturnRC (rc);
6012 }
6013 }
6014#endif
6015
6016 /* BIOS (required) */
6017 {
6018 CFGNODE biosNode = 0;
6019 CFGLDRCreateChildNode (aNode, "BIOS", &biosNode);
6020 {
6021 BOOL fSet;
6022 /* ACPI */
6023 CFGNODE acpiNode = 0;
6024 CFGLDRCreateChildNode (biosNode, "ACPI", &acpiNode);
6025 mBIOSSettings->COMGETTER(ACPIEnabled)(&fSet);
6026 CFGLDRSetBool (acpiNode, "enabled", !!fSet);
6027 CFGLDRReleaseNode (acpiNode);
6028
6029 /* IOAPIC */
6030 CFGNODE ioapicNode = 0;
6031 CFGLDRCreateChildNode (biosNode, "IOAPIC", &ioapicNode);
6032 mBIOSSettings->COMGETTER(IOAPICEnabled)(&fSet);
6033 CFGLDRSetBool (ioapicNode, "enabled", !!fSet);
6034 CFGLDRReleaseNode (ioapicNode);
6035
6036 /* BIOS logo (optional) **/
6037 CFGNODE logoNode = 0;
6038 CFGLDRCreateChildNode (biosNode, "Logo", &logoNode);
6039 mBIOSSettings->COMGETTER(LogoFadeIn)(&fSet);
6040 CFGLDRSetBool (logoNode, "fadeIn", !!fSet);
6041 mBIOSSettings->COMGETTER(LogoFadeOut)(&fSet);
6042 CFGLDRSetBool (logoNode, "fadeOut", !!fSet);
6043 ULONG ulDisplayTime;
6044 mBIOSSettings->COMGETTER(LogoDisplayTime)(&ulDisplayTime);
6045 CFGLDRSetUInt32 (logoNode, "displayTime", ulDisplayTime);
6046 Bstr logoPath;
6047 mBIOSSettings->COMGETTER(LogoImagePath)(logoPath.asOutParam());
6048 if (logoPath)
6049 CFGLDRSetBSTR (logoNode, "imagePath", logoPath);
6050 else
6051 CFGLDRDeleteAttribute (logoNode, "imagePath");
6052 CFGLDRReleaseNode (logoNode);
6053
6054 /* boot menu (optional) */
6055 CFGNODE bootMenuNode = 0;
6056 CFGLDRCreateChildNode (biosNode, "BootMenu", &bootMenuNode);
6057 BIOSBootMenuMode_T bootMenuMode;
6058 Bstr bootMenuModeStr;
6059 mBIOSSettings->COMGETTER(BootMenuMode)(&bootMenuMode);
6060 switch (bootMenuMode)
6061 {
6062 case BIOSBootMenuMode_Disabled:
6063 bootMenuModeStr = "disabled";
6064 break;
6065 case BIOSBootMenuMode_MenuOnly:
6066 bootMenuModeStr = "menuonly";
6067 break;
6068 default:
6069 bootMenuModeStr = "messageandmenu";
6070 }
6071 CFGLDRSetBSTR (bootMenuNode, "mode", bootMenuModeStr);
6072 CFGLDRReleaseNode (bootMenuNode);
6073
6074 /* time offset (optional) */
6075 CFGNODE timeOffsetNode = 0;
6076 CFGLDRCreateChildNode (biosNode, "TimeOffset", &timeOffsetNode);
6077 LONG64 timeOffset;
6078 mBIOSSettings->COMGETTER(TimeOffset)(&timeOffset);
6079 CFGLDRSetInt64 (timeOffsetNode, "value", timeOffset);
6080 CFGLDRReleaseNode (timeOffsetNode);
6081 }
6082 CFGLDRReleaseNode(biosNode);
6083 }
6084
6085 /* DVD drive (required) */
6086 /// @todo (dmik) move the code to DVDDrive
6087 do
6088 {
6089 CFGNODE dvdNode = 0;
6090 CFGLDRCreateChildNode (aNode, "DVDDrive", &dvdNode);
6091
6092 BOOL fPassthrough;
6093 mDVDDrive->COMGETTER(Passthrough)(&fPassthrough);
6094 CFGLDRSetBool(dvdNode, "passthrough", !!fPassthrough);
6095
6096 switch (mDVDDrive->data()->mDriveState)
6097 {
6098 case DriveState_ImageMounted:
6099 {
6100 Assert (!mDVDDrive->data()->mDVDImage.isNull());
6101
6102 Guid id;
6103 rc = mDVDDrive->data()->mDVDImage->COMGETTER(Id) (id.asOutParam());
6104 Assert (!id.isEmpty());
6105
6106 CFGNODE imageNode = 0;
6107 CFGLDRCreateChildNode (dvdNode, "Image", &imageNode);
6108 CFGLDRSetUUID (imageNode, "uuid", id.ptr());
6109 CFGLDRReleaseNode (imageNode);
6110 break;
6111 }
6112 case DriveState_HostDriveCaptured:
6113 {
6114 Assert (!mDVDDrive->data()->mHostDrive.isNull());
6115
6116 Bstr name;
6117 rc = mDVDDrive->data()->mHostDrive->COMGETTER(Name) (name.asOutParam());
6118 Assert (!name.isEmpty());
6119
6120 CFGNODE hostDriveNode = 0;
6121 CFGLDRCreateChildNode (dvdNode, "HostDrive", &hostDriveNode);
6122 CFGLDRSetBSTR (hostDriveNode, "src", name);
6123 CFGLDRReleaseNode (hostDriveNode);
6124 break;
6125 }
6126 case DriveState_NotMounted:
6127 /* do nothing, i.e.leave the DVD drive node empty */
6128 break;
6129 default:
6130 ComAssertMsgFailedBreak (("Invalid DVD drive state: %d\n",
6131 mDVDDrive->data()->mDriveState),
6132 rc = E_FAIL);
6133 }
6134
6135 CFGLDRReleaseNode (dvdNode);
6136 }
6137 while (0);
6138
6139 CheckComRCReturnRC (rc);
6140
6141 /* Flooppy drive (required) */
6142 /// @todo (dmik) move the code to DVDDrive
6143 do
6144 {
6145 CFGNODE floppyNode = 0;
6146 CFGLDRCreateChildNode (aNode, "FloppyDrive", &floppyNode);
6147
6148 BOOL fFloppyEnabled;
6149 rc = mFloppyDrive->COMGETTER(Enabled)(&fFloppyEnabled);
6150 CFGLDRSetBool (floppyNode, "enabled", !!fFloppyEnabled);
6151
6152 switch (mFloppyDrive->data()->mDriveState)
6153 {
6154 case DriveState_ImageMounted:
6155 {
6156 Assert (!mFloppyDrive->data()->mFloppyImage.isNull());
6157
6158 Guid id;
6159 rc = mFloppyDrive->data()->mFloppyImage->COMGETTER(Id) (id.asOutParam());
6160 Assert (!id.isEmpty());
6161
6162 CFGNODE imageNode = 0;
6163 CFGLDRCreateChildNode (floppyNode, "Image", &imageNode);
6164 CFGLDRSetUUID (imageNode, "uuid", id.ptr());
6165 CFGLDRReleaseNode (imageNode);
6166 break;
6167 }
6168 case DriveState_HostDriveCaptured:
6169 {
6170 Assert (!mFloppyDrive->data()->mHostDrive.isNull());
6171
6172 Bstr name;
6173 rc = mFloppyDrive->data()->mHostDrive->COMGETTER(Name) (name.asOutParam());
6174 Assert (!name.isEmpty());
6175
6176 CFGNODE hostDriveNode = 0;
6177 CFGLDRCreateChildNode (floppyNode, "HostDrive", &hostDriveNode);
6178 CFGLDRSetBSTR (hostDriveNode, "src", name);
6179 CFGLDRReleaseNode (hostDriveNode);
6180 break;
6181 }
6182 case DriveState_NotMounted:
6183 /* do nothing, i.e.leave the Floppy drive node empty */
6184 break;
6185 default:
6186 ComAssertMsgFailedBreak (("Invalid Floppy drive state: %d\n",
6187 mFloppyDrive->data()->mDriveState),
6188 rc = E_FAIL);
6189 }
6190
6191 CFGLDRReleaseNode (floppyNode);
6192 }
6193 while (0);
6194
6195 CheckComRCReturnRC (rc);
6196
6197
6198 /* USB Controller (required) */
6199 rc = mUSBController->saveSettings (aNode);
6200 CheckComRCReturnRC (rc);
6201
6202 /* Network adapters (required) */
6203 do
6204 {
6205 CFGNODE nwNode = 0;
6206 CFGLDRCreateChildNode (aNode, "Network", &nwNode);
6207
6208 for (ULONG slot = 0; slot < ELEMENTS (mNetworkAdapters); slot ++)
6209 {
6210 CFGNODE networkAdapterNode = 0;
6211 CFGLDRAppendChildNode (nwNode, "Adapter", &networkAdapterNode);
6212
6213 CFGLDRSetUInt32 (networkAdapterNode, "slot", slot);
6214 CFGLDRSetBool (networkAdapterNode, "enabled",
6215 !!mNetworkAdapters [slot]->data()->mEnabled);
6216 CFGLDRSetBSTR (networkAdapterNode, "MACAddress",
6217 mNetworkAdapters [slot]->data()->mMACAddress);
6218 CFGLDRSetBool (networkAdapterNode, "cable",
6219 !!mNetworkAdapters [slot]->data()->mCableConnected);
6220
6221 CFGLDRSetUInt32 (networkAdapterNode, "speed",
6222 mNetworkAdapters [slot]->data()->mLineSpeed);
6223
6224 if (mNetworkAdapters [slot]->data()->mTraceEnabled)
6225 CFGLDRSetBool (networkAdapterNode, "trace", true);
6226
6227 CFGLDRSetBSTR (networkAdapterNode, "tracefile",
6228 mNetworkAdapters [slot]->data()->mTraceFile);
6229
6230 switch (mNetworkAdapters [slot]->data()->mAdapterType)
6231 {
6232 case NetworkAdapterType_NetworkAdapterAm79C970A:
6233 CFGLDRSetString (networkAdapterNode, "type", "Am79C970A");
6234 break;
6235 case NetworkAdapterType_NetworkAdapterAm79C973:
6236 CFGLDRSetString (networkAdapterNode, "type", "Am79C973");
6237 break;
6238 default:
6239 ComAssertMsgFailedBreak (("Invalid network adapter type: %d\n",
6240 mNetworkAdapters [slot]->data()->mAdapterType),
6241 rc = E_FAIL);
6242 }
6243
6244 CFGNODE attachmentNode = 0;
6245 switch (mNetworkAdapters [slot]->data()->mAttachmentType)
6246 {
6247 case NetworkAttachmentType_NoNetworkAttachment:
6248 {
6249 /* do nothing -- empty content */
6250 break;
6251 }
6252 case NetworkAttachmentType_NATNetworkAttachment:
6253 {
6254 CFGLDRAppendChildNode (networkAdapterNode, "NAT", &attachmentNode);
6255 break;
6256 }
6257 case NetworkAttachmentType_HostInterfaceNetworkAttachment:
6258 {
6259 CFGLDRAppendChildNode (networkAdapterNode, "HostInterface", &attachmentNode);
6260 const Bstr &name = mNetworkAdapters [slot]->data()->mHostInterface;
6261#ifdef RT_OS_WINDOWS
6262 Assert (!name.isNull());
6263#endif
6264#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
6265 if (!name.isEmpty())
6266#endif
6267 CFGLDRSetBSTR (attachmentNode, "name", name);
6268#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
6269 const Bstr &tapSetupApp =
6270 mNetworkAdapters [slot]->data()->mTAPSetupApplication;
6271 if (!tapSetupApp.isEmpty())
6272 CFGLDRSetBSTR (attachmentNode, "TAPSetup", tapSetupApp);
6273 const Bstr &tapTerminateApp =
6274 mNetworkAdapters [slot]->data()->mTAPTerminateApplication;
6275 if (!tapTerminateApp.isEmpty())
6276 CFGLDRSetBSTR (attachmentNode, "TAPTerminate", tapTerminateApp);
6277#endif /* VBOX_WITH_UNIXY_TAP_NETWORKING */
6278 break;
6279 }
6280 case NetworkAttachmentType_InternalNetworkAttachment:
6281 {
6282 CFGLDRAppendChildNode (networkAdapterNode, "InternalNetwork", &attachmentNode);
6283 const Bstr &name = mNetworkAdapters[slot]->data()->mInternalNetwork;
6284 Assert(!name.isNull());
6285 CFGLDRSetBSTR (attachmentNode, "name", name);
6286 break;
6287 }
6288 default:
6289 {
6290 ComAssertFailedBreak (rc = E_FAIL);
6291 break;
6292 }
6293 }
6294 if (attachmentNode)
6295 CFGLDRReleaseNode (attachmentNode);
6296
6297 CFGLDRReleaseNode (networkAdapterNode);
6298 }
6299
6300 CFGLDRReleaseNode (nwNode);
6301 }
6302 while (0);
6303
6304 if (FAILED (rc))
6305 return rc;
6306
6307 /* Serial ports */
6308 CFGNODE serialNode = 0;
6309 CFGLDRCreateChildNode (aNode, "Uart", &serialNode);
6310
6311 for (ULONG slot = 0; slot < ELEMENTS (mSerialPorts); slot++)
6312 {
6313 rc = mSerialPorts [slot]->saveSettings (serialNode);
6314 CheckComRCReturnRC (rc);
6315 }
6316 CFGLDRReleaseNode (serialNode);
6317
6318 /* Parallel ports */
6319 CFGNODE parallelNode = 0;
6320 CFGLDRCreateChildNode (aNode, "Lpt", &parallelNode);
6321
6322 for (ULONG slot = 0; slot < ELEMENTS (mParallelPorts); slot++)
6323 {
6324 rc = mParallelPorts [slot]->saveSettings (parallelNode);
6325 CheckComRCReturnRC (rc);
6326 }
6327 CFGLDRReleaseNode (parallelNode);
6328
6329 /* Audio adapter */
6330 do
6331 {
6332 CFGNODE adapterNode = 0;
6333 CFGLDRCreateChildNode (aNode, "AudioAdapter", &adapterNode);
6334
6335 switch (mAudioAdapter->data()->mAudioDriver)
6336 {
6337 case AudioDriverType_NullAudioDriver:
6338 {
6339 CFGLDRSetString (adapterNode, "driver", "null");
6340 break;
6341 }
6342#ifdef RT_OS_WINDOWS
6343 case AudioDriverType_WINMMAudioDriver:
6344# ifdef VBOX_WITH_WINMM
6345 {
6346 CFGLDRSetString (adapterNode, "driver", "winmm");
6347 break;
6348 }
6349# endif
6350 case AudioDriverType_DSOUNDAudioDriver:
6351 {
6352 CFGLDRSetString (adapterNode, "driver", "dsound");
6353 break;
6354 }
6355#endif /* RT_OS_WINDOWS */
6356#ifdef RT_OS_LINUX
6357 case AudioDriverType_ALSAAudioDriver:
6358# ifdef VBOX_WITH_ALSA
6359 {
6360 CFGLDRSetString (adapterNode, "driver", "alsa");
6361 break;
6362 }
6363# endif
6364 case AudioDriverType_OSSAudioDriver:
6365 {
6366 CFGLDRSetString (adapterNode, "driver", "oss");
6367 break;
6368 }
6369#endif /* RT_OS_LINUX */
6370#ifdef RT_OS_DARWIN
6371 case AudioDriverType_CoreAudioDriver:
6372 {
6373 CFGLDRSetString (adapterNode, "driver", "coreaudio");
6374 break;
6375 }
6376#endif
6377#ifdef RT_OS_OS2
6378 case AudioDriverType_MMPMAudioDriver:
6379 {
6380 CFGLDRSetString (adapterNode, "driver", "mmpm");
6381 break;
6382 }
6383#endif
6384 default:
6385 ComAssertMsgFailedBreak (("Wrong audio driver type! driver = %d\n",
6386 mAudioAdapter->data()->mAudioDriver),
6387 rc = E_FAIL);
6388 }
6389
6390 CFGLDRSetBool (adapterNode, "enabled", !!mAudioAdapter->data()->mEnabled);
6391
6392 CFGLDRReleaseNode (adapterNode);
6393 }
6394 while (0);
6395
6396 if (FAILED (rc))
6397 return rc;
6398
6399 /* Shared folders */
6400 do
6401 {
6402 CFGNODE sharedFoldersNode = 0;
6403 CFGLDRCreateChildNode (aNode, "SharedFolders", &sharedFoldersNode);
6404
6405 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
6406 it != mHWData->mSharedFolders.end();
6407 ++ it)
6408 {
6409 ComObjPtr <SharedFolder> folder = *it;
6410
6411 CFGNODE folderNode = 0;
6412 CFGLDRAppendChildNode (sharedFoldersNode, "SharedFolder", &folderNode);
6413
6414 /* all are mandatory */
6415 CFGLDRSetBSTR (folderNode, "name", folder->name());
6416 CFGLDRSetBSTR (folderNode, "hostPath", folder->hostPath());
6417
6418 CFGLDRReleaseNode (folderNode);
6419 }
6420
6421 CFGLDRReleaseNode (sharedFoldersNode);
6422 }
6423 while (0);
6424
6425 /* Clipboard */
6426 {
6427 CFGNODE clipNode = 0;
6428 CFGLDRCreateChildNode (aNode, "Clipboard", &clipNode);
6429
6430 const char *mode = "Disabled";
6431 switch (mHWData->mClipboardMode)
6432 {
6433 case ClipboardMode_ClipDisabled:
6434 /* already assigned */
6435 break;
6436 case ClipboardMode_ClipHostToGuest:
6437 mode = "HostToGuest";
6438 break;
6439 case ClipboardMode_ClipGuestToHost:
6440 mode = "GuestToHost";
6441 break;
6442 case ClipboardMode_ClipBidirectional:
6443 mode = "Bidirectional";
6444 break;
6445 default:
6446 AssertMsgFailed (("Clipboard mode %d is invalid",
6447 mHWData->mClipboardMode));
6448 break;
6449 }
6450 CFGLDRSetString (clipNode, "mode", mode);
6451
6452 CFGLDRReleaseNode (clipNode);
6453 }
6454
6455 /* Guest */
6456 {
6457 CFGNODE guestNode = 0;
6458 CFGLDRGetChildNode (aNode, "Guest", 0, &guestNode);
6459 /* first, delete the entire node if exists */
6460 if (guestNode)
6461 CFGLDRDeleteNode (guestNode);
6462 /* then recreate it */
6463 guestNode = 0;
6464 CFGLDRCreateChildNode (aNode, "Guest", &guestNode);
6465
6466 CFGLDRSetUInt32 (guestNode, "MemoryBalloonSize",
6467 mHWData->mMemoryBalloonSize);
6468 CFGLDRSetUInt32 (guestNode, "StatisticsUpdateInterval",
6469 mHWData->mStatisticsUpdateInterval);
6470
6471 CFGLDRReleaseNode (guestNode);
6472 }
6473
6474 return rc;
6475}
6476
6477/**
6478 * Saves the hard disk confguration.
6479 * It is assumed that the given node is empty.
6480 *
6481 * @param aNode <HardDiskAttachments> node to save the hard disk confguration to
6482 */
6483HRESULT Machine::saveHardDisks (CFGNODE aNode)
6484{
6485 AssertReturn (aNode, E_INVALIDARG);
6486
6487 HRESULT rc = S_OK;
6488
6489 for (HDData::HDAttachmentList::const_iterator it = mHDData->mHDAttachments.begin();
6490 it != mHDData->mHDAttachments.end() && SUCCEEDED (rc);
6491 ++ it)
6492 {
6493 ComObjPtr <HardDiskAttachment> att = *it;
6494
6495 CFGNODE hdNode = 0;
6496 CFGLDRAppendChildNode (aNode, "HardDiskAttachment", &hdNode);
6497
6498 do
6499 {
6500 const char *bus = NULL;
6501 switch (att->controller())
6502 {
6503 case DiskControllerType_IDE0Controller: bus = "ide0"; break;
6504 case DiskControllerType_IDE1Controller: bus = "ide1"; break;
6505 default:
6506 ComAssertFailedBreak (rc = E_FAIL);
6507 }
6508 if (FAILED (rc))
6509 break;
6510
6511 const char *dev = NULL;
6512 switch (att->deviceNumber())
6513 {
6514 case 0: dev = "master"; break;
6515 case 1: dev = "slave"; break;
6516 default:
6517 ComAssertFailedBreak (rc = E_FAIL);
6518 }
6519 if (FAILED (rc))
6520 break;
6521
6522 CFGLDRSetUUID (hdNode, "hardDisk", att->hardDisk()->id());
6523 CFGLDRSetString (hdNode, "bus", bus);
6524 CFGLDRSetString (hdNode, "device", dev);
6525 }
6526 while (0);
6527
6528 CFGLDRReleaseNode (hdNode);
6529 }
6530
6531 return rc;
6532}
6533
6534/**
6535 * Saves machine state settings as defined by aFlags
6536 * (SaveSTS_* values).
6537 *
6538 * @param aFlags a combination of SaveSTS_* flags
6539 *
6540 * @note Locks objects!
6541 */
6542HRESULT Machine::saveStateSettings (int aFlags)
6543{
6544 if (aFlags == 0)
6545 return S_OK;
6546
6547 AutoCaller autoCaller (this);
6548 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
6549
6550 AutoLock alock (this);
6551
6552 /* load the config file */
6553 CFGHANDLE configLoader = 0;
6554 HRESULT rc = openConfigLoader (&configLoader);
6555 if (FAILED (rc))
6556 return rc;
6557
6558 CFGNODE machineNode = 0;
6559 CFGLDRGetNode (configLoader, "VirtualBox/Machine", 0, &machineNode);
6560
6561 do
6562 {
6563 ComAssertBreak (machineNode, rc = E_FAIL);
6564
6565 if (aFlags & SaveSTS_CurStateModified)
6566 {
6567 if (!mData->mCurrentStateModified)
6568 CFGLDRSetBool (machineNode, "currentStateModified", false);
6569 else
6570 CFGLDRDeleteAttribute (machineNode, "currentStateModified");
6571 }
6572
6573 if (aFlags & SaveSTS_StateFilePath)
6574 {
6575 if (mSSData->mStateFilePath)
6576 CFGLDRSetBSTR (machineNode, "stateFile", mSSData->mStateFilePath);
6577 else
6578 CFGLDRDeleteAttribute (machineNode, "stateFile");
6579 }
6580
6581 if (aFlags & SaveSTS_StateTimeStamp)
6582 {
6583 Assert (mData->mMachineState != MachineState_Aborted ||
6584 mSSData->mStateFilePath.isNull());
6585
6586 CFGLDRSetDateTime (machineNode, "lastStateChange",
6587 mData->mLastStateChange);
6588
6589 // set the aborted attribute when appropriate
6590 if (mData->mMachineState == MachineState_Aborted)
6591 CFGLDRSetBool (machineNode, "aborted", true);
6592 else
6593 CFGLDRDeleteAttribute (machineNode, "aborted");
6594 }
6595 }
6596 while (0);
6597
6598 if (machineNode)
6599 CFGLDRReleaseNode (machineNode);
6600
6601 if (SUCCEEDED (rc))
6602 rc = closeConfigLoader (configLoader, true /* aSaveBeforeClose */);
6603 else
6604 closeConfigLoader (configLoader, false /* aSaveBeforeClose */);
6605
6606 return rc;
6607}
6608
6609/**
6610 * Cleans up all differencing hard disks based on immutable hard disks.
6611 *
6612 * @note Locks objects!
6613 */
6614HRESULT Machine::wipeOutImmutableDiffs()
6615{
6616 AutoCaller autoCaller (this);
6617 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
6618
6619 AutoReaderLock alock (this);
6620
6621 AssertReturn (mData->mMachineState == MachineState_PoweredOff ||
6622 mData->mMachineState == MachineState_Aborted, E_FAIL);
6623
6624 for (HDData::HDAttachmentList::const_iterator it = mHDData->mHDAttachments.begin();
6625 it != mHDData->mHDAttachments.end();
6626 ++ it)
6627 {
6628 ComObjPtr <HardDisk> hd = (*it)->hardDisk();
6629 AutoLock hdLock (hd);
6630
6631 if(hd->isParentImmutable())
6632 {
6633 /// @todo (dmik) no error handling for now
6634 // (need async error reporting for this)
6635 hd->asVDI()->wipeOutImage();
6636 }
6637 }
6638
6639 return S_OK;
6640}
6641
6642/**
6643 * Fixes up lazy hard disk attachments by creating or deleting differencing
6644 * hard disks when machine settings are being committed.
6645 * Must be called only from #commit().
6646 *
6647 * @note Locks objects!
6648 */
6649HRESULT Machine::fixupHardDisks (bool aCommit)
6650{
6651 AutoCaller autoCaller (this);
6652 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
6653
6654 AutoLock alock (this);
6655
6656 /* no attac/detach operations -- nothing to do */
6657 if (!mHDData.isBackedUp())
6658 {
6659 mHDData->mHDAttachmentsChanged = false;
6660 return S_OK;
6661 }
6662
6663 AssertReturn (mData->mRegistered, E_FAIL);
6664
6665 if (aCommit)
6666 {
6667 /*
6668 * changes are being committed,
6669 * perform actual diff image creation, deletion etc.
6670 */
6671
6672 /* take a copy of backed up attachments (will modify it) */
6673 HDData::HDAttachmentList backedUp = mHDData.backedUpData()->mHDAttachments;
6674 /* list of new diffs created */
6675 std::list <ComObjPtr <HardDisk> > newDiffs;
6676
6677 HRESULT rc = S_OK;
6678
6679 /* go through current attachments */
6680 for (HDData::HDAttachmentList::const_iterator
6681 it = mHDData->mHDAttachments.begin();
6682 it != mHDData->mHDAttachments.end();
6683 ++ it)
6684 {
6685 ComObjPtr <HardDiskAttachment> hda = *it;
6686 ComObjPtr <HardDisk> hd = hda->hardDisk();
6687 AutoLock hdLock (hd);
6688
6689 if (!hda->isDirty())
6690 {
6691 /*
6692 * not dirty, therefore was either attached before backing up
6693 * or doesn't need any fixup (already fixed up); try to locate
6694 * this hard disk among backed up attachments and remove from
6695 * there to prevent it from being deassociated/deleted
6696 */
6697 HDData::HDAttachmentList::iterator oldIt;
6698 for (oldIt = backedUp.begin(); oldIt != backedUp.end(); ++ oldIt)
6699 if ((*oldIt)->hardDisk().equalsTo (hd))
6700 break;
6701 if (oldIt != backedUp.end())
6702 {
6703 /* remove from there */
6704 backedUp.erase (oldIt);
6705 Log3 (("FC: %ls found in old\n", hd->toString().raw()));
6706 }
6707 }
6708 else
6709 {
6710 /* dirty, determine what to do */
6711
6712 bool needDiff = false;
6713 bool searchAmongSnapshots = false;
6714
6715 switch (hd->type())
6716 {
6717 case HardDiskType_ImmutableHardDisk:
6718 {
6719 /* decrease readers increased in AttachHardDisk() */
6720 hd->releaseReader();
6721 Log3 (("FC: %ls released\n", hd->toString().raw()));
6722 /* indicate we need a diff (indirect attachment) */
6723 needDiff = true;
6724 break;
6725 }
6726 case HardDiskType_WritethroughHardDisk:
6727 {
6728 /* reset the dirty flag */
6729 hda->updateHardDisk (hd, false /* aDirty */);
6730 Log3 (("FC: %ls updated\n", hd->toString().raw()));
6731 break;
6732 }
6733 case HardDiskType_NormalHardDisk:
6734 {
6735 if (hd->snapshotId().isEmpty())
6736 {
6737 /* reset the dirty flag */
6738 hda->updateHardDisk (hd, false /* aDirty */);
6739 Log3 (("FC: %ls updated\n", hd->toString().raw()));
6740 }
6741 else
6742 {
6743 /* decrease readers increased in AttachHardDisk() */
6744 hd->releaseReader();
6745 Log3 (("FC: %ls released\n", hd->toString().raw()));
6746 /* indicate we need a diff (indirect attachment) */
6747 needDiff = true;
6748 /* search for the most recent base among snapshots */
6749 searchAmongSnapshots = true;
6750 }
6751 break;
6752 }
6753 }
6754
6755 if (!needDiff)
6756 continue;
6757
6758 bool createDiff = false;
6759
6760 /*
6761 * see whether any previously attached hard disk has the
6762 * the currently attached one (Normal or Independent) as
6763 * the root
6764 */
6765
6766 HDData::HDAttachmentList::iterator foundIt = backedUp.end();
6767
6768 for (HDData::HDAttachmentList::iterator it = backedUp.begin();
6769 it != backedUp.end();
6770 ++ it)
6771 {
6772 if ((*it)->hardDisk()->root().equalsTo (hd))
6773 {
6774 /*
6775 * matched dev and ctl (i.e. attached to the same place)
6776 * will win and immediately stop the search; otherwise
6777 * the first attachment that matched the hd only will
6778 * be used
6779 */
6780 if ((*it)->deviceNumber() == hda->deviceNumber() &&
6781 (*it)->controller() == hda->controller())
6782 {
6783 foundIt = it;
6784 break;
6785 }
6786 else
6787 if (foundIt == backedUp.end())
6788 {
6789 /*
6790 * not an exact match; ensure there is no exact match
6791 * among other current attachments referring the same
6792 * root (to prevent this attachmend from reusing the
6793 * hard disk of the other attachment that will later
6794 * give the exact match or already gave it before)
6795 */
6796 bool canReuse = true;
6797 for (HDData::HDAttachmentList::const_iterator
6798 it2 = mHDData->mHDAttachments.begin();
6799 it2 != mHDData->mHDAttachments.end();
6800 ++ it2)
6801 {
6802 if ((*it2)->deviceNumber() == (*it)->deviceNumber() &&
6803 (*it2)->controller() == (*it)->controller() &&
6804 (*it2)->hardDisk()->root().equalsTo (hd))
6805 {
6806 /*
6807 * the exact match, either non-dirty or dirty
6808 * one refers the same root: in both cases
6809 * we cannot reuse the hard disk, so break
6810 */
6811 canReuse = false;
6812 break;
6813 }
6814 }
6815
6816 if (canReuse)
6817 foundIt = it;
6818 }
6819 }
6820 }
6821
6822 if (foundIt != backedUp.end())
6823 {
6824 /* found either one or another, reuse the diff */
6825 hda->updateHardDisk ((*foundIt)->hardDisk(),
6826 false /* aDirty */);
6827 Log3 (("FC: %ls reused as %ls\n", hd->toString().raw(),
6828 (*foundIt)->hardDisk()->toString().raw()));
6829 /* remove from there */
6830 backedUp.erase (foundIt);
6831 }
6832 else
6833 {
6834 /* was not attached, need a diff */
6835 createDiff = true;
6836 }
6837
6838 if (!createDiff)
6839 continue;
6840
6841 ComObjPtr <HardDisk> baseHd = hd;
6842
6843 if (searchAmongSnapshots)
6844 {
6845 /*
6846 * find the most recent diff based on the currently
6847 * attached root (Normal hard disk) among snapshots
6848 */
6849
6850 ComObjPtr <Snapshot> snap = mData->mCurrentSnapshot;
6851
6852 while (snap)
6853 {
6854 AutoLock snapLock (snap);
6855
6856 const HDData::HDAttachmentList &snapAtts =
6857 snap->data().mMachine->hdData()->mHDAttachments;
6858
6859 HDData::HDAttachmentList::const_iterator foundIt = snapAtts.end();
6860
6861 for (HDData::HDAttachmentList::const_iterator
6862 it = snapAtts.begin(); it != snapAtts.end(); ++ it)
6863 {
6864 if ((*it)->hardDisk()->root().equalsTo (hd))
6865 {
6866 /*
6867 * matched dev and ctl (i.e. attached to the same place)
6868 * will win and immediately stop the search; otherwise
6869 * the first attachment that matched the hd only will
6870 * be used
6871 */
6872 if ((*it)->deviceNumber() == hda->deviceNumber() &&
6873 (*it)->controller() == hda->controller())
6874 {
6875 foundIt = it;
6876 break;
6877 }
6878 else
6879 if (foundIt == snapAtts.end())
6880 foundIt = it;
6881 }
6882 }
6883
6884 if (foundIt != snapAtts.end())
6885 {
6886 /* the most recent diff has been found, use as a base */
6887 baseHd = (*foundIt)->hardDisk();
6888 Log3 (("FC: %ls: recent found %ls\n",
6889 hd->toString().raw(), baseHd->toString().raw()));
6890 break;
6891 }
6892
6893 snap = snap->parent();
6894 }
6895 }
6896
6897 /* create a new diff for the hard disk being indirectly attached */
6898
6899 AutoLock baseHdLock (baseHd);
6900 baseHd->addReader();
6901
6902 ComObjPtr <HVirtualDiskImage> vdi;
6903 rc = baseHd->createDiffHardDisk (mUserData->mSnapshotFolderFull,
6904 mData->mUuid, vdi, NULL);
6905 baseHd->releaseReader();
6906 CheckComRCBreakRC (rc);
6907
6908 newDiffs.push_back (ComObjPtr <HardDisk> (vdi));
6909
6910 /* update the attachment and reset the dirty flag */
6911 hda->updateHardDisk (ComObjPtr <HardDisk> (vdi),
6912 false /* aDirty */);
6913 Log3 (("FC: %ls: diff created %ls\n",
6914 baseHd->toString().raw(), vdi->toString().raw()));
6915 }
6916 }
6917
6918 if (FAILED (rc))
6919 {
6920 /* delete diffs we created */
6921 for (std::list <ComObjPtr <HardDisk> >::const_iterator
6922 it = newDiffs.begin(); it != newDiffs.end(); ++ it)
6923 {
6924 /*
6925 * unregisterDiffHardDisk() is supposed to delete and uninit
6926 * the differencing hard disk
6927 */
6928 mParent->unregisterDiffHardDisk (*it);
6929 /* too bad if we fail here, but nothing to do, just continue */
6930 }
6931
6932 /* the best is to rollback the changes... */
6933 mHDData.rollback();
6934 mHDData->mHDAttachmentsChanged = false;
6935 Log3 (("FC: ROLLED BACK\n"));
6936 return rc;
6937 }
6938
6939 /*
6940 * go through the rest of old attachments and delete diffs
6941 * or deassociate hard disks from machines (they will become detached)
6942 */
6943 for (HDData::HDAttachmentList::iterator
6944 it = backedUp.begin(); it != backedUp.end(); ++ it)
6945 {
6946 ComObjPtr <HardDiskAttachment> hda = *it;
6947 ComObjPtr <HardDisk> hd = hda->hardDisk();
6948 AutoLock hdLock (hd);
6949
6950 if (hd->isDifferencing())
6951 {
6952 /*
6953 * unregisterDiffHardDisk() is supposed to delete and uninit
6954 * the differencing hard disk
6955 */
6956 Log3 (("FC: %ls diff deleted\n", hd->toString().raw()));
6957 rc = mParent->unregisterDiffHardDisk (hd);
6958 /*
6959 * too bad if we fail here, but nothing to do, just continue
6960 * (the last rc will be returned to the caller though)
6961 */
6962 }
6963 else
6964 {
6965 /* deassociate from this machine */
6966 Log3 (("FC: %ls deassociated\n", hd->toString().raw()));
6967 hd->setMachineId (Guid());
6968 }
6969 }
6970
6971 /* commit all the changes */
6972 mHDData->mHDAttachmentsChanged = mHDData.hasActualChanges();
6973 mHDData.commit();
6974 Log3 (("FC: COMMITTED\n"));
6975
6976 return rc;
6977 }
6978
6979 /*
6980 * changes are being rolled back,
6981 * go trhough all current attachments and fix up dirty ones
6982 * the way it is done in DetachHardDisk()
6983 */
6984
6985 for (HDData::HDAttachmentList::iterator it = mHDData->mHDAttachments.begin();
6986 it != mHDData->mHDAttachments.end();
6987 ++ it)
6988 {
6989 ComObjPtr <HardDiskAttachment> hda = *it;
6990 ComObjPtr <HardDisk> hd = hda->hardDisk();
6991 AutoLock hdLock (hd);
6992
6993 if (hda->isDirty())
6994 {
6995 switch (hd->type())
6996 {
6997 case HardDiskType_ImmutableHardDisk:
6998 {
6999 /* decrease readers increased in AttachHardDisk() */
7000 hd->releaseReader();
7001 Log3 (("FR: %ls released\n", hd->toString().raw()));
7002 break;
7003 }
7004 case HardDiskType_WritethroughHardDisk:
7005 {
7006 /* deassociate from this machine */
7007 hd->setMachineId (Guid());
7008 Log3 (("FR: %ls deassociated\n", hd->toString().raw()));
7009 break;
7010 }
7011 case HardDiskType_NormalHardDisk:
7012 {
7013 if (hd->snapshotId().isEmpty())
7014 {
7015 /* deassociate from this machine */
7016 hd->setMachineId (Guid());
7017 Log3 (("FR: %ls deassociated\n", hd->toString().raw()));
7018 }
7019 else
7020 {
7021 /* decrease readers increased in AttachHardDisk() */
7022 hd->releaseReader();
7023 Log3 (("FR: %ls released\n", hd->toString().raw()));
7024 }
7025
7026 break;
7027 }
7028 }
7029 }
7030 }
7031
7032 /* rollback all the changes */
7033 mHDData.rollback();
7034 Log3 (("FR: ROLLED BACK\n"));
7035
7036 return S_OK;
7037}
7038
7039/**
7040 * Creates differencing hard disks for all normal hard disks
7041 * and replaces attachments to refer to created disks.
7042 * Used when taking a snapshot or when discarding the current state.
7043 *
7044 * @param aSnapshotId ID of the snapshot being taken
7045 * or NULL if the current state is being discarded
7046 * @param aFolder folder where to create diff. hard disks
7047 * @param aProgress progress object to run (must contain at least as
7048 * many operations left as the number of VDIs attached)
7049 * @param aOnline whether the machine is online (i.e., when the EMT
7050 * thread is paused, OR when current hard disks are
7051 * marked as busy for some other reason)
7052 *
7053 * @note
7054 * The progress object is not marked as completed, neither on success
7055 * nor on failure. This is a responsibility of the caller.
7056 *
7057 * @note Locks mParent + this object for writing
7058 */
7059HRESULT Machine::createSnapshotDiffs (const Guid *aSnapshotId,
7060 const Bstr &aFolder,
7061 const ComObjPtr <Progress> &aProgress,
7062 bool aOnline)
7063{
7064 AssertReturn (!aFolder.isEmpty(), E_FAIL);
7065
7066 AutoCaller autoCaller (this);
7067 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
7068
7069 /* accessing mParent methods below needs mParent lock */
7070 AutoMultiLock <2> alock (mParent->wlock(), this->wlock());
7071
7072 HRESULT rc = S_OK;
7073
7074 // first pass: check accessibility before performing changes
7075 if (!aOnline)
7076 {
7077 for (HDData::HDAttachmentList::const_iterator it = mHDData->mHDAttachments.begin();
7078 it != mHDData->mHDAttachments.end();
7079 ++ it)
7080 {
7081 ComObjPtr <HardDiskAttachment> hda = *it;
7082 ComObjPtr <HardDisk> hd = hda->hardDisk();
7083 AutoLock hdLock (hd);
7084
7085 ComAssertMsgBreak (hd->type() == HardDiskType_NormalHardDisk,
7086 ("Invalid hard disk type %d\n", hd->type()),
7087 rc = E_FAIL);
7088
7089 ComAssertMsgBreak (!hd->isParentImmutable() ||
7090 hd->storageType() == HardDiskStorageType_VirtualDiskImage,
7091 ("Invalid hard disk storage type %d\n", hd->storageType()),
7092 rc = E_FAIL);
7093
7094 Bstr accessError;
7095 rc = hd->getAccessible (accessError);
7096 CheckComRCBreakRC (rc);
7097
7098 if (!accessError.isNull())
7099 {
7100 rc = setError (E_FAIL,
7101 tr ("Hard disk '%ls' is not accessible (%ls)"),
7102 hd->toString().raw(), accessError.raw());
7103 break;
7104 }
7105 }
7106 CheckComRCReturnRC (rc);
7107 }
7108
7109 HDData::HDAttachmentList attachments;
7110
7111 // second pass: perform changes
7112 for (HDData::HDAttachmentList::const_iterator it = mHDData->mHDAttachments.begin();
7113 it != mHDData->mHDAttachments.end();
7114 ++ it)
7115 {
7116 ComObjPtr <HardDiskAttachment> hda = *it;
7117 ComObjPtr <HardDisk> hd = hda->hardDisk();
7118 AutoLock hdLock (hd);
7119
7120 ComObjPtr <HardDisk> parent = hd->parent();
7121 AutoLock parentHdLock (parent);
7122
7123 ComObjPtr <HardDisk> newHd;
7124
7125 // clear busy flag if the VM is online
7126 if (aOnline)
7127 hd->clearBusy();
7128 // increase readers
7129 hd->addReader();
7130
7131 if (hd->isParentImmutable())
7132 {
7133 aProgress->advanceOperation (Bstr (Utf8StrFmt (
7134 tr ("Preserving immutable hard disk '%ls'"),
7135 parent->toString (true /* aShort */).raw())));
7136
7137 parentHdLock.unlock();
7138 alock.leave();
7139
7140 // create a copy of the independent diff
7141 ComObjPtr <HVirtualDiskImage> vdi;
7142 rc = hd->asVDI()->cloneDiffImage (aFolder, mData->mUuid, vdi,
7143 aProgress);
7144 newHd = vdi;
7145
7146 alock.enter();
7147 parentHdLock.lock();
7148
7149 // decrease readers (hd is no more used for reading in any case)
7150 hd->releaseReader();
7151 }
7152 else
7153 {
7154 // checked in the first pass
7155 Assert (hd->type() == HardDiskType_NormalHardDisk);
7156
7157 aProgress->advanceOperation (Bstr (Utf8StrFmt (
7158 tr ("Creating a differencing hard disk for '%ls'"),
7159 hd->root()->toString (true /* aShort */).raw())));
7160
7161 parentHdLock.unlock();
7162 alock.leave();
7163
7164 // create a new diff for the image being attached
7165 ComObjPtr <HVirtualDiskImage> vdi;
7166 rc = hd->createDiffHardDisk (aFolder, mData->mUuid, vdi, aProgress);
7167 newHd = vdi;
7168
7169 alock.enter();
7170 parentHdLock.lock();
7171
7172 if (SUCCEEDED (rc))
7173 {
7174 // if online, hd must keep a reader referece
7175 if (!aOnline)
7176 hd->releaseReader();
7177 }
7178 else
7179 {
7180 // decrease readers
7181 hd->releaseReader();
7182 }
7183 }
7184
7185 if (SUCCEEDED (rc))
7186 {
7187 ComObjPtr <HardDiskAttachment> newHda;
7188 newHda.createObject();
7189 rc = newHda->init (newHd, hda->controller(), hda->deviceNumber(),
7190 false /* aDirty */);
7191
7192 if (SUCCEEDED (rc))
7193 {
7194 // associate the snapshot id with the old hard disk
7195 if (hd->type() != HardDiskType_WritethroughHardDisk && aSnapshotId)
7196 hd->setSnapshotId (*aSnapshotId);
7197
7198 // add the new attachment
7199 attachments.push_back (newHda);
7200
7201 // if online, newHd must be marked as busy
7202 if (aOnline)
7203 newHd->setBusy();
7204 }
7205 }
7206
7207 if (FAILED (rc))
7208 {
7209 // set busy flag back if the VM is online
7210 if (aOnline)
7211 hd->setBusy();
7212 break;
7213 }
7214 }
7215
7216 if (SUCCEEDED (rc))
7217 {
7218 // replace the whole list of attachments with the new one
7219 mHDData->mHDAttachments = attachments;
7220 }
7221 else
7222 {
7223 // delete those diffs we've just created
7224 for (HDData::HDAttachmentList::const_iterator it = attachments.begin();
7225 it != attachments.end();
7226 ++ it)
7227 {
7228 ComObjPtr <HardDisk> hd = (*it)->hardDisk();
7229 AutoLock hdLock (hd);
7230 Assert (hd->children().size() == 0);
7231 Assert (hd->isDifferencing());
7232 // unregisterDiffHardDisk() is supposed to delete and uninit
7233 // the differencing hard disk
7234 mParent->unregisterDiffHardDisk (hd);
7235 }
7236 }
7237
7238 return rc;
7239}
7240
7241/**
7242 * Deletes differencing hard disks created by createSnapshotDiffs() in case
7243 * if snapshot creation was failed.
7244 *
7245 * @param aSnapshot failed snapshot
7246 *
7247 * @note Locks mParent + this object for writing.
7248 */
7249HRESULT Machine::deleteSnapshotDiffs (const ComObjPtr <Snapshot> &aSnapshot)
7250{
7251 AssertReturn (!aSnapshot.isNull(), E_FAIL);
7252
7253 AutoCaller autoCaller (this);
7254 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
7255
7256 /* accessing mParent methods below needs mParent lock */
7257 AutoMultiLock <2> alock (mParent->wlock(), this->wlock());
7258
7259 /* short cut: check whether attachments are all the same */
7260 if (mHDData->mHDAttachments == aSnapshot->data().mMachine->mHDData->mHDAttachments)
7261 return S_OK;
7262
7263 HRESULT rc = S_OK;
7264
7265 for (HDData::HDAttachmentList::const_iterator it = mHDData->mHDAttachments.begin();
7266 it != mHDData->mHDAttachments.end();
7267 ++ it)
7268 {
7269 ComObjPtr <HardDiskAttachment> hda = *it;
7270 ComObjPtr <HardDisk> hd = hda->hardDisk();
7271 AutoLock hdLock (hd);
7272
7273 ComObjPtr <HardDisk> parent = hd->parent();
7274 AutoLock parentHdLock (parent);
7275
7276 if (!parent || parent->snapshotId() != aSnapshot->data().mId)
7277 continue;
7278
7279 /* must not have children */
7280 ComAssertRet (hd->children().size() == 0, E_FAIL);
7281
7282 /* deassociate the old hard disk from the given snapshot's ID */
7283 parent->setSnapshotId (Guid());
7284
7285 /* unregisterDiffHardDisk() is supposed to delete and uninit
7286 * the differencing hard disk */
7287 rc = mParent->unregisterDiffHardDisk (hd);
7288 /* continue on error */
7289 }
7290
7291 /* restore the whole list of attachments from the failed snapshot */
7292 mHDData->mHDAttachments = aSnapshot->data().mMachine->mHDData->mHDAttachments;
7293
7294 return rc;
7295}
7296
7297/**
7298 * Helper to lock the machine configuration for write access.
7299 *
7300 * @return S_OK or E_FAIL and sets error info on failure
7301 *
7302 * @note Doesn't lock anything (must be called from this object's lock)
7303 */
7304HRESULT Machine::lockConfig()
7305{
7306 HRESULT rc = S_OK;
7307
7308 if (!isConfigLocked())
7309 {
7310 /* open the associated config file */
7311 int vrc = RTFileOpen (&mData->mHandleCfgFile,
7312 Utf8Str (mData->mConfigFileFull),
7313 RTFILE_O_READWRITE | RTFILE_O_OPEN |
7314 RTFILE_O_DENY_WRITE);
7315 if (VBOX_FAILURE (vrc))
7316 mData->mHandleCfgFile = NIL_RTFILE;
7317 }
7318
7319 LogFlowThisFunc (("mConfigFile={%ls}, mHandleCfgFile=%d, rc=%08X\n",
7320 mData->mConfigFileFull.raw(), mData->mHandleCfgFile, rc));
7321 return rc;
7322}
7323
7324/**
7325 * Helper to unlock the machine configuration from write access
7326 *
7327 * @return S_OK
7328 *
7329 * @note Doesn't lock anything.
7330 * @note Not thread safe (must be called from this object's lock).
7331 */
7332HRESULT Machine::unlockConfig()
7333{
7334 HRESULT rc = S_OK;
7335
7336 if (isConfigLocked())
7337 {
7338 RTFileFlush(mData->mHandleCfgFile);
7339 RTFileClose(mData->mHandleCfgFile);
7340 /** @todo flush the directory. */
7341 mData->mHandleCfgFile = NIL_RTFILE;
7342 }
7343
7344 LogFlowThisFunc (("\n"));
7345
7346 return rc;
7347}
7348
7349/**
7350 * Returns true if the settings file is located in the directory named exactly
7351 * as the machine. This will be true if the machine settings structure was
7352 * created by default in #openConfigLoader().
7353 *
7354 * @param aSettingsDir if not NULL, the full machine settings file directory
7355 * name will be assigned there.
7356 *
7357 * @note Doesn't lock anything.
7358 * @note Not thread safe (must be called from this object's lock).
7359 */
7360bool Machine::isInOwnDir (Utf8Str *aSettingsDir /* = NULL */)
7361{
7362 Utf8Str settingsDir = mData->mConfigFileFull;
7363 RTPathStripFilename (settingsDir.mutableRaw());
7364 char *dirName = RTPathFilename (settingsDir);
7365
7366 AssertReturn (dirName, false);
7367
7368 /* if we don't rename anything on name change, return false shorlty */
7369 if (!mUserData->mNameSync)
7370 return false;
7371
7372 if (aSettingsDir)
7373 *aSettingsDir = settingsDir;
7374
7375 return Bstr (dirName) == mUserData->mName;
7376}
7377
7378/**
7379 * @note Locks objects for reading!
7380 */
7381bool Machine::isModified()
7382{
7383 AutoCaller autoCaller (this);
7384 AssertComRCReturn (autoCaller.rc(), false);
7385
7386 AutoReaderLock alock (this);
7387
7388 for (ULONG slot = 0; slot < ELEMENTS (mNetworkAdapters); slot ++)
7389 if (mNetworkAdapters [slot] && mNetworkAdapters [slot]->isModified())
7390 return true;
7391
7392 for (ULONG slot = 0; slot < ELEMENTS (mSerialPorts); slot ++)
7393 if (mSerialPorts [slot] && mSerialPorts [slot]->isModified())
7394 return true;
7395
7396 for (ULONG slot = 0; slot < ELEMENTS (mParallelPorts); slot ++)
7397 if (mParallelPorts [slot] && mParallelPorts [slot]->isModified())
7398 return true;
7399
7400 return
7401 mUserData.isBackedUp() ||
7402 mHWData.isBackedUp() ||
7403 mHDData.isBackedUp() ||
7404#ifdef VBOX_VRDP
7405 (mVRDPServer && mVRDPServer->isModified()) ||
7406#endif
7407 (mDVDDrive && mDVDDrive->isModified()) ||
7408 (mFloppyDrive && mFloppyDrive->isModified()) ||
7409 (mAudioAdapter && mAudioAdapter->isModified()) ||
7410 (mUSBController && mUSBController->isModified()) ||
7411 (mBIOSSettings && mBIOSSettings->isModified());
7412}
7413
7414/**
7415 * @note This method doesn't check (ignores) actual changes to mHDData.
7416 * Use mHDData.mHDAttachmentsChanged right after #commit() instead.
7417 *
7418 * @param aIgnoreUserData |true| to ignore changes to mUserData
7419 *
7420 * @note Locks objects for reading!
7421 */
7422bool Machine::isReallyModified (bool aIgnoreUserData /* = false */)
7423{
7424 AutoCaller autoCaller (this);
7425 AssertComRCReturn (autoCaller.rc(), false);
7426
7427 AutoReaderLock alock (this);
7428
7429 for (ULONG slot = 0; slot < ELEMENTS (mNetworkAdapters); slot ++)
7430 if (mNetworkAdapters [slot] && mNetworkAdapters [slot]->isReallyModified())
7431 return true;
7432
7433 for (ULONG slot = 0; slot < ELEMENTS (mSerialPorts); slot ++)
7434 if (mSerialPorts [slot] && mSerialPorts [slot]->isReallyModified())
7435 return true;
7436
7437 for (ULONG slot = 0; slot < ELEMENTS (mParallelPorts); slot ++)
7438 if (mParallelPorts [slot] && mParallelPorts [slot]->isReallyModified())
7439 return true;
7440
7441 return
7442 (!aIgnoreUserData && mUserData.hasActualChanges()) ||
7443 mHWData.hasActualChanges() ||
7444 /* ignore mHDData */
7445 //mHDData.hasActualChanges() ||
7446#ifdef VBOX_VRDP
7447 (mVRDPServer && mVRDPServer->isReallyModified()) ||
7448#endif
7449 (mDVDDrive && mDVDDrive->isReallyModified()) ||
7450 (mFloppyDrive && mFloppyDrive->isReallyModified()) ||
7451 (mAudioAdapter && mAudioAdapter->isReallyModified()) ||
7452 (mUSBController && mUSBController->isReallyModified()) ||
7453 (mBIOSSettings && mBIOSSettings->isReallyModified());
7454}
7455
7456/**
7457 * Discards all changes to machine settings.
7458 *
7459 * @param aNotify whether to notify the direct session about changes or not
7460 *
7461 * @note Locks objects!
7462 */
7463void Machine::rollback (bool aNotify)
7464{
7465 AutoCaller autoCaller (this);
7466 AssertComRCReturn (autoCaller.rc(), (void) 0);
7467
7468 AutoLock alock (this);
7469
7470 /* check for changes in own data */
7471
7472 bool sharedFoldersChanged = false;
7473
7474 if (aNotify && mHWData.isBackedUp())
7475 {
7476 if (mHWData->mSharedFolders.size() !=
7477 mHWData.backedUpData()->mSharedFolders.size())
7478 sharedFoldersChanged = true;
7479 else
7480 {
7481 for (HWData::SharedFolderList::iterator rit =
7482 mHWData->mSharedFolders.begin();
7483 rit != mHWData->mSharedFolders.end() && !sharedFoldersChanged;
7484 ++ rit)
7485 {
7486 for (HWData::SharedFolderList::iterator cit =
7487 mHWData.backedUpData()->mSharedFolders.begin();
7488 cit != mHWData.backedUpData()->mSharedFolders.end();
7489 ++ cit)
7490 {
7491 if ((*cit)->name() != (*rit)->name() ||
7492 (*cit)->hostPath() != (*rit)->hostPath())
7493 {
7494 sharedFoldersChanged = true;
7495 break;
7496 }
7497 }
7498 }
7499 }
7500 }
7501
7502 mUserData.rollback();
7503
7504 mHWData.rollback();
7505
7506 if (mHDData.isBackedUp())
7507 fixupHardDisks (false /* aCommit */);
7508
7509 /* check for changes in child objects */
7510
7511 bool vrdpChanged = false, dvdChanged = false, floppyChanged = false,
7512 usbChanged = false;
7513
7514 ComPtr <INetworkAdapter> networkAdapters [ELEMENTS (mNetworkAdapters)];
7515 ComPtr <ISerialPort> serialPorts [ELEMENTS (mSerialPorts)];
7516 ComPtr <IParallelPort> parallelPorts [ELEMENTS (mParallelPorts)];
7517
7518 if (mBIOSSettings)
7519 mBIOSSettings->rollback();
7520
7521#ifdef VBOX_VRDP
7522 if (mVRDPServer)
7523 vrdpChanged = mVRDPServer->rollback();
7524#endif
7525
7526 if (mDVDDrive)
7527 dvdChanged = mDVDDrive->rollback();
7528
7529 if (mFloppyDrive)
7530 floppyChanged = mFloppyDrive->rollback();
7531
7532 if (mAudioAdapter)
7533 mAudioAdapter->rollback();
7534
7535 if (mUSBController)
7536 usbChanged = mUSBController->rollback();
7537
7538 for (ULONG slot = 0; slot < ELEMENTS (mNetworkAdapters); slot ++)
7539 if (mNetworkAdapters [slot])
7540 if (mNetworkAdapters [slot]->rollback())
7541 networkAdapters [slot] = mNetworkAdapters [slot];
7542
7543 for (ULONG slot = 0; slot < ELEMENTS (mSerialPorts); slot ++)
7544 if (mSerialPorts [slot])
7545 if (mSerialPorts [slot]->rollback())
7546 serialPorts [slot] = mSerialPorts [slot];
7547
7548 for (ULONG slot = 0; slot < ELEMENTS (mParallelPorts); slot ++)
7549 if (mParallelPorts [slot])
7550 if (mParallelPorts [slot]->rollback())
7551 parallelPorts [slot] = mParallelPorts [slot];
7552
7553 if (aNotify)
7554 {
7555 /* inform the direct session about changes */
7556
7557 ComObjPtr <Machine> that = this;
7558 alock.leave();
7559
7560 if (sharedFoldersChanged)
7561 that->onSharedFolderChange();
7562
7563 if (vrdpChanged)
7564 that->onVRDPServerChange();
7565 if (dvdChanged)
7566 that->onDVDDriveChange();
7567 if (floppyChanged)
7568 that->onFloppyDriveChange();
7569 if (usbChanged)
7570 that->onUSBControllerChange();
7571
7572 for (ULONG slot = 0; slot < ELEMENTS (networkAdapters); slot ++)
7573 if (networkAdapters [slot])
7574 that->onNetworkAdapterChange (networkAdapters [slot]);
7575 for (ULONG slot = 0; slot < ELEMENTS (serialPorts); slot ++)
7576 if (serialPorts [slot])
7577 that->onSerialPortChange (serialPorts [slot]);
7578 for (ULONG slot = 0; slot < ELEMENTS (parallelPorts); slot ++)
7579 if (parallelPorts [slot])
7580 that->onParallelPortChange (parallelPorts [slot]);
7581 }
7582}
7583
7584/**
7585 * Commits all the changes to machine settings.
7586 *
7587 * Note that when committing fails at some stage, it still continues
7588 * until the end. So, all data will either be actually committed or rolled
7589 * back (for failed cases) and the returned result code will describe the
7590 * first failure encountered. However, #isModified() will still return true
7591 * in case of failure, to indicade that settings in memory and on disk are
7592 * out of sync.
7593 *
7594 * @note Locks objects!
7595 */
7596HRESULT Machine::commit()
7597{
7598 AutoCaller autoCaller (this);
7599 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
7600
7601 AutoLock alock (this);
7602
7603 HRESULT rc = S_OK;
7604
7605 /*
7606 * use safe commit to ensure Snapshot machines (that share mUserData)
7607 * will still refer to a valid memory location
7608 */
7609 mUserData.commitCopy();
7610
7611 mHWData.commit();
7612
7613 if (mHDData.isBackedUp())
7614 rc = fixupHardDisks (true /* aCommit */);
7615
7616 mBIOSSettings->commit();
7617#ifdef VBOX_VRDP
7618 mVRDPServer->commit();
7619#endif
7620 mDVDDrive->commit();
7621 mFloppyDrive->commit();
7622 mAudioAdapter->commit();
7623 mUSBController->commit();
7624
7625 for (ULONG slot = 0; slot < ELEMENTS (mNetworkAdapters); slot ++)
7626 mNetworkAdapters [slot]->commit();
7627 for (ULONG slot = 0; slot < ELEMENTS (mSerialPorts); slot ++)
7628 mSerialPorts [slot]->commit();
7629 for (ULONG slot = 0; slot < ELEMENTS (mParallelPorts); slot ++)
7630 mParallelPorts [slot]->commit();
7631
7632 if (mType == IsSessionMachine)
7633 {
7634 /* attach new data to the primary machine and reshare it */
7635 mPeer->mUserData.attach (mUserData);
7636 mPeer->mHWData.attach (mHWData);
7637 mPeer->mHDData.attach (mHDData);
7638 }
7639
7640 if (FAILED (rc))
7641 {
7642 /*
7643 * backup arbitrary data item to cause #isModified() to still return
7644 * true in case of any error
7645 */
7646 mHWData.backup();
7647 }
7648
7649 return rc;
7650}
7651
7652/**
7653 * Copies all the hardware data from the given machine.
7654 *
7655 * @note
7656 * This method must be called from under this object's lock.
7657 * @note
7658 * This method doesn't call #commit(), so all data remains backed up
7659 * and unsaved.
7660 */
7661void Machine::copyFrom (Machine *aThat)
7662{
7663 AssertReturn (mType == IsMachine || mType == IsSessionMachine, (void) 0);
7664 AssertReturn (aThat->mType == IsSnapshotMachine, (void) 0);
7665
7666 mHWData.assignCopy (aThat->mHWData);
7667
7668 // create copies of all shared folders (mHWData after attiching a copy
7669 // contains just references to original objects)
7670 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
7671 it != mHWData->mSharedFolders.end();
7672 ++ it)
7673 {
7674 ComObjPtr <SharedFolder> folder;
7675 folder.createObject();
7676 HRESULT rc = folder->initCopy (machine(), *it);
7677 AssertComRC (rc);
7678 *it = folder;
7679 }
7680
7681 mBIOSSettings->copyFrom (aThat->mBIOSSettings);
7682#ifdef VBOX_VRDP
7683 mVRDPServer->copyFrom (aThat->mVRDPServer);
7684#endif
7685 mDVDDrive->copyFrom (aThat->mDVDDrive);
7686 mFloppyDrive->copyFrom (aThat->mFloppyDrive);
7687 mAudioAdapter->copyFrom (aThat->mAudioAdapter);
7688 mUSBController->copyFrom (aThat->mUSBController);
7689
7690 for (ULONG slot = 0; slot < ELEMENTS (mNetworkAdapters); slot ++)
7691 mNetworkAdapters [slot]->copyFrom (aThat->mNetworkAdapters [slot]);
7692 for (ULONG slot = 0; slot < ELEMENTS (mSerialPorts); slot ++)
7693 mSerialPorts [slot]->copyFrom (aThat->mSerialPorts [slot]);
7694 for (ULONG slot = 0; slot < ELEMENTS (mParallelPorts); slot ++)
7695 mParallelPorts [slot]->copyFrom (aThat->mParallelPorts [slot]);
7696}
7697
7698/////////////////////////////////////////////////////////////////////////////
7699// SessionMachine class
7700/////////////////////////////////////////////////////////////////////////////
7701
7702/** Task structure for asynchronous VM operations */
7703struct SessionMachine::Task
7704{
7705 Task (SessionMachine *m, Progress *p)
7706 : machine (m), progress (p)
7707 , state (m->data()->mMachineState) // save the current machine state
7708 , subTask (false), settingsChanged (false)
7709 {}
7710
7711 void modifyLastState (MachineState_T s)
7712 {
7713 *const_cast <MachineState_T *> (&state) = s;
7714 }
7715
7716 virtual void handler() = 0;
7717
7718 const ComObjPtr <SessionMachine> machine;
7719 const ComObjPtr <Progress> progress;
7720 const MachineState_T state;
7721
7722 bool subTask : 1;
7723 bool settingsChanged : 1;
7724};
7725
7726/** Take snapshot task */
7727struct SessionMachine::TakeSnapshotTask : public SessionMachine::Task
7728{
7729 TakeSnapshotTask (SessionMachine *m)
7730 : Task (m, NULL) {}
7731
7732 void handler() { machine->takeSnapshotHandler (*this); }
7733};
7734
7735/** Discard snapshot task */
7736struct SessionMachine::DiscardSnapshotTask : public SessionMachine::Task
7737{
7738 DiscardSnapshotTask (SessionMachine *m, Progress *p, Snapshot *s)
7739 : Task (m, p)
7740 , snapshot (s) {}
7741
7742 DiscardSnapshotTask (const Task &task, Snapshot *s)
7743 : Task (task)
7744 , snapshot (s) {}
7745
7746 void handler() { machine->discardSnapshotHandler (*this); }
7747
7748 const ComObjPtr <Snapshot> snapshot;
7749};
7750
7751/** Discard current state task */
7752struct SessionMachine::DiscardCurrentStateTask : public SessionMachine::Task
7753{
7754 DiscardCurrentStateTask (SessionMachine *m, Progress *p,
7755 bool discardCurSnapshot)
7756 : Task (m, p), discardCurrentSnapshot (discardCurSnapshot) {}
7757
7758 void handler() { machine->discardCurrentStateHandler (*this); }
7759
7760 const bool discardCurrentSnapshot;
7761};
7762
7763////////////////////////////////////////////////////////////////////////////////
7764
7765DEFINE_EMPTY_CTOR_DTOR (SessionMachine)
7766
7767HRESULT SessionMachine::FinalConstruct()
7768{
7769 LogFlowThisFunc (("\n"));
7770
7771 /* set the proper type to indicate we're the SessionMachine instance */
7772 unconst (mType) = IsSessionMachine;
7773
7774#if defined(RT_OS_WINDOWS)
7775 mIPCSem = NULL;
7776#elif defined(RT_OS_OS2)
7777 mIPCSem = NULLHANDLE;
7778#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
7779 mIPCSem = -1;
7780#else
7781# error "Port me!"
7782#endif
7783
7784 return S_OK;
7785}
7786
7787void SessionMachine::FinalRelease()
7788{
7789 LogFlowThisFunc (("\n"));
7790
7791 uninit (Uninit::Unexpected);
7792}
7793
7794/**
7795 * @note Must be called only by Machine::openSession() from its own write lock.
7796 */
7797HRESULT SessionMachine::init (Machine *aMachine)
7798{
7799 LogFlowThisFuncEnter();
7800 LogFlowThisFunc (("mName={%ls}\n", aMachine->mUserData->mName.raw()));
7801
7802 AssertReturn (aMachine, E_INVALIDARG);
7803
7804 AssertReturn (aMachine->lockHandle()->isLockedOnCurrentThread(), E_FAIL);
7805
7806 /* Enclose the state transition NotReady->InInit->Ready */
7807 AutoInitSpan autoInitSpan (this);
7808 AssertReturn (autoInitSpan.isOk(), E_UNEXPECTED);
7809
7810 /* create the interprocess semaphore */
7811#if defined(RT_OS_WINDOWS)
7812 mIPCSemName = aMachine->mData->mConfigFileFull;
7813 for (size_t i = 0; i < mIPCSemName.length(); i++)
7814 if (mIPCSemName[i] == '\\')
7815 mIPCSemName[i] = '/';
7816 mIPCSem = ::CreateMutex (NULL, FALSE, mIPCSemName);
7817 ComAssertMsgRet (mIPCSem,
7818 ("Cannot create IPC mutex '%ls', err=%d\n",
7819 mIPCSemName.raw(), ::GetLastError()),
7820 E_FAIL);
7821#elif defined(RT_OS_OS2)
7822 Utf8Str ipcSem = Utf8StrFmt ("\\SEM32\\VBOX\\VM\\{%Vuuid}",
7823 aMachine->mData->mUuid.raw());
7824 mIPCSemName = ipcSem;
7825 APIRET arc = ::DosCreateMutexSem ((PSZ) ipcSem.raw(), &mIPCSem, 0, FALSE);
7826 ComAssertMsgRet (arc == NO_ERROR,
7827 ("Cannot create IPC mutex '%s', arc=%ld\n",
7828 ipcSem.raw(), arc),
7829 E_FAIL);
7830#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
7831 Utf8Str configFile = aMachine->mData->mConfigFileFull;
7832 char *configFileCP = NULL;
7833 RTStrUtf8ToCurrentCP (&configFileCP, configFile);
7834 key_t key = ::ftok (configFileCP, 0);
7835 RTStrFree (configFileCP);
7836 mIPCSem = ::semget (key, 1, S_IRWXU | S_IRWXG | S_IRWXO | IPC_CREAT);
7837 ComAssertMsgRet (mIPCSem >= 0, ("Cannot create IPC semaphore, errno=%d", errno),
7838 E_FAIL);
7839 /* set the initial value to 1 */
7840 int rv = ::semctl (mIPCSem, 0, SETVAL, 1);
7841 ComAssertMsgRet (rv == 0, ("Cannot init IPC semaphore, errno=%d", errno),
7842 E_FAIL);
7843#else
7844# error "Port me!"
7845#endif
7846
7847 /* memorize the peer Machine */
7848 unconst (mPeer) = aMachine;
7849 /* share the parent pointer */
7850 unconst (mParent) = aMachine->mParent;
7851
7852 /* take the pointers to data to share */
7853 mData.share (aMachine->mData);
7854 mSSData.share (aMachine->mSSData);
7855
7856 mUserData.share (aMachine->mUserData);
7857 mHWData.share (aMachine->mHWData);
7858 mHDData.share (aMachine->mHDData);
7859
7860 unconst (mBIOSSettings).createObject();
7861 mBIOSSettings->init (this, aMachine->mBIOSSettings);
7862#ifdef VBOX_VRDP
7863 /* create another VRDPServer object that will be mutable */
7864 unconst (mVRDPServer).createObject();
7865 mVRDPServer->init (this, aMachine->mVRDPServer);
7866#endif
7867 /* create another DVD drive object that will be mutable */
7868 unconst (mDVDDrive).createObject();
7869 mDVDDrive->init (this, aMachine->mDVDDrive);
7870 /* create another floppy drive object that will be mutable */
7871 unconst (mFloppyDrive).createObject();
7872 mFloppyDrive->init (this, aMachine->mFloppyDrive);
7873 /* create another audio adapter object that will be mutable */
7874 unconst (mAudioAdapter).createObject();
7875 mAudioAdapter->init (this, aMachine->mAudioAdapter);
7876 /* create a list of serial ports that will be mutable */
7877 for (ULONG slot = 0; slot < ELEMENTS (mSerialPorts); slot ++)
7878 {
7879 unconst (mSerialPorts [slot]).createObject();
7880 mSerialPorts [slot]->init (this, aMachine->mSerialPorts [slot]);
7881 }
7882 /* create a list of parallel ports that will be mutable */
7883 for (ULONG slot = 0; slot < ELEMENTS (mParallelPorts); slot ++)
7884 {
7885 unconst (mParallelPorts [slot]).createObject();
7886 mParallelPorts [slot]->init (this, aMachine->mParallelPorts [slot]);
7887 }
7888 /* create another USB controller object that will be mutable */
7889 unconst (mUSBController).createObject();
7890 mUSBController->init (this, aMachine->mUSBController);
7891 /* create a list of network adapters that will be mutable */
7892 for (ULONG slot = 0; slot < ELEMENTS (mNetworkAdapters); slot ++)
7893 {
7894 unconst (mNetworkAdapters [slot]).createObject();
7895 mNetworkAdapters [slot]->init (this, aMachine->mNetworkAdapters [slot]);
7896 }
7897
7898 /* Confirm a successful initialization when it's the case */
7899 autoInitSpan.setSucceeded();
7900
7901 LogFlowThisFuncLeave();
7902 return S_OK;
7903}
7904
7905/**
7906 * Uninitializes this session object. If the reason is other than
7907 * Uninit::Unexpected, then this method MUST be called from #checkForDeath().
7908 *
7909 * @param aReason uninitialization reason
7910 *
7911 * @note Locks mParent + this object for writing.
7912 */
7913void SessionMachine::uninit (Uninit::Reason aReason)
7914{
7915 LogFlowThisFuncEnter();
7916 LogFlowThisFunc (("reason=%d\n", aReason));
7917
7918 /*
7919 * Strongly reference ourselves to prevent this object deletion after
7920 * mData->mSession.mMachine.setNull() below (which can release the last
7921 * reference and call the destructor). Important: this must be done before
7922 * accessing any members (and before AutoUninitSpan that does it as well).
7923 * This self reference will be released as the very last step on return.
7924 */
7925 ComObjPtr <SessionMachine> selfRef = this;
7926
7927 /* Enclose the state transition Ready->InUninit->NotReady */
7928 AutoUninitSpan autoUninitSpan (this);
7929 if (autoUninitSpan.uninitDone())
7930 {
7931 LogFlowThisFunc (("Already uninitialized\n"));
7932 LogFlowThisFuncLeave();
7933 return;
7934 }
7935
7936 if (autoUninitSpan.initFailed())
7937 {
7938 /*
7939 * We've been called by init() because it's failed. It's not really
7940 * necessary (nor it's safe) to perform the regular uninit sequence
7941 * below, the following is enough.
7942 */
7943 LogFlowThisFunc (("Initialization failed.\n"));
7944#if defined(RT_OS_WINDOWS)
7945 if (mIPCSem)
7946 ::CloseHandle (mIPCSem);
7947 mIPCSem = NULL;
7948#elif defined(RT_OS_OS2)
7949 if (mIPCSem != NULLHANDLE)
7950 ::DosCloseMutexSem (mIPCSem);
7951 mIPCSem = NULLHANDLE;
7952#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
7953 if (mIPCSem >= 0)
7954 ::semctl (mIPCSem, 0, IPC_RMID);
7955 mIPCSem = -1;
7956#else
7957# error "Port me!"
7958#endif
7959 uninitDataAndChildObjects();
7960 unconst (mParent).setNull();
7961 unconst (mPeer).setNull();
7962 LogFlowThisFuncLeave();
7963 return;
7964 }
7965
7966 /*
7967 * We need to lock this object in uninit() because the lock is shared
7968 * with mPeer (as well as data we modify below).
7969 * mParent->addProcessToReap() and others need mParent lock.
7970 */
7971 AutoMultiLock <2> alock (mParent->wlock(), this->wlock());
7972
7973 MachineState_T lastState = mData->mMachineState;
7974
7975 if (aReason == Uninit::Abnormal)
7976 {
7977 LogWarningThisFunc (("ABNORMAL client termination! (wasRunning=%d)\n",
7978 lastState >= MachineState_Running));
7979
7980 /* reset the state to Aborted */
7981 if (mData->mMachineState != MachineState_Aborted)
7982 setMachineState (MachineState_Aborted);
7983 }
7984
7985 if (isModified())
7986 {
7987 LogWarningThisFunc (("Discarding unsaved settings changes!\n"));
7988 rollback (false /* aNotify */);
7989 }
7990
7991 Assert (!mSnapshotData.mStateFilePath || !mSnapshotData.mSnapshot);
7992 if (mSnapshotData.mStateFilePath)
7993 {
7994 LogWarningThisFunc (("canceling failed save state request!\n"));
7995 endSavingState (FALSE /* aSuccess */);
7996 }
7997 else if (!!mSnapshotData.mSnapshot)
7998 {
7999 LogWarningThisFunc (("canceling untaken snapshot!\n"));
8000 endTakingSnapshot (FALSE /* aSuccess */);
8001 }
8002
8003 /* release all captured USB devices */
8004 if (aReason == Uninit::Abnormal && lastState >= MachineState_Running)
8005 {
8006 /* Console::captureUSBDevices() is called in the VM process only after
8007 * setting the machine state to Starting or Restoring.
8008 * Console::detachAllUSBDevices() will be called upon successful
8009 * termination. So, we need to release USB devices only if there was
8010 * an abnormal termination of a running VM. */
8011 DetachAllUSBDevices (TRUE /* aDone */);
8012 }
8013
8014 if (!mData->mSession.mType.isNull())
8015 {
8016 /* mType is not null when this machine's process has been started by
8017 * VirtualBox::OpenRemoteSession(), therefore it is our child. We
8018 * need to queue the PID to reap the process (and avoid zombies on
8019 * Linux). */
8020 Assert (mData->mSession.mPid != NIL_RTPROCESS);
8021 mParent->addProcessToReap (mData->mSession.mPid);
8022 }
8023
8024 mData->mSession.mPid = NIL_RTPROCESS;
8025
8026 if (aReason == Uninit::Unexpected)
8027 {
8028 /* Uninitialization didn't come from #checkForDeath(), so tell the
8029 * client watcher thread to update the set of machines that have open
8030 * sessions. */
8031 mParent->updateClientWatcher();
8032 }
8033
8034 /* uninitialize all remote controls */
8035 if (mData->mSession.mRemoteControls.size())
8036 {
8037 LogFlowThisFunc (("Closing remote sessions (%d):\n",
8038 mData->mSession.mRemoteControls.size()));
8039
8040 Data::Session::RemoteControlList::iterator it =
8041 mData->mSession.mRemoteControls.begin();
8042 while (it != mData->mSession.mRemoteControls.end())
8043 {
8044 LogFlowThisFunc ((" Calling remoteControl->Uninitialize()...\n"));
8045 HRESULT rc = (*it)->Uninitialize();
8046 LogFlowThisFunc ((" remoteControl->Uninitialize() returned %08X\n", rc));
8047 if (FAILED (rc))
8048 LogWarningThisFunc (("Forgot to close the remote session?\n"));
8049 ++ it;
8050 }
8051 mData->mSession.mRemoteControls.clear();
8052 }
8053
8054 /*
8055 * An expected uninitialization can come only from #checkForDeath().
8056 * Otherwise it means that something's got really wrong (for examlple,
8057 * the Session implementation has released the VirtualBox reference
8058 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
8059 * etc). However, it's also possible, that the client releases the IPC
8060 * semaphore correctly (i.e. before it releases the VirtualBox reference),
8061 * but but the VirtualBox release event comes first to the server process.
8062 * This case is practically possible, so we should not assert on an
8063 * unexpected uninit, just log a warning.
8064 */
8065
8066 if ((aReason == Uninit::Unexpected))
8067 LogWarningThisFunc (("Unexpected SessionMachine uninitialization!\n"));
8068
8069 if (aReason != Uninit::Normal)
8070 mData->mSession.mDirectControl.setNull();
8071 else
8072 {
8073 /* this must be null here (see #OnSessionEnd()) */
8074 Assert (mData->mSession.mDirectControl.isNull());
8075 Assert (mData->mSession.mState == SessionState_SessionClosing);
8076 Assert (!mData->mSession.mProgress.isNull());
8077
8078 mData->mSession.mProgress->notifyComplete (S_OK);
8079 mData->mSession.mProgress.setNull();
8080 }
8081
8082 /* remove the association between the peer machine and this session machine */
8083 Assert (mData->mSession.mMachine == this ||
8084 aReason == Uninit::Unexpected);
8085
8086 /* reset the rest of session data */
8087 mData->mSession.mMachine.setNull();
8088 mData->mSession.mState = SessionState_SessionClosed;
8089 mData->mSession.mType.setNull();
8090
8091 /* close the interprocess semaphore before leaving the shared lock */
8092#if defined(RT_OS_WINDOWS)
8093 if (mIPCSem)
8094 ::CloseHandle (mIPCSem);
8095 mIPCSem = NULL;
8096#elif defined(RT_OS_OS2)
8097 if (mIPCSem != NULLHANDLE)
8098 ::DosCloseMutexSem (mIPCSem);
8099 mIPCSem = NULLHANDLE;
8100#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
8101 if (mIPCSem >= 0)
8102 ::semctl (mIPCSem, 0, IPC_RMID);
8103 mIPCSem = -1;
8104#else
8105# error "Port me!"
8106#endif
8107
8108 /* fire an event */
8109 mParent->onSessionStateChange (mData->mUuid, SessionState_SessionClosed);
8110
8111 uninitDataAndChildObjects();
8112
8113 /* leave the shared lock before setting the above two to NULL */
8114 alock.leave();
8115
8116 unconst (mParent).setNull();
8117 unconst (mPeer).setNull();
8118
8119 LogFlowThisFuncLeave();
8120}
8121
8122// AutoLock::Lockable interface
8123////////////////////////////////////////////////////////////////////////////////
8124
8125/**
8126 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
8127 * with the primary Machine instance (mPeer).
8128 */
8129AutoLock::Handle *SessionMachine::lockHandle() const
8130{
8131 AssertReturn (!mPeer.isNull(), NULL);
8132 return mPeer->lockHandle();
8133}
8134
8135// IInternalMachineControl methods
8136////////////////////////////////////////////////////////////////////////////////
8137
8138/**
8139 * @note Locks the same as #setMachineState() does.
8140 */
8141STDMETHODIMP SessionMachine::UpdateState (MachineState_T machineState)
8142{
8143 return setMachineState (machineState);
8144}
8145
8146/**
8147 * @note Locks this object for reading.
8148 */
8149STDMETHODIMP SessionMachine::GetIPCId (BSTR *id)
8150{
8151 AutoCaller autoCaller (this);
8152 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8153
8154 AutoReaderLock alock (this);
8155
8156#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
8157 mIPCSemName.cloneTo (id);
8158 return S_OK;
8159#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
8160 mData->mConfigFileFull.cloneTo (id);
8161 return S_OK;
8162#else
8163# error "Port me!"
8164#endif
8165}
8166
8167/**
8168 * Goes through the USB filters of the given machine to see if the given
8169 * device matches any filter or not.
8170 *
8171 * @note Locks the same as USBController::hasMatchingFilter() does.
8172 */
8173STDMETHODIMP SessionMachine::RunUSBDeviceFilters (IUSBDevice *aUSBDevice,
8174 BOOL *aMatched)
8175{
8176 LogFlowThisFunc (("\n"));
8177
8178 if (!aUSBDevice)
8179 return E_INVALIDARG;
8180 if (!aMatched)
8181 return E_POINTER;
8182
8183 AutoCaller autoCaller (this);
8184 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8185
8186 *aMatched = mUSBController->hasMatchingFilter (aUSBDevice);
8187
8188 return S_OK;
8189}
8190
8191/**
8192 * @note Locks the same as Host::captureUSBDevice() does.
8193 */
8194STDMETHODIMP SessionMachine::CaptureUSBDevice (INPTR GUIDPARAM aId)
8195{
8196 LogFlowThisFunc (("\n"));
8197
8198 AutoCaller autoCaller (this);
8199 AssertComRCReturnRC (autoCaller.rc());
8200
8201 /* if cautureUSBDevice() fails, it must have set extended error info */
8202 return mParent->host()->captureUSBDevice (this, aId);
8203}
8204
8205/**
8206 * @note Locks the same as Host::detachUSBDevice() does.
8207 */
8208STDMETHODIMP SessionMachine::DetachUSBDevice (INPTR GUIDPARAM aId, BOOL aDone)
8209{
8210 LogFlowThisFunc (("\n"));
8211
8212 AutoCaller autoCaller (this);
8213 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8214
8215 return mParent->host()->detachUSBDevice (this, aId, aDone);
8216}
8217
8218/**
8219 * Inserts all machine filters to the USB proxy service and then calls
8220 * Host::autoCaptureUSBDevices().
8221 *
8222 * Called by Console from the VM process upon VM startup.
8223 *
8224 * @note Locks what called methods lock.
8225 */
8226STDMETHODIMP SessionMachine::AutoCaptureUSBDevices()
8227{
8228 LogFlowThisFunc (("\n"));
8229
8230 AutoCaller autoCaller (this);
8231 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8232
8233 HRESULT rc = mUSBController->notifyProxy (true /* aInsertFilters */);
8234 AssertComRC (rc);
8235 NOREF (rc);
8236
8237 return mParent->host()->autoCaptureUSBDevices (this);
8238}
8239
8240/**
8241 * Removes all machine filters from the USB proxy service and then calls
8242 * Host::detachAllUSBDevices().
8243 *
8244 * Called by Console from the VM process upon normal VM termination or by
8245 * SessionMachine::uninit() upon abnormal VM termination (from under the
8246 * Machine/SessionMachine lock).
8247 *
8248 * @note Locks what called methods lock.
8249 */
8250STDMETHODIMP SessionMachine::DetachAllUSBDevices(BOOL aDone)
8251{
8252 LogFlowThisFunc (("\n"));
8253
8254 AutoCaller autoCaller (this);
8255 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8256
8257 HRESULT rc = mUSBController->notifyProxy (false /* aInsertFilters */);
8258 AssertComRC (rc);
8259 NOREF (rc);
8260
8261 return mParent->host()->detachAllUSBDevices (this, aDone);
8262}
8263
8264/**
8265 * @note Locks mParent + this object for writing.
8266 */
8267STDMETHODIMP SessionMachine::OnSessionEnd (ISession *aSession,
8268 IProgress **aProgress)
8269{
8270 LogFlowThisFuncEnter();
8271
8272 AssertReturn (aSession, E_INVALIDARG);
8273 AssertReturn (aProgress, E_INVALIDARG);
8274
8275 AutoCaller autoCaller (this);
8276
8277 LogFlowThisFunc (("state=%d\n", autoCaller.state()));
8278 /*
8279 * We don't assert below because it might happen that a non-direct session
8280 * informs us it is closed right after we've been uninitialized -- it's ok.
8281 */
8282 CheckComRCReturnRC (autoCaller.rc());
8283
8284 /* get IInternalSessionControl interface */
8285 ComPtr <IInternalSessionControl> control (aSession);
8286
8287 ComAssertRet (!control.isNull(), E_INVALIDARG);
8288
8289 /* Progress::init() needs mParent lock */
8290 AutoMultiLock <2> alock (mParent->wlock(), this->wlock());
8291
8292 if (control.equalsTo (mData->mSession.mDirectControl))
8293 {
8294 ComAssertRet (aProgress, E_POINTER);
8295
8296 /* The direct session is being normally closed by the client process
8297 * ----------------------------------------------------------------- */
8298
8299 /* go to the closing state (essential for all open*Session() calls and
8300 * for #checkForDeath()) */
8301 Assert (mData->mSession.mState == SessionState_SessionOpen);
8302 mData->mSession.mState = SessionState_SessionClosing;
8303
8304 /* set direct control to NULL to release the remote instance */
8305 mData->mSession.mDirectControl.setNull();
8306 LogFlowThisFunc (("Direct control is set to NULL\n"));
8307
8308 /*
8309 * Create the progress object the client will use to wait until
8310 * #checkForDeath() is called to uninitialize this session object
8311 * after it releases the IPC semaphore.
8312 */
8313 ComObjPtr <Progress> progress;
8314 progress.createObject();
8315 progress->init (mParent, (IMachine *) mPeer, Bstr (tr ("Closing session")),
8316 FALSE /* aCancelable */);
8317 progress.queryInterfaceTo (aProgress);
8318 mData->mSession.mProgress = progress;
8319 }
8320 else
8321 {
8322 /* the remote session is being normally closed */
8323 Data::Session::RemoteControlList::iterator it =
8324 mData->mSession.mRemoteControls.begin();
8325 while (it != mData->mSession.mRemoteControls.end())
8326 {
8327 if (control.equalsTo (*it))
8328 break;
8329 ++it;
8330 }
8331 BOOL found = it != mData->mSession.mRemoteControls.end();
8332 ComAssertMsgRet (found, ("The session is not found in the session list!"),
8333 E_INVALIDARG);
8334 mData->mSession.mRemoteControls.remove (*it);
8335 }
8336
8337 LogFlowThisFuncLeave();
8338 return S_OK;
8339}
8340
8341/**
8342 * @note Locks mParent + this object for writing.
8343 */
8344STDMETHODIMP SessionMachine::BeginSavingState (IProgress *aProgress, BSTR *aStateFilePath)
8345{
8346 LogFlowThisFuncEnter();
8347
8348 AssertReturn (aProgress, E_INVALIDARG);
8349 AssertReturn (aStateFilePath, E_POINTER);
8350
8351 AutoCaller autoCaller (this);
8352 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8353
8354 /* mParent->addProgress() needs mParent lock */
8355 AutoMultiLock <2> alock (mParent->wlock(), this->wlock());
8356
8357 AssertReturn (mData->mMachineState == MachineState_Paused &&
8358 mSnapshotData.mLastState == MachineState_InvalidMachineState &&
8359 mSnapshotData.mProgressId.isEmpty() &&
8360 mSnapshotData.mStateFilePath.isNull(),
8361 E_FAIL);
8362
8363 /* memorize the progress ID and add it to the global collection */
8364 Guid progressId;
8365 HRESULT rc = aProgress->COMGETTER(Id) (progressId.asOutParam());
8366 AssertComRCReturn (rc, rc);
8367 rc = mParent->addProgress (aProgress);
8368 AssertComRCReturn (rc, rc);
8369
8370 Bstr stateFilePath;
8371 /* stateFilePath is null when the machine is not running */
8372 if (mData->mMachineState == MachineState_Paused)
8373 {
8374 stateFilePath = Utf8StrFmt ("%ls%c{%Vuuid}.sav",
8375 mUserData->mSnapshotFolderFull.raw(),
8376 RTPATH_DELIMITER, mData->mUuid.raw());
8377 }
8378
8379 /* fill in the snapshot data */
8380 mSnapshotData.mLastState = mData->mMachineState;
8381 mSnapshotData.mProgressId = progressId;
8382 mSnapshotData.mStateFilePath = stateFilePath;
8383
8384 /* set the state to Saving (this is expected by Console::SaveState()) */
8385 setMachineState (MachineState_Saving);
8386
8387 stateFilePath.cloneTo (aStateFilePath);
8388
8389 return S_OK;
8390}
8391
8392/**
8393 * @note Locks mParent + this objects for writing.
8394 */
8395STDMETHODIMP SessionMachine::EndSavingState (BOOL aSuccess)
8396{
8397 LogFlowThisFunc (("\n"));
8398
8399 AutoCaller autoCaller (this);
8400 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8401
8402 /* endSavingState() need mParent lock */
8403 AutoMultiLock <2> alock (mParent->wlock(), this->wlock());
8404
8405 AssertReturn (mData->mMachineState == MachineState_Saving &&
8406 mSnapshotData.mLastState != MachineState_InvalidMachineState &&
8407 !mSnapshotData.mProgressId.isEmpty() &&
8408 !mSnapshotData.mStateFilePath.isNull(),
8409 E_FAIL);
8410
8411 /*
8412 * on success, set the state to Saved;
8413 * on failure, set the state to the state we had when BeginSavingState() was
8414 * called (this is expected by Console::SaveState() and
8415 * Console::saveStateThread())
8416 */
8417 if (aSuccess)
8418 setMachineState (MachineState_Saved);
8419 else
8420 setMachineState (mSnapshotData.mLastState);
8421
8422 return endSavingState (aSuccess);
8423}
8424
8425/**
8426 * @note Locks mParent + this objects for writing.
8427 */
8428STDMETHODIMP SessionMachine::BeginTakingSnapshot (
8429 IConsole *aInitiator, INPTR BSTR aName, INPTR BSTR aDescription,
8430 IProgress *aProgress, BSTR *aStateFilePath,
8431 IProgress **aServerProgress)
8432{
8433 LogFlowThisFuncEnter();
8434
8435 AssertReturn (aInitiator && aName, E_INVALIDARG);
8436 AssertReturn (aStateFilePath && aServerProgress, E_POINTER);
8437
8438 LogFlowThisFunc (("aName='%ls'\n", aName));
8439
8440 AutoCaller autoCaller (this);
8441 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8442
8443 /* Progress::init() needs mParent lock */
8444 AutoMultiLock <2> alock (mParent->wlock(), this->wlock());
8445
8446 AssertReturn ((mData->mMachineState < MachineState_Running ||
8447 mData->mMachineState == MachineState_Paused) &&
8448 mSnapshotData.mLastState == MachineState_InvalidMachineState &&
8449 mSnapshotData.mSnapshot.isNull() &&
8450 mSnapshotData.mServerProgress.isNull() &&
8451 mSnapshotData.mCombinedProgress.isNull(),
8452 E_FAIL);
8453
8454 bool takingSnapshotOnline = mData->mMachineState == MachineState_Paused;
8455
8456 if (!takingSnapshotOnline && mData->mMachineState != MachineState_Saved)
8457 {
8458 /*
8459 * save all current settings to ensure current changes are committed
8460 * and hard disks are fixed up
8461 */
8462 HRESULT rc = saveSettings();
8463 CheckComRCReturnRC (rc);
8464 }
8465
8466 /* check that there are no Writethrough hard disks attached */
8467 for (HDData::HDAttachmentList::const_iterator
8468 it = mHDData->mHDAttachments.begin();
8469 it != mHDData->mHDAttachments.end();
8470 ++ it)
8471 {
8472 ComObjPtr <HardDisk> hd = (*it)->hardDisk();
8473 AutoLock hdLock (hd);
8474 if (hd->type() == HardDiskType_WritethroughHardDisk)
8475 return setError (E_FAIL,
8476 tr ("Cannot take a snapshot when there is a Writethrough hard "
8477 " disk attached ('%ls')"), hd->toString().raw());
8478 }
8479
8480 AssertReturn (aProgress || !takingSnapshotOnline, E_FAIL);
8481
8482 /* create an ID for the snapshot */
8483 Guid snapshotId;
8484 snapshotId.create();
8485
8486 Bstr stateFilePath;
8487 /* stateFilePath is null when the machine is not online nor saved */
8488 if (takingSnapshotOnline || mData->mMachineState == MachineState_Saved)
8489 stateFilePath = Utf8StrFmt ("%ls%c{%Vuuid}.sav",
8490 mUserData->mSnapshotFolderFull.raw(),
8491 RTPATH_DELIMITER,
8492 snapshotId.ptr());
8493
8494 /* ensure the directory for the saved state file exists */
8495 if (stateFilePath)
8496 {
8497 Utf8Str dir = stateFilePath;
8498 RTPathStripFilename (dir.mutableRaw());
8499 if (!RTDirExists (dir))
8500 {
8501 int vrc = RTDirCreateFullPath (dir, 0777);
8502 if (VBOX_FAILURE (vrc))
8503 return setError (E_FAIL,
8504 tr ("Could not create a directory '%s' to save the "
8505 "VM state to (%Vrc)"),
8506 dir.raw(), vrc);
8507 }
8508 }
8509
8510 /* create a snapshot machine object */
8511 ComObjPtr <SnapshotMachine> snapshotMachine;
8512 snapshotMachine.createObject();
8513 HRESULT rc = snapshotMachine->init (this, snapshotId, stateFilePath);
8514 AssertComRCReturn (rc, rc);
8515
8516 Bstr progressDesc = Bstr (tr ("Taking snapshot of virtual machine"));
8517 Bstr firstOpDesc = Bstr (tr ("Preparing to take snapshot"));
8518
8519 /*
8520 * create a server-side progress object (it will be descriptionless
8521 * when we need to combine it with the VM-side progress, i.e. when we're
8522 * taking a snapshot online). The number of operations is:
8523 * 1 (preparing) + # of VDIs + 1 (if the state is saved so we need to copy it)
8524 */
8525 ComObjPtr <Progress> serverProgress;
8526 {
8527 ULONG opCount = 1 + mHDData->mHDAttachments.size();
8528 if (mData->mMachineState == MachineState_Saved)
8529 opCount ++;
8530 serverProgress.createObject();
8531 if (takingSnapshotOnline)
8532 rc = serverProgress->init (FALSE, opCount, firstOpDesc);
8533 else
8534 rc = serverProgress->init (mParent, aInitiator, progressDesc, FALSE,
8535 opCount, firstOpDesc);
8536 AssertComRCReturn (rc, rc);
8537 }
8538
8539 /* create a combined server-side progress object when necessary */
8540 ComObjPtr <CombinedProgress> combinedProgress;
8541 if (takingSnapshotOnline)
8542 {
8543 combinedProgress.createObject();
8544 rc = combinedProgress->init (mParent, aInitiator, progressDesc,
8545 serverProgress, aProgress);
8546 AssertComRCReturn (rc, rc);
8547 }
8548
8549 /* create a snapshot object */
8550 RTTIMESPEC time;
8551 ComObjPtr <Snapshot> snapshot;
8552 snapshot.createObject();
8553 rc = snapshot->init (snapshotId, aName, aDescription,
8554 RTTimeSpecGetMilli (RTTimeNow (&time)),
8555 snapshotMachine, mData->mCurrentSnapshot);
8556 AssertComRCReturn (rc, rc);
8557
8558 /*
8559 * create and start the task on a separate thread
8560 * (note that it will not start working until we release alock)
8561 */
8562 TakeSnapshotTask *task = new TakeSnapshotTask (this);
8563 int vrc = RTThreadCreate (NULL, taskHandler,
8564 (void *) task,
8565 0, RTTHREADTYPE_MAIN_WORKER, 0, "TakeSnapshot");
8566 if (VBOX_FAILURE (vrc))
8567 {
8568 snapshot->uninit();
8569 delete task;
8570 ComAssertFailedRet (E_FAIL);
8571 }
8572
8573 /* fill in the snapshot data */
8574 mSnapshotData.mLastState = mData->mMachineState;
8575 mSnapshotData.mSnapshot = snapshot;
8576 mSnapshotData.mServerProgress = serverProgress;
8577 mSnapshotData.mCombinedProgress = combinedProgress;
8578
8579 /* set the state to Saving (this is expected by Console::TakeSnapshot()) */
8580 setMachineState (MachineState_Saving);
8581
8582 if (takingSnapshotOnline)
8583 stateFilePath.cloneTo (aStateFilePath);
8584 else
8585 *aStateFilePath = NULL;
8586
8587 serverProgress.queryInterfaceTo (aServerProgress);
8588
8589 LogFlowThisFuncLeave();
8590 return S_OK;
8591}
8592
8593/**
8594 * @note Locks mParent + this objects for writing.
8595 */
8596STDMETHODIMP SessionMachine::EndTakingSnapshot (BOOL aSuccess)
8597{
8598 LogFlowThisFunc (("\n"));
8599
8600 AutoCaller autoCaller (this);
8601 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8602
8603 /* Lock mParent because of endTakingSnapshot() */
8604 AutoMultiLock <2> alock (mParent->wlock(), this->wlock());
8605
8606 AssertReturn (!aSuccess ||
8607 (mData->mMachineState == MachineState_Saving &&
8608 mSnapshotData.mLastState != MachineState_InvalidMachineState &&
8609 !mSnapshotData.mSnapshot.isNull() &&
8610 !mSnapshotData.mServerProgress.isNull() &&
8611 !mSnapshotData.mCombinedProgress.isNull()),
8612 E_FAIL);
8613
8614 /*
8615 * set the state to the state we had when BeginTakingSnapshot() was called
8616 * (this is expected by Console::TakeSnapshot() and
8617 * Console::saveStateThread())
8618 */
8619 setMachineState (mSnapshotData.mLastState);
8620
8621 return endTakingSnapshot (aSuccess);
8622}
8623
8624/**
8625 * @note Locks mParent + this + children objects for writing!
8626 */
8627STDMETHODIMP SessionMachine::DiscardSnapshot (
8628 IConsole *aInitiator, INPTR GUIDPARAM aId,
8629 MachineState_T *aMachineState, IProgress **aProgress)
8630{
8631 LogFlowThisFunc (("\n"));
8632
8633 Guid id = aId;
8634 AssertReturn (aInitiator && !id.isEmpty(), E_INVALIDARG);
8635 AssertReturn (aMachineState && aProgress, E_POINTER);
8636
8637 AutoCaller autoCaller (this);
8638 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8639
8640 /* Progress::init() needs mParent lock */
8641 AutoMultiLock <2> alock (mParent->wlock(), this->wlock());
8642
8643 ComAssertRet (mData->mMachineState < MachineState_Running, E_FAIL);
8644
8645 ComObjPtr <Snapshot> snapshot;
8646 HRESULT rc = findSnapshot (id, snapshot, true /* aSetError */);
8647 CheckComRCReturnRC (rc);
8648
8649 AutoLock snapshotLock (snapshot);
8650 if (snapshot == mData->mFirstSnapshot)
8651 {
8652 AutoLock chLock (mData->mFirstSnapshot->childrenLock());
8653 size_t childrenCount = mData->mFirstSnapshot->children().size();
8654 if (childrenCount > 1)
8655 return setError (E_FAIL,
8656 tr ("Cannot discard the snapshot '%ls' because it is the first "
8657 "snapshot of the machine '%ls' and it has more than one "
8658 "child snapshot (%d)"),
8659 snapshot->data().mName.raw(), mUserData->mName.raw(),
8660 childrenCount);
8661 }
8662
8663 /*
8664 * If the snapshot being discarded is the current one, ensure current
8665 * settings are committed and saved.
8666 */
8667 if (snapshot == mData->mCurrentSnapshot)
8668 {
8669 if (isModified())
8670 {
8671 rc = saveSettings();
8672 CheckComRCReturnRC (rc);
8673 }
8674 }
8675
8676 /*
8677 * create a progress object. The number of operations is:
8678 * 1 (preparing) + # of VDIs
8679 */
8680 ComObjPtr <Progress> progress;
8681 progress.createObject();
8682 rc = progress->init (mParent, aInitiator,
8683 Bstr (Utf8StrFmt (tr ("Discarding snapshot '%ls'"),
8684 snapshot->data().mName.raw())),
8685 FALSE /* aCancelable */,
8686 1 + snapshot->data().mMachine->mHDData->mHDAttachments.size(),
8687 Bstr (tr ("Preparing to discard snapshot")));
8688 AssertComRCReturn (rc, rc);
8689
8690 /* create and start the task on a separate thread */
8691 DiscardSnapshotTask *task = new DiscardSnapshotTask (this, progress, snapshot);
8692 int vrc = RTThreadCreate (NULL, taskHandler,
8693 (void *) task,
8694 0, RTTHREADTYPE_MAIN_WORKER, 0, "DiscardSnapshot");
8695 if (VBOX_FAILURE (vrc))
8696 delete task;
8697 ComAssertRCRet (vrc, E_FAIL);
8698
8699 /* set the proper machine state (note: after creating a Task instance) */
8700 setMachineState (MachineState_Discarding);
8701
8702 /* return the progress to the caller */
8703 progress.queryInterfaceTo (aProgress);
8704
8705 /* return the new state to the caller */
8706 *aMachineState = mData->mMachineState;
8707
8708 return S_OK;
8709}
8710
8711/**
8712 * @note Locks mParent + this + children objects for writing!
8713 */
8714STDMETHODIMP SessionMachine::DiscardCurrentState (
8715 IConsole *aInitiator, MachineState_T *aMachineState, IProgress **aProgress)
8716{
8717 LogFlowThisFunc (("\n"));
8718
8719 AssertReturn (aInitiator, E_INVALIDARG);
8720 AssertReturn (aMachineState && aProgress, E_POINTER);
8721
8722 AutoCaller autoCaller (this);
8723 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8724
8725 /* Progress::init() needs mParent lock */
8726 AutoMultiLock <2> alock (mParent->wlock(), this->wlock());
8727
8728 ComAssertRet (mData->mMachineState < MachineState_Running, E_FAIL);
8729
8730 if (mData->mCurrentSnapshot.isNull())
8731 return setError (E_FAIL,
8732 tr ("Could not discard the current state of the machine '%ls' "
8733 "because it doesn't have any snapshots"),
8734 mUserData->mName.raw());
8735
8736 /*
8737 * create a progress object. The number of operations is:
8738 * 1 (preparing) + # of VDIs + 1 (if we need to copy the saved state file)
8739 */
8740 ComObjPtr <Progress> progress;
8741 progress.createObject();
8742 {
8743 ULONG opCount = 1 + mData->mCurrentSnapshot->data()
8744 .mMachine->mHDData->mHDAttachments.size();
8745 if (mData->mCurrentSnapshot->stateFilePath())
8746 ++ opCount;
8747 progress->init (mParent, aInitiator,
8748 Bstr (tr ("Discarding current machine state")),
8749 FALSE /* aCancelable */, opCount,
8750 Bstr (tr ("Preparing to discard current state")));
8751 }
8752
8753 /* create and start the task on a separate thread */
8754 DiscardCurrentStateTask *task =
8755 new DiscardCurrentStateTask (this, progress, false /* discardCurSnapshot */);
8756 int vrc = RTThreadCreate (NULL, taskHandler,
8757 (void *) task,
8758 0, RTTHREADTYPE_MAIN_WORKER, 0, "DiscardCurState");
8759 if (VBOX_FAILURE (vrc))
8760 delete task;
8761 ComAssertRCRet (vrc, E_FAIL);
8762
8763 /* set the proper machine state (note: after creating a Task instance) */
8764 setMachineState (MachineState_Discarding);
8765
8766 /* return the progress to the caller */
8767 progress.queryInterfaceTo (aProgress);
8768
8769 /* return the new state to the caller */
8770 *aMachineState = mData->mMachineState;
8771
8772 return S_OK;
8773}
8774
8775/**
8776 * @note Locks mParent + other objects for writing!
8777 */
8778STDMETHODIMP SessionMachine::DiscardCurrentSnapshotAndState (
8779 IConsole *aInitiator, MachineState_T *aMachineState, IProgress **aProgress)
8780{
8781 LogFlowThisFunc (("\n"));
8782
8783 AssertReturn (aInitiator, E_INVALIDARG);
8784 AssertReturn (aMachineState && aProgress, E_POINTER);
8785
8786 AutoCaller autoCaller (this);
8787 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8788
8789 /* Progress::init() needs mParent lock */
8790 AutoMultiLock <2> alock (mParent->wlock(), this->wlock());
8791
8792 ComAssertRet (mData->mMachineState < MachineState_Running, E_FAIL);
8793
8794 if (mData->mCurrentSnapshot.isNull())
8795 return setError (E_FAIL,
8796 tr ("Could not discard the current state of the machine '%ls' "
8797 "because it doesn't have any snapshots"),
8798 mUserData->mName.raw());
8799
8800 /*
8801 * create a progress object. The number of operations is:
8802 * 1 (preparing) + # of VDIs in the current snapshot +
8803 * # of VDIs in the previous snapshot +
8804 * 1 (if we need to copy the saved state file of the previous snapshot)
8805 * or (if there is no previous snapshot):
8806 * 1 (preparing) + # of VDIs in the current snapshot * 2 +
8807 * 1 (if we need to copy the saved state file of the current snapshot)
8808 */
8809 ComObjPtr <Progress> progress;
8810 progress.createObject();
8811 {
8812 ComObjPtr <Snapshot> curSnapshot = mData->mCurrentSnapshot;
8813 ComObjPtr <Snapshot> prevSnapshot = mData->mCurrentSnapshot->parent();
8814
8815 ULONG opCount = 1;
8816 if (prevSnapshot)
8817 {
8818 opCount += curSnapshot->data().mMachine->mHDData->mHDAttachments.size();
8819 opCount += prevSnapshot->data().mMachine->mHDData->mHDAttachments.size();
8820 if (prevSnapshot->stateFilePath())
8821 ++ opCount;
8822 }
8823 else
8824 {
8825 opCount += curSnapshot->data().mMachine->mHDData->mHDAttachments.size() * 2;
8826 if (curSnapshot->stateFilePath())
8827 ++ opCount;
8828 }
8829
8830 progress->init (mParent, aInitiator,
8831 Bstr (tr ("Discarding current machine snapshot and state")),
8832 FALSE /* aCancelable */, opCount,
8833 Bstr (tr ("Preparing to discard current snapshot and state")));
8834 }
8835
8836 /* create and start the task on a separate thread */
8837 DiscardCurrentStateTask *task =
8838 new DiscardCurrentStateTask (this, progress, true /* discardCurSnapshot */);
8839 int vrc = RTThreadCreate (NULL, taskHandler,
8840 (void *) task,
8841 0, RTTHREADTYPE_MAIN_WORKER, 0, "DiscardCurState");
8842 if (VBOX_FAILURE (vrc))
8843 delete task;
8844 ComAssertRCRet (vrc, E_FAIL);
8845
8846 /* set the proper machine state (note: after creating a Task instance) */
8847 setMachineState (MachineState_Discarding);
8848
8849 /* return the progress to the caller */
8850 progress.queryInterfaceTo (aProgress);
8851
8852 /* return the new state to the caller */
8853 *aMachineState = mData->mMachineState;
8854
8855 return S_OK;
8856}
8857
8858// public methods only for internal purposes
8859/////////////////////////////////////////////////////////////////////////////
8860
8861/**
8862 * Called from the client watcher thread to check for unexpected client
8863 * process death.
8864 *
8865 * @note On Win32 and on OS/2, this method is called only when we've got the
8866 * mutex (i.e. the client has either died or terminated normally). This
8867 * method always returns true.
8868 *
8869 * @note On Linux, the method returns true if the client process has
8870 * terminated abnormally (and/or the session has been uninitialized) and
8871 * false if it is still alive.
8872 *
8873 * @note Locks this object for writing.
8874 */
8875bool SessionMachine::checkForDeath()
8876{
8877 Uninit::Reason reason;
8878 bool doUninit = false;
8879 bool ret = false;
8880
8881 /*
8882 * Enclose autoCaller with a block because calling uninit()
8883 * from under it will deadlock.
8884 */
8885 {
8886 AutoCaller autoCaller (this);
8887 if (!autoCaller.isOk())
8888 {
8889 /*
8890 * return true if not ready, to cause the client watcher to exclude
8891 * the corresponding session from watching
8892 */
8893 LogFlowThisFunc (("Already uninitialized!"));
8894 return true;
8895 }
8896
8897 AutoLock alock (this);
8898
8899 /*
8900 * Determine the reason of death: if the session state is Closing here,
8901 * everything is fine. Otherwise it means that the client did not call
8902 * OnSessionEnd() before it released the IPC semaphore.
8903 * This may happen either because the client process has abnormally
8904 * terminated, or because it simply forgot to call ISession::Close()
8905 * before exiting. We threat the latter also as an abnormal termination
8906 * (see Session::uninit() for details).
8907 */
8908 reason = mData->mSession.mState == SessionState_SessionClosing ?
8909 Uninit::Normal :
8910 Uninit::Abnormal;
8911
8912#if defined(RT_OS_WINDOWS)
8913
8914 AssertMsg (mIPCSem, ("semaphore must be created"));
8915
8916 /* release the IPC mutex */
8917 ::ReleaseMutex (mIPCSem);
8918
8919 doUninit = true;
8920
8921 ret = true;
8922
8923#elif defined(RT_OS_OS2)
8924
8925 AssertMsg (mIPCSem, ("semaphore must be created"));
8926
8927 /* release the IPC mutex */
8928 ::DosReleaseMutexSem (mIPCSem);
8929
8930 doUninit = true;
8931
8932 ret = true;
8933
8934#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
8935
8936 AssertMsg (mIPCSem >= 0, ("semaphore must be created"));
8937
8938 int val = ::semctl (mIPCSem, 0, GETVAL);
8939 if (val > 0)
8940 {
8941 /* the semaphore is signaled, meaning the session is terminated */
8942 doUninit = true;
8943 }
8944
8945 ret = val > 0;
8946
8947#else
8948# error "Port me!"
8949#endif
8950
8951 } /* AutoCaller block */
8952
8953 if (doUninit)
8954 uninit (reason);
8955
8956 return ret;
8957}
8958
8959/**
8960 * @note Locks this object for reading.
8961 */
8962HRESULT SessionMachine::onDVDDriveChange()
8963{
8964 LogFlowThisFunc (("\n"));
8965
8966 AutoCaller autoCaller (this);
8967 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8968
8969 ComPtr <IInternalSessionControl> directControl;
8970 {
8971 AutoReaderLock alock (this);
8972 directControl = mData->mSession.mDirectControl;
8973 }
8974
8975 /* ignore notifications sent after #OnSessionEnd() is called */
8976 if (!directControl)
8977 return S_OK;
8978
8979 return directControl->OnDVDDriveChange();
8980}
8981
8982/**
8983 * @note Locks this object for reading.
8984 */
8985HRESULT SessionMachine::onFloppyDriveChange()
8986{
8987 LogFlowThisFunc (("\n"));
8988
8989 AutoCaller autoCaller (this);
8990 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8991
8992 ComPtr <IInternalSessionControl> directControl;
8993 {
8994 AutoReaderLock alock (this);
8995 directControl = mData->mSession.mDirectControl;
8996 }
8997
8998 /* ignore notifications sent after #OnSessionEnd() is called */
8999 if (!directControl)
9000 return S_OK;
9001
9002 return directControl->OnFloppyDriveChange();
9003}
9004
9005/**
9006 * @note Locks this object for reading.
9007 */
9008HRESULT SessionMachine::onNetworkAdapterChange(INetworkAdapter *networkAdapter)
9009{
9010 LogFlowThisFunc (("\n"));
9011
9012 AutoCaller autoCaller (this);
9013 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9014
9015 ComPtr <IInternalSessionControl> directControl;
9016 {
9017 AutoReaderLock alock (this);
9018 directControl = mData->mSession.mDirectControl;
9019 }
9020
9021 /* ignore notifications sent after #OnSessionEnd() is called */
9022 if (!directControl)
9023 return S_OK;
9024
9025 return directControl->OnNetworkAdapterChange(networkAdapter);
9026}
9027
9028/**
9029 * @note Locks this object for reading.
9030 */
9031HRESULT SessionMachine::onSerialPortChange(ISerialPort *serialPort)
9032{
9033 LogFlowThisFunc (("\n"));
9034
9035 AutoCaller autoCaller (this);
9036 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9037
9038 ComPtr <IInternalSessionControl> directControl;
9039 {
9040 AutoReaderLock alock (this);
9041 directControl = mData->mSession.mDirectControl;
9042 }
9043
9044 /* ignore notifications sent after #OnSessionEnd() is called */
9045 if (!directControl)
9046 return S_OK;
9047
9048 return directControl->OnSerialPortChange(serialPort);
9049}
9050
9051/**
9052 * @note Locks this object for reading.
9053 */
9054HRESULT SessionMachine::onParallelPortChange(IParallelPort *parallelPort)
9055{
9056 LogFlowThisFunc (("\n"));
9057
9058 AutoCaller autoCaller (this);
9059 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9060
9061 ComPtr <IInternalSessionControl> directControl;
9062 {
9063 AutoReaderLock alock (this);
9064 directControl = mData->mSession.mDirectControl;
9065 }
9066
9067 /* ignore notifications sent after #OnSessionEnd() is called */
9068 if (!directControl)
9069 return S_OK;
9070
9071 return directControl->OnParallelPortChange(parallelPort);
9072}
9073
9074/**
9075 * @note Locks this object for reading.
9076 */
9077HRESULT SessionMachine::onVRDPServerChange()
9078{
9079 LogFlowThisFunc (("\n"));
9080
9081 AutoCaller autoCaller (this);
9082 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9083
9084 ComPtr <IInternalSessionControl> directControl;
9085 {
9086 AutoReaderLock alock (this);
9087 directControl = mData->mSession.mDirectControl;
9088 }
9089
9090 /* ignore notifications sent after #OnSessionEnd() is called */
9091 if (!directControl)
9092 return S_OK;
9093
9094 return directControl->OnVRDPServerChange();
9095}
9096
9097/**
9098 * @note Locks this object for reading.
9099 */
9100HRESULT SessionMachine::onUSBControllerChange()
9101{
9102 LogFlowThisFunc (("\n"));
9103
9104 AutoCaller autoCaller (this);
9105 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9106
9107 ComPtr <IInternalSessionControl> directControl;
9108 {
9109 AutoReaderLock alock (this);
9110 directControl = mData->mSession.mDirectControl;
9111 }
9112
9113 /* ignore notifications sent after #OnSessionEnd() is called */
9114 if (!directControl)
9115 return S_OK;
9116
9117 return directControl->OnUSBControllerChange();
9118}
9119
9120/**
9121 * @note Locks this object for reading.
9122 */
9123HRESULT SessionMachine::onSharedFolderChange()
9124{
9125 LogFlowThisFunc (("\n"));
9126
9127 AutoCaller autoCaller (this);
9128 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9129
9130 ComPtr <IInternalSessionControl> directControl;
9131 {
9132 AutoReaderLock alock (this);
9133 directControl = mData->mSession.mDirectControl;
9134 }
9135
9136 /* ignore notifications sent after #OnSessionEnd() is called */
9137 if (!directControl)
9138 return S_OK;
9139
9140 return directControl->OnSharedFolderChange (FALSE /* aGlobal */);
9141}
9142
9143/**
9144 * @note Locks this object for reading.
9145 */
9146HRESULT SessionMachine::onUSBDeviceAttach (IUSBDevice *aDevice,
9147 IVirtualBoxErrorInfo *aError)
9148{
9149 LogFlowThisFunc (("\n"));
9150
9151 AutoCaller autoCaller (this);
9152
9153 /* This notification may happen after the machine object has been
9154 * uninitialized (the session was closed), so don't assert. */
9155 CheckComRCReturnRC (autoCaller.rc());
9156
9157 ComPtr <IInternalSessionControl> directControl;
9158 {
9159 AutoReaderLock alock (this);
9160 directControl = mData->mSession.mDirectControl;
9161 }
9162
9163 /* fail on notifications sent after #OnSessionEnd() is called, it is
9164 * expected by the caller */
9165 if (!directControl)
9166 return E_FAIL;
9167
9168 return directControl->OnUSBDeviceAttach (aDevice, aError);
9169}
9170
9171/**
9172 * @note Locks this object for reading.
9173 */
9174HRESULT SessionMachine::onUSBDeviceDetach (INPTR GUIDPARAM aId,
9175 IVirtualBoxErrorInfo *aError)
9176{
9177 LogFlowThisFunc (("\n"));
9178
9179 AutoCaller autoCaller (this);
9180
9181 /* This notification may happen after the machine object has been
9182 * uninitialized (the session was closed), so don't assert. */
9183 CheckComRCReturnRC (autoCaller.rc());
9184
9185 ComPtr <IInternalSessionControl> directControl;
9186 {
9187 AutoReaderLock alock (this);
9188 directControl = mData->mSession.mDirectControl;
9189 }
9190
9191 /* fail on notifications sent after #OnSessionEnd() is called, it is
9192 * expected by the caller */
9193 if (!directControl)
9194 return E_FAIL;
9195
9196 return directControl->OnUSBDeviceDetach (aId, aError);
9197}
9198
9199// protected methods
9200/////////////////////////////////////////////////////////////////////////////
9201
9202/**
9203 * Helper method to finalize saving the state.
9204 *
9205 * @note Must be called from under this object's lock.
9206 *
9207 * @param aSuccess TRUE if the snapshot has been taken successfully
9208 *
9209 * @note Locks mParent + this objects for writing.
9210 */
9211HRESULT SessionMachine::endSavingState (BOOL aSuccess)
9212{
9213 LogFlowThisFuncEnter();
9214
9215 AutoCaller autoCaller (this);
9216 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9217
9218 /* mParent->removeProgress() needs mParent lock */
9219 AutoMultiLock <2> alock (mParent->wlock(), this->wlock());
9220
9221 HRESULT rc = S_OK;
9222
9223 if (aSuccess)
9224 {
9225 mSSData->mStateFilePath = mSnapshotData.mStateFilePath;
9226
9227 /* save all VM settings */
9228 rc = saveSettings();
9229 }
9230 else
9231 {
9232 /* delete the saved state file (it might have been already created) */
9233 RTFileDelete (Utf8Str (mSnapshotData.mStateFilePath));
9234 }
9235
9236 /* remove the completed progress object */
9237 mParent->removeProgress (mSnapshotData.mProgressId);
9238
9239 /* clear out the temporary saved state data */
9240 mSnapshotData.mLastState = MachineState_InvalidMachineState;
9241 mSnapshotData.mProgressId.clear();
9242 mSnapshotData.mStateFilePath.setNull();
9243
9244 LogFlowThisFuncLeave();
9245 return rc;
9246}
9247
9248/**
9249 * Helper method to finalize taking a snapshot.
9250 * Gets called only from #EndTakingSnapshot() that is expected to
9251 * be called by the VM process when it finishes *all* the tasks related to
9252 * taking a snapshot, either scucessfully or unsuccessfilly.
9253 *
9254 * @param aSuccess TRUE if the snapshot has been taken successfully
9255 *
9256 * @note Locks mParent + this objects for writing.
9257 */
9258HRESULT SessionMachine::endTakingSnapshot (BOOL aSuccess)
9259{
9260 LogFlowThisFuncEnter();
9261
9262 AutoCaller autoCaller (this);
9263 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9264
9265 /* Progress object uninitialization needs mParent lock */
9266 AutoMultiLock <2> alock (mParent->wlock(), this->wlock());
9267
9268 HRESULT rc = S_OK;
9269
9270 if (aSuccess)
9271 {
9272 /* the server progress must be completed on success */
9273 Assert (mSnapshotData.mServerProgress->completed());
9274
9275 mData->mCurrentSnapshot = mSnapshotData.mSnapshot;
9276 /* memorize the first snapshot if necessary */
9277 if (!mData->mFirstSnapshot)
9278 mData->mFirstSnapshot = mData->mCurrentSnapshot;
9279
9280 int opFlags = SaveSS_AddOp | SaveSS_UpdateCurrentId;
9281 if (mSnapshotData.mLastState != MachineState_Paused && !isModified())
9282 {
9283 /*
9284 * the machine was powered off or saved when taking a snapshot,
9285 * so reset the mCurrentStateModified flag
9286 */
9287 mData->mCurrentStateModified = FALSE;
9288 opFlags |= SaveSS_UpdateCurStateModified;
9289 }
9290
9291 rc = saveSnapshotSettings (mSnapshotData.mSnapshot, opFlags);
9292 }
9293
9294 if (!aSuccess || FAILED (rc))
9295 {
9296 if (mSnapshotData.mSnapshot)
9297 {
9298 /* wait for the completion of the server progress (diff VDI creation) */
9299 /// @todo (dmik) later, we will definitely want to cancel it instead
9300 // (when the cancel function is implemented)
9301 mSnapshotData.mServerProgress->WaitForCompletion (-1);
9302
9303 /*
9304 * delete all differencing VDIs created
9305 * (this will attach their parents back)
9306 */
9307 rc = deleteSnapshotDiffs (mSnapshotData.mSnapshot);
9308 /* continue cleanup on error */
9309
9310 /* delete the saved state file (it might have been already created) */
9311 if (mSnapshotData.mSnapshot->stateFilePath())
9312 RTFileDelete (Utf8Str (mSnapshotData.mSnapshot->stateFilePath()));
9313
9314 mSnapshotData.mSnapshot->uninit();
9315 }
9316 }
9317
9318 /* inform callbacks */
9319 if (aSuccess && SUCCEEDED (rc))
9320 mParent->onSnapshotTaken (mData->mUuid, mSnapshotData.mSnapshot->data().mId);
9321
9322 /* clear out the snapshot data */
9323 mSnapshotData.mLastState = MachineState_InvalidMachineState;
9324 mSnapshotData.mSnapshot.setNull();
9325 mSnapshotData.mServerProgress.setNull();
9326 /* uninitialize the combined progress (to remove it from the VBox collection) */
9327 if (!mSnapshotData.mCombinedProgress.isNull())
9328 {
9329 mSnapshotData.mCombinedProgress->uninit();
9330 mSnapshotData.mCombinedProgress.setNull();
9331 }
9332
9333 LogFlowThisFuncLeave();
9334 return rc;
9335}
9336
9337/**
9338 * Take snapshot task handler.
9339 * Must be called only by TakeSnapshotTask::handler()!
9340 *
9341 * The sole purpose of this task is to asynchronously create differencing VDIs
9342 * and copy the saved state file (when necessary). The VM process will wait
9343 * for this task to complete using the mSnapshotData.mServerProgress
9344 * returned to it.
9345 *
9346 * @note Locks mParent + this objects for writing.
9347 */
9348void SessionMachine::takeSnapshotHandler (TakeSnapshotTask &aTask)
9349{
9350 LogFlowThisFuncEnter();
9351
9352 AutoCaller autoCaller (this);
9353
9354 LogFlowThisFunc (("state=%d\n", autoCaller.state()));
9355 if (!autoCaller.isOk())
9356 {
9357 /*
9358 * we might have been uninitialized because the session was
9359 * accidentally closed by the client, so don't assert
9360 */
9361 LogFlowThisFuncLeave();
9362 return;
9363 }
9364
9365 /* endTakingSnapshot() needs mParent lock */
9366 AutoMultiLock <2> alock (mParent->wlock(), this->wlock());
9367
9368 HRESULT rc = S_OK;
9369
9370 LogFlowThisFunc (("Creating differencing VDIs...\n"));
9371
9372 /* create new differencing hard disks and attach them to this machine */
9373 rc = createSnapshotDiffs (&mSnapshotData.mSnapshot->data().mId,
9374 mUserData->mSnapshotFolderFull,
9375 mSnapshotData.mServerProgress,
9376 true /* aOnline */);
9377
9378 if (SUCCEEDED (rc) && mSnapshotData.mLastState == MachineState_Saved)
9379 {
9380 Utf8Str stateFrom = mSSData->mStateFilePath;
9381 Utf8Str stateTo = mSnapshotData.mSnapshot->stateFilePath();
9382
9383 LogFlowThisFunc (("Copying the execution state from '%s' to '%s'...\n",
9384 stateFrom.raw(), stateTo.raw()));
9385
9386 mSnapshotData.mServerProgress->advanceOperation (
9387 Bstr (tr ("Copying the execution state")));
9388
9389 /*
9390 * We can safely leave the lock here:
9391 * mMachineState is MachineState_Saving here
9392 */
9393 alock.leave();
9394
9395 /* copy the state file */
9396 int vrc = RTFileCopyEx (stateFrom, stateTo, progressCallback,
9397 static_cast <Progress *> (mSnapshotData.mServerProgress));
9398
9399 alock.enter();
9400
9401 if (VBOX_FAILURE (vrc))
9402 rc = setError (E_FAIL,
9403 tr ("Could not copy the state file '%ls' to '%ls' (%Vrc)"),
9404 stateFrom.raw(), stateTo.raw());
9405 }
9406
9407 /*
9408 * we have to call endTakingSnapshot() here if the snapshot was taken
9409 * offline, because the VM process will not do it in this case
9410 */
9411 if (mSnapshotData.mLastState != MachineState_Paused)
9412 {
9413 LogFlowThisFunc (("Finalizing the taken snapshot (rc=%08X)...\n", rc));
9414
9415 setMachineState (mSnapshotData.mLastState);
9416 updateMachineStateOnClient();
9417
9418 /* finalize the progress after setting the state, for consistency */
9419 mSnapshotData.mServerProgress->notifyComplete (rc);
9420
9421 endTakingSnapshot (SUCCEEDED (rc));
9422 }
9423 else
9424 {
9425 mSnapshotData.mServerProgress->notifyComplete (rc);
9426 }
9427
9428 LogFlowThisFuncLeave();
9429}
9430
9431/**
9432 * Discard snapshot task handler.
9433 * Must be called only by DiscardSnapshotTask::handler()!
9434 *
9435 * When aTask.subTask is true, the associated progress object is left
9436 * uncompleted on success. On failure, the progress is marked as completed
9437 * regardless of this parameter.
9438 *
9439 * @note Locks mParent + this + child objects for writing!
9440 */
9441void SessionMachine::discardSnapshotHandler (DiscardSnapshotTask &aTask)
9442{
9443 LogFlowThisFuncEnter();
9444
9445 AutoCaller autoCaller (this);
9446
9447 LogFlowThisFunc (("state=%d\n", autoCaller.state()));
9448 if (!autoCaller.isOk())
9449 {
9450 /*
9451 * we might have been uninitialized because the session was
9452 * accidentally closed by the client, so don't assert
9453 */
9454 aTask.progress->notifyComplete (
9455 E_FAIL, COM_IIDOF (IMachine), getComponentName(),
9456 tr ("The session has been accidentally closed"));
9457
9458 LogFlowThisFuncLeave();
9459 return;
9460 }
9461
9462 ComObjPtr <SnapshotMachine> sm = aTask.snapshot->data().mMachine;
9463
9464 /* mParent is locked because of Progress::notifyComplete(), etc. */
9465 AutoMultiLock <3> alock (mParent->wlock(), this->wlock(), sm->rlock());
9466
9467 /* Safe locking in the direction parent->child */
9468 AutoLock snapshotLock (aTask.snapshot);
9469 AutoLock snapshotChildrenLock (aTask.snapshot->childrenLock());
9470
9471 HRESULT rc = S_OK;
9472
9473 /* save the snapshot ID (for callbacks) */
9474 Guid snapshotId = aTask.snapshot->data().mId;
9475
9476 do
9477 {
9478 /* first pass: */
9479 LogFlowThisFunc (("Check hard disk accessibility and affected machines...\n"));
9480
9481 HDData::HDAttachmentList::const_iterator it;
9482 for (it = sm->mHDData->mHDAttachments.begin();
9483 it != sm->mHDData->mHDAttachments.end();
9484 ++ it)
9485 {
9486 ComObjPtr <HardDiskAttachment> hda = *it;
9487 ComObjPtr <HardDisk> hd = hda->hardDisk();
9488 ComObjPtr <HardDisk> parent = hd->parent();
9489
9490 AutoLock hdLock (hd);
9491
9492 if (hd->hasForeignChildren())
9493 {
9494 rc = setError (E_FAIL,
9495 tr ("One or more hard disks belonging to other machines are "
9496 "based on the hard disk '%ls' stored in the snapshot '%ls'"),
9497 hd->toString().raw(), aTask.snapshot->data().mName.raw());
9498 break;
9499 }
9500
9501 if (hd->type() == HardDiskType_NormalHardDisk)
9502 {
9503 AutoLock hdChildrenLock (hd->childrenLock());
9504 size_t childrenCount = hd->children().size();
9505 if (childrenCount > 1)
9506 {
9507 rc = setError (E_FAIL,
9508 tr ("Normal hard disk '%ls' stored in the snapshot '%ls' "
9509 "has more than one child hard disk (%d)"),
9510 hd->toString().raw(), aTask.snapshot->data().mName.raw(),
9511 childrenCount);
9512 break;
9513 }
9514 }
9515 else
9516 {
9517 ComAssertMsgFailedBreak (("Invalid hard disk type %d\n", hd->type()),
9518 rc = E_FAIL);
9519 }
9520
9521 Bstr accessError;
9522 rc = hd->getAccessibleWithChildren (accessError);
9523 CheckComRCBreakRC (rc);
9524
9525 if (!accessError.isNull())
9526 {
9527 rc = setError (E_FAIL,
9528 tr ("Hard disk '%ls' stored in the snapshot '%ls' is not "
9529 "accessible (%ls)"),
9530 hd->toString().raw(), aTask.snapshot->data().mName.raw(),
9531 accessError.raw());
9532 break;
9533 }
9534
9535 rc = hd->setBusyWithChildren();
9536 if (FAILED (rc))
9537 {
9538 /* reset the busy flag of all previous hard disks */
9539 while (it != sm->mHDData->mHDAttachments.begin())
9540 (*(-- it))->hardDisk()->clearBusyWithChildren();
9541 break;
9542 }
9543 }
9544
9545 CheckComRCBreakRC (rc);
9546
9547 /* second pass: */
9548 LogFlowThisFunc (("Performing actual vdi merging...\n"));
9549
9550 for (it = sm->mHDData->mHDAttachments.begin();
9551 it != sm->mHDData->mHDAttachments.end();
9552 ++ it)
9553 {
9554 ComObjPtr <HardDiskAttachment> hda = *it;
9555 ComObjPtr <HardDisk> hd = hda->hardDisk();
9556 ComObjPtr <HardDisk> parent = hd->parent();
9557
9558 AutoLock hdLock (hd);
9559
9560 Bstr hdRootString = hd->root()->toString (true /* aShort */);
9561
9562 if (parent)
9563 {
9564 if (hd->isParentImmutable())
9565 {
9566 aTask.progress->advanceOperation (Bstr (Utf8StrFmt (
9567 tr ("Discarding changes to immutable hard disk '%ls'"),
9568 hdRootString.raw())));
9569
9570 /* clear the busy flag before unregistering */
9571 hd->clearBusy();
9572
9573 /*
9574 * unregisterDiffHardDisk() is supposed to delete and uninit
9575 * the differencing hard disk
9576 */
9577 rc = mParent->unregisterDiffHardDisk (hd);
9578 CheckComRCBreakRC (rc);
9579 continue;
9580 }
9581 else
9582 {
9583 /*
9584 * differencing VDI:
9585 * merge this image to all its children
9586 */
9587
9588 aTask.progress->advanceOperation (Bstr (Utf8StrFmt (
9589 tr ("Merging changes to normal hard disk '%ls' to children"),
9590 hdRootString.raw())));
9591
9592 snapshotChildrenLock.unlock();
9593 snapshotLock.unlock();
9594 alock.leave();
9595
9596 rc = hd->asVDI()->mergeImageToChildren (aTask.progress);
9597
9598 alock.enter();
9599 snapshotLock.lock();
9600 snapshotChildrenLock.lock();
9601
9602 // debug code
9603 // if (it != sm->mHDData->mHDAttachments.begin())
9604 // {
9605 // rc = setError (E_FAIL, "Simulated failure");
9606 // break;
9607 //}
9608
9609 if (SUCCEEDED (rc))
9610 rc = mParent->unregisterDiffHardDisk (hd);
9611 else
9612 hd->clearBusyWithChildren();
9613
9614 CheckComRCBreakRC (rc);
9615 }
9616 }
9617 else if (hd->type() == HardDiskType_NormalHardDisk)
9618 {
9619 /*
9620 * normal vdi has the only child or none
9621 * (checked in the first pass)
9622 */
9623
9624 ComObjPtr <HardDisk> child;
9625 {
9626 AutoLock hdChildrenLock (hd->childrenLock());
9627 if (hd->children().size())
9628 child = hd->children().front();
9629 }
9630
9631 if (child.isNull())
9632 {
9633 aTask.progress->advanceOperation (Bstr (Utf8StrFmt (
9634 tr ("Detaching normal hard disk '%ls'"),
9635 hdRootString.raw())));
9636
9637 /* just deassociate the normal image from this machine */
9638 hd->setMachineId (Guid());
9639 hd->setSnapshotId (Guid());
9640
9641 /* clear the busy flag */
9642 hd->clearBusy();
9643 }
9644 else
9645 {
9646 AutoLock childLock (child);
9647
9648 aTask.progress->advanceOperation (Bstr (Utf8StrFmt (
9649 tr ("Preserving changes to normal hard disk '%ls'"),
9650 hdRootString.raw())));
9651
9652 ComObjPtr <Machine> cm;
9653 ComObjPtr <Snapshot> cs;
9654 ComObjPtr <HardDiskAttachment> childHda;
9655 rc = findHardDiskAttachment (child, &cm, &cs, &childHda);
9656 CheckComRCBreakRC (rc);
9657 /* must be the same machine (checked in the first pass) */
9658 ComAssertBreak (cm->mData->mUuid == mData->mUuid, rc = E_FAIL);
9659
9660 /* merge the child to this basic image */
9661
9662 snapshotChildrenLock.unlock();
9663 snapshotLock.unlock();
9664 alock.leave();
9665
9666 rc = child->asVDI()->mergeImageToParent (aTask.progress);
9667
9668 alock.enter();
9669 snapshotLock.lock();
9670 snapshotChildrenLock.lock();
9671
9672 if (SUCCEEDED (rc))
9673 rc = mParent->unregisterDiffHardDisk (child);
9674 else
9675 hd->clearBusyWithChildren();
9676
9677 CheckComRCBreakRC (rc);
9678
9679 /* reset the snapshot Id */
9680 hd->setSnapshotId (Guid());
9681
9682 /* replace the child image in the appropriate place */
9683 childHda->updateHardDisk (hd, FALSE /* aDirty */);
9684
9685 if (!cs)
9686 {
9687 aTask.settingsChanged = true;
9688 }
9689 else
9690 {
9691 rc = cm->saveSnapshotSettings (cs, SaveSS_UpdateAllOp);
9692 CheckComRCBreakRC (rc);
9693 }
9694 }
9695 }
9696 else
9697 {
9698 ComAssertMsgFailedBreak (("Invalid hard disk type %d\n", hd->type()),
9699 rc = E_FAIL);
9700 }
9701 }
9702
9703 /* preserve existing error info */
9704 ErrorInfoKeeper mergeEik;
9705 HRESULT mergeRc = rc;
9706
9707 if (FAILED (rc))
9708 {
9709 /* clear the busy flag on the rest of hard disks */
9710 for (++ it; it != sm->mHDData->mHDAttachments.end(); ++ it)
9711 (*it)->hardDisk()->clearBusyWithChildren();
9712 }
9713
9714 /*
9715 * we have to try to discard the snapshot even if merging failed
9716 * because some images might have been already merged (and deleted)
9717 */
9718
9719 do
9720 {
9721 LogFlowThisFunc (("Discarding the snapshot (reparenting children)...\n"));
9722
9723 ComObjPtr <Snapshot> parentSnapshot = aTask.snapshot->parent();
9724
9725 /// @todo (dmik):
9726 // when we introduce clones later, discarding the snapshot
9727 // will affect the current and first snapshots of clones, if they are
9728 // direct children of this snapshot. So we will need to lock machines
9729 // associated with child snapshots as well and update mCurrentSnapshot
9730 // and/or mFirstSnapshot fields.
9731
9732 if (aTask.snapshot == mData->mCurrentSnapshot)
9733 {
9734 /* currently, the parent snapshot must refer to the same machine */
9735 ComAssertBreak (
9736 !parentSnapshot ||
9737 parentSnapshot->data().mMachine->mData->mUuid == mData->mUuid,
9738 rc = E_FAIL);
9739 mData->mCurrentSnapshot = parentSnapshot;
9740 /* mark the current state as modified */
9741 mData->mCurrentStateModified = TRUE;
9742 }
9743
9744 if (aTask.snapshot == mData->mFirstSnapshot)
9745 {
9746 /*
9747 * the first snapshot must have only one child when discarded,
9748 * or no children at all
9749 */
9750 ComAssertBreak (aTask.snapshot->children().size() <= 1, rc = E_FAIL);
9751
9752 if (aTask.snapshot->children().size() == 1)
9753 {
9754 ComObjPtr <Snapshot> childSnapshot = aTask.snapshot->children().front();
9755 ComAssertBreak (
9756 childSnapshot->data().mMachine->mData->mUuid == mData->mUuid,
9757 rc = E_FAIL);
9758 mData->mFirstSnapshot = childSnapshot;
9759 }
9760 else
9761 mData->mFirstSnapshot.setNull();
9762 }
9763
9764 /// @todo (dmik)
9765 // if we implement some warning mechanism later, we'll have
9766 // to return a warning if the state file path cannot be deleted
9767 Bstr stateFilePath = aTask.snapshot->stateFilePath();
9768 if (stateFilePath)
9769 RTFileDelete (Utf8Str (stateFilePath));
9770
9771 aTask.snapshot->discard();
9772
9773 rc = saveSnapshotSettings (parentSnapshot,
9774 SaveSS_UpdateAllOp | SaveSS_UpdateCurrentId);
9775 }
9776 while (0);
9777
9778 /* restore the merge error if any (ErrorInfo will be restored
9779 * automatically) */
9780 if (FAILED (mergeRc))
9781 rc = mergeRc;
9782 }
9783 while (0);
9784
9785 if (!aTask.subTask || FAILED (rc))
9786 {
9787 if (!aTask.subTask)
9788 {
9789 /* preserve existing error info */
9790 ErrorInfoKeeper eik;
9791
9792 /* restore the machine state */
9793 setMachineState (aTask.state);
9794 updateMachineStateOnClient();
9795
9796 /*
9797 * save settings anyway, since we've already changed the current
9798 * machine configuration
9799 */
9800 if (aTask.settingsChanged)
9801 {
9802 saveSettings (true /* aMarkCurStateAsModified */,
9803 true /* aInformCallbacksAnyway */);
9804 }
9805 }
9806
9807 /* set the result (this will try to fetch current error info on failure) */
9808 aTask.progress->notifyComplete (rc);
9809 }
9810
9811 if (SUCCEEDED (rc))
9812 mParent->onSnapshotDiscarded (mData->mUuid, snapshotId);
9813
9814 LogFlowThisFunc (("Done discarding snapshot (rc=%08X)\n", rc));
9815 LogFlowThisFuncLeave();
9816}
9817
9818/**
9819 * Discard current state task handler.
9820 * Must be called only by DiscardCurrentStateTask::handler()!
9821 *
9822 * @note Locks mParent + this object for writing.
9823 */
9824void SessionMachine::discardCurrentStateHandler (DiscardCurrentStateTask &aTask)
9825{
9826 LogFlowThisFuncEnter();
9827
9828 AutoCaller autoCaller (this);
9829
9830 LogFlowThisFunc (("state=%d\n", autoCaller.state()));
9831 if (!autoCaller.isOk())
9832 {
9833 /*
9834 * we might have been uninitialized because the session was
9835 * accidentally closed by the client, so don't assert
9836 */
9837 aTask.progress->notifyComplete (
9838 E_FAIL, COM_IIDOF (IMachine), getComponentName(),
9839 tr ("The session has been accidentally closed"));
9840
9841 LogFlowThisFuncLeave();
9842 return;
9843 }
9844
9845 /* mParent is locked because of Progress::notifyComplete(), etc. */
9846 AutoMultiLock <2> alock (mParent->wlock(), this->wlock());
9847
9848 /*
9849 * discard all current changes to mUserData (name, OSType etc.)
9850 * (note that the machine is powered off, so there is no need
9851 * to inform the direct session)
9852 */
9853 if (isModified())
9854 rollback (false /* aNotify */);
9855
9856 HRESULT rc = S_OK;
9857
9858 bool errorInSubtask = false;
9859 bool stateRestored = false;
9860
9861 const bool isLastSnapshot = mData->mCurrentSnapshot->parent().isNull();
9862
9863 do
9864 {
9865 /*
9866 * discard the saved state file if the machine was Saved prior
9867 * to this operation
9868 */
9869 if (aTask.state == MachineState_Saved)
9870 {
9871 Assert (!mSSData->mStateFilePath.isEmpty());
9872 RTFileDelete (Utf8Str (mSSData->mStateFilePath));
9873 mSSData->mStateFilePath.setNull();
9874 aTask.modifyLastState (MachineState_PoweredOff);
9875 rc = saveStateSettings (SaveSTS_StateFilePath);
9876 CheckComRCBreakRC (rc);
9877 }
9878
9879 if (aTask.discardCurrentSnapshot && !isLastSnapshot)
9880 {
9881 /*
9882 * the "discard current snapshot and state" task is in action,
9883 * the current snapshot is not the last one.
9884 * Discard the current snapshot first.
9885 */
9886
9887 DiscardSnapshotTask subTask (aTask, mData->mCurrentSnapshot);
9888 subTask.subTask = true;
9889 discardSnapshotHandler (subTask);
9890 aTask.settingsChanged = subTask.settingsChanged;
9891 if (aTask.progress->completed())
9892 {
9893 /*
9894 * the progress can be completed by a subtask only if there was
9895 * a failure
9896 */
9897 Assert (FAILED (aTask.progress->resultCode()));
9898 errorInSubtask = true;
9899 rc = aTask.progress->resultCode();
9900 break;
9901 }
9902 }
9903
9904 LONG64 snapshotTimeStamp = 0;
9905
9906 {
9907 ComObjPtr <Snapshot> curSnapshot = mData->mCurrentSnapshot;
9908 AutoLock snapshotLock (curSnapshot);
9909
9910 /* remember the timestamp of the snapshot we're restoring from */
9911 snapshotTimeStamp = curSnapshot->data().mTimeStamp;
9912
9913 /* copy all hardware data from the current snapshot */
9914 copyFrom (curSnapshot->data().mMachine);
9915
9916 LogFlowThisFunc (("Restoring VDIs from the snapshot...\n"));
9917
9918 /* restore the attachmends from the snapshot */
9919 mHDData.backup();
9920 mHDData->mHDAttachments =
9921 curSnapshot->data().mMachine->mHDData->mHDAttachments;
9922
9923 snapshotLock.unlock();
9924 alock.leave();
9925 rc = createSnapshotDiffs (NULL, mUserData->mSnapshotFolderFull,
9926 aTask.progress,
9927 false /* aOnline */);
9928 alock.enter();
9929 snapshotLock.lock();
9930
9931 if (FAILED (rc))
9932 {
9933 /* here we can still safely rollback, so do it */
9934 /* preserve existing error info */
9935 ErrorInfoKeeper eik;
9936 /* undo all changes */
9937 rollback (false /* aNotify */);
9938 break;
9939 }
9940
9941 /*
9942 * note: old VDIs will be deassociated/deleted on #commit() called
9943 * either from #saveSettings() or directly at the end
9944 */
9945
9946 /* should not have a saved state file associated at this point */
9947 Assert (mSSData->mStateFilePath.isNull());
9948
9949 if (curSnapshot->stateFilePath())
9950 {
9951 Utf8Str snapStateFilePath = curSnapshot->stateFilePath();
9952
9953 Utf8Str stateFilePath = Utf8StrFmt ("%ls%c{%Vuuid}.sav",
9954 mUserData->mSnapshotFolderFull.raw(),
9955 RTPATH_DELIMITER, mData->mUuid.raw());
9956
9957 LogFlowThisFunc (("Copying saved state file from '%s' to '%s'...\n",
9958 snapStateFilePath.raw(), stateFilePath.raw()));
9959
9960 aTask.progress->advanceOperation (
9961 Bstr (tr ("Restoring the execution state")));
9962
9963 /* copy the state file */
9964 snapshotLock.unlock();
9965 alock.leave();
9966 int vrc = RTFileCopyEx (snapStateFilePath, stateFilePath,
9967 progressCallback, aTask.progress);
9968 alock.enter();
9969 snapshotLock.lock();
9970
9971 if (VBOX_SUCCESS (vrc))
9972 {
9973 mSSData->mStateFilePath = stateFilePath;
9974 }
9975 else
9976 {
9977 rc = setError (E_FAIL,
9978 tr ("Could not copy the state file '%s' to '%s' (%Vrc)"),
9979 snapStateFilePath.raw(), stateFilePath.raw(), vrc);
9980 break;
9981 }
9982 }
9983 }
9984
9985 bool informCallbacks = false;
9986
9987 if (aTask.discardCurrentSnapshot && isLastSnapshot)
9988 {
9989 /*
9990 * discard the current snapshot and state task is in action,
9991 * the current snapshot is the last one.
9992 * Discard the current snapshot after discarding the current state.
9993 */
9994
9995 /* commit changes to fixup hard disks before discarding */
9996 rc = commit();
9997 if (SUCCEEDED (rc))
9998 {
9999 DiscardSnapshotTask subTask (aTask, mData->mCurrentSnapshot);
10000 subTask.subTask = true;
10001 discardSnapshotHandler (subTask);
10002 aTask.settingsChanged = subTask.settingsChanged;
10003 if (aTask.progress->completed())
10004 {
10005 /*
10006 * the progress can be completed by a subtask only if there
10007 * was a failure
10008 */
10009 Assert (FAILED (aTask.progress->resultCode()));
10010 errorInSubtask = true;
10011 rc = aTask.progress->resultCode();
10012 }
10013 }
10014
10015 /*
10016 * we've committed already, so inform callbacks anyway to ensure
10017 * they don't miss some change
10018 */
10019 informCallbacks = true;
10020 }
10021
10022 /*
10023 * we have already discarded the current state, so set the
10024 * execution state accordingly no matter of the discard snapshot result
10025 */
10026 if (mSSData->mStateFilePath)
10027 setMachineState (MachineState_Saved);
10028 else
10029 setMachineState (MachineState_PoweredOff);
10030
10031 updateMachineStateOnClient();
10032 stateRestored = true;
10033
10034 if (errorInSubtask)
10035 break;
10036
10037 /* assign the timestamp from the snapshot */
10038 Assert (snapshotTimeStamp != 0);
10039 mData->mLastStateChange = snapshotTimeStamp;
10040
10041 /* mark the current state as not modified */
10042 mData->mCurrentStateModified = FALSE;
10043
10044 /* save all settings and commit */
10045 rc = saveSettings (false /* aMarkCurStateAsModified */,
10046 informCallbacks);
10047 aTask.settingsChanged = false;
10048 }
10049 while (0);
10050
10051 if (FAILED (rc))
10052 {
10053 /* preserve existing error info */
10054 ErrorInfoKeeper eik;
10055
10056 if (!stateRestored)
10057 {
10058 /* restore the machine state */
10059 setMachineState (aTask.state);
10060 updateMachineStateOnClient();
10061 }
10062
10063 /*
10064 * save all settings and commit if still modified (there is no way to
10065 * rollback properly). Note that isModified() will return true after
10066 * copyFrom(). Also save the settings if requested by the subtask.
10067 */
10068 if (isModified() || aTask.settingsChanged)
10069 {
10070 if (aTask.settingsChanged)
10071 saveSettings (true /* aMarkCurStateAsModified */,
10072 true /* aInformCallbacksAnyway */);
10073 else
10074 saveSettings();
10075 }
10076 }
10077
10078 if (!errorInSubtask)
10079 {
10080 /* set the result (this will try to fetch current error info on failure) */
10081 aTask.progress->notifyComplete (rc);
10082 }
10083
10084 if (SUCCEEDED (rc))
10085 mParent->onSnapshotDiscarded (mData->mUuid, Guid());
10086
10087 LogFlowThisFunc (("Done discarding current state (rc=%08X)\n", rc));
10088
10089 LogFlowThisFuncLeave();
10090}
10091
10092/**
10093 * Helper to change the machine state (reimplementation).
10094 *
10095 * @note Locks this object for writing.
10096 */
10097HRESULT SessionMachine::setMachineState (MachineState_T aMachineState)
10098{
10099 LogFlowThisFuncEnter();
10100 LogFlowThisFunc (("aMachineState=%d\n", aMachineState));
10101
10102 AutoCaller autoCaller (this);
10103 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
10104
10105 AutoLock alock (this);
10106
10107 MachineState_T oldMachineState = mData->mMachineState;
10108
10109 AssertMsgReturn (oldMachineState != aMachineState,
10110 ("oldMachineState=%d, aMachineState=%d\n",
10111 oldMachineState, aMachineState), E_FAIL);
10112
10113 HRESULT rc = S_OK;
10114
10115 int stsFlags = 0;
10116 bool deleteSavedState = false;
10117
10118 /* detect some state transitions */
10119
10120 if (oldMachineState < MachineState_Running &&
10121 aMachineState >= MachineState_Running &&
10122 aMachineState != MachineState_Discarding)
10123 {
10124 /*
10125 * the EMT thread is about to start, so mark attached HDDs as busy
10126 * and all its ancestors as being in use
10127 */
10128 for (HDData::HDAttachmentList::const_iterator it =
10129 mHDData->mHDAttachments.begin();
10130 it != mHDData->mHDAttachments.end();
10131 ++ it)
10132 {
10133 ComObjPtr <HardDisk> hd = (*it)->hardDisk();
10134 AutoLock hdLock (hd);
10135 hd->setBusy();
10136 hd->addReaderOnAncestors();
10137 }
10138 }
10139 else
10140 if (oldMachineState >= MachineState_Running &&
10141 oldMachineState != MachineState_Discarding &&
10142 aMachineState < MachineState_Running)
10143 {
10144 /*
10145 * the EMT thread stopped, so mark attached HDDs as no more busy
10146 * and remove the in-use flag from all its ancestors
10147 */
10148 for (HDData::HDAttachmentList::const_iterator it =
10149 mHDData->mHDAttachments.begin();
10150 it != mHDData->mHDAttachments.end();
10151 ++ it)
10152 {
10153 ComObjPtr <HardDisk> hd = (*it)->hardDisk();
10154 AutoLock hdLock (hd);
10155 hd->releaseReaderOnAncestors();
10156 hd->clearBusy();
10157 }
10158 }
10159
10160 if (oldMachineState == MachineState_Restoring)
10161 {
10162 if (aMachineState != MachineState_Saved)
10163 {
10164 /*
10165 * delete the saved state file once the machine has finished
10166 * restoring from it (note that Console sets the state from
10167 * Restoring to Saved if the VM couldn't restore successfully,
10168 * to give the user an ability to fix an error and retry --
10169 * we keep the saved state file in this case)
10170 */
10171 deleteSavedState = true;
10172 }
10173 }
10174 else
10175 if (oldMachineState == MachineState_Saved &&
10176 (aMachineState == MachineState_PoweredOff ||
10177 aMachineState == MachineState_Aborted))
10178 {
10179 /*
10180 * delete the saved state after Console::DiscardSavedState() is called
10181 * or if the VM process (owning a direct VM session) crashed while the
10182 * VM was Saved
10183 */
10184
10185 /// @todo (dmik)
10186 // Not sure that deleting the saved state file just because of the
10187 // client death before it attempted to restore the VM is a good
10188 // thing. But when it crashes we need to go to the Aborted state
10189 // which cannot have the saved state file associated... The only
10190 // way to fix this is to make the Aborted condition not a VM state
10191 // but a bool flag: i.e., when a crash occurs, set it to true and
10192 // change the state to PoweredOff or Saved depending on the
10193 // saved state presence.
10194
10195 deleteSavedState = true;
10196 mData->mCurrentStateModified = TRUE;
10197 stsFlags |= SaveSTS_CurStateModified;
10198 }
10199
10200 if (aMachineState == MachineState_Starting ||
10201 aMachineState == MachineState_Restoring)
10202 {
10203 /*
10204 * set the current state modified flag to indicate that the
10205 * current state is no more identical to the state in the
10206 * current snapshot
10207 */
10208 if (!mData->mCurrentSnapshot.isNull())
10209 {
10210 mData->mCurrentStateModified = TRUE;
10211 stsFlags |= SaveSTS_CurStateModified;
10212 }
10213 }
10214
10215 if (deleteSavedState == true)
10216 {
10217 Assert (!mSSData->mStateFilePath.isEmpty());
10218 RTFileDelete (Utf8Str (mSSData->mStateFilePath));
10219 mSSData->mStateFilePath.setNull();
10220 stsFlags |= SaveSTS_StateFilePath;
10221 }
10222
10223 /* redirect to the underlying peer machine */
10224 mPeer->setMachineState (aMachineState);
10225
10226 if (aMachineState == MachineState_PoweredOff ||
10227 aMachineState == MachineState_Aborted ||
10228 aMachineState == MachineState_Saved)
10229 {
10230 stsFlags |= SaveSTS_StateTimeStamp;
10231 }
10232
10233 rc = saveStateSettings (stsFlags);
10234
10235 if ((oldMachineState != MachineState_PoweredOff &&
10236 oldMachineState != MachineState_Aborted) &&
10237 (aMachineState == MachineState_PoweredOff ||
10238 aMachineState == MachineState_Aborted))
10239 {
10240 /*
10241 * clear differencing hard disks based on immutable hard disks
10242 * once we've been shut down for any reason
10243 */
10244 rc = wipeOutImmutableDiffs();
10245 }
10246
10247 LogFlowThisFunc (("rc=%08X\n", rc));
10248 LogFlowThisFuncLeave();
10249 return rc;
10250}
10251
10252/**
10253 * Sends the current machine state value to the VM process.
10254 *
10255 * @note Locks this object for reading, then calls a client process.
10256 */
10257HRESULT SessionMachine::updateMachineStateOnClient()
10258{
10259 AutoCaller autoCaller (this);
10260 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
10261
10262 ComPtr <IInternalSessionControl> directControl;
10263 {
10264 AutoReaderLock alock (this);
10265 AssertReturn (!!mData, E_FAIL);
10266 directControl = mData->mSession.mDirectControl;
10267
10268 /* directControl may be already set to NULL here in #OnSessionEnd()
10269 * called too early by the direct session process while there is still
10270 * some operation (like discarding the snapshot) in progress. The client
10271 * process in this case is waiting inside Session::close() for the
10272 * "end session" process object to complete, while #uninit() called by
10273 * #checkForDeath() on the Watcher thread is waiting for the pending
10274 * operation to complete. For now, we accept this inconsitent behavior
10275 * and simply do nothing here. */
10276
10277 if (mData->mSession.mState == SessionState_SessionClosing)
10278 return S_OK;
10279
10280 AssertReturn (!directControl.isNull(), E_FAIL);
10281 }
10282
10283 return directControl->UpdateMachineState (mData->mMachineState);
10284}
10285
10286/* static */
10287DECLCALLBACK(int) SessionMachine::taskHandler (RTTHREAD thread, void *pvUser)
10288{
10289 AssertReturn (pvUser, VERR_INVALID_POINTER);
10290
10291 Task *task = static_cast <Task *> (pvUser);
10292 task->handler();
10293
10294 // it's our responsibility to delete the task
10295 delete task;
10296
10297 return 0;
10298}
10299
10300/////////////////////////////////////////////////////////////////////////////
10301// SnapshotMachine class
10302/////////////////////////////////////////////////////////////////////////////
10303
10304DEFINE_EMPTY_CTOR_DTOR (SnapshotMachine)
10305
10306HRESULT SnapshotMachine::FinalConstruct()
10307{
10308 LogFlowThisFunc (("\n"));
10309
10310 /* set the proper type to indicate we're the SnapshotMachine instance */
10311 unconst (mType) = IsSnapshotMachine;
10312
10313 return S_OK;
10314}
10315
10316void SnapshotMachine::FinalRelease()
10317{
10318 LogFlowThisFunc (("\n"));
10319
10320 uninit();
10321}
10322
10323/**
10324 * Initializes the SnapshotMachine object when taking a snapshot.
10325 *
10326 * @param aSessionMachine machine to take a snapshot from
10327 * @param aSnapshotId snapshot ID of this snapshot machine
10328 * @param aStateFilePath file where the execution state will be later saved
10329 * (or NULL for the offline snapshot)
10330 *
10331 * @note Locks aSessionMachine object for reading.
10332 */
10333HRESULT SnapshotMachine::init (SessionMachine *aSessionMachine,
10334 INPTR GUIDPARAM aSnapshotId,
10335 INPTR BSTR aStateFilePath)
10336{
10337 LogFlowThisFuncEnter();
10338 LogFlowThisFunc (("mName={%ls}\n", aSessionMachine->mUserData->mName.raw()));
10339
10340 AssertReturn (aSessionMachine && !Guid (aSnapshotId).isEmpty(), E_INVALIDARG);
10341
10342 /* Enclose the state transition NotReady->InInit->Ready */
10343 AutoInitSpan autoInitSpan (this);
10344 AssertReturn (autoInitSpan.isOk(), E_UNEXPECTED);
10345
10346 mSnapshotId = aSnapshotId;
10347
10348 AutoReaderLock alock (aSessionMachine);
10349
10350 /* memorize the primary Machine instance (i.e. not SessionMachine!) */
10351 unconst (mPeer) = aSessionMachine->mPeer;
10352 /* share the parent pointer */
10353 unconst (mParent) = mPeer->mParent;
10354
10355 /* take the pointer to Data to share */
10356 mData.share (mPeer->mData);
10357 /*
10358 * take the pointer to UserData to share
10359 * (our UserData must always be the same as Machine's data)
10360 */
10361 mUserData.share (mPeer->mUserData);
10362 /* make a private copy of all other data (recent changes from SessionMachine) */
10363 mHWData.attachCopy (aSessionMachine->mHWData);
10364 mHDData.attachCopy (aSessionMachine->mHDData);
10365
10366 /* SSData is always unique for SnapshotMachine */
10367 mSSData.allocate();
10368 mSSData->mStateFilePath = aStateFilePath;
10369
10370 /*
10371 * create copies of all shared folders (mHWData after attiching a copy
10372 * contains just references to original objects)
10373 */
10374 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
10375 it != mHWData->mSharedFolders.end();
10376 ++ it)
10377 {
10378 ComObjPtr <SharedFolder> folder;
10379 folder.createObject();
10380 HRESULT rc = folder->initCopy (this, *it);
10381 CheckComRCReturnRC (rc);
10382 *it = folder;
10383 }
10384
10385 /* create all other child objects that will be immutable private copies */
10386
10387 unconst (mBIOSSettings).createObject();
10388 mBIOSSettings->initCopy (this, mPeer->mBIOSSettings);
10389
10390#ifdef VBOX_VRDP
10391 unconst (mVRDPServer).createObject();
10392 mVRDPServer->initCopy (this, mPeer->mVRDPServer);
10393#endif
10394
10395 unconst (mDVDDrive).createObject();
10396 mDVDDrive->initCopy (this, mPeer->mDVDDrive);
10397
10398 unconst (mFloppyDrive).createObject();
10399 mFloppyDrive->initCopy (this, mPeer->mFloppyDrive);
10400
10401 unconst (mAudioAdapter).createObject();
10402 mAudioAdapter->initCopy (this, mPeer->mAudioAdapter);
10403
10404 unconst (mUSBController).createObject();
10405 mUSBController->initCopy (this, mPeer->mUSBController);
10406
10407 for (ULONG slot = 0; slot < ELEMENTS (mNetworkAdapters); slot ++)
10408 {
10409 unconst (mNetworkAdapters [slot]).createObject();
10410 mNetworkAdapters [slot]->initCopy (this, mPeer->mNetworkAdapters [slot]);
10411 }
10412
10413 for (ULONG slot = 0; slot < ELEMENTS (mSerialPorts); slot ++)
10414 {
10415 unconst (mSerialPorts [slot]).createObject();
10416 mSerialPorts [slot]->initCopy (this, mPeer->mSerialPorts [slot]);
10417 }
10418
10419 for (ULONG slot = 0; slot < ELEMENTS (mParallelPorts); slot ++)
10420 {
10421 unconst (mParallelPorts [slot]).createObject();
10422 mParallelPorts [slot]->initCopy (this, mPeer->mParallelPorts [slot]);
10423 }
10424
10425 /* Confirm a successful initialization when it's the case */
10426 autoInitSpan.setSucceeded();
10427
10428 LogFlowThisFuncLeave();
10429 return S_OK;
10430}
10431
10432/**
10433 * Initializes the SnapshotMachine object when loading from the settings file.
10434 *
10435 * @param aMachine machine the snapshot belngs to
10436 * @param aHWNode <Hardware> node
10437 * @param aHDAsNode <HardDiskAttachments> node
10438 * @param aSnapshotId snapshot ID of this snapshot machine
10439 * @param aStateFilePath file where the execution state is saved
10440 * (or NULL for the offline snapshot)
10441 *
10442 * @note Locks aMachine object for reading.
10443 */
10444HRESULT SnapshotMachine::init (Machine *aMachine, CFGNODE aHWNode, CFGNODE aHDAsNode,
10445 INPTR GUIDPARAM aSnapshotId, INPTR BSTR aStateFilePath)
10446{
10447 LogFlowThisFuncEnter();
10448 LogFlowThisFunc (("mName={%ls}\n", aMachine->mUserData->mName.raw()));
10449
10450 AssertReturn (aMachine && aHWNode && aHDAsNode && !Guid (aSnapshotId).isEmpty(),
10451 E_INVALIDARG);
10452
10453 /* Enclose the state transition NotReady->InInit->Ready */
10454 AutoInitSpan autoInitSpan (this);
10455 AssertReturn (autoInitSpan.isOk(), E_UNEXPECTED);
10456
10457 mSnapshotId = aSnapshotId;
10458
10459 AutoReaderLock alock (aMachine);
10460
10461 /* memorize the primary Machine instance */
10462 unconst (mPeer) = aMachine;
10463 /* share the parent pointer */
10464 unconst (mParent) = mPeer->mParent;
10465
10466 /* take the pointer to Data to share */
10467 mData.share (mPeer->mData);
10468 /*
10469 * take the pointer to UserData to share
10470 * (our UserData must always be the same as Machine's data)
10471 */
10472 mUserData.share (mPeer->mUserData);
10473 /* allocate private copies of all other data (will be loaded from settings) */
10474 mHWData.allocate();
10475 mHDData.allocate();
10476
10477 /* SSData is always unique for SnapshotMachine */
10478 mSSData.allocate();
10479 mSSData->mStateFilePath = aStateFilePath;
10480
10481 /* create all other child objects that will be immutable private copies */
10482
10483 unconst (mBIOSSettings).createObject();
10484 mBIOSSettings->init (this);
10485
10486#ifdef VBOX_VRDP
10487 unconst (mVRDPServer).createObject();
10488 mVRDPServer->init (this);
10489#endif
10490
10491 unconst (mDVDDrive).createObject();
10492 mDVDDrive->init (this);
10493
10494 unconst (mFloppyDrive).createObject();
10495 mFloppyDrive->init (this);
10496
10497 unconst (mAudioAdapter).createObject();
10498 mAudioAdapter->init (this);
10499
10500 unconst (mUSBController).createObject();
10501 mUSBController->init (this);
10502
10503 for (ULONG slot = 0; slot < ELEMENTS (mNetworkAdapters); slot ++)
10504 {
10505 unconst (mNetworkAdapters [slot]).createObject();
10506 mNetworkAdapters [slot]->init (this, slot);
10507 }
10508
10509 for (ULONG slot = 0; slot < ELEMENTS (mSerialPorts); slot ++)
10510 {
10511 unconst (mSerialPorts [slot]).createObject();
10512 mSerialPorts [slot]->init (this, slot);
10513 }
10514
10515 for (ULONG slot = 0; slot < ELEMENTS (mParallelPorts); slot ++)
10516 {
10517 unconst (mParallelPorts [slot]).createObject();
10518 mParallelPorts [slot]->init (this, slot);
10519 }
10520
10521 /* load hardware and harddisk settings */
10522
10523 HRESULT rc = loadHardware (aHWNode);
10524 if (SUCCEEDED (rc))
10525 rc = loadHardDisks (aHDAsNode, true /* aRegistered */, &mSnapshotId);
10526
10527 if (SUCCEEDED (rc))
10528 {
10529 /* commit all changes made during the initialization */
10530 commit();
10531 }
10532
10533 /* Confirm a successful initialization when it's the case */
10534 if (SUCCEEDED (rc))
10535 autoInitSpan.setSucceeded();
10536
10537 LogFlowThisFuncLeave();
10538 return rc;
10539}
10540
10541/**
10542 * Uninitializes this SnapshotMachine object.
10543 */
10544void SnapshotMachine::uninit()
10545{
10546 LogFlowThisFuncEnter();
10547
10548 /* Enclose the state transition Ready->InUninit->NotReady */
10549 AutoUninitSpan autoUninitSpan (this);
10550 if (autoUninitSpan.uninitDone())
10551 return;
10552
10553 uninitDataAndChildObjects();
10554
10555 unconst (mParent).setNull();
10556 unconst (mPeer).setNull();
10557
10558 LogFlowThisFuncLeave();
10559}
10560
10561// AutoLock::Lockable interface
10562////////////////////////////////////////////////////////////////////////////////
10563
10564/**
10565 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
10566 * with the primary Machine instance (mPeer).
10567 */
10568AutoLock::Handle *SnapshotMachine::lockHandle() const
10569{
10570 AssertReturn (!mPeer.isNull(), NULL);
10571 return mPeer->lockHandle();
10572}
10573
10574// public methods only for internal purposes
10575////////////////////////////////////////////////////////////////////////////////
10576
10577/**
10578 * Called by the snapshot object associated with this SnapshotMachine when
10579 * snapshot data such as name or description is changed.
10580 *
10581 * @note Locks this object for writing.
10582 */
10583HRESULT SnapshotMachine::onSnapshotChange (Snapshot *aSnapshot)
10584{
10585 AutoLock alock (this);
10586
10587 mPeer->saveSnapshotSettings (aSnapshot, SaveSS_UpdateAttrsOp);
10588
10589 /* inform callbacks */
10590 mParent->onSnapshotChange (mData->mUuid, aSnapshot->data().mId);
10591
10592 return S_OK;
10593}
Note: See TracBrowser for help on using the repository browser.

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