VirtualBox

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

Last change on this file since 30935 was 30934, checked in by vboxsync, 14 years ago

Main: automatically fix host-specific audio drivers when loading machine settings

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