VirtualBox

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

Last change on this file since 15404 was 15380, checked in by vboxsync, 16 years ago

Main: Warning.

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