VirtualBox

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

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

Turn on VPID by default (VT-x).

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

© 2023 Oracle
ContactPrivacy policyTerms of Use