VirtualBox

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

Last change on this file since 11162 was 11108, checked in by vboxsync, 16 years ago

Main, HostServices/GuestProperties: the timestamp is in nanoseconds and fix a segfault

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

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