VirtualBox

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

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

Storage/Main/GUI: Implemented preliminary support of VMDK images version 3 and 4 (no separate Disk DescriptionFile support).

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