VirtualBox

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

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

Save guest settings in snapshot tree

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