VirtualBox

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

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

Main: added a note

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