VirtualBox

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

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

Currently we only support memory ballooning on all 64-bit hosts except Mac OS X. Return a proper error value on unsupported platforms.

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

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