VirtualBox

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

Last change on this file since 25809 was 25809, checked in by vboxsync, 14 years ago

Main: adjust lock validation code to use IPRT lock validation, first steps (not active yet)

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

© 2023 Oracle
ContactPrivacy policyTerms of Use