VirtualBox

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

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

Main: fix regressions with renaming VMs; as a welcome side effect, Machine::saveSettings() no longer implicitly calls VirtualBox::saveSettings() and therefore no longer requires the global VirtualBox lock

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