VirtualBox

Ticket #7511: MachineImpl.cpp

File MachineImpl.cpp, 367.0 KB (added by Twisted Lincoln, Inc., 14 years ago)

Fixed MachineImpl.cpp

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

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