VirtualBox

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

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

build fix

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

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