VirtualBox

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

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

Main: IMachine::SetMemoryBalloonSize may change the size of the balloon even at runtime

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