VirtualBox

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

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

Main: fix broken deletion of extradata

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