VirtualBox

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

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

Main/VirtualBox: new parameter for overriding VM file existence check on creation (2nd try)

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