VirtualBox

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

Last change on this file since 15245 was 15202, checked in by vboxsync, 16 years ago

Main: Fixed regression after r40588 (no hard disk names in HD UI).

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