VirtualBox

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

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

Main: new method Medium::RefreshState() which refreshes medium state; make the ::state attribute return the state only without refreshing

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette