VirtualBox

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

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

Main/Machine: correctly release the lock

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

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