VirtualBox

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

Last change on this file since 21525 was 21446, checked in by vboxsync, 15 years ago

API/Machine+SystemProperties: get rid of the tri-state bool controlling hwvirtex

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