VirtualBox

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

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

Main: attempt at USB locking fixes

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

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