VirtualBox

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

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

Fixed assumption that GetSnapshot by name would fail; previous broken code always returned the first snapshot in such cases.

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

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