VirtualBox

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

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

Enable nested paging by default for new VMs

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 344.5 KB
Line 
1/* $Id: MachineImpl.cpp 26043 2010-01-26 12:04:38Z 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 = true;
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 // we're calling host methods for getting DVD and floppy drives so lock host first
2987 AutoMultiWriteLock2 alock(mParent->host(), this COMMA_LOCKVAL_SRC_POS);
2988
2989 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
2990 aControllerName,
2991 aControllerPort,
2992 aDevice);
2993 if (pAttach.isNull())
2994 return setError(VBOX_E_OBJECT_NOT_FOUND,
2995 tr("No drive attached to device slot %d on port %d of controller '%ls'"),
2996 aDevice, aControllerPort, aControllerName);
2997
2998 /* Remember previously mounted medium. The medium before taking the
2999 * backup is not necessarily the same thing. */
3000 ComObjPtr<Medium> oldmedium;
3001 oldmedium = pAttach->getMedium();
3002
3003 Guid uuid(aId);
3004 ComObjPtr<Medium> medium;
3005 DeviceType_T mediumType = pAttach->getType();
3006 switch (mediumType)
3007 {
3008 case DeviceType_DVD:
3009 if (!uuid.isEmpty())
3010 {
3011 /* find a DVD by host device UUID */
3012 SafeIfaceArray<IMedium> drivevec;
3013 rc = mParent->host()->COMGETTER(DVDDrives)(ComSafeArrayAsOutParam(drivevec));
3014 if (SUCCEEDED(rc))
3015 {
3016 for (size_t i = 0; i < drivevec.size(); ++i)
3017 {
3018 /// @todo eliminate this conversion
3019 ComObjPtr<Medium> med = (Medium *)drivevec[i];
3020 if (uuid == med->getId())
3021 {
3022 medium = med;
3023 break;
3024 }
3025 }
3026 }
3027 /* find a DVD by UUID */
3028 if (medium.isNull())
3029 rc = mParent->findDVDImage(&uuid, NULL, true /* aDoSetError */, &medium);
3030 }
3031 if (FAILED(rc)) return rc;
3032 break;
3033 case DeviceType_Floppy:
3034 if (!uuid.isEmpty())
3035 {
3036 /* find a Floppy by host device UUID */
3037 SafeIfaceArray<IMedium> drivevec;
3038 rc = mParent->host()->COMGETTER(FloppyDrives)(ComSafeArrayAsOutParam(drivevec));
3039 if (SUCCEEDED(rc))
3040 {
3041 for (size_t i = 0; i < drivevec.size(); ++i)
3042 {
3043 /// @todo eliminate this conversion
3044 ComObjPtr<Medium> med = (Medium *)drivevec[i];
3045 if (uuid == med->getId())
3046 {
3047 medium = med;
3048 break;
3049 }
3050 }
3051 }
3052 /* find a Floppy by UUID */
3053 if (medium.isNull())
3054 rc = mParent->findFloppyImage(&uuid, NULL, true /* aDoSetError */, &medium);
3055 }
3056 if (FAILED(rc)) return rc;
3057 break;
3058 default:
3059 return setError(VBOX_E_INVALID_OBJECT_STATE,
3060 tr("Cannot change medium attached to device slot %d on port %d of controller '%ls'"),
3061 aDevice, aControllerPort, aControllerName);
3062 }
3063
3064 if (SUCCEEDED(rc))
3065 {
3066
3067 mMediaData.backup();
3068 /* The backup operation makes the pAttach reference point to the
3069 * old settings. Re-get the correct reference. */
3070 pAttach = findAttachment(mMediaData->mAttachments,
3071 aControllerName,
3072 aControllerPort,
3073 aDevice);
3074 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
3075 /* For non-hard disk media, detach straight away. */
3076 if (mediumType != DeviceType_HardDisk && !oldmedium.isNull())
3077 oldmedium->detachFrom(mData->mUuid);
3078 if (!medium.isNull())
3079 medium->attachTo(mData->mUuid);
3080 pAttach->updateMedium(medium, false /* aImplicit */);
3081 }
3082
3083 alock.leave();
3084 rc = onMediumChange(pAttach, aForce);
3085 alock.enter();
3086
3087 /* On error roll back this change only. */
3088 if (FAILED(rc))
3089 {
3090 if (!medium.isNull())
3091 medium->detachFrom(mData->mUuid);
3092 pAttach = findAttachment(mMediaData->mAttachments,
3093 aControllerName,
3094 aControllerPort,
3095 aDevice);
3096 /* If the attachment is gone in the mean time, bail out. */
3097 if (pAttach.isNull())
3098 return rc;
3099 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
3100 /* For non-hard disk media, re-attach straight away. */
3101 if (mediumType != DeviceType_HardDisk && !oldmedium.isNull())
3102 oldmedium->attachTo(mData->mUuid);
3103 pAttach->updateMedium(oldmedium, false /* aImplicit */);
3104 }
3105
3106 return rc;
3107}
3108
3109STDMETHODIMP Machine::GetMedium(IN_BSTR aControllerName,
3110 LONG aControllerPort,
3111 LONG aDevice,
3112 IMedium **aMedium)
3113{
3114 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld\n",
3115 aControllerName, aControllerPort, aDevice));
3116
3117 CheckComArgNotNull(aControllerName);
3118 CheckComArgOutPointerValid(aMedium);
3119
3120 AutoCaller autoCaller(this);
3121 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3122
3123 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3124
3125 *aMedium = NULL;
3126
3127 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
3128 aControllerName,
3129 aControllerPort,
3130 aDevice);
3131 if (pAttach.isNull())
3132 return setError(VBOX_E_OBJECT_NOT_FOUND,
3133 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
3134 aDevice, aControllerPort, aControllerName);
3135
3136 pAttach->getMedium().queryInterfaceTo(aMedium);
3137
3138 return S_OK;
3139}
3140
3141STDMETHODIMP Machine::GetSerialPort (ULONG slot, ISerialPort **port)
3142{
3143 CheckComArgOutPointerValid(port);
3144 CheckComArgExpr (slot, slot < RT_ELEMENTS (mSerialPorts));
3145
3146 AutoCaller autoCaller(this);
3147 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3148
3149 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3150
3151 mSerialPorts [slot].queryInterfaceTo(port);
3152
3153 return S_OK;
3154}
3155
3156STDMETHODIMP Machine::GetParallelPort (ULONG slot, IParallelPort **port)
3157{
3158 CheckComArgOutPointerValid(port);
3159 CheckComArgExpr (slot, slot < RT_ELEMENTS (mParallelPorts));
3160
3161 AutoCaller autoCaller(this);
3162 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3163
3164 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3165
3166 mParallelPorts [slot].queryInterfaceTo(port);
3167
3168 return S_OK;
3169}
3170
3171STDMETHODIMP Machine::GetNetworkAdapter (ULONG slot, INetworkAdapter **adapter)
3172{
3173 CheckComArgOutPointerValid(adapter);
3174 CheckComArgExpr (slot, slot < RT_ELEMENTS (mNetworkAdapters));
3175
3176 AutoCaller autoCaller(this);
3177 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3178
3179 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3180
3181 mNetworkAdapters[slot].queryInterfaceTo(adapter);
3182
3183 return S_OK;
3184}
3185
3186STDMETHODIMP Machine::GetExtraDataKeys(ComSafeArrayOut(BSTR, aKeys))
3187{
3188 if (ComSafeArrayOutIsNull(aKeys))
3189 return E_POINTER;
3190
3191 AutoCaller autoCaller(this);
3192 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3193
3194 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3195
3196 com::SafeArray<BSTR> saKeys(mData->m_pMachineConfigFile->mapExtraDataItems.size());
3197 int i = 0;
3198 for (settings::ExtraDataItemsMap::const_iterator it = mData->m_pMachineConfigFile->mapExtraDataItems.begin();
3199 it != mData->m_pMachineConfigFile->mapExtraDataItems.end();
3200 ++it, ++i)
3201 {
3202 const Utf8Str &strKey = it->first;
3203 strKey.cloneTo(&saKeys[i]);
3204 }
3205 saKeys.detachTo(ComSafeArrayOutArg(aKeys));
3206
3207 return S_OK;
3208 }
3209
3210 /**
3211 * @note Locks this object for reading.
3212 */
3213STDMETHODIMP Machine::GetExtraData(IN_BSTR aKey,
3214 BSTR *aValue)
3215{
3216 CheckComArgNotNull(aKey);
3217 CheckComArgOutPointerValid(aValue);
3218
3219 AutoCaller autoCaller(this);
3220 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3221
3222 /* start with nothing found */
3223 Bstr bstrResult("");
3224
3225 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3226
3227 settings::ExtraDataItemsMap::const_iterator it = mData->m_pMachineConfigFile->mapExtraDataItems.find(Utf8Str(aKey));
3228 if (it != mData->m_pMachineConfigFile->mapExtraDataItems.end())
3229 // found:
3230 bstrResult = it->second; // source is a Utf8Str
3231
3232 /* return the result to caller (may be empty) */
3233 bstrResult.cloneTo(aValue);
3234
3235 return S_OK;
3236}
3237
3238 /**
3239 * @note Locks mParent for writing + this object for writing.
3240 */
3241STDMETHODIMP Machine::SetExtraData(IN_BSTR aKey, IN_BSTR aValue)
3242{
3243 CheckComArgNotNull(aKey);
3244
3245 AutoCaller autoCaller(this);
3246 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3247
3248 Utf8Str strKey(aKey);
3249 Utf8Str strValue(aValue);
3250 Utf8Str strOldValue; // empty
3251
3252 // locking note: we only hold the read lock briefly to look up the old value,
3253 // then release it and call the onExtraCanChange callbacks. There is a small
3254 // chance of a race insofar as the callback might be called twice if two callers
3255 // change the same key at the same time, but that's a much better solution
3256 // than the deadlock we had here before. The actual changing of the extradata
3257 // is then performed under the write lock and race-free.
3258
3259 // look up the old value first; if nothing's changed then we need not do anything
3260 {
3261 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS); // hold read lock only while looking up
3262 settings::ExtraDataItemsMap::const_iterator it = mData->m_pMachineConfigFile->mapExtraDataItems.find(strKey);
3263 if (it != mData->m_pMachineConfigFile->mapExtraDataItems.end())
3264 strOldValue = it->second;
3265 }
3266
3267 bool fChanged;
3268 if ((fChanged = (strOldValue != strValue)))
3269 {
3270 // ask for permission from all listeners outside the locks;
3271 // onExtraDataCanChange() only briefly requests the VirtualBox
3272 // lock to copy the list of callbacks to invoke
3273 Bstr error;
3274 Bstr bstrValue;
3275 if (aValue)
3276 bstrValue = aValue;
3277 else
3278 bstrValue = (const char *)"";
3279
3280 if (!mParent->onExtraDataCanChange(mData->mUuid, aKey, bstrValue, error))
3281 {
3282 const char *sep = error.isEmpty() ? "" : ": ";
3283 CBSTR err = error.isNull() ? (CBSTR) L"" : error.raw();
3284 LogWarningFunc(("Someone vetoed! Change refused%s%ls\n",
3285 sep, err));
3286 return setError(E_ACCESSDENIED,
3287 tr("Could not set extra data because someone refused the requested change of '%ls' to '%ls'%s%ls"),
3288 aKey,
3289 bstrValue.raw(),
3290 sep,
3291 err);
3292 }
3293
3294 // data is changing and change not vetoed: then write it out under the locks
3295
3296 // saveSettings() needs VirtualBox write lock
3297 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
3298
3299 if (getClassID() == clsidSnapshotMachine)
3300 {
3301 HRESULT rc = checkStateDependency(MutableStateDep);
3302 if (FAILED(rc)) return rc;
3303 }
3304
3305 if (strValue.isEmpty())
3306 mData->m_pMachineConfigFile->mapExtraDataItems.erase(strKey);
3307 else
3308 mData->m_pMachineConfigFile->mapExtraDataItems[strKey] = strValue;
3309 // creates a new key if needed
3310
3311 /* save settings on success */
3312 HRESULT rc = saveSettings();
3313 if (FAILED(rc)) return rc;
3314 }
3315
3316 // fire notification outside the lock
3317 if (fChanged)
3318 mParent->onExtraDataChange(mData->mUuid, aKey, aValue);
3319
3320 return S_OK;
3321}
3322
3323STDMETHODIMP Machine::SaveSettings()
3324{
3325 AutoCaller autoCaller(this);
3326 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3327
3328 /* saveSettings() needs mParent lock */
3329 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
3330
3331 /* when there was auto-conversion, we want to save the file even if
3332 * the VM is saved */
3333 HRESULT rc = checkStateDependency(MutableStateDep);
3334 if (FAILED(rc)) return rc;
3335
3336 /* the settings file path may never be null */
3337 ComAssertRet(!mData->m_strConfigFileFull.isEmpty(), E_FAIL);
3338
3339 /* save all VM data excluding snapshots */
3340 return saveSettings();
3341}
3342
3343STDMETHODIMP Machine::DiscardSettings()
3344{
3345 AutoCaller autoCaller(this);
3346 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3347
3348 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3349
3350 HRESULT rc = checkStateDependency(MutableStateDep);
3351 if (FAILED(rc)) return rc;
3352
3353 /*
3354 * during this rollback, the session will be notified if data has
3355 * been actually changed
3356 */
3357 rollback (true /* aNotify */);
3358
3359 return S_OK;
3360}
3361
3362STDMETHODIMP Machine::DeleteSettings()
3363{
3364 AutoCaller autoCaller(this);
3365 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3366
3367 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3368
3369 HRESULT rc = checkStateDependency(MutableStateDep);
3370 if (FAILED(rc)) return rc;
3371
3372 if (mData->mRegistered)
3373 return setError(VBOX_E_INVALID_VM_STATE,
3374 tr("Cannot delete settings of a registered machine"));
3375
3376 /* delete the settings only when the file actually exists */
3377 if (mData->m_pMachineConfigFile->fileExists())
3378 {
3379 int vrc = RTFileDelete(mData->m_strConfigFileFull.c_str());
3380 if (RT_FAILURE(vrc))
3381 return setError(VBOX_E_IPRT_ERROR,
3382 tr("Could not delete the settings file '%s' (%Rrc)"),
3383 mData->m_strConfigFileFull.raw(),
3384 vrc);
3385
3386 /* delete the Logs folder, nothing important should be left
3387 * there (we don't check for errors because the user might have
3388 * some private files there that we don't want to delete) */
3389 Utf8Str logFolder;
3390 getLogFolder(logFolder);
3391 Assert(logFolder.length());
3392 if (RTDirExists(logFolder.c_str()))
3393 {
3394 /* Delete all VBox.log[.N] files from the Logs folder
3395 * (this must be in sync with the rotation logic in
3396 * Console::powerUpThread()). Also, delete the VBox.png[.N]
3397 * files that may have been created by the GUI. */
3398 Utf8Str log = Utf8StrFmt("%s/VBox.log", logFolder.raw());
3399 RTFileDelete(log.c_str());
3400 log = Utf8StrFmt("%s/VBox.png", logFolder.raw());
3401 RTFileDelete(log.c_str());
3402 for (int i = 3; i >= 0; i--)
3403 {
3404 log = Utf8StrFmt("%s/VBox.log.%d", logFolder.raw(), i);
3405 RTFileDelete(log.c_str());
3406 log = Utf8StrFmt("%s/VBox.png.%d", logFolder.raw(), i);
3407 RTFileDelete(log.c_str());
3408 }
3409
3410 RTDirRemove(logFolder.c_str());
3411 }
3412
3413 /* delete the Snapshots folder, nothing important should be left
3414 * there (we don't check for errors because the user might have
3415 * some private files there that we don't want to delete) */
3416 Utf8Str snapshotFolder(mUserData->mSnapshotFolderFull);
3417 Assert(snapshotFolder.length());
3418 if (RTDirExists(snapshotFolder.c_str()))
3419 RTDirRemove(snapshotFolder.c_str());
3420
3421 /* delete the directory that contains the settings file, but only
3422 * if it matches the VM name (i.e. a structure created by default in
3423 * prepareSaveSettings()) */
3424 {
3425 Utf8Str settingsDir;
3426 if (isInOwnDir(&settingsDir))
3427 RTDirRemove(settingsDir.c_str());
3428 }
3429 }
3430
3431 return S_OK;
3432}
3433
3434STDMETHODIMP Machine::GetSnapshot (IN_BSTR aId, ISnapshot **aSnapshot)
3435{
3436 CheckComArgOutPointerValid(aSnapshot);
3437
3438 AutoCaller autoCaller(this);
3439 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3440
3441 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3442
3443 Guid uuid(aId);
3444 /* Todo: fix this properly by perhaps introducing an isValid method for the Guid class */
3445 if ( aId
3446 && uuid.isEmpty())
3447 {
3448 RTUUID uuidTemp;
3449 /* Either it's a null UUID or the conversion failed. (null uuid has a special meaning in findSnapshot) */
3450 if (RT_FAILURE(RTUuidFromUtf16(&uuidTemp, aId)))
3451 return setError(E_FAIL,
3452 tr("Could not find a snapshot with UUID {%ls}"),
3453 aId);
3454 }
3455
3456 ComObjPtr<Snapshot> snapshot;
3457
3458 HRESULT rc = findSnapshot(uuid, snapshot, true /* aSetError */);
3459 snapshot.queryInterfaceTo(aSnapshot);
3460
3461 return rc;
3462}
3463
3464STDMETHODIMP Machine::FindSnapshot (IN_BSTR aName, ISnapshot **aSnapshot)
3465{
3466 CheckComArgNotNull (aName);
3467 CheckComArgOutPointerValid(aSnapshot);
3468
3469 AutoCaller autoCaller(this);
3470 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3471
3472 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3473
3474 ComObjPtr<Snapshot> snapshot;
3475
3476 HRESULT rc = findSnapshot(aName, snapshot, true /* aSetError */);
3477 snapshot.queryInterfaceTo(aSnapshot);
3478
3479 return rc;
3480}
3481
3482STDMETHODIMP Machine::SetCurrentSnapshot (IN_BSTR /* aId */)
3483{
3484 /// @todo (dmik) don't forget to set
3485 // mData->mCurrentStateModified to FALSE
3486
3487 return setError (E_NOTIMPL, "Not implemented");
3488}
3489
3490STDMETHODIMP Machine::CreateSharedFolder (IN_BSTR aName, IN_BSTR aHostPath, BOOL aWritable)
3491{
3492 CheckComArgNotNull(aName);
3493 CheckComArgNotNull(aHostPath);
3494
3495 AutoCaller autoCaller(this);
3496 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3497
3498 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3499
3500 HRESULT rc = checkStateDependency(MutableStateDep);
3501 if (FAILED(rc)) return rc;
3502
3503 ComObjPtr<SharedFolder> sharedFolder;
3504 rc = findSharedFolder (aName, sharedFolder, false /* aSetError */);
3505 if (SUCCEEDED(rc))
3506 return setError(VBOX_E_OBJECT_IN_USE,
3507 tr("Shared folder named '%ls' already exists"),
3508 aName);
3509
3510 sharedFolder.createObject();
3511 rc = sharedFolder->init(getMachine(), aName, aHostPath, aWritable);
3512 if (FAILED(rc)) return rc;
3513
3514 mHWData.backup();
3515 mHWData->mSharedFolders.push_back (sharedFolder);
3516
3517 /* inform the direct session if any */
3518 alock.leave();
3519 onSharedFolderChange();
3520
3521 return S_OK;
3522}
3523
3524STDMETHODIMP Machine::RemoveSharedFolder (IN_BSTR aName)
3525{
3526 CheckComArgNotNull (aName);
3527
3528 AutoCaller autoCaller(this);
3529 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3530
3531 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3532
3533 HRESULT rc = checkStateDependency(MutableStateDep);
3534 if (FAILED(rc)) return rc;
3535
3536 ComObjPtr<SharedFolder> sharedFolder;
3537 rc = findSharedFolder (aName, sharedFolder, true /* aSetError */);
3538 if (FAILED(rc)) return rc;
3539
3540 mHWData.backup();
3541 mHWData->mSharedFolders.remove (sharedFolder);
3542
3543 /* inform the direct session if any */
3544 alock.leave();
3545 onSharedFolderChange();
3546
3547 return S_OK;
3548}
3549
3550STDMETHODIMP Machine::CanShowConsoleWindow (BOOL *aCanShow)
3551{
3552 CheckComArgOutPointerValid(aCanShow);
3553
3554 /* start with No */
3555 *aCanShow = FALSE;
3556
3557 AutoCaller autoCaller(this);
3558 AssertComRCReturnRC(autoCaller.rc());
3559
3560 ComPtr<IInternalSessionControl> directControl;
3561 {
3562 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3563
3564 if (mData->mSession.mState != SessionState_Open)
3565 return setError(VBOX_E_INVALID_VM_STATE,
3566 tr("Machine session is not open (session state: %s)"),
3567 Global::stringifySessionState(mData->mSession.mState));
3568
3569 directControl = mData->mSession.mDirectControl;
3570 }
3571
3572 /* ignore calls made after #OnSessionEnd() is called */
3573 if (!directControl)
3574 return S_OK;
3575
3576 ULONG64 dummy;
3577 return directControl->OnShowWindow (TRUE /* aCheck */, aCanShow, &dummy);
3578}
3579
3580STDMETHODIMP Machine::ShowConsoleWindow (ULONG64 *aWinId)
3581{
3582 CheckComArgOutPointerValid(aWinId);
3583
3584 AutoCaller autoCaller(this);
3585 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
3586
3587 ComPtr<IInternalSessionControl> directControl;
3588 {
3589 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3590
3591 if (mData->mSession.mState != SessionState_Open)
3592 return setError(E_FAIL,
3593 tr("Machine session is not open (session state: %s)"),
3594 Global::stringifySessionState(mData->mSession.mState));
3595
3596 directControl = mData->mSession.mDirectControl;
3597 }
3598
3599 /* ignore calls made after #OnSessionEnd() is called */
3600 if (!directControl)
3601 return S_OK;
3602
3603 BOOL dummy;
3604 return directControl->OnShowWindow (FALSE /* aCheck */, &dummy, aWinId);
3605}
3606
3607STDMETHODIMP Machine::GetGuestProperty(IN_BSTR aName,
3608 BSTR *aValue,
3609 ULONG64 *aTimestamp,
3610 BSTR *aFlags)
3611{
3612#if !defined (VBOX_WITH_GUEST_PROPS)
3613 ReturnComNotImplemented();
3614#else
3615 CheckComArgNotNull(aName);
3616 CheckComArgOutPointerValid(aValue);
3617 CheckComArgOutPointerValid(aTimestamp);
3618 CheckComArgOutPointerValid(aFlags);
3619
3620 AutoCaller autoCaller(this);
3621 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3622
3623 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3624
3625 using namespace guestProp;
3626 HRESULT rc = E_FAIL;
3627
3628 Utf8Str strName(aName);
3629
3630 if (!mHWData->mPropertyServiceActive)
3631 {
3632 bool found = false;
3633 for (HWData::GuestPropertyList::const_iterator it = mHWData->mGuestProperties.begin();
3634 (it != mHWData->mGuestProperties.end()) && !found;
3635 ++it)
3636 {
3637 if (it->strName == strName)
3638 {
3639 char szFlags[MAX_FLAGS_LEN + 1];
3640 it->strValue.cloneTo(aValue);
3641 *aTimestamp = it->mTimestamp;
3642 writeFlags(it->mFlags, szFlags);
3643 Bstr(szFlags).cloneTo(aFlags);
3644 found = true;
3645 }
3646 }
3647 rc = S_OK;
3648 }
3649 else
3650 {
3651 ComPtr<IInternalSessionControl> directControl =
3652 mData->mSession.mDirectControl;
3653
3654 /* just be on the safe side when calling another process */
3655 alock.release();
3656
3657 /* fail if we were called after #OnSessionEnd() is called. This is a
3658 * silly race condition. */
3659
3660 if (!directControl)
3661 rc = E_FAIL;
3662 else
3663 rc = directControl->AccessGuestProperty (aName, NULL, NULL,
3664 false /* isSetter */,
3665 aValue, aTimestamp, aFlags);
3666 }
3667 return rc;
3668#endif /* else !defined (VBOX_WITH_GUEST_PROPS) */
3669}
3670
3671STDMETHODIMP Machine::GetGuestPropertyValue (IN_BSTR aName, BSTR *aValue)
3672{
3673 ULONG64 dummyTimestamp;
3674 BSTR dummyFlags;
3675 return GetGuestProperty (aName, aValue, &dummyTimestamp, &dummyFlags);
3676}
3677
3678STDMETHODIMP Machine::GetGuestPropertyTimestamp (IN_BSTR aName, ULONG64 *aTimestamp)
3679{
3680 BSTR dummyValue;
3681 BSTR dummyFlags;
3682 return GetGuestProperty (aName, &dummyValue, aTimestamp, &dummyFlags);
3683}
3684
3685STDMETHODIMP Machine::SetGuestProperty(IN_BSTR aName,
3686 IN_BSTR aValue,
3687 IN_BSTR aFlags)
3688{
3689#if !defined (VBOX_WITH_GUEST_PROPS)
3690 ReturnComNotImplemented();
3691#else
3692 using namespace guestProp;
3693
3694 CheckComArgNotNull(aName);
3695 CheckComArgNotNull(aValue);
3696 if ((aFlags != NULL) && !VALID_PTR (aFlags))
3697 return E_INVALIDARG;
3698
3699 HRESULT rc = S_OK;
3700
3701 try
3702 {
3703 Utf8Str utf8Name(aName);
3704 Utf8Str utf8Flags(aFlags);
3705
3706 AutoCaller autoCaller(this);
3707 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3708
3709 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3710
3711 rc = checkStateDependency(MutableStateDep);
3712 if (FAILED(rc)) return rc;
3713
3714 rc = S_OK;
3715 uint32_t fFlags = NILFLAG;
3716 if ( (aFlags != NULL)
3717 && RT_FAILURE(validateFlags (utf8Flags.raw(), &fFlags))
3718 )
3719 return setError(E_INVALIDARG,
3720 tr("Invalid flag values: '%ls'"),
3721 aFlags);
3722
3723 if (!mHWData->mPropertyServiceActive)
3724 {
3725 bool found = false;
3726 HWData::GuestProperty property;
3727 property.mFlags = NILFLAG;
3728
3729 /** @todo r=bird: see efficiency rant in PushGuestProperty. (Yeah, I know,
3730 * this is simple and do an OK job atm.) */
3731 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
3732 it != mHWData->mGuestProperties.end();
3733 ++it)
3734 if (it->strName == utf8Name)
3735 {
3736 property = *it;
3737 if (it->mFlags & (RDONLYHOST))
3738 rc = setError(E_ACCESSDENIED,
3739 tr("The property '%ls' cannot be changed by the host"),
3740 aName);
3741 else
3742 {
3743 mHWData.backup();
3744 /* The backup() operation invalidates our iterator, so
3745 * get a new one. */
3746 for (it = mHWData->mGuestProperties.begin();
3747 it->strName != utf8Name;
3748 ++it)
3749 ;
3750 mHWData->mGuestProperties.erase (it);
3751 }
3752 found = true;
3753 break;
3754 }
3755 if (found && SUCCEEDED(rc))
3756 {
3757 if (*aValue)
3758 {
3759 RTTIMESPEC time;
3760 property.strValue = aValue;
3761 property.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
3762 if (aFlags != NULL)
3763 property.mFlags = fFlags;
3764 mHWData->mGuestProperties.push_back (property);
3765 }
3766 }
3767 else if (SUCCEEDED(rc) && *aValue)
3768 {
3769 RTTIMESPEC time;
3770 mHWData.backup();
3771 property.strName = aName;
3772 property.strValue = aValue;
3773 property.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
3774 property.mFlags = fFlags;
3775 mHWData->mGuestProperties.push_back (property);
3776 }
3777 if ( SUCCEEDED(rc)
3778 && ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
3779 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.raw(), RTSTR_MAX,
3780 utf8Name.raw(), RTSTR_MAX, NULL) )
3781 )
3782 {
3783 /** @todo r=bird: Why aren't we leaving the lock here? The
3784 * same code in PushGuestProperty does... */
3785 mParent->onGuestPropertyChange(mData->mUuid, aName, aValue, aFlags);
3786 }
3787 }
3788 else
3789 {
3790 ComPtr<IInternalSessionControl> directControl =
3791 mData->mSession.mDirectControl;
3792
3793 /* just be on the safe side when calling another process */
3794 alock.leave();
3795
3796 BSTR dummy = NULL;
3797 ULONG64 dummy64;
3798 if (!directControl)
3799 rc = E_FAIL;
3800 else
3801 rc = directControl->AccessGuestProperty(aName,
3802 *aValue ? aValue : NULL, /** @todo Fix when adding DeleteGuestProperty(), see defect. */
3803 aFlags,
3804 true /* isSetter */,
3805 &dummy, &dummy64, &dummy);
3806 }
3807 }
3808 catch (std::bad_alloc &)
3809 {
3810 rc = E_OUTOFMEMORY;
3811 }
3812
3813 return rc;
3814#endif /* else !defined (VBOX_WITH_GUEST_PROPS) */
3815}
3816
3817STDMETHODIMP Machine::SetGuestPropertyValue (IN_BSTR aName, IN_BSTR aValue)
3818{
3819 return SetGuestProperty (aName, aValue, NULL);
3820}
3821
3822STDMETHODIMP Machine::EnumerateGuestProperties(IN_BSTR aPatterns,
3823 ComSafeArrayOut(BSTR, aNames),
3824 ComSafeArrayOut(BSTR, aValues),
3825 ComSafeArrayOut(ULONG64, aTimestamps),
3826 ComSafeArrayOut(BSTR, aFlags))
3827{
3828#if !defined (VBOX_WITH_GUEST_PROPS)
3829 ReturnComNotImplemented();
3830#else
3831 if (!VALID_PTR (aPatterns) && (aPatterns != NULL))
3832 return E_POINTER;
3833
3834 CheckComArgOutSafeArrayPointerValid(aNames);
3835 CheckComArgOutSafeArrayPointerValid(aValues);
3836 CheckComArgOutSafeArrayPointerValid(aTimestamps);
3837 CheckComArgOutSafeArrayPointerValid(aFlags);
3838
3839 AutoCaller autoCaller(this);
3840 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3841
3842 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3843
3844 using namespace guestProp;
3845 HRESULT rc = E_FAIL;
3846
3847 Utf8Str strPatterns(aPatterns);
3848
3849 if (!mHWData->mPropertyServiceActive)
3850 {
3851
3852 /*
3853 * Look for matching patterns and build up a list.
3854 */
3855 HWData::GuestPropertyList propList;
3856 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
3857 it != mHWData->mGuestProperties.end();
3858 ++it)
3859 if ( strPatterns.isEmpty()
3860 || RTStrSimplePatternMultiMatch(strPatterns.raw(),
3861 RTSTR_MAX,
3862 it->strName.raw(),
3863 RTSTR_MAX, NULL)
3864 )
3865 propList.push_back(*it);
3866
3867 /*
3868 * And build up the arrays for returning the property information.
3869 */
3870 size_t cEntries = propList.size();
3871 SafeArray<BSTR> names (cEntries);
3872 SafeArray<BSTR> values (cEntries);
3873 SafeArray<ULONG64> timestamps (cEntries);
3874 SafeArray<BSTR> flags (cEntries);
3875 size_t iProp = 0;
3876 for (HWData::GuestPropertyList::iterator it = propList.begin();
3877 it != propList.end();
3878 ++it)
3879 {
3880 char szFlags[MAX_FLAGS_LEN + 1];
3881 it->strName.cloneTo(&names[iProp]);
3882 it->strValue.cloneTo(&values[iProp]);
3883 timestamps[iProp] = it->mTimestamp;
3884 writeFlags(it->mFlags, szFlags);
3885 Bstr(szFlags).cloneTo(&flags[iProp]);
3886 ++iProp;
3887 }
3888 names.detachTo(ComSafeArrayOutArg(aNames));
3889 values.detachTo(ComSafeArrayOutArg(aValues));
3890 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
3891 flags.detachTo(ComSafeArrayOutArg(aFlags));
3892 rc = S_OK;
3893 }
3894 else
3895 {
3896 ComPtr<IInternalSessionControl> directControl = mData->mSession.mDirectControl;
3897
3898 /* just be on the safe side when calling another process */
3899 alock.release();
3900
3901 if (!directControl)
3902 rc = E_FAIL;
3903 else
3904 rc = directControl->EnumerateGuestProperties(aPatterns,
3905 ComSafeArrayOutArg(aNames),
3906 ComSafeArrayOutArg(aValues),
3907 ComSafeArrayOutArg(aTimestamps),
3908 ComSafeArrayOutArg(aFlags));
3909 }
3910 return rc;
3911#endif /* else !defined (VBOX_WITH_GUEST_PROPS) */
3912}
3913
3914STDMETHODIMP Machine::GetMediumAttachmentsOfController(IN_BSTR aName,
3915 ComSafeArrayOut(IMediumAttachment*, aAttachments))
3916{
3917 MediaData::AttachmentList atts;
3918
3919 HRESULT rc = getMediumAttachmentsOfController(aName, atts);
3920 if (FAILED(rc)) return rc;
3921
3922 SafeIfaceArray<IMediumAttachment> attachments(atts);
3923 attachments.detachTo(ComSafeArrayOutArg(aAttachments));
3924
3925 return S_OK;
3926}
3927
3928STDMETHODIMP Machine::GetMediumAttachment(IN_BSTR aControllerName,
3929 LONG aControllerPort,
3930 LONG aDevice,
3931 IMediumAttachment **aAttachment)
3932{
3933 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d\n",
3934 aControllerName, aControllerPort, aDevice));
3935
3936 CheckComArgNotNull(aControllerName);
3937 CheckComArgOutPointerValid(aAttachment);
3938
3939 AutoCaller autoCaller(this);
3940 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3941
3942 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3943
3944 *aAttachment = NULL;
3945
3946 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
3947 aControllerName,
3948 aControllerPort,
3949 aDevice);
3950 if (pAttach.isNull())
3951 return setError(VBOX_E_OBJECT_NOT_FOUND,
3952 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
3953 aDevice, aControllerPort, aControllerName);
3954
3955 pAttach.queryInterfaceTo(aAttachment);
3956
3957 return S_OK;
3958}
3959
3960STDMETHODIMP Machine::AddStorageController(IN_BSTR aName,
3961 StorageBus_T aConnectionType,
3962 IStorageController **controller)
3963{
3964 CheckComArgStrNotEmptyOrNull(aName);
3965
3966 if ( (aConnectionType <= StorageBus_Null)
3967 || (aConnectionType > StorageBus_SAS))
3968 return setError (E_INVALIDARG,
3969 tr ("Invalid connection type: %d"),
3970 aConnectionType);
3971
3972 AutoCaller autoCaller(this);
3973 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3974
3975 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3976
3977 HRESULT rc = checkStateDependency(MutableStateDep);
3978 if (FAILED(rc)) return rc;
3979
3980 /* try to find one with the name first. */
3981 ComObjPtr<StorageController> ctrl;
3982
3983 rc = getStorageControllerByName (aName, ctrl, false /* aSetError */);
3984 if (SUCCEEDED(rc))
3985 return setError (VBOX_E_OBJECT_IN_USE,
3986 tr ("Storage controller named '%ls' already exists"), aName);
3987
3988 ctrl.createObject();
3989
3990 /* get a new instance number for the storage controller */
3991 ULONG ulInstance = 0;
3992 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
3993 it != mStorageControllers->end();
3994 ++it)
3995 {
3996 if ((*it)->getStorageBus() == aConnectionType)
3997 {
3998 ULONG ulCurInst = (*it)->getInstance();
3999
4000 if (ulCurInst >= ulInstance)
4001 ulInstance = ulCurInst + 1;
4002 }
4003 }
4004
4005 rc = ctrl->init(this, aName, aConnectionType, ulInstance);
4006 if (FAILED(rc)) return rc;
4007
4008 mStorageControllers.backup();
4009 mStorageControllers->push_back (ctrl);
4010
4011 ctrl.queryInterfaceTo(controller);
4012
4013 /* inform the direct session if any */
4014 alock.leave();
4015 onStorageControllerChange();
4016
4017 return S_OK;
4018}
4019
4020STDMETHODIMP Machine::GetStorageControllerByName(IN_BSTR aName,
4021 IStorageController **aStorageController)
4022{
4023 CheckComArgStrNotEmptyOrNull(aName);
4024
4025 AutoCaller autoCaller(this);
4026 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4027
4028 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4029
4030 ComObjPtr<StorageController> ctrl;
4031
4032 HRESULT rc = getStorageControllerByName (aName, ctrl, true /* aSetError */);
4033 if (SUCCEEDED(rc))
4034 ctrl.queryInterfaceTo(aStorageController);
4035
4036 return rc;
4037}
4038
4039STDMETHODIMP Machine::GetStorageControllerByInstance(ULONG aInstance,
4040 IStorageController **aStorageController)
4041{
4042 AutoCaller autoCaller(this);
4043 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4044
4045 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4046
4047 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
4048 it != mStorageControllers->end();
4049 ++it)
4050 {
4051 if ((*it)->getInstance() == aInstance)
4052 {
4053 (*it).queryInterfaceTo(aStorageController);
4054 return S_OK;
4055 }
4056 }
4057
4058 return setError(VBOX_E_OBJECT_NOT_FOUND,
4059 tr("Could not find a storage controller with instance number '%lu'"),
4060 aInstance);
4061}
4062
4063STDMETHODIMP Machine::RemoveStorageController(IN_BSTR aName)
4064{
4065 CheckComArgStrNotEmptyOrNull(aName);
4066
4067 AutoCaller autoCaller(this);
4068 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4069
4070 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4071
4072 HRESULT rc = checkStateDependency(MutableStateDep);
4073 if (FAILED(rc)) return rc;
4074
4075 ComObjPtr<StorageController> ctrl;
4076 rc = getStorageControllerByName (aName, ctrl, true /* aSetError */);
4077 if (FAILED(rc)) return rc;
4078
4079 /* We can remove the controller only if there is no device attached. */
4080 /* check if the device slot is already busy */
4081 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
4082 it != mMediaData->mAttachments.end();
4083 ++it)
4084 {
4085 if ((*it)->getControllerName() == aName)
4086 return setError(VBOX_E_OBJECT_IN_USE,
4087 tr("Storage controller named '%ls' has still devices attached"),
4088 aName);
4089 }
4090
4091 /* We can remove it now. */
4092 mStorageControllers.backup();
4093
4094 ctrl->unshare();
4095
4096 mStorageControllers->remove (ctrl);
4097
4098 /* inform the direct session if any */
4099 alock.leave();
4100 onStorageControllerChange();
4101
4102 return S_OK;
4103}
4104
4105/* @todo where is the right place for this? */
4106#define sSSMDisplayScreenshotVer 0x00010001
4107
4108static int readSavedDisplayScreenshot(Utf8Str *pStateFilePath, uint32_t u32Type, uint8_t **ppu8Data, uint32_t *pcbData, uint32_t *pu32Width, uint32_t *pu32Height)
4109{
4110 LogFlowFunc(("u32Type = %d [%s]\n", u32Type, pStateFilePath->raw()));
4111
4112 /* @todo cache read data */
4113 if (pStateFilePath->isEmpty())
4114 {
4115 /* No saved state data. */
4116 return VERR_NOT_SUPPORTED;
4117 }
4118
4119 uint8_t *pu8Data = NULL;
4120 uint32_t cbData = 0;
4121 uint32_t u32Width = 0;
4122 uint32_t u32Height = 0;
4123
4124 PSSMHANDLE pSSM;
4125 int rc = SSMR3Open(pStateFilePath->raw(), 0 /*fFlags*/, &pSSM);
4126 if (RT_SUCCESS(rc))
4127 {
4128 uint32_t uVersion;
4129 rc = SSMR3Seek(pSSM, "DisplayScreenshot", 1100 /*iInstance*/, &uVersion);
4130 if (RT_SUCCESS(rc))
4131 {
4132 if (uVersion == sSSMDisplayScreenshotVer)
4133 {
4134 uint32_t cBlocks;
4135 rc = SSMR3GetU32(pSSM, &cBlocks);
4136 AssertRCReturn(rc, rc);
4137
4138 for (uint32_t i = 0; i < cBlocks; i++)
4139 {
4140 uint32_t cbBlock;
4141 rc = SSMR3GetU32(pSSM, &cbBlock);
4142 AssertRCBreak(rc);
4143
4144 uint32_t typeOfBlock;
4145 rc = SSMR3GetU32(pSSM, &typeOfBlock);
4146 AssertRCBreak(rc);
4147
4148 LogFlowFunc(("[%d] type %d, size %d bytes\n", i, typeOfBlock, cbBlock));
4149
4150 if (typeOfBlock == u32Type)
4151 {
4152 if (cbBlock > 2 * sizeof (uint32_t))
4153 {
4154 cbData = cbBlock - 2 * sizeof (uint32_t);
4155 pu8Data = (uint8_t *)RTMemAlloc(cbData);
4156 if (pu8Data == NULL)
4157 {
4158 rc = VERR_NO_MEMORY;
4159 break;
4160 }
4161
4162 rc = SSMR3GetU32(pSSM, &u32Width);
4163 AssertRCBreak(rc);
4164 rc = SSMR3GetU32(pSSM, &u32Height);
4165 AssertRCBreak(rc);
4166 rc = SSMR3GetMem(pSSM, pu8Data, cbData);
4167 AssertRCBreak(rc);
4168 }
4169 else
4170 {
4171 /* No saved state data. */
4172 rc = VERR_NOT_SUPPORTED;
4173 }
4174
4175 break;
4176 }
4177 else
4178 {
4179 if (cbBlock != 0)
4180 {
4181 rc = SSMR3Skip(pSSM, cbBlock);
4182 AssertRCBreak(rc);
4183 }
4184 }
4185 }
4186 }
4187 else
4188 {
4189 rc = VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
4190 }
4191 }
4192
4193 SSMR3Close(pSSM);
4194 }
4195
4196 if (RT_SUCCESS(rc))
4197 {
4198 if (u32Type == 0 && cbData % 4 != 0)
4199 {
4200 /* Bitmap is 32bpp, so data is invalid. */
4201 rc = VERR_SSM_UNEXPECTED_DATA;
4202 }
4203 }
4204
4205 if (RT_SUCCESS(rc))
4206 {
4207 *ppu8Data = pu8Data;
4208 *pcbData = cbData;
4209 *pu32Width = u32Width;
4210 *pu32Height = u32Height;
4211 LogFlowFunc(("cbData %d, u32Width %d, u32Height %d\n", cbData, u32Width, u32Height));
4212 }
4213
4214 LogFlowFunc(("rc %Rrc\n", rc));
4215 return rc;
4216}
4217
4218static void freeSavedDisplayScreenshot(uint8_t *pu8Data)
4219{
4220 /* @todo not necessary when caching is implemented. */
4221 RTMemFree(pu8Data);
4222}
4223
4224STDMETHODIMP Machine::QuerySavedThumbnailSize(ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
4225{
4226 LogFlowThisFunc(("\n"));
4227
4228 CheckComArgNotNull(aSize);
4229 CheckComArgNotNull(aWidth);
4230 CheckComArgNotNull(aHeight);
4231
4232 AutoCaller autoCaller(this);
4233 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4234
4235 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4236
4237 uint8_t *pu8Data = NULL;
4238 uint32_t cbData = 0;
4239 uint32_t u32Width = 0;
4240 uint32_t u32Height = 0;
4241
4242 int vrc = readSavedDisplayScreenshot(&mSSData->mStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
4243
4244 if (RT_FAILURE(vrc))
4245 return setError (VBOX_E_IPRT_ERROR,
4246 tr("Saved screenshot data is not available (%Rrc)"), vrc);
4247
4248 *aSize = cbData;
4249 *aWidth = u32Width;
4250 *aHeight = u32Height;
4251
4252 freeSavedDisplayScreenshot(pu8Data);
4253
4254 return S_OK;
4255}
4256
4257STDMETHODIMP Machine::ReadSavedThumbnailToArray(BOOL aBGR, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
4258{
4259 LogFlowThisFunc(("\n"));
4260
4261 CheckComArgNotNull(aWidth);
4262 CheckComArgNotNull(aHeight);
4263 CheckComArgExpr(aData, !ComSafeArrayOutIsNull(aData));
4264
4265 AutoCaller autoCaller(this);
4266 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4267
4268 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4269
4270 uint8_t *pu8Data = NULL;
4271 uint32_t cbData = 0;
4272 uint32_t u32Width = 0;
4273 uint32_t u32Height = 0;
4274
4275 int vrc = readSavedDisplayScreenshot(&mSSData->mStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
4276
4277 if (RT_FAILURE(vrc))
4278 return setError (VBOX_E_IPRT_ERROR,
4279 tr("Saved screenshot data is not available (%Rrc)"), vrc);
4280
4281 *aWidth = u32Width;
4282 *aHeight = u32Height;
4283
4284 com::SafeArray<BYTE> bitmap(cbData);
4285 /* Convert pixels to format expected by the API caller. */
4286 if (aBGR)
4287 {
4288 /* [0] B, [1] G, [2] R, [3] A. */
4289 for (unsigned i = 0; i < cbData; i += 4)
4290 {
4291 bitmap[i] = pu8Data[i];
4292 bitmap[i + 1] = pu8Data[i + 1];
4293 bitmap[i + 2] = pu8Data[i + 2];
4294 bitmap[i + 3] = 0xff;
4295 }
4296 }
4297 else
4298 {
4299 /* [0] R, [1] G, [2] B, [3] A. */
4300 for (unsigned i = 0; i < cbData; i += 4)
4301 {
4302 bitmap[i] = pu8Data[i + 2];
4303 bitmap[i + 1] = pu8Data[i + 1];
4304 bitmap[i + 2] = pu8Data[i];
4305 bitmap[i + 3] = 0xff;
4306 }
4307 }
4308 bitmap.detachTo(ComSafeArrayOutArg(aData));
4309
4310 freeSavedDisplayScreenshot(pu8Data);
4311
4312 return S_OK;
4313}
4314
4315STDMETHODIMP Machine::QuerySavedScreenshotPNGSize(ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
4316{
4317 LogFlowThisFunc(("\n"));
4318
4319 CheckComArgNotNull(aSize);
4320 CheckComArgNotNull(aWidth);
4321 CheckComArgNotNull(aHeight);
4322
4323 AutoCaller autoCaller(this);
4324 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4325
4326 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4327
4328 uint8_t *pu8Data = NULL;
4329 uint32_t cbData = 0;
4330 uint32_t u32Width = 0;
4331 uint32_t u32Height = 0;
4332
4333 int vrc = readSavedDisplayScreenshot(&mSSData->mStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
4334
4335 if (RT_FAILURE(vrc))
4336 return setError (VBOX_E_IPRT_ERROR,
4337 tr("Saved screenshot data is not available (%Rrc)"), vrc);
4338
4339 *aSize = cbData;
4340 *aWidth = u32Width;
4341 *aHeight = u32Height;
4342
4343 freeSavedDisplayScreenshot(pu8Data);
4344
4345 return S_OK;
4346}
4347
4348STDMETHODIMP Machine::ReadSavedScreenshotPNGToArray(ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
4349{
4350 LogFlowThisFunc(("\n"));
4351
4352 CheckComArgNotNull(aWidth);
4353 CheckComArgNotNull(aHeight);
4354 CheckComArgExpr(aData, !ComSafeArrayOutIsNull(aData));
4355
4356 AutoCaller autoCaller(this);
4357 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4358
4359 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4360
4361 uint8_t *pu8Data = NULL;
4362 uint32_t cbData = 0;
4363 uint32_t u32Width = 0;
4364 uint32_t u32Height = 0;
4365
4366 int vrc = readSavedDisplayScreenshot(&mSSData->mStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
4367
4368 if (RT_FAILURE(vrc))
4369 return setError (VBOX_E_IPRT_ERROR,
4370 tr("Saved screenshot data is not available (%Rrc)"), vrc);
4371
4372 *aWidth = u32Width;
4373 *aHeight = u32Height;
4374
4375 com::SafeArray<BYTE> png(cbData);
4376 for (unsigned i = 0; i < cbData; i++)
4377 png[i] = pu8Data[i];
4378 png.detachTo(ComSafeArrayOutArg(aData));
4379
4380 freeSavedDisplayScreenshot(pu8Data);
4381
4382 return S_OK;
4383}
4384
4385STDMETHODIMP Machine::HotPlugCPU(ULONG aCpu)
4386{
4387 HRESULT rc = S_OK;
4388 LogFlowThisFunc(("\n"));
4389
4390 AutoCaller autoCaller(this);
4391 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4392
4393 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4394
4395 if (!mHWData->mCPUHotPlugEnabled)
4396 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
4397
4398 if (aCpu >= mHWData->mCPUCount)
4399 return setError(E_INVALIDARG, tr("CPU id exceeds number of possible CPUs [0:%lu]"), mHWData->mCPUCount-1);
4400
4401 if (mHWData->mCPUAttached[aCpu])
4402 return setError(VBOX_E_OBJECT_IN_USE, tr("CPU %lu is already attached"), aCpu);
4403
4404 alock.leave();
4405 rc = onCPUChange(aCpu, false);
4406 alock.enter();
4407 if (FAILED(rc)) return rc;
4408
4409 mHWData.backup();
4410 mHWData->mCPUAttached[aCpu] = true;
4411
4412 /* Save settings if online */
4413 if (Global::IsOnline(mData->mMachineState))
4414 SaveSettings();
4415
4416 return S_OK;
4417}
4418
4419STDMETHODIMP Machine::HotUnplugCPU(ULONG aCpu)
4420{
4421 HRESULT rc = S_OK;
4422 LogFlowThisFunc(("\n"));
4423
4424 AutoCaller autoCaller(this);
4425 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4426
4427 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4428
4429 if (!mHWData->mCPUHotPlugEnabled)
4430 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
4431
4432 if (aCpu >= SchemaDefs::MaxCPUCount)
4433 return setError(E_INVALIDARG,
4434 tr("CPU index exceeds maximum CPU count (must be in range [0:%lu])"),
4435 SchemaDefs::MaxCPUCount);
4436
4437 if (!mHWData->mCPUAttached[aCpu])
4438 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("CPU %lu is not attached"), aCpu);
4439
4440 /* CPU 0 can't be detached */
4441 if (aCpu == 0)
4442 return setError(E_INVALIDARG, tr("It is not possible to detach CPU 0"));
4443
4444 alock.leave();
4445 rc = onCPUChange(aCpu, true);
4446 alock.enter();
4447 if (FAILED(rc)) return rc;
4448
4449 mHWData.backup();
4450 mHWData->mCPUAttached[aCpu] = false;
4451
4452 /* Save settings if online */
4453 if (Global::IsOnline(mData->mMachineState))
4454 SaveSettings();
4455
4456 return S_OK;
4457}
4458
4459STDMETHODIMP Machine::GetCPUStatus(ULONG aCpu, BOOL *aCpuAttached)
4460{
4461 LogFlowThisFunc(("\n"));
4462
4463 CheckComArgNotNull(aCpuAttached);
4464
4465 *aCpuAttached = false;
4466
4467 AutoCaller autoCaller(this);
4468 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4469
4470 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4471
4472 /* If hotplug is enabled the CPU is always enabled. */
4473 if (!mHWData->mCPUHotPlugEnabled)
4474 {
4475 if (aCpu < mHWData->mCPUCount)
4476 *aCpuAttached = true;
4477 }
4478 else
4479 {
4480 if (aCpu < SchemaDefs::MaxCPUCount)
4481 *aCpuAttached = mHWData->mCPUAttached[aCpu];
4482 }
4483
4484 return S_OK;
4485}
4486
4487// public methods for internal purposes
4488/////////////////////////////////////////////////////////////////////////////
4489
4490/**
4491 * Saves the registry entry of this machine to the given configuration node.
4492 *
4493 * @param aEntryNode Node to save the registry entry to.
4494 *
4495 * @note locks this object for reading.
4496 */
4497HRESULT Machine::saveRegistryEntry(settings::MachineRegistryEntry &data)
4498{
4499 AutoLimitedCaller autoCaller(this);
4500 AssertComRCReturnRC(autoCaller.rc());
4501
4502 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4503
4504 data.uuid = mData->mUuid;
4505 data.strSettingsFile = mData->m_strConfigFile;
4506
4507 return S_OK;
4508}
4509
4510/**
4511 * Calculates the absolute path of the given path taking the directory of the
4512 * machine settings file as the current directory.
4513 *
4514 * @param aPath Path to calculate the absolute path for.
4515 * @param aResult Where to put the result (used only on success, can be the
4516 * same Utf8Str instance as passed in @a aPath).
4517 * @return IPRT result.
4518 *
4519 * @note Locks this object for reading.
4520 */
4521int Machine::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
4522{
4523 AutoCaller autoCaller(this);
4524 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
4525
4526 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4527
4528 AssertReturn (!mData->m_strConfigFileFull.isEmpty(), VERR_GENERAL_FAILURE);
4529
4530 Utf8Str strSettingsDir = mData->m_strConfigFileFull;
4531
4532 strSettingsDir.stripFilename();
4533 char folder[RTPATH_MAX];
4534 int vrc = RTPathAbsEx(strSettingsDir.c_str(), strPath.c_str(), folder, sizeof(folder));
4535 if (RT_SUCCESS(vrc))
4536 aResult = folder;
4537
4538 return vrc;
4539}
4540
4541/**
4542 * Tries to calculate the relative path of the given absolute path using the
4543 * directory of the machine settings file as the base directory.
4544 *
4545 * @param aPath Absolute path to calculate the relative path for.
4546 * @param aResult Where to put the result (used only when it's possible to
4547 * make a relative path from the given absolute path; otherwise
4548 * left untouched).
4549 *
4550 * @note Locks this object for reading.
4551 */
4552void Machine::calculateRelativePath(const Utf8Str &strPath, Utf8Str &aResult)
4553{
4554 AutoCaller autoCaller(this);
4555 AssertComRCReturn (autoCaller.rc(), (void) 0);
4556
4557 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4558
4559 AssertReturnVoid (!mData->m_strConfigFileFull.isEmpty());
4560
4561 Utf8Str settingsDir = mData->m_strConfigFileFull;
4562
4563 settingsDir.stripFilename();
4564 if (RTPathStartsWith(strPath.c_str(), settingsDir.c_str()))
4565 {
4566 /* when assigning, we create a separate Utf8Str instance because both
4567 * aPath and aResult can point to the same memory location when this
4568 * func is called (if we just do aResult = aPath, aResult will be freed
4569 * first, and since its the same as aPath, an attempt to copy garbage
4570 * will be made. */
4571 aResult = Utf8Str(strPath.c_str() + settingsDir.length() + 1);
4572 }
4573}
4574
4575/**
4576 * Returns the full path to the machine's log folder in the
4577 * \a aLogFolder argument.
4578 */
4579void Machine::getLogFolder (Utf8Str &aLogFolder)
4580{
4581 AutoCaller autoCaller(this);
4582 AssertComRCReturnVoid (autoCaller.rc());
4583
4584 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4585
4586 Utf8Str settingsDir;
4587 if (isInOwnDir (&settingsDir))
4588 {
4589 /* Log folder is <Machines>/<VM_Name>/Logs */
4590 aLogFolder = Utf8StrFmt ("%s%cLogs", settingsDir.raw(), RTPATH_DELIMITER);
4591 }
4592 else
4593 {
4594 /* Log folder is <Machines>/<VM_SnapshotFolder>/Logs */
4595 Assert (!mUserData->mSnapshotFolderFull.isEmpty());
4596 aLogFolder = Utf8StrFmt ("%ls%cLogs", mUserData->mSnapshotFolderFull.raw(),
4597 RTPATH_DELIMITER);
4598 }
4599}
4600
4601/**
4602 * @note Locks this object for writing, calls the client process (outside the
4603 * lock).
4604 */
4605HRESULT Machine::openSession(IInternalSessionControl *aControl)
4606{
4607 LogFlowThisFuncEnter();
4608
4609 AssertReturn(aControl, E_FAIL);
4610
4611 AutoCaller autoCaller(this);
4612 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4613
4614 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4615
4616 if (!mData->mRegistered)
4617 return setError(E_UNEXPECTED,
4618 tr("The machine '%ls' is not registered"),
4619 mUserData->mName.raw());
4620
4621 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
4622
4623 /* Hack: in case the session is closing and there is a progress object
4624 * which allows waiting for the session to be closed, take the opportunity
4625 * and do a limited wait (max. 1 second). This helps a lot when the system
4626 * is busy and thus session closing can take a little while. */
4627 if ( mData->mSession.mState == SessionState_Closing
4628 && mData->mSession.mProgress)
4629 {
4630 alock.leave();
4631 mData->mSession.mProgress->WaitForCompletion(1000);
4632 alock.enter();
4633 LogFlowThisFunc(("after waiting: mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
4634 }
4635
4636 if (mData->mSession.mState == SessionState_Open ||
4637 mData->mSession.mState == SessionState_Closing)
4638 return setError(VBOX_E_INVALID_OBJECT_STATE,
4639 tr("A session for the machine '%ls' is currently open (or being closed)"),
4640 mUserData->mName.raw());
4641
4642 /* may not be busy */
4643 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
4644
4645 /* get the session PID */
4646 RTPROCESS pid = NIL_RTPROCESS;
4647 AssertCompile(sizeof(ULONG) == sizeof(RTPROCESS));
4648 aControl->GetPID((ULONG *) &pid);
4649 Assert(pid != NIL_RTPROCESS);
4650
4651 if (mData->mSession.mState == SessionState_Spawning)
4652 {
4653 /* This machine is awaiting for a spawning session to be opened, so
4654 * reject any other open attempts from processes other than one
4655 * started by #openRemoteSession(). */
4656
4657 LogFlowThisFunc(("mSession.mPid=%d(0x%x)\n",
4658 mData->mSession.mPid, mData->mSession.mPid));
4659 LogFlowThisFunc(("session.pid=%d(0x%x)\n", pid, pid));
4660
4661 if (mData->mSession.mPid != pid)
4662 return setError(E_ACCESSDENIED,
4663 tr("An unexpected process (PID=0x%08X) has tried to open a direct "
4664 "session with the machine named '%ls', while only a process "
4665 "started by OpenRemoteSession (PID=0x%08X) is allowed"),
4666 pid, mUserData->mName.raw(), mData->mSession.mPid);
4667 }
4668
4669 /* create a SessionMachine object */
4670 ComObjPtr<SessionMachine> sessionMachine;
4671 sessionMachine.createObject();
4672 HRESULT rc = sessionMachine->init(this);
4673 AssertComRC(rc);
4674
4675 /* NOTE: doing return from this function after this point but
4676 * before the end is forbidden since it may call SessionMachine::uninit()
4677 * (through the ComObjPtr's destructor) which requests the VirtualBox write
4678 * lock while still holding the Machine lock in alock so that a deadlock
4679 * is possible due to the wrong lock order. */
4680
4681 if (SUCCEEDED(rc))
4682 {
4683#ifdef VBOX_WITH_RESOURCE_USAGE_API
4684 registerMetrics(mParent->performanceCollector(), this, pid);
4685#endif /* VBOX_WITH_RESOURCE_USAGE_API */
4686
4687 /*
4688 * Set the session state to Spawning to protect against subsequent
4689 * attempts to open a session and to unregister the machine after
4690 * we leave the lock.
4691 */
4692 SessionState_T origState = mData->mSession.mState;
4693 mData->mSession.mState = SessionState_Spawning;
4694
4695 /*
4696 * Leave the lock before calling the client process -- it will call
4697 * Machine/SessionMachine methods. Leaving the lock here is quite safe
4698 * because the state is Spawning, so that openRemotesession() and
4699 * openExistingSession() calls will fail. This method, called before we
4700 * enter the lock again, will fail because of the wrong PID.
4701 *
4702 * Note that mData->mSession.mRemoteControls accessed outside
4703 * the lock may not be modified when state is Spawning, so it's safe.
4704 */
4705 alock.leave();
4706
4707 LogFlowThisFunc(("Calling AssignMachine()...\n"));
4708 rc = aControl->AssignMachine(sessionMachine);
4709 LogFlowThisFunc(("AssignMachine() returned %08X\n", rc));
4710
4711 /* The failure may occur w/o any error info (from RPC), so provide one */
4712 if (FAILED(rc))
4713 setError(VBOX_E_VM_ERROR,
4714 tr("Failed to assign the machine to the session (%Rrc)"), rc);
4715
4716 if (SUCCEEDED(rc) && origState == SessionState_Spawning)
4717 {
4718 /* complete the remote session initialization */
4719
4720 /* get the console from the direct session */
4721 ComPtr<IConsole> console;
4722 rc = aControl->GetRemoteConsole(console.asOutParam());
4723 ComAssertComRC(rc);
4724
4725 if (SUCCEEDED(rc) && !console)
4726 {
4727 ComAssert(!!console);
4728 rc = E_FAIL;
4729 }
4730
4731 /* assign machine & console to the remote session */
4732 if (SUCCEEDED(rc))
4733 {
4734 /*
4735 * after openRemoteSession(), the first and the only
4736 * entry in remoteControls is that remote session
4737 */
4738 LogFlowThisFunc(("Calling AssignRemoteMachine()...\n"));
4739 rc = mData->mSession.mRemoteControls.front()->
4740 AssignRemoteMachine(sessionMachine, console);
4741 LogFlowThisFunc(("AssignRemoteMachine() returned %08X\n", rc));
4742
4743 /* The failure may occur w/o any error info (from RPC), so provide one */
4744 if (FAILED(rc))
4745 setError(VBOX_E_VM_ERROR,
4746 tr("Failed to assign the machine to the remote session (%Rrc)"), rc);
4747 }
4748
4749 if (FAILED(rc))
4750 aControl->Uninitialize();
4751 }
4752
4753 /* enter the lock again */
4754 alock.enter();
4755
4756 /* Restore the session state */
4757 mData->mSession.mState = origState;
4758 }
4759
4760 /* finalize spawning anyway (this is why we don't return on errors above) */
4761 if (mData->mSession.mState == SessionState_Spawning)
4762 {
4763 /* Note that the progress object is finalized later */
4764
4765 /* We don't reset mSession.mPid here because it is necessary for
4766 * SessionMachine::uninit() to reap the child process later. */
4767
4768 if (FAILED(rc))
4769 {
4770 /* Close the remote session, remove the remote control from the list
4771 * and reset session state to Closed (@note keep the code in sync
4772 * with the relevant part in openSession()). */
4773
4774 Assert (mData->mSession.mRemoteControls.size() == 1);
4775 if (mData->mSession.mRemoteControls.size() == 1)
4776 {
4777 ErrorInfoKeeper eik;
4778 mData->mSession.mRemoteControls.front()->Uninitialize();
4779 }
4780
4781 mData->mSession.mRemoteControls.clear();
4782 mData->mSession.mState = SessionState_Closed;
4783 }
4784 }
4785 else
4786 {
4787 /* memorize PID of the directly opened session */
4788 if (SUCCEEDED(rc))
4789 mData->mSession.mPid = pid;
4790 }
4791
4792 if (SUCCEEDED(rc))
4793 {
4794 /* memorize the direct session control and cache IUnknown for it */
4795 mData->mSession.mDirectControl = aControl;
4796 mData->mSession.mState = SessionState_Open;
4797 /* associate the SessionMachine with this Machine */
4798 mData->mSession.mMachine = sessionMachine;
4799
4800 /* request an IUnknown pointer early from the remote party for later
4801 * identity checks (it will be internally cached within mDirectControl
4802 * at least on XPCOM) */
4803 ComPtr<IUnknown> unk = mData->mSession.mDirectControl;
4804 NOREF(unk);
4805 }
4806
4807 if (mData->mSession.mProgress)
4808 {
4809 /* finalize the progress after setting the state, for consistency */
4810 mData->mSession.mProgress->notifyComplete(rc);
4811 mData->mSession.mProgress.setNull();
4812 }
4813
4814 /* Leave the lock since SessionMachine::uninit() locks VirtualBox which
4815 * would break the lock order */
4816 alock.leave();
4817
4818 /* uninitialize the created session machine on failure */
4819 if (FAILED(rc))
4820 sessionMachine->uninit();
4821
4822 LogFlowThisFunc(("rc=%08X\n", rc));
4823 LogFlowThisFuncLeave();
4824 return rc;
4825}
4826
4827/**
4828 * @note Locks this object for writing, calls the client process
4829 * (inside the lock).
4830 */
4831HRESULT Machine::openRemoteSession(IInternalSessionControl *aControl,
4832 IN_BSTR aType,
4833 IN_BSTR aEnvironment,
4834 Progress *aProgress)
4835{
4836 LogFlowThisFuncEnter();
4837
4838 AssertReturn(aControl, E_FAIL);
4839 AssertReturn(aProgress, E_FAIL);
4840
4841 AutoCaller autoCaller(this);
4842 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4843
4844 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4845
4846 if (!mData->mRegistered)
4847 return setError(E_UNEXPECTED,
4848 tr("The machine '%ls' is not registered"),
4849 mUserData->mName.raw());
4850
4851 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
4852
4853 if (mData->mSession.mState == SessionState_Open ||
4854 mData->mSession.mState == SessionState_Spawning ||
4855 mData->mSession.mState == SessionState_Closing)
4856 return setError(VBOX_E_INVALID_OBJECT_STATE,
4857 tr("A session for the machine '%ls' is currently open (or being opened or closed)"),
4858 mUserData->mName.raw());
4859
4860 /* may not be busy */
4861 AssertReturn(!Global::IsOnlineOrTransient (mData->mMachineState), E_FAIL);
4862
4863 /* get the path to the executable */
4864 char szPath[RTPATH_MAX];
4865 RTPathAppPrivateArch(szPath, RTPATH_MAX);
4866 size_t sz = strlen(szPath);
4867 szPath[sz++] = RTPATH_DELIMITER;
4868 szPath[sz] = 0;
4869 char *cmd = szPath + sz;
4870 sz = RTPATH_MAX - sz;
4871
4872 int vrc = VINF_SUCCESS;
4873 RTPROCESS pid = NIL_RTPROCESS;
4874
4875 RTENV env = RTENV_DEFAULT;
4876
4877 if (aEnvironment != NULL && *aEnvironment)
4878 {
4879 char *newEnvStr = NULL;
4880
4881 do
4882 {
4883 /* clone the current environment */
4884 int vrc2 = RTEnvClone(&env, RTENV_DEFAULT);
4885 AssertRCBreakStmt(vrc2, vrc = vrc2);
4886
4887 newEnvStr = RTStrDup(Utf8Str(aEnvironment).c_str());
4888 AssertPtrBreakStmt(newEnvStr, vrc = vrc2);
4889
4890 /* put new variables to the environment
4891 * (ignore empty variable names here since RTEnv API
4892 * intentionally doesn't do that) */
4893 char *var = newEnvStr;
4894 for (char *p = newEnvStr; *p; ++p)
4895 {
4896 if (*p == '\n' && (p == newEnvStr || *(p - 1) != '\\'))
4897 {
4898 *p = '\0';
4899 if (*var)
4900 {
4901 char *val = strchr (var, '=');
4902 if (val)
4903 {
4904 *val++ = '\0';
4905 vrc2 = RTEnvSetEx (env, var, val);
4906 }
4907 else
4908 vrc2 = RTEnvUnsetEx (env, var);
4909 if (RT_FAILURE(vrc2))
4910 break;
4911 }
4912 var = p + 1;
4913 }
4914 }
4915 if (RT_SUCCESS(vrc2) && *var)
4916 vrc2 = RTEnvPutEx (env, var);
4917
4918 AssertRCBreakStmt (vrc2, vrc = vrc2);
4919 }
4920 while (0);
4921
4922 if (newEnvStr != NULL)
4923 RTStrFree(newEnvStr);
4924 }
4925
4926 Utf8Str strType(aType);
4927
4928 /* Qt is default */
4929#ifdef VBOX_WITH_QTGUI
4930 if (strType == "gui" || strType == "GUI/Qt")
4931 {
4932# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
4933 const char VirtualBox_exe[] = "../Resources/VirtualBoxVM.app/Contents/MacOS/VirtualBoxVM";
4934# else
4935 const char VirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
4936# endif
4937 Assert (sz >= sizeof (VirtualBox_exe));
4938 strcpy (cmd, VirtualBox_exe);
4939
4940 Utf8Str idStr = mData->mUuid.toString();
4941# ifdef RT_OS_WINDOWS /** @todo drop this once the RTProcCreate bug has been fixed */
4942 const char * args[] = {szPath, "--startvm", idStr.c_str(), 0 };
4943# else
4944 Utf8Str strName = mUserData->mName;
4945 const char * args[] = {szPath, "--comment", strName.c_str(), "--startvm", idStr.c_str(), 0 };
4946# endif
4947 vrc = RTProcCreate(szPath, args, env, 0, &pid);
4948 }
4949#else /* !VBOX_WITH_QTGUI */
4950 if (0)
4951 ;
4952#endif /* VBOX_WITH_QTGUI */
4953
4954 else
4955
4956#ifdef VBOX_WITH_VBOXSDL
4957 if (strType == "sdl" || strType == "GUI/SDL")
4958 {
4959 const char VBoxSDL_exe[] = "VBoxSDL" HOSTSUFF_EXE;
4960 Assert (sz >= sizeof (VBoxSDL_exe));
4961 strcpy (cmd, VBoxSDL_exe);
4962
4963 Utf8Str idStr = mData->mUuid.toString();
4964# ifdef RT_OS_WINDOWS
4965 const char * args[] = {szPath, "--startvm", idStr.c_str(), 0 };
4966# else
4967 Utf8Str strName = mUserData->mName;
4968 const char * args[] = {szPath, "--comment", strName.c_str(), "--startvm", idStr.c_str(), 0 };
4969# endif
4970 vrc = RTProcCreate(szPath, args, env, 0, &pid);
4971 }
4972#else /* !VBOX_WITH_VBOXSDL */
4973 if (0)
4974 ;
4975#endif /* !VBOX_WITH_VBOXSDL */
4976
4977 else
4978
4979#ifdef VBOX_WITH_HEADLESS
4980 if ( strType == "headless"
4981 || strType == "capture"
4982#ifdef VBOX_WITH_VRDP
4983 || strType == "vrdp"
4984#endif
4985 )
4986 {
4987 const char VBoxHeadless_exe[] = "VBoxHeadless" HOSTSUFF_EXE;
4988 Assert (sz >= sizeof (VBoxHeadless_exe));
4989 strcpy (cmd, VBoxHeadless_exe);
4990
4991 Utf8Str idStr = mData->mUuid.toString();
4992 /* Leave space for 2 args, as "headless" needs --vrdp off on non-OSE. */
4993# ifdef RT_OS_WINDOWS
4994 const char * args[] = {szPath, "--startvm", idStr.c_str(), 0, 0, 0 };
4995# else
4996 Utf8Str strName = mUserData->mName;
4997 const char * args[] ={szPath, "--comment", strName.c_str(), "--startvm", idStr.c_str(), 0, 0, 0 };
4998# endif
4999#ifdef VBOX_WITH_VRDP
5000 if (strType == "headless")
5001 {
5002 unsigned pos = RT_ELEMENTS(args) - 3;
5003 args[pos++] = "--vrdp";
5004 args[pos] = "off";
5005 }
5006#endif
5007 if (strType == "capture")
5008 {
5009 unsigned pos = RT_ELEMENTS(args) - 3;
5010 args[pos] = "--capture";
5011 }
5012 vrc = RTProcCreate(szPath, args, env, 0, &pid);
5013 }
5014#else /* !VBOX_WITH_HEADLESS */
5015 if (0)
5016 ;
5017#endif /* !VBOX_WITH_HEADLESS */
5018 else
5019 {
5020 RTEnvDestroy (env);
5021 return setError(E_INVALIDARG,
5022 tr("Invalid session type: '%s'"),
5023 strType.c_str());
5024 }
5025
5026 RTEnvDestroy (env);
5027
5028 if (RT_FAILURE(vrc))
5029 return setError(VBOX_E_IPRT_ERROR,
5030 tr("Could not launch a process for the machine '%ls' (%Rrc)"),
5031 mUserData->mName.raw(), vrc);
5032
5033 LogFlowThisFunc(("launched.pid=%d(0x%x)\n", pid, pid));
5034
5035 /*
5036 * Note that we don't leave the lock here before calling the client,
5037 * because it doesn't need to call us back if called with a NULL argument.
5038 * Leaving the lock herer is dangerous because we didn't prepare the
5039 * launch data yet, but the client we've just started may happen to be
5040 * too fast and call openSession() that will fail (because of PID, etc.),
5041 * so that the Machine will never get out of the Spawning session state.
5042 */
5043
5044 /* inform the session that it will be a remote one */
5045 LogFlowThisFunc(("Calling AssignMachine (NULL)...\n"));
5046 HRESULT rc = aControl->AssignMachine (NULL);
5047 LogFlowThisFunc(("AssignMachine (NULL) returned %08X\n", rc));
5048
5049 if (FAILED(rc))
5050 {
5051 /* restore the session state */
5052 mData->mSession.mState = SessionState_Closed;
5053 /* The failure may occur w/o any error info (from RPC), so provide one */
5054 return setError(VBOX_E_VM_ERROR,
5055 tr("Failed to assign the machine to the session (%Rrc)"), rc);
5056 }
5057
5058 /* attach launch data to the machine */
5059 Assert (mData->mSession.mPid == NIL_RTPROCESS);
5060 mData->mSession.mRemoteControls.push_back (aControl);
5061 mData->mSession.mProgress = aProgress;
5062 mData->mSession.mPid = pid;
5063 mData->mSession.mState = SessionState_Spawning;
5064 mData->mSession.mType = strType;
5065
5066 LogFlowThisFuncLeave();
5067 return S_OK;
5068}
5069
5070/**
5071 * @note Locks this object for writing, calls the client process
5072 * (outside the lock).
5073 */
5074HRESULT Machine::openExistingSession (IInternalSessionControl *aControl)
5075{
5076 LogFlowThisFuncEnter();
5077
5078 AssertReturn(aControl, E_FAIL);
5079
5080 AutoCaller autoCaller(this);
5081 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5082
5083 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5084
5085 if (!mData->mRegistered)
5086 return setError (E_UNEXPECTED,
5087 tr ("The machine '%ls' is not registered"), mUserData->mName.raw());
5088
5089 LogFlowThisFunc(("mSession.state=%s\n", Global::stringifySessionState(mData->mSession.mState)));
5090
5091 if (mData->mSession.mState != SessionState_Open)
5092 return setError (VBOX_E_INVALID_SESSION_STATE,
5093 tr ("The machine '%ls' does not have an open session"),
5094 mUserData->mName.raw());
5095
5096 ComAssertRet (!mData->mSession.mDirectControl.isNull(), E_FAIL);
5097
5098 /*
5099 * Get the console from the direct session (note that we don't leave the
5100 * lock here because GetRemoteConsole must not call us back).
5101 */
5102 ComPtr<IConsole> console;
5103 HRESULT rc = mData->mSession.mDirectControl->
5104 GetRemoteConsole (console.asOutParam());
5105 if (FAILED (rc))
5106 {
5107 /* The failure may occur w/o any error info (from RPC), so provide one */
5108 return setError (VBOX_E_VM_ERROR,
5109 tr ("Failed to get a console object from the direct session (%Rrc)"), rc);
5110 }
5111
5112 ComAssertRet (!console.isNull(), E_FAIL);
5113
5114 ComObjPtr<SessionMachine> sessionMachine = mData->mSession.mMachine;
5115 AssertReturn(!sessionMachine.isNull(), E_FAIL);
5116
5117 /*
5118 * Leave the lock before calling the client process. It's safe here
5119 * since the only thing to do after we get the lock again is to add
5120 * the remote control to the list (which doesn't directly influence
5121 * anything).
5122 */
5123 alock.leave();
5124
5125 /* attach the remote session to the machine */
5126 LogFlowThisFunc(("Calling AssignRemoteMachine()...\n"));
5127 rc = aControl->AssignRemoteMachine (sessionMachine, console);
5128 LogFlowThisFunc(("AssignRemoteMachine() returned %08X\n", rc));
5129
5130 /* The failure may occur w/o any error info (from RPC), so provide one */
5131 if (FAILED(rc))
5132 return setError(VBOX_E_VM_ERROR,
5133 tr("Failed to assign the machine to the session (%Rrc)"),
5134 rc);
5135
5136 alock.enter();
5137
5138 /* need to revalidate the state after entering the lock again */
5139 if (mData->mSession.mState != SessionState_Open)
5140 {
5141 aControl->Uninitialize();
5142
5143 return setError(VBOX_E_INVALID_SESSION_STATE,
5144 tr("The machine '%ls' does not have an open session"),
5145 mUserData->mName.raw());
5146 }
5147
5148 /* store the control in the list */
5149 mData->mSession.mRemoteControls.push_back (aControl);
5150
5151 LogFlowThisFuncLeave();
5152 return S_OK;
5153}
5154
5155/**
5156 * Returns @c true if the given machine has an open direct session and returns
5157 * the session machine instance and additional session data (on some platforms)
5158 * if so.
5159 *
5160 * Note that when the method returns @c false, the arguments remain unchanged.
5161 *
5162 * @param aMachine Session machine object.
5163 * @param aControl Direct session control object (optional).
5164 * @param aIPCSem Mutex IPC semaphore handle for this machine (optional).
5165 *
5166 * @note locks this object for reading.
5167 */
5168#if defined (RT_OS_WINDOWS)
5169bool Machine::isSessionOpen (ComObjPtr<SessionMachine> &aMachine,
5170 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
5171 HANDLE *aIPCSem /*= NULL*/,
5172 bool aAllowClosing /*= false*/)
5173#elif defined (RT_OS_OS2)
5174bool Machine::isSessionOpen (ComObjPtr<SessionMachine> &aMachine,
5175 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
5176 HMTX *aIPCSem /*= NULL*/,
5177 bool aAllowClosing /*= false*/)
5178#else
5179bool Machine::isSessionOpen (ComObjPtr<SessionMachine> &aMachine,
5180 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
5181 bool aAllowClosing /*= false*/)
5182#endif
5183{
5184 AutoLimitedCaller autoCaller(this);
5185 AssertComRCReturn (autoCaller.rc(), false);
5186
5187 /* just return false for inaccessible machines */
5188 if (autoCaller.state() != Ready)
5189 return false;
5190
5191 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5192
5193 if (mData->mSession.mState == SessionState_Open ||
5194 (aAllowClosing && mData->mSession.mState == SessionState_Closing))
5195 {
5196 AssertReturn(!mData->mSession.mMachine.isNull(), false);
5197
5198 aMachine = mData->mSession.mMachine;
5199
5200 if (aControl != NULL)
5201 *aControl = mData->mSession.mDirectControl;
5202
5203#if defined (RT_OS_WINDOWS) || defined (RT_OS_OS2)
5204 /* Additional session data */
5205 if (aIPCSem != NULL)
5206 *aIPCSem = aMachine->mIPCSem;
5207#endif
5208 return true;
5209 }
5210
5211 return false;
5212}
5213
5214/**
5215 * Returns @c true if the given machine has an spawning direct session and
5216 * returns and additional session data (on some platforms) if so.
5217 *
5218 * Note that when the method returns @c false, the arguments remain unchanged.
5219 *
5220 * @param aPID PID of the spawned direct session process.
5221 *
5222 * @note locks this object for reading.
5223 */
5224#if defined (RT_OS_WINDOWS) || defined (RT_OS_OS2)
5225bool Machine::isSessionSpawning (RTPROCESS *aPID /*= NULL*/)
5226#else
5227bool Machine::isSessionSpawning()
5228#endif
5229{
5230 AutoLimitedCaller autoCaller(this);
5231 AssertComRCReturn (autoCaller.rc(), false);
5232
5233 /* just return false for inaccessible machines */
5234 if (autoCaller.state() != Ready)
5235 return false;
5236
5237 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5238
5239 if (mData->mSession.mState == SessionState_Spawning)
5240 {
5241#if defined (RT_OS_WINDOWS) || defined (RT_OS_OS2)
5242 /* Additional session data */
5243 if (aPID != NULL)
5244 {
5245 AssertReturn(mData->mSession.mPid != NIL_RTPROCESS, false);
5246 *aPID = mData->mSession.mPid;
5247 }
5248#endif
5249 return true;
5250 }
5251
5252 return false;
5253}
5254
5255/**
5256 * Called from the client watcher thread to check for unexpected client process
5257 * death during Session_Spawning state (e.g. before it successfully opened a
5258 * direct session).
5259 *
5260 * On Win32 and on OS/2, this method is called only when we've got the
5261 * direct client's process termination notification, so it always returns @c
5262 * true.
5263 *
5264 * On other platforms, this method returns @c true if the client process is
5265 * terminated and @c false if it's still alive.
5266 *
5267 * @note Locks this object for writing.
5268 */
5269bool Machine::checkForSpawnFailure()
5270{
5271 AutoCaller autoCaller(this);
5272 if (!autoCaller.isOk())
5273 {
5274 /* nothing to do */
5275 LogFlowThisFunc(("Already uninitialized!\n"));
5276 return true;
5277 }
5278
5279 /* VirtualBox::addProcessToReap() needs a write lock */
5280 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
5281
5282 if (mData->mSession.mState != SessionState_Spawning)
5283 {
5284 /* nothing to do */
5285 LogFlowThisFunc(("Not spawning any more!\n"));
5286 return true;
5287 }
5288
5289 HRESULT rc = S_OK;
5290
5291#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
5292
5293 /* the process was already unexpectedly terminated, we just need to set an
5294 * error and finalize session spawning */
5295 rc = setError(E_FAIL,
5296 tr("Virtual machine '%ls' has terminated unexpectedly during startup"),
5297 getName().raw());
5298#else
5299
5300 /* PID not yet initialized, skip check. */
5301 if (mData->mSession.mPid == NIL_RTPROCESS)
5302 return false;
5303
5304 RTPROCSTATUS status;
5305 int vrc = ::RTProcWait(mData->mSession.mPid, RTPROCWAIT_FLAGS_NOBLOCK,
5306 &status);
5307
5308 if (vrc != VERR_PROCESS_RUNNING)
5309 rc = setError(E_FAIL,
5310 tr("Virtual machine '%ls' has terminated unexpectedly during startup"),
5311 getName().raw());
5312#endif
5313
5314 if (FAILED(rc))
5315 {
5316 /* Close the remote session, remove the remote control from the list
5317 * and reset session state to Closed (@note keep the code in sync with
5318 * the relevant part in checkForSpawnFailure()). */
5319
5320 Assert(mData->mSession.mRemoteControls.size() == 1);
5321 if (mData->mSession.mRemoteControls.size() == 1)
5322 {
5323 ErrorInfoKeeper eik;
5324 mData->mSession.mRemoteControls.front()->Uninitialize();
5325 }
5326
5327 mData->mSession.mRemoteControls.clear();
5328 mData->mSession.mState = SessionState_Closed;
5329
5330 /* finalize the progress after setting the state, for consistency */
5331 if (!mData->mSession.mProgress.isNull())
5332 {
5333 mData->mSession.mProgress->notifyComplete(rc);
5334 mData->mSession.mProgress.setNull();
5335 }
5336
5337 mParent->addProcessToReap(mData->mSession.mPid);
5338 mData->mSession.mPid = NIL_RTPROCESS;
5339
5340 mParent->onSessionStateChange(mData->mUuid, SessionState_Closed);
5341 return true;
5342 }
5343
5344 return false;
5345}
5346
5347/**
5348 * Checks that the registered flag of the machine can be set according to
5349 * the argument and sets it. On success, commits and saves all settings.
5350 *
5351 * @note When this machine is inaccessible, the only valid value for \a
5352 * aRegistered is FALSE (i.e. unregister the machine) because unregistered
5353 * inaccessible machines are not currently supported. Note that unregistering
5354 * an inaccessible machine will \b uninitialize this machine object. Therefore,
5355 * the caller must make sure there are no active Machine::addCaller() calls
5356 * on the current thread because this will block Machine::uninit().
5357 *
5358 * @note Must be called from mParent's write lock. Locks this object and
5359 * children for writing.
5360 */
5361HRESULT Machine::trySetRegistered(BOOL argNewRegistered)
5362{
5363 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
5364
5365 AutoLimitedCaller autoCaller(this);
5366 AssertComRCReturnRC(autoCaller.rc());
5367
5368 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5369
5370 /* wait for state dependants to drop to zero */
5371 ensureNoStateDependencies();
5372
5373 ComAssertRet(mData->mRegistered != argNewRegistered, E_FAIL);
5374
5375 if (!mData->mAccessible)
5376 {
5377 /* A special case: the machine is not accessible. */
5378
5379 /* inaccessible machines can only be unregistered */
5380 AssertReturn(!argNewRegistered, E_FAIL);
5381
5382 /* Uninitialize ourselves here because currently there may be no
5383 * unregistered that are inaccessible (this state combination is not
5384 * supported). Note releasing the caller and leaving the lock before
5385 * calling uninit() */
5386
5387 alock.leave();
5388 autoCaller.release();
5389
5390 uninit();
5391
5392 return S_OK;
5393 }
5394
5395 AssertReturn(autoCaller.state() == Ready, E_FAIL);
5396
5397 if (argNewRegistered)
5398 {
5399 if (mData->mRegistered)
5400 return setError(VBOX_E_INVALID_OBJECT_STATE,
5401 tr("The machine '%ls' with UUID {%s} is already registered"),
5402 mUserData->mName.raw(),
5403 mData->mUuid.toString().raw());
5404 }
5405 else
5406 {
5407 if (mData->mMachineState == MachineState_Saved)
5408 return setError(VBOX_E_INVALID_VM_STATE,
5409 tr("Cannot unregister the machine '%ls' because it is in the Saved state"),
5410 mUserData->mName.raw());
5411
5412 size_t snapshotCount = 0;
5413 if (mData->mFirstSnapshot)
5414 snapshotCount = mData->mFirstSnapshot->getAllChildrenCount() + 1;
5415 if (snapshotCount)
5416 return setError(VBOX_E_INVALID_OBJECT_STATE,
5417 tr("Cannot unregister the machine '%ls' because it has %d snapshots"),
5418 mUserData->mName.raw(), snapshotCount);
5419
5420 if (mData->mSession.mState != SessionState_Closed)
5421 return setError(VBOX_E_INVALID_OBJECT_STATE,
5422 tr("Cannot unregister the machine '%ls' because it has an open session"),
5423 mUserData->mName.raw());
5424
5425 if (mMediaData->mAttachments.size() != 0)
5426 return setError(VBOX_E_INVALID_OBJECT_STATE,
5427 tr("Cannot unregister the machine '%ls' because it has %d medium attachments"),
5428 mUserData->mName.raw(),
5429 mMediaData->mAttachments.size());
5430
5431 /* Note that we do not prevent unregistration of a DVD or Floppy image
5432 * is attached: as opposed to hard disks detaching such an image
5433 * implicitly in this method (which we will do below) won't have any
5434 * side effects (like detached orphan base and diff hard disks etc).*/
5435 }
5436
5437 HRESULT rc = S_OK;
5438
5439 /* Ensure the settings are saved. If we are going to be registered and
5440 * isConfigLocked() is FALSE then it means that no config file exists yet,
5441 * so create it by calling saveSettings() too. */
5442 if ( isModified()
5443 || (argNewRegistered && !mData->m_pMachineConfigFile->fileExists())
5444 )
5445 {
5446 rc = saveSettings();
5447 if (FAILED(rc)) return rc;
5448 }
5449
5450 /* more config checking goes here */
5451
5452 if (SUCCEEDED(rc))
5453 {
5454 /* we may have had implicit modifications we want to fix on success */
5455 commit();
5456
5457 mData->mRegistered = argNewRegistered;
5458 }
5459 else
5460 {
5461 /* we may have had implicit modifications we want to cancel on failure*/
5462 rollback (false /* aNotify */);
5463 }
5464
5465 return rc;
5466}
5467
5468/**
5469 * Increases the number of objects dependent on the machine state or on the
5470 * registered state. Guarantees that these two states will not change at least
5471 * until #releaseStateDependency() is called.
5472 *
5473 * Depending on the @a aDepType value, additional state checks may be made.
5474 * These checks will set extended error info on failure. See
5475 * #checkStateDependency() for more info.
5476 *
5477 * If this method returns a failure, the dependency is not added and the caller
5478 * is not allowed to rely on any particular machine state or registration state
5479 * value and may return the failed result code to the upper level.
5480 *
5481 * @param aDepType Dependency type to add.
5482 * @param aState Current machine state (NULL if not interested).
5483 * @param aRegistered Current registered state (NULL if not interested).
5484 *
5485 * @note Locks this object for writing.
5486 */
5487HRESULT Machine::addStateDependency (StateDependency aDepType /* = AnyStateDep */,
5488 MachineState_T *aState /* = NULL */,
5489 BOOL *aRegistered /* = NULL */)
5490{
5491 AutoCaller autoCaller(this);
5492 AssertComRCReturnRC(autoCaller.rc());
5493
5494 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5495
5496 HRESULT rc = checkStateDependency(aDepType);
5497 if (FAILED(rc)) return rc;
5498
5499 {
5500 if (mData->mMachineStateChangePending != 0)
5501 {
5502 /* ensureNoStateDependencies() is waiting for state dependencies to
5503 * drop to zero so don't add more. It may make sense to wait a bit
5504 * and retry before reporting an error (since the pending state
5505 * transition should be really quick) but let's just assert for
5506 * now to see if it ever happens on practice. */
5507
5508 AssertFailed();
5509
5510 return setError(E_ACCESSDENIED,
5511 tr("Machine state change is in progress. Please retry the operation later."));
5512 }
5513
5514 ++mData->mMachineStateDeps;
5515 Assert (mData->mMachineStateDeps != 0 /* overflow */);
5516 }
5517
5518 if (aState)
5519 *aState = mData->mMachineState;
5520 if (aRegistered)
5521 *aRegistered = mData->mRegistered;
5522
5523 return S_OK;
5524}
5525
5526/**
5527 * Decreases the number of objects dependent on the machine state.
5528 * Must always complete the #addStateDependency() call after the state
5529 * dependency is no more necessary.
5530 */
5531void Machine::releaseStateDependency()
5532{
5533 AutoCaller autoCaller(this);
5534 AssertComRCReturnVoid (autoCaller.rc());
5535
5536 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5537
5538 AssertReturnVoid (mData->mMachineStateDeps != 0
5539 /* releaseStateDependency() w/o addStateDependency()? */);
5540 -- mData->mMachineStateDeps;
5541
5542 if (mData->mMachineStateDeps == 0)
5543 {
5544 /* inform ensureNoStateDependencies() that there are no more deps */
5545 if (mData->mMachineStateChangePending != 0)
5546 {
5547 Assert (mData->mMachineStateDepsSem != NIL_RTSEMEVENTMULTI);
5548 RTSemEventMultiSignal (mData->mMachineStateDepsSem);
5549 }
5550 }
5551}
5552
5553// protected methods
5554/////////////////////////////////////////////////////////////////////////////
5555
5556/**
5557 * Performs machine state checks based on the @a aDepType value. If a check
5558 * fails, this method will set extended error info, otherwise it will return
5559 * S_OK. It is supposed, that on failure, the caller will immedieately return
5560 * the return value of this method to the upper level.
5561 *
5562 * When @a aDepType is AnyStateDep, this method always returns S_OK.
5563 *
5564 * When @a aDepType is MutableStateDep, this method returns S_OK only if the
5565 * current state of this machine object allows to change settings of the
5566 * machine (i.e. the machine is not registered, or registered but not running
5567 * and not saved). It is useful to call this method from Machine setters
5568 * before performing any change.
5569 *
5570 * When @a aDepType is MutableOrSavedStateDep, this method behaves the same
5571 * as for MutableStateDep except that if the machine is saved, S_OK is also
5572 * returned. This is useful in setters which allow changing machine
5573 * properties when it is in the saved state.
5574 *
5575 * @param aDepType Dependency type to check.
5576 *
5577 * @note Non Machine based classes should use #addStateDependency() and
5578 * #releaseStateDependency() methods or the smart AutoStateDependency
5579 * template.
5580 *
5581 * @note This method must be called from under this object's read or write
5582 * lock.
5583 */
5584HRESULT Machine::checkStateDependency(StateDependency aDepType)
5585{
5586 switch (aDepType)
5587 {
5588 case AnyStateDep:
5589 {
5590 break;
5591 }
5592 case MutableStateDep:
5593 {
5594 if ( mData->mRegistered
5595 && ( getClassID() != clsidSessionMachine /** @todo This was just convered raw; Check if Running and Paused should actually be included here... (Live Migration) */
5596 || ( mData->mMachineState != MachineState_Paused
5597 && mData->mMachineState != MachineState_Running
5598 && mData->mMachineState != MachineState_Aborted
5599 && mData->mMachineState != MachineState_Teleported
5600 && mData->mMachineState != MachineState_PoweredOff
5601 )
5602 )
5603 )
5604 return setError(VBOX_E_INVALID_VM_STATE,
5605 tr("The machine is not mutable (state is %s)"),
5606 Global::stringifyMachineState(mData->mMachineState));
5607 break;
5608 }
5609 case MutableOrSavedStateDep:
5610 {
5611 if ( mData->mRegistered
5612 && ( getClassID() != clsidSessionMachine /** @todo This was just convered raw; Check if Running and Paused should actually be included here... (Live Migration) */
5613 || ( mData->mMachineState != MachineState_Paused
5614 && mData->mMachineState != MachineState_Running
5615 && mData->mMachineState != MachineState_Aborted
5616 && mData->mMachineState != MachineState_Teleported
5617 && mData->mMachineState != MachineState_Saved
5618 && mData->mMachineState != MachineState_PoweredOff
5619 )
5620 )
5621 )
5622 return setError(VBOX_E_INVALID_VM_STATE,
5623 tr("The machine is not mutable (state is %s)"),
5624 Global::stringifyMachineState(mData->mMachineState));
5625 break;
5626 }
5627 }
5628
5629 return S_OK;
5630}
5631
5632/**
5633 * Helper to initialize all associated child objects and allocate data
5634 * structures.
5635 *
5636 * This method must be called as a part of the object's initialization procedure
5637 * (usually done in the #init() method).
5638 *
5639 * @note Must be called only from #init() or from #registeredInit().
5640 */
5641HRESULT Machine::initDataAndChildObjects()
5642{
5643 AutoCaller autoCaller(this);
5644 AssertComRCReturnRC(autoCaller.rc());
5645 AssertComRCReturn (autoCaller.state() == InInit ||
5646 autoCaller.state() == Limited, E_FAIL);
5647
5648 AssertReturn(!mData->mAccessible, E_FAIL);
5649
5650 /* allocate data structures */
5651 mSSData.allocate();
5652 mUserData.allocate();
5653 mHWData.allocate();
5654 mMediaData.allocate();
5655 mStorageControllers.allocate();
5656
5657 /* initialize mOSTypeId */
5658 mUserData->mOSTypeId = mParent->getUnknownOSType()->id();
5659
5660 /* create associated BIOS settings object */
5661 unconst(mBIOSSettings).createObject();
5662 mBIOSSettings->init (this);
5663
5664#ifdef VBOX_WITH_VRDP
5665 /* create an associated VRDPServer object (default is disabled) */
5666 unconst(mVRDPServer).createObject();
5667 mVRDPServer->init (this);
5668#endif
5669
5670 /* create associated serial port objects */
5671 for (ULONG slot = 0; slot < RT_ELEMENTS (mSerialPorts); slot ++)
5672 {
5673 unconst(mSerialPorts [slot]).createObject();
5674 mSerialPorts [slot]->init (this, slot);
5675 }
5676
5677 /* create associated parallel port objects */
5678 for (ULONG slot = 0; slot < RT_ELEMENTS (mParallelPorts); slot ++)
5679 {
5680 unconst(mParallelPorts [slot]).createObject();
5681 mParallelPorts [slot]->init (this, slot);
5682 }
5683
5684 /* create the audio adapter object (always present, default is disabled) */
5685 unconst(mAudioAdapter).createObject();
5686 mAudioAdapter->init (this);
5687
5688 /* create the USB controller object (always present, default is disabled) */
5689 unconst(mUSBController).createObject();
5690 mUSBController->init (this);
5691
5692 /* create associated network adapter objects */
5693 for (ULONG slot = 0; slot < RT_ELEMENTS (mNetworkAdapters); slot ++)
5694 {
5695 unconst(mNetworkAdapters [slot]).createObject();
5696 mNetworkAdapters [slot]->init (this, slot);
5697 }
5698
5699 return S_OK;
5700}
5701
5702/**
5703 * Helper to uninitialize all associated child objects and to free all data
5704 * structures.
5705 *
5706 * This method must be called as a part of the object's uninitialization
5707 * procedure (usually done in the #uninit() method).
5708 *
5709 * @note Must be called only from #uninit() or from #registeredInit().
5710 */
5711void Machine::uninitDataAndChildObjects()
5712{
5713 AutoCaller autoCaller(this);
5714 AssertComRCReturnVoid(autoCaller.rc());
5715 AssertComRCReturnVoid( autoCaller.state() == InUninit
5716 || autoCaller.state() == Limited);
5717
5718 /* uninit all children using addDependentChild()/removeDependentChild()
5719 * in their init()/uninit() methods */
5720 uninitDependentChildren();
5721
5722 /* tell all our other child objects we've been uninitialized */
5723
5724 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
5725 {
5726 if (mNetworkAdapters[slot])
5727 {
5728 mNetworkAdapters[slot]->uninit();
5729 unconst(mNetworkAdapters[slot]).setNull();
5730 }
5731 }
5732
5733 if (mUSBController)
5734 {
5735 mUSBController->uninit();
5736 unconst(mUSBController).setNull();
5737 }
5738
5739 if (mAudioAdapter)
5740 {
5741 mAudioAdapter->uninit();
5742 unconst(mAudioAdapter).setNull();
5743 }
5744
5745 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
5746 {
5747 if (mParallelPorts[slot])
5748 {
5749 mParallelPorts[slot]->uninit();
5750 unconst(mParallelPorts[slot]).setNull();
5751 }
5752 }
5753
5754 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
5755 {
5756 if (mSerialPorts[slot])
5757 {
5758 mSerialPorts[slot]->uninit();
5759 unconst(mSerialPorts[slot]).setNull();
5760 }
5761 }
5762
5763#ifdef VBOX_WITH_VRDP
5764 if (mVRDPServer)
5765 {
5766 mVRDPServer->uninit();
5767 unconst(mVRDPServer).setNull();
5768 }
5769#endif
5770
5771 if (mBIOSSettings)
5772 {
5773 mBIOSSettings->uninit();
5774 unconst(mBIOSSettings).setNull();
5775 }
5776
5777 /* Deassociate hard disks (only when a real Machine or a SnapshotMachine
5778 * instance is uninitialized; SessionMachine instances refer to real
5779 * Machine hard disks). This is necessary for a clean re-initialization of
5780 * the VM after successfully re-checking the accessibility state. Note
5781 * that in case of normal Machine or SnapshotMachine uninitialization (as
5782 * a result of unregistering or discarding the snapshot), outdated hard
5783 * disk attachments will already be uninitialized and deleted, so this
5784 * code will not affect them. */
5785 VBoxClsID clsid = getClassID();
5786 if ( !!mMediaData
5787 && (clsid == clsidMachine || clsid == clsidSnapshotMachine)
5788 )
5789 {
5790 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
5791 it != mMediaData->mAttachments.end();
5792 ++it)
5793 {
5794 ComObjPtr<Medium> hd = (*it)->getMedium();
5795 if (hd.isNull())
5796 continue;
5797 HRESULT rc = hd->detachFrom(mData->mUuid, getSnapshotId());
5798 AssertComRC (rc);
5799 }
5800 }
5801
5802 if (getClassID() == clsidMachine)
5803 {
5804 // clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
5805 if (mData->mFirstSnapshot)
5806 {
5807 // snapshots tree is protected by media write lock; strictly
5808 // this isn't necessary here since we're deleting the entire
5809 // machine, but otherwise we assert in Snapshot::uninit()
5810 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5811 mData->mFirstSnapshot->uninit();
5812 mData->mFirstSnapshot.setNull();
5813 }
5814
5815 mData->mCurrentSnapshot.setNull();
5816 }
5817
5818 /* free data structures (the essential mData structure is not freed here
5819 * since it may be still in use) */
5820 mMediaData.free();
5821 mStorageControllers.free();
5822 mHWData.free();
5823 mUserData.free();
5824 mSSData.free();
5825}
5826
5827/**
5828 * Makes sure that there are no machine state dependants. If necessary, waits
5829 * for the number of dependants to drop to zero.
5830 *
5831 * Make sure this method is called from under this object's write lock to
5832 * guarantee that no new dependants may be added when this method returns
5833 * control to the caller.
5834 *
5835 * @note Locks this object for writing. The lock will be released while waiting
5836 * (if necessary).
5837 *
5838 * @warning To be used only in methods that change the machine state!
5839 */
5840void Machine::ensureNoStateDependencies()
5841{
5842 AssertReturnVoid (isWriteLockOnCurrentThread());
5843
5844 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5845
5846 /* Wait for all state dependants if necessary */
5847 if (mData->mMachineStateDeps != 0)
5848 {
5849 /* lazy semaphore creation */
5850 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
5851 RTSemEventMultiCreate (&mData->mMachineStateDepsSem);
5852
5853 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
5854 mData->mMachineStateDeps));
5855
5856 ++mData->mMachineStateChangePending;
5857
5858 /* reset the semaphore before waiting, the last dependant will signal
5859 * it */
5860 RTSemEventMultiReset (mData->mMachineStateDepsSem);
5861
5862 alock.leave();
5863
5864 RTSemEventMultiWait (mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
5865
5866 alock.enter();
5867
5868 -- mData->mMachineStateChangePending;
5869 }
5870}
5871
5872/**
5873 * Changes the machine state and informs callbacks.
5874 *
5875 * This method is not intended to fail so it either returns S_OK or asserts (and
5876 * returns a failure).
5877 *
5878 * @note Locks this object for writing.
5879 */
5880HRESULT Machine::setMachineState (MachineState_T aMachineState)
5881{
5882 LogFlowThisFuncEnter();
5883 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
5884
5885 AutoCaller autoCaller(this);
5886 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
5887
5888 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5889
5890 /* wait for state dependants to drop to zero */
5891 ensureNoStateDependencies();
5892
5893 if (mData->mMachineState != aMachineState)
5894 {
5895 mData->mMachineState = aMachineState;
5896
5897 RTTimeNow (&mData->mLastStateChange);
5898
5899 mParent->onMachineStateChange(mData->mUuid, aMachineState);
5900 }
5901
5902 LogFlowThisFuncLeave();
5903 return S_OK;
5904}
5905
5906/**
5907 * Searches for a shared folder with the given logical name
5908 * in the collection of shared folders.
5909 *
5910 * @param aName logical name of the shared folder
5911 * @param aSharedFolder where to return the found object
5912 * @param aSetError whether to set the error info if the folder is
5913 * not found
5914 * @return
5915 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
5916 *
5917 * @note
5918 * must be called from under the object's lock!
5919 */
5920HRESULT Machine::findSharedFolder (CBSTR aName,
5921 ComObjPtr<SharedFolder> &aSharedFolder,
5922 bool aSetError /* = false */)
5923{
5924 bool found = false;
5925 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
5926 !found && it != mHWData->mSharedFolders.end();
5927 ++it)
5928 {
5929 AutoWriteLock alock(*it COMMA_LOCKVAL_SRC_POS);
5930 found = (*it)->getName() == aName;
5931 if (found)
5932 aSharedFolder = *it;
5933 }
5934
5935 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
5936
5937 if (aSetError && !found)
5938 setError(rc, tr("Could not find a shared folder named '%ls'"), aName);
5939
5940 return rc;
5941}
5942
5943/**
5944 * Loads all the VM settings by walking down the <Machine> node.
5945 *
5946 * @param aRegistered true when the machine is being loaded on VirtualBox
5947 * startup
5948 *
5949 * @note This method is intended to be called only from init(), so it assumes
5950 * all machine data fields have appropriate default values when it is called.
5951 *
5952 * @note Doesn't lock any objects.
5953 */
5954HRESULT Machine::loadSettings(bool aRegistered)
5955{
5956 LogFlowThisFuncEnter();
5957 AssertReturn(getClassID() == clsidMachine, E_FAIL);
5958
5959 AutoCaller autoCaller(this);
5960 AssertReturn(autoCaller.state() == InInit, E_FAIL);
5961
5962 HRESULT rc = S_OK;
5963
5964 try
5965 {
5966 Assert(mData->m_pMachineConfigFile == NULL);
5967
5968 // load and parse machine XML; this will throw on XML or logic errors
5969 mData->m_pMachineConfigFile = new settings::MachineConfigFile(&mData->m_strConfigFileFull);
5970
5971 /* If the stored UUID is not empty, it means the registered machine
5972 * is being loaded. Compare the loaded UUID with the stored one taken
5973 * from the global registry. */
5974 if (!mData->mUuid.isEmpty())
5975 {
5976 if (mData->mUuid != mData->m_pMachineConfigFile->uuid)
5977 {
5978 throw setError(E_FAIL,
5979 tr("Machine UUID {%RTuuid} in '%s' doesn't match its UUID {%s} in the registry file '%s'"),
5980 mData->m_pMachineConfigFile->uuid.raw(),
5981 mData->m_strConfigFileFull.raw(),
5982 mData->mUuid.toString().raw(),
5983 mParent->settingsFilePath().raw());
5984 }
5985 }
5986 else
5987 unconst (mData->mUuid) = mData->m_pMachineConfigFile->uuid;
5988
5989 /* name (required) */
5990 mUserData->mName = mData->m_pMachineConfigFile->strName;
5991
5992 /* nameSync (optional, default is true) */
5993 mUserData->mNameSync = mData->m_pMachineConfigFile->fNameSync;
5994
5995 mUserData->mDescription = mData->m_pMachineConfigFile->strDescription;
5996
5997 // guest OS type
5998 mUserData->mOSTypeId = mData->m_pMachineConfigFile->strOsType;
5999 /* look up the object by Id to check it is valid */
6000 ComPtr<IGuestOSType> guestOSType;
6001 rc = mParent->GetGuestOSType(mUserData->mOSTypeId,
6002 guestOSType.asOutParam());
6003 if (FAILED(rc)) throw rc;
6004
6005 // stateFile (optional)
6006 if (mData->m_pMachineConfigFile->strStateFile.isEmpty())
6007 mSSData->mStateFilePath.setNull();
6008 else
6009 {
6010 Utf8Str stateFilePathFull(mData->m_pMachineConfigFile->strStateFile);
6011 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
6012 if (RT_FAILURE(vrc))
6013 throw setError(E_FAIL,
6014 tr("Invalid saved state file path '%s' (%Rrc)"),
6015 mData->m_pMachineConfigFile->strStateFile.raw(),
6016 vrc);
6017 mSSData->mStateFilePath = stateFilePathFull;
6018 }
6019
6020 /* snapshotFolder (optional) */
6021 rc = COMSETTER(SnapshotFolder)(Bstr(mData->m_pMachineConfigFile->strSnapshotFolder));
6022 if (FAILED(rc)) throw rc;
6023
6024 /* currentStateModified (optional, default is true) */
6025 mData->mCurrentStateModified = mData->m_pMachineConfigFile->fCurrentStateModified;
6026
6027 mData->mLastStateChange = mData->m_pMachineConfigFile->timeLastStateChange;
6028
6029 /* teleportation */
6030 mUserData->mTeleporterEnabled = mData->m_pMachineConfigFile->fTeleporterEnabled;
6031 mUserData->mTeleporterPort = mData->m_pMachineConfigFile->uTeleporterPort;
6032 mUserData->mTeleporterAddress = mData->m_pMachineConfigFile->strTeleporterAddress;
6033 mUserData->mTeleporterPassword = mData->m_pMachineConfigFile->strTeleporterPassword;
6034
6035 /* RTC */
6036 mUserData->mRTCUseUTC = mData->m_pMachineConfigFile->fRTCUseUTC;
6037
6038 /*
6039 * note: all mUserData members must be assigned prior this point because
6040 * we need to commit changes in order to let mUserData be shared by all
6041 * snapshot machine instances.
6042 */
6043 mUserData.commitCopy();
6044
6045 /* Snapshot node (optional) */
6046 size_t cRootSnapshots;
6047 if ((cRootSnapshots = mData->m_pMachineConfigFile->llFirstSnapshot.size()))
6048 {
6049 // there must be only one root snapshot
6050 Assert(cRootSnapshots == 1);
6051
6052 settings::Snapshot &snap = mData->m_pMachineConfigFile->llFirstSnapshot.front();
6053
6054 rc = loadSnapshot(snap,
6055 mData->m_pMachineConfigFile->uuidCurrentSnapshot,
6056 NULL); // no parent == first snapshot
6057 if (FAILED(rc)) throw rc;
6058 }
6059
6060 /* Hardware node (required) */
6061 rc = loadHardware(mData->m_pMachineConfigFile->hardwareMachine);
6062 if (FAILED(rc)) throw rc;
6063
6064 /* Load storage controllers */
6065 rc = loadStorageControllers(mData->m_pMachineConfigFile->storageMachine, aRegistered);
6066 if (FAILED(rc)) throw rc;
6067
6068 /*
6069 * NOTE: the assignment below must be the last thing to do,
6070 * otherwise it will be not possible to change the settings
6071 * somewehere in the code above because all setters will be
6072 * blocked by checkStateDependency(MutableStateDep).
6073 */
6074
6075 /* set the machine state to Aborted or Saved when appropriate */
6076 if (mData->m_pMachineConfigFile->fAborted)
6077 {
6078 Assert(!mSSData->mStateFilePath.isEmpty());
6079 mSSData->mStateFilePath.setNull();
6080
6081 /* no need to use setMachineState() during init() */
6082 mData->mMachineState = MachineState_Aborted;
6083 }
6084 else if (!mSSData->mStateFilePath.isEmpty())
6085 {
6086 /* no need to use setMachineState() during init() */
6087 mData->mMachineState = MachineState_Saved;
6088 }
6089 }
6090 catch (HRESULT err)
6091 {
6092 /* we assume that error info is set by the thrower */
6093 rc = err;
6094 }
6095 catch (...)
6096 {
6097 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
6098 }
6099
6100 LogFlowThisFuncLeave();
6101 return rc;
6102}
6103
6104/**
6105 * Recursively loads all snapshots starting from the given.
6106 *
6107 * @param aNode <Snapshot> node.
6108 * @param aCurSnapshotId Current snapshot ID from the settings file.
6109 * @param aParentSnapshot Parent snapshot.
6110 */
6111HRESULT Machine::loadSnapshot(const settings::Snapshot &data,
6112 const Guid &aCurSnapshotId,
6113 Snapshot *aParentSnapshot)
6114{
6115 AssertReturn(getClassID() == clsidMachine, E_FAIL);
6116
6117 HRESULT rc = S_OK;
6118
6119 Utf8Str strStateFile;
6120 if (!data.strStateFile.isEmpty())
6121 {
6122 /* optional */
6123 strStateFile = data.strStateFile;
6124 int vrc = calculateFullPath(strStateFile, strStateFile);
6125 if (RT_FAILURE(vrc))
6126 return setError(E_FAIL,
6127 tr("Invalid saved state file path '%s' (%Rrc)"),
6128 strStateFile.raw(),
6129 vrc);
6130 }
6131
6132 /* create a snapshot machine object */
6133 ComObjPtr<SnapshotMachine> pSnapshotMachine;
6134 pSnapshotMachine.createObject();
6135 rc = pSnapshotMachine->init(this,
6136 data.hardware,
6137 data.storage,
6138 data.uuid,
6139 strStateFile);
6140 if (FAILED(rc)) return rc;
6141
6142 /* create a snapshot object */
6143 ComObjPtr<Snapshot> pSnapshot;
6144 pSnapshot.createObject();
6145 /* initialize the snapshot */
6146 rc = pSnapshot->init(mParent, // VirtualBox object
6147 data.uuid,
6148 data.strName,
6149 data.strDescription,
6150 data.timestamp,
6151 pSnapshotMachine,
6152 aParentSnapshot);
6153 if (FAILED(rc)) return rc;
6154
6155 /* memorize the first snapshot if necessary */
6156 if (!mData->mFirstSnapshot)
6157 mData->mFirstSnapshot = pSnapshot;
6158
6159 /* memorize the current snapshot when appropriate */
6160 if ( !mData->mCurrentSnapshot
6161 && pSnapshot->getId() == aCurSnapshotId
6162 )
6163 mData->mCurrentSnapshot = pSnapshot;
6164
6165 // now create the children
6166 for (settings::SnapshotsList::const_iterator it = data.llChildSnapshots.begin();
6167 it != data.llChildSnapshots.end();
6168 ++it)
6169 {
6170 const settings::Snapshot &childData = *it;
6171 // recurse
6172 rc = loadSnapshot(childData,
6173 aCurSnapshotId,
6174 pSnapshot); // parent = the one we created above
6175 if (FAILED(rc)) return rc;
6176 }
6177
6178 return rc;
6179}
6180
6181/**
6182 * @param aNode <Hardware> node.
6183 */
6184HRESULT Machine::loadHardware(const settings::Hardware &data)
6185{
6186 AssertReturn(getClassID() == clsidMachine || getClassID() == clsidSnapshotMachine, E_FAIL);
6187
6188 HRESULT rc = S_OK;
6189
6190 try
6191 {
6192 /* The hardware version attribute (optional). */
6193 mHWData->mHWVersion = data.strVersion;
6194 mHWData->mHardwareUUID = data.uuid;
6195
6196 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
6197 mHWData->mHWVirtExExclusive = data.fHardwareVirtExclusive;
6198 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
6199 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
6200 mHWData->mPAEEnabled = data.fPAE;
6201 mHWData->mSyntheticCpu = data.fSyntheticCpu;
6202
6203 mHWData->mCPUCount = data.cCPUs;
6204 mHWData->mCPUHotPlugEnabled = data.fCpuHotPlug;
6205
6206 // cpu
6207 if (mHWData->mCPUHotPlugEnabled)
6208 {
6209 for (settings::CpuList::const_iterator it = data.llCpus.begin();
6210 it != data.llCpus.end();
6211 ++it)
6212 {
6213 const settings::Cpu &cpu = *it;
6214
6215 mHWData->mCPUAttached[cpu.ulId] = true;
6216 }
6217 }
6218
6219 // cpuid leafs
6220 for (settings::CpuIdLeafsList::const_iterator it = data.llCpuIdLeafs.begin();
6221 it != data.llCpuIdLeafs.end();
6222 ++it)
6223 {
6224 const settings::CpuIdLeaf &leaf = *it;
6225
6226 switch (leaf.ulId)
6227 {
6228 case 0x0:
6229 case 0x1:
6230 case 0x2:
6231 case 0x3:
6232 case 0x4:
6233 case 0x5:
6234 case 0x6:
6235 case 0x7:
6236 case 0x8:
6237 case 0x9:
6238 case 0xA:
6239 mHWData->mCpuIdStdLeafs[leaf.ulId] = leaf;
6240 break;
6241
6242 case 0x80000000:
6243 case 0x80000001:
6244 case 0x80000002:
6245 case 0x80000003:
6246 case 0x80000004:
6247 case 0x80000005:
6248 case 0x80000006:
6249 case 0x80000007:
6250 case 0x80000008:
6251 case 0x80000009:
6252 case 0x8000000A:
6253 mHWData->mCpuIdExtLeafs[leaf.ulId - 0x80000000] = leaf;
6254 break;
6255
6256 default:
6257 /* just ignore */
6258 break;
6259 }
6260 }
6261
6262 mHWData->mMemorySize = data.ulMemorySizeMB;
6263
6264 // boot order
6265 for (size_t i = 0;
6266 i < RT_ELEMENTS(mHWData->mBootOrder);
6267 i++)
6268 {
6269 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
6270 if (it == data.mapBootOrder.end())
6271 mHWData->mBootOrder[i] = DeviceType_Null;
6272 else
6273 mHWData->mBootOrder[i] = it->second;
6274 }
6275
6276 mHWData->mVRAMSize = data.ulVRAMSizeMB;
6277 mHWData->mMonitorCount = data.cMonitors;
6278 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
6279 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
6280 mHWData->mFirmwareType = data.firmwareType;
6281
6282#ifdef VBOX_WITH_VRDP
6283 /* RemoteDisplay */
6284 rc = mVRDPServer->loadSettings(data.vrdpSettings);
6285 if (FAILED(rc)) return rc;
6286#endif
6287
6288 /* BIOS */
6289 rc = mBIOSSettings->loadSettings(data.biosSettings);
6290 if (FAILED(rc)) return rc;
6291
6292 /* USB Controller */
6293 rc = mUSBController->loadSettings(data.usbController);
6294 if (FAILED(rc)) return rc;
6295
6296 // network adapters
6297 for (settings::NetworkAdaptersList::const_iterator it = data.llNetworkAdapters.begin();
6298 it != data.llNetworkAdapters.end();
6299 ++it)
6300 {
6301 const settings::NetworkAdapter &nic = *it;
6302
6303 /* slot unicity is guaranteed by XML Schema */
6304 AssertBreak(nic.ulSlot < RT_ELEMENTS(mNetworkAdapters));
6305 rc = mNetworkAdapters[nic.ulSlot]->loadSettings(nic);
6306 if (FAILED(rc)) return rc;
6307 }
6308
6309 // serial ports
6310 for (settings::SerialPortsList::const_iterator it = data.llSerialPorts.begin();
6311 it != data.llSerialPorts.end();
6312 ++it)
6313 {
6314 const settings::SerialPort &s = *it;
6315
6316 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
6317 rc = mSerialPorts[s.ulSlot]->loadSettings(s);
6318 if (FAILED(rc)) return rc;
6319 }
6320
6321 // parallel ports (optional)
6322 for (settings::ParallelPortsList::const_iterator it = data.llParallelPorts.begin();
6323 it != data.llParallelPorts.end();
6324 ++it)
6325 {
6326 const settings::ParallelPort &p = *it;
6327
6328 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
6329 rc = mParallelPorts[p.ulSlot]->loadSettings(p);
6330 if (FAILED(rc)) return rc;
6331 }
6332
6333 /* AudioAdapter */
6334 rc = mAudioAdapter->loadSettings(data.audioAdapter);
6335 if (FAILED(rc)) return rc;
6336
6337 for (settings::SharedFoldersList::const_iterator it = data.llSharedFolders.begin();
6338 it != data.llSharedFolders.end();
6339 ++it)
6340 {
6341 const settings::SharedFolder &sf = *it;
6342 rc = CreateSharedFolder(Bstr(sf.strName), Bstr(sf.strHostPath), sf.fWritable);
6343 if (FAILED(rc)) return rc;
6344 }
6345
6346 // Clipboard
6347 mHWData->mClipboardMode = data.clipboardMode;
6348
6349 // guest settings
6350 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
6351 mHWData->mStatisticsUpdateInterval = data.ulStatisticsUpdateInterval;
6352
6353#ifdef VBOX_WITH_GUEST_PROPS
6354 /* Guest properties (optional) */
6355 for (settings::GuestPropertiesList::const_iterator it = data.llGuestProperties.begin();
6356 it != data.llGuestProperties.end();
6357 ++it)
6358 {
6359 const settings::GuestProperty &prop = *it;
6360 uint32_t fFlags = guestProp::NILFLAG;
6361 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
6362 HWData::GuestProperty property = { prop.strName, prop.strValue, prop.timestamp, fFlags };
6363 mHWData->mGuestProperties.push_back(property);
6364 }
6365
6366 mHWData->mPropertyServiceActive = false;
6367 mHWData->mGuestPropertyNotificationPatterns = data.strNotificationPatterns;
6368#endif /* VBOX_WITH_GUEST_PROPS defined */
6369 }
6370 catch(std::bad_alloc &)
6371 {
6372 return E_OUTOFMEMORY;
6373 }
6374
6375 AssertComRC(rc);
6376 return rc;
6377}
6378
6379 /**
6380 * @param aNode <StorageControllers> node.
6381 */
6382HRESULT Machine::loadStorageControllers(const settings::Storage &data,
6383 bool aRegistered,
6384 const Guid *aSnapshotId /* = NULL */)
6385{
6386 AssertReturn(getClassID() == clsidMachine || getClassID() == clsidSnapshotMachine, E_FAIL);
6387
6388 HRESULT rc = S_OK;
6389
6390 for (settings::StorageControllersList::const_iterator it = data.llStorageControllers.begin();
6391 it != data.llStorageControllers.end();
6392 ++it)
6393 {
6394 const settings::StorageController &ctlData = *it;
6395
6396 ComObjPtr<StorageController> pCtl;
6397 /* Try to find one with the name first. */
6398 rc = getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
6399 if (SUCCEEDED(rc))
6400 return setError(VBOX_E_OBJECT_IN_USE,
6401 tr("Storage controller named '%s' already exists"),
6402 ctlData.strName.raw());
6403
6404 pCtl.createObject();
6405 rc = pCtl->init(this,
6406 ctlData.strName,
6407 ctlData.storageBus,
6408 ctlData.ulInstance);
6409 if (FAILED(rc)) return rc;
6410
6411 mStorageControllers->push_back(pCtl);
6412
6413 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
6414 if (FAILED(rc)) return rc;
6415
6416 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
6417 if (FAILED(rc)) return rc;
6418
6419 /* Set IDE emulation settings (only for AHCI controller). */
6420 if (ctlData.controllerType == StorageControllerType_IntelAhci)
6421 {
6422 if ( (FAILED(rc = pCtl->SetIDEEmulationPort(0, ctlData.lIDE0MasterEmulationPort)))
6423 || (FAILED(rc = pCtl->SetIDEEmulationPort(1, ctlData.lIDE0SlaveEmulationPort)))
6424 || (FAILED(rc = pCtl->SetIDEEmulationPort(2, ctlData.lIDE1MasterEmulationPort)))
6425 || (FAILED(rc = pCtl->SetIDEEmulationPort(3, ctlData.lIDE1SlaveEmulationPort)))
6426 )
6427 return rc;
6428 }
6429
6430 /* Load the attached devices now. */
6431 rc = loadStorageDevices(pCtl,
6432 ctlData,
6433 aRegistered,
6434 aSnapshotId);
6435 if (FAILED(rc)) return rc;
6436 }
6437
6438 return S_OK;
6439}
6440
6441/**
6442 * @param aNode <HardDiskAttachments> node.
6443 * @param aRegistered true when the machine is being loaded on VirtualBox
6444 * startup, or when a snapshot is being loaded (wchich
6445 * currently can happen on startup only)
6446 * @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
6447 *
6448 * @note Lock mParent for reading and hard disks for writing before calling.
6449 */
6450HRESULT Machine::loadStorageDevices(StorageController *aStorageController,
6451 const settings::StorageController &data,
6452 bool aRegistered,
6453 const Guid *aSnapshotId /*= NULL*/)
6454{
6455 AssertReturn( (getClassID() == clsidMachine && aSnapshotId == NULL)
6456 || (getClassID() == clsidSnapshotMachine && aSnapshotId != NULL),
6457 E_FAIL);
6458
6459 HRESULT rc = S_OK;
6460
6461 if (!aRegistered && data.llAttachedDevices.size() > 0)
6462 /* when the machine is being loaded (opened) from a file, it cannot
6463 * have hard disks attached (this should not happen normally,
6464 * because we don't allow to attach hard disks to an unregistered
6465 * VM at all */
6466 return setError(E_FAIL,
6467 tr("Unregistered machine '%ls' cannot have storage devices attached (found %d attachments)"),
6468 mUserData->mName.raw(),
6469 data.llAttachedDevices.size());
6470
6471 /* paranoia: detect duplicate attachments */
6472 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
6473 it != data.llAttachedDevices.end();
6474 ++it)
6475 {
6476 for (settings::AttachedDevicesList::const_iterator it2 = it;
6477 it2 != data.llAttachedDevices.end();
6478 ++it2)
6479 {
6480 if (it == it2)
6481 continue;
6482
6483 if ( (*it).lPort == (*it2).lPort
6484 && (*it).lDevice == (*it2).lDevice)
6485 {
6486 return setError(E_FAIL,
6487 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%ls'"),
6488 aStorageController->getName().raw(), (*it).lPort, (*it).lDevice, mUserData->mName.raw());
6489 }
6490 }
6491 }
6492
6493 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
6494 it != data.llAttachedDevices.end();
6495 ++it)
6496 {
6497 const settings::AttachedDevice &dev = *it;
6498 ComObjPtr<Medium> medium;
6499
6500 switch (dev.deviceType)
6501 {
6502 case DeviceType_Floppy:
6503 /* find a floppy by UUID */
6504 if (!dev.uuid.isEmpty())
6505 rc = mParent->findFloppyImage(&dev.uuid, NULL, true /* aDoSetError */, &medium);
6506 /* find a floppy by host device name */
6507 else if (!dev.strHostDriveSrc.isEmpty())
6508 {
6509 SafeIfaceArray<IMedium> drivevec;
6510 rc = mParent->host()->COMGETTER(FloppyDrives)(ComSafeArrayAsOutParam(drivevec));
6511 if (SUCCEEDED(rc))
6512 {
6513 for (size_t i = 0; i < drivevec.size(); ++i)
6514 {
6515 /// @todo eliminate this conversion
6516 ComObjPtr<Medium> med = (Medium *)drivevec[i];
6517 if ( dev.strHostDriveSrc == med->getName()
6518 || dev.strHostDriveSrc == med->getLocation())
6519 {
6520 medium = med;
6521 break;
6522 }
6523 }
6524 }
6525 }
6526 break;
6527
6528 case DeviceType_DVD:
6529 /* find a DVD by UUID */
6530 if (!dev.uuid.isEmpty())
6531 rc = mParent->findDVDImage(&dev.uuid, NULL, true /* aDoSetError */, &medium);
6532 /* find a DVD by host device name */
6533 else if (!dev.strHostDriveSrc.isEmpty())
6534 {
6535 SafeIfaceArray<IMedium> drivevec;
6536 rc = mParent->host()->COMGETTER(DVDDrives)(ComSafeArrayAsOutParam(drivevec));
6537 if (SUCCEEDED(rc))
6538 {
6539 for (size_t i = 0; i < drivevec.size(); ++i)
6540 {
6541 Bstr hostDriveSrc(dev.strHostDriveSrc);
6542 /// @todo eliminate this conversion
6543 ComObjPtr<Medium> med = (Medium *)drivevec[i];
6544 if ( hostDriveSrc == med->getName()
6545 || hostDriveSrc == med->getLocation())
6546 {
6547 medium = med;
6548 break;
6549 }
6550 }
6551 }
6552 }
6553 break;
6554
6555 case DeviceType_HardDisk:
6556 {
6557 /* find a hard disk by UUID */
6558 rc = mParent->findHardDisk(&dev.uuid, NULL, true /* aDoSetError */, &medium);
6559 if (FAILED(rc))
6560 {
6561 VBoxClsID clsid = getClassID();
6562 if (clsid == clsidSnapshotMachine)
6563 {
6564 // wrap another error message around the "cannot find hard disk" set by findHardDisk
6565 // so the user knows that the bad disk is in a snapshot somewhere
6566 com::ErrorInfo info;
6567 return setError(E_FAIL,
6568 tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
6569 aSnapshotId->raw(),
6570 info.getText().raw());
6571 }
6572 else
6573 return rc;
6574 }
6575
6576 AutoWriteLock hdLock(medium COMMA_LOCKVAL_SRC_POS);
6577
6578 if (medium->getType() == MediumType_Immutable)
6579 {
6580 if (getClassID() == clsidSnapshotMachine)
6581 return setError(E_FAIL,
6582 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
6583 "of the virtual machine '%ls' ('%s')"),
6584 medium->getLocationFull().raw(),
6585 dev.uuid.raw(),
6586 aSnapshotId->raw(),
6587 mUserData->mName.raw(),
6588 mData->m_strConfigFileFull.raw());
6589
6590 return setError(E_FAIL,
6591 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%ls' ('%s')"),
6592 medium->getLocationFull().raw(),
6593 dev.uuid.raw(),
6594 mUserData->mName.raw(),
6595 mData->m_strConfigFileFull.raw());
6596 }
6597
6598 if ( getClassID() != clsidSnapshotMachine
6599 && medium->getChildren().size() != 0
6600 )
6601 return setError(E_FAIL,
6602 tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%ls' ('%s') "
6603 "because it has %d differencing child hard disks"),
6604 medium->getLocationFull().raw(),
6605 dev.uuid.raw(),
6606 mUserData->mName.raw(),
6607 mData->m_strConfigFileFull.raw(),
6608 medium->getChildren().size());
6609
6610 if (findAttachment(mMediaData->mAttachments,
6611 medium))
6612 return setError(E_FAIL,
6613 tr("Hard disk '%s' with UUID {%RTuuid} is already attached to the virtual machine '%ls' ('%s')"),
6614 medium->getLocationFull().raw(),
6615 dev.uuid.raw(),
6616 mUserData->mName.raw(),
6617 mData->m_strConfigFileFull.raw());
6618
6619 break;
6620 }
6621
6622 default:
6623 return setError(E_FAIL,
6624 tr("Device with unknown type is attached to the virtual machine '%s' ('%s')"),
6625 medium->getLocationFull().raw(),
6626 mUserData->mName.raw(),
6627 mData->m_strConfigFileFull.raw());
6628 }
6629
6630 if (FAILED(rc))
6631 break;
6632
6633 const Bstr controllerName = aStorageController->getName();
6634 ComObjPtr<MediumAttachment> pAttachment;
6635 pAttachment.createObject();
6636 rc = pAttachment->init(this,
6637 medium,
6638 controllerName,
6639 dev.lPort,
6640 dev.lDevice,
6641 dev.deviceType,
6642 dev.fPassThrough);
6643 if (FAILED(rc)) break;
6644
6645 /* associate the medium with this machine and snapshot */
6646 if (!medium.isNull())
6647 {
6648 if (getClassID() == clsidSnapshotMachine)
6649 rc = medium->attachTo(mData->mUuid, *aSnapshotId);
6650 else
6651 rc = medium->attachTo(mData->mUuid);
6652 }
6653
6654 if (FAILED(rc))
6655 break;
6656
6657 /* back up mMediaData to let registeredInit() properly rollback on failure
6658 * (= limited accessibility) */
6659 mMediaData.backup();
6660 mMediaData->mAttachments.push_back(pAttachment);
6661 }
6662
6663 return rc;
6664}
6665
6666/**
6667 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
6668 *
6669 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
6670 * @param aSnapshot where to return the found snapshot
6671 * @param aSetError true to set extended error info on failure
6672 */
6673HRESULT Machine::findSnapshot(const Guid &aId,
6674 ComObjPtr<Snapshot> &aSnapshot,
6675 bool aSetError /* = false */)
6676{
6677 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
6678
6679 if (!mData->mFirstSnapshot)
6680 {
6681 if (aSetError)
6682 return setError(E_FAIL,
6683 tr("This machine does not have any snapshots"));
6684 return E_FAIL;
6685 }
6686
6687 if (aId.isEmpty())
6688 aSnapshot = mData->mFirstSnapshot;
6689 else
6690 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aId);
6691
6692 if (!aSnapshot)
6693 {
6694 if (aSetError)
6695 return setError(E_FAIL,
6696 tr("Could not find a snapshot with UUID {%s}"),
6697 aId.toString().raw());
6698 return E_FAIL;
6699 }
6700
6701 return S_OK;
6702}
6703
6704/**
6705 * Returns the snapshot with the given name or fails of no such snapshot.
6706 *
6707 * @param aName snapshot name to find
6708 * @param aSnapshot where to return the found snapshot
6709 * @param aSetError true to set extended error info on failure
6710 */
6711HRESULT Machine::findSnapshot(IN_BSTR aName,
6712 ComObjPtr<Snapshot> &aSnapshot,
6713 bool aSetError /* = false */)
6714{
6715 AssertReturn(aName, E_INVALIDARG);
6716
6717 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
6718
6719 if (!mData->mFirstSnapshot)
6720 {
6721 if (aSetError)
6722 return setError(VBOX_E_OBJECT_NOT_FOUND,
6723 tr("This machine does not have any snapshots"));
6724 return VBOX_E_OBJECT_NOT_FOUND;
6725 }
6726
6727 aSnapshot = mData->mFirstSnapshot->findChildOrSelf (aName);
6728
6729 if (!aSnapshot)
6730 {
6731 if (aSetError)
6732 return setError(VBOX_E_OBJECT_NOT_FOUND,
6733 tr("Could not find a snapshot named '%ls'"), aName);
6734 return VBOX_E_OBJECT_NOT_FOUND;
6735 }
6736
6737 return S_OK;
6738}
6739
6740/**
6741 * Returns a storage controller object with the given name.
6742 *
6743 * @param aName storage controller name to find
6744 * @param aStorageController where to return the found storage controller
6745 * @param aSetError true to set extended error info on failure
6746 */
6747HRESULT Machine::getStorageControllerByName(const Utf8Str &aName,
6748 ComObjPtr<StorageController> &aStorageController,
6749 bool aSetError /* = false */)
6750{
6751 AssertReturn (!aName.isEmpty(), E_INVALIDARG);
6752
6753 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
6754 it != mStorageControllers->end();
6755 ++it)
6756 {
6757 if ((*it)->getName() == aName)
6758 {
6759 aStorageController = (*it);
6760 return S_OK;
6761 }
6762 }
6763
6764 if (aSetError)
6765 return setError(VBOX_E_OBJECT_NOT_FOUND,
6766 tr("Could not find a storage controller named '%s'"),
6767 aName.raw());
6768 return VBOX_E_OBJECT_NOT_FOUND;
6769}
6770
6771HRESULT Machine::getMediumAttachmentsOfController(CBSTR aName,
6772 MediaData::AttachmentList &atts)
6773{
6774 AutoCaller autoCaller(this);
6775 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6776
6777 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6778
6779 for (MediaData::AttachmentList::iterator it = mMediaData->mAttachments.begin();
6780 it != mMediaData->mAttachments.end();
6781 ++it)
6782 {
6783 if ((*it)->getControllerName() == aName)
6784 atts.push_back(*it);
6785 }
6786
6787 return S_OK;
6788}
6789
6790/**
6791 * Helper for #saveSettings. Cares about renaming the settings directory and
6792 * file if the machine name was changed and about creating a new settings file
6793 * if this is a new machine.
6794 *
6795 * @note Must be never called directly but only from #saveSettings().
6796 *
6797 * @param aRenamed receives |true| if the name was changed and the settings
6798 * file was renamed as a result, or |false| otherwise. The
6799 * value makes sense only on success.
6800 * @param aNew receives |true| if a virgin settings file was created.
6801 */
6802HRESULT Machine::prepareSaveSettings(bool &aRenamed,
6803 bool &aNew)
6804{
6805 /* Note: tecnhically, mParent needs to be locked only when the machine is
6806 * registered (see prepareSaveSettings() for details) but we don't
6807 * currently differentiate it in callers of saveSettings() so we don't
6808 * make difference here too. */
6809 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
6810 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
6811
6812 HRESULT rc = S_OK;
6813
6814 aRenamed = false;
6815
6816 /* if we're ready and isConfigLocked() is FALSE then it means
6817 * that no config file exists yet (we will create a virgin one) */
6818 aNew = !mData->m_pMachineConfigFile->fileExists();
6819
6820 /* attempt to rename the settings file if machine name is changed */
6821 if ( mUserData->mNameSync
6822 && mUserData.isBackedUp()
6823 && mUserData.backedUpData()->mName != mUserData->mName
6824 )
6825 {
6826 aRenamed = true;
6827
6828 bool dirRenamed = false;
6829 bool fileRenamed = false;
6830
6831 Utf8Str configFile, newConfigFile;
6832 Utf8Str configDir, newConfigDir;
6833
6834 do
6835 {
6836 int vrc = VINF_SUCCESS;
6837
6838 Utf8Str name = mUserData.backedUpData()->mName;
6839 Utf8Str newName = mUserData->mName;
6840
6841 configFile = mData->m_strConfigFileFull;
6842
6843 /* first, rename the directory if it matches the machine name */
6844 configDir = configFile;
6845 configDir.stripFilename();
6846 newConfigDir = configDir;
6847 if (!strcmp(RTPathFilename(configDir.c_str()), name.c_str()))
6848 {
6849 newConfigDir.stripFilename();
6850 newConfigDir = Utf8StrFmt ("%s%c%s",
6851 newConfigDir.raw(), RTPATH_DELIMITER, newName.raw());
6852 /* new dir and old dir cannot be equal here because of 'if'
6853 * above and because name != newName */
6854 Assert (configDir != newConfigDir);
6855 if (!aNew)
6856 {
6857 /* perform real rename only if the machine is not new */
6858 vrc = RTPathRename (configDir.raw(), newConfigDir.raw(), 0);
6859 if (RT_FAILURE(vrc))
6860 {
6861 rc = setError(E_FAIL,
6862 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
6863 configDir.raw(),
6864 newConfigDir.raw(),
6865 vrc);
6866 break;
6867 }
6868 dirRenamed = true;
6869 }
6870 }
6871
6872 newConfigFile = Utf8StrFmt ("%s%c%s.xml",
6873 newConfigDir.raw(), RTPATH_DELIMITER, newName.raw());
6874
6875 /* then try to rename the settings file itself */
6876 if (newConfigFile != configFile)
6877 {
6878 /* get the path to old settings file in renamed directory */
6879 configFile = Utf8StrFmt("%s%c%s",
6880 newConfigDir.raw(),
6881 RTPATH_DELIMITER,
6882 RTPathFilename(configFile.c_str()));
6883 if (!aNew)
6884 {
6885 /* perform real rename only if the machine is not new */
6886 vrc = RTFileRename (configFile.raw(), newConfigFile.raw(), 0);
6887 if (RT_FAILURE(vrc))
6888 {
6889 rc = setError(E_FAIL,
6890 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
6891 configFile.raw(),
6892 newConfigFile.raw(),
6893 vrc);
6894 break;
6895 }
6896 fileRenamed = true;
6897 }
6898 }
6899
6900 /* update m_strConfigFileFull amd mConfigFile */
6901 Utf8Str oldConfigFileFull = mData->m_strConfigFileFull;
6902 Utf8Str oldConfigFile = mData->m_strConfigFile;
6903 mData->m_strConfigFileFull = newConfigFile;
6904 /* try to get the relative path for mConfigFile */
6905 Utf8Str path = newConfigFile;
6906 mParent->calculateRelativePath (path, path);
6907 mData->m_strConfigFile = path;
6908
6909 /* last, try to update the global settings with the new path */
6910 if (mData->mRegistered)
6911 {
6912 rc = mParent->updateSettings(configDir.c_str(), newConfigDir.c_str());
6913 if (FAILED(rc))
6914 {
6915 /* revert to old values */
6916 mData->m_strConfigFileFull = oldConfigFileFull;
6917 mData->m_strConfigFile = oldConfigFile;
6918 break;
6919 }
6920 }
6921
6922 /* update the snapshot folder */
6923 path = mUserData->mSnapshotFolderFull;
6924 if (RTPathStartsWith(path.c_str(), configDir.c_str()))
6925 {
6926 path = Utf8StrFmt("%s%s", newConfigDir.raw(),
6927 path.raw() + configDir.length());
6928 mUserData->mSnapshotFolderFull = path;
6929 calculateRelativePath (path, path);
6930 mUserData->mSnapshotFolder = path;
6931 }
6932
6933 /* update the saved state file path */
6934 path = mSSData->mStateFilePath;
6935 if (RTPathStartsWith(path.c_str(), configDir.c_str()))
6936 {
6937 path = Utf8StrFmt("%s%s", newConfigDir.raw(),
6938 path.raw() + configDir.length());
6939 mSSData->mStateFilePath = path;
6940 }
6941
6942 /* Update saved state file paths of all online snapshots.
6943 * Note that saveSettings() will recognize name change
6944 * and will save all snapshots in this case. */
6945 if (mData->mFirstSnapshot)
6946 mData->mFirstSnapshot->updateSavedStatePaths(configDir.c_str(),
6947 newConfigDir.c_str());
6948 }
6949 while (0);
6950
6951 if (FAILED(rc))
6952 {
6953 /* silently try to rename everything back */
6954 if (fileRenamed)
6955 RTFileRename(newConfigFile.raw(), configFile.raw(), 0);
6956 if (dirRenamed)
6957 RTPathRename(newConfigDir.raw(), configDir.raw(), 0);
6958 }
6959
6960 if (FAILED(rc)) return rc;
6961 }
6962
6963 if (aNew)
6964 {
6965 /* create a virgin config file */
6966 int vrc = VINF_SUCCESS;
6967
6968 /* ensure the settings directory exists */
6969 Utf8Str path(mData->m_strConfigFileFull);
6970 path.stripFilename();
6971 if (!RTDirExists(path.c_str()))
6972 {
6973 vrc = RTDirCreateFullPath(path.c_str(), 0777);
6974 if (RT_FAILURE(vrc))
6975 {
6976 return setError(E_FAIL,
6977 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
6978 path.raw(),
6979 vrc);
6980 }
6981 }
6982
6983 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
6984 path = Utf8Str(mData->m_strConfigFileFull);
6985 vrc = RTFileOpen(&mData->mHandleCfgFile, path.c_str(),
6986 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
6987 if (RT_FAILURE(vrc))
6988 {
6989 mData->mHandleCfgFile = NIL_RTFILE;
6990 return setError(E_FAIL,
6991 tr("Could not create the settings file '%s' (%Rrc)"),
6992 path.raw(),
6993 vrc);
6994 }
6995 RTFileClose(mData->mHandleCfgFile);
6996 }
6997
6998 return rc;
6999}
7000
7001/**
7002 * Saves and commits machine data, user data and hardware data.
7003 *
7004 * Note that on failure, the data remains uncommitted.
7005 *
7006 * @a aFlags may combine the following flags:
7007 *
7008 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
7009 * Used when saving settings after an operation that makes them 100%
7010 * correspond to the settings from the current snapshot.
7011 * - SaveS_InformCallbacksAnyway: Callbacks will be informed even if
7012 * #isReallyModified() returns false. This is necessary for cases when we
7013 * change machine data directly, not through the backup()/commit() mechanism.
7014 *
7015 * @note Must be called from under mParent write lock (sometimes needed by
7016 * #prepareSaveSettings()) and this object's write lock. Locks children for
7017 * writing. There is one exception when mParent is unused and therefore may be
7018 * left unlocked: if this machine is an unregistered one.
7019 */
7020HRESULT Machine::saveSettings(int aFlags /*= 0*/)
7021{
7022 LogFlowThisFuncEnter();
7023
7024 /* Note: tecnhically, mParent needs to be locked only when the machine is
7025 * registered (see prepareSaveSettings() for details) but we don't
7026 * currently differentiate it in callers of saveSettings() so we don't
7027 * make difference here too. */
7028 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
7029 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7030
7031 /* make sure child objects are unable to modify the settings while we are
7032 * saving them */
7033 ensureNoStateDependencies();
7034
7035 AssertReturn(getClassID() == clsidMachine || getClassID() == clsidSessionMachine, E_FAIL);
7036
7037 BOOL currentStateModified = mData->mCurrentStateModified;
7038 bool settingsModified;
7039
7040 if (!(aFlags & SaveS_ResetCurStateModified) && !currentStateModified)
7041 {
7042 /* We ignore changes to user data when setting mCurrentStateModified
7043 * because the current state will not differ from the current snapshot
7044 * if only user data has been changed (user data is shared by all
7045 * snapshots). */
7046 currentStateModified = isReallyModified (true /* aIgnoreUserData */);
7047 settingsModified = mUserData.hasActualChanges() || currentStateModified;
7048 }
7049 else
7050 {
7051 if (aFlags & SaveS_ResetCurStateModified)
7052 currentStateModified = FALSE;
7053 settingsModified = isReallyModified();
7054 }
7055
7056 HRESULT rc = S_OK;
7057
7058 /* First, prepare to save settings. It will care about renaming the
7059 * settings directory and file if the machine name was changed and about
7060 * creating a new settings file if this is a new machine. */
7061 bool isRenamed = false;
7062 bool isNew = false;
7063 rc = prepareSaveSettings(isRenamed, isNew);
7064 if (FAILED(rc)) return rc;
7065
7066 try
7067 {
7068 mData->m_pMachineConfigFile->uuid = mData->mUuid;
7069 mData->m_pMachineConfigFile->strName = mUserData->mName;
7070 mData->m_pMachineConfigFile->fNameSync = !!mUserData->mNameSync;
7071 mData->m_pMachineConfigFile->strDescription = mUserData->mDescription;
7072 mData->m_pMachineConfigFile->strOsType = mUserData->mOSTypeId;
7073
7074 if ( mData->mMachineState == MachineState_Saved
7075 || mData->mMachineState == MachineState_Restoring
7076 // when deleting a snapshot we may or may not have a saved state in the current state,
7077 // so let's not assert here please
7078 || ( (mData->mMachineState == MachineState_DeletingSnapshot)
7079 && (!mSSData->mStateFilePath.isEmpty())
7080 )
7081 )
7082 {
7083 Assert(!mSSData->mStateFilePath.isEmpty());
7084 /* try to make the file name relative to the settings file dir */
7085 calculateRelativePath(mSSData->mStateFilePath, mData->m_pMachineConfigFile->strStateFile);
7086 }
7087 else
7088 {
7089 Assert(mSSData->mStateFilePath.isEmpty());
7090 mData->m_pMachineConfigFile->strStateFile.setNull();
7091 }
7092
7093 if (mData->mCurrentSnapshot)
7094 mData->m_pMachineConfigFile->uuidCurrentSnapshot = mData->mCurrentSnapshot->getId();
7095 else
7096 mData->m_pMachineConfigFile->uuidCurrentSnapshot.clear();
7097
7098 mData->m_pMachineConfigFile->strSnapshotFolder = mUserData->mSnapshotFolder;
7099 mData->m_pMachineConfigFile->fCurrentStateModified = !!currentStateModified;
7100 mData->m_pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
7101 mData->m_pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
7102/// @todo Live Migration: mData->m_pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
7103
7104 mData->m_pMachineConfigFile->fTeleporterEnabled = !!mUserData->mTeleporterEnabled;
7105 mData->m_pMachineConfigFile->uTeleporterPort = mUserData->mTeleporterPort;
7106 mData->m_pMachineConfigFile->strTeleporterAddress = mUserData->mTeleporterAddress;
7107 mData->m_pMachineConfigFile->strTeleporterPassword = mUserData->mTeleporterPassword;
7108
7109 mData->m_pMachineConfigFile->fRTCUseUTC = !!mUserData->mRTCUseUTC;
7110
7111 rc = saveHardware(mData->m_pMachineConfigFile->hardwareMachine);
7112 if (FAILED(rc)) throw rc;
7113
7114 rc = saveStorageControllers(mData->m_pMachineConfigFile->storageMachine);
7115 if (FAILED(rc)) throw rc;
7116
7117 // save snapshots
7118 rc = saveAllSnapshots();
7119 if (FAILED(rc)) throw rc;
7120
7121 // now spit it all out
7122 mData->m_pMachineConfigFile->write(mData->m_strConfigFileFull);
7123 }
7124 catch (HRESULT err)
7125 {
7126 /* we assume that error info is set by the thrower */
7127 rc = err;
7128 }
7129 catch (...)
7130 {
7131 rc = VirtualBox::handleUnexpectedExceptions (RT_SRC_POS);
7132 }
7133
7134 if (SUCCEEDED(rc))
7135 {
7136 commit();
7137
7138 /* memorize the new modified state */
7139 mData->mCurrentStateModified = currentStateModified;
7140 }
7141
7142 if (settingsModified || (aFlags & SaveS_InformCallbacksAnyway))
7143 {
7144 /* Fire the data change event, even on failure (since we've already
7145 * committed all data). This is done only for SessionMachines because
7146 * mutable Machine instances are always not registered (i.e. private
7147 * to the client process that creates them) and thus don't need to
7148 * inform callbacks. */
7149 if (getClassID() == clsidSessionMachine)
7150 mParent->onMachineDataChange(mData->mUuid);
7151 }
7152
7153 LogFlowThisFunc(("rc=%08X\n", rc));
7154 LogFlowThisFuncLeave();
7155 return rc;
7156}
7157
7158HRESULT Machine::saveAllSnapshots()
7159{
7160 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
7161
7162 HRESULT rc = S_OK;
7163
7164 try
7165 {
7166 mData->m_pMachineConfigFile->llFirstSnapshot.clear();
7167
7168 if (mData->mFirstSnapshot)
7169 {
7170 settings::Snapshot snapNew;
7171 mData->m_pMachineConfigFile->llFirstSnapshot.push_back(snapNew);
7172
7173 // get reference to the fresh copy of the snapshot on the list and
7174 // work on that copy directly to avoid excessive copying later
7175 settings::Snapshot &snap = mData->m_pMachineConfigFile->llFirstSnapshot.front();
7176
7177 rc = mData->mFirstSnapshot->saveSnapshot(snap, false /*aAttrsOnly*/);
7178 if (FAILED(rc)) throw rc;
7179 }
7180
7181// if (mType == IsSessionMachine)
7182// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
7183
7184 }
7185 catch (HRESULT err)
7186 {
7187 /* we assume that error info is set by the thrower */
7188 rc = err;
7189 }
7190 catch (...)
7191 {
7192 rc = VirtualBox::handleUnexpectedExceptions (RT_SRC_POS);
7193 }
7194
7195 return rc;
7196}
7197
7198/**
7199 * Saves the VM hardware configuration. It is assumed that the
7200 * given node is empty.
7201 *
7202 * @param aNode <Hardware> node to save the VM hardware confguration to.
7203 */
7204HRESULT Machine::saveHardware(settings::Hardware &data)
7205{
7206 HRESULT rc = S_OK;
7207
7208 try
7209 {
7210 /* The hardware version attribute (optional).
7211 Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
7212 if ( mHWData->mHWVersion == "1"
7213 && mSSData->mStateFilePath.isEmpty()
7214 )
7215 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. */
7216
7217 data.strVersion = mHWData->mHWVersion;
7218 data.uuid = mHWData->mHardwareUUID;
7219
7220 // CPU
7221 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
7222 data.fHardwareVirtExclusive = !!mHWData->mHWVirtExExclusive;
7223 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
7224 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
7225 data.fPAE = !!mHWData->mPAEEnabled;
7226 data.fSyntheticCpu = !!mHWData->mSyntheticCpu;
7227
7228 /* Standard and Extended CPUID leafs. */
7229 data.llCpuIdLeafs.clear();
7230 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); idx++)
7231 {
7232 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
7233 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
7234 }
7235 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); idx++)
7236 {
7237 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
7238 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
7239 }
7240
7241 data.cCPUs = mHWData->mCPUCount;
7242 data.fCpuHotPlug = mHWData->mCPUHotPlugEnabled;
7243
7244 data.llCpus.clear();
7245 if (data.fCpuHotPlug)
7246 {
7247 for (unsigned idx = 0; idx < data.cCPUs; idx++)
7248 {
7249 if (mHWData->mCPUAttached[idx])
7250 {
7251 settings::Cpu cpu;
7252 cpu.ulId = idx;
7253 data.llCpus.push_back(cpu);
7254 }
7255 }
7256 }
7257
7258 // memory
7259 data.ulMemorySizeMB = mHWData->mMemorySize;
7260
7261 // firmware
7262 data.firmwareType = mHWData->mFirmwareType;
7263
7264 // boot order
7265 data.mapBootOrder.clear();
7266 for (size_t i = 0;
7267 i < RT_ELEMENTS(mHWData->mBootOrder);
7268 ++i)
7269 data.mapBootOrder[i] = mHWData->mBootOrder[i];
7270
7271 // display
7272 data.ulVRAMSizeMB = mHWData->mVRAMSize;
7273 data.cMonitors = mHWData->mMonitorCount;
7274 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
7275 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
7276
7277#ifdef VBOX_WITH_VRDP
7278 /* VRDP settings (optional) */
7279 rc = mVRDPServer->saveSettings(data.vrdpSettings);
7280 if (FAILED(rc)) throw rc;
7281#endif
7282
7283 /* BIOS (required) */
7284 rc = mBIOSSettings->saveSettings(data.biosSettings);
7285 if (FAILED(rc)) throw rc;
7286
7287 /* USB Controller (required) */
7288 rc = mUSBController->saveSettings(data.usbController);
7289 if (FAILED(rc)) throw rc;
7290
7291 /* Network adapters (required) */
7292 data.llNetworkAdapters.clear();
7293 for (ULONG slot = 0;
7294 slot < RT_ELEMENTS(mNetworkAdapters);
7295 ++slot)
7296 {
7297 settings::NetworkAdapter nic;
7298 nic.ulSlot = slot;
7299 rc = mNetworkAdapters[slot]->saveSettings(nic);
7300 if (FAILED(rc)) throw rc;
7301
7302 data.llNetworkAdapters.push_back(nic);
7303 }
7304
7305 /* Serial ports */
7306 data.llSerialPorts.clear();
7307 for (ULONG slot = 0;
7308 slot < RT_ELEMENTS(mSerialPorts);
7309 ++slot)
7310 {
7311 settings::SerialPort s;
7312 s.ulSlot = slot;
7313 rc = mSerialPorts[slot]->saveSettings(s);
7314 if (FAILED(rc)) return rc;
7315
7316 data.llSerialPorts.push_back(s);
7317 }
7318
7319 /* Parallel ports */
7320 data.llParallelPorts.clear();
7321 for (ULONG slot = 0;
7322 slot < RT_ELEMENTS(mParallelPorts);
7323 ++slot)
7324 {
7325 settings::ParallelPort p;
7326 p.ulSlot = slot;
7327 rc = mParallelPorts[slot]->saveSettings(p);
7328 if (FAILED(rc)) return rc;
7329
7330 data.llParallelPorts.push_back(p);
7331 }
7332
7333 /* Audio adapter */
7334 rc = mAudioAdapter->saveSettings(data.audioAdapter);
7335 if (FAILED(rc)) return rc;
7336
7337 /* Shared folders */
7338 data.llSharedFolders.clear();
7339 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
7340 it != mHWData->mSharedFolders.end();
7341 ++it)
7342 {
7343 ComObjPtr<SharedFolder> pFolder = *it;
7344 settings::SharedFolder sf;
7345 sf.strName = pFolder->getName();
7346 sf.strHostPath = pFolder->getHostPath();
7347 sf.fWritable = !!pFolder->isWritable();
7348
7349 data.llSharedFolders.push_back(sf);
7350 }
7351
7352 // clipboard
7353 data.clipboardMode = mHWData->mClipboardMode;
7354
7355 /* Guest */
7356 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
7357 data.ulStatisticsUpdateInterval = mHWData->mStatisticsUpdateInterval;
7358
7359 // guest properties
7360 data.llGuestProperties.clear();
7361#ifdef VBOX_WITH_GUEST_PROPS
7362 for (HWData::GuestPropertyList::const_iterator it = mHWData->mGuestProperties.begin();
7363 it != mHWData->mGuestProperties.end();
7364 ++it)
7365 {
7366 HWData::GuestProperty property = *it;
7367
7368 settings::GuestProperty prop;
7369 prop.strName = property.strName;
7370 prop.strValue = property.strValue;
7371 prop.timestamp = property.mTimestamp;
7372 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
7373 guestProp::writeFlags(property.mFlags, szFlags);
7374 prop.strFlags = szFlags;
7375
7376 data.llGuestProperties.push_back(prop);
7377 }
7378
7379 data.strNotificationPatterns = mHWData->mGuestPropertyNotificationPatterns;
7380#endif /* VBOX_WITH_GUEST_PROPS defined */
7381 }
7382 catch(std::bad_alloc &)
7383 {
7384 return E_OUTOFMEMORY;
7385 }
7386
7387 AssertComRC(rc);
7388 return rc;
7389}
7390
7391/**
7392 * Saves the storage controller configuration.
7393 *
7394 * @param aNode <StorageControllers> node to save the VM hardware confguration to.
7395 */
7396HRESULT Machine::saveStorageControllers(settings::Storage &data)
7397{
7398 data.llStorageControllers.clear();
7399
7400 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
7401 it != mStorageControllers->end();
7402 ++it)
7403 {
7404 HRESULT rc;
7405 ComObjPtr<StorageController> pCtl = *it;
7406
7407 settings::StorageController ctl;
7408 ctl.strName = pCtl->getName();
7409 ctl.controllerType = pCtl->getControllerType();
7410 ctl.storageBus = pCtl->getStorageBus();
7411 ctl.ulInstance = pCtl->getInstance();
7412
7413 /* Save the port count. */
7414 ULONG portCount;
7415 rc = pCtl->COMGETTER(PortCount)(&portCount);
7416 ComAssertComRCRet(rc, rc);
7417 ctl.ulPortCount = portCount;
7418
7419 /* Save IDE emulation settings. */
7420 if (ctl.controllerType == StorageControllerType_IntelAhci)
7421 {
7422 if ( (FAILED(rc = pCtl->GetIDEEmulationPort(0, (LONG*)&ctl.lIDE0MasterEmulationPort)))
7423 || (FAILED(rc = pCtl->GetIDEEmulationPort(1, (LONG*)&ctl.lIDE0SlaveEmulationPort)))
7424 || (FAILED(rc = pCtl->GetIDEEmulationPort(2, (LONG*)&ctl.lIDE1MasterEmulationPort)))
7425 || (FAILED(rc = pCtl->GetIDEEmulationPort(3, (LONG*)&ctl.lIDE1SlaveEmulationPort)))
7426 )
7427 ComAssertComRCRet(rc, rc);
7428 }
7429
7430 /* save the devices now. */
7431 rc = saveStorageDevices(pCtl, ctl);
7432 ComAssertComRCRet(rc, rc);
7433
7434 data.llStorageControllers.push_back(ctl);
7435 }
7436
7437 return S_OK;
7438}
7439
7440/**
7441 * Saves the hard disk confguration.
7442 */
7443HRESULT Machine::saveStorageDevices(ComObjPtr<StorageController> aStorageController,
7444 settings::StorageController &data)
7445{
7446 MediaData::AttachmentList atts;
7447
7448 HRESULT rc = getMediumAttachmentsOfController(Bstr(aStorageController->getName()), atts);
7449 if (FAILED(rc)) return rc;
7450
7451 data.llAttachedDevices.clear();
7452 for (MediaData::AttachmentList::const_iterator it = atts.begin();
7453 it != atts.end();
7454 ++it)
7455 {
7456 settings::AttachedDevice dev;
7457
7458 MediumAttachment *pAttach = *it;
7459 Medium *pMedium = pAttach->getMedium();
7460
7461 dev.deviceType = pAttach->getType();
7462 dev.lPort = pAttach->getPort();
7463 dev.lDevice = pAttach->getDevice();
7464 if (pMedium)
7465 {
7466 BOOL fHostDrive = FALSE;
7467 rc = pMedium->COMGETTER(HostDrive)(&fHostDrive);
7468 if (FAILED(rc))
7469 return rc;
7470 if (fHostDrive)
7471 dev.strHostDriveSrc = pMedium->getLocation();
7472 else
7473 dev.uuid = pMedium->getId();
7474 dev.fPassThrough = pAttach->getPassthrough();
7475 }
7476
7477 data.llAttachedDevices.push_back(dev);
7478 }
7479
7480 return S_OK;
7481}
7482
7483/**
7484 * Saves machine state settings as defined by aFlags
7485 * (SaveSTS_* values).
7486 *
7487 * @param aFlags Combination of SaveSTS_* flags.
7488 *
7489 * @note Locks objects for writing.
7490 */
7491HRESULT Machine::saveStateSettings(int aFlags)
7492{
7493 if (aFlags == 0)
7494 return S_OK;
7495
7496 AutoCaller autoCaller(this);
7497 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
7498
7499 /* This object's write lock is also necessary to serialize file access
7500 * (prevent concurrent reads and writes) */
7501 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7502
7503 HRESULT rc = S_OK;
7504
7505 Assert(mData->m_pMachineConfigFile);
7506
7507 try
7508 {
7509 if (aFlags & SaveSTS_CurStateModified)
7510 mData->m_pMachineConfigFile->fCurrentStateModified = true;
7511
7512 if (aFlags & SaveSTS_StateFilePath)
7513 {
7514 if (!mSSData->mStateFilePath.isEmpty())
7515 /* try to make the file name relative to the settings file dir */
7516 calculateRelativePath(mSSData->mStateFilePath, mData->m_pMachineConfigFile->strStateFile);
7517 else
7518 mData->m_pMachineConfigFile->strStateFile.setNull();
7519 }
7520
7521 if (aFlags & SaveSTS_StateTimeStamp)
7522 {
7523 Assert( mData->mMachineState != MachineState_Aborted
7524 || mSSData->mStateFilePath.isEmpty());
7525
7526 mData->m_pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
7527
7528 mData->m_pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
7529//@todo live migration mData->m_pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
7530 }
7531
7532 mData->m_pMachineConfigFile->write(mData->m_strConfigFileFull);
7533 }
7534 catch (...)
7535 {
7536 rc = VirtualBox::handleUnexpectedExceptions (RT_SRC_POS);
7537 }
7538
7539 return rc;
7540}
7541
7542/**
7543 * Creates differencing hard disks for all normal hard disks attached to this
7544 * machine and a new set of attachments to refer to created disks.
7545 *
7546 * Used when taking a snapshot or when discarding the current state.
7547 *
7548 * This method assumes that mMediaData contains the original hard disk attachments
7549 * it needs to create diffs for. On success, these attachments will be replaced
7550 * with the created diffs. On failure, #deleteImplicitDiffs() is implicitly
7551 * called to delete created diffs which will also rollback mMediaData and restore
7552 * whatever was backed up before calling this method.
7553 *
7554 * Attachments with non-normal hard disks are left as is.
7555 *
7556 * If @a aOnline is @c false then the original hard disks that require implicit
7557 * diffs will be locked for reading. Otherwise it is assumed that they are
7558 * already locked for writing (when the VM was started). Note that in the latter
7559 * case it is responsibility of the caller to lock the newly created diffs for
7560 * writing if this method succeeds.
7561 *
7562 * @param aFolder Folder where to create diff hard disks.
7563 * @param aProgress Progress object to run (must contain at least as
7564 * many operations left as the number of hard disks
7565 * attached).
7566 * @param aOnline Whether the VM was online prior to this operation.
7567 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
7568 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
7569 *
7570 * @note The progress object is not marked as completed, neither on success nor
7571 * on failure. This is a responsibility of the caller.
7572 *
7573 * @note Locks this object for writing.
7574 */
7575HRESULT Machine::createImplicitDiffs(const Bstr &aFolder,
7576 IProgress *aProgress,
7577 ULONG aWeight,
7578 bool aOnline,
7579 bool *pfNeedsSaveSettings)
7580{
7581 AssertReturn(!aFolder.isEmpty(), E_FAIL);
7582
7583 LogFlowThisFunc(("aFolder='%ls', aOnline=%d\n", aFolder.raw(), aOnline));
7584
7585 AutoCaller autoCaller(this);
7586 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
7587
7588 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7589
7590 /* must be in a protective state because we leave the lock below */
7591 AssertReturn( mData->mMachineState == MachineState_Saving
7592 || mData->mMachineState == MachineState_LiveSnapshotting
7593 || mData->mMachineState == MachineState_RestoringSnapshot
7594 || mData->mMachineState == MachineState_DeletingSnapshot
7595 , E_FAIL);
7596
7597 HRESULT rc = S_OK;
7598
7599 MediaList lockedMedia;
7600
7601 try
7602 {
7603 if (!aOnline)
7604 {
7605 /* lock all attached hard disks early to detect "in use"
7606 * situations before creating actual diffs */
7607 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
7608 it != mMediaData->mAttachments.end();
7609 ++it)
7610 {
7611 MediumAttachment* pAtt = *it;
7612 if (pAtt->getType() == DeviceType_HardDisk)
7613 {
7614 Medium* pHD = pAtt->getMedium();
7615 Assert(pHD);
7616 rc = pHD->LockRead (NULL);
7617 if (FAILED(rc)) throw rc;
7618 lockedMedia.push_back(pHD);
7619 }
7620 }
7621 }
7622
7623 /* remember the current list (note that we don't use backup() since
7624 * mMediaData may be already backed up) */
7625 MediaData::AttachmentList atts = mMediaData->mAttachments;
7626
7627 /* start from scratch */
7628 mMediaData->mAttachments.clear();
7629
7630 /* go through remembered attachments and create diffs for normal hard
7631 * disks and attach them */
7632 for (MediaData::AttachmentList::const_iterator it = atts.begin();
7633 it != atts.end();
7634 ++it)
7635 {
7636 MediumAttachment* pAtt = *it;
7637
7638 DeviceType_T devType = pAtt->getType();
7639 Medium* medium = pAtt->getMedium();
7640
7641 if ( devType != DeviceType_HardDisk
7642 || medium == NULL
7643 || medium->getType() != MediumType_Normal)
7644 {
7645 /* copy the attachment as is */
7646
7647 /** @todo the progress object created in Console::TakeSnaphot
7648 * only expects operations for hard disks. Later other
7649 * device types need to show up in the progress as well. */
7650 if (devType == DeviceType_HardDisk)
7651 {
7652 if (medium == NULL)
7653 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")),
7654 aWeight); // weight
7655 else
7656 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
7657 medium->getBase()->getName().raw()),
7658 aWeight); // weight
7659 }
7660
7661 mMediaData->mAttachments.push_back(pAtt);
7662 continue;
7663 }
7664
7665 /* need a diff */
7666 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
7667 medium->getBase()->getName().raw()),
7668 aWeight); // weight
7669
7670 ComObjPtr<Medium> diff;
7671 diff.createObject();
7672 rc = diff->init(mParent,
7673 medium->preferredDiffFormat().raw(),
7674 BstrFmt("%ls"RTPATH_SLASH_STR,
7675 mUserData->mSnapshotFolderFull.raw()).raw(),
7676 pfNeedsSaveSettings);
7677 if (FAILED(rc)) throw rc;
7678
7679 /* leave the lock before the potentially lengthy operation */
7680 alock.leave();
7681
7682 rc = medium->createDiffStorageAndWait(diff,
7683 MediumVariant_Standard,
7684 pfNeedsSaveSettings);
7685
7686 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
7687 * the push_back? Looks like we're going to leave medium with the
7688 * wrong kind of lock (general issue with if we fail anywhere at all)
7689 * and an orphaned VDI in the snapshots folder. */
7690 // at this point, the old image is still locked for writing, but instead
7691 // we need the new diff image locked for writing and lock the previously
7692 // current one for reading only
7693 if (aOnline)
7694 {
7695 diff->LockWrite(NULL);
7696 mData->mSession.mLockedMedia.push_back(Data::Session::LockedMedia::value_type(ComPtr<IMedium>(diff), true));
7697 medium->UnlockWrite(NULL);
7698 medium->LockRead(NULL);
7699 mData->mSession.mLockedMedia.push_back(Data::Session::LockedMedia::value_type(ComPtr<IMedium>(medium), false));
7700 }
7701
7702 if (FAILED(rc)) throw rc;
7703
7704 alock.enter();
7705
7706 rc = diff->attachTo(mData->mUuid);
7707 AssertComRCThrowRC(rc);
7708
7709 /* add a new attachment */
7710 ComObjPtr<MediumAttachment> attachment;
7711 attachment.createObject();
7712 rc = attachment->init(this,
7713 diff,
7714 pAtt->getControllerName(),
7715 pAtt->getPort(),
7716 pAtt->getDevice(),
7717 DeviceType_HardDisk,
7718 true /* aImplicit */);
7719 if (FAILED(rc)) throw rc;
7720
7721 mMediaData->mAttachments.push_back(attachment);
7722 }
7723 }
7724 catch (HRESULT aRC) { rc = aRC; }
7725
7726 /* unlock all hard disks we locked */
7727 if (!aOnline)
7728 {
7729 ErrorInfoKeeper eik;
7730
7731 for (MediaList::const_iterator it = lockedMedia.begin();
7732 it != lockedMedia.end();
7733 ++it)
7734 {
7735 HRESULT rc2 = (*it)->UnlockRead(NULL);
7736 AssertComRC(rc2);
7737 }
7738 }
7739
7740 if (FAILED(rc))
7741 {
7742 MultiResultRef mrc (rc);
7743
7744 mrc = deleteImplicitDiffs(pfNeedsSaveSettings);
7745 }
7746
7747 return rc;
7748}
7749
7750/**
7751 * Deletes implicit differencing hard disks created either by
7752 * #createImplicitDiffs() or by #AttachMedium() and rolls back mMediaData.
7753 *
7754 * Note that to delete hard disks created by #AttachMedium() this method is
7755 * called from #fixupMedia() when the changes are rolled back.
7756 *
7757 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
7758 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
7759 *
7760 * @note Locks this object for writing.
7761 */
7762HRESULT Machine::deleteImplicitDiffs(bool *pfNeedsSaveSettings)
7763{
7764 AutoCaller autoCaller(this);
7765 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
7766
7767 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7768 LogFlowThisFuncEnter();
7769
7770 AssertReturn(mMediaData.isBackedUp(), E_FAIL);
7771
7772 HRESULT rc = S_OK;
7773
7774 MediaData::AttachmentList implicitAtts;
7775
7776 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
7777
7778 /* enumerate new attachments */
7779 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
7780 it != mMediaData->mAttachments.end();
7781 ++it)
7782 {
7783 ComObjPtr<Medium> hd = (*it)->getMedium();
7784 if (hd.isNull())
7785 continue;
7786
7787 if ((*it)->isImplicit())
7788 {
7789 /* deassociate and mark for deletion */
7790 LogFlowThisFunc(("Detaching '%s', pending deletion\n", (*it)->getLogName()));
7791 rc = hd->detachFrom(mData->mUuid);
7792 AssertComRC(rc);
7793 implicitAtts.push_back (*it);
7794 continue;
7795 }
7796
7797 /* was this hard disk attached before? */
7798 if (!findAttachment(oldAtts, hd))
7799 {
7800 /* no: de-associate */
7801 LogFlowThisFunc(("Detaching '%s', no deletion\n", (*it)->getLogName()));
7802 rc = hd->detachFrom(mData->mUuid);
7803 AssertComRC(rc);
7804 continue;
7805 }
7806 LogFlowThisFunc(("Not detaching '%s'\n", (*it)->getLogName()));
7807 }
7808
7809 /* rollback hard disk changes */
7810 mMediaData.rollback();
7811
7812 MultiResult mrc (S_OK);
7813
7814 /* delete unused implicit diffs */
7815 if (implicitAtts.size() != 0)
7816 {
7817 /* will leave the lock before the potentially lengthy
7818 * operation, so protect with the special state (unless already
7819 * protected) */
7820 MachineState_T oldState = mData->mMachineState;
7821 if ( oldState != MachineState_Saving
7822 && oldState != MachineState_LiveSnapshotting
7823 && oldState != MachineState_RestoringSnapshot
7824 && oldState != MachineState_DeletingSnapshot
7825 )
7826 setMachineState (MachineState_SettingUp);
7827
7828 alock.leave();
7829
7830 for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin();
7831 it != implicitAtts.end();
7832 ++it)
7833 {
7834 LogFlowThisFunc(("Deleting '%s'\n", (*it)->getLogName()));
7835 ComObjPtr<Medium> hd = (*it)->getMedium();
7836
7837 rc = hd->deleteStorageAndWait(NULL /*aProgress*/, pfNeedsSaveSettings);
7838#if 1 /* HACK ALERT: Just make it kind of work */ /** @todo Fix this hack properly. The LockWrite / UnlockWrite / LockRead changes aren't undone! */
7839 if (rc == VBOX_E_INVALID_OBJECT_STATE)
7840 {
7841 LogFlowFunc(("Applying unlock hack on '%s'! FIXME!\n", (*it)->getLogName()));
7842 hd->UnlockWrite(NULL);
7843 rc = hd->deleteStorageAndWait(NULL /*aProgress*/, pfNeedsSaveSettings);
7844 }
7845#endif
7846 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, (*it)->getLogName(), hd->getLocationFull().c_str() ));
7847 mrc = rc;
7848 }
7849
7850 alock.enter();
7851
7852 if (mData->mMachineState == MachineState_SettingUp)
7853 {
7854 setMachineState (oldState);
7855 }
7856 }
7857
7858 return mrc;
7859}
7860
7861/**
7862 * Looks through the given list of media attachments for one with the given parameters
7863 * and returns it, or NULL if not found. The list is a parameter so that backup lists
7864 * can be searched as well if needed.
7865 *
7866 * @param list
7867 * @param aControllerName
7868 * @param aControllerPort
7869 * @param aDevice
7870 * @return
7871 */
7872MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
7873 IN_BSTR aControllerName,
7874 LONG aControllerPort,
7875 LONG aDevice)
7876{
7877 for (MediaData::AttachmentList::const_iterator it = ll.begin();
7878 it != ll.end();
7879 ++it)
7880 {
7881 MediumAttachment *pAttach = *it;
7882 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
7883 return pAttach;
7884 }
7885
7886 return NULL;
7887}
7888
7889/**
7890 * Looks through the given list of media attachments for one with the given parameters
7891 * and returns it, or NULL if not found. The list is a parameter so that backup lists
7892 * can be searched as well if needed.
7893 *
7894 * @param list
7895 * @param aControllerName
7896 * @param aControllerPort
7897 * @param aDevice
7898 * @return
7899 */
7900MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
7901 ComObjPtr<Medium> pMedium)
7902{
7903 for (MediaData::AttachmentList::const_iterator it = ll.begin();
7904 it != ll.end();
7905 ++it)
7906 {
7907 MediumAttachment *pAttach = *it;
7908 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
7909 if (pMediumThis.equalsTo(pMedium))
7910 return pAttach;
7911 }
7912
7913 return NULL;
7914}
7915
7916/**
7917 * Looks through the given list of media attachments for one with the given parameters
7918 * and returns it, or NULL if not found. The list is a parameter so that backup lists
7919 * can be searched as well if needed.
7920 *
7921 * @param list
7922 * @param aControllerName
7923 * @param aControllerPort
7924 * @param aDevice
7925 * @return
7926 */
7927MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
7928 Guid &id)
7929{
7930 for (MediaData::AttachmentList::const_iterator it = ll.begin();
7931 it != ll.end();
7932 ++it)
7933 {
7934 MediumAttachment *pAttach = *it;
7935 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
7936 if (pMediumThis->getId() == id)
7937 return pAttach;
7938 }
7939
7940 return NULL;
7941}
7942
7943/**
7944 * Perform deferred hard disk detachments.
7945 *
7946 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
7947 * backed up).
7948 *
7949 * If @a aOnline is @c true then this method will also unlock the old hard disks
7950 * for which the new implicit diffs were created and will lock these new diffs for
7951 * writing.
7952 *
7953 * @param aOnline Whether the VM was online prior to this operation.
7954 *
7955 * @note Locks this object for writing!
7956 */
7957void Machine::commitMedia(bool aOnline /*= false*/)
7958{
7959 AutoCaller autoCaller(this);
7960 AssertComRCReturnVoid (autoCaller.rc());
7961
7962 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7963
7964 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
7965
7966 HRESULT rc = S_OK;
7967
7968 /* no attach/detach operations -- nothing to do */
7969 if (!mMediaData.isBackedUp())
7970 return;
7971
7972 MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
7973
7974 /* enumerate new attachments */
7975 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
7976 it != mMediaData->mAttachments.end();
7977 ++it)
7978 {
7979 MediumAttachment *pAttach = *it;
7980
7981 pAttach->commit();
7982
7983 Medium* pMedium = pAttach->getMedium();
7984 bool fImplicit = pAttach->isImplicit();
7985
7986 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
7987 (pMedium) ? pMedium->getName().raw() : "NULL",
7988 fImplicit));
7989
7990 /** @todo convert all this Machine-based voodoo to MediumAttachment
7991 * based commit logic. */
7992 if (fImplicit)
7993 {
7994 /* convert implicit attachment to normal */
7995 pAttach->setImplicit(false);
7996
7997 if ( aOnline
7998 && pMedium
7999 && pAttach->getType() == DeviceType_HardDisk
8000 )
8001 {
8002 rc = pMedium->LockWrite(NULL);
8003 AssertComRC(rc);
8004
8005 mData->mSession.mLockedMedia.push_back(
8006 Data::Session::LockedMedia::value_type(
8007 ComPtr<IMedium>(pMedium), true));
8008
8009 /* also, relock the old hard disk which is a base for the
8010 * new diff for reading if the VM is online */
8011
8012 ComObjPtr<Medium> parent = pMedium->getParent();
8013 /* make the relock atomic */
8014 AutoWriteLock parentLock(parent COMMA_LOCKVAL_SRC_POS);
8015 rc = parent->UnlockWrite(NULL);
8016 AssertComRC(rc);
8017 rc = parent->LockRead(NULL);
8018 AssertComRC(rc);
8019
8020 /* XXX actually we should replace the old entry in that
8021 * vector (write lock => read lock) but this would take
8022 * some effort. So lets just ignore the error code in
8023 * SessionMachine::unlockMedia(). */
8024 mData->mSession.mLockedMedia.push_back(
8025 Data::Session::LockedMedia::value_type (
8026 ComPtr<IMedium>(parent), false));
8027 }
8028
8029 continue;
8030 }
8031
8032 if (pMedium)
8033 {
8034 /* was this medium attached before? */
8035 for (MediaData::AttachmentList::iterator oldIt = oldAtts.begin();
8036 oldIt != oldAtts.end();
8037 ++oldIt)
8038 {
8039 MediumAttachment *pOldAttach = *oldIt;
8040 if (pOldAttach->getMedium().equalsTo(pMedium))
8041 {
8042 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->getName().raw()));
8043
8044 /* yes: remove from old to avoid de-association */
8045 oldAtts.erase(oldIt);
8046 break;
8047 }
8048 }
8049 }
8050 }
8051
8052 /* enumerate remaining old attachments and de-associate from the
8053 * current machine state */
8054 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
8055 it != oldAtts.end();
8056 ++it)
8057 {
8058 MediumAttachment *pAttach = *it;
8059 Medium* pMedium = pAttach->getMedium();
8060
8061 /* Detach only hard disks, since DVD/floppy media is detached
8062 * instantly in MountMedium. */
8063 if (pAttach->getType() == DeviceType_HardDisk && pMedium)
8064 {
8065 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->getName().raw()));
8066
8067 /* now de-associate from the current machine state */
8068 rc = pMedium->detachFrom(mData->mUuid);
8069 AssertComRC(rc);
8070
8071 if ( aOnline
8072 && pAttach->getType() == DeviceType_HardDisk)
8073 {
8074 /* unlock since not used anymore */
8075 MediumState_T state;
8076 rc = pMedium->UnlockWrite(&state);
8077 /* the disk may be alredy relocked for reading above */
8078 Assert (SUCCEEDED(rc) || state == MediumState_LockedRead);
8079 }
8080 }
8081 }
8082
8083 /* commit the hard disk changes */
8084 mMediaData.commit();
8085
8086 if (getClassID() == clsidSessionMachine)
8087 {
8088 /* attach new data to the primary machine and reshare it */
8089 mPeer->mMediaData.attach(mMediaData);
8090 }
8091
8092 return;
8093}
8094
8095/**
8096 * Perform deferred deletion of implicitly created diffs.
8097 *
8098 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
8099 * backed up).
8100 *
8101 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8102 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8103 *
8104 * @note Locks this object for writing!
8105 */
8106void Machine::rollbackMedia()
8107{
8108 AutoCaller autoCaller(this);
8109 AssertComRCReturnVoid (autoCaller.rc());
8110
8111 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8112
8113 LogFlowThisFunc(("Entering\n"));
8114
8115 HRESULT rc = S_OK;
8116
8117 /* no attach/detach operations -- nothing to do */
8118 if (!mMediaData.isBackedUp())
8119 return;
8120
8121 /* enumerate new attachments */
8122 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8123 it != mMediaData->mAttachments.end();
8124 ++it)
8125 {
8126 MediumAttachment *pAttach = *it;
8127 /* Fix up the backrefs for DVD/floppy media. */
8128 if (pAttach->getType() != DeviceType_HardDisk)
8129 {
8130 Medium* pMedium = pAttach->getMedium();
8131 if (pMedium)
8132 {
8133 rc = pMedium->detachFrom(mData->mUuid);
8134 AssertComRC(rc);
8135 }
8136 }
8137
8138 (*it)->rollback();
8139
8140 pAttach = *it;
8141 /* Fix up the backrefs for DVD/floppy media. */
8142 if (pAttach->getType() != DeviceType_HardDisk)
8143 {
8144 Medium* pMedium = pAttach->getMedium();
8145 if (pMedium)
8146 {
8147 rc = pMedium->attachTo(mData->mUuid);
8148 AssertComRC(rc);
8149 }
8150 }
8151 }
8152
8153 /** @todo convert all this Machine-based voodoo to MediumAttachment
8154 * based rollback logic. */
8155 // @todo r=dj the below totally fails if this gets called from Machine::rollback(),
8156 // which gets called if Machine::registeredInit() fails...
8157 deleteImplicitDiffs(NULL /*pfNeedsSaveSettings*/);
8158
8159 return;
8160}
8161
8162/**
8163 * Returns true if the settings file is located in the directory named exactly
8164 * as the machine. This will be true if the machine settings structure was
8165 * created by default in #openConfigLoader().
8166 *
8167 * @param aSettingsDir if not NULL, the full machine settings file directory
8168 * name will be assigned there.
8169 *
8170 * @note Doesn't lock anything.
8171 * @note Not thread safe (must be called from this object's lock).
8172 */
8173bool Machine::isInOwnDir(Utf8Str *aSettingsDir /* = NULL */)
8174{
8175 Utf8Str settingsDir = mData->m_strConfigFileFull;
8176 settingsDir.stripFilename();
8177 char *dirName = RTPathFilename(settingsDir.c_str());
8178
8179 AssertReturn(dirName, false);
8180
8181 /* if we don't rename anything on name change, return false shorlty */
8182 if (!mUserData->mNameSync)
8183 return false;
8184
8185 if (aSettingsDir)
8186 *aSettingsDir = settingsDir;
8187
8188 return Bstr (dirName) == mUserData->mName;
8189}
8190
8191/**
8192 * @note Locks objects for reading!
8193 */
8194bool Machine::isModified()
8195{
8196 AutoCaller autoCaller(this);
8197 AssertComRCReturn (autoCaller.rc(), false);
8198
8199 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
8200
8201 for (ULONG slot = 0; slot < RT_ELEMENTS (mNetworkAdapters); slot ++)
8202 if (mNetworkAdapters [slot] && mNetworkAdapters [slot]->isModified())
8203 return true;
8204
8205 for (ULONG slot = 0; slot < RT_ELEMENTS (mSerialPorts); slot ++)
8206 if (mSerialPorts [slot] && mSerialPorts [slot]->isModified())
8207 return true;
8208
8209 for (ULONG slot = 0; slot < RT_ELEMENTS (mParallelPorts); slot ++)
8210 if (mParallelPorts [slot] && mParallelPorts [slot]->isModified())
8211 return true;
8212
8213 if (!mStorageControllers.isNull())
8214 {
8215 for (StorageControllerList::const_iterator it =
8216 mStorageControllers->begin();
8217 it != mStorageControllers->end();
8218 ++it)
8219 {
8220 if ((*it)->isModified())
8221 return true;
8222 }
8223 }
8224
8225 return
8226 mUserData.isBackedUp() ||
8227 mHWData.isBackedUp() ||
8228 mMediaData.isBackedUp() ||
8229 mStorageControllers.isBackedUp() ||
8230#ifdef VBOX_WITH_VRDP
8231 (mVRDPServer && mVRDPServer->isModified()) ||
8232#endif
8233 (mAudioAdapter && mAudioAdapter->isModified()) ||
8234 (mUSBController && mUSBController->isModified()) ||
8235 (mBIOSSettings && mBIOSSettings->isModified());
8236}
8237
8238/**
8239 * Returns the logical OR of data.hasActualChanges() of this and all child
8240 * objects.
8241 *
8242 * @param aIgnoreUserData @c true to ignore changes to mUserData
8243 *
8244 * @note Locks objects for reading!
8245 */
8246bool Machine::isReallyModified (bool aIgnoreUserData /* = false */)
8247{
8248 AutoCaller autoCaller(this);
8249 AssertComRCReturn (autoCaller.rc(), false);
8250
8251 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
8252
8253 for (ULONG slot = 0; slot < RT_ELEMENTS (mNetworkAdapters); slot ++)
8254 if (mNetworkAdapters [slot] && mNetworkAdapters [slot]->isReallyModified())
8255 return true;
8256
8257 for (ULONG slot = 0; slot < RT_ELEMENTS (mSerialPorts); slot ++)
8258 if (mSerialPorts [slot] && mSerialPorts [slot]->isReallyModified())
8259 return true;
8260
8261 for (ULONG slot = 0; slot < RT_ELEMENTS (mParallelPorts); slot ++)
8262 if (mParallelPorts [slot] && mParallelPorts [slot]->isReallyModified())
8263 return true;
8264
8265 if (!mStorageControllers.isBackedUp())
8266 {
8267 /* see whether any of the devices has changed its data */
8268 for (StorageControllerList::const_iterator
8269 it = mStorageControllers->begin();
8270 it != mStorageControllers->end();
8271 ++it)
8272 {
8273 if ((*it)->isReallyModified())
8274 return true;
8275 }
8276 }
8277 else
8278 {
8279 if (mStorageControllers->size() != mStorageControllers.backedUpData()->size())
8280 return true;
8281 }
8282
8283 return
8284 (!aIgnoreUserData && mUserData.hasActualChanges()) ||
8285 mHWData.hasActualChanges() ||
8286 mMediaData.hasActualChanges() ||
8287 mStorageControllers.hasActualChanges() ||
8288#ifdef VBOX_WITH_VRDP
8289 (mVRDPServer && mVRDPServer->isReallyModified()) ||
8290#endif
8291 (mAudioAdapter && mAudioAdapter->isReallyModified()) ||
8292 (mUSBController && mUSBController->isReallyModified()) ||
8293 (mBIOSSettings && mBIOSSettings->isReallyModified());
8294}
8295
8296/**
8297 * Discards all changes to machine settings.
8298 *
8299 * @param aNotify Whether to notify the direct session about changes or not.
8300 *
8301 * @note Locks objects for writing!
8302 */
8303void Machine::rollback(bool aNotify)
8304{
8305 AutoCaller autoCaller(this);
8306 AssertComRCReturn (autoCaller.rc(), (void) 0);
8307
8308 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8309
8310 /* check for changes in own data */
8311
8312 bool sharedFoldersChanged = false, storageChanged = false;
8313
8314 if (aNotify && mHWData.isBackedUp())
8315 {
8316 if (mHWData->mSharedFolders.size() != mHWData.backedUpData()->mSharedFolders.size())
8317 sharedFoldersChanged = true;
8318 else
8319 {
8320 for (HWData::SharedFolderList::iterator rit = mHWData->mSharedFolders.begin();
8321 rit != mHWData->mSharedFolders.end() && !sharedFoldersChanged;
8322 ++rit)
8323 {
8324 for (HWData::SharedFolderList::iterator cit = mHWData.backedUpData()->mSharedFolders.begin();
8325 cit != mHWData.backedUpData()->mSharedFolders.end();
8326 ++cit)
8327 {
8328 if ( (*cit)->getName() != (*rit)->getName()
8329 || (*cit)->getHostPath() != (*rit)->getHostPath()
8330 )
8331 {
8332 sharedFoldersChanged = true;
8333 break;
8334 }
8335 }
8336 }
8337 }
8338 }
8339
8340 if (!mStorageControllers.isNull())
8341 {
8342 if (mStorageControllers.isBackedUp())
8343 {
8344 /* unitialize all new devices (absent in the backed up list). */
8345 StorageControllerList::const_iterator it = mStorageControllers->begin();
8346 StorageControllerList *backedList = mStorageControllers.backedUpData();
8347 while (it != mStorageControllers->end())
8348 {
8349 if ( std::find(backedList->begin(), backedList->end(), *it)
8350 == backedList->end()
8351 )
8352 {
8353 (*it)->uninit();
8354 }
8355 ++it;
8356 }
8357
8358 /* restore the list */
8359 mStorageControllers.rollback();
8360 }
8361
8362 /* rollback any changes to devices after restoring the list */
8363 StorageControllerList::const_iterator it = mStorageControllers->begin();
8364 while (it != mStorageControllers->end())
8365 {
8366 if ((*it)->isModified())
8367 (*it)->rollback();
8368
8369 ++it;
8370 }
8371 }
8372
8373 mUserData.rollback();
8374
8375 mHWData.rollback();
8376
8377 if (mMediaData.isBackedUp())
8378 rollbackMedia();
8379
8380 /* check for changes in child objects */
8381 bool vrdpChanged = false, usbChanged = false;
8382
8383 ComPtr<INetworkAdapter> networkAdapters[RT_ELEMENTS(mNetworkAdapters)];
8384 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
8385 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
8386
8387 if (mBIOSSettings)
8388 mBIOSSettings->rollback();
8389
8390#ifdef VBOX_WITH_VRDP
8391 if (mVRDPServer)
8392 vrdpChanged = mVRDPServer->rollback();
8393#endif
8394
8395 if (mAudioAdapter)
8396 mAudioAdapter->rollback();
8397
8398 if (mUSBController)
8399 usbChanged = mUSBController->rollback();
8400
8401 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
8402 if (mNetworkAdapters[slot])
8403 if (mNetworkAdapters[slot]->rollback())
8404 networkAdapters[slot] = mNetworkAdapters[slot];
8405
8406 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
8407 if (mSerialPorts[slot])
8408 if (mSerialPorts[slot]->rollback())
8409 serialPorts[slot] = mSerialPorts[slot];
8410
8411 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
8412 if (mParallelPorts[slot])
8413 if (mParallelPorts[slot]->rollback())
8414 parallelPorts[slot] = mParallelPorts[slot];
8415
8416 if (aNotify)
8417 {
8418 /* inform the direct session about changes */
8419
8420 ComObjPtr<Machine> that = this;
8421 alock.leave();
8422
8423 if (sharedFoldersChanged)
8424 that->onSharedFolderChange();
8425
8426 if (vrdpChanged)
8427 that->onVRDPServerChange();
8428 if (usbChanged)
8429 that->onUSBControllerChange();
8430
8431 for (ULONG slot = 0; slot < RT_ELEMENTS(networkAdapters); slot ++)
8432 if (networkAdapters[slot])
8433 that->onNetworkAdapterChange(networkAdapters[slot], FALSE);
8434 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); slot ++)
8435 if (serialPorts[slot])
8436 that->onSerialPortChange(serialPorts[slot]);
8437 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); slot ++)
8438 if (parallelPorts[slot])
8439 that->onParallelPortChange(parallelPorts[slot]);
8440
8441 if (storageChanged)
8442 that->onStorageControllerChange();
8443 }
8444}
8445
8446/**
8447 * Commits all the changes to machine settings.
8448 *
8449 * Note that this operation is supposed to never fail.
8450 *
8451 * @note Locks this object and children for writing.
8452 */
8453void Machine::commit()
8454{
8455 AutoCaller autoCaller(this);
8456 AssertComRCReturnVoid (autoCaller.rc());
8457
8458 AutoCaller peerCaller (mPeer);
8459 AssertComRCReturnVoid (peerCaller.rc());
8460
8461 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
8462
8463 /*
8464 * use safe commit to ensure Snapshot machines (that share mUserData)
8465 * will still refer to a valid memory location
8466 */
8467 mUserData.commitCopy();
8468
8469 mHWData.commit();
8470
8471 if (mMediaData.isBackedUp())
8472 commitMedia();
8473
8474 mBIOSSettings->commit();
8475#ifdef VBOX_WITH_VRDP
8476 mVRDPServer->commit();
8477#endif
8478 mAudioAdapter->commit();
8479 mUSBController->commit();
8480
8481 for (ULONG slot = 0; slot < RT_ELEMENTS (mNetworkAdapters); slot ++)
8482 mNetworkAdapters [slot]->commit();
8483 for (ULONG slot = 0; slot < RT_ELEMENTS (mSerialPorts); slot ++)
8484 mSerialPorts [slot]->commit();
8485 for (ULONG slot = 0; slot < RT_ELEMENTS (mParallelPorts); slot ++)
8486 mParallelPorts [slot]->commit();
8487
8488 bool commitStorageControllers = false;
8489
8490 if (mStorageControllers.isBackedUp())
8491 {
8492 mStorageControllers.commit();
8493
8494 if (mPeer)
8495 {
8496 AutoWriteLock peerlock(mPeer COMMA_LOCKVAL_SRC_POS);
8497
8498 /* Commit all changes to new controllers (this will reshare data with
8499 * peers for thos who have peers) */
8500 StorageControllerList *newList = new StorageControllerList();
8501 StorageControllerList::const_iterator it = mStorageControllers->begin();
8502 while (it != mStorageControllers->end())
8503 {
8504 (*it)->commit();
8505
8506 /* look if this controller has a peer device */
8507 ComObjPtr<StorageController> peer = (*it)->getPeer();
8508 if (!peer)
8509 {
8510 /* no peer means the device is a newly created one;
8511 * create a peer owning data this device share it with */
8512 peer.createObject();
8513 peer->init (mPeer, *it, true /* aReshare */);
8514 }
8515 else
8516 {
8517 /* remove peer from the old list */
8518 mPeer->mStorageControllers->remove (peer);
8519 }
8520 /* and add it to the new list */
8521 newList->push_back(peer);
8522
8523 ++it;
8524 }
8525
8526 /* uninit old peer's controllers that are left */
8527 it = mPeer->mStorageControllers->begin();
8528 while (it != mPeer->mStorageControllers->end())
8529 {
8530 (*it)->uninit();
8531 ++it;
8532 }
8533
8534 /* attach new list of controllers to our peer */
8535 mPeer->mStorageControllers.attach (newList);
8536 }
8537 else
8538 {
8539 /* we have no peer (our parent is the newly created machine);
8540 * just commit changes to devices */
8541 commitStorageControllers = true;
8542 }
8543 }
8544 else
8545 {
8546 /* the list of controllers itself is not changed,
8547 * just commit changes to controllers themselves */
8548 commitStorageControllers = true;
8549 }
8550
8551 if (commitStorageControllers)
8552 {
8553 StorageControllerList::const_iterator it = mStorageControllers->begin();
8554 while (it != mStorageControllers->end())
8555 {
8556 (*it)->commit();
8557 ++it;
8558 }
8559 }
8560
8561 if (getClassID() == clsidSessionMachine)
8562 {
8563 /* attach new data to the primary machine and reshare it */
8564 mPeer->mUserData.attach (mUserData);
8565 mPeer->mHWData.attach (mHWData);
8566 /* mMediaData is reshared by fixupMedia */
8567 // mPeer->mMediaData.attach(mMediaData);
8568 Assert(mPeer->mMediaData.data() == mMediaData.data());
8569 }
8570}
8571
8572/**
8573 * Copies all the hardware data from the given machine.
8574 *
8575 * Currently, only called when the VM is being restored from a snapshot. In
8576 * particular, this implies that the VM is not running during this method's
8577 * call.
8578 *
8579 * @note This method must be called from under this object's lock.
8580 *
8581 * @note This method doesn't call #commit(), so all data remains backed up and
8582 * unsaved.
8583 */
8584void Machine::copyFrom(Machine *aThat)
8585{
8586 AssertReturnVoid(getClassID() == clsidMachine || getClassID() == clsidSessionMachine);
8587 AssertReturnVoid(aThat->getClassID() == clsidSnapshotMachine);
8588
8589 AssertReturnVoid(!Global::IsOnline (mData->mMachineState));
8590
8591 mHWData.assignCopy(aThat->mHWData);
8592
8593 // create copies of all shared folders (mHWData after attiching a copy
8594 // contains just references to original objects)
8595 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
8596 it != mHWData->mSharedFolders.end();
8597 ++it)
8598 {
8599 ComObjPtr<SharedFolder> folder;
8600 folder.createObject();
8601 HRESULT rc = folder->initCopy(getMachine(), *it);
8602 AssertComRC (rc);
8603 *it = folder;
8604 }
8605
8606 mBIOSSettings->copyFrom(aThat->mBIOSSettings);
8607#ifdef VBOX_WITH_VRDP
8608 mVRDPServer->copyFrom(aThat->mVRDPServer);
8609#endif
8610 mAudioAdapter->copyFrom(aThat->mAudioAdapter);
8611 mUSBController->copyFrom(aThat->mUSBController);
8612
8613 /* create private copies of all controllers */
8614 mStorageControllers.backup();
8615 mStorageControllers->clear();
8616 for (StorageControllerList::iterator it = aThat->mStorageControllers->begin();
8617 it != aThat->mStorageControllers->end();
8618 ++it)
8619 {
8620 ComObjPtr<StorageController> ctrl;
8621 ctrl.createObject();
8622 ctrl->initCopy (this, *it);
8623 mStorageControllers->push_back(ctrl);
8624 }
8625
8626 for (ULONG slot = 0; slot < RT_ELEMENTS (mNetworkAdapters); slot ++)
8627 mNetworkAdapters [slot]->copyFrom (aThat->mNetworkAdapters [slot]);
8628 for (ULONG slot = 0; slot < RT_ELEMENTS (mSerialPorts); slot ++)
8629 mSerialPorts [slot]->copyFrom (aThat->mSerialPorts [slot]);
8630 for (ULONG slot = 0; slot < RT_ELEMENTS (mParallelPorts); slot ++)
8631 mParallelPorts [slot]->copyFrom (aThat->mParallelPorts [slot]);
8632}
8633
8634#ifdef VBOX_WITH_RESOURCE_USAGE_API
8635void Machine::registerMetrics (PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
8636{
8637 pm::CollectorHAL *hal = aCollector->getHAL();
8638 /* Create sub metrics */
8639 pm::SubMetric *cpuLoadUser = new pm::SubMetric ("CPU/Load/User",
8640 "Percentage of processor time spent in user mode by VM process.");
8641 pm::SubMetric *cpuLoadKernel = new pm::SubMetric ("CPU/Load/Kernel",
8642 "Percentage of processor time spent in kernel mode by VM process.");
8643 pm::SubMetric *ramUsageUsed = new pm::SubMetric ("RAM/Usage/Used",
8644 "Size of resident portion of VM process in memory.");
8645 /* Create and register base metrics */
8646 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw (hal, aMachine, pid,
8647 cpuLoadUser, cpuLoadKernel);
8648 aCollector->registerBaseMetric (cpuLoad);
8649 pm::BaseMetric *ramUsage = new pm::MachineRamUsage (hal, aMachine, pid,
8650 ramUsageUsed);
8651 aCollector->registerBaseMetric (ramUsage);
8652
8653 aCollector->registerMetric (new pm::Metric (cpuLoad, cpuLoadUser, 0));
8654 aCollector->registerMetric (new pm::Metric (cpuLoad, cpuLoadUser,
8655 new pm::AggregateAvg()));
8656 aCollector->registerMetric (new pm::Metric (cpuLoad, cpuLoadUser,
8657 new pm::AggregateMin()));
8658 aCollector->registerMetric (new pm::Metric (cpuLoad, cpuLoadUser,
8659 new pm::AggregateMax()));
8660 aCollector->registerMetric (new pm::Metric (cpuLoad, cpuLoadKernel, 0));
8661 aCollector->registerMetric (new pm::Metric (cpuLoad, cpuLoadKernel,
8662 new pm::AggregateAvg()));
8663 aCollector->registerMetric (new pm::Metric (cpuLoad, cpuLoadKernel,
8664 new pm::AggregateMin()));
8665 aCollector->registerMetric (new pm::Metric (cpuLoad, cpuLoadKernel,
8666 new pm::AggregateMax()));
8667
8668 aCollector->registerMetric (new pm::Metric (ramUsage, ramUsageUsed, 0));
8669 aCollector->registerMetric (new pm::Metric (ramUsage, ramUsageUsed,
8670 new pm::AggregateAvg()));
8671 aCollector->registerMetric (new pm::Metric (ramUsage, ramUsageUsed,
8672 new pm::AggregateMin()));
8673 aCollector->registerMetric (new pm::Metric (ramUsage, ramUsageUsed,
8674 new pm::AggregateMax()));
8675};
8676
8677void Machine::unregisterMetrics (PerformanceCollector *aCollector, Machine *aMachine)
8678{
8679 aCollector->unregisterMetricsFor (aMachine);
8680 aCollector->unregisterBaseMetricsFor (aMachine);
8681};
8682#endif /* VBOX_WITH_RESOURCE_USAGE_API */
8683
8684
8685////////////////////////////////////////////////////////////////////////////////
8686
8687DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
8688
8689HRESULT SessionMachine::FinalConstruct()
8690{
8691 LogFlowThisFunc(("\n"));
8692
8693#if defined(RT_OS_WINDOWS)
8694 mIPCSem = NULL;
8695#elif defined(RT_OS_OS2)
8696 mIPCSem = NULLHANDLE;
8697#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
8698 mIPCSem = -1;
8699#else
8700# error "Port me!"
8701#endif
8702
8703 return S_OK;
8704}
8705
8706void SessionMachine::FinalRelease()
8707{
8708 LogFlowThisFunc(("\n"));
8709
8710 uninit (Uninit::Unexpected);
8711}
8712
8713/**
8714 * @note Must be called only by Machine::openSession() from its own write lock.
8715 */
8716HRESULT SessionMachine::init (Machine *aMachine)
8717{
8718 LogFlowThisFuncEnter();
8719 LogFlowThisFunc(("mName={%ls}\n", aMachine->mUserData->mName.raw()));
8720
8721 AssertReturn(aMachine, E_INVALIDARG);
8722
8723 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
8724
8725 /* Enclose the state transition NotReady->InInit->Ready */
8726 AutoInitSpan autoInitSpan(this);
8727 AssertReturn(autoInitSpan.isOk(), E_FAIL);
8728
8729 /* create the interprocess semaphore */
8730#if defined(RT_OS_WINDOWS)
8731 mIPCSemName = aMachine->mData->m_strConfigFileFull;
8732 for (size_t i = 0; i < mIPCSemName.length(); i++)
8733 if (mIPCSemName[i] == '\\')
8734 mIPCSemName[i] = '/';
8735 mIPCSem = ::CreateMutex (NULL, FALSE, mIPCSemName);
8736 ComAssertMsgRet (mIPCSem,
8737 ("Cannot create IPC mutex '%ls', err=%d",
8738 mIPCSemName.raw(), ::GetLastError()),
8739 E_FAIL);
8740#elif defined(RT_OS_OS2)
8741 Utf8Str ipcSem = Utf8StrFmt ("\\SEM32\\VBOX\\VM\\{%RTuuid}",
8742 aMachine->mData->mUuid.raw());
8743 mIPCSemName = ipcSem;
8744 APIRET arc = ::DosCreateMutexSem ((PSZ) ipcSem.raw(), &mIPCSem, 0, FALSE);
8745 ComAssertMsgRet (arc == NO_ERROR,
8746 ("Cannot create IPC mutex '%s', arc=%ld",
8747 ipcSem.raw(), arc),
8748 E_FAIL);
8749#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
8750# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
8751# if defined(RT_OS_FREEBSD) && (HC_ARCH_BITS == 64)
8752 /** @todo Check that this still works correctly. */
8753 AssertCompileSize(key_t, 8);
8754# else
8755 AssertCompileSize(key_t, 4);
8756# endif
8757 key_t key;
8758 mIPCSem = -1;
8759 mIPCKey = "0";
8760 for (uint32_t i = 0; i < 1 << 24; i++)
8761 {
8762 key = ((uint32_t)'V' << 24) | i;
8763 int sem = ::semget (key, 1, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
8764 if (sem >= 0 || (errno != EEXIST && errno != EACCES))
8765 {
8766 mIPCSem = sem;
8767 if (sem >= 0)
8768 mIPCKey = BstrFmt ("%u", key);
8769 break;
8770 }
8771 }
8772# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
8773 Utf8Str semName = aMachine->mData->m_strConfigFileFull;
8774 char *pszSemName = NULL;
8775 RTStrUtf8ToCurrentCP (&pszSemName, semName);
8776 key_t key = ::ftok (pszSemName, 'V');
8777 RTStrFree (pszSemName);
8778
8779 mIPCSem = ::semget (key, 1, S_IRWXU | S_IRWXG | S_IRWXO | IPC_CREAT);
8780# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
8781
8782 int errnoSave = errno;
8783 if (mIPCSem < 0 && errnoSave == ENOSYS)
8784 {
8785 setError(E_FAIL,
8786 tr("Cannot create IPC semaphore. Most likely your host kernel lacks "
8787 "support for SysV IPC. Check the host kernel configuration for "
8788 "CONFIG_SYSVIPC=y"));
8789 return E_FAIL;
8790 }
8791 /* ENOSPC can also be the result of VBoxSVC crashes without properly freeing
8792 * the IPC semaphores */
8793 if (mIPCSem < 0 && errnoSave == ENOSPC)
8794 {
8795#ifdef RT_OS_LINUX
8796 setError(E_FAIL,
8797 tr("Cannot create IPC semaphore because the system limit for the "
8798 "maximum number of semaphore sets (SEMMNI), or the system wide "
8799 "maximum number of sempahores (SEMMNS) would be exceeded. The "
8800 "current set of SysV IPC semaphores can be determined from "
8801 "the file /proc/sysvipc/sem"));
8802#else
8803 setError(E_FAIL,
8804 tr("Cannot create IPC semaphore because the system-imposed limit "
8805 "on the maximum number of allowed semaphores or semaphore "
8806 "identifiers system-wide would be exceeded"));
8807#endif
8808 return E_FAIL;
8809 }
8810 ComAssertMsgRet (mIPCSem >= 0, ("Cannot create IPC semaphore, errno=%d", errnoSave),
8811 E_FAIL);
8812 /* set the initial value to 1 */
8813 int rv = ::semctl (mIPCSem, 0, SETVAL, 1);
8814 ComAssertMsgRet (rv == 0, ("Cannot init IPC semaphore, errno=%d", errno),
8815 E_FAIL);
8816#else
8817# error "Port me!"
8818#endif
8819
8820 /* memorize the peer Machine */
8821 unconst(mPeer) = aMachine;
8822 /* share the parent pointer */
8823 unconst(mParent) = aMachine->mParent;
8824
8825 /* take the pointers to data to share */
8826 mData.share (aMachine->mData);
8827 mSSData.share (aMachine->mSSData);
8828
8829 mUserData.share (aMachine->mUserData);
8830 mHWData.share (aMachine->mHWData);
8831 mMediaData.share(aMachine->mMediaData);
8832
8833 mStorageControllers.allocate();
8834 for (StorageControllerList::const_iterator it = aMachine->mStorageControllers->begin();
8835 it != aMachine->mStorageControllers->end();
8836 ++it)
8837 {
8838 ComObjPtr<StorageController> ctl;
8839 ctl.createObject();
8840 ctl->init(this, *it);
8841 mStorageControllers->push_back (ctl);
8842 }
8843
8844 unconst(mBIOSSettings).createObject();
8845 mBIOSSettings->init (this, aMachine->mBIOSSettings);
8846#ifdef VBOX_WITH_VRDP
8847 /* create another VRDPServer object that will be mutable */
8848 unconst(mVRDPServer).createObject();
8849 mVRDPServer->init (this, aMachine->mVRDPServer);
8850#endif
8851 /* create another audio adapter object that will be mutable */
8852 unconst(mAudioAdapter).createObject();
8853 mAudioAdapter->init (this, aMachine->mAudioAdapter);
8854 /* create a list of serial ports that will be mutable */
8855 for (ULONG slot = 0; slot < RT_ELEMENTS (mSerialPorts); slot ++)
8856 {
8857 unconst(mSerialPorts [slot]).createObject();
8858 mSerialPorts [slot]->init (this, aMachine->mSerialPorts [slot]);
8859 }
8860 /* create a list of parallel ports that will be mutable */
8861 for (ULONG slot = 0; slot < RT_ELEMENTS (mParallelPorts); slot ++)
8862 {
8863 unconst(mParallelPorts [slot]).createObject();
8864 mParallelPorts [slot]->init (this, aMachine->mParallelPorts [slot]);
8865 }
8866 /* create another USB controller object that will be mutable */
8867 unconst(mUSBController).createObject();
8868 mUSBController->init(this, aMachine->mUSBController);
8869
8870 /* create a list of network adapters that will be mutable */
8871 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
8872 {
8873 unconst(mNetworkAdapters [slot]).createObject();
8874 mNetworkAdapters[slot]->init (this, aMachine->mNetworkAdapters [slot]);
8875 }
8876
8877 /* default is to delete saved state on Saved -> PoweredOff transition */
8878 mRemoveSavedState = true;
8879
8880 /* Confirm a successful initialization when it's the case */
8881 autoInitSpan.setSucceeded();
8882
8883 LogFlowThisFuncLeave();
8884 return S_OK;
8885}
8886
8887/**
8888 * Uninitializes this session object. If the reason is other than
8889 * Uninit::Unexpected, then this method MUST be called from #checkForDeath().
8890 *
8891 * @param aReason uninitialization reason
8892 *
8893 * @note Locks mParent + this object for writing.
8894 */
8895void SessionMachine::uninit (Uninit::Reason aReason)
8896{
8897 LogFlowThisFuncEnter();
8898 LogFlowThisFunc(("reason=%d\n", aReason));
8899
8900 /*
8901 * Strongly reference ourselves to prevent this object deletion after
8902 * mData->mSession.mMachine.setNull() below (which can release the last
8903 * reference and call the destructor). Important: this must be done before
8904 * accessing any members (and before AutoUninitSpan that does it as well).
8905 * This self reference will be released as the very last step on return.
8906 */
8907 ComObjPtr<SessionMachine> selfRef = this;
8908
8909 /* Enclose the state transition Ready->InUninit->NotReady */
8910 AutoUninitSpan autoUninitSpan(this);
8911 if (autoUninitSpan.uninitDone())
8912 {
8913 LogFlowThisFunc(("Already uninitialized\n"));
8914 LogFlowThisFuncLeave();
8915 return;
8916 }
8917
8918 if (autoUninitSpan.initFailed())
8919 {
8920 /* We've been called by init() because it's failed. It's not really
8921 * necessary (nor it's safe) to perform the regular uninit sequense
8922 * below, the following is enough.
8923 */
8924 LogFlowThisFunc(("Initialization failed.\n"));
8925#if defined(RT_OS_WINDOWS)
8926 if (mIPCSem)
8927 ::CloseHandle (mIPCSem);
8928 mIPCSem = NULL;
8929#elif defined(RT_OS_OS2)
8930 if (mIPCSem != NULLHANDLE)
8931 ::DosCloseMutexSem (mIPCSem);
8932 mIPCSem = NULLHANDLE;
8933#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
8934 if (mIPCSem >= 0)
8935 ::semctl (mIPCSem, 0, IPC_RMID);
8936 mIPCSem = -1;
8937# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
8938 mIPCKey = "0";
8939# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
8940#else
8941# error "Port me!"
8942#endif
8943 uninitDataAndChildObjects();
8944 mData.free();
8945 unconst(mParent).setNull();
8946 unconst(mPeer).setNull();
8947 LogFlowThisFuncLeave();
8948 return;
8949 }
8950
8951 /* We need to lock this object in uninit() because the lock is shared
8952 * with mPeer (as well as data we modify below). mParent->addProcessToReap()
8953 * and others need mParent lock. */
8954 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
8955
8956#ifdef VBOX_WITH_RESOURCE_USAGE_API
8957 unregisterMetrics (mParent->performanceCollector(), mPeer);
8958#endif /* VBOX_WITH_RESOURCE_USAGE_API */
8959
8960 MachineState_T lastState = mData->mMachineState;
8961 NOREF(lastState);
8962
8963 if (aReason == Uninit::Abnormal)
8964 {
8965 LogWarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n",
8966 Global::IsOnlineOrTransient (lastState)));
8967
8968 /* reset the state to Aborted */
8969 if (mData->mMachineState != MachineState_Aborted)
8970 setMachineState (MachineState_Aborted);
8971 }
8972
8973 if (isModified())
8974 {
8975 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
8976 rollback (false /* aNotify */);
8977 }
8978
8979 Assert(mSnapshotData.mStateFilePath.isEmpty() || !mSnapshotData.mSnapshot);
8980 if (!mSnapshotData.mStateFilePath.isEmpty())
8981 {
8982 LogWarningThisFunc(("canceling failed save state request!\n"));
8983 endSavingState(FALSE /* aSuccess */);
8984 }
8985 else if (!mSnapshotData.mSnapshot.isNull())
8986 {
8987 LogWarningThisFunc(("canceling untaken snapshot!\n"));
8988
8989 /* delete all differencing hard disks created (this will also attach
8990 * their parents back by rolling back mMediaData) */
8991 rollbackMedia();
8992 /* delete the saved state file (it might have been already created) */
8993 if (mSnapshotData.mSnapshot->stateFilePath().length())
8994 RTFileDelete(mSnapshotData.mSnapshot->stateFilePath().c_str());
8995
8996 mSnapshotData.mSnapshot->uninit();
8997 }
8998
8999#ifdef VBOX_WITH_USB
9000 /* release all captured USB devices */
9001 if (aReason == Uninit::Abnormal && Global::IsOnline (lastState))
9002 {
9003 /* Console::captureUSBDevices() is called in the VM process only after
9004 * setting the machine state to Starting or Restoring.
9005 * Console::detachAllUSBDevices() will be called upon successful
9006 * termination. So, we need to release USB devices only if there was
9007 * an abnormal termination of a running VM.
9008 *
9009 * This is identical to SessionMachine::DetachAllUSBDevices except
9010 * for the aAbnormal argument. */
9011 HRESULT rc = mUSBController->notifyProxy (false /* aInsertFilters */);
9012 AssertComRC(rc);
9013 NOREF (rc);
9014
9015 USBProxyService *service = mParent->host()->usbProxyService();
9016 if (service)
9017 service->detachAllDevicesFromVM (this, true /* aDone */, true /* aAbnormal */);
9018 }
9019#endif /* VBOX_WITH_USB */
9020
9021 if (!mData->mSession.mType.isNull())
9022 {
9023 /* mType is not null when this machine's process has been started by
9024 * VirtualBox::OpenRemoteSession(), therefore it is our child. We
9025 * need to queue the PID to reap the process (and avoid zombies on
9026 * Linux). */
9027 Assert (mData->mSession.mPid != NIL_RTPROCESS);
9028 mParent->addProcessToReap (mData->mSession.mPid);
9029 }
9030
9031 mData->mSession.mPid = NIL_RTPROCESS;
9032
9033 if (aReason == Uninit::Unexpected)
9034 {
9035 /* Uninitialization didn't come from #checkForDeath(), so tell the
9036 * client watcher thread to update the set of machines that have open
9037 * sessions. */
9038 mParent->updateClientWatcher();
9039 }
9040
9041 /* uninitialize all remote controls */
9042 if (mData->mSession.mRemoteControls.size())
9043 {
9044 LogFlowThisFunc(("Closing remote sessions (%d):\n",
9045 mData->mSession.mRemoteControls.size()));
9046
9047 Data::Session::RemoteControlList::iterator it =
9048 mData->mSession.mRemoteControls.begin();
9049 while (it != mData->mSession.mRemoteControls.end())
9050 {
9051 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
9052 HRESULT rc = (*it)->Uninitialize();
9053 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
9054 if (FAILED (rc))
9055 LogWarningThisFunc(("Forgot to close the remote session?\n"));
9056 ++it;
9057 }
9058 mData->mSession.mRemoteControls.clear();
9059 }
9060
9061 /*
9062 * An expected uninitialization can come only from #checkForDeath().
9063 * Otherwise it means that something's got really wrong (for examlple,
9064 * the Session implementation has released the VirtualBox reference
9065 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
9066 * etc). However, it's also possible, that the client releases the IPC
9067 * semaphore correctly (i.e. before it releases the VirtualBox reference),
9068 * but the VirtualBox release event comes first to the server process.
9069 * This case is practically possible, so we should not assert on an
9070 * unexpected uninit, just log a warning.
9071 */
9072
9073 if ((aReason == Uninit::Unexpected))
9074 LogWarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
9075
9076 if (aReason != Uninit::Normal)
9077 {
9078 mData->mSession.mDirectControl.setNull();
9079 }
9080 else
9081 {
9082 /* this must be null here (see #OnSessionEnd()) */
9083 Assert (mData->mSession.mDirectControl.isNull());
9084 Assert (mData->mSession.mState == SessionState_Closing);
9085 Assert (!mData->mSession.mProgress.isNull());
9086
9087 mData->mSession.mProgress->notifyComplete (S_OK);
9088 mData->mSession.mProgress.setNull();
9089 }
9090
9091 /* remove the association between the peer machine and this session machine */
9092 Assert (mData->mSession.mMachine == this ||
9093 aReason == Uninit::Unexpected);
9094
9095 /* reset the rest of session data */
9096 mData->mSession.mMachine.setNull();
9097 mData->mSession.mState = SessionState_Closed;
9098 mData->mSession.mType.setNull();
9099
9100 /* close the interprocess semaphore before leaving the exclusive lock */
9101#if defined(RT_OS_WINDOWS)
9102 if (mIPCSem)
9103 ::CloseHandle (mIPCSem);
9104 mIPCSem = NULL;
9105#elif defined(RT_OS_OS2)
9106 if (mIPCSem != NULLHANDLE)
9107 ::DosCloseMutexSem (mIPCSem);
9108 mIPCSem = NULLHANDLE;
9109#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9110 if (mIPCSem >= 0)
9111 ::semctl (mIPCSem, 0, IPC_RMID);
9112 mIPCSem = -1;
9113# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9114 mIPCKey = "0";
9115# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
9116#else
9117# error "Port me!"
9118#endif
9119
9120 /* fire an event */
9121 mParent->onSessionStateChange (mData->mUuid, SessionState_Closed);
9122
9123 uninitDataAndChildObjects();
9124
9125 /* free the essential data structure last */
9126 mData.free();
9127
9128 /* leave the exclusive lock before setting the below two to NULL */
9129 alock.leave();
9130
9131 unconst(mParent).setNull();
9132 unconst(mPeer).setNull();
9133
9134 LogFlowThisFuncLeave();
9135}
9136
9137// util::Lockable interface
9138////////////////////////////////////////////////////////////////////////////////
9139
9140/**
9141 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
9142 * with the primary Machine instance (mPeer).
9143 */
9144RWLockHandle *SessionMachine::lockHandle() const
9145{
9146 AssertReturn(!mPeer.isNull(), NULL);
9147 return mPeer->lockHandle();
9148}
9149
9150// IInternalMachineControl methods
9151////////////////////////////////////////////////////////////////////////////////
9152
9153/**
9154 * @note Locks this object for writing.
9155 */
9156STDMETHODIMP SessionMachine::SetRemoveSavedState(BOOL aRemove)
9157{
9158 AutoCaller autoCaller(this);
9159 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9160
9161 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9162
9163 mRemoveSavedState = aRemove;
9164
9165 return S_OK;
9166}
9167
9168/**
9169 * @note Locks the same as #setMachineState() does.
9170 */
9171STDMETHODIMP SessionMachine::UpdateState (MachineState_T aMachineState)
9172{
9173 return setMachineState (aMachineState);
9174}
9175
9176/**
9177 * @note Locks this object for reading.
9178 */
9179STDMETHODIMP SessionMachine::GetIPCId (BSTR *aId)
9180{
9181 AutoCaller autoCaller(this);
9182 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9183
9184 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
9185
9186#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
9187 mIPCSemName.cloneTo(aId);
9188 return S_OK;
9189#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9190# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9191 mIPCKey.cloneTo(aId);
9192# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9193 mData->m_strConfigFileFull.cloneTo(aId);
9194# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9195 return S_OK;
9196#else
9197# error "Port me!"
9198#endif
9199}
9200
9201/**
9202 * Goes through the USB filters of the given machine to see if the given
9203 * device matches any filter or not.
9204 *
9205 * @note Locks the same as USBController::hasMatchingFilter() does.
9206 */
9207STDMETHODIMP SessionMachine::RunUSBDeviceFilters (IUSBDevice *aUSBDevice,
9208 BOOL *aMatched,
9209 ULONG *aMaskedIfs)
9210{
9211 LogFlowThisFunc(("\n"));
9212
9213 CheckComArgNotNull (aUSBDevice);
9214 CheckComArgOutPointerValid(aMatched);
9215
9216 AutoCaller autoCaller(this);
9217 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9218
9219#ifdef VBOX_WITH_USB
9220 *aMatched = mUSBController->hasMatchingFilter (aUSBDevice, aMaskedIfs);
9221#else
9222 NOREF(aUSBDevice);
9223 NOREF(aMaskedIfs);
9224 *aMatched = FALSE;
9225#endif
9226
9227 return S_OK;
9228}
9229
9230/**
9231 * @note Locks the same as Host::captureUSBDevice() does.
9232 */
9233STDMETHODIMP SessionMachine::CaptureUSBDevice (IN_BSTR aId)
9234{
9235 LogFlowThisFunc(("\n"));
9236
9237 AutoCaller autoCaller(this);
9238 AssertComRCReturnRC(autoCaller.rc());
9239
9240#ifdef VBOX_WITH_USB
9241 /* if captureDeviceForVM() fails, it must have set extended error info */
9242 MultiResult rc = mParent->host()->checkUSBProxyService();
9243 if (FAILED(rc)) return rc;
9244
9245 USBProxyService *service = mParent->host()->usbProxyService();
9246 AssertReturn(service, E_FAIL);
9247 return service->captureDeviceForVM (this, Guid(aId));
9248#else
9249 NOREF(aId);
9250 return E_NOTIMPL;
9251#endif
9252}
9253
9254/**
9255 * @note Locks the same as Host::detachUSBDevice() does.
9256 */
9257STDMETHODIMP SessionMachine::DetachUSBDevice (IN_BSTR aId, BOOL aDone)
9258{
9259 LogFlowThisFunc(("\n"));
9260
9261 AutoCaller autoCaller(this);
9262 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9263
9264#ifdef VBOX_WITH_USB
9265 USBProxyService *service = mParent->host()->usbProxyService();
9266 AssertReturn(service, E_FAIL);
9267 return service->detachDeviceFromVM (this, Guid(aId), !!aDone);
9268#else
9269 NOREF(aId);
9270 NOREF(aDone);
9271 return E_NOTIMPL;
9272#endif
9273}
9274
9275/**
9276 * Inserts all machine filters to the USB proxy service and then calls
9277 * Host::autoCaptureUSBDevices().
9278 *
9279 * Called by Console from the VM process upon VM startup.
9280 *
9281 * @note Locks what called methods lock.
9282 */
9283STDMETHODIMP SessionMachine::AutoCaptureUSBDevices()
9284{
9285 LogFlowThisFunc(("\n"));
9286
9287 AutoCaller autoCaller(this);
9288 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9289
9290#ifdef VBOX_WITH_USB
9291 HRESULT rc = mUSBController->notifyProxy (true /* aInsertFilters */);
9292 AssertComRC(rc);
9293 NOREF (rc);
9294
9295 USBProxyService *service = mParent->host()->usbProxyService();
9296 AssertReturn(service, E_FAIL);
9297 return service->autoCaptureDevicesForVM (this);
9298#else
9299 return S_OK;
9300#endif
9301}
9302
9303/**
9304 * Removes all machine filters from the USB proxy service and then calls
9305 * Host::detachAllUSBDevices().
9306 *
9307 * Called by Console from the VM process upon normal VM termination or by
9308 * SessionMachine::uninit() upon abnormal VM termination (from under the
9309 * Machine/SessionMachine lock).
9310 *
9311 * @note Locks what called methods lock.
9312 */
9313STDMETHODIMP SessionMachine::DetachAllUSBDevices (BOOL aDone)
9314{
9315 LogFlowThisFunc(("\n"));
9316
9317 AutoCaller autoCaller(this);
9318 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9319
9320#ifdef VBOX_WITH_USB
9321 HRESULT rc = mUSBController->notifyProxy (false /* aInsertFilters */);
9322 AssertComRC(rc);
9323 NOREF (rc);
9324
9325 USBProxyService *service = mParent->host()->usbProxyService();
9326 AssertReturn(service, E_FAIL);
9327 return service->detachAllDevicesFromVM (this, !!aDone, false /* aAbnormal */);
9328#else
9329 NOREF(aDone);
9330 return S_OK;
9331#endif
9332}
9333
9334/**
9335 * @note Locks this object for writing.
9336 */
9337STDMETHODIMP SessionMachine::OnSessionEnd (ISession *aSession,
9338 IProgress **aProgress)
9339{
9340 LogFlowThisFuncEnter();
9341
9342 AssertReturn(aSession, E_INVALIDARG);
9343 AssertReturn(aProgress, E_INVALIDARG);
9344
9345 AutoCaller autoCaller(this);
9346
9347 LogFlowThisFunc(("callerstate=%d\n", autoCaller.state()));
9348 /*
9349 * We don't assert below because it might happen that a non-direct session
9350 * informs us it is closed right after we've been uninitialized -- it's ok.
9351 */
9352 if (FAILED(autoCaller.rc())) return autoCaller.rc();
9353
9354 /* get IInternalSessionControl interface */
9355 ComPtr<IInternalSessionControl> control (aSession);
9356
9357 ComAssertRet (!control.isNull(), E_INVALIDARG);
9358
9359 /* Creating a Progress object requires the VirtualBox lock, and
9360 * thus locking it here is required by the lock order rules. */
9361 AutoMultiWriteLock2 alock(mParent->lockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
9362
9363 if (control.equalsTo(mData->mSession.mDirectControl))
9364 {
9365 ComAssertRet (aProgress, E_POINTER);
9366
9367 /* The direct session is being normally closed by the client process
9368 * ----------------------------------------------------------------- */
9369
9370 /* go to the closing state (essential for all open*Session() calls and
9371 * for #checkForDeath()) */
9372 Assert (mData->mSession.mState == SessionState_Open);
9373 mData->mSession.mState = SessionState_Closing;
9374
9375 /* set direct control to NULL to release the remote instance */
9376 mData->mSession.mDirectControl.setNull();
9377 LogFlowThisFunc(("Direct control is set to NULL\n"));
9378
9379 /* Create the progress object the client will use to wait until
9380 * #checkForDeath() is called to uninitialize this session object after
9381 * it releases the IPC semaphore. */
9382 ComObjPtr<Progress> progress;
9383 progress.createObject();
9384 progress->init (mParent, static_cast <IMachine *> (mPeer),
9385 Bstr (tr ("Closing session")), FALSE /* aCancelable */);
9386 progress.queryInterfaceTo(aProgress);
9387 mData->mSession.mProgress = progress;
9388 }
9389 else
9390 {
9391 /* the remote session is being normally closed */
9392 Data::Session::RemoteControlList::iterator it =
9393 mData->mSession.mRemoteControls.begin();
9394 while (it != mData->mSession.mRemoteControls.end())
9395 {
9396 if (control.equalsTo (*it))
9397 break;
9398 ++it;
9399 }
9400 BOOL found = it != mData->mSession.mRemoteControls.end();
9401 ComAssertMsgRet (found, ("The session is not found in the session list!"),
9402 E_INVALIDARG);
9403 mData->mSession.mRemoteControls.remove (*it);
9404 }
9405
9406 LogFlowThisFuncLeave();
9407 return S_OK;
9408}
9409
9410/**
9411 * @note Locks this object for writing.
9412 */
9413STDMETHODIMP SessionMachine::BeginSavingState (IProgress *aProgress, BSTR *aStateFilePath)
9414{
9415 LogFlowThisFuncEnter();
9416
9417 AssertReturn(aProgress, E_INVALIDARG);
9418 AssertReturn(aStateFilePath, E_POINTER);
9419
9420 AutoCaller autoCaller(this);
9421 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9422
9423 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9424
9425 AssertReturn( mData->mMachineState == MachineState_Paused
9426 && mSnapshotData.mLastState == MachineState_Null
9427 && mSnapshotData.mProgressId.isEmpty()
9428 && mSnapshotData.mStateFilePath.isEmpty(),
9429 E_FAIL);
9430
9431 /* memorize the progress ID and add it to the global collection */
9432 Bstr progressId;
9433 HRESULT rc = aProgress->COMGETTER(Id) (progressId.asOutParam());
9434 AssertComRCReturn (rc, rc);
9435 rc = mParent->addProgress (aProgress);
9436 AssertComRCReturn (rc, rc);
9437
9438 Bstr stateFilePath;
9439 /* stateFilePath is null when the machine is not running */
9440 if (mData->mMachineState == MachineState_Paused)
9441 {
9442 stateFilePath = Utf8StrFmt ("%ls%c{%RTuuid}.sav",
9443 mUserData->mSnapshotFolderFull.raw(),
9444 RTPATH_DELIMITER, mData->mUuid.raw());
9445 }
9446
9447 /* fill in the snapshot data */
9448 mSnapshotData.mLastState = mData->mMachineState;
9449 mSnapshotData.mProgressId = Guid(progressId);
9450 mSnapshotData.mStateFilePath = stateFilePath;
9451
9452 /* set the state to Saving (this is expected by Console::SaveState()) */
9453 setMachineState (MachineState_Saving);
9454
9455 stateFilePath.cloneTo(aStateFilePath);
9456
9457 return S_OK;
9458}
9459
9460/**
9461 * @note Locks mParent + this object for writing.
9462 */
9463STDMETHODIMP SessionMachine::EndSavingState (BOOL aSuccess)
9464{
9465 LogFlowThisFunc(("\n"));
9466
9467 AutoCaller autoCaller(this);
9468 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9469
9470 /* endSavingState() need mParent lock */
9471 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
9472
9473 AssertReturn( mData->mMachineState == MachineState_Saving
9474 && mSnapshotData.mLastState != MachineState_Null
9475 && !mSnapshotData.mProgressId.isEmpty()
9476 && !mSnapshotData.mStateFilePath.isEmpty(),
9477 E_FAIL);
9478
9479 /*
9480 * on success, set the state to Saved;
9481 * on failure, set the state to the state we had when BeginSavingState() was
9482 * called (this is expected by Console::SaveState() and
9483 * Console::saveStateThread())
9484 */
9485 if (aSuccess)
9486 setMachineState (MachineState_Saved);
9487 else
9488 setMachineState (mSnapshotData.mLastState);
9489
9490 return endSavingState (aSuccess);
9491}
9492
9493/**
9494 * @note Locks this object for writing.
9495 */
9496STDMETHODIMP SessionMachine::AdoptSavedState (IN_BSTR aSavedStateFile)
9497{
9498 LogFlowThisFunc(("\n"));
9499
9500 CheckComArgStrNotEmptyOrNull(aSavedStateFile);
9501
9502 AutoCaller autoCaller(this);
9503 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9504
9505 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9506
9507 AssertReturn( mData->mMachineState == MachineState_PoweredOff
9508 || mData->mMachineState == MachineState_Teleported
9509 || mData->mMachineState == MachineState_Aborted
9510 , E_FAIL); /** @todo setError. */
9511
9512 Utf8Str stateFilePathFull = aSavedStateFile;
9513 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
9514 if (RT_FAILURE(vrc))
9515 return setError(VBOX_E_FILE_ERROR,
9516 tr("Invalid saved state file path '%ls' (%Rrc)"),
9517 aSavedStateFile,
9518 vrc);
9519
9520 mSSData->mStateFilePath = stateFilePathFull;
9521
9522 /* The below setMachineState() will detect the state transition and will
9523 * update the settings file */
9524
9525 return setMachineState (MachineState_Saved);
9526}
9527
9528STDMETHODIMP SessionMachine::PullGuestProperties(ComSafeArrayOut(BSTR, aNames),
9529 ComSafeArrayOut(BSTR, aValues),
9530 ComSafeArrayOut(ULONG64, aTimestamps),
9531 ComSafeArrayOut(BSTR, aFlags))
9532{
9533 LogFlowThisFunc(("\n"));
9534
9535#ifdef VBOX_WITH_GUEST_PROPS
9536 using namespace guestProp;
9537
9538 AutoCaller autoCaller(this);
9539 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9540
9541 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
9542
9543 AssertReturn(!ComSafeArrayOutIsNull(aNames), E_POINTER);
9544 AssertReturn(!ComSafeArrayOutIsNull(aValues), E_POINTER);
9545 AssertReturn(!ComSafeArrayOutIsNull(aTimestamps), E_POINTER);
9546 AssertReturn(!ComSafeArrayOutIsNull(aFlags), E_POINTER);
9547
9548 size_t cEntries = mHWData->mGuestProperties.size();
9549 com::SafeArray<BSTR> names (cEntries);
9550 com::SafeArray<BSTR> values (cEntries);
9551 com::SafeArray<ULONG64> timestamps (cEntries);
9552 com::SafeArray<BSTR> flags (cEntries);
9553 unsigned i = 0;
9554 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
9555 it != mHWData->mGuestProperties.end();
9556 ++it)
9557 {
9558 char szFlags[MAX_FLAGS_LEN + 1];
9559 it->strName.cloneTo(&names[i]);
9560 it->strValue.cloneTo(&values[i]);
9561 timestamps[i] = it->mTimestamp;
9562 /* If it is NULL, keep it NULL. */
9563 if (it->mFlags)
9564 {
9565 writeFlags(it->mFlags, szFlags);
9566 Bstr(szFlags).cloneTo(&flags[i]);
9567 }
9568 else
9569 flags[i] = NULL;
9570 ++i;
9571 }
9572 names.detachTo(ComSafeArrayOutArg(aNames));
9573 values.detachTo(ComSafeArrayOutArg(aValues));
9574 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
9575 flags.detachTo(ComSafeArrayOutArg(aFlags));
9576 mHWData->mPropertyServiceActive = true;
9577 return S_OK;
9578#else
9579 ReturnComNotImplemented();
9580#endif
9581}
9582
9583STDMETHODIMP SessionMachine::PushGuestProperties(ComSafeArrayIn(IN_BSTR, aNames),
9584 ComSafeArrayIn(IN_BSTR, aValues),
9585 ComSafeArrayIn(ULONG64, aTimestamps),
9586 ComSafeArrayIn(IN_BSTR, aFlags))
9587{
9588 LogFlowThisFunc(("\n"));
9589
9590#ifdef VBOX_WITH_GUEST_PROPS
9591 using namespace guestProp;
9592
9593 AssertReturn(!ComSafeArrayInIsNull(aNames), E_POINTER);
9594 AssertReturn(!ComSafeArrayInIsNull(aValues), E_POINTER);
9595 AssertReturn(!ComSafeArrayInIsNull(aTimestamps), E_POINTER);
9596 AssertReturn(!ComSafeArrayInIsNull(aFlags), E_POINTER);
9597
9598 AutoCaller autoCaller(this);
9599 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9600
9601 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9602
9603 /*
9604 * Temporarily reset the registered flag, so that our machine state
9605 * changes (i.e. mHWData.backup()) succeed. (isMutable() used in all
9606 * setters will return FALSE for a Machine instance if mRegistered is TRUE).
9607 *
9608 * This is copied from registeredInit(), and may or may not be the right
9609 * way to handle this.
9610 */
9611 Assert(mData->mRegistered);
9612 mData->mRegistered = FALSE;
9613
9614 HRESULT rc = checkStateDependency(MutableStateDep);
9615 AssertLogRelMsgReturn(SUCCEEDED(rc), ("%Rhrc\n", rc), rc);
9616
9617 com::SafeArray<IN_BSTR> names( ComSafeArrayInArg(aNames));
9618 com::SafeArray<IN_BSTR> values( ComSafeArrayInArg(aValues));
9619 com::SafeArray<ULONG64> timestamps(ComSafeArrayInArg(aTimestamps));
9620 com::SafeArray<IN_BSTR> flags( ComSafeArrayInArg(aFlags));
9621
9622 DiscardSettings();
9623 mHWData.backup();
9624
9625 mHWData->mGuestProperties.erase(mHWData->mGuestProperties.begin(),
9626 mHWData->mGuestProperties.end());
9627 for (unsigned i = 0; i < names.size(); ++i)
9628 {
9629 uint32_t fFlags = NILFLAG;
9630 validateFlags(Utf8Str(flags[i]).raw(), &fFlags);
9631 HWData::GuestProperty property = { names[i], values[i], timestamps[i], fFlags };
9632 mHWData->mGuestProperties.push_back(property);
9633 }
9634
9635 mHWData->mPropertyServiceActive = false;
9636
9637 alock.release();
9638 SaveSettings();
9639
9640 /* Restore the mRegistered flag. */
9641 alock.acquire();
9642 mData->mRegistered = TRUE;
9643
9644 return S_OK;
9645#else
9646 ReturnComNotImplemented();
9647#endif
9648}
9649
9650STDMETHODIMP SessionMachine::PushGuestProperty(IN_BSTR aName,
9651 IN_BSTR aValue,
9652 ULONG64 aTimestamp,
9653 IN_BSTR aFlags)
9654{
9655 LogFlowThisFunc(("\n"));
9656
9657#ifdef VBOX_WITH_GUEST_PROPS
9658 using namespace guestProp;
9659
9660 CheckComArgNotNull(aName);
9661 if (aValue != NULL && (!VALID_PTR(aValue) || !VALID_PTR(aFlags)))
9662 return E_POINTER; /* aValue can be NULL to indicate deletion */
9663
9664 try
9665 {
9666 /*
9667 * Convert input up front.
9668 */
9669 Utf8Str utf8Name(aName);
9670 uint32_t fFlags = NILFLAG;
9671 if (aFlags)
9672 {
9673 Utf8Str utf8Flags(aFlags);
9674 int vrc = validateFlags(utf8Flags.raw(), &fFlags);
9675 AssertRCReturn(vrc, E_INVALIDARG);
9676 }
9677
9678 /*
9679 * Now grab the object lock, validate the state and do the update.
9680 */
9681 AutoCaller autoCaller(this);
9682 if (FAILED(autoCaller.rc())) return autoCaller.rc();
9683
9684 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9685
9686 AssertReturn(mHWData->mPropertyServiceActive, VBOX_E_INVALID_OBJECT_STATE);
9687 switch (mData->mMachineState)
9688 {
9689 case MachineState_Paused:
9690 case MachineState_Running:
9691 case MachineState_Teleporting:
9692 case MachineState_TeleportingPausedVM:
9693 case MachineState_LiveSnapshotting:
9694 case MachineState_Saving:
9695 break;
9696
9697 default:
9698 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
9699 VBOX_E_INVALID_VM_STATE);
9700 }
9701
9702 mHWData.backup();
9703
9704 /** @todo r=bird: The careful memory handling doesn't work out here because
9705 * the catch block won't undo any damange we've done. So, if push_back throws
9706 * bad_alloc then you've lost the value.
9707 *
9708 * Another thing. Doing a linear search here isn't extremely efficient, esp.
9709 * since values that changes actually bubbles to the end of the list. Using
9710 * something that has an efficient lookup and can tollerate a bit of updates
9711 * would be nice. RTStrSpace is one suggestion (it's not perfect). Some
9712 * combination of RTStrCache (for sharing names and getting uniqueness into
9713 * the bargain) and hash/tree is another. */
9714 for (HWData::GuestPropertyList::iterator iter = mHWData->mGuestProperties.begin();
9715 iter != mHWData->mGuestProperties.end();
9716 ++iter)
9717 if (utf8Name == iter->strName)
9718 {
9719 mHWData->mGuestProperties.erase(iter);
9720 break;
9721 }
9722 if (aValue != NULL)
9723 {
9724 HWData::GuestProperty property = { aName, aValue, aTimestamp, fFlags };
9725 mHWData->mGuestProperties.push_back(property);
9726 }
9727
9728 /*
9729 * Send a callback notification if appropriate
9730 */
9731 if ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
9732 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.raw(),
9733 RTSTR_MAX,
9734 utf8Name.raw(),
9735 RTSTR_MAX, NULL)
9736 )
9737 {
9738 alock.leave();
9739
9740 mParent->onGuestPropertyChange(mData->mUuid,
9741 aName,
9742 aValue,
9743 aFlags);
9744 }
9745 }
9746 catch (...)
9747 {
9748 return VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
9749 }
9750 return S_OK;
9751#else
9752 ReturnComNotImplemented();
9753#endif
9754}
9755
9756// public methods only for internal purposes
9757/////////////////////////////////////////////////////////////////////////////
9758
9759/**
9760 * Called from the client watcher thread to check for expected or unexpected
9761 * death of the client process that has a direct session to this machine.
9762 *
9763 * On Win32 and on OS/2, this method is called only when we've got the
9764 * mutex (i.e. the client has either died or terminated normally) so it always
9765 * returns @c true (the client is terminated, the session machine is
9766 * uninitialized).
9767 *
9768 * On other platforms, the method returns @c true if the client process has
9769 * terminated normally or abnormally and the session machine was uninitialized,
9770 * and @c false if the client process is still alive.
9771 *
9772 * @note Locks this object for writing.
9773 */
9774bool SessionMachine::checkForDeath()
9775{
9776 Uninit::Reason reason;
9777 bool terminated = false;
9778
9779 /* Enclose autoCaller with a block because calling uninit() from under it
9780 * will deadlock. */
9781 {
9782 AutoCaller autoCaller(this);
9783 if (!autoCaller.isOk())
9784 {
9785 /* return true if not ready, to cause the client watcher to exclude
9786 * the corresponding session from watching */
9787 LogFlowThisFunc(("Already uninitialized!\n"));
9788 return true;
9789 }
9790
9791 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9792
9793 /* Determine the reason of death: if the session state is Closing here,
9794 * everything is fine. Otherwise it means that the client did not call
9795 * OnSessionEnd() before it released the IPC semaphore. This may happen
9796 * either because the client process has abnormally terminated, or
9797 * because it simply forgot to call ISession::Close() before exiting. We
9798 * threat the latter also as an abnormal termination (see
9799 * Session::uninit() for details). */
9800 reason = mData->mSession.mState == SessionState_Closing ?
9801 Uninit::Normal :
9802 Uninit::Abnormal;
9803
9804#if defined(RT_OS_WINDOWS)
9805
9806 AssertMsg (mIPCSem, ("semaphore must be created"));
9807
9808 /* release the IPC mutex */
9809 ::ReleaseMutex (mIPCSem);
9810
9811 terminated = true;
9812
9813#elif defined(RT_OS_OS2)
9814
9815 AssertMsg (mIPCSem, ("semaphore must be created"));
9816
9817 /* release the IPC mutex */
9818 ::DosReleaseMutexSem (mIPCSem);
9819
9820 terminated = true;
9821
9822#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9823
9824 AssertMsg (mIPCSem >= 0, ("semaphore must be created"));
9825
9826 int val = ::semctl (mIPCSem, 0, GETVAL);
9827 if (val > 0)
9828 {
9829 /* the semaphore is signaled, meaning the session is terminated */
9830 terminated = true;
9831 }
9832
9833#else
9834# error "Port me!"
9835#endif
9836
9837 } /* AutoCaller block */
9838
9839 if (terminated)
9840 uninit (reason);
9841
9842 return terminated;
9843}
9844
9845/**
9846 * @note Locks this object for reading.
9847 */
9848HRESULT SessionMachine::onNetworkAdapterChange (INetworkAdapter *networkAdapter, BOOL changeAdapter)
9849{
9850 LogFlowThisFunc(("\n"));
9851
9852 AutoCaller autoCaller(this);
9853 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9854
9855 ComPtr<IInternalSessionControl> directControl;
9856 {
9857 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
9858 directControl = mData->mSession.mDirectControl;
9859 }
9860
9861 /* ignore notifications sent after #OnSessionEnd() is called */
9862 if (!directControl)
9863 return S_OK;
9864
9865 return directControl->OnNetworkAdapterChange (networkAdapter, changeAdapter);
9866}
9867
9868/**
9869 * @note Locks this object for reading.
9870 */
9871HRESULT SessionMachine::onSerialPortChange (ISerialPort *serialPort)
9872{
9873 LogFlowThisFunc(("\n"));
9874
9875 AutoCaller autoCaller(this);
9876 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9877
9878 ComPtr<IInternalSessionControl> directControl;
9879 {
9880 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
9881 directControl = mData->mSession.mDirectControl;
9882 }
9883
9884 /* ignore notifications sent after #OnSessionEnd() is called */
9885 if (!directControl)
9886 return S_OK;
9887
9888 return directControl->OnSerialPortChange (serialPort);
9889}
9890
9891/**
9892 * @note Locks this object for reading.
9893 */
9894HRESULT SessionMachine::onParallelPortChange (IParallelPort *parallelPort)
9895{
9896 LogFlowThisFunc(("\n"));
9897
9898 AutoCaller autoCaller(this);
9899 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9900
9901 ComPtr<IInternalSessionControl> directControl;
9902 {
9903 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
9904 directControl = mData->mSession.mDirectControl;
9905 }
9906
9907 /* ignore notifications sent after #OnSessionEnd() is called */
9908 if (!directControl)
9909 return S_OK;
9910
9911 return directControl->OnParallelPortChange (parallelPort);
9912}
9913
9914/**
9915 * @note Locks this object for reading.
9916 */
9917HRESULT SessionMachine::onStorageControllerChange ()
9918{
9919 LogFlowThisFunc(("\n"));
9920
9921 AutoCaller autoCaller(this);
9922 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9923
9924 ComPtr<IInternalSessionControl> directControl;
9925 {
9926 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
9927 directControl = mData->mSession.mDirectControl;
9928 }
9929
9930 /* ignore notifications sent after #OnSessionEnd() is called */
9931 if (!directControl)
9932 return S_OK;
9933
9934 return directControl->OnStorageControllerChange ();
9935}
9936
9937/**
9938 * @note Locks this object for reading.
9939 */
9940HRESULT SessionMachine::onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
9941{
9942 LogFlowThisFunc(("\n"));
9943
9944 AutoCaller autoCaller(this);
9945 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9946
9947 ComPtr<IInternalSessionControl> directControl;
9948 {
9949 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
9950 directControl = mData->mSession.mDirectControl;
9951 }
9952
9953 /* ignore notifications sent after #OnSessionEnd() is called */
9954 if (!directControl)
9955 return S_OK;
9956
9957 return directControl->OnMediumChange(aAttachment, aForce);
9958}
9959
9960/**
9961 * @note Locks this object for reading.
9962 */
9963HRESULT SessionMachine::onCPUChange(ULONG aCPU, BOOL aRemove)
9964{
9965 LogFlowThisFunc(("\n"));
9966
9967 AutoCaller autoCaller(this);
9968 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9969
9970 ComPtr<IInternalSessionControl> directControl;
9971 {
9972 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
9973 directControl = mData->mSession.mDirectControl;
9974 }
9975
9976 /* ignore notifications sent after #OnSessionEnd() is called */
9977 if (!directControl)
9978 return S_OK;
9979
9980 return directControl->OnCPUChange(aCPU, aRemove);
9981}
9982
9983/**
9984 * @note Locks this object for reading.
9985 */
9986HRESULT SessionMachine::onVRDPServerChange()
9987{
9988 LogFlowThisFunc(("\n"));
9989
9990 AutoCaller autoCaller(this);
9991 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
9992
9993 ComPtr<IInternalSessionControl> directControl;
9994 {
9995 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
9996 directControl = mData->mSession.mDirectControl;
9997 }
9998
9999 /* ignore notifications sent after #OnSessionEnd() is called */
10000 if (!directControl)
10001 return S_OK;
10002
10003 return directControl->OnVRDPServerChange();
10004}
10005
10006/**
10007 * @note Locks this object for reading.
10008 */
10009HRESULT SessionMachine::onUSBControllerChange()
10010{
10011 LogFlowThisFunc(("\n"));
10012
10013 AutoCaller autoCaller(this);
10014 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
10015
10016 ComPtr<IInternalSessionControl> directControl;
10017 {
10018 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10019 directControl = mData->mSession.mDirectControl;
10020 }
10021
10022 /* ignore notifications sent after #OnSessionEnd() is called */
10023 if (!directControl)
10024 return S_OK;
10025
10026 return directControl->OnUSBControllerChange();
10027}
10028
10029/**
10030 * @note Locks this object for reading.
10031 */
10032HRESULT SessionMachine::onSharedFolderChange()
10033{
10034 LogFlowThisFunc(("\n"));
10035
10036 AutoCaller autoCaller(this);
10037 AssertComRCReturnRC(autoCaller.rc());
10038
10039 ComPtr<IInternalSessionControl> directControl;
10040 {
10041 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10042 directControl = mData->mSession.mDirectControl;
10043 }
10044
10045 /* ignore notifications sent after #OnSessionEnd() is called */
10046 if (!directControl)
10047 return S_OK;
10048
10049 return directControl->OnSharedFolderChange (FALSE /* aGlobal */);
10050}
10051
10052/**
10053 * Returns @c true if this machine's USB controller reports it has a matching
10054 * filter for the given USB device and @c false otherwise.
10055 *
10056 * @note Caller must have requested machine read lock.
10057 */
10058bool SessionMachine::hasMatchingUSBFilter (const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
10059{
10060 AutoCaller autoCaller(this);
10061 /* silently return if not ready -- this method may be called after the
10062 * direct machine session has been called */
10063 if (!autoCaller.isOk())
10064 return false;
10065
10066 AssertReturn(isWriteLockOnCurrentThread(), false);
10067
10068#ifdef VBOX_WITH_USB
10069 switch (mData->mMachineState)
10070 {
10071 case MachineState_Starting:
10072 case MachineState_Restoring:
10073 case MachineState_TeleportingIn:
10074 case MachineState_Paused:
10075 case MachineState_Running:
10076 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
10077 * elsewhere... */
10078 return mUSBController->hasMatchingFilter (aDevice, aMaskedIfs);
10079 default: break;
10080 }
10081#else
10082 NOREF(aDevice);
10083 NOREF(aMaskedIfs);
10084#endif
10085 return false;
10086}
10087
10088/**
10089 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
10090 */
10091HRESULT SessionMachine::onUSBDeviceAttach (IUSBDevice *aDevice,
10092 IVirtualBoxErrorInfo *aError,
10093 ULONG aMaskedIfs)
10094{
10095 LogFlowThisFunc(("\n"));
10096
10097 AutoCaller autoCaller(this);
10098
10099 /* This notification may happen after the machine object has been
10100 * uninitialized (the session was closed), so don't assert. */
10101 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10102
10103 ComPtr<IInternalSessionControl> directControl;
10104 {
10105 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10106 directControl = mData->mSession.mDirectControl;
10107 }
10108
10109 /* fail on notifications sent after #OnSessionEnd() is called, it is
10110 * expected by the caller */
10111 if (!directControl)
10112 return E_FAIL;
10113
10114 /* No locks should be held at this point. */
10115 AssertMsg (RTLockValidatorWriteLockGetCount (RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount (RTThreadSelf())));
10116 AssertMsg (RTLockValidatorReadLockGetCount (RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount (RTThreadSelf())));
10117
10118 return directControl->OnUSBDeviceAttach (aDevice, aError, aMaskedIfs);
10119}
10120
10121/**
10122 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
10123 */
10124HRESULT SessionMachine::onUSBDeviceDetach (IN_BSTR aId,
10125 IVirtualBoxErrorInfo *aError)
10126{
10127 LogFlowThisFunc(("\n"));
10128
10129 AutoCaller autoCaller(this);
10130
10131 /* This notification may happen after the machine object has been
10132 * uninitialized (the session was closed), so don't assert. */
10133 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10134
10135 ComPtr<IInternalSessionControl> directControl;
10136 {
10137 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10138 directControl = mData->mSession.mDirectControl;
10139 }
10140
10141 /* fail on notifications sent after #OnSessionEnd() is called, it is
10142 * expected by the caller */
10143 if (!directControl)
10144 return E_FAIL;
10145
10146 /* No locks should be held at this point. */
10147 AssertMsg (RTLockValidatorWriteLockGetCount (RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount (RTThreadSelf())));
10148 AssertMsg (RTLockValidatorReadLockGetCount (RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount (RTThreadSelf())));
10149
10150 return directControl->OnUSBDeviceDetach (aId, aError);
10151}
10152
10153// protected methods
10154/////////////////////////////////////////////////////////////////////////////
10155
10156/**
10157 * Helper method to finalize saving the state.
10158 *
10159 * @note Must be called from under this object's lock.
10160 *
10161 * @param aSuccess TRUE if the snapshot has been taken successfully
10162 *
10163 * @note Locks mParent + this objects for writing.
10164 */
10165HRESULT SessionMachine::endSavingState (BOOL aSuccess)
10166{
10167 LogFlowThisFuncEnter();
10168
10169 AutoCaller autoCaller(this);
10170 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
10171
10172 /* saveSettings() needs mParent lock */
10173 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
10174
10175 HRESULT rc = S_OK;
10176
10177 if (aSuccess)
10178 {
10179 mSSData->mStateFilePath = mSnapshotData.mStateFilePath;
10180
10181 /* save all VM settings */
10182 rc = saveSettings();
10183 }
10184 else
10185 {
10186 /* delete the saved state file (it might have been already created) */
10187 RTFileDelete(mSnapshotData.mStateFilePath.c_str());
10188 }
10189
10190 /* remove the completed progress object */
10191 mParent->removeProgress(mSnapshotData.mProgressId);
10192
10193 /* clear out the temporary saved state data */
10194 mSnapshotData.mLastState = MachineState_Null;
10195 mSnapshotData.mProgressId.clear();
10196 mSnapshotData.mStateFilePath.setNull();
10197
10198 LogFlowThisFuncLeave();
10199 return rc;
10200}
10201
10202/**
10203 * Locks the attached media.
10204 *
10205 * All attached hard disks are locked for writing and DVD/floppy are locked for
10206 * reading. Parents of attached hard disks (if any) are locked for reading.
10207 *
10208 * This method also performs accessibility check of all media it locks: if some
10209 * media is inaccessible, the method will return a failure and a bunch of
10210 * extended error info objects per each inaccessible medium.
10211 *
10212 * Note that this method is atomic: if it returns a success, all media are
10213 * locked as described above; on failure no media is locked at all (all
10214 * succeeded individual locks will be undone).
10215 *
10216 * This method is intended to be called when the machine is in Starting or
10217 * Restoring state and asserts otherwise.
10218 *
10219 * The locks made by this method must be undone by calling #unlockMedia() when
10220 * no more needed.
10221 */
10222HRESULT SessionMachine::lockMedia()
10223{
10224 AutoCaller autoCaller(this);
10225 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
10226
10227 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10228
10229 AssertReturn( mData->mMachineState == MachineState_Starting
10230 || mData->mMachineState == MachineState_Restoring
10231 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
10232
10233 typedef std::list <ComPtr<IMedium> > MediaList;
10234
10235 try
10236 {
10237 HRESULT rc = S_OK;
10238
10239 ErrorInfoKeeper eik(true /* aIsNull */);
10240 MultiResult mrc(S_OK);
10241
10242 /* Lock all medium objects attached to the VM.
10243 * Get status for inaccessible media as well. */
10244 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
10245 it != mMediaData->mAttachments.end();
10246 ++it)
10247 {
10248 DeviceType_T devType = (*it)->getType();
10249 ComObjPtr<Medium> medium = (*it)->getMedium();
10250
10251 bool first = true;
10252
10253 /** @todo split out the media locking, and put it into
10254 * MediumImpl.cpp, as it needs this functionality too. */
10255 while (!medium.isNull())
10256 {
10257 MediumState_T mediumState = medium->getState();
10258
10259 /* accessibility check must be first, otherwise locking
10260 * interferes with getting the medium state. */
10261 if (mediumState == MediumState_Inaccessible)
10262 {
10263 rc = medium->RefreshState(&mediumState);
10264 if (FAILED(rc)) throw rc;
10265
10266 if (mediumState == MediumState_Inaccessible)
10267 {
10268 Bstr error;
10269 rc = medium->COMGETTER(LastAccessError)(error.asOutParam());
10270 if (FAILED(rc)) throw rc;
10271
10272 Bstr loc;
10273 rc = medium->COMGETTER(Location)(loc.asOutParam());
10274 if (FAILED(rc)) throw rc;
10275
10276 /* collect multiple errors */
10277 eik.restore();
10278
10279 /* be in sync with MediumBase::setStateError() */
10280 Assert(!error.isEmpty());
10281 mrc = setError(E_FAIL,
10282 tr("Medium '%ls' is not accessible. %ls"),
10283 loc.raw(),
10284 error.raw());
10285
10286 eik.fetch();
10287 }
10288 }
10289
10290 if (first)
10291 {
10292 if (devType != DeviceType_DVD)
10293 {
10294 /* HardDisk and Floppy medium must be locked for writing */
10295 rc = medium->LockWrite(NULL);
10296 if (FAILED(rc)) throw rc;
10297 }
10298 else
10299 {
10300 /* DVD medium must be locked for reading */
10301 rc = medium->LockRead(NULL);
10302 if (FAILED(rc)) throw rc;
10303 }
10304
10305 mData->mSession.mLockedMedia.push_back(
10306 Data::Session::LockedMedia::value_type(
10307 ComPtr<IMedium>(medium), true));
10308
10309 first = false;
10310 }
10311 else
10312 {
10313 rc = medium->LockRead(NULL);
10314 if (FAILED(rc)) throw rc;
10315
10316 mData->mSession.mLockedMedia.push_back(
10317 Data::Session::LockedMedia::value_type(
10318 ComPtr<IMedium>(medium), false));
10319 }
10320
10321
10322 /* no locks or callers here since there should be no way to
10323 * change the hard disk parent at this point (as it is still
10324 * attached to the machine) */
10325 medium = medium->getParent();
10326 }
10327 }
10328
10329 /* @todo r=dj is this correct? first restoring the eik and then throwing? */
10330 eik.restore();
10331 HRESULT rc2 = (HRESULT)mrc;
10332 if (FAILED(rc2)) throw rc2;
10333 }
10334 catch (HRESULT aRC)
10335 {
10336 /* Unlock all locked media on failure */
10337 unlockMedia();
10338 return aRC;
10339 }
10340
10341 return S_OK;
10342}
10343
10344/**
10345 * Undoes the locks made by by #lockMedia().
10346 */
10347void SessionMachine::unlockMedia()
10348{
10349 AutoCaller autoCaller(this);
10350 AssertComRCReturnVoid (autoCaller.rc());
10351
10352 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10353
10354 /* we may be holding important error info on the current thread;
10355 * preserve it */
10356 ErrorInfoKeeper eik;
10357
10358 HRESULT rc = S_OK;
10359
10360 for (Data::Session::LockedMedia::const_iterator
10361 it = mData->mSession.mLockedMedia.begin();
10362 it != mData->mSession.mLockedMedia.end(); ++it)
10363 {
10364 MediumState_T state;
10365 if (it->second)
10366 rc = it->first->UnlockWrite (&state);
10367 else
10368 rc = it->first->UnlockRead (&state);
10369
10370 /* The second can happen if an object was re-locked in
10371 * Machine::fixupMedia(). The last can happen when e.g a DVD/Floppy
10372 * image was unmounted at runtime. */
10373 Assert (SUCCEEDED(rc) || state == MediumState_LockedRead || state == MediumState_Created);
10374 }
10375
10376 mData->mSession.mLockedMedia.clear();
10377}
10378
10379/**
10380 * Helper to change the machine state (reimplementation).
10381 *
10382 * @note Locks this object for writing.
10383 */
10384HRESULT SessionMachine::setMachineState (MachineState_T aMachineState)
10385{
10386 LogFlowThisFuncEnter();
10387 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
10388
10389 AutoCaller autoCaller(this);
10390 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
10391
10392 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10393
10394 MachineState_T oldMachineState = mData->mMachineState;
10395
10396 AssertMsgReturn(oldMachineState != aMachineState,
10397 ("oldMachineState=%s, aMachineState=%s\n",
10398 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
10399 E_FAIL);
10400
10401 HRESULT rc = S_OK;
10402
10403 int stsFlags = 0;
10404 bool deleteSavedState = false;
10405
10406 /* detect some state transitions */
10407
10408 if ( ( oldMachineState == MachineState_Saved
10409 && aMachineState == MachineState_Restoring)
10410 || ( ( oldMachineState == MachineState_PoweredOff
10411 || oldMachineState == MachineState_Teleported
10412 || oldMachineState == MachineState_Aborted
10413 )
10414 && ( aMachineState == MachineState_TeleportingIn
10415 || aMachineState == MachineState_Starting
10416 )
10417 )
10418 )
10419 {
10420 /* The EMT thread is about to start */
10421
10422 /* Nothing to do here for now... */
10423
10424 /// @todo NEWMEDIA don't let mDVDDrive and other children
10425 /// change anything when in the Starting/Restoring state
10426 }
10427 else if ( ( oldMachineState == MachineState_Running
10428 || oldMachineState == MachineState_Paused
10429 || oldMachineState == MachineState_Teleporting
10430 || oldMachineState == MachineState_LiveSnapshotting
10431 || oldMachineState == MachineState_Stuck
10432 || oldMachineState == MachineState_Starting
10433 || oldMachineState == MachineState_Stopping
10434 || oldMachineState == MachineState_Saving
10435 || oldMachineState == MachineState_Restoring
10436 || oldMachineState == MachineState_TeleportingPausedVM
10437 || oldMachineState == MachineState_TeleportingIn
10438 )
10439 && ( aMachineState == MachineState_PoweredOff
10440 || aMachineState == MachineState_Saved
10441 || aMachineState == MachineState_Teleported
10442 || aMachineState == MachineState_Aborted
10443 )
10444 /* ignore PoweredOff->Saving->PoweredOff transition when taking a
10445 * snapshot */
10446 && ( mSnapshotData.mSnapshot.isNull()
10447 || mSnapshotData.mLastState >= MachineState_Running /** @todo Live Migration: clean up (lazy bird) */
10448 )
10449 )
10450 {
10451 /* The EMT thread has just stopped, unlock attached media. Note that as
10452 * opposed to locking that is done from Console, we do unlocking here
10453 * because the VM process may have aborted before having a chance to
10454 * properly unlock all media it locked. */
10455
10456 unlockMedia();
10457 }
10458
10459 if (oldMachineState == MachineState_Restoring)
10460 {
10461 if (aMachineState != MachineState_Saved)
10462 {
10463 /*
10464 * delete the saved state file once the machine has finished
10465 * restoring from it (note that Console sets the state from
10466 * Restoring to Saved if the VM couldn't restore successfully,
10467 * to give the user an ability to fix an error and retry --
10468 * we keep the saved state file in this case)
10469 */
10470 deleteSavedState = true;
10471 }
10472 }
10473 else if ( oldMachineState == MachineState_Saved
10474 && ( aMachineState == MachineState_PoweredOff
10475 || aMachineState == MachineState_Aborted
10476 || aMachineState == MachineState_Teleported
10477 )
10478 )
10479 {
10480 /*
10481 * delete the saved state after Console::DiscardSavedState() is called
10482 * or if the VM process (owning a direct VM session) crashed while the
10483 * VM was Saved
10484 */
10485
10486 /// @todo (dmik)
10487 // Not sure that deleting the saved state file just because of the
10488 // client death before it attempted to restore the VM is a good
10489 // thing. But when it crashes we need to go to the Aborted state
10490 // which cannot have the saved state file associated... The only
10491 // way to fix this is to make the Aborted condition not a VM state
10492 // but a bool flag: i.e., when a crash occurs, set it to true and
10493 // change the state to PoweredOff or Saved depending on the
10494 // saved state presence.
10495
10496 deleteSavedState = true;
10497 mData->mCurrentStateModified = TRUE;
10498 stsFlags |= SaveSTS_CurStateModified;
10499 }
10500
10501 if ( aMachineState == MachineState_Starting
10502 || aMachineState == MachineState_Restoring
10503 || aMachineState == MachineState_TeleportingIn
10504 )
10505 {
10506 /* set the current state modified flag to indicate that the current
10507 * state is no more identical to the state in the
10508 * current snapshot */
10509 if (!mData->mCurrentSnapshot.isNull())
10510 {
10511 mData->mCurrentStateModified = TRUE;
10512 stsFlags |= SaveSTS_CurStateModified;
10513 }
10514 }
10515
10516 if (deleteSavedState)
10517 {
10518 if (mRemoveSavedState)
10519 {
10520 Assert(!mSSData->mStateFilePath.isEmpty());
10521 RTFileDelete(mSSData->mStateFilePath.c_str());
10522 }
10523 mSSData->mStateFilePath.setNull();
10524 stsFlags |= SaveSTS_StateFilePath;
10525 }
10526
10527 /* redirect to the underlying peer machine */
10528 mPeer->setMachineState (aMachineState);
10529
10530 if ( aMachineState == MachineState_PoweredOff
10531 || aMachineState == MachineState_Teleported
10532 || aMachineState == MachineState_Aborted
10533 || aMachineState == MachineState_Saved)
10534 {
10535 /* the machine has stopped execution
10536 * (or the saved state file was adopted) */
10537 stsFlags |= SaveSTS_StateTimeStamp;
10538 }
10539
10540 if ( ( oldMachineState == MachineState_PoweredOff
10541 || oldMachineState == MachineState_Aborted
10542 || oldMachineState == MachineState_Teleported
10543 )
10544 && aMachineState == MachineState_Saved)
10545 {
10546 /* the saved state file was adopted */
10547 Assert(!mSSData->mStateFilePath.isEmpty());
10548 stsFlags |= SaveSTS_StateFilePath;
10549 }
10550
10551 rc = saveStateSettings (stsFlags);
10552
10553 if ( ( oldMachineState != MachineState_PoweredOff
10554 && oldMachineState != MachineState_Aborted
10555 && oldMachineState != MachineState_Teleported
10556 )
10557 && ( aMachineState == MachineState_PoweredOff
10558 || aMachineState == MachineState_Aborted
10559 || aMachineState == MachineState_Teleported
10560 )
10561 )
10562 {
10563 /* we've been shut down for any reason */
10564 /* no special action so far */
10565 }
10566
10567 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
10568 LogFlowThisFuncLeave();
10569 return rc;
10570}
10571
10572/**
10573 * Sends the current machine state value to the VM process.
10574 *
10575 * @note Locks this object for reading, then calls a client process.
10576 */
10577HRESULT SessionMachine::updateMachineStateOnClient()
10578{
10579 AutoCaller autoCaller(this);
10580 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
10581
10582 ComPtr<IInternalSessionControl> directControl;
10583 {
10584 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10585 AssertReturn(!!mData, E_FAIL);
10586 directControl = mData->mSession.mDirectControl;
10587
10588 /* directControl may be already set to NULL here in #OnSessionEnd()
10589 * called too early by the direct session process while there is still
10590 * some operation (like discarding the snapshot) in progress. The client
10591 * process in this case is waiting inside Session::close() for the
10592 * "end session" process object to complete, while #uninit() called by
10593 * #checkForDeath() on the Watcher thread is waiting for the pending
10594 * operation to complete. For now, we accept this inconsitent behavior
10595 * and simply do nothing here. */
10596
10597 if (mData->mSession.mState == SessionState_Closing)
10598 return S_OK;
10599
10600 AssertReturn(!directControl.isNull(), E_FAIL);
10601 }
10602
10603 return directControl->UpdateMachineState (mData->mMachineState);
10604}
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