VirtualBox

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

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

Main: fix initialization order in machine

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

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