VirtualBox

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

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

Main: fix missing shared folders XML save

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 335.0 KB
Line 
1/* $Id: MachineImpl.cpp 22287 2009-08-17 11:47:47Z 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 '%ls' of the machine '%ls' has more than one child snapshot (%d)"),
8100 snapshot->getName().raw(),
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 snapshotLock.unlock();
8112 treeLock.unlock();
8113
8114 AutoWriteLock vboxLock(mParent);
8115 rc = saveSettings();
8116 CheckComRCReturnRC (rc);
8117 vboxLock.unlock();
8118
8119 treeLock.lock();
8120 snapshotLock.lock();
8121 }
8122 }
8123
8124 /* create a progress object. The number of operations is:
8125 * 1 (preparing) + # of hard disks + 1 if the snapshot is online
8126 */
8127 ComObjPtr<Progress> progress;
8128 progress.createObject();
8129 rc = progress->init (mParent, aInitiator,
8130 Bstr(Utf8StrFmt(tr("Discarding snapshot '%ls'"),
8131 snapshot->getName().raw())),
8132 FALSE /* aCancelable */,
8133 1 + (ULONG)snapshot->getSnapshotMachine()->mHDData->mAttachments.size() +
8134 (snapshot->stateFilePath().isNull() ? 0 : 1),
8135 Bstr (tr ("Preparing to discard snapshot")));
8136 AssertComRCReturn (rc, rc);
8137
8138 /* create and start the task on a separate thread */
8139 DiscardSnapshotTask *task = new DiscardSnapshotTask (this, progress, snapshot);
8140 int vrc = RTThreadCreate (NULL, taskHandler,
8141 (void *) task,
8142 0, RTTHREADTYPE_MAIN_WORKER, 0, "DiscardSnapshot");
8143 if (RT_FAILURE(vrc))
8144 delete task;
8145 ComAssertRCRet (vrc, E_FAIL);
8146
8147 /* set the proper machine state (note: after creating a Task instance) */
8148 setMachineState (MachineState_Discarding);
8149
8150 /* return the progress to the caller */
8151 progress.queryInterfaceTo(aProgress);
8152
8153 /* return the new state to the caller */
8154 *aMachineState = mData->mMachineState;
8155
8156 return S_OK;
8157}
8158
8159/**
8160 * @note Locks this + children objects for writing!
8161 */
8162STDMETHODIMP SessionMachine::DiscardCurrentState (
8163 IConsole *aInitiator, MachineState_T *aMachineState, IProgress **aProgress)
8164{
8165 LogFlowThisFunc(("\n"));
8166
8167 AssertReturn(aInitiator, E_INVALIDARG);
8168 AssertReturn(aMachineState && aProgress, E_POINTER);
8169
8170 AutoCaller autoCaller(this);
8171 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8172
8173 AutoWriteLock alock(this);
8174
8175 ComAssertRet (!Global::IsOnlineOrTransient (mData->mMachineState), E_FAIL);
8176
8177 if (mData->mCurrentSnapshot.isNull())
8178 return setError(VBOX_E_INVALID_OBJECT_STATE,
8179 tr("Could not discard the current state of the machine '%ls' because it doesn't have any snapshots"),
8180 mUserData->mName.raw());
8181
8182 /* create a progress object. The number of operations is: 1 (preparing) + #
8183 * of hard disks + 1 (if we need to copy the saved state file) */
8184 ComObjPtr<Progress> progress;
8185 progress.createObject();
8186 {
8187 ULONG opCount = 1 + (ULONG)mData->mCurrentSnapshot->getSnapshotMachine()->mHDData->mAttachments.size();
8188 if (mData->mCurrentSnapshot->stateFilePath())
8189 ++ opCount;
8190 progress->init (mParent, aInitiator,
8191 Bstr (tr ("Discarding current machine state")),
8192 FALSE /* aCancelable */, opCount,
8193 Bstr (tr ("Preparing to discard current state")));
8194 }
8195
8196 /* create and start the task on a separate thread (note that it will not
8197 * start working until we release alock) */
8198 DiscardCurrentStateTask *task =
8199 new DiscardCurrentStateTask (this, progress, false /* discardCurSnapshot */);
8200 int vrc = RTThreadCreate (NULL, taskHandler,
8201 (void *) task,
8202 0, RTTHREADTYPE_MAIN_WORKER, 0, "DiscardCurState");
8203 if (RT_FAILURE(vrc))
8204 {
8205 delete task;
8206 ComAssertRCRet (vrc, E_FAIL);
8207 }
8208
8209 /* set the proper machine state (note: after creating a Task instance) */
8210 setMachineState (MachineState_Discarding);
8211
8212 /* return the progress to the caller */
8213 progress.queryInterfaceTo(aProgress);
8214
8215 /* return the new state to the caller */
8216 *aMachineState = mData->mMachineState;
8217
8218 return S_OK;
8219}
8220
8221/**
8222 * @note Locks thos object for writing!
8223 */
8224STDMETHODIMP SessionMachine::DiscardCurrentSnapshotAndState(IConsole *aInitiator,
8225 MachineState_T *aMachineState,
8226 IProgress **aProgress)
8227{
8228 LogFlowThisFunc(("\n"));
8229
8230 AssertReturn(aInitiator, E_INVALIDARG);
8231 AssertReturn(aMachineState && aProgress, E_POINTER);
8232
8233 AutoCaller autoCaller(this);
8234 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8235
8236 AutoWriteLock alock(this);
8237
8238 ComAssertRet (!Global::IsOnlineOrTransient (mData->mMachineState), E_FAIL);
8239
8240 if (mData->mCurrentSnapshot.isNull())
8241 return setError(VBOX_E_INVALID_OBJECT_STATE,
8242 tr("Could not discard the current state of the machine '%ls' "
8243 "because it doesn't have any snapshots"),
8244 mUserData->mName.raw());
8245
8246 /* create a progress object. The number of operations is:
8247 * 1 (preparing) + # of hard disks in the current snapshot +
8248 * # of hard disks in the previous snapshot +
8249 * 1 if we need to copy the saved state file of the previous snapshot +
8250 * 1 if the current snapshot is online
8251 * or (if there is no previous snapshot):
8252 * 1 (preparing) + # of hard disks in the current snapshot * 2 +
8253 * 1 if we need to copy the saved state file of the current snapshot * 2
8254 */
8255 ComObjPtr<Progress> progress;
8256 progress.createObject();
8257 {
8258 ComObjPtr<Snapshot> curSnapshot = mData->mCurrentSnapshot;
8259 ComObjPtr<Snapshot> prevSnapshot = mData->mCurrentSnapshot->parent();
8260
8261 ULONG opCount = 1;
8262 if (prevSnapshot)
8263 {
8264 opCount += (ULONG)curSnapshot->getSnapshotMachine()->mHDData->mAttachments.size();
8265 opCount += (ULONG)prevSnapshot->getSnapshotMachine()->mHDData->mAttachments.size();
8266 if (prevSnapshot->stateFilePath())
8267 ++opCount;
8268 if (curSnapshot->stateFilePath())
8269 ++opCount;
8270 }
8271 else
8272 {
8273 opCount +=
8274 (ULONG)curSnapshot->getSnapshotMachine()->mHDData->mAttachments.size() * 2;
8275 if (curSnapshot->stateFilePath())
8276 opCount += 2;
8277 }
8278
8279 progress->init(mParent, aInitiator,
8280 Bstr (tr ("Discarding current machine snapshot and state")),
8281 FALSE /* aCancelable */, opCount,
8282 Bstr (tr ("Preparing to discard current snapshot and state")));
8283 }
8284
8285 /* create and start the task on a separate thread */
8286 DiscardCurrentStateTask *task =
8287 new DiscardCurrentStateTask (this, progress, true /* discardCurSnapshot */);
8288 int vrc = RTThreadCreate(NULL, taskHandler,
8289 (void *) task,
8290 0, RTTHREADTYPE_MAIN_WORKER, 0, "DiscardCurStSnp");
8291 if (RT_FAILURE(vrc))
8292 {
8293 delete task;
8294 ComAssertRCRet(vrc, E_FAIL);
8295 }
8296
8297 /* set the proper machine state (note: after creating a Task instance) */
8298 setMachineState(MachineState_Discarding);
8299
8300 /* return the progress to the caller */
8301 progress.queryInterfaceTo(aProgress);
8302
8303 /* return the new state to the caller */
8304 *aMachineState = mData->mMachineState;
8305
8306 return S_OK;
8307}
8308
8309STDMETHODIMP SessionMachine::PullGuestProperties(ComSafeArrayOut(BSTR, aNames),
8310 ComSafeArrayOut(BSTR, aValues),
8311 ComSafeArrayOut(ULONG64, aTimestamps),
8312 ComSafeArrayOut(BSTR, aFlags))
8313{
8314 LogFlowThisFunc(("\n"));
8315
8316#ifdef VBOX_WITH_GUEST_PROPS
8317 using namespace guestProp;
8318
8319 AutoCaller autoCaller(this);
8320 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8321
8322 AutoReadLock alock(this);
8323
8324 AssertReturn(!ComSafeArrayOutIsNull(aNames), E_POINTER);
8325 AssertReturn(!ComSafeArrayOutIsNull(aValues), E_POINTER);
8326 AssertReturn(!ComSafeArrayOutIsNull(aTimestamps), E_POINTER);
8327 AssertReturn(!ComSafeArrayOutIsNull(aFlags), E_POINTER);
8328
8329 size_t cEntries = mHWData->mGuestProperties.size();
8330 com::SafeArray<BSTR> names (cEntries);
8331 com::SafeArray<BSTR> values (cEntries);
8332 com::SafeArray<ULONG64> timestamps (cEntries);
8333 com::SafeArray<BSTR> flags (cEntries);
8334 unsigned i = 0;
8335 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
8336 it != mHWData->mGuestProperties.end();
8337 ++it)
8338 {
8339 char szFlags[MAX_FLAGS_LEN + 1];
8340 it->strName.cloneTo(&names[i]);
8341 it->strValue.cloneTo(&values[i]);
8342 timestamps[i] = it->mTimestamp;
8343 writeFlags(it->mFlags, szFlags);
8344 Bstr(szFlags).cloneTo(&flags[i]);
8345 ++i;
8346 }
8347 names.detachTo(ComSafeArrayOutArg(aNames));
8348 values.detachTo(ComSafeArrayOutArg(aValues));
8349 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
8350 flags.detachTo(ComSafeArrayOutArg(aFlags));
8351 mHWData->mPropertyServiceActive = true;
8352 return S_OK;
8353#else
8354 ReturnComNotImplemented();
8355#endif
8356}
8357
8358STDMETHODIMP SessionMachine::PushGuestProperties(ComSafeArrayIn (IN_BSTR, aNames),
8359 ComSafeArrayIn (IN_BSTR, aValues),
8360 ComSafeArrayIn (ULONG64, aTimestamps),
8361 ComSafeArrayIn (IN_BSTR, aFlags))
8362{
8363 LogFlowThisFunc(("\n"));
8364
8365#ifdef VBOX_WITH_GUEST_PROPS
8366 using namespace guestProp;
8367
8368 AutoCaller autoCaller(this);
8369 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8370
8371 AutoWriteLock alock(this);
8372
8373 /* Temporarily reset the registered flag, so that our machine state
8374 * changes (i.e. mHWData.backup()) succeed. (isMutable() used in
8375 * all setters will return FALSE for a Machine instance if mRegistered
8376 * is TRUE). This is copied from registeredInit(), and may or may not be
8377 * the right way to handle this. */
8378 mData->mRegistered = FALSE;
8379 HRESULT rc = checkStateDependency(MutableStateDep);
8380 LogRel (("checkStateDependency(MutableStateDep) returned 0x%x\n", rc));
8381 CheckComRCReturnRC(rc);
8382
8383 // ComAssertRet (mData->mMachineState < MachineState_Running, E_FAIL);
8384
8385 AssertReturn(!ComSafeArrayInIsNull (aNames), E_POINTER);
8386 AssertReturn(!ComSafeArrayInIsNull (aValues), E_POINTER);
8387 AssertReturn(!ComSafeArrayInIsNull (aTimestamps), E_POINTER);
8388 AssertReturn(!ComSafeArrayInIsNull (aFlags), E_POINTER);
8389
8390 com::SafeArray<IN_BSTR> names (ComSafeArrayInArg (aNames));
8391 com::SafeArray<IN_BSTR> values (ComSafeArrayInArg (aValues));
8392 com::SafeArray<ULONG64> timestamps (ComSafeArrayInArg (aTimestamps));
8393 com::SafeArray<IN_BSTR> flags (ComSafeArrayInArg (aFlags));
8394 DiscardSettings();
8395 mHWData.backup();
8396 mHWData->mGuestProperties.erase (mHWData->mGuestProperties.begin(),
8397 mHWData->mGuestProperties.end());
8398 for (unsigned i = 0; i < names.size(); ++i)
8399 {
8400 uint32_t fFlags = NILFLAG;
8401 validateFlags (Utf8Str (flags[i]).raw(), &fFlags);
8402 HWData::GuestProperty property = { names[i], values[i], timestamps[i], fFlags };
8403 mHWData->mGuestProperties.push_back (property);
8404 }
8405 mHWData->mPropertyServiceActive = false;
8406 alock.unlock();
8407 SaveSettings();
8408 /* Restore the mRegistered flag. */
8409 mData->mRegistered = TRUE;
8410 return S_OK;
8411#else
8412 ReturnComNotImplemented();
8413#endif
8414}
8415
8416STDMETHODIMP SessionMachine::PushGuestProperty(IN_BSTR aName,
8417 IN_BSTR aValue,
8418 ULONG64 aTimestamp,
8419 IN_BSTR aFlags)
8420{
8421 LogFlowThisFunc(("\n"));
8422
8423#ifdef VBOX_WITH_GUEST_PROPS
8424 using namespace guestProp;
8425
8426 CheckComArgNotNull (aName);
8427 if ((aValue != NULL) && (!VALID_PTR (aValue) || !VALID_PTR (aFlags)))
8428 return E_POINTER; /* aValue can be NULL to indicate deletion */
8429
8430 try
8431 {
8432 Utf8Str utf8Name(aName);
8433 Utf8Str utf8Flags(aFlags);
8434 Utf8Str utf8Patterns(mHWData->mGuestPropertyNotificationPatterns);
8435
8436 uint32_t fFlags = NILFLAG;
8437 if ((aFlags != NULL) && RT_FAILURE(validateFlags (utf8Flags.raw(), &fFlags)))
8438 return E_INVALIDARG;
8439
8440 bool matchAll = false;
8441 if (utf8Patterns.isEmpty())
8442 matchAll = true;
8443
8444 AutoCaller autoCaller(this);
8445 CheckComRCReturnRC(autoCaller.rc());
8446
8447 AutoWriteLock alock(this);
8448
8449 HRESULT rc = checkStateDependency(MutableStateDep);
8450 CheckComRCReturnRC(rc);
8451
8452 mHWData.backup();
8453 for (HWData::GuestPropertyList::iterator iter = mHWData->mGuestProperties.begin();
8454 iter != mHWData->mGuestProperties.end();
8455 ++iter)
8456 if (utf8Name == iter->strName)
8457 {
8458 mHWData->mGuestProperties.erase(iter);
8459 break;
8460 }
8461 if (aValue != NULL)
8462 {
8463 HWData::GuestProperty property = { aName, aValue, aTimestamp, fFlags };
8464 mHWData->mGuestProperties.push_back (property);
8465 }
8466
8467 /* send a callback notification if appropriate */
8468 alock.leave();
8469 if ( matchAll
8470 || RTStrSimplePatternMultiMatch(utf8Patterns.raw(),
8471 RTSTR_MAX,
8472 utf8Name.raw(),
8473 RTSTR_MAX, NULL)
8474 )
8475 mParent->onGuestPropertyChange(mData->mUuid,
8476 aName,
8477 aValue,
8478 aFlags);
8479 }
8480 catch(std::bad_alloc &)
8481 {
8482 return E_OUTOFMEMORY;
8483 }
8484 return S_OK;
8485#else
8486 ReturnComNotImplemented();
8487#endif
8488}
8489
8490// public methods only for internal purposes
8491/////////////////////////////////////////////////////////////////////////////
8492
8493/**
8494 * Called from the client watcher thread to check for expected or unexpected
8495 * death of the client process that has a direct session to this machine.
8496 *
8497 * On Win32 and on OS/2, this method is called only when we've got the
8498 * mutex (i.e. the client has either died or terminated normally) so it always
8499 * returns @c true (the client is terminated, the session machine is
8500 * uninitialized).
8501 *
8502 * On other platforms, the method returns @c true if the client process has
8503 * terminated normally or abnormally and the session machine was uninitialized,
8504 * and @c false if the client process is still alive.
8505 *
8506 * @note Locks this object for writing.
8507 */
8508bool SessionMachine::checkForDeath()
8509{
8510 Uninit::Reason reason;
8511 bool terminated = false;
8512
8513 /* Enclose autoCaller with a block because calling uninit() from under it
8514 * will deadlock. */
8515 {
8516 AutoCaller autoCaller(this);
8517 if (!autoCaller.isOk())
8518 {
8519 /* return true if not ready, to cause the client watcher to exclude
8520 * the corresponding session from watching */
8521 LogFlowThisFunc(("Already uninitialized!"));
8522 return true;
8523 }
8524
8525 AutoWriteLock alock(this);
8526
8527 /* Determine the reason of death: if the session state is Closing here,
8528 * everything is fine. Otherwise it means that the client did not call
8529 * OnSessionEnd() before it released the IPC semaphore. This may happen
8530 * either because the client process has abnormally terminated, or
8531 * because it simply forgot to call ISession::Close() before exiting. We
8532 * threat the latter also as an abnormal termination (see
8533 * Session::uninit() for details). */
8534 reason = mData->mSession.mState == SessionState_Closing ?
8535 Uninit::Normal :
8536 Uninit::Abnormal;
8537
8538#if defined(RT_OS_WINDOWS)
8539
8540 AssertMsg (mIPCSem, ("semaphore must be created"));
8541
8542 /* release the IPC mutex */
8543 ::ReleaseMutex (mIPCSem);
8544
8545 terminated = true;
8546
8547#elif defined(RT_OS_OS2)
8548
8549 AssertMsg (mIPCSem, ("semaphore must be created"));
8550
8551 /* release the IPC mutex */
8552 ::DosReleaseMutexSem (mIPCSem);
8553
8554 terminated = true;
8555
8556#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
8557
8558 AssertMsg (mIPCSem >= 0, ("semaphore must be created"));
8559
8560 int val = ::semctl (mIPCSem, 0, GETVAL);
8561 if (val > 0)
8562 {
8563 /* the semaphore is signaled, meaning the session is terminated */
8564 terminated = true;
8565 }
8566
8567#else
8568# error "Port me!"
8569#endif
8570
8571 } /* AutoCaller block */
8572
8573 if (terminated)
8574 uninit (reason);
8575
8576 return terminated;
8577}
8578
8579/**
8580 * @note Locks this object for reading.
8581 */
8582HRESULT SessionMachine::onDVDDriveChange()
8583{
8584 LogFlowThisFunc(("\n"));
8585
8586 AutoCaller autoCaller(this);
8587 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8588
8589 ComPtr<IInternalSessionControl> directControl;
8590 {
8591 AutoReadLock alock(this);
8592 directControl = mData->mSession.mDirectControl;
8593 }
8594
8595 /* ignore notifications sent after #OnSessionEnd() is called */
8596 if (!directControl)
8597 return S_OK;
8598
8599 return directControl->OnDVDDriveChange();
8600}
8601
8602/**
8603 * @note Locks this object for reading.
8604 */
8605HRESULT SessionMachine::onFloppyDriveChange()
8606{
8607 LogFlowThisFunc(("\n"));
8608
8609 AutoCaller autoCaller(this);
8610 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8611
8612 ComPtr<IInternalSessionControl> directControl;
8613 {
8614 AutoReadLock alock(this);
8615 directControl = mData->mSession.mDirectControl;
8616 }
8617
8618 /* ignore notifications sent after #OnSessionEnd() is called */
8619 if (!directControl)
8620 return S_OK;
8621
8622 return directControl->OnFloppyDriveChange();
8623}
8624
8625/**
8626 * @note Locks this object for reading.
8627 */
8628HRESULT SessionMachine::onNetworkAdapterChange (INetworkAdapter *networkAdapter, BOOL changeAdapter)
8629{
8630 LogFlowThisFunc(("\n"));
8631
8632 AutoCaller autoCaller(this);
8633 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8634
8635 ComPtr<IInternalSessionControl> directControl;
8636 {
8637 AutoReadLock alock(this);
8638 directControl = mData->mSession.mDirectControl;
8639 }
8640
8641 /* ignore notifications sent after #OnSessionEnd() is called */
8642 if (!directControl)
8643 return S_OK;
8644
8645 return directControl->OnNetworkAdapterChange (networkAdapter, changeAdapter);
8646}
8647
8648/**
8649 * @note Locks this object for reading.
8650 */
8651HRESULT SessionMachine::onSerialPortChange (ISerialPort *serialPort)
8652{
8653 LogFlowThisFunc(("\n"));
8654
8655 AutoCaller autoCaller(this);
8656 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8657
8658 ComPtr<IInternalSessionControl> directControl;
8659 {
8660 AutoReadLock alock(this);
8661 directControl = mData->mSession.mDirectControl;
8662 }
8663
8664 /* ignore notifications sent after #OnSessionEnd() is called */
8665 if (!directControl)
8666 return S_OK;
8667
8668 return directControl->OnSerialPortChange (serialPort);
8669}
8670
8671/**
8672 * @note Locks this object for reading.
8673 */
8674HRESULT SessionMachine::onParallelPortChange (IParallelPort *parallelPort)
8675{
8676 LogFlowThisFunc(("\n"));
8677
8678 AutoCaller autoCaller(this);
8679 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8680
8681 ComPtr<IInternalSessionControl> directControl;
8682 {
8683 AutoReadLock alock(this);
8684 directControl = mData->mSession.mDirectControl;
8685 }
8686
8687 /* ignore notifications sent after #OnSessionEnd() is called */
8688 if (!directControl)
8689 return S_OK;
8690
8691 return directControl->OnParallelPortChange (parallelPort);
8692}
8693
8694/**
8695 * @note Locks this object for reading.
8696 */
8697HRESULT SessionMachine::onStorageControllerChange ()
8698{
8699 LogFlowThisFunc(("\n"));
8700
8701 AutoCaller autoCaller(this);
8702 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8703
8704 ComPtr<IInternalSessionControl> directControl;
8705 {
8706 AutoReadLock alock(this);
8707 directControl = mData->mSession.mDirectControl;
8708 }
8709
8710 /* ignore notifications sent after #OnSessionEnd() is called */
8711 if (!directControl)
8712 return S_OK;
8713
8714 return directControl->OnStorageControllerChange ();
8715}
8716
8717/**
8718 * @note Locks this object for reading.
8719 */
8720HRESULT SessionMachine::onVRDPServerChange()
8721{
8722 LogFlowThisFunc(("\n"));
8723
8724 AutoCaller autoCaller(this);
8725 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8726
8727 ComPtr<IInternalSessionControl> directControl;
8728 {
8729 AutoReadLock alock(this);
8730 directControl = mData->mSession.mDirectControl;
8731 }
8732
8733 /* ignore notifications sent after #OnSessionEnd() is called */
8734 if (!directControl)
8735 return S_OK;
8736
8737 return directControl->OnVRDPServerChange();
8738}
8739
8740/**
8741 * @note Locks this object for reading.
8742 */
8743HRESULT SessionMachine::onUSBControllerChange()
8744{
8745 LogFlowThisFunc(("\n"));
8746
8747 AutoCaller autoCaller(this);
8748 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8749
8750 ComPtr<IInternalSessionControl> directControl;
8751 {
8752 AutoReadLock alock(this);
8753 directControl = mData->mSession.mDirectControl;
8754 }
8755
8756 /* ignore notifications sent after #OnSessionEnd() is called */
8757 if (!directControl)
8758 return S_OK;
8759
8760 return directControl->OnUSBControllerChange();
8761}
8762
8763/**
8764 * @note Locks this object for reading.
8765 */
8766HRESULT SessionMachine::onSharedFolderChange()
8767{
8768 LogFlowThisFunc(("\n"));
8769
8770 AutoCaller autoCaller(this);
8771 AssertComRCReturnRC(autoCaller.rc());
8772
8773 ComPtr<IInternalSessionControl> directControl;
8774 {
8775 AutoReadLock alock(this);
8776 directControl = mData->mSession.mDirectControl;
8777 }
8778
8779 /* ignore notifications sent after #OnSessionEnd() is called */
8780 if (!directControl)
8781 return S_OK;
8782
8783 return directControl->OnSharedFolderChange (FALSE /* aGlobal */);
8784}
8785
8786/**
8787 * Returns @c true if this machine's USB controller reports it has a matching
8788 * filter for the given USB device and @c false otherwise.
8789 *
8790 * @note Locks this object for reading.
8791 */
8792bool SessionMachine::hasMatchingUSBFilter (const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
8793{
8794 AutoCaller autoCaller(this);
8795 /* silently return if not ready -- this method may be called after the
8796 * direct machine session has been called */
8797 if (!autoCaller.isOk())
8798 return false;
8799
8800 AutoReadLock alock(this);
8801
8802#ifdef VBOX_WITH_USB
8803 switch (mData->mMachineState)
8804 {
8805 case MachineState_Starting:
8806 case MachineState_Restoring:
8807 case MachineState_Paused:
8808 case MachineState_Running:
8809 return mUSBController->hasMatchingFilter (aDevice, aMaskedIfs);
8810 default: break;
8811 }
8812#else
8813 NOREF(aDevice);
8814 NOREF(aMaskedIfs);
8815#endif
8816 return false;
8817}
8818
8819/**
8820 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
8821 */
8822HRESULT SessionMachine::onUSBDeviceAttach (IUSBDevice *aDevice,
8823 IVirtualBoxErrorInfo *aError,
8824 ULONG aMaskedIfs)
8825{
8826 LogFlowThisFunc(("\n"));
8827
8828 AutoCaller autoCaller(this);
8829
8830 /* This notification may happen after the machine object has been
8831 * uninitialized (the session was closed), so don't assert. */
8832 CheckComRCReturnRC(autoCaller.rc());
8833
8834 ComPtr<IInternalSessionControl> directControl;
8835 {
8836 AutoReadLock alock(this);
8837 directControl = mData->mSession.mDirectControl;
8838 }
8839
8840 /* fail on notifications sent after #OnSessionEnd() is called, it is
8841 * expected by the caller */
8842 if (!directControl)
8843 return E_FAIL;
8844
8845 /* No locks should be held at this point. */
8846 AssertMsg (RTThreadGetWriteLockCount (RTThreadSelf()) == 0, ("%d\n", RTThreadGetWriteLockCount (RTThreadSelf())));
8847 AssertMsg (RTThreadGetReadLockCount (RTThreadSelf()) == 0, ("%d\n", RTThreadGetReadLockCount (RTThreadSelf())));
8848
8849 return directControl->OnUSBDeviceAttach (aDevice, aError, aMaskedIfs);
8850}
8851
8852/**
8853 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
8854 */
8855HRESULT SessionMachine::onUSBDeviceDetach (IN_BSTR aId,
8856 IVirtualBoxErrorInfo *aError)
8857{
8858 LogFlowThisFunc(("\n"));
8859
8860 AutoCaller autoCaller(this);
8861
8862 /* This notification may happen after the machine object has been
8863 * uninitialized (the session was closed), so don't assert. */
8864 CheckComRCReturnRC(autoCaller.rc());
8865
8866 ComPtr<IInternalSessionControl> directControl;
8867 {
8868 AutoReadLock alock(this);
8869 directControl = mData->mSession.mDirectControl;
8870 }
8871
8872 /* fail on notifications sent after #OnSessionEnd() is called, it is
8873 * expected by the caller */
8874 if (!directControl)
8875 return E_FAIL;
8876
8877 /* No locks should be held at this point. */
8878 AssertMsg (RTThreadGetWriteLockCount (RTThreadSelf()) == 0, ("%d\n", RTThreadGetWriteLockCount (RTThreadSelf())));
8879 AssertMsg (RTThreadGetReadLockCount (RTThreadSelf()) == 0, ("%d\n", RTThreadGetReadLockCount (RTThreadSelf())));
8880
8881 return directControl->OnUSBDeviceDetach (aId, aError);
8882}
8883
8884// protected methods
8885/////////////////////////////////////////////////////////////////////////////
8886
8887/**
8888 * Helper method to finalize saving the state.
8889 *
8890 * @note Must be called from under this object's lock.
8891 *
8892 * @param aSuccess TRUE if the snapshot has been taken successfully
8893 *
8894 * @note Locks mParent + this objects for writing.
8895 */
8896HRESULT SessionMachine::endSavingState (BOOL aSuccess)
8897{
8898 LogFlowThisFuncEnter();
8899
8900 AutoCaller autoCaller(this);
8901 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8902
8903 /* saveSettings() needs mParent lock */
8904 AutoMultiWriteLock2 alock (mParent, this);
8905
8906 HRESULT rc = S_OK;
8907
8908 if (aSuccess)
8909 {
8910 mSSData->mStateFilePath = mSnapshotData.mStateFilePath;
8911
8912 /* save all VM settings */
8913 rc = saveSettings();
8914 }
8915 else
8916 {
8917 /* delete the saved state file (it might have been already created) */
8918 RTFileDelete(Utf8Str(mSnapshotData.mStateFilePath).c_str());
8919 }
8920
8921 /* remove the completed progress object */
8922 mParent->removeProgress (mSnapshotData.mProgressId);
8923
8924 /* clear out the temporary saved state data */
8925 mSnapshotData.mLastState = MachineState_Null;
8926 mSnapshotData.mProgressId.clear();
8927 mSnapshotData.mStateFilePath.setNull();
8928
8929 LogFlowThisFuncLeave();
8930 return rc;
8931}
8932
8933/**
8934 * Helper method to finalize taking a snapshot. Gets called to finalize the
8935 * "take snapshot" procedure.
8936 *
8937 * Expected to be called after completing *all* the tasks related to taking the
8938 * snapshot, either successfully or unsuccessfilly.
8939 *
8940 * @param aSuccess TRUE if the snapshot has been taken successfully.
8941 *
8942 * @note Locks this objects for writing.
8943 */
8944HRESULT SessionMachine::endTakingSnapshot (BOOL aSuccess)
8945{
8946 LogFlowThisFuncEnter();
8947
8948 AutoCaller autoCaller(this);
8949 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
8950
8951 AutoMultiWriteLock2 alock(mParent, this);
8952 // saveSettings needs VirtualBox lock
8953
8954 AssertReturn(!mSnapshotData.mSnapshot.isNull(), E_FAIL);
8955
8956 MultiResult rc (S_OK);
8957
8958 if (aSuccess)
8959 {
8960 /* the server progress must be completed on success */
8961 Assert (mSnapshotData.mServerProgress->completed());
8962
8963 mData->mCurrentSnapshot = mSnapshotData.mSnapshot;
8964
8965 /* memorize the first snapshot if necessary */
8966 if (!mData->mFirstSnapshot)
8967 mData->mFirstSnapshot = mData->mCurrentSnapshot;
8968
8969 if (!Global::IsOnline (mSnapshotData.mLastState))
8970 /* the machine was powered off or saved when taking a snapshot, so
8971 * reset the mCurrentStateModified flag */
8972 mData->mCurrentStateModified = FALSE;
8973
8974 rc = saveSettings();
8975 }
8976
8977 if (aSuccess && SUCCEEDED(rc))
8978 {
8979 bool online = Global::IsOnline (mSnapshotData.mLastState);
8980
8981 /* associate old hard disks with the snapshot and do locking/unlocking*/
8982 fixupHardDisks(true /* aCommit */, online);
8983
8984 /* inform callbacks */
8985 mParent->onSnapshotTaken(mData->mUuid,
8986 mSnapshotData.mSnapshot->getId());
8987 }
8988 else
8989 {
8990 /* wait for the completion of the server progress (diff VDI creation) */
8991 /// @todo (dmik) later, we will definitely want to cancel it instead
8992 // (when the cancel function is implemented)
8993 mSnapshotData.mServerProgress->WaitForCompletion (-1);
8994
8995 /* delete all differencing hard disks created (this will also attach
8996 * their parents back by rolling back mHDData) */
8997 fixupHardDisks(false /* aCommit */);
8998
8999 /* delete the saved state file (it might have been already created) */
9000 if (mSnapshotData.mSnapshot->stateFilePath())
9001 RTFileDelete(Utf8Str(mSnapshotData.mSnapshot->stateFilePath()).c_str());
9002
9003 mSnapshotData.mSnapshot->uninit();
9004 }
9005
9006 /* clear out the snapshot data */
9007 mSnapshotData.mLastState = MachineState_Null;
9008 mSnapshotData.mSnapshot.setNull();
9009 mSnapshotData.mServerProgress.setNull();
9010
9011 /* uninitialize the combined progress (to remove it from the VBox collection) */
9012 if (!mSnapshotData.mCombinedProgress.isNull())
9013 {
9014 mSnapshotData.mCombinedProgress->uninit();
9015 mSnapshotData.mCombinedProgress.setNull();
9016 }
9017
9018 LogFlowThisFuncLeave();
9019 return rc;
9020}
9021
9022/**
9023 * Take snapshot task handler. Must be called only by
9024 * TakeSnapshotTask::handler()!
9025 *
9026 * The sole purpose of this task is to asynchronously create differencing VDIs
9027 * and copy the saved state file (when necessary). The VM process will wait for
9028 * this task to complete using the mSnapshotData.mServerProgress returned to it.
9029 *
9030 * @note Locks this object for writing.
9031 */
9032void SessionMachine::takeSnapshotHandler (TakeSnapshotTask & /* aTask */)
9033{
9034 LogFlowThisFuncEnter();
9035
9036 AutoCaller autoCaller(this);
9037
9038 LogFlowThisFunc(("state=%d\n", autoCaller.state()));
9039 if (!autoCaller.isOk())
9040 {
9041 /* we might have been uninitialized because the session was accidentally
9042 * closed by the client, so don't assert */
9043 LogFlowThisFuncLeave();
9044 return;
9045 }
9046
9047 AutoWriteLock alock(this);
9048
9049 HRESULT rc = S_OK;
9050
9051 bool online = Global::IsOnline (mSnapshotData.mLastState);
9052
9053 LogFlowThisFunc(("Creating differencing hard disks (online=%d)...\n",
9054 online));
9055
9056 mHDData.backup();
9057
9058 /* create new differencing hard disks and attach them to this machine */
9059 rc = createImplicitDiffs (mUserData->mSnapshotFolderFull,
9060 mSnapshotData.mServerProgress,
9061 online);
9062
9063 if (SUCCEEDED(rc) && mSnapshotData.mLastState == MachineState_Saved)
9064 {
9065 Utf8Str stateFrom = mSSData->mStateFilePath;
9066 Utf8Str stateTo = mSnapshotData.mSnapshot->stateFilePath();
9067
9068 LogFlowThisFunc(("Copying the execution state from '%s' to '%s'...\n",
9069 stateFrom.raw(), stateTo.raw()));
9070
9071 mSnapshotData.mServerProgress->setNextOperation(Bstr(tr("Copying the execution state")),
9072 1); // weight
9073
9074 /* Leave the lock before a lengthy operation (mMachineState is
9075 * MachineState_Saving here) */
9076
9077 alock.leave();
9078
9079 /* copy the state file */
9080 int vrc = RTFileCopyEx(stateFrom.c_str(),
9081 stateTo.c_str(),
9082 0,
9083 progressCallback,
9084 static_cast<Progress*>(mSnapshotData.mServerProgress));
9085
9086 alock.enter();
9087
9088 if (RT_FAILURE(vrc))
9089 rc = setError(E_FAIL,
9090 tr("Could not copy the state file '%s' to '%s' (%Rrc)"),
9091 stateFrom.raw(),
9092 stateTo.raw(),
9093 vrc);
9094 }
9095
9096 /* we have to call endTakingSnapshot() ourselves if the snapshot was taken
9097 * offline because the VM process will not do it in this case
9098 */
9099 if (!online)
9100 {
9101 LogFlowThisFunc(("Finalizing the taken snapshot (rc=%Rhrc)...\n", rc));
9102
9103 {
9104 ErrorInfoKeeper eik;
9105
9106 setMachineState (mSnapshotData.mLastState);
9107 updateMachineStateOnClient();
9108 }
9109
9110 /* finalize the progress after setting the state, for consistency */
9111 mSnapshotData.mServerProgress->notifyComplete (rc);
9112
9113 endTakingSnapshot (SUCCEEDED(rc));
9114 }
9115 else
9116 {
9117 mSnapshotData.mServerProgress->notifyComplete (rc);
9118 }
9119
9120 LogFlowThisFuncLeave();
9121}
9122
9123/**
9124 * Helper struct for SessionMachine::discardSnapshotHandler().
9125 */
9126struct HardDiskDiscardRec
9127{
9128 HardDiskDiscardRec() : chain (NULL) {}
9129
9130 HardDiskDiscardRec (const ComObjPtr<HardDisk> &aHd,
9131 HardDisk::MergeChain *aChain = NULL)
9132 : hd (aHd), chain (aChain) {}
9133
9134 HardDiskDiscardRec (const ComObjPtr<HardDisk> &aHd,
9135 HardDisk::MergeChain *aChain,
9136 const ComObjPtr<HardDisk> &aReplaceHd,
9137 const ComObjPtr<HardDiskAttachment> &aReplaceHda,
9138 const Guid &aSnapshotId)
9139 : hd (aHd), chain (aChain)
9140 , replaceHd (aReplaceHd), replaceHda (aReplaceHda)
9141 , snapshotId (aSnapshotId) {}
9142
9143 ComObjPtr<HardDisk> hd;
9144 HardDisk::MergeChain *chain;
9145 /* these are for the replace hard disk case: */
9146 ComObjPtr<HardDisk> replaceHd;
9147 ComObjPtr<HardDiskAttachment> replaceHda;
9148 Guid snapshotId;
9149};
9150
9151typedef std::list <HardDiskDiscardRec> HardDiskDiscardRecList;
9152
9153/**
9154 * Discard snapshot task handler. Must be called only by
9155 * DiscardSnapshotTask::handler()!
9156 *
9157 * When aTask.subTask is true, the associated progress object is left
9158 * uncompleted on success. On failure, the progress is marked as completed
9159 * regardless of this parameter.
9160 *
9161 * @note Locks mParent + this + child objects for writing!
9162 */
9163void SessionMachine::discardSnapshotHandler(DiscardSnapshotTask &aTask)
9164{
9165 LogFlowThisFuncEnter();
9166
9167 AutoCaller autoCaller(this);
9168
9169 LogFlowThisFunc(("state=%d\n", autoCaller.state()));
9170 if (!autoCaller.isOk())
9171 {
9172 /* we might have been uninitialized because the session was accidentally
9173 * closed by the client, so don't assert */
9174 aTask.progress->notifyComplete (
9175 E_FAIL, COM_IIDOF (IMachine), getComponentName(),
9176 tr ("The session has been accidentally closed"));
9177
9178 LogFlowThisFuncLeave();
9179 return;
9180 }
9181
9182 /* Locking order: */
9183 AutoMultiWriteLock3 alock(this->lockHandle(),
9184 this->snapshotsTreeLockHandle(),
9185 aTask.snapshot->lockHandle());
9186
9187 ComPtr<SnapshotMachine> sm = aTask.snapshot->getSnapshotMachine();
9188 /* no need to lock the snapshot machine since it is const by definiton */
9189
9190 HRESULT rc = S_OK;
9191
9192 /* save the snapshot ID (for callbacks) */
9193 Guid snapshotId = aTask.snapshot->getId();
9194
9195 HardDiskDiscardRecList toDiscard;
9196
9197 bool settingsChanged = false;
9198
9199 try
9200 {
9201 /* first pass: */
9202 LogFlowThisFunc(("1: Checking hard disk merge prerequisites...\n"));
9203
9204 for (HDData::AttachmentList::const_iterator it = sm->mHDData->mAttachments.begin();
9205 it != sm->mHDData->mAttachments.end();
9206 ++ it)
9207 {
9208 ComObjPtr<HardDiskAttachment> hda = *it;
9209 ComObjPtr<HardDisk> hd = hda->hardDisk();
9210
9211 /* HardDisk::prepareDiscard() reqiuires a write lock */
9212 AutoWriteLock hdLock(hd);
9213
9214 if (hd->type() != HardDiskType_Normal)
9215 {
9216 /* skip writethrough hard disks */
9217
9218 Assert (hd->type() == HardDiskType_Writethrough);
9219
9220 rc = aTask.progress->setNextOperation(BstrFmt(tr("Skipping writethrough hard disk '%s'"),
9221 hd->root()->name().raw()),
9222 1); // weight
9223 CheckComRCThrowRC(rc);
9224
9225 continue;
9226 }
9227
9228 HardDisk::MergeChain *chain = NULL;
9229
9230 /* needs to be discarded (merged with the child if any), check
9231 * prerequisites */
9232 rc = hd->prepareDiscard (chain);
9233 CheckComRCThrowRC(rc);
9234
9235 if (hd->parent().isNull() && chain != NULL)
9236 {
9237 /* it's a base hard disk so it will be a backward merge of its
9238 * only child to it (prepareDiscard() does necessary checks). We
9239 * need then to update the attachment that refers to the child
9240 * to refer to the parent insead. Don't forget to detach the
9241 * child (otherwise mergeTo() called by discard() will assert
9242 * because it will be going to delete the child) */
9243
9244 /* The below assert would be nice but I don't want to move
9245 * HardDisk::MergeChain to the header just for that
9246 * Assert (!chain->isForward()); */
9247
9248 Assert(hd->children().size() == 1);
9249
9250 ComObjPtr<HardDisk> replaceHd = hd->children().front();
9251
9252 Assert (replaceHd->backRefs().front().machineId == mData->mUuid);
9253 Assert (replaceHd->backRefs().front().snapshotIds.size() <= 1);
9254
9255 Guid snapshotId;
9256 if (replaceHd->backRefs().front().snapshotIds.size() == 1)
9257 snapshotId = replaceHd->backRefs().front().snapshotIds.front();
9258
9259 HRESULT rc2 = S_OK;
9260
9261 /* adjust back references */
9262 rc2 = replaceHd->detachFrom (mData->mUuid, snapshotId);
9263 AssertComRC(rc2);
9264
9265 rc2 = hd->attachTo (mData->mUuid, snapshotId);
9266 AssertComRC(rc2);
9267
9268 /* replace the hard disk in the attachment object */
9269 HDData::AttachmentList::iterator it;
9270 if (snapshotId.isEmpty())
9271 {
9272 /* in current state */
9273 it = std::find_if (mHDData->mAttachments.begin(),
9274 mHDData->mAttachments.end(),
9275 HardDiskAttachment::RefersTo (replaceHd));
9276 AssertBreak (it != mHDData->mAttachments.end());
9277 }
9278 else
9279 {
9280 /* in snapshot */
9281 ComObjPtr<Snapshot> snapshot;
9282 rc2 = findSnapshot (snapshotId, snapshot);
9283 AssertComRC (rc2);
9284
9285 /* don't lock the snapshot; cannot be modified outside */
9286 HDData::AttachmentList &snapAtts = snapshot->getSnapshotMachine()->mHDData->mAttachments;
9287 it = std::find_if (snapAtts.begin(),
9288 snapAtts.end(),
9289 HardDiskAttachment::RefersTo (replaceHd));
9290 AssertBreak (it != snapAtts.end());
9291 }
9292
9293 AutoWriteLock attLock (*it);
9294 (*it)->updateHardDisk (hd, false /* aImplicit */);
9295
9296 toDiscard.push_back (HardDiskDiscardRec (hd, chain, replaceHd,
9297 *it, snapshotId));
9298 continue;
9299 }
9300
9301 toDiscard.push_back (HardDiskDiscardRec (hd, chain));
9302 }
9303
9304 /* Now we checked that we can successfully merge all normal hard disks
9305 * (unless a runtime error like end-of-disc happens). Prior to
9306 * performing the actual merge, we want to discard the snapshot itself
9307 * and remove it from the XML file to make sure that a possible merge
9308 * ruintime error will not make this snapshot inconsistent because of
9309 * the partially merged or corrupted hard disks */
9310
9311 /* second pass: */
9312 LogFlowThisFunc(("2: Discarding snapshot...\n"));
9313
9314 {
9315 ComObjPtr<Snapshot> parentSnapshot = aTask.snapshot->parent();
9316 Bstr stateFilePath = aTask.snapshot->stateFilePath();
9317
9318 /* Note that discarding the snapshot will deassociate it from the
9319 * hard disks which will allow the merge+delete operation for them*/
9320 aTask.snapshot->beginDiscard();
9321 aTask.snapshot->uninit();
9322
9323 rc = saveAllSnapshots();
9324 CheckComRCThrowRC(rc);
9325
9326 /// @todo (dmik)
9327 // if we implement some warning mechanism later, we'll have
9328 // to return a warning if the state file path cannot be deleted
9329 if (stateFilePath)
9330 {
9331 aTask.progress->setNextOperation(Bstr(tr("Discarding the execution state")),
9332 1); // weight
9333
9334 RTFileDelete(Utf8Str(stateFilePath).c_str());
9335 }
9336
9337 /// @todo NEWMEDIA to provide a good level of fauilt tolerance, we
9338 /// should restore the shapshot in the snapshot tree if
9339 /// saveSnapshotSettings fails. Actually, we may call
9340 /// #saveSnapshotSettings() with a special flag that will tell it to
9341 /// skip the given snapshot as if it would have been discarded and
9342 /// only actually discard it if the save operation succeeds.
9343 }
9344
9345 /* here we come when we've irrevesibly discarded the snapshot which
9346 * means that the VM settigns (our relevant changes to mData) need to be
9347 * saved too */
9348 /// @todo NEWMEDIA maybe save everything in one operation in place of
9349 /// saveSnapshotSettings() above
9350 settingsChanged = true;
9351
9352 /* third pass: */
9353 LogFlowThisFunc(("3: Performing actual hard disk merging...\n"));
9354
9355 /* leave the locks before the potentially lengthy operation */
9356 alock.leave();
9357
9358 /// @todo NEWMEDIA turn the following errors into warnings because the
9359 /// snapshot itself has been already deleted (and interpret these
9360 /// warnings properly on the GUI side)
9361
9362 for (HardDiskDiscardRecList::iterator it = toDiscard.begin();
9363 it != toDiscard.end();)
9364 {
9365 rc = it->hd->discard (aTask.progress, it->chain);
9366 CheckComRCBreakRC(rc);
9367
9368 /* prevent from calling cancelDiscard() */
9369 it = toDiscard.erase (it);
9370 }
9371
9372 alock.enter();
9373
9374 CheckComRCThrowRC(rc);
9375 }
9376 catch (HRESULT aRC) { rc = aRC; }
9377
9378 if FAILED(rc)
9379 {
9380 HRESULT rc2 = S_OK;
9381
9382 /* un-prepare the remaining hard disks */
9383 for (HardDiskDiscardRecList::const_iterator it = toDiscard.begin();
9384 it != toDiscard.end(); ++ it)
9385 {
9386 it->hd->cancelDiscard (it->chain);
9387
9388 if (!it->replaceHd.isNull())
9389 {
9390 /* undo hard disk replacement */
9391
9392 rc2 = it->replaceHd->attachTo (mData->mUuid, it->snapshotId);
9393 AssertComRC(rc2);
9394
9395 rc2 = it->hd->detachFrom (mData->mUuid, it->snapshotId);
9396 AssertComRC(rc2);
9397
9398 AutoWriteLock attLock (it->replaceHda);
9399 it->replaceHda->updateHardDisk (it->replaceHd, false /* aImplicit */);
9400 }
9401 }
9402 }
9403
9404 if (!aTask.subTask || FAILED(rc))
9405 {
9406 if (!aTask.subTask)
9407 {
9408 /* saveSettings() below needs a VirtualBox write lock and we need to
9409 * leave this object's lock to do this to follow the {parent-child}
9410 * locking rule. This is the last chance to do that while we are
9411 * still in a protective state which allows us to temporarily leave
9412 * the lock */
9413 alock.unlock();
9414 AutoWriteLock vboxLock(mParent);
9415 alock.lock();
9416
9417 /* preserve existing error info */
9418 ErrorInfoKeeper eik;
9419
9420 /* restore the machine state */
9421 setMachineState(aTask.state);
9422 updateMachineStateOnClient();
9423
9424 if (settingsChanged)
9425 saveSettings(SaveS_InformCallbacksAnyway);
9426 }
9427
9428 /* set the result (this will try to fetch current error info on failure) */
9429 aTask.progress->notifyComplete (rc);
9430 }
9431
9432 if (SUCCEEDED(rc))
9433 mParent->onSnapshotDiscarded (mData->mUuid, snapshotId);
9434
9435 LogFlowThisFunc(("Done discarding snapshot (rc=%08X)\n", rc));
9436 LogFlowThisFuncLeave();
9437}
9438
9439/**
9440 * Discard current state task handler. Must be called only by
9441 * DiscardCurrentStateTask::handler()!
9442 *
9443 * @note Locks mParent + this object for writing.
9444 */
9445void SessionMachine::discardCurrentStateHandler (DiscardCurrentStateTask &aTask)
9446{
9447 LogFlowThisFuncEnter();
9448
9449 AutoCaller autoCaller(this);
9450
9451 LogFlowThisFunc(("state=%d\n", autoCaller.state()));
9452 if (!autoCaller.isOk())
9453 {
9454 /* we might have been uninitialized because the session was accidentally
9455 * closed by the client, so don't assert */
9456 aTask.progress->notifyComplete (
9457 E_FAIL, COM_IIDOF (IMachine), getComponentName(),
9458 tr ("The session has been accidentally closed"));
9459
9460 LogFlowThisFuncLeave();
9461 return;
9462 }
9463
9464 /* saveSettings() needs mParent lock */
9465 AutoWriteLock vboxLock (mParent);
9466
9467 /* @todo We don't need mParent lock so far so unlock() it. Better is to
9468 * provide an AutoWriteLock argument that lets create a non-locking
9469 * instance */
9470 vboxLock.unlock();
9471
9472 AutoWriteLock alock(this);
9473
9474 /* discard all current changes to mUserData (name, OSType etc.) (note that
9475 * the machine is powered off, so there is no need to inform the direct
9476 * session) */
9477 if (isModified())
9478 rollback (false /* aNotify */);
9479
9480 HRESULT rc = S_OK;
9481
9482 bool errorInSubtask = false;
9483 bool stateRestored = false;
9484
9485 const bool isLastSnapshot = mData->mCurrentSnapshot->parent().isNull();
9486
9487 try
9488 {
9489 /* discard the saved state file if the machine was Saved prior to this
9490 * operation */
9491 if (aTask.state == MachineState_Saved)
9492 {
9493 Assert (!mSSData->mStateFilePath.isEmpty());
9494 RTFileDelete(Utf8Str(mSSData->mStateFilePath).c_str());
9495 mSSData->mStateFilePath.setNull();
9496 aTask.modifyLastState (MachineState_PoweredOff);
9497 rc = saveStateSettings (SaveSTS_StateFilePath);
9498 CheckComRCThrowRC(rc);
9499 }
9500
9501 if (aTask.discardCurrentSnapshot && !isLastSnapshot)
9502 {
9503 /* the "discard current snapshot and state" task is in action, the
9504 * current snapshot is not the last one. Discard the current
9505 * snapshot first */
9506
9507 DiscardSnapshotTask subTask (aTask, mData->mCurrentSnapshot);
9508 subTask.subTask = true;
9509 discardSnapshotHandler (subTask);
9510
9511 AutoCaller progressCaller (aTask.progress);
9512 AutoReadLock progressLock (aTask.progress);
9513 if (aTask.progress->completed())
9514 {
9515 /* the progress can be completed by a subtask only if there was
9516 * a failure */
9517 rc = aTask.progress->resultCode();
9518 Assert (FAILED(rc));
9519 errorInSubtask = true;
9520 throw rc;
9521 }
9522 }
9523
9524 RTTIMESPEC snapshotTimeStamp;
9525 RTTimeSpecSetMilli (&snapshotTimeStamp, 0);
9526
9527 {
9528 ComObjPtr<Snapshot> curSnapshot = mData->mCurrentSnapshot;
9529 AutoReadLock snapshotLock (curSnapshot);
9530
9531 /* remember the timestamp of the snapshot we're restoring from */
9532 snapshotTimeStamp = curSnapshot->getTimeStamp();
9533
9534 ComPtr<SnapshotMachine> pSnapshotMachine(curSnapshot->getSnapshotMachine());
9535
9536 /* copy all hardware data from the current snapshot */
9537 copyFrom(pSnapshotMachine);
9538
9539 LogFlowThisFunc(("Restoring hard disks from the snapshot...\n"));
9540
9541 /* restore the attachmends from the snapshot */
9542 mHDData.backup();
9543 mHDData->mAttachments =
9544 pSnapshotMachine->mHDData->mAttachments;
9545
9546 /* leave the locks before the potentially lengthy operation */
9547 snapshotLock.unlock();
9548 alock.leave();
9549
9550 rc = createImplicitDiffs(mUserData->mSnapshotFolderFull,
9551 aTask.progress,
9552 false /* aOnline */);
9553
9554 alock.enter();
9555 snapshotLock.lock();
9556
9557 CheckComRCThrowRC(rc);
9558
9559 /* Note: on success, current (old) hard disks will be
9560 * deassociated/deleted on #commit() called from #saveSettings() at
9561 * the end. On failure, newly created implicit diffs will be
9562 * deleted by #rollback() at the end. */
9563
9564 /* should not have a saved state file associated at this point */
9565 Assert (mSSData->mStateFilePath.isNull());
9566
9567 if (curSnapshot->stateFilePath())
9568 {
9569 Utf8Str snapStateFilePath = curSnapshot->stateFilePath();
9570
9571 Utf8Str stateFilePath = Utf8StrFmt ("%ls%c{%RTuuid}.sav",
9572 mUserData->mSnapshotFolderFull.raw(),
9573 RTPATH_DELIMITER, mData->mUuid.raw());
9574
9575 LogFlowThisFunc(("Copying saved state file from '%s' to '%s'...\n",
9576 snapStateFilePath.raw(), stateFilePath.raw()));
9577
9578 aTask.progress->setNextOperation(Bstr(tr("Restoring the execution state")),
9579 1); // weight
9580
9581 /* leave the lock before the potentially lengthy operation */
9582 snapshotLock.unlock();
9583 alock.leave();
9584
9585 /* copy the state file */
9586 int vrc = RTFileCopyEx(snapStateFilePath.c_str(),
9587 stateFilePath.c_str(),
9588 0,
9589 progressCallback,
9590 aTask.progress);
9591
9592 alock.enter();
9593 snapshotLock.lock();
9594
9595 if (RT_SUCCESS(vrc))
9596 {
9597 mSSData->mStateFilePath = stateFilePath;
9598 }
9599 else
9600 {
9601 throw setError(E_FAIL,
9602 tr("Could not copy the state file '%s' to '%s' (%Rrc)"),
9603 snapStateFilePath.raw(),
9604 stateFilePath.raw(),
9605 vrc);
9606 }
9607 }
9608 }
9609
9610 /* grab differencing hard disks from the old attachments that will
9611 * become unused and need to be auto-deleted */
9612
9613 std::list< ComObjPtr<HardDisk> > diffs;
9614
9615 for (HDData::AttachmentList::const_iterator
9616 it = mHDData.backedUpData()->mAttachments.begin();
9617 it != mHDData.backedUpData()->mAttachments.end(); ++ it)
9618 {
9619 ComObjPtr<HardDisk> hd = (*it)->hardDisk();
9620
9621 /* while the hard disk is attached, the number of children or the
9622 * parent cannot change, so no lock */
9623 if (!hd->parent().isNull() && hd->children().size() == 0)
9624 diffs.push_back (hd);
9625 }
9626
9627 int saveFlags = 0;
9628
9629 if (aTask.discardCurrentSnapshot && isLastSnapshot)
9630 {
9631 /* commit changes to have unused diffs deassociated from this
9632 * machine before deletion (see below) */
9633 commit();
9634
9635 /* delete the unused diffs now (and uninit them) because discard
9636 * may fail otherwise (too many children of the hard disk to be
9637 * discarded) */
9638 for (std::list< ComObjPtr<HardDisk> >::const_iterator
9639 it = diffs.begin(); it != diffs.end(); ++ it)
9640 {
9641 /// @todo for now, we ignore errors since we've already
9642 /// and therefore cannot fail. Later, we may want to report a
9643 /// warning through the Progress object
9644 HRESULT rc2 = (*it)->deleteStorageAndWait();
9645 if (SUCCEEDED(rc2))
9646 (*it)->uninit();
9647 }
9648
9649 /* prevent further deletion */
9650 diffs.clear();
9651
9652 /* discard the current snapshot and state task is in action, the
9653 * current snapshot is the last one. Discard the current snapshot
9654 * after discarding the current state. */
9655
9656 DiscardSnapshotTask subTask (aTask, mData->mCurrentSnapshot);
9657 subTask.subTask = true;
9658 discardSnapshotHandler (subTask);
9659
9660 AutoCaller progressCaller (aTask.progress);
9661 AutoReadLock progressLock (aTask.progress);
9662 if (aTask.progress->completed())
9663 {
9664 /* the progress can be completed by a subtask only if there
9665 * was a failure */
9666 rc = aTask.progress->resultCode();
9667 Assert (FAILED(rc));
9668 errorInSubtask = true;
9669 }
9670
9671 /* we've committed already, so inform callbacks anyway to ensure
9672 * they don't miss some change */
9673 /// @todo NEWMEDIA check if we need this informCallbacks at all
9674 /// after updating discardCurrentSnapshot functionality
9675 saveFlags |= SaveS_InformCallbacksAnyway;
9676 }
9677
9678 /* @todo saveSettings() below needs a VirtualBox write lock and we need
9679 * to leave this object's lock to do this to follow the {parent-child}
9680 * locking rule. This is the last chance to do that while we are still
9681 * in a protective state which allows us to temporarily leave the lock*/
9682 alock.unlock();
9683 vboxLock.lock();
9684 alock.lock();
9685
9686 /* we have already discarded the current state, so set the execution
9687 * state accordingly no matter of the discard snapshot result */
9688 if (mSSData->mStateFilePath)
9689 setMachineState (MachineState_Saved);
9690 else
9691 setMachineState (MachineState_PoweredOff);
9692
9693 updateMachineStateOnClient();
9694 stateRestored = true;
9695
9696 /* assign the timestamp from the snapshot */
9697 Assert (RTTimeSpecGetMilli (&snapshotTimeStamp) != 0);
9698 mData->mLastStateChange = snapshotTimeStamp;
9699
9700 /* save all settings, reset the modified flag and commit. Note that we
9701 * do so even if the subtask failed (errorInSubtask=true) because we've
9702 * already committed machine data and deleted old diffs before
9703 * discarding the current snapshot so there is no way to rollback */
9704 HRESULT rc2 = saveSettings(SaveS_ResetCurStateModified | saveFlags);
9705
9706 /// @todo NEWMEDIA return multiple errors
9707 if (errorInSubtask)
9708 throw rc;
9709
9710 rc = rc2;
9711
9712 if (SUCCEEDED(rc))
9713 {
9714 /* now, delete the unused diffs (only on success!) and uninit them*/
9715 for (std::list< ComObjPtr<HardDisk> >::const_iterator
9716 it = diffs.begin(); it != diffs.end(); ++ it)
9717 {
9718 /// @todo for now, we ignore errors since we've already
9719 /// discarded and therefore cannot fail. Later, we may want to
9720 /// report a warning through the Progress object
9721 HRESULT rc2 = (*it)->deleteStorageAndWait();
9722 if (SUCCEEDED(rc2))
9723 (*it)->uninit();
9724 }
9725 }
9726 }
9727 catch (HRESULT aRC) { rc = aRC; }
9728
9729 if (FAILED (rc))
9730 {
9731 /* preserve existing error info */
9732 ErrorInfoKeeper eik;
9733
9734 if (!errorInSubtask)
9735 {
9736 /* undo all changes on failure unless the subtask has done so */
9737 rollback (false /* aNotify */);
9738 }
9739
9740 if (!stateRestored)
9741 {
9742 /* restore the machine state */
9743 setMachineState (aTask.state);
9744 updateMachineStateOnClient();
9745 }
9746 }
9747
9748 if (!errorInSubtask)
9749 {
9750 /* set the result (this will try to fetch current error info on failure) */
9751 aTask.progress->notifyComplete (rc);
9752 }
9753
9754 if (SUCCEEDED(rc))
9755 mParent->onSnapshotDiscarded (mData->mUuid, Guid());
9756
9757 LogFlowThisFunc(("Done discarding current state (rc=%08X)\n", rc));
9758
9759 LogFlowThisFuncLeave();
9760}
9761
9762/**
9763 * Locks the attached media.
9764 *
9765 * All attached hard disks are locked for writing and DVD/floppy are locked for
9766 * reading. Parents of attached hard disks (if any) are locked for reading.
9767 *
9768 * This method also performs accessibility check of all media it locks: if some
9769 * media is inaccessible, the method will return a failure and a bunch of
9770 * extended error info objects per each inaccessible medium.
9771 *
9772 * Note that this method is atomic: if it returns a success, all media are
9773 * locked as described above; on failure no media is locked at all (all
9774 * succeeded individual locks will be undone).
9775 *
9776 * This method is intended to be called when the machine is in Starting or
9777 * Restoring state and asserts otherwise.
9778 *
9779 * The locks made by this method must be undone by calling #unlockMedia() when
9780 * no more needed.
9781 */
9782HRESULT SessionMachine::lockMedia()
9783{
9784 AutoCaller autoCaller(this);
9785 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9786
9787 AutoWriteLock alock(this);
9788
9789 AssertReturn(mData->mMachineState == MachineState_Starting ||
9790 mData->mMachineState == MachineState_Restoring, E_FAIL);
9791
9792 typedef std::list <ComPtr<IMedium> > MediaList;
9793 MediaList mediaToCheck;
9794 MediaState_T mediaState;
9795
9796 try
9797 {
9798 HRESULT rc = S_OK;
9799
9800 /* lock hard disks */
9801 for (HDData::AttachmentList::const_iterator it =
9802 mHDData->mAttachments.begin();
9803 it != mHDData->mAttachments.end(); ++ it)
9804 {
9805 ComObjPtr<HardDisk> hd = (*it)->hardDisk();
9806
9807 bool first = true;
9808
9809 /** @todo split out the media locking, and put it into
9810 * HardDiskImpl.cpp, as it needs this functionality too. */
9811 while (!hd.isNull())
9812 {
9813 if (first)
9814 {
9815 rc = hd->LockWrite (&mediaState);
9816 CheckComRCThrowRC(rc);
9817
9818 mData->mSession.mLockedMedia.push_back (
9819 Data::Session::LockedMedia::value_type (
9820 ComPtr<IHardDisk> (hd), true));
9821
9822 first = false;
9823 }
9824 else
9825 {
9826 rc = hd->LockRead (&mediaState);
9827 CheckComRCThrowRC(rc);
9828
9829 mData->mSession.mLockedMedia.push_back (
9830 Data::Session::LockedMedia::value_type (
9831 ComPtr<IHardDisk> (hd), false));
9832 }
9833
9834 if (mediaState == MediaState_Inaccessible)
9835 mediaToCheck.push_back (ComPtr<IHardDisk> (hd));
9836
9837 /* no locks or callers here since there should be no way to
9838 * change the hard disk parent at this point (as it is still
9839 * attached to the machine) */
9840 hd = hd->parent();
9841 }
9842 }
9843
9844 /* lock the DVD image for reading if mounted */
9845 {
9846 AutoReadLock driveLock (mDVDDrive);
9847 if (mDVDDrive->data()->state == DriveState_ImageMounted)
9848 {
9849 ComObjPtr<DVDImage> image = mDVDDrive->data()->image;
9850
9851 rc = image->LockRead (&mediaState);
9852 CheckComRCThrowRC (rc);
9853
9854 mData->mSession.mLockedMedia.push_back (
9855 Data::Session::LockedMedia::value_type (
9856 ComPtr<IDVDImage> (image), false));
9857
9858 if (mediaState == MediaState_Inaccessible)
9859 mediaToCheck.push_back (ComPtr<IDVDImage> (image));
9860 }
9861 }
9862
9863 /* lock the floppy image for reading if mounted */
9864 {
9865 AutoReadLock driveLock (mFloppyDrive);
9866 if (mFloppyDrive->data()->state == DriveState_ImageMounted)
9867 {
9868 ComObjPtr<FloppyImage> image = mFloppyDrive->data()->image;
9869
9870 rc = image->LockRead (&mediaState);
9871 CheckComRCThrowRC (rc);
9872
9873 mData->mSession.mLockedMedia.push_back (
9874 Data::Session::LockedMedia::value_type (
9875 ComPtr<IFloppyImage> (image), false));
9876
9877 if (mediaState == MediaState_Inaccessible)
9878 mediaToCheck.push_back (ComPtr<IFloppyImage> (image));
9879 }
9880 }
9881
9882 /* SUCCEEDED locking all media, now check accessibility */
9883
9884 ErrorInfoKeeper eik (true /* aIsNull */);
9885 MultiResult mrc (S_OK);
9886
9887 /* perform a check of inaccessible media deferred above */
9888 for (MediaList::const_iterator
9889 it = mediaToCheck.begin();
9890 it != mediaToCheck.end(); ++ it)
9891 {
9892 MediaState_T mediaState;
9893 rc = (*it)->COMGETTER(State) (&mediaState);
9894 CheckComRCThrowRC(rc);
9895
9896 Assert (mediaState == MediaState_LockedRead ||
9897 mediaState == MediaState_LockedWrite);
9898
9899 /* Note that we locked the medium already, so use the error
9900 * value to see if there was an accessibility failure */
9901
9902 Bstr error;
9903 rc = (*it)->COMGETTER(LastAccessError) (error.asOutParam());
9904 CheckComRCThrowRC(rc);
9905
9906 if (!error.isEmpty())
9907 {
9908 Bstr loc;
9909 rc = (*it)->COMGETTER(Location) (loc.asOutParam());
9910 CheckComRCThrowRC(rc);
9911
9912 /* collect multiple errors */
9913 eik.restore();
9914
9915 /* be in sync with MediumBase::setStateError() */
9916 Assert (!error.isEmpty());
9917 mrc = setError(E_FAIL,
9918 tr("Medium '%ls' is not accessible. %ls"),
9919 loc.raw(),
9920 error.raw());
9921
9922 eik.fetch();
9923 }
9924 }
9925
9926 eik.restore();
9927 CheckComRCThrowRC((HRESULT) mrc);
9928 }
9929 catch (HRESULT aRC)
9930 {
9931 /* Unlock all locked media on failure */
9932 unlockMedia();
9933 return aRC;
9934 }
9935
9936 return S_OK;
9937}
9938
9939/**
9940 * Undoes the locks made by by #lockMedia().
9941 */
9942void SessionMachine::unlockMedia()
9943{
9944 AutoCaller autoCaller(this);
9945 AssertComRCReturnVoid (autoCaller.rc());
9946
9947 AutoWriteLock alock(this);
9948
9949 /* we may be holding important error info on the current thread;
9950 * preserve it */
9951 ErrorInfoKeeper eik;
9952
9953 HRESULT rc = S_OK;
9954
9955 for (Data::Session::LockedMedia::const_iterator
9956 it = mData->mSession.mLockedMedia.begin();
9957 it != mData->mSession.mLockedMedia.end(); ++ it)
9958 {
9959 MediaState_T state;
9960 if (it->second)
9961 rc = it->first->UnlockWrite (&state);
9962 else
9963 rc = it->first->UnlockRead (&state);
9964
9965 /* The second can happen if an object was re-locked in
9966 * Machine::fixupHardDisks(). The last can happen when e.g a DVD/Floppy
9967 * image was unmounted at runtime. */
9968 Assert (SUCCEEDED(rc) || state == MediaState_LockedRead || state == MediaState_Created);
9969 }
9970
9971 mData->mSession.mLockedMedia.clear();
9972}
9973
9974/**
9975 * Helper to change the machine state (reimplementation).
9976 *
9977 * @note Locks this object for writing.
9978 */
9979HRESULT SessionMachine::setMachineState (MachineState_T aMachineState)
9980{
9981 LogFlowThisFuncEnter();
9982 LogFlowThisFunc(("aMachineState=%d\n", aMachineState));
9983
9984 AutoCaller autoCaller(this);
9985 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9986
9987 AutoWriteLock alock(this);
9988
9989 MachineState_T oldMachineState = mData->mMachineState;
9990
9991 AssertMsgReturn (oldMachineState != aMachineState,
9992 ("oldMachineState=%d, aMachineState=%d\n",
9993 oldMachineState, aMachineState), E_FAIL);
9994
9995 HRESULT rc = S_OK;
9996
9997 int stsFlags = 0;
9998 bool deleteSavedState = false;
9999
10000 /* detect some state transitions */
10001
10002 if ((oldMachineState == MachineState_Saved &&
10003 aMachineState == MachineState_Restoring) ||
10004 (oldMachineState < MachineState_Running /* any other OFF state */ &&
10005 aMachineState == MachineState_Starting))
10006 {
10007 /* The EMT thread is about to start */
10008
10009 /* Nothing to do here for now... */
10010
10011 /// @todo NEWMEDIA don't let mDVDDrive and other children
10012 /// change anything when in the Starting/Restoring state
10013 }
10014 else
10015 if (oldMachineState >= MachineState_Running &&
10016 oldMachineState != MachineState_Discarding &&
10017 oldMachineState != MachineState_SettingUp &&
10018 aMachineState < MachineState_Running &&
10019 /* ignore PoweredOff->Saving->PoweredOff transition when taking a
10020 * snapshot */
10021 (mSnapshotData.mSnapshot.isNull() ||
10022 mSnapshotData.mLastState >= MachineState_Running))
10023 {
10024 /* The EMT thread has just stopped, unlock attached media. Note that as
10025 * opposed to locking that is done from Console, we do unlocking here
10026 * because the VM process may have aborted before having a chance to
10027 * properly unlock all media it locked. */
10028
10029 unlockMedia();
10030 }
10031
10032 if (oldMachineState == MachineState_Restoring)
10033 {
10034 if (aMachineState != MachineState_Saved)
10035 {
10036 /*
10037 * delete the saved state file once the machine has finished
10038 * restoring from it (note that Console sets the state from
10039 * Restoring to Saved if the VM couldn't restore successfully,
10040 * to give the user an ability to fix an error and retry --
10041 * we keep the saved state file in this case)
10042 */
10043 deleteSavedState = true;
10044 }
10045 }
10046 else
10047 if (oldMachineState == MachineState_Saved &&
10048 (aMachineState == MachineState_PoweredOff ||
10049 aMachineState == MachineState_Aborted))
10050 {
10051 /*
10052 * delete the saved state after Console::DiscardSavedState() is called
10053 * or if the VM process (owning a direct VM session) crashed while the
10054 * VM was Saved
10055 */
10056
10057 /// @todo (dmik)
10058 // Not sure that deleting the saved state file just because of the
10059 // client death before it attempted to restore the VM is a good
10060 // thing. But when it crashes we need to go to the Aborted state
10061 // which cannot have the saved state file associated... The only
10062 // way to fix this is to make the Aborted condition not a VM state
10063 // but a bool flag: i.e., when a crash occurs, set it to true and
10064 // change the state to PoweredOff or Saved depending on the
10065 // saved state presence.
10066
10067 deleteSavedState = true;
10068 mData->mCurrentStateModified = TRUE;
10069 stsFlags |= SaveSTS_CurStateModified;
10070 }
10071
10072 if (aMachineState == MachineState_Starting ||
10073 aMachineState == MachineState_Restoring)
10074 {
10075 /* set the current state modified flag to indicate that the current
10076 * state is no more identical to the state in the
10077 * current snapshot */
10078 if (!mData->mCurrentSnapshot.isNull())
10079 {
10080 mData->mCurrentStateModified = TRUE;
10081 stsFlags |= SaveSTS_CurStateModified;
10082 }
10083 }
10084
10085 if (deleteSavedState)
10086 {
10087 if (mRemoveSavedState)
10088 {
10089 Assert (!mSSData->mStateFilePath.isEmpty());
10090 RTFileDelete(Utf8Str(mSSData->mStateFilePath).c_str());
10091 }
10092 mSSData->mStateFilePath.setNull();
10093 stsFlags |= SaveSTS_StateFilePath;
10094 }
10095
10096 /* redirect to the underlying peer machine */
10097 mPeer->setMachineState (aMachineState);
10098
10099 if (aMachineState == MachineState_PoweredOff ||
10100 aMachineState == MachineState_Aborted ||
10101 aMachineState == MachineState_Saved)
10102 {
10103 /* the machine has stopped execution
10104 * (or the saved state file was adopted) */
10105 stsFlags |= SaveSTS_StateTimeStamp;
10106 }
10107
10108 if ((oldMachineState == MachineState_PoweredOff ||
10109 oldMachineState == MachineState_Aborted) &&
10110 aMachineState == MachineState_Saved)
10111 {
10112 /* the saved state file was adopted */
10113 Assert (!mSSData->mStateFilePath.isNull());
10114 stsFlags |= SaveSTS_StateFilePath;
10115 }
10116
10117 rc = saveStateSettings (stsFlags);
10118
10119 if ((oldMachineState != MachineState_PoweredOff &&
10120 oldMachineState != MachineState_Aborted) &&
10121 (aMachineState == MachineState_PoweredOff ||
10122 aMachineState == MachineState_Aborted))
10123 {
10124 /* we've been shut down for any reason */
10125 /* no special action so far */
10126 }
10127
10128 LogFlowThisFunc(("rc=%08X\n", rc));
10129 LogFlowThisFuncLeave();
10130 return rc;
10131}
10132
10133/**
10134 * Sends the current machine state value to the VM process.
10135 *
10136 * @note Locks this object for reading, then calls a client process.
10137 */
10138HRESULT SessionMachine::updateMachineStateOnClient()
10139{
10140 AutoCaller autoCaller(this);
10141 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
10142
10143 ComPtr<IInternalSessionControl> directControl;
10144 {
10145 AutoReadLock alock(this);
10146 AssertReturn(!!mData, E_FAIL);
10147 directControl = mData->mSession.mDirectControl;
10148
10149 /* directControl may be already set to NULL here in #OnSessionEnd()
10150 * called too early by the direct session process while there is still
10151 * some operation (like discarding the snapshot) in progress. The client
10152 * process in this case is waiting inside Session::close() for the
10153 * "end session" process object to complete, while #uninit() called by
10154 * #checkForDeath() on the Watcher thread is waiting for the pending
10155 * operation to complete. For now, we accept this inconsitent behavior
10156 * and simply do nothing here. */
10157
10158 if (mData->mSession.mState == SessionState_Closing)
10159 return S_OK;
10160
10161 AssertReturn(!directControl.isNull(), E_FAIL);
10162 }
10163
10164 return directControl->UpdateMachineState (mData->mMachineState);
10165}
10166
10167/* static */
10168DECLCALLBACK(int) SessionMachine::taskHandler (RTTHREAD /* thread */, void *pvUser)
10169{
10170 AssertReturn(pvUser, VERR_INVALID_POINTER);
10171
10172 Task *task = static_cast <Task *> (pvUser);
10173 task->handler();
10174
10175 // it's our responsibility to delete the task
10176 delete task;
10177
10178 return 0;
10179}
10180
10181/////////////////////////////////////////////////////////////////////////////
10182// SnapshotMachine class
10183/////////////////////////////////////////////////////////////////////////////
10184
10185DEFINE_EMPTY_CTOR_DTOR (SnapshotMachine)
10186
10187HRESULT SnapshotMachine::FinalConstruct()
10188{
10189 LogFlowThisFunc(("\n"));
10190
10191 /* set the proper type to indicate we're the SnapshotMachine instance */
10192 unconst(mType) = IsSnapshotMachine;
10193
10194 return S_OK;
10195}
10196
10197void SnapshotMachine::FinalRelease()
10198{
10199 LogFlowThisFunc(("\n"));
10200
10201 uninit();
10202}
10203
10204/**
10205 * Initializes the SnapshotMachine object when taking a snapshot.
10206 *
10207 * @param aSessionMachine machine to take a snapshot from
10208 * @param aSnapshotId snapshot ID of this snapshot machine
10209 * @param aStateFilePath file where the execution state will be later saved
10210 * (or NULL for the offline snapshot)
10211 *
10212 * @note The aSessionMachine must be locked for writing.
10213 */
10214HRESULT SnapshotMachine::init (SessionMachine *aSessionMachine,
10215 IN_GUID aSnapshotId,
10216 const Utf8Str &aStateFilePath)
10217{
10218 LogFlowThisFuncEnter();
10219 LogFlowThisFunc(("mName={%ls}\n", aSessionMachine->mUserData->mName.raw()));
10220
10221 AssertReturn(aSessionMachine && !Guid (aSnapshotId).isEmpty(), E_INVALIDARG);
10222
10223 /* Enclose the state transition NotReady->InInit->Ready */
10224 AutoInitSpan autoInitSpan(this);
10225 AssertReturn(autoInitSpan.isOk(), E_FAIL);
10226
10227 AssertReturn(aSessionMachine->isWriteLockOnCurrentThread(), E_FAIL);
10228
10229 mSnapshotId = aSnapshotId;
10230
10231 /* memorize the primary Machine instance (i.e. not SessionMachine!) */
10232 unconst(mPeer) = aSessionMachine->mPeer;
10233 /* share the parent pointer */
10234 unconst(mParent) = mPeer->mParent;
10235
10236 /* take the pointer to Data to share */
10237 mData.share (mPeer->mData);
10238
10239 /* take the pointer to UserData to share (our UserData must always be the
10240 * same as Machine's data) */
10241 mUserData.share (mPeer->mUserData);
10242 /* make a private copy of all other data (recent changes from SessionMachine) */
10243 mHWData.attachCopy (aSessionMachine->mHWData);
10244 mHDData.attachCopy (aSessionMachine->mHDData);
10245
10246 /* SSData is always unique for SnapshotMachine */
10247 mSSData.allocate();
10248 mSSData->mStateFilePath = aStateFilePath;
10249
10250 HRESULT rc = S_OK;
10251
10252 /* create copies of all shared folders (mHWData after attiching a copy
10253 * contains just references to original objects) */
10254 for (HWData::SharedFolderList::iterator
10255 it = mHWData->mSharedFolders.begin();
10256 it != mHWData->mSharedFolders.end();
10257 ++ it)
10258 {
10259 ComObjPtr<SharedFolder> folder;
10260 folder.createObject();
10261 rc = folder->initCopy (this, *it);
10262 CheckComRCReturnRC(rc);
10263 *it = folder;
10264 }
10265
10266 /* associate hard disks with the snapshot
10267 * (Machine::uninitDataAndChildObjects() will deassociate at destruction) */
10268 for (HDData::AttachmentList::const_iterator
10269 it = mHDData->mAttachments.begin();
10270 it != mHDData->mAttachments.end();
10271 ++ it)
10272 {
10273 rc = (*it)->hardDisk()->attachTo (mData->mUuid, mSnapshotId);
10274 AssertComRC(rc);
10275 }
10276
10277 /* create copies of all storage controllers (mStorageControllerData
10278 * after attaching a copy contains just references to original objects) */
10279 mStorageControllers.allocate();
10280 for (StorageControllerList::const_iterator
10281 it = aSessionMachine->mStorageControllers->begin();
10282 it != aSessionMachine->mStorageControllers->end();
10283 ++ it)
10284 {
10285 ComObjPtr<StorageController> ctrl;
10286 ctrl.createObject();
10287 ctrl->initCopy (this, *it);
10288 mStorageControllers->push_back(ctrl);
10289 }
10290
10291 /* create all other child objects that will be immutable private copies */
10292
10293 unconst(mBIOSSettings).createObject();
10294 mBIOSSettings->initCopy (this, mPeer->mBIOSSettings);
10295
10296#ifdef VBOX_WITH_VRDP
10297 unconst(mVRDPServer).createObject();
10298 mVRDPServer->initCopy (this, mPeer->mVRDPServer);
10299#endif
10300
10301 unconst(mDVDDrive).createObject();
10302 mDVDDrive->initCopy (this, mPeer->mDVDDrive);
10303
10304 unconst(mFloppyDrive).createObject();
10305 mFloppyDrive->initCopy (this, mPeer->mFloppyDrive);
10306
10307 unconst(mAudioAdapter).createObject();
10308 mAudioAdapter->initCopy (this, mPeer->mAudioAdapter);
10309
10310 unconst(mUSBController).createObject();
10311 mUSBController->initCopy (this, mPeer->mUSBController);
10312
10313 for (ULONG slot = 0; slot < RT_ELEMENTS (mNetworkAdapters); slot ++)
10314 {
10315 unconst(mNetworkAdapters [slot]).createObject();
10316 mNetworkAdapters [slot]->initCopy (this, mPeer->mNetworkAdapters [slot]);
10317 }
10318
10319 for (ULONG slot = 0; slot < RT_ELEMENTS (mSerialPorts); slot ++)
10320 {
10321 unconst(mSerialPorts [slot]).createObject();
10322 mSerialPorts [slot]->initCopy (this, mPeer->mSerialPorts [slot]);
10323 }
10324
10325 for (ULONG slot = 0; slot < RT_ELEMENTS (mParallelPorts); slot ++)
10326 {
10327 unconst(mParallelPorts [slot]).createObject();
10328 mParallelPorts [slot]->initCopy (this, mPeer->mParallelPorts [slot]);
10329 }
10330
10331 /* Confirm a successful initialization when it's the case */
10332 autoInitSpan.setSucceeded();
10333
10334 LogFlowThisFuncLeave();
10335 return S_OK;
10336}
10337
10338/**
10339 * Initializes the SnapshotMachine object when loading from the settings file.
10340 *
10341 * @param aMachine machine the snapshot belngs to
10342 * @param aHWNode <Hardware> node
10343 * @param aHDAsNode <HardDiskAttachments> node
10344 * @param aSnapshotId snapshot ID of this snapshot machine
10345 * @param aStateFilePath file where the execution state is saved
10346 * (or NULL for the offline snapshot)
10347 *
10348 * @note Doesn't lock anything.
10349 */
10350HRESULT SnapshotMachine::init(Machine *aMachine,
10351 const settings::Hardware &hardware,
10352 const settings::Storage &storage,
10353 IN_GUID aSnapshotId,
10354 const Utf8Str &aStateFilePath)
10355{
10356 LogFlowThisFuncEnter();
10357 LogFlowThisFunc(("mName={%ls}\n", aMachine->mUserData->mName.raw()));
10358
10359 AssertReturn(aMachine && !Guid(aSnapshotId).isEmpty(), E_INVALIDARG);
10360
10361 /* Enclose the state transition NotReady->InInit->Ready */
10362 AutoInitSpan autoInitSpan(this);
10363 AssertReturn(autoInitSpan.isOk(), E_FAIL);
10364
10365 /* Don't need to lock aMachine when VirtualBox is starting up */
10366
10367 mSnapshotId = aSnapshotId;
10368
10369 /* memorize the primary Machine instance */
10370 unconst(mPeer) = aMachine;
10371 /* share the parent pointer */
10372 unconst(mParent) = mPeer->mParent;
10373
10374 /* take the pointer to Data to share */
10375 mData.share (mPeer->mData);
10376 /*
10377 * take the pointer to UserData to share
10378 * (our UserData must always be the same as Machine's data)
10379 */
10380 mUserData.share (mPeer->mUserData);
10381 /* allocate private copies of all other data (will be loaded from settings) */
10382 mHWData.allocate();
10383 mHDData.allocate();
10384 mStorageControllers.allocate();
10385
10386 /* SSData is always unique for SnapshotMachine */
10387 mSSData.allocate();
10388 mSSData->mStateFilePath = aStateFilePath;
10389
10390 /* create all other child objects that will be immutable private copies */
10391
10392 unconst(mBIOSSettings).createObject();
10393 mBIOSSettings->init (this);
10394
10395#ifdef VBOX_WITH_VRDP
10396 unconst(mVRDPServer).createObject();
10397 mVRDPServer->init (this);
10398#endif
10399
10400 unconst(mDVDDrive).createObject();
10401 mDVDDrive->init (this);
10402
10403 unconst(mFloppyDrive).createObject();
10404 mFloppyDrive->init (this);
10405
10406 unconst(mAudioAdapter).createObject();
10407 mAudioAdapter->init (this);
10408
10409 unconst(mUSBController).createObject();
10410 mUSBController->init (this);
10411
10412 for (ULONG slot = 0; slot < RT_ELEMENTS (mNetworkAdapters); slot ++)
10413 {
10414 unconst(mNetworkAdapters [slot]).createObject();
10415 mNetworkAdapters [slot]->init (this, slot);
10416 }
10417
10418 for (ULONG slot = 0; slot < RT_ELEMENTS (mSerialPorts); slot ++)
10419 {
10420 unconst(mSerialPorts [slot]).createObject();
10421 mSerialPorts [slot]->init (this, slot);
10422 }
10423
10424 for (ULONG slot = 0; slot < RT_ELEMENTS (mParallelPorts); slot ++)
10425 {
10426 unconst(mParallelPorts [slot]).createObject();
10427 mParallelPorts [slot]->init (this, slot);
10428 }
10429
10430 /* load hardware and harddisk settings */
10431
10432 HRESULT rc = loadHardware(hardware);
10433 if (SUCCEEDED(rc))
10434 rc = loadStorageControllers(storage, true /* aRegistered */, &mSnapshotId);
10435
10436 if (SUCCEEDED(rc))
10437 /* commit all changes made during the initialization */
10438 commit();
10439
10440 /* Confirm a successful initialization when it's the case */
10441 if (SUCCEEDED(rc))
10442 autoInitSpan.setSucceeded();
10443
10444 LogFlowThisFuncLeave();
10445 return rc;
10446}
10447
10448/**
10449 * Uninitializes this SnapshotMachine object.
10450 */
10451void SnapshotMachine::uninit()
10452{
10453 LogFlowThisFuncEnter();
10454
10455 /* Enclose the state transition Ready->InUninit->NotReady */
10456 AutoUninitSpan autoUninitSpan(this);
10457 if (autoUninitSpan.uninitDone())
10458 return;
10459
10460 uninitDataAndChildObjects();
10461
10462 /* free the essential data structure last */
10463 mData.free();
10464
10465 unconst(mParent).setNull();
10466 unconst(mPeer).setNull();
10467
10468 LogFlowThisFuncLeave();
10469}
10470
10471// util::Lockable interface
10472////////////////////////////////////////////////////////////////////////////////
10473
10474/**
10475 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
10476 * with the primary Machine instance (mPeer).
10477 */
10478RWLockHandle *SnapshotMachine::lockHandle() const
10479{
10480 AssertReturn(!mPeer.isNull(), NULL);
10481 return mPeer->lockHandle();
10482}
10483
10484// public methods only for internal purposes
10485////////////////////////////////////////////////////////////////////////////////
10486
10487/**
10488 * Called by the snapshot object associated with this SnapshotMachine when
10489 * snapshot data such as name or description is changed.
10490 *
10491 * @note Locks this object for writing.
10492 */
10493HRESULT SnapshotMachine::onSnapshotChange (Snapshot *aSnapshot)
10494{
10495 AutoWriteLock alock(this);
10496
10497 // mPeer->saveAllSnapshots(); @todo
10498
10499 /* inform callbacks */
10500 mParent->onSnapshotChange(mData->mUuid, aSnapshot->getId());
10501
10502 return S_OK;
10503}
10504/* 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