VirtualBox

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

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

Main: fix bad unicode in discarding snapshot title

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