VirtualBox

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

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

Main: fixed saving guest properties at machine power off

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

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