VirtualBox

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

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

Main: do not hold any other lock while calling VirtualBox::saveSettings (mostly comments, only real change is in DHCPServer); also, VirtualBox lock is not needed in SessionMachine::endSavingState

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

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