VirtualBox

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

Last change on this file since 24017 was 23973, checked in by vboxsync, 15 years ago

*,RTFileOpen: Fixing RTFileOpen flag misdesign: The deny, access and action flags are mandatory now.

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