VirtualBox

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

Last change on this file since 24088 was 24079, checked in by vboxsync, 15 years ago

Main: logging cleanup

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