VirtualBox

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

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

Main/OVF: import vbox:Machine XML within OVF, first batch (XML is parsed and machine config created, but COM Machine can't handle it yet)

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

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