VirtualBox

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

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

Main: cleanup: remove all CheckComRC* macros (no functional change)

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

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