VirtualBox

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

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

Main: rename internal method

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

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