VirtualBox

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

Last change on this file since 21809 was 21686, checked in by vboxsync, 15 years ago

Main: back out r50147 until the locking is properly understood; will come back.

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