VirtualBox

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

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

Main: warning

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