VirtualBox

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

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

Main: one function instead of two for finding DVD and floppy images

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 375.3 KB
Line 
1/* $Id: MachineImpl.cpp 31281 2010-08-02 10:35:19Z 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_Unlocked;
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
2680/**
2681 * @note Locks objects!
2682 */
2683STDMETHODIMP Machine::LockMachine(ISession *aSession,
2684 LockType_T lockType)
2685{
2686 CheckComArgNotNull(aSession);
2687
2688 AutoCaller autoCaller(this);
2689 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2690
2691 /* check the session state */
2692 SessionState_T state;
2693 HRESULT rc = aSession->COMGETTER(State)(&state);
2694 if (FAILED(rc)) return rc;
2695
2696 if (state != SessionState_Unlocked)
2697 return setError(VBOX_E_INVALID_OBJECT_STATE,
2698 tr("The given session is busy"));
2699
2700 // get the client's IInternalSessionControl interface
2701 ComPtr<IInternalSessionControl> pSessionControl = aSession;
2702 ComAssertMsgRet(!!pSessionControl, ("No IInternalSessionControl interface"),
2703 E_INVALIDARG);
2704
2705 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2706
2707 if (!mData->mRegistered)
2708 return setError(E_UNEXPECTED,
2709 tr("The machine '%ls' is not registered"),
2710 mUserData->mName.raw());
2711
2712 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
2713
2714 SessionState_T oldState = mData->mSession.mState;
2715 /* Hack: in case the session is closing and there is a progress object
2716 * which allows waiting for the session to be closed, take the opportunity
2717 * and do a limited wait (max. 1 second). This helps a lot when the system
2718 * is busy and thus session closing can take a little while. */
2719 if ( mData->mSession.mState == SessionState_Unlocking
2720 && mData->mSession.mProgress)
2721 {
2722 alock.release();
2723 mData->mSession.mProgress->WaitForCompletion(1000);
2724 alock.acquire();
2725 LogFlowThisFunc(("after waiting: mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
2726 }
2727
2728 // try again now
2729 if ( (mData->mSession.mState == SessionState_Locked) // machine is write-locked already (i.e. session machine exists)
2730 && (lockType == LockType_Shared) // caller wants a shared link to the existing session that holds the write lock:
2731 )
2732 {
2733 // OK, share the session... we are now dealing with three processes:
2734 // 1) VBoxSVC (where this code runs);
2735 // 2) process C: the caller's client process (who wants a shared session);
2736 // 3) process W: the process which already holds the write lock on the machine (write-locking session)
2737
2738 // copy pointers to W (the write-locking session) before leaving lock (these must not be NULL)
2739 ComPtr<IInternalSessionControl> pSessionW = mData->mSession.mDirectControl;
2740 ComAssertRet(!pSessionW.isNull(), E_FAIL);
2741 ComObjPtr<SessionMachine> pSessionMachine = mData->mSession.mMachine;
2742 AssertReturn(!pSessionMachine.isNull(), E_FAIL);
2743
2744 /*
2745 * Leave the lock before calling the client process. It's safe here
2746 * since the only thing to do after we get the lock again is to add
2747 * the remote control to the list (which doesn't directly influence
2748 * anything).
2749 */
2750 alock.leave();
2751
2752 // get the console of the session holding the write lock (this is a remote call)
2753 ComPtr<IConsole> pConsoleW;
2754 LogFlowThisFunc(("Calling GetRemoteConsole()...\n"));
2755 rc = pSessionW->GetRemoteConsole(pConsoleW.asOutParam());
2756 LogFlowThisFunc(("GetRemoteConsole() returned %08X\n", rc));
2757 if (FAILED(rc))
2758 // the failure may occur w/o any error info (from RPC), so provide one
2759 return setError(VBOX_E_VM_ERROR,
2760 tr("Failed to get a console object from the direct session (%Rrc)"), rc);
2761
2762 ComAssertRet(!pConsoleW.isNull(), E_FAIL);
2763
2764 // share the session machine and W's console with the caller's session
2765 LogFlowThisFunc(("Calling AssignRemoteMachine()...\n"));
2766 rc = pSessionControl->AssignRemoteMachine(pSessionMachine, pConsoleW);
2767 LogFlowThisFunc(("AssignRemoteMachine() returned %08X\n", rc));
2768
2769 if (FAILED(rc))
2770 // the failure may occur w/o any error info (from RPC), so provide one
2771 return setError(VBOX_E_VM_ERROR,
2772 tr("Failed to assign the machine to the session (%Rrc)"), rc);
2773 alock.enter();
2774
2775 // need to revalidate the state after entering the lock again
2776 if (mData->mSession.mState != SessionState_Locked)
2777 {
2778 pSessionControl->Uninitialize();
2779 return setError(VBOX_E_INVALID_SESSION_STATE,
2780 tr("The machine '%ls' was unlocked unexpectedly while attempting to share its session"),
2781 mUserData->mName.raw());
2782 }
2783
2784 // add the caller's session to the list
2785 mData->mSession.mRemoteControls.push_back(pSessionControl);
2786 }
2787 else if ( mData->mSession.mState == SessionState_Locked
2788 || mData->mSession.mState == SessionState_Unlocking
2789 )
2790 {
2791 // sharing not permitted, or machine still unlocking:
2792 return setError(VBOX_E_INVALID_OBJECT_STATE,
2793 tr("The machine '%ls' is already locked for a session (or being unlocked)"),
2794 mUserData->mName.raw());
2795 }
2796 else
2797 {
2798 // machine is not locked: then write-lock the machine (create the session machine)
2799
2800 // must not be busy
2801 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
2802
2803 // get the caller's session PID
2804 RTPROCESS pid = NIL_RTPROCESS;
2805 AssertCompile(sizeof(ULONG) == sizeof(RTPROCESS));
2806 pSessionControl->GetPID((ULONG*)&pid);
2807 Assert(pid != NIL_RTPROCESS);
2808
2809 bool fLaunchingVMProcess = (mData->mSession.mState == SessionState_Spawning);
2810
2811 if (fLaunchingVMProcess)
2812 {
2813 // this machine is awaiting for a spawning session to be opened:
2814 // then the calling process must be the one that got started by
2815 // launchVMProcess()
2816
2817 LogFlowThisFunc(("mSession.mPid=%d(0x%x)\n", mData->mSession.mPid, mData->mSession.mPid));
2818 LogFlowThisFunc(("session.pid=%d(0x%x)\n", pid, pid));
2819
2820 if (mData->mSession.mPid != pid)
2821 return setError(E_ACCESSDENIED,
2822 tr("An unexpected process (PID=0x%08X) has tried to lock the "
2823 "machine '%ls', while only the process started by launchVMProcess (PID=0x%08X) is allowed"),
2824 pid, mUserData->mName.raw(), mData->mSession.mPid);
2825 }
2826
2827 // create the mutable SessionMachine from the current machine
2828 ComObjPtr<SessionMachine> sessionMachine;
2829 sessionMachine.createObject();
2830 rc = sessionMachine->init(this);
2831 AssertComRC(rc);
2832
2833 /* NOTE: doing return from this function after this point but
2834 * before the end is forbidden since it may call SessionMachine::uninit()
2835 * (through the ComObjPtr's destructor) which requests the VirtualBox write
2836 * lock while still holding the Machine lock in alock so that a deadlock
2837 * is possible due to the wrong lock order. */
2838
2839 if (SUCCEEDED(rc))
2840 {
2841 /*
2842 * Set the session state to Spawning to protect against subsequent
2843 * attempts to open a session and to unregister the machine after
2844 * we leave the lock.
2845 */
2846 SessionState_T origState = mData->mSession.mState;
2847 mData->mSession.mState = SessionState_Spawning;
2848
2849 /*
2850 * Leave the lock before calling the client process -- it will call
2851 * Machine/SessionMachine methods. Leaving the lock here is quite safe
2852 * because the state is Spawning, so that openRemotesession() and
2853 * openExistingSession() calls will fail. This method, called before we
2854 * enter the lock again, will fail because of the wrong PID.
2855 *
2856 * Note that mData->mSession.mRemoteControls accessed outside
2857 * the lock may not be modified when state is Spawning, so it's safe.
2858 */
2859 alock.leave();
2860
2861 LogFlowThisFunc(("Calling AssignMachine()...\n"));
2862 rc = pSessionControl->AssignMachine(sessionMachine);
2863 LogFlowThisFunc(("AssignMachine() returned %08X\n", rc));
2864
2865 /* The failure may occur w/o any error info (from RPC), so provide one */
2866 if (FAILED(rc))
2867 setError(VBOX_E_VM_ERROR,
2868 tr("Failed to assign the machine to the session (%Rrc)"), rc);
2869
2870 if ( SUCCEEDED(rc)
2871 && fLaunchingVMProcess
2872 )
2873 {
2874 /* complete the remote session initialization */
2875
2876 /* get the console from the direct session */
2877 ComPtr<IConsole> console;
2878 rc = pSessionControl->GetRemoteConsole(console.asOutParam());
2879 ComAssertComRC(rc);
2880
2881 if (SUCCEEDED(rc) && !console)
2882 {
2883 ComAssert(!!console);
2884 rc = E_FAIL;
2885 }
2886
2887 /* assign machine & console to the remote session */
2888 if (SUCCEEDED(rc))
2889 {
2890 /*
2891 * after openRemoteSession(), the first and the only
2892 * entry in remoteControls is that remote session
2893 */
2894 LogFlowThisFunc(("Calling AssignRemoteMachine()...\n"));
2895 rc = mData->mSession.mRemoteControls.front()->AssignRemoteMachine(sessionMachine, console);
2896 LogFlowThisFunc(("AssignRemoteMachine() returned %08X\n", rc));
2897
2898 /* The failure may occur w/o any error info (from RPC), so provide one */
2899 if (FAILED(rc))
2900 setError(VBOX_E_VM_ERROR,
2901 tr("Failed to assign the machine to the remote session (%Rrc)"), rc);
2902 }
2903
2904 if (FAILED(rc))
2905 pSessionControl->Uninitialize();
2906 }
2907
2908 /* enter the lock again */
2909 alock.enter();
2910
2911 /* Restore the session state */
2912 mData->mSession.mState = origState;
2913 }
2914
2915 // finalize spawning anyway (this is why we don't return on errors above)
2916 if (fLaunchingVMProcess)
2917 {
2918 /* Note that the progress object is finalized later */
2919 /** @todo Consider checking mData->mSession.mProgress for cancellation
2920 * around here. */
2921
2922 /* We don't reset mSession.mPid here because it is necessary for
2923 * SessionMachine::uninit() to reap the child process later. */
2924
2925 if (FAILED(rc))
2926 {
2927 /* Close the remote session, remove the remote control from the list
2928 * and reset session state to Closed (@note keep the code in sync
2929 * with the relevant part in openSession()). */
2930
2931 Assert(mData->mSession.mRemoteControls.size() == 1);
2932 if (mData->mSession.mRemoteControls.size() == 1)
2933 {
2934 ErrorInfoKeeper eik;
2935 mData->mSession.mRemoteControls.front()->Uninitialize();
2936 }
2937
2938 mData->mSession.mRemoteControls.clear();
2939 mData->mSession.mState = SessionState_Unlocked;
2940 }
2941 }
2942 else
2943 {
2944 /* memorize PID of the directly opened session */
2945 if (SUCCEEDED(rc))
2946 mData->mSession.mPid = pid;
2947 }
2948
2949 if (SUCCEEDED(rc))
2950 {
2951 /* memorize the direct session control and cache IUnknown for it */
2952 mData->mSession.mDirectControl = pSessionControl;
2953 mData->mSession.mState = SessionState_Locked;
2954 /* associate the SessionMachine with this Machine */
2955 mData->mSession.mMachine = sessionMachine;
2956
2957 /* request an IUnknown pointer early from the remote party for later
2958 * identity checks (it will be internally cached within mDirectControl
2959 * at least on XPCOM) */
2960 ComPtr<IUnknown> unk = mData->mSession.mDirectControl;
2961 NOREF(unk);
2962 }
2963
2964 /* Leave the lock since SessionMachine::uninit() locks VirtualBox which
2965 * would break the lock order */
2966 alock.leave();
2967
2968 /* uninitialize the created session machine on failure */
2969 if (FAILED(rc))
2970 sessionMachine->uninit();
2971
2972 }
2973
2974 if (SUCCEEDED(rc))
2975 {
2976 /*
2977 * tell the client watcher thread to update the set of
2978 * machines that have open sessions
2979 */
2980 mParent->updateClientWatcher();
2981
2982 if (oldState != SessionState_Locked)
2983 /* fire an event */
2984 mParent->onSessionStateChange(getId(), SessionState_Locked);
2985 }
2986
2987 return rc;
2988}
2989
2990/**
2991 * @note Locks objects!
2992 */
2993STDMETHODIMP Machine::LaunchVMProcess(ISession *aSession,
2994 IN_BSTR aType,
2995 IN_BSTR aEnvironment,
2996 IProgress **aProgress)
2997{
2998 CheckComArgNotNull(aSession);
2999 CheckComArgStrNotEmptyOrNull(aType);
3000 CheckComArgOutSafeArrayPointerValid(aProgress);
3001
3002 AutoCaller autoCaller(this);
3003 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3004
3005 /* check the session state */
3006 SessionState_T state;
3007 HRESULT rc = aSession->COMGETTER(State)(&state);
3008 if (FAILED(rc)) return rc;
3009
3010 if (state != SessionState_Unlocked)
3011 return setError(VBOX_E_INVALID_OBJECT_STATE,
3012 tr("The given session is busy"));
3013
3014 /* get the IInternalSessionControl interface */
3015 ComPtr<IInternalSessionControl> control = aSession;
3016 ComAssertMsgRet(!!control, ("No IInternalSessionControl interface"),
3017 E_INVALIDARG);
3018
3019 /* get the teleporter enable state for the progress object init. */
3020 BOOL fTeleporterEnabled;
3021 rc = COMGETTER(TeleporterEnabled)(&fTeleporterEnabled);
3022 if (FAILED(rc))
3023 return rc;
3024
3025 /* create a progress object */
3026 ComObjPtr<ProgressProxy> progress;
3027 progress.createObject();
3028 rc = progress->init(mParent,
3029 static_cast<IMachine*>(this),
3030 Bstr(tr("Spawning session")),
3031 TRUE /* aCancelable */,
3032 fTeleporterEnabled ? 20 : 10 /* uTotalOperationsWeight */,
3033 Bstr(tr("Spawning session")),
3034 2 /* uFirstOperationWeight */,
3035 fTeleporterEnabled ? 3 : 1 /* cOtherProgressObjectOperations */);
3036 if (SUCCEEDED(rc))
3037 {
3038 rc = openRemoteSession(control, aType, aEnvironment, progress);
3039 if (SUCCEEDED(rc))
3040 {
3041 progress.queryInterfaceTo(aProgress);
3042
3043 /* signal the client watcher thread */
3044 mParent->updateClientWatcher();
3045
3046 /* fire an event */
3047 mParent->onSessionStateChange(getId(), SessionState_Spawning);
3048 }
3049 }
3050
3051 return rc;
3052}
3053
3054STDMETHODIMP Machine::SetBootOrder(ULONG aPosition, DeviceType_T aDevice)
3055{
3056 if (aPosition < 1 || aPosition > SchemaDefs::MaxBootPosition)
3057 return setError(E_INVALIDARG,
3058 tr("Invalid boot position: %lu (must be in range [1, %lu])"),
3059 aPosition, SchemaDefs::MaxBootPosition);
3060
3061 if (aDevice == DeviceType_USB)
3062 return setError(E_NOTIMPL,
3063 tr("Booting from USB device is currently not supported"));
3064
3065 AutoCaller autoCaller(this);
3066 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3067
3068 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3069
3070 HRESULT rc = checkStateDependency(MutableStateDep);
3071 if (FAILED(rc)) return rc;
3072
3073 setModified(IsModified_MachineData);
3074 mHWData.backup();
3075 mHWData->mBootOrder[aPosition - 1] = aDevice;
3076
3077 return S_OK;
3078}
3079
3080STDMETHODIMP Machine::GetBootOrder(ULONG aPosition, DeviceType_T *aDevice)
3081{
3082 if (aPosition < 1 || aPosition > SchemaDefs::MaxBootPosition)
3083 return setError(E_INVALIDARG,
3084 tr("Invalid boot position: %lu (must be in range [1, %lu])"),
3085 aPosition, SchemaDefs::MaxBootPosition);
3086
3087 AutoCaller autoCaller(this);
3088 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3089
3090 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3091
3092 *aDevice = mHWData->mBootOrder[aPosition - 1];
3093
3094 return S_OK;
3095}
3096
3097STDMETHODIMP Machine::AttachDevice(IN_BSTR aControllerName,
3098 LONG aControllerPort,
3099 LONG aDevice,
3100 DeviceType_T aType,
3101 IN_BSTR aId)
3102{
3103 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d aType=%d aId=\"%ls\"\n",
3104 aControllerName, aControllerPort, aDevice, aType, aId));
3105
3106 CheckComArgStrNotEmptyOrNull(aControllerName);
3107
3108 AutoCaller autoCaller(this);
3109 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3110
3111 // if this becomes true then we need to call saveSettings in the end
3112 // @todo r=dj there is no error handling so far...
3113 bool fNeedsSaveSettings = false;
3114
3115 // request the host lock first, since might be calling Host methods for getting host drives;
3116 // next, protect the media tree all the while we're in here, as well as our member variables
3117 AutoMultiWriteLock2 alock(mParent->host()->lockHandle(),
3118 this->lockHandle() COMMA_LOCKVAL_SRC_POS);
3119 AutoWriteLock treeLock(&mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3120
3121 HRESULT rc = checkStateDependency(MutableStateDep);
3122 if (FAILED(rc)) return rc;
3123
3124 /// @todo NEWMEDIA implicit machine registration
3125 if (!mData->mRegistered)
3126 return setError(VBOX_E_INVALID_OBJECT_STATE,
3127 tr("Cannot attach storage devices to an unregistered machine"));
3128
3129 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
3130
3131 if (Global::IsOnlineOrTransient(mData->mMachineState))
3132 return setError(VBOX_E_INVALID_VM_STATE,
3133 tr("Invalid machine state: %s"),
3134 Global::stringifyMachineState(mData->mMachineState));
3135
3136 /* Check for an existing controller. */
3137 ComObjPtr<StorageController> ctl;
3138 rc = getStorageControllerByName(aControllerName, ctl, true /* aSetError */);
3139 if (FAILED(rc)) return rc;
3140
3141 /* check that the port and device are not out of range. */
3142 ULONG portCount;
3143 ULONG devicesPerPort;
3144 rc = ctl->COMGETTER(PortCount)(&portCount);
3145 if (FAILED(rc)) return rc;
3146 rc = ctl->COMGETTER(MaxDevicesPerPortCount)(&devicesPerPort);
3147 if (FAILED(rc)) return rc;
3148
3149 if ( (aControllerPort < 0)
3150 || (aControllerPort >= (LONG)portCount)
3151 || (aDevice < 0)
3152 || (aDevice >= (LONG)devicesPerPort)
3153 )
3154 return setError(E_INVALIDARG,
3155 tr("The port and/or count parameter are out of range [%lu:%lu]"),
3156 portCount,
3157 devicesPerPort);
3158
3159 /* check if the device slot is already busy */
3160 MediumAttachment *pAttachTemp;
3161 if ((pAttachTemp = findAttachment(mMediaData->mAttachments,
3162 aControllerName,
3163 aControllerPort,
3164 aDevice)))
3165 {
3166 Medium *pMedium = pAttachTemp->getMedium();
3167 if (pMedium)
3168 {
3169 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3170 return setError(VBOX_E_OBJECT_IN_USE,
3171 tr("Medium '%s' is already attached to port %d, device %d of controller '%ls' of this virtual machine"),
3172 pMedium->getLocationFull().raw(),
3173 aControllerPort,
3174 aDevice,
3175 aControllerName);
3176 }
3177 else
3178 return setError(VBOX_E_OBJECT_IN_USE,
3179 tr("Device is already attached to port %d, device %d of controller '%ls' of this virtual machine"),
3180 aControllerPort, aDevice, aControllerName);
3181 }
3182
3183 Guid uuid(aId);
3184
3185 ComObjPtr<Medium> medium;
3186
3187 switch (aType)
3188 {
3189 case DeviceType_HardDisk:
3190 /* find a hard disk by UUID */
3191 rc = mParent->findHardDisk(&uuid, NULL, true /* aSetError */, &medium);
3192 if (FAILED(rc)) return rc;
3193 break;
3194
3195 case DeviceType_DVD: // @todo r=dj eliminate this, replace with findDVDImage
3196 if (!uuid.isEmpty())
3197 {
3198 /* first search for host drive */
3199 SafeIfaceArray<IMedium> drivevec;
3200 rc = mParent->host()->COMGETTER(DVDDrives)(ComSafeArrayAsOutParam(drivevec));
3201 if (SUCCEEDED(rc))
3202 {
3203 for (size_t i = 0; i < drivevec.size(); ++i)
3204 {
3205 /// @todo eliminate this conversion
3206 ComObjPtr<Medium> med = (Medium *)drivevec[i];
3207 if (med->getId() == uuid)
3208 {
3209 medium = med;
3210 break;
3211 }
3212 }
3213 }
3214
3215 if (medium.isNull())
3216 {
3217 /* find a DVD image by UUID */
3218 rc = mParent->findDVDOrFloppyImage(DeviceType_DVD, &uuid, Utf8Str::Empty, true /* aSetError */, &medium);
3219 if (FAILED(rc)) return rc;
3220 }
3221 }
3222 else
3223 {
3224 /* null UUID means null medium, which needs no code */
3225 }
3226 break;
3227
3228 case DeviceType_Floppy: // @todo r=dj eliminate this, replace with findFloppyImage
3229 if (!uuid.isEmpty())
3230 {
3231 /* first search for host drive */
3232 SafeIfaceArray<IMedium> drivevec;
3233 rc = mParent->host()->COMGETTER(FloppyDrives)(ComSafeArrayAsOutParam(drivevec));
3234 if (SUCCEEDED(rc))
3235 {
3236 for (size_t i = 0; i < drivevec.size(); ++i)
3237 {
3238 /// @todo eliminate this conversion
3239 ComObjPtr<Medium> med = (Medium *)drivevec[i];
3240 if (med->getId() == uuid)
3241 {
3242 medium = med;
3243 break;
3244 }
3245 }
3246 }
3247
3248 if (medium.isNull())
3249 {
3250 /* find a floppy image by UUID */
3251 rc = mParent->findDVDOrFloppyImage(DeviceType_Floppy, &uuid, Utf8Str::Empty, true /* aSetError */, &medium);
3252 if (FAILED(rc)) return rc;
3253 }
3254 }
3255 else
3256 {
3257 /* null UUID means null medium, which needs no code */
3258 }
3259 break;
3260
3261 default:
3262 return setError(E_INVALIDARG,
3263 tr("The device type %d is not recognized"),
3264 (int)aType);
3265 }
3266
3267 AutoCaller mediumCaller(medium);
3268 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3269
3270 AutoWriteLock mediumLock(medium COMMA_LOCKVAL_SRC_POS);
3271
3272 if ( (pAttachTemp = findAttachment(mMediaData->mAttachments, medium))
3273 && !medium.isNull()
3274 )
3275 return setError(VBOX_E_OBJECT_IN_USE,
3276 tr("Medium '%s' is already attached to this virtual machine"),
3277 medium->getLocationFull().raw());
3278
3279 bool indirect = false;
3280 if (!medium.isNull())
3281 indirect = medium->isReadOnly();
3282 bool associate = true;
3283
3284 do
3285 {
3286 if (aType == DeviceType_HardDisk && mMediaData.isBackedUp())
3287 {
3288 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
3289
3290 /* check if the medium was attached to the VM before we started
3291 * changing attachments in which case the attachment just needs to
3292 * be restored */
3293 if ((pAttachTemp = findAttachment(oldAtts, medium)))
3294 {
3295 AssertReturn(!indirect, E_FAIL);
3296
3297 /* see if it's the same bus/channel/device */
3298 if (pAttachTemp->matches(aControllerName, aControllerPort, aDevice))
3299 {
3300 /* the simplest case: restore the whole attachment
3301 * and return, nothing else to do */
3302 mMediaData->mAttachments.push_back(pAttachTemp);
3303 return S_OK;
3304 }
3305
3306 /* bus/channel/device differ; we need a new attachment object,
3307 * but don't try to associate it again */
3308 associate = false;
3309 break;
3310 }
3311 }
3312
3313 /* go further only if the attachment is to be indirect */
3314 if (!indirect)
3315 break;
3316
3317 /* perform the so called smart attachment logic for indirect
3318 * attachments. Note that smart attachment is only applicable to base
3319 * hard disks. */
3320
3321 if (medium->getParent().isNull())
3322 {
3323 /* first, investigate the backup copy of the current hard disk
3324 * attachments to make it possible to re-attach existing diffs to
3325 * another device slot w/o losing their contents */
3326 if (mMediaData.isBackedUp())
3327 {
3328 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
3329
3330 MediaData::AttachmentList::const_iterator foundIt = oldAtts.end();
3331 uint32_t foundLevel = 0;
3332
3333 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
3334 it != oldAtts.end();
3335 ++it)
3336 {
3337 uint32_t level = 0;
3338 MediumAttachment *pAttach = *it;
3339 ComObjPtr<Medium> pMedium = pAttach->getMedium();
3340 Assert(!pMedium.isNull() || pAttach->getType() != DeviceType_HardDisk);
3341 if (pMedium.isNull())
3342 continue;
3343
3344 if (pMedium->getBase(&level) == medium)
3345 {
3346 /* skip the hard disk if its currently attached (we
3347 * cannot attach the same hard disk twice) */
3348 if (findAttachment(mMediaData->mAttachments,
3349 pMedium))
3350 continue;
3351
3352 /* matched device, channel and bus (i.e. attached to the
3353 * same place) will win and immediately stop the search;
3354 * otherwise the attachment that has the youngest
3355 * descendant of medium will be used
3356 */
3357 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
3358 {
3359 /* the simplest case: restore the whole attachment
3360 * and return, nothing else to do */
3361 mMediaData->mAttachments.push_back(*it);
3362 return S_OK;
3363 }
3364 else if ( foundIt == oldAtts.end()
3365 || level > foundLevel /* prefer younger */
3366 )
3367 {
3368 foundIt = it;
3369 foundLevel = level;
3370 }
3371 }
3372 }
3373
3374 if (foundIt != oldAtts.end())
3375 {
3376 /* use the previously attached hard disk */
3377 medium = (*foundIt)->getMedium();
3378 mediumCaller.attach(medium);
3379 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3380 mediumLock.attach(medium);
3381 /* not implicit, doesn't require association with this VM */
3382 indirect = false;
3383 associate = false;
3384 /* go right to the MediumAttachment creation */
3385 break;
3386 }
3387 }
3388
3389 /* must give up the medium lock and medium tree lock as below we
3390 * go over snapshots, which needs a lock with higher lock order. */
3391 mediumLock.release();
3392 treeLock.release();
3393
3394 /* then, search through snapshots for the best diff in the given
3395 * hard disk's chain to base the new diff on */
3396
3397 ComObjPtr<Medium> base;
3398 ComObjPtr<Snapshot> snap = mData->mCurrentSnapshot;
3399 while (snap)
3400 {
3401 AutoReadLock snapLock(snap COMMA_LOCKVAL_SRC_POS);
3402
3403 const MediaData::AttachmentList &snapAtts = snap->getSnapshotMachine()->mMediaData->mAttachments;
3404
3405 MediaData::AttachmentList::const_iterator foundIt = snapAtts.end();
3406 uint32_t foundLevel = 0;
3407
3408 for (MediaData::AttachmentList::const_iterator it = snapAtts.begin();
3409 it != snapAtts.end();
3410 ++it)
3411 {
3412 MediumAttachment *pAttach = *it;
3413 ComObjPtr<Medium> pMedium = pAttach->getMedium();
3414 Assert(!pMedium.isNull() || pAttach->getType() != DeviceType_HardDisk);
3415 if (pMedium.isNull())
3416 continue;
3417
3418 uint32_t level = 0;
3419 if (pMedium->getBase(&level) == medium)
3420 {
3421 /* matched device, channel and bus (i.e. attached to the
3422 * same place) will win and immediately stop the search;
3423 * otherwise the attachment that has the youngest
3424 * descendant of medium will be used
3425 */
3426 if ( (*it)->getDevice() == aDevice
3427 && (*it)->getPort() == aControllerPort
3428 && (*it)->getControllerName() == aControllerName
3429 )
3430 {
3431 foundIt = it;
3432 break;
3433 }
3434 else if ( foundIt == snapAtts.end()
3435 || level > foundLevel /* prefer younger */
3436 )
3437 {
3438 foundIt = it;
3439 foundLevel = level;
3440 }
3441 }
3442 }
3443
3444 if (foundIt != snapAtts.end())
3445 {
3446 base = (*foundIt)->getMedium();
3447 break;
3448 }
3449
3450 snap = snap->getParent();
3451 }
3452
3453 /* re-lock medium tree and the medium, as we need it below */
3454 treeLock.acquire();
3455 mediumLock.acquire();
3456
3457 /* found a suitable diff, use it as a base */
3458 if (!base.isNull())
3459 {
3460 medium = base;
3461 mediumCaller.attach(medium);
3462 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3463 mediumLock.attach(medium);
3464 }
3465 }
3466
3467 ComObjPtr<Medium> diff;
3468 diff.createObject();
3469 rc = diff->init(mParent,
3470 medium->preferredDiffFormat().raw(),
3471 BstrFmt("%ls"RTPATH_SLASH_STR,
3472 mUserData->mSnapshotFolderFull.raw()).raw(),
3473 &fNeedsSaveSettings);
3474 if (FAILED(rc)) return rc;
3475
3476 /* Apply the normal locking logic to the entire chain. */
3477 MediumLockList *pMediumLockList(new MediumLockList());
3478 rc = diff->createMediumLockList(true /* fFailIfInaccessible */,
3479 true /* fMediumLockWrite */,
3480 medium,
3481 *pMediumLockList);
3482 if (FAILED(rc)) return rc;
3483 rc = pMediumLockList->Lock();
3484 if (FAILED(rc))
3485 return setError(rc,
3486 tr("Could not lock medium when creating diff '%s'"),
3487 diff->getLocationFull().c_str());
3488
3489 /* will leave the lock before the potentially lengthy operation, so
3490 * protect with the special state */
3491 MachineState_T oldState = mData->mMachineState;
3492 setMachineState(MachineState_SettingUp);
3493
3494 mediumLock.leave();
3495 treeLock.leave();
3496 alock.leave();
3497
3498 rc = medium->createDiffStorage(diff,
3499 MediumVariant_Standard,
3500 pMediumLockList,
3501 NULL /* aProgress */,
3502 true /* aWait */,
3503 &fNeedsSaveSettings);
3504
3505 alock.enter();
3506 treeLock.enter();
3507 mediumLock.enter();
3508
3509 setMachineState(oldState);
3510
3511 /* Unlock the media and free the associated memory. */
3512 delete pMediumLockList;
3513
3514 if (FAILED(rc)) return rc;
3515
3516 /* use the created diff for the actual attachment */
3517 medium = diff;
3518 mediumCaller.attach(medium);
3519 if (FAILED(mediumCaller.rc())) return mediumCaller.rc();
3520 mediumLock.attach(medium);
3521 }
3522 while (0);
3523
3524 ComObjPtr<MediumAttachment> attachment;
3525 attachment.createObject();
3526 rc = attachment->init(this, medium, aControllerName, aControllerPort, aDevice, aType, indirect);
3527 if (FAILED(rc)) return rc;
3528
3529 if (associate && !medium.isNull())
3530 {
3531 /* as the last step, associate the medium to the VM */
3532 rc = medium->addBackReference(mData->mUuid);
3533 /* here we can fail because of Deleting, or being in process of
3534 * creating a Diff */
3535 if (FAILED(rc)) return rc;
3536 }
3537
3538 /* success: finally remember the attachment */
3539 setModified(IsModified_Storage);
3540 mMediaData.backup();
3541 mMediaData->mAttachments.push_back(attachment);
3542
3543 if (fNeedsSaveSettings)
3544 {
3545 // save the global settings; for that we should hold only the VirtualBox lock
3546 mediumLock.release();
3547 treeLock.leave();
3548 alock.release();
3549
3550 AutoWriteLock vboxLock(mParent COMMA_LOCKVAL_SRC_POS);
3551 mParent->saveSettings();
3552 }
3553
3554 return rc;
3555}
3556
3557STDMETHODIMP Machine::DetachDevice(IN_BSTR aControllerName, LONG aControllerPort,
3558 LONG aDevice)
3559{
3560 CheckComArgStrNotEmptyOrNull(aControllerName);
3561
3562 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld\n",
3563 aControllerName, aControllerPort, aDevice));
3564
3565 AutoCaller autoCaller(this);
3566 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3567
3568 bool fNeedsSaveSettings = false;
3569
3570 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3571
3572 HRESULT rc = checkStateDependency(MutableStateDep);
3573 if (FAILED(rc)) return rc;
3574
3575 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
3576
3577 if (Global::IsOnlineOrTransient(mData->mMachineState))
3578 return setError(VBOX_E_INVALID_VM_STATE,
3579 tr("Invalid machine state: %s"),
3580 Global::stringifyMachineState(mData->mMachineState));
3581
3582 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
3583 aControllerName,
3584 aControllerPort,
3585 aDevice);
3586 if (!pAttach)
3587 return setError(VBOX_E_OBJECT_NOT_FOUND,
3588 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
3589 aDevice, aControllerPort, aControllerName);
3590
3591 rc = detachDevice(pAttach, alock, NULL /* pSnapshot */, &fNeedsSaveSettings);
3592
3593 if (fNeedsSaveSettings)
3594 {
3595 bool fNeedsGlobalSaveSettings = false;
3596 saveSettings(&fNeedsGlobalSaveSettings);
3597
3598 if (fNeedsGlobalSaveSettings)
3599 {
3600 // save the global settings; for that we should hold only the VirtualBox lock
3601 alock.release();
3602 AutoWriteLock vboxlock(this COMMA_LOCKVAL_SRC_POS);
3603 mParent->saveSettings();
3604 }
3605 }
3606
3607 return S_OK;
3608}
3609
3610STDMETHODIMP Machine::PassthroughDevice(IN_BSTR aControllerName, LONG aControllerPort,
3611 LONG aDevice, BOOL aPassthrough)
3612{
3613 CheckComArgStrNotEmptyOrNull(aControllerName);
3614
3615 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld aPassthrough=%d\n",
3616 aControllerName, aControllerPort, aDevice, aPassthrough));
3617
3618 AutoCaller autoCaller(this);
3619 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3620
3621 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3622
3623 HRESULT rc = checkStateDependency(MutableStateDep);
3624 if (FAILED(rc)) return rc;
3625
3626 AssertReturn(mData->mMachineState != MachineState_Saved, E_FAIL);
3627
3628 if (Global::IsOnlineOrTransient(mData->mMachineState))
3629 return setError(VBOX_E_INVALID_VM_STATE,
3630 tr("Invalid machine state: %s"),
3631 Global::stringifyMachineState(mData->mMachineState));
3632
3633 MediumAttachment *pAttach = findAttachment(mMediaData->mAttachments,
3634 aControllerName,
3635 aControllerPort,
3636 aDevice);
3637 if (!pAttach)
3638 return setError(VBOX_E_OBJECT_NOT_FOUND,
3639 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
3640 aDevice, aControllerPort, aControllerName);
3641
3642
3643 setModified(IsModified_Storage);
3644 mMediaData.backup();
3645
3646 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
3647
3648 if (pAttach->getType() != DeviceType_DVD)
3649 return setError(E_INVALIDARG,
3650 tr("Setting passthrough rejected as the device attached to device slot %d on port %d of controller '%ls' is not a DVD"),
3651 aDevice, aControllerPort, aControllerName);
3652 pAttach->updatePassthrough(!!aPassthrough);
3653
3654 return S_OK;
3655}
3656
3657STDMETHODIMP Machine::MountMedium(IN_BSTR aControllerName,
3658 LONG aControllerPort,
3659 LONG aDevice,
3660 IN_BSTR aId,
3661 BOOL aForce)
3662{
3663 int rc = S_OK;
3664 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld aForce=%d\n",
3665 aControllerName, aControllerPort, aDevice, aForce));
3666
3667 CheckComArgStrNotEmptyOrNull(aControllerName);
3668
3669 AutoCaller autoCaller(this);
3670 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3671
3672 // we're calling host methods for getting DVD and floppy drives so lock host first
3673 AutoMultiWriteLock2 alock(mParent->host(), this COMMA_LOCKVAL_SRC_POS);
3674
3675 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
3676 aControllerName,
3677 aControllerPort,
3678 aDevice);
3679 if (pAttach.isNull())
3680 return setError(VBOX_E_OBJECT_NOT_FOUND,
3681 tr("No drive attached to device slot %d on port %d of controller '%ls'"),
3682 aDevice, aControllerPort, aControllerName);
3683
3684 /* Remember previously mounted medium. The medium before taking the
3685 * backup is not necessarily the same thing. */
3686 ComObjPtr<Medium> oldmedium;
3687 oldmedium = pAttach->getMedium();
3688
3689 Guid uuid(aId);
3690 ComObjPtr<Medium> medium;
3691 DeviceType_T mediumType = pAttach->getType();
3692 switch (mediumType)
3693 {
3694 case DeviceType_DVD:
3695 case DeviceType_Floppy:
3696 if (!uuid.isEmpty())
3697 {
3698 // check if the UUID refers to a host DVD or floppy drive
3699 MediaList llHostDrives;
3700 rc = (mediumType == DeviceType_DVD)
3701 ? mParent->host()->getDVDDrives(llHostDrives)
3702 : mParent->host()->getFloppyDrives(llHostDrives);
3703 if (SUCCEEDED(rc))
3704 {
3705 for (MediaList::iterator it = llHostDrives.begin();
3706 it != llHostDrives.end();
3707 ++it)
3708 {
3709 ComObjPtr<Medium> &p = *it;
3710 if (uuid == p->getId())
3711 {
3712 medium = p;
3713 break;
3714 }
3715 }
3716 }
3717
3718 if (medium.isNull())
3719 // UUID was not a host drive:
3720 rc = mParent->findDVDOrFloppyImage(mediumType, &uuid, Utf8Str::Empty, true /* aDoSetError */, &medium);
3721 }
3722 if (FAILED(rc)) return rc;
3723 break;
3724
3725 default:
3726 return setError(VBOX_E_INVALID_OBJECT_STATE,
3727 tr("Cannot change medium attached to device slot %d on port %d of controller '%ls'"),
3728 aDevice, aControllerPort, aControllerName);
3729 }
3730
3731 if (SUCCEEDED(rc))
3732 {
3733 setModified(IsModified_Storage);
3734 mMediaData.backup();
3735
3736 /* The backup operation makes the pAttach reference point to the
3737 * old settings. Re-get the correct reference. */
3738 pAttach = findAttachment(mMediaData->mAttachments,
3739 aControllerName,
3740 aControllerPort,
3741 aDevice);
3742 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
3743 /* For non-hard disk media, detach straight away. */
3744 if (mediumType != DeviceType_HardDisk && !oldmedium.isNull())
3745 oldmedium->removeBackReference(mData->mUuid);
3746 if (!medium.isNull())
3747 medium->addBackReference(mData->mUuid);
3748 pAttach->updateMedium(medium, false /* aImplicit */);
3749 setModified(IsModified_Storage);
3750 }
3751
3752 alock.leave();
3753 rc = onMediumChange(pAttach, aForce);
3754 alock.enter();
3755
3756 /* On error roll back this change only. */
3757 if (FAILED(rc))
3758 {
3759 if (!medium.isNull())
3760 medium->removeBackReference(mData->mUuid);
3761 pAttach = findAttachment(mMediaData->mAttachments,
3762 aControllerName,
3763 aControllerPort,
3764 aDevice);
3765 /* If the attachment is gone in the mean time, bail out. */
3766 if (pAttach.isNull())
3767 return rc;
3768 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
3769 /* For non-hard disk media, re-attach straight away. */
3770 if (mediumType != DeviceType_HardDisk && !oldmedium.isNull())
3771 oldmedium->addBackReference(mData->mUuid);
3772 pAttach->updateMedium(oldmedium, false /* aImplicit */);
3773 }
3774
3775 return rc;
3776}
3777
3778STDMETHODIMP Machine::GetMedium(IN_BSTR aControllerName,
3779 LONG aControllerPort,
3780 LONG aDevice,
3781 IMedium **aMedium)
3782{
3783 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%ld aDevice=%ld\n",
3784 aControllerName, aControllerPort, aDevice));
3785
3786 CheckComArgStrNotEmptyOrNull(aControllerName);
3787 CheckComArgOutPointerValid(aMedium);
3788
3789 AutoCaller autoCaller(this);
3790 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3791
3792 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3793
3794 *aMedium = NULL;
3795
3796 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
3797 aControllerName,
3798 aControllerPort,
3799 aDevice);
3800 if (pAttach.isNull())
3801 return setError(VBOX_E_OBJECT_NOT_FOUND,
3802 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
3803 aDevice, aControllerPort, aControllerName);
3804
3805 pAttach->getMedium().queryInterfaceTo(aMedium);
3806
3807 return S_OK;
3808}
3809
3810STDMETHODIMP Machine::GetSerialPort(ULONG slot, ISerialPort **port)
3811{
3812 CheckComArgOutPointerValid(port);
3813 CheckComArgExpr(slot, slot < RT_ELEMENTS(mSerialPorts));
3814
3815 AutoCaller autoCaller(this);
3816 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3817
3818 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3819
3820 mSerialPorts[slot].queryInterfaceTo(port);
3821
3822 return S_OK;
3823}
3824
3825STDMETHODIMP Machine::GetParallelPort(ULONG slot, IParallelPort **port)
3826{
3827 CheckComArgOutPointerValid(port);
3828 CheckComArgExpr(slot, slot < RT_ELEMENTS(mParallelPorts));
3829
3830 AutoCaller autoCaller(this);
3831 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3832
3833 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3834
3835 mParallelPorts[slot].queryInterfaceTo(port);
3836
3837 return S_OK;
3838}
3839
3840STDMETHODIMP Machine::GetNetworkAdapter(ULONG slot, INetworkAdapter **adapter)
3841{
3842 CheckComArgOutPointerValid(adapter);
3843 CheckComArgExpr(slot, slot < RT_ELEMENTS(mNetworkAdapters));
3844
3845 AutoCaller autoCaller(this);
3846 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3847
3848 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3849
3850 mNetworkAdapters[slot].queryInterfaceTo(adapter);
3851
3852 return S_OK;
3853}
3854
3855STDMETHODIMP Machine::GetExtraDataKeys(ComSafeArrayOut(BSTR, aKeys))
3856{
3857 if (ComSafeArrayOutIsNull(aKeys))
3858 return E_POINTER;
3859
3860 AutoCaller autoCaller(this);
3861 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3862
3863 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3864
3865 com::SafeArray<BSTR> saKeys(mData->pMachineConfigFile->mapExtraDataItems.size());
3866 int i = 0;
3867 for (settings::ExtraDataItemsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.begin();
3868 it != mData->pMachineConfigFile->mapExtraDataItems.end();
3869 ++it, ++i)
3870 {
3871 const Utf8Str &strKey = it->first;
3872 strKey.cloneTo(&saKeys[i]);
3873 }
3874 saKeys.detachTo(ComSafeArrayOutArg(aKeys));
3875
3876 return S_OK;
3877 }
3878
3879 /**
3880 * @note Locks this object for reading.
3881 */
3882STDMETHODIMP Machine::GetExtraData(IN_BSTR aKey,
3883 BSTR *aValue)
3884{
3885 CheckComArgStrNotEmptyOrNull(aKey);
3886 CheckComArgOutPointerValid(aValue);
3887
3888 AutoCaller autoCaller(this);
3889 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3890
3891 /* start with nothing found */
3892 Bstr bstrResult("");
3893
3894 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3895
3896 settings::ExtraDataItemsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(Utf8Str(aKey));
3897 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
3898 // found:
3899 bstrResult = it->second; // source is a Utf8Str
3900
3901 /* return the result to caller (may be empty) */
3902 bstrResult.cloneTo(aValue);
3903
3904 return S_OK;
3905}
3906
3907 /**
3908 * @note Locks mParent for writing + this object for writing.
3909 */
3910STDMETHODIMP Machine::SetExtraData(IN_BSTR aKey, IN_BSTR aValue)
3911{
3912 CheckComArgStrNotEmptyOrNull(aKey);
3913
3914 AutoCaller autoCaller(this);
3915 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3916
3917 Utf8Str strKey(aKey);
3918 Utf8Str strValue(aValue);
3919 Utf8Str strOldValue; // empty
3920
3921 // locking note: we only hold the read lock briefly to look up the old value,
3922 // then release it and call the onExtraCanChange callbacks. There is a small
3923 // chance of a race insofar as the callback might be called twice if two callers
3924 // change the same key at the same time, but that's a much better solution
3925 // than the deadlock we had here before. The actual changing of the extradata
3926 // is then performed under the write lock and race-free.
3927
3928 // look up the old value first; if nothing's changed then we need not do anything
3929 {
3930 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS); // hold read lock only while looking up
3931 settings::ExtraDataItemsMap::const_iterator it = mData->pMachineConfigFile->mapExtraDataItems.find(strKey);
3932 if (it != mData->pMachineConfigFile->mapExtraDataItems.end())
3933 strOldValue = it->second;
3934 }
3935
3936 bool fChanged;
3937 if ((fChanged = (strOldValue != strValue)))
3938 {
3939 // ask for permission from all listeners outside the locks;
3940 // onExtraDataCanChange() only briefly requests the VirtualBox
3941 // lock to copy the list of callbacks to invoke
3942 Bstr error;
3943 Bstr bstrValue(aValue);
3944
3945 if (!mParent->onExtraDataCanChange(mData->mUuid, aKey, bstrValue, error))
3946 {
3947 const char *sep = error.isEmpty() ? "" : ": ";
3948 CBSTR err = error.raw();
3949 LogWarningFunc(("Someone vetoed! Change refused%s%ls\n",
3950 sep, err));
3951 return setError(E_ACCESSDENIED,
3952 tr("Could not set extra data because someone refused the requested change of '%ls' to '%ls'%s%ls"),
3953 aKey,
3954 bstrValue.raw(),
3955 sep,
3956 err);
3957 }
3958
3959 // data is changing and change not vetoed: then write it out under the lock
3960 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3961
3962 if (isSnapshotMachine())
3963 {
3964 HRESULT rc = checkStateDependency(MutableStateDep);
3965 if (FAILED(rc)) return rc;
3966 }
3967
3968 if (strValue.isEmpty())
3969 mData->pMachineConfigFile->mapExtraDataItems.erase(strKey);
3970 else
3971 mData->pMachineConfigFile->mapExtraDataItems[strKey] = strValue;
3972 // creates a new key if needed
3973
3974 bool fNeedsGlobalSaveSettings = false;
3975 saveSettings(&fNeedsGlobalSaveSettings);
3976
3977 if (fNeedsGlobalSaveSettings)
3978 {
3979 // save the global settings; for that we should hold only the VirtualBox lock
3980 alock.release();
3981 AutoWriteLock vboxlock(mParent COMMA_LOCKVAL_SRC_POS);
3982 mParent->saveSettings();
3983 }
3984 }
3985
3986 // fire notification outside the lock
3987 if (fChanged)
3988 mParent->onExtraDataChange(mData->mUuid, aKey, aValue);
3989
3990 return S_OK;
3991}
3992
3993STDMETHODIMP Machine::SaveSettings()
3994{
3995 AutoCaller autoCaller(this);
3996 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3997
3998 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
3999
4000 /* when there was auto-conversion, we want to save the file even if
4001 * the VM is saved */
4002 HRESULT rc = checkStateDependency(MutableStateDep);
4003 if (FAILED(rc)) return rc;
4004
4005 /* the settings file path may never be null */
4006 ComAssertRet(!mData->m_strConfigFileFull.isEmpty(), E_FAIL);
4007
4008 /* save all VM data excluding snapshots */
4009 bool fNeedsGlobalSaveSettings = false;
4010 rc = saveSettings(&fNeedsGlobalSaveSettings);
4011 mlock.release();
4012
4013 if (SUCCEEDED(rc) && fNeedsGlobalSaveSettings)
4014 {
4015 // save the global settings; for that we should hold only the VirtualBox lock
4016 AutoWriteLock vlock(mParent COMMA_LOCKVAL_SRC_POS);
4017 rc = mParent->saveSettings();
4018 }
4019
4020 return rc;
4021}
4022
4023STDMETHODIMP Machine::DiscardSettings()
4024{
4025 AutoCaller autoCaller(this);
4026 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4027
4028 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4029
4030 HRESULT rc = checkStateDependency(MutableStateDep);
4031 if (FAILED(rc)) return rc;
4032
4033 /*
4034 * during this rollback, the session will be notified if data has
4035 * been actually changed
4036 */
4037 rollback(true /* aNotify */);
4038
4039 return S_OK;
4040}
4041
4042/** @note Locks objects! */
4043STDMETHODIMP Machine::Unregister(BOOL fAutoCleanup,
4044 ComSafeArrayOut(BSTR, aFiles))
4045{
4046 AutoCaller autoCaller(this);
4047 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4048
4049 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4050
4051 if (mData->mSession.mState != SessionState_Unlocked)
4052 return setError(VBOX_E_INVALID_OBJECT_STATE,
4053 tr("Cannot unregister the machine '%ls' while it is locked"),
4054 mUserData->mName.raw());
4055
4056 HRESULT rc = S_OK;
4057
4058 // this list collects the files that should be reported
4059 // as to be deleted to the caller in aFiles (this includes the
4060 // media files in llMedia below)
4061 std::list<Utf8Str> llFilesForCaller;
4062
4063 // discard saved state
4064 if (mData->mMachineState == MachineState_Saved)
4065 {
4066 // add the saved state file to the list of files the caller should delete
4067 Assert(!mSSData->mStateFilePath.isEmpty());
4068 llFilesForCaller.push_back(mSSData->mStateFilePath);
4069
4070 mSSData->mStateFilePath.setNull();
4071
4072 // unconditionally set the machine state to powered off, we now
4073 // know no session has locked the machine
4074 mData->mMachineState = MachineState_PoweredOff;
4075 }
4076
4077 size_t cSnapshots = 0;
4078 if (mData->mFirstSnapshot)
4079 cSnapshots = mData->mFirstSnapshot->getAllChildrenCount() + 1;
4080 if (cSnapshots && !fAutoCleanup)
4081 // fail now before we start detaching media
4082 return setError(VBOX_E_INVALID_OBJECT_STATE,
4083 tr("Cannot unregister the machine '%ls' because it has %d snapshots"),
4084 mUserData->mName.raw(), cSnapshots);
4085
4086 // this list collects the medium objects from all medium attachments
4087 // which got detached from the machine and its snapshots, in the following
4088 // order:
4089 // 1) media from machine attachments (these have the "leaf" attachments with snapshots
4090 // and must be closed first, or closing the parents will fail because they will
4091 // children);
4092 // 2) media from the youngest snapshots followed those from the parent snapshots until
4093 // the root ("first") snapshot of the machine
4094 // This order allows for closing the media on this list from the beginning to the end
4095 // without getting "media in use" errors.
4096 MediaList llMedia;
4097
4098 if ( !mMediaData.isNull() // can be NULL if machine is inaccessible
4099 && mMediaData->mAttachments.size()
4100 )
4101 {
4102 // we have media attachments: detach them all and add the Medium objects to our list
4103 if (fAutoCleanup)
4104 detachAllMedia(alock, NULL /* pSnapshot */, llMedia);
4105 else
4106 return setError(VBOX_E_INVALID_OBJECT_STATE,
4107 tr("Cannot unregister the machine '%ls' because it has %d media attachments"),
4108 mUserData->mName.raw(), mMediaData->mAttachments.size());
4109 }
4110
4111 if (cSnapshots)
4112 {
4113 // autoCleanup must be true here, or we would have failed above
4114
4115 // add the media from the medium attachments of the snapshots to llMedia
4116 // as well, after the "main" machine media; Snapshot::uninitRecursively()
4117 // calls Machine::detachAllMedia() for the snapshot machine, recursing
4118 // into the children first
4119
4120 // Snapshot::beginDeletingSnapshot() asserts if the machine state is not this
4121 MachineState_T oldState = mData->mMachineState;
4122 mData->mMachineState = MachineState_DeletingSnapshot;
4123
4124 // make a copy of the first snapshot so the refcount does not drop to 0
4125 // in beginDeletingSnapshot, which sets pFirstSnapshot to 0 (that hangs
4126 // because of the AutoCaller voodoo)
4127 ComObjPtr<Snapshot> pFirstSnapshot = mData->mFirstSnapshot;
4128
4129 // GO!
4130 pFirstSnapshot->uninitRecursively(alock, llMedia, llFilesForCaller);
4131
4132 mData->mMachineState = oldState;
4133 }
4134
4135
4136 if (FAILED(rc))
4137 {
4138 rollbackMedia();
4139 return rc;
4140 }
4141
4142 // commit all the media changes made above
4143 commitMedia();
4144
4145 mData->mRegistered = false;
4146
4147 // machine lock no longer needed
4148 alock.release();
4149
4150 if (fAutoCleanup)
4151 {
4152 // now go thru the list of attached media reported by prepareUnregister() and close them all
4153 for (MediaList::const_iterator it = llMedia.begin();
4154 it != llMedia.end();
4155 ++it)
4156 {
4157 ComObjPtr<Medium> pMedium = *it;
4158 Utf8Str strFile = pMedium->getLocationFull();
4159
4160 AutoCaller autoCaller2(pMedium);
4161 if (FAILED(autoCaller2.rc())) return autoCaller2.rc();
4162
4163 ErrorInfoKeeper eik;
4164 rc = pMedium->close(NULL /*fNeedsSaveSettings*/, // we'll call saveSettings() in any case below
4165 autoCaller2);
4166 // this uninitializes the medium
4167
4168 LogFlowThisFunc(("Medium::close() on %s yielded rc (%Rhra)\n", strFile.c_str(), rc));
4169
4170 if (rc == VBOX_E_OBJECT_IN_USE)
4171 // can happen if the medium was still attached to another machine;
4172 // do not report the file to the caller then, but don't report
4173 // an error either
4174 eik.setNull();
4175 else if (SUCCEEDED(rc))
4176 // report the path to the caller
4177 llFilesForCaller.push_back(strFile);
4178 }
4179 }
4180
4181 // report all paths to the caller
4182 SafeArray<BSTR> sfaFiles(llFilesForCaller.size());
4183 size_t i = 0;
4184 for (std::list<Utf8Str>::iterator it = llFilesForCaller.begin();
4185 it != llFilesForCaller.end();
4186 ++it)
4187 Bstr(*it).detachTo(&sfaFiles[i++]);
4188 sfaFiles.detachTo(ComSafeArrayOutArg(aFiles));
4189
4190 mParent->unregisterMachine(this);
4191 // calls VirtualBox::saveSettings()
4192
4193 return S_OK;
4194}
4195
4196STDMETHODIMP Machine::Delete()
4197{
4198 AutoCaller autoCaller(this);
4199 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4200
4201 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4202
4203 HRESULT rc = checkStateDependency(MutableStateDep);
4204 if (FAILED(rc)) return rc;
4205
4206 if (mData->mRegistered)
4207 return setError(VBOX_E_INVALID_VM_STATE,
4208 tr("Cannot delete settings of a registered machine"));
4209
4210 ULONG uLogHistoryCount = 3;
4211 ComPtr<ISystemProperties> systemProperties;
4212 mParent->COMGETTER(SystemProperties)(systemProperties.asOutParam());
4213 if (!systemProperties.isNull())
4214 systemProperties->COMGETTER(LogHistoryCount)(&uLogHistoryCount);
4215
4216 /* delete the settings only when the file actually exists */
4217 if (mData->pMachineConfigFile->fileExists())
4218 {
4219 int vrc = RTFileDelete(mData->m_strConfigFileFull.c_str());
4220 if (RT_FAILURE(vrc))
4221 return setError(VBOX_E_IPRT_ERROR,
4222 tr("Could not delete the settings file '%s' (%Rrc)"),
4223 mData->m_strConfigFileFull.raw(),
4224 vrc);
4225
4226 /* Delete any backup or uncommitted XML files. Ignore failures.
4227 See the fSafe parameter of xml::XmlFileWriter::write for details. */
4228 /** @todo Find a way to avoid referring directly to iprt/xml.h here. */
4229 Utf8Str otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszTmpSuff);
4230 RTFileDelete(otherXml.c_str());
4231 otherXml = Utf8StrFmt("%s%s", mData->m_strConfigFileFull.c_str(), xml::XmlFileWriter::s_pszPrevSuff);
4232 RTFileDelete(otherXml.c_str());
4233
4234 /* delete the Logs folder, nothing important should be left
4235 * there (we don't check for errors because the user might have
4236 * some private files there that we don't want to delete) */
4237 Utf8Str logFolder;
4238 getLogFolder(logFolder);
4239 Assert(logFolder.length());
4240 if (RTDirExists(logFolder.c_str()))
4241 {
4242 /* Delete all VBox.log[.N] files from the Logs folder
4243 * (this must be in sync with the rotation logic in
4244 * Console::powerUpThread()). Also, delete the VBox.png[.N]
4245 * files that may have been created by the GUI. */
4246 Utf8Str log = Utf8StrFmt("%s%cVBox.log",
4247 logFolder.raw(), RTPATH_DELIMITER);
4248 RTFileDelete(log.c_str());
4249 log = Utf8StrFmt("%s%cVBox.png",
4250 logFolder.raw(), RTPATH_DELIMITER);
4251 RTFileDelete(log.c_str());
4252 for (int i = uLogHistoryCount; i > 0; i--)
4253 {
4254 log = Utf8StrFmt("%s%cVBox.log.%d",
4255 logFolder.raw(), RTPATH_DELIMITER, i);
4256 RTFileDelete(log.c_str());
4257 log = Utf8StrFmt("%s%cVBox.png.%d",
4258 logFolder.raw(), RTPATH_DELIMITER, i);
4259 RTFileDelete(log.c_str());
4260 }
4261
4262 RTDirRemove(logFolder.c_str());
4263 }
4264
4265 /* delete the Snapshots folder, nothing important should be left
4266 * there (we don't check for errors because the user might have
4267 * some private files there that we don't want to delete) */
4268 Utf8Str snapshotFolder(mUserData->mSnapshotFolderFull);
4269 Assert(snapshotFolder.length());
4270 if (RTDirExists(snapshotFolder.c_str()))
4271 RTDirRemove(snapshotFolder.c_str());
4272
4273 /* delete the directory that contains the settings file, but only
4274 * if it matches the VM name (i.e. a structure created by default in
4275 * prepareSaveSettings()) */
4276 {
4277 Utf8Str settingsDir;
4278 if (isInOwnDir(&settingsDir))
4279 RTDirRemove(settingsDir.c_str());
4280 }
4281 }
4282
4283 return S_OK;
4284}
4285
4286STDMETHODIMP Machine::GetSnapshot(IN_BSTR aId, ISnapshot **aSnapshot)
4287{
4288 CheckComArgOutPointerValid(aSnapshot);
4289
4290 AutoCaller autoCaller(this);
4291 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4292
4293 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4294
4295 Guid uuid(aId);
4296 /* Todo: fix this properly by perhaps introducing an isValid method for the Guid class */
4297 if ( (aId)
4298 && (*aId != '\0') // an empty Bstr means "get root snapshot", so don't fail on that
4299 && (uuid.isEmpty()))
4300 {
4301 RTUUID uuidTemp;
4302 /* Either it's a null UUID or the conversion failed. (null uuid has a special meaning in findSnapshot) */
4303 if (RT_FAILURE(RTUuidFromUtf16(&uuidTemp, aId)))
4304 return setError(E_FAIL,
4305 tr("Could not find a snapshot with UUID {%ls}"),
4306 aId);
4307 }
4308
4309 ComObjPtr<Snapshot> snapshot;
4310
4311 HRESULT rc = findSnapshot(uuid, snapshot, true /* aSetError */);
4312 snapshot.queryInterfaceTo(aSnapshot);
4313
4314 return rc;
4315}
4316
4317STDMETHODIMP Machine::FindSnapshot(IN_BSTR aName, ISnapshot **aSnapshot)
4318{
4319 CheckComArgStrNotEmptyOrNull(aName);
4320 CheckComArgOutPointerValid(aSnapshot);
4321
4322 AutoCaller autoCaller(this);
4323 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4324
4325 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4326
4327 ComObjPtr<Snapshot> snapshot;
4328
4329 HRESULT rc = findSnapshot(aName, snapshot, true /* aSetError */);
4330 snapshot.queryInterfaceTo(aSnapshot);
4331
4332 return rc;
4333}
4334
4335STDMETHODIMP Machine::SetCurrentSnapshot(IN_BSTR /* aId */)
4336{
4337 /// @todo (dmik) don't forget to set
4338 // mData->mCurrentStateModified to FALSE
4339
4340 return setError(E_NOTIMPL, "Not implemented");
4341}
4342
4343STDMETHODIMP Machine::CreateSharedFolder(IN_BSTR aName, IN_BSTR aHostPath, BOOL aWritable, BOOL aAutoMount)
4344{
4345 CheckComArgStrNotEmptyOrNull(aName);
4346 CheckComArgStrNotEmptyOrNull(aHostPath);
4347
4348 AutoCaller autoCaller(this);
4349 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4350
4351 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4352
4353 HRESULT rc = checkStateDependency(MutableStateDep);
4354 if (FAILED(rc)) return rc;
4355
4356 ComObjPtr<SharedFolder> sharedFolder;
4357 rc = findSharedFolder(aName, sharedFolder, false /* aSetError */);
4358 if (SUCCEEDED(rc))
4359 return setError(VBOX_E_OBJECT_IN_USE,
4360 tr("Shared folder named '%ls' already exists"),
4361 aName);
4362
4363 sharedFolder.createObject();
4364 rc = sharedFolder->init(getMachine(), aName, aHostPath, aWritable, aAutoMount);
4365 if (FAILED(rc)) return rc;
4366
4367 setModified(IsModified_SharedFolders);
4368 mHWData.backup();
4369 mHWData->mSharedFolders.push_back(sharedFolder);
4370
4371 /* inform the direct session if any */
4372 alock.leave();
4373 onSharedFolderChange();
4374
4375 return S_OK;
4376}
4377
4378STDMETHODIMP Machine::RemoveSharedFolder(IN_BSTR aName)
4379{
4380 CheckComArgStrNotEmptyOrNull(aName);
4381
4382 AutoCaller autoCaller(this);
4383 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4384
4385 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4386
4387 HRESULT rc = checkStateDependency(MutableStateDep);
4388 if (FAILED(rc)) return rc;
4389
4390 ComObjPtr<SharedFolder> sharedFolder;
4391 rc = findSharedFolder(aName, sharedFolder, true /* aSetError */);
4392 if (FAILED(rc)) return rc;
4393
4394 setModified(IsModified_SharedFolders);
4395 mHWData.backup();
4396 mHWData->mSharedFolders.remove(sharedFolder);
4397
4398 /* inform the direct session if any */
4399 alock.leave();
4400 onSharedFolderChange();
4401
4402 return S_OK;
4403}
4404
4405STDMETHODIMP Machine::CanShowConsoleWindow(BOOL *aCanShow)
4406{
4407 CheckComArgOutPointerValid(aCanShow);
4408
4409 /* start with No */
4410 *aCanShow = FALSE;
4411
4412 AutoCaller autoCaller(this);
4413 AssertComRCReturnRC(autoCaller.rc());
4414
4415 ComPtr<IInternalSessionControl> directControl;
4416 {
4417 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4418
4419 if (mData->mSession.mState != SessionState_Locked)
4420 return setError(VBOX_E_INVALID_VM_STATE,
4421 tr("Machine is not locked for session (session state: %s)"),
4422 Global::stringifySessionState(mData->mSession.mState));
4423
4424 directControl = mData->mSession.mDirectControl;
4425 }
4426
4427 /* ignore calls made after #OnSessionEnd() is called */
4428 if (!directControl)
4429 return S_OK;
4430
4431 ULONG64 dummy;
4432 return directControl->OnShowWindow(TRUE /* aCheck */, aCanShow, &dummy);
4433}
4434
4435STDMETHODIMP Machine::ShowConsoleWindow(ULONG64 *aWinId)
4436{
4437 CheckComArgOutPointerValid(aWinId);
4438
4439 AutoCaller autoCaller(this);
4440 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4441
4442 ComPtr<IInternalSessionControl> directControl;
4443 {
4444 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4445
4446 if (mData->mSession.mState != SessionState_Locked)
4447 return setError(E_FAIL,
4448 tr("Machine is not locked for session (session state: %s)"),
4449 Global::stringifySessionState(mData->mSession.mState));
4450
4451 directControl = mData->mSession.mDirectControl;
4452 }
4453
4454 /* ignore calls made after #OnSessionEnd() is called */
4455 if (!directControl)
4456 return S_OK;
4457
4458 BOOL dummy;
4459 return directControl->OnShowWindow(FALSE /* aCheck */, &dummy, aWinId);
4460}
4461
4462#ifdef VBOX_WITH_GUEST_PROPS
4463/**
4464 * Look up a guest property in VBoxSVC's internal structures.
4465 */
4466HRESULT Machine::getGuestPropertyFromService(IN_BSTR aName,
4467 BSTR *aValue,
4468 ULONG64 *aTimestamp,
4469 BSTR *aFlags) const
4470{
4471 using namespace guestProp;
4472
4473 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4474 Utf8Str strName(aName);
4475 HWData::GuestPropertyList::const_iterator it;
4476
4477 for (it = mHWData->mGuestProperties.begin();
4478 it != mHWData->mGuestProperties.end(); ++it)
4479 {
4480 if (it->strName == strName)
4481 {
4482 char szFlags[MAX_FLAGS_LEN + 1];
4483 it->strValue.cloneTo(aValue);
4484 *aTimestamp = it->mTimestamp;
4485 writeFlags(it->mFlags, szFlags);
4486 Bstr(szFlags).cloneTo(aFlags);
4487 break;
4488 }
4489 }
4490 return S_OK;
4491}
4492
4493/**
4494 * Query the VM that a guest property belongs to for the property.
4495 * @returns E_ACCESSDENIED if the VM process is not available or not
4496 * currently handling queries and the lookup should then be done in
4497 * VBoxSVC.
4498 */
4499HRESULT Machine::getGuestPropertyFromVM(IN_BSTR aName,
4500 BSTR *aValue,
4501 ULONG64 *aTimestamp,
4502 BSTR *aFlags) const
4503{
4504 HRESULT rc;
4505 ComPtr<IInternalSessionControl> directControl;
4506 directControl = mData->mSession.mDirectControl;
4507
4508 /* fail if we were called after #OnSessionEnd() is called. This is a
4509 * silly race condition. */
4510
4511 if (!directControl)
4512 rc = E_ACCESSDENIED;
4513 else
4514 rc = directControl->AccessGuestProperty(aName, NULL, NULL,
4515 false /* isSetter */,
4516 aValue, aTimestamp, aFlags);
4517 return rc;
4518}
4519#endif // VBOX_WITH_GUEST_PROPS
4520
4521STDMETHODIMP Machine::GetGuestProperty(IN_BSTR aName,
4522 BSTR *aValue,
4523 ULONG64 *aTimestamp,
4524 BSTR *aFlags)
4525{
4526#ifndef VBOX_WITH_GUEST_PROPS
4527 ReturnComNotImplemented();
4528#else // VBOX_WITH_GUEST_PROPS
4529 CheckComArgStrNotEmptyOrNull(aName);
4530 CheckComArgOutPointerValid(aValue);
4531 CheckComArgOutPointerValid(aTimestamp);
4532 CheckComArgOutPointerValid(aFlags);
4533
4534 AutoCaller autoCaller(this);
4535 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4536
4537 HRESULT rc = getGuestPropertyFromVM(aName, aValue, aTimestamp, aFlags);
4538 if (rc == E_ACCESSDENIED)
4539 /* The VM is not running or the service is not (yet) accessible */
4540 rc = getGuestPropertyFromService(aName, aValue, aTimestamp, aFlags);
4541 return rc;
4542#endif // VBOX_WITH_GUEST_PROPS
4543}
4544
4545STDMETHODIMP Machine::GetGuestPropertyValue(IN_BSTR aName, BSTR *aValue)
4546{
4547 ULONG64 dummyTimestamp;
4548 Bstr dummyFlags;
4549 return GetGuestProperty(aName, aValue, &dummyTimestamp, dummyFlags.asOutParam());
4550}
4551
4552STDMETHODIMP Machine::GetGuestPropertyTimestamp(IN_BSTR aName, ULONG64 *aTimestamp)
4553{
4554 Bstr dummyValue;
4555 Bstr dummyFlags;
4556 return GetGuestProperty(aName, dummyValue.asOutParam(), aTimestamp, dummyFlags.asOutParam());
4557}
4558
4559#ifdef VBOX_WITH_GUEST_PROPS
4560/**
4561 * Set a guest property in VBoxSVC's internal structures.
4562 */
4563HRESULT Machine::setGuestPropertyToService(IN_BSTR aName, IN_BSTR aValue,
4564 IN_BSTR aFlags)
4565{
4566 using namespace guestProp;
4567
4568 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4569 HRESULT rc = S_OK;
4570 HWData::GuestProperty property;
4571 property.mFlags = NILFLAG;
4572 bool found = false;
4573
4574 rc = checkStateDependency(MutableStateDep);
4575 if (FAILED(rc)) return rc;
4576
4577 try
4578 {
4579 Utf8Str utf8Name(aName);
4580 Utf8Str utf8Flags(aFlags);
4581 uint32_t fFlags = NILFLAG;
4582 if ( (aFlags != NULL)
4583 && RT_FAILURE(validateFlags(utf8Flags.raw(), &fFlags))
4584 )
4585 return setError(E_INVALIDARG,
4586 tr("Invalid flag values: '%ls'"),
4587 aFlags);
4588
4589 /** @todo r=bird: see efficiency rant in PushGuestProperty. (Yeah, I
4590 * know, this is simple and do an OK job atm.) */
4591 HWData::GuestPropertyList::iterator it;
4592 for (it = mHWData->mGuestProperties.begin();
4593 it != mHWData->mGuestProperties.end(); ++it)
4594 if (it->strName == utf8Name)
4595 {
4596 property = *it;
4597 if (it->mFlags & (RDONLYHOST))
4598 rc = setError(E_ACCESSDENIED,
4599 tr("The property '%ls' cannot be changed by the host"),
4600 aName);
4601 else
4602 {
4603 setModified(IsModified_MachineData);
4604 mHWData.backup(); // @todo r=dj backup in a loop?!?
4605
4606 /* The backup() operation invalidates our iterator, so
4607 * get a new one. */
4608 for (it = mHWData->mGuestProperties.begin();
4609 it->strName != utf8Name;
4610 ++it)
4611 ;
4612 mHWData->mGuestProperties.erase(it);
4613 }
4614 found = true;
4615 break;
4616 }
4617 if (found && SUCCEEDED(rc))
4618 {
4619 if (*aValue)
4620 {
4621 RTTIMESPEC time;
4622 property.strValue = aValue;
4623 property.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
4624 if (aFlags != NULL)
4625 property.mFlags = fFlags;
4626 mHWData->mGuestProperties.push_back(property);
4627 }
4628 }
4629 else if (SUCCEEDED(rc) && *aValue)
4630 {
4631 RTTIMESPEC time;
4632 setModified(IsModified_MachineData);
4633 mHWData.backup();
4634 property.strName = aName;
4635 property.strValue = aValue;
4636 property.mTimestamp = RTTimeSpecGetNano(RTTimeNow(&time));
4637 property.mFlags = fFlags;
4638 mHWData->mGuestProperties.push_back(property);
4639 }
4640 if ( SUCCEEDED(rc)
4641 && ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
4642 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.raw(), RTSTR_MAX,
4643 utf8Name.raw(), RTSTR_MAX, NULL) )
4644 )
4645 {
4646 /** @todo r=bird: Why aren't we leaving the lock here? The
4647 * same code in PushGuestProperty does... */
4648 mParent->onGuestPropertyChange(mData->mUuid, aName, aValue, aFlags);
4649 }
4650 }
4651 catch (std::bad_alloc &)
4652 {
4653 rc = E_OUTOFMEMORY;
4654 }
4655
4656 return rc;
4657}
4658
4659/**
4660 * Set a property on the VM that that property belongs to.
4661 * @returns E_ACCESSDENIED if the VM process is not available or not
4662 * currently handling queries and the setting should then be done in
4663 * VBoxSVC.
4664 */
4665HRESULT Machine::setGuestPropertyToVM(IN_BSTR aName, IN_BSTR aValue,
4666 IN_BSTR aFlags)
4667{
4668 HRESULT rc;
4669
4670 try {
4671 ComPtr<IInternalSessionControl> directControl =
4672 mData->mSession.mDirectControl;
4673
4674 BSTR dummy = NULL; /* will not be changed (setter) */
4675 ULONG64 dummy64;
4676 if (!directControl)
4677 rc = E_ACCESSDENIED;
4678 else
4679 rc = directControl->AccessGuestProperty
4680 (aName,
4681 /** @todo Fix when adding DeleteGuestProperty(),
4682 see defect. */
4683 *aValue ? aValue : NULL, aFlags, true /* isSetter */,
4684 &dummy, &dummy64, &dummy);
4685 }
4686 catch (std::bad_alloc &)
4687 {
4688 rc = E_OUTOFMEMORY;
4689 }
4690
4691 return rc;
4692}
4693#endif // VBOX_WITH_GUEST_PROPS
4694
4695STDMETHODIMP Machine::SetGuestProperty(IN_BSTR aName, IN_BSTR aValue,
4696 IN_BSTR aFlags)
4697{
4698#ifndef VBOX_WITH_GUEST_PROPS
4699 ReturnComNotImplemented();
4700#else // VBOX_WITH_GUEST_PROPS
4701 CheckComArgStrNotEmptyOrNull(aName);
4702 if ((aFlags != NULL) && !VALID_PTR(aFlags))
4703 return E_INVALIDARG;
4704 AutoCaller autoCaller(this);
4705 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4706
4707 HRESULT rc = setGuestPropertyToVM(aName, aValue, aFlags);
4708 if (rc == E_ACCESSDENIED)
4709 /* The VM is not running or the service is not (yet) accessible */
4710 rc = setGuestPropertyToService(aName, aValue, aFlags);
4711 return rc;
4712#endif // VBOX_WITH_GUEST_PROPS
4713}
4714
4715STDMETHODIMP Machine::SetGuestPropertyValue(IN_BSTR aName, IN_BSTR aValue)
4716{
4717 return SetGuestProperty(aName, aValue, NULL);
4718}
4719
4720#ifdef VBOX_WITH_GUEST_PROPS
4721/**
4722 * Enumerate the guest properties in VBoxSVC's internal structures.
4723 */
4724HRESULT Machine::enumerateGuestPropertiesInService
4725 (IN_BSTR aPatterns, ComSafeArrayOut(BSTR, aNames),
4726 ComSafeArrayOut(BSTR, aValues),
4727 ComSafeArrayOut(ULONG64, aTimestamps),
4728 ComSafeArrayOut(BSTR, aFlags))
4729{
4730 using namespace guestProp;
4731
4732 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4733 Utf8Str strPatterns(aPatterns);
4734
4735 /*
4736 * Look for matching patterns and build up a list.
4737 */
4738 HWData::GuestPropertyList propList;
4739 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
4740 it != mHWData->mGuestProperties.end();
4741 ++it)
4742 if ( strPatterns.isEmpty()
4743 || RTStrSimplePatternMultiMatch(strPatterns.raw(),
4744 RTSTR_MAX,
4745 it->strName.raw(),
4746 RTSTR_MAX, NULL)
4747 )
4748 propList.push_back(*it);
4749
4750 /*
4751 * And build up the arrays for returning the property information.
4752 */
4753 size_t cEntries = propList.size();
4754 SafeArray<BSTR> names(cEntries);
4755 SafeArray<BSTR> values(cEntries);
4756 SafeArray<ULONG64> timestamps(cEntries);
4757 SafeArray<BSTR> flags(cEntries);
4758 size_t iProp = 0;
4759 for (HWData::GuestPropertyList::iterator it = propList.begin();
4760 it != propList.end();
4761 ++it)
4762 {
4763 char szFlags[MAX_FLAGS_LEN + 1];
4764 it->strName.cloneTo(&names[iProp]);
4765 it->strValue.cloneTo(&values[iProp]);
4766 timestamps[iProp] = it->mTimestamp;
4767 writeFlags(it->mFlags, szFlags);
4768 Bstr(szFlags).cloneTo(&flags[iProp]);
4769 ++iProp;
4770 }
4771 names.detachTo(ComSafeArrayOutArg(aNames));
4772 values.detachTo(ComSafeArrayOutArg(aValues));
4773 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
4774 flags.detachTo(ComSafeArrayOutArg(aFlags));
4775 return S_OK;
4776}
4777
4778/**
4779 * Enumerate the properties managed by a VM.
4780 * @returns E_ACCESSDENIED if the VM process is not available or not
4781 * currently handling queries and the setting should then be done in
4782 * VBoxSVC.
4783 */
4784HRESULT Machine::enumerateGuestPropertiesOnVM
4785 (IN_BSTR aPatterns, ComSafeArrayOut(BSTR, aNames),
4786 ComSafeArrayOut(BSTR, aValues),
4787 ComSafeArrayOut(ULONG64, aTimestamps),
4788 ComSafeArrayOut(BSTR, aFlags))
4789{
4790 HRESULT rc;
4791 ComPtr<IInternalSessionControl> directControl;
4792 directControl = mData->mSession.mDirectControl;
4793
4794 if (!directControl)
4795 rc = E_ACCESSDENIED;
4796 else
4797 rc = directControl->EnumerateGuestProperties
4798 (aPatterns, ComSafeArrayOutArg(aNames),
4799 ComSafeArrayOutArg(aValues),
4800 ComSafeArrayOutArg(aTimestamps),
4801 ComSafeArrayOutArg(aFlags));
4802 return rc;
4803}
4804#endif // VBOX_WITH_GUEST_PROPS
4805
4806STDMETHODIMP Machine::EnumerateGuestProperties(IN_BSTR aPatterns,
4807 ComSafeArrayOut(BSTR, aNames),
4808 ComSafeArrayOut(BSTR, aValues),
4809 ComSafeArrayOut(ULONG64, aTimestamps),
4810 ComSafeArrayOut(BSTR, aFlags))
4811{
4812#ifndef VBOX_WITH_GUEST_PROPS
4813 ReturnComNotImplemented();
4814#else // VBOX_WITH_GUEST_PROPS
4815 if (!VALID_PTR(aPatterns) && (aPatterns != NULL))
4816 return E_POINTER;
4817
4818 CheckComArgOutSafeArrayPointerValid(aNames);
4819 CheckComArgOutSafeArrayPointerValid(aValues);
4820 CheckComArgOutSafeArrayPointerValid(aTimestamps);
4821 CheckComArgOutSafeArrayPointerValid(aFlags);
4822
4823 AutoCaller autoCaller(this);
4824 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4825
4826 HRESULT rc = enumerateGuestPropertiesOnVM
4827 (aPatterns, ComSafeArrayOutArg(aNames),
4828 ComSafeArrayOutArg(aValues),
4829 ComSafeArrayOutArg(aTimestamps),
4830 ComSafeArrayOutArg(aFlags));
4831 if (rc == E_ACCESSDENIED)
4832 /* The VM is not running or the service is not (yet) accessible */
4833 rc = enumerateGuestPropertiesInService
4834 (aPatterns, ComSafeArrayOutArg(aNames),
4835 ComSafeArrayOutArg(aValues),
4836 ComSafeArrayOutArg(aTimestamps),
4837 ComSafeArrayOutArg(aFlags));
4838 return rc;
4839#endif // VBOX_WITH_GUEST_PROPS
4840}
4841
4842STDMETHODIMP Machine::GetMediumAttachmentsOfController(IN_BSTR aName,
4843 ComSafeArrayOut(IMediumAttachment*, aAttachments))
4844{
4845 MediaData::AttachmentList atts;
4846
4847 HRESULT rc = getMediumAttachmentsOfController(aName, atts);
4848 if (FAILED(rc)) return rc;
4849
4850 SafeIfaceArray<IMediumAttachment> attachments(atts);
4851 attachments.detachTo(ComSafeArrayOutArg(aAttachments));
4852
4853 return S_OK;
4854}
4855
4856STDMETHODIMP Machine::GetMediumAttachment(IN_BSTR aControllerName,
4857 LONG aControllerPort,
4858 LONG aDevice,
4859 IMediumAttachment **aAttachment)
4860{
4861 LogFlowThisFunc(("aControllerName=\"%ls\" aControllerPort=%d aDevice=%d\n",
4862 aControllerName, aControllerPort, aDevice));
4863
4864 CheckComArgStrNotEmptyOrNull(aControllerName);
4865 CheckComArgOutPointerValid(aAttachment);
4866
4867 AutoCaller autoCaller(this);
4868 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4869
4870 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4871
4872 *aAttachment = NULL;
4873
4874 ComObjPtr<MediumAttachment> pAttach = findAttachment(mMediaData->mAttachments,
4875 aControllerName,
4876 aControllerPort,
4877 aDevice);
4878 if (pAttach.isNull())
4879 return setError(VBOX_E_OBJECT_NOT_FOUND,
4880 tr("No storage device attached to device slot %d on port %d of controller '%ls'"),
4881 aDevice, aControllerPort, aControllerName);
4882
4883 pAttach.queryInterfaceTo(aAttachment);
4884
4885 return S_OK;
4886}
4887
4888STDMETHODIMP Machine::AddStorageController(IN_BSTR aName,
4889 StorageBus_T aConnectionType,
4890 IStorageController **controller)
4891{
4892 CheckComArgStrNotEmptyOrNull(aName);
4893
4894 if ( (aConnectionType <= StorageBus_Null)
4895 || (aConnectionType > StorageBus_SAS))
4896 return setError(E_INVALIDARG,
4897 tr("Invalid connection type: %d"),
4898 aConnectionType);
4899
4900 AutoCaller autoCaller(this);
4901 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4902
4903 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4904
4905 HRESULT rc = checkStateDependency(MutableStateDep);
4906 if (FAILED(rc)) return rc;
4907
4908 /* try to find one with the name first. */
4909 ComObjPtr<StorageController> ctrl;
4910
4911 rc = getStorageControllerByName(aName, ctrl, false /* aSetError */);
4912 if (SUCCEEDED(rc))
4913 return setError(VBOX_E_OBJECT_IN_USE,
4914 tr("Storage controller named '%ls' already exists"),
4915 aName);
4916
4917 ctrl.createObject();
4918
4919 /* get a new instance number for the storage controller */
4920 ULONG ulInstance = 0;
4921 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
4922 it != mStorageControllers->end();
4923 ++it)
4924 {
4925 if ((*it)->getStorageBus() == aConnectionType)
4926 {
4927 ULONG ulCurInst = (*it)->getInstance();
4928
4929 if (ulCurInst >= ulInstance)
4930 ulInstance = ulCurInst + 1;
4931 }
4932 }
4933
4934 rc = ctrl->init(this, aName, aConnectionType, ulInstance);
4935 if (FAILED(rc)) return rc;
4936
4937 setModified(IsModified_Storage);
4938 mStorageControllers.backup();
4939 mStorageControllers->push_back(ctrl);
4940
4941 ctrl.queryInterfaceTo(controller);
4942
4943 /* inform the direct session if any */
4944 alock.leave();
4945 onStorageControllerChange();
4946
4947 return S_OK;
4948}
4949
4950STDMETHODIMP Machine::GetStorageControllerByName(IN_BSTR aName,
4951 IStorageController **aStorageController)
4952{
4953 CheckComArgStrNotEmptyOrNull(aName);
4954
4955 AutoCaller autoCaller(this);
4956 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4957
4958 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4959
4960 ComObjPtr<StorageController> ctrl;
4961
4962 HRESULT rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
4963 if (SUCCEEDED(rc))
4964 ctrl.queryInterfaceTo(aStorageController);
4965
4966 return rc;
4967}
4968
4969STDMETHODIMP Machine::GetStorageControllerByInstance(ULONG aInstance,
4970 IStorageController **aStorageController)
4971{
4972 AutoCaller autoCaller(this);
4973 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4974
4975 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4976
4977 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
4978 it != mStorageControllers->end();
4979 ++it)
4980 {
4981 if ((*it)->getInstance() == aInstance)
4982 {
4983 (*it).queryInterfaceTo(aStorageController);
4984 return S_OK;
4985 }
4986 }
4987
4988 return setError(VBOX_E_OBJECT_NOT_FOUND,
4989 tr("Could not find a storage controller with instance number '%lu'"),
4990 aInstance);
4991}
4992
4993STDMETHODIMP Machine::RemoveStorageController(IN_BSTR aName)
4994{
4995 CheckComArgStrNotEmptyOrNull(aName);
4996
4997 AutoCaller autoCaller(this);
4998 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4999
5000 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5001
5002 HRESULT rc = checkStateDependency(MutableStateDep);
5003 if (FAILED(rc)) return rc;
5004
5005 ComObjPtr<StorageController> ctrl;
5006 rc = getStorageControllerByName(aName, ctrl, true /* aSetError */);
5007 if (FAILED(rc)) return rc;
5008
5009 /* We can remove the controller only if there is no device attached. */
5010 /* check if the device slot is already busy */
5011 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
5012 it != mMediaData->mAttachments.end();
5013 ++it)
5014 {
5015 if ((*it)->getControllerName() == aName)
5016 return setError(VBOX_E_OBJECT_IN_USE,
5017 tr("Storage controller named '%ls' has still devices attached"),
5018 aName);
5019 }
5020
5021 /* We can remove it now. */
5022 setModified(IsModified_Storage);
5023 mStorageControllers.backup();
5024
5025 ctrl->unshare();
5026
5027 mStorageControllers->remove(ctrl);
5028
5029 /* inform the direct session if any */
5030 alock.leave();
5031 onStorageControllerChange();
5032
5033 return S_OK;
5034}
5035
5036/* @todo where is the right place for this? */
5037#define sSSMDisplayScreenshotVer 0x00010001
5038
5039static int readSavedDisplayScreenshot(Utf8Str *pStateFilePath, uint32_t u32Type, uint8_t **ppu8Data, uint32_t *pcbData, uint32_t *pu32Width, uint32_t *pu32Height)
5040{
5041 LogFlowFunc(("u32Type = %d [%s]\n", u32Type, pStateFilePath->raw()));
5042
5043 /* @todo cache read data */
5044 if (pStateFilePath->isEmpty())
5045 {
5046 /* No saved state data. */
5047 return VERR_NOT_SUPPORTED;
5048 }
5049
5050 uint8_t *pu8Data = NULL;
5051 uint32_t cbData = 0;
5052 uint32_t u32Width = 0;
5053 uint32_t u32Height = 0;
5054
5055 PSSMHANDLE pSSM;
5056 int vrc = SSMR3Open(pStateFilePath->raw(), 0 /*fFlags*/, &pSSM);
5057 if (RT_SUCCESS(vrc))
5058 {
5059 uint32_t uVersion;
5060 vrc = SSMR3Seek(pSSM, "DisplayScreenshot", 1100 /*iInstance*/, &uVersion);
5061 if (RT_SUCCESS(vrc))
5062 {
5063 if (uVersion == sSSMDisplayScreenshotVer)
5064 {
5065 uint32_t cBlocks;
5066 vrc = SSMR3GetU32(pSSM, &cBlocks);
5067 AssertRCReturn(vrc, vrc);
5068
5069 for (uint32_t i = 0; i < cBlocks; i++)
5070 {
5071 uint32_t cbBlock;
5072 vrc = SSMR3GetU32(pSSM, &cbBlock);
5073 AssertRCBreak(vrc);
5074
5075 uint32_t typeOfBlock;
5076 vrc = SSMR3GetU32(pSSM, &typeOfBlock);
5077 AssertRCBreak(vrc);
5078
5079 LogFlowFunc(("[%d] type %d, size %d bytes\n", i, typeOfBlock, cbBlock));
5080
5081 if (typeOfBlock == u32Type)
5082 {
5083 if (cbBlock > 2 * sizeof(uint32_t))
5084 {
5085 cbData = cbBlock - 2 * sizeof(uint32_t);
5086 pu8Data = (uint8_t *)RTMemAlloc(cbData);
5087 if (pu8Data == NULL)
5088 {
5089 vrc = VERR_NO_MEMORY;
5090 break;
5091 }
5092
5093 vrc = SSMR3GetU32(pSSM, &u32Width);
5094 AssertRCBreak(vrc);
5095 vrc = SSMR3GetU32(pSSM, &u32Height);
5096 AssertRCBreak(vrc);
5097 vrc = SSMR3GetMem(pSSM, pu8Data, cbData);
5098 AssertRCBreak(vrc);
5099 }
5100 else
5101 {
5102 /* No saved state data. */
5103 vrc = VERR_NOT_SUPPORTED;
5104 }
5105
5106 break;
5107 }
5108 else
5109 {
5110 /* displaySSMSaveScreenshot did not write any data, if
5111 * cbBlock was == 2 * sizeof (uint32_t).
5112 */
5113 if (cbBlock > 2 * sizeof (uint32_t))
5114 {
5115 vrc = SSMR3Skip(pSSM, cbBlock);
5116 AssertRCBreak(vrc);
5117 }
5118 }
5119 }
5120 }
5121 else
5122 {
5123 vrc = VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
5124 }
5125 }
5126
5127 SSMR3Close(pSSM);
5128 }
5129
5130 if (RT_SUCCESS(vrc))
5131 {
5132 if (u32Type == 0 && cbData % 4 != 0)
5133 {
5134 /* Bitmap is 32bpp, so data is invalid. */
5135 vrc = VERR_SSM_UNEXPECTED_DATA;
5136 }
5137 }
5138
5139 if (RT_SUCCESS(vrc))
5140 {
5141 *ppu8Data = pu8Data;
5142 *pcbData = cbData;
5143 *pu32Width = u32Width;
5144 *pu32Height = u32Height;
5145 LogFlowFunc(("cbData %d, u32Width %d, u32Height %d\n", cbData, u32Width, u32Height));
5146 }
5147
5148 LogFlowFunc(("vrc %Rrc\n", vrc));
5149 return vrc;
5150}
5151
5152static void freeSavedDisplayScreenshot(uint8_t *pu8Data)
5153{
5154 /* @todo not necessary when caching is implemented. */
5155 RTMemFree(pu8Data);
5156}
5157
5158STDMETHODIMP Machine::QuerySavedThumbnailSize(ULONG aScreenId, ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
5159{
5160 LogFlowThisFunc(("\n"));
5161
5162 CheckComArgNotNull(aSize);
5163 CheckComArgNotNull(aWidth);
5164 CheckComArgNotNull(aHeight);
5165
5166 if (aScreenId != 0)
5167 return E_NOTIMPL;
5168
5169 AutoCaller autoCaller(this);
5170 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5171
5172 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5173
5174 uint8_t *pu8Data = NULL;
5175 uint32_t cbData = 0;
5176 uint32_t u32Width = 0;
5177 uint32_t u32Height = 0;
5178
5179 int vrc = readSavedDisplayScreenshot(&mSSData->mStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5180
5181 if (RT_FAILURE(vrc))
5182 return setError(VBOX_E_IPRT_ERROR,
5183 tr("Saved screenshot data is not available (%Rrc)"),
5184 vrc);
5185
5186 *aSize = cbData;
5187 *aWidth = u32Width;
5188 *aHeight = u32Height;
5189
5190 freeSavedDisplayScreenshot(pu8Data);
5191
5192 return S_OK;
5193}
5194
5195STDMETHODIMP Machine::ReadSavedThumbnailToArray(ULONG aScreenId, BOOL aBGR, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5196{
5197 LogFlowThisFunc(("\n"));
5198
5199 CheckComArgNotNull(aWidth);
5200 CheckComArgNotNull(aHeight);
5201 CheckComArgOutSafeArrayPointerValid(aData);
5202
5203 if (aScreenId != 0)
5204 return E_NOTIMPL;
5205
5206 AutoCaller autoCaller(this);
5207 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5208
5209 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5210
5211 uint8_t *pu8Data = NULL;
5212 uint32_t cbData = 0;
5213 uint32_t u32Width = 0;
5214 uint32_t u32Height = 0;
5215
5216 int vrc = readSavedDisplayScreenshot(&mSSData->mStateFilePath, 0 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5217
5218 if (RT_FAILURE(vrc))
5219 return setError(VBOX_E_IPRT_ERROR,
5220 tr("Saved screenshot data is not available (%Rrc)"),
5221 vrc);
5222
5223 *aWidth = u32Width;
5224 *aHeight = u32Height;
5225
5226 com::SafeArray<BYTE> bitmap(cbData);
5227 /* Convert pixels to format expected by the API caller. */
5228 if (aBGR)
5229 {
5230 /* [0] B, [1] G, [2] R, [3] A. */
5231 for (unsigned i = 0; i < cbData; i += 4)
5232 {
5233 bitmap[i] = pu8Data[i];
5234 bitmap[i + 1] = pu8Data[i + 1];
5235 bitmap[i + 2] = pu8Data[i + 2];
5236 bitmap[i + 3] = 0xff;
5237 }
5238 }
5239 else
5240 {
5241 /* [0] R, [1] G, [2] B, [3] A. */
5242 for (unsigned i = 0; i < cbData; i += 4)
5243 {
5244 bitmap[i] = pu8Data[i + 2];
5245 bitmap[i + 1] = pu8Data[i + 1];
5246 bitmap[i + 2] = pu8Data[i];
5247 bitmap[i + 3] = 0xff;
5248 }
5249 }
5250 bitmap.detachTo(ComSafeArrayOutArg(aData));
5251
5252 freeSavedDisplayScreenshot(pu8Data);
5253
5254 return S_OK;
5255}
5256
5257STDMETHODIMP Machine::QuerySavedScreenshotPNGSize(ULONG aScreenId, ULONG *aSize, ULONG *aWidth, ULONG *aHeight)
5258{
5259 LogFlowThisFunc(("\n"));
5260
5261 CheckComArgNotNull(aSize);
5262 CheckComArgNotNull(aWidth);
5263 CheckComArgNotNull(aHeight);
5264
5265 if (aScreenId != 0)
5266 return E_NOTIMPL;
5267
5268 AutoCaller autoCaller(this);
5269 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5270
5271 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5272
5273 uint8_t *pu8Data = NULL;
5274 uint32_t cbData = 0;
5275 uint32_t u32Width = 0;
5276 uint32_t u32Height = 0;
5277
5278 int vrc = readSavedDisplayScreenshot(&mSSData->mStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5279
5280 if (RT_FAILURE(vrc))
5281 return setError(VBOX_E_IPRT_ERROR,
5282 tr("Saved screenshot data is not available (%Rrc)"),
5283 vrc);
5284
5285 *aSize = cbData;
5286 *aWidth = u32Width;
5287 *aHeight = u32Height;
5288
5289 freeSavedDisplayScreenshot(pu8Data);
5290
5291 return S_OK;
5292}
5293
5294STDMETHODIMP Machine::ReadSavedScreenshotPNGToArray(ULONG aScreenId, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData))
5295{
5296 LogFlowThisFunc(("\n"));
5297
5298 CheckComArgNotNull(aWidth);
5299 CheckComArgNotNull(aHeight);
5300 CheckComArgOutSafeArrayPointerValid(aData);
5301
5302 if (aScreenId != 0)
5303 return E_NOTIMPL;
5304
5305 AutoCaller autoCaller(this);
5306 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5307
5308 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5309
5310 uint8_t *pu8Data = NULL;
5311 uint32_t cbData = 0;
5312 uint32_t u32Width = 0;
5313 uint32_t u32Height = 0;
5314
5315 int vrc = readSavedDisplayScreenshot(&mSSData->mStateFilePath, 1 /* u32Type */, &pu8Data, &cbData, &u32Width, &u32Height);
5316
5317 if (RT_FAILURE(vrc))
5318 return setError(VBOX_E_IPRT_ERROR,
5319 tr("Saved screenshot data is not available (%Rrc)"),
5320 vrc);
5321
5322 *aWidth = u32Width;
5323 *aHeight = u32Height;
5324
5325 com::SafeArray<BYTE> png(cbData);
5326 for (unsigned i = 0; i < cbData; i++)
5327 png[i] = pu8Data[i];
5328 png.detachTo(ComSafeArrayOutArg(aData));
5329
5330 freeSavedDisplayScreenshot(pu8Data);
5331
5332 return S_OK;
5333}
5334
5335STDMETHODIMP Machine::HotPlugCPU(ULONG aCpu)
5336{
5337 HRESULT rc = S_OK;
5338 LogFlowThisFunc(("\n"));
5339
5340 AutoCaller autoCaller(this);
5341 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5342
5343 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5344
5345 if (!mHWData->mCPUHotPlugEnabled)
5346 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
5347
5348 if (aCpu >= mHWData->mCPUCount)
5349 return setError(E_INVALIDARG, tr("CPU id exceeds number of possible CPUs [0:%lu]"), mHWData->mCPUCount-1);
5350
5351 if (mHWData->mCPUAttached[aCpu])
5352 return setError(VBOX_E_OBJECT_IN_USE, tr("CPU %lu is already attached"), aCpu);
5353
5354 alock.release();
5355 rc = onCPUChange(aCpu, false);
5356 alock.acquire();
5357 if (FAILED(rc)) return rc;
5358
5359 setModified(IsModified_MachineData);
5360 mHWData.backup();
5361 mHWData->mCPUAttached[aCpu] = true;
5362
5363 /* Save settings if online */
5364 if (Global::IsOnline(mData->mMachineState))
5365 saveSettings(NULL);
5366
5367 return S_OK;
5368}
5369
5370STDMETHODIMP Machine::HotUnplugCPU(ULONG aCpu)
5371{
5372 HRESULT rc = S_OK;
5373 LogFlowThisFunc(("\n"));
5374
5375 AutoCaller autoCaller(this);
5376 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5377
5378 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5379
5380 if (!mHWData->mCPUHotPlugEnabled)
5381 return setError(E_INVALIDARG, tr("CPU hotplug is not enabled"));
5382
5383 if (aCpu >= SchemaDefs::MaxCPUCount)
5384 return setError(E_INVALIDARG,
5385 tr("CPU index exceeds maximum CPU count (must be in range [0:%lu])"),
5386 SchemaDefs::MaxCPUCount);
5387
5388 if (!mHWData->mCPUAttached[aCpu])
5389 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("CPU %lu is not attached"), aCpu);
5390
5391 /* CPU 0 can't be detached */
5392 if (aCpu == 0)
5393 return setError(E_INVALIDARG, tr("It is not possible to detach CPU 0"));
5394
5395 alock.release();
5396 rc = onCPUChange(aCpu, true);
5397 alock.acquire();
5398 if (FAILED(rc)) return rc;
5399
5400 setModified(IsModified_MachineData);
5401 mHWData.backup();
5402 mHWData->mCPUAttached[aCpu] = false;
5403
5404 /* Save settings if online */
5405 if (Global::IsOnline(mData->mMachineState))
5406 saveSettings(NULL);
5407
5408 return S_OK;
5409}
5410
5411STDMETHODIMP Machine::GetCPUStatus(ULONG aCpu, BOOL *aCpuAttached)
5412{
5413 LogFlowThisFunc(("\n"));
5414
5415 CheckComArgNotNull(aCpuAttached);
5416
5417 *aCpuAttached = false;
5418
5419 AutoCaller autoCaller(this);
5420 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5421
5422 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5423
5424 /* If hotplug is enabled the CPU is always enabled. */
5425 if (!mHWData->mCPUHotPlugEnabled)
5426 {
5427 if (aCpu < mHWData->mCPUCount)
5428 *aCpuAttached = true;
5429 }
5430 else
5431 {
5432 if (aCpu < SchemaDefs::MaxCPUCount)
5433 *aCpuAttached = mHWData->mCPUAttached[aCpu];
5434 }
5435
5436 return S_OK;
5437}
5438
5439STDMETHODIMP Machine::QueryLogFilename(ULONG aIdx, BSTR *aName)
5440{
5441 CheckComArgOutPointerValid(aName);
5442
5443 AutoCaller autoCaller(this);
5444 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5445
5446 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5447
5448 Utf8Str log = queryLogFilename(aIdx);
5449 if (!RTFileExists(log.c_str()))
5450 log.setNull();
5451 log.cloneTo(aName);
5452
5453 return S_OK;
5454}
5455
5456STDMETHODIMP Machine::ReadLog(ULONG aIdx, ULONG64 aOffset, ULONG64 aSize, ComSafeArrayOut(BYTE, aData))
5457{
5458 LogFlowThisFunc(("\n"));
5459 CheckComArgOutSafeArrayPointerValid(aData);
5460
5461 AutoCaller autoCaller(this);
5462 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5463
5464 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5465
5466 HRESULT rc = S_OK;
5467 Utf8Str log = queryLogFilename(aIdx);
5468
5469 /* do not unnecessarily hold the lock while doing something which does
5470 * not need the lock and potentially takes a long time. */
5471 alock.release();
5472
5473 /* Limit the chunk size to 32K for now, as that gives better performance
5474 * over (XP)COM, and keeps the SOAP reply size under 1M for the webservice.
5475 * One byte expands to approx. 25 bytes of breathtaking XML. */
5476 size_t cbData = (size_t)RT_MIN(aSize, 32768);
5477 com::SafeArray<BYTE> logData(cbData);
5478
5479 RTFILE LogFile;
5480 int vrc = RTFileOpen(&LogFile, log.raw(),
5481 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
5482 if (RT_SUCCESS(vrc))
5483 {
5484 vrc = RTFileReadAt(LogFile, aOffset, logData.raw(), cbData, &cbData);
5485 if (RT_SUCCESS(vrc))
5486 logData.resize(cbData);
5487 else
5488 rc = setError(VBOX_E_IPRT_ERROR,
5489 tr("Could not read log file '%s' (%Rrc)"),
5490 log.raw(), vrc);
5491 RTFileClose(LogFile);
5492 }
5493 else
5494 rc = setError(VBOX_E_IPRT_ERROR,
5495 tr("Could not open log file '%s' (%Rrc)"),
5496 log.raw(), vrc);
5497
5498 if (FAILED(rc))
5499 logData.resize(0);
5500 logData.detachTo(ComSafeArrayOutArg(aData));
5501
5502 return rc;
5503}
5504
5505
5506// public methods for internal purposes
5507/////////////////////////////////////////////////////////////////////////////
5508
5509/**
5510 * Adds the given IsModified_* flag to the dirty flags of the machine.
5511 * This must be called either during loadSettings or under the machine write lock.
5512 * @param fl
5513 */
5514void Machine::setModified(uint32_t fl)
5515{
5516 mData->flModifications |= fl;
5517}
5518
5519/**
5520 * Saves the registry entry of this machine to the given configuration node.
5521 *
5522 * @param aEntryNode Node to save the registry entry to.
5523 *
5524 * @note locks this object for reading.
5525 */
5526HRESULT Machine::saveRegistryEntry(settings::MachineRegistryEntry &data)
5527{
5528 AutoLimitedCaller autoCaller(this);
5529 AssertComRCReturnRC(autoCaller.rc());
5530
5531 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5532
5533 data.uuid = mData->mUuid;
5534 data.strSettingsFile = mData->m_strConfigFile;
5535
5536 return S_OK;
5537}
5538
5539/**
5540 * Calculates the absolute path of the given path taking the directory of the
5541 * machine settings file as the current directory.
5542 *
5543 * @param aPath Path to calculate the absolute path for.
5544 * @param aResult Where to put the result (used only on success, can be the
5545 * same Utf8Str instance as passed in @a aPath).
5546 * @return IPRT result.
5547 *
5548 * @note Locks this object for reading.
5549 */
5550int Machine::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
5551{
5552 AutoCaller autoCaller(this);
5553 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
5554
5555 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5556
5557 AssertReturn(!mData->m_strConfigFileFull.isEmpty(), VERR_GENERAL_FAILURE);
5558
5559 Utf8Str strSettingsDir = mData->m_strConfigFileFull;
5560
5561 strSettingsDir.stripFilename();
5562 char folder[RTPATH_MAX];
5563 int vrc = RTPathAbsEx(strSettingsDir.c_str(), strPath.c_str(), folder, sizeof(folder));
5564 if (RT_SUCCESS(vrc))
5565 aResult = folder;
5566
5567 return vrc;
5568}
5569
5570/**
5571 * Copies strSource to strTarget, making it relative to the machine folder
5572 * if it is a subdirectory thereof, or simply copying it otherwise.
5573 *
5574 * @param strSource Path to evalue and copy.
5575 * @param strTarget Buffer to receive target path.
5576 *
5577 * @note Locks this object for reading.
5578 */
5579void Machine::copyPathRelativeToMachine(const Utf8Str &strSource,
5580 Utf8Str &strTarget)
5581{
5582 AutoCaller autoCaller(this);
5583 AssertComRCReturn(autoCaller.rc(), (void)0);
5584
5585 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5586
5587 AssertReturnVoid(!mData->m_strConfigFileFull.isEmpty());
5588 // use strTarget as a temporary buffer to hold the machine settings dir
5589 strTarget = mData->m_strConfigFileFull;
5590 strTarget.stripFilename();
5591 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
5592 // is relative: then append what's left
5593 strTarget.append(strSource.c_str() + strTarget.length()); // include '/'
5594 else
5595 // is not relative: then overwrite
5596 strTarget = strSource;
5597}
5598
5599/**
5600 * Returns the full path to the machine's log folder in the
5601 * \a aLogFolder argument.
5602 */
5603void Machine::getLogFolder(Utf8Str &aLogFolder)
5604{
5605 AutoCaller autoCaller(this);
5606 AssertComRCReturnVoid(autoCaller.rc());
5607
5608 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5609
5610 Utf8Str settingsDir;
5611 if (isInOwnDir(&settingsDir))
5612 {
5613 /* Log folder is <Machines>/<VM_Name>/Logs */
5614 aLogFolder = Utf8StrFmt("%s%cLogs", settingsDir.raw(), RTPATH_DELIMITER);
5615 }
5616 else
5617 {
5618 /* Log folder is <Machines>/<VM_SnapshotFolder>/Logs */
5619 Assert(!mUserData->mSnapshotFolderFull.isEmpty());
5620 aLogFolder = Utf8StrFmt ("%ls%cLogs", mUserData->mSnapshotFolderFull.raw(),
5621 RTPATH_DELIMITER);
5622 }
5623}
5624
5625/**
5626 * Returns the full path to the machine's log file for an given index.
5627 */
5628Utf8Str Machine::queryLogFilename(ULONG idx)
5629{
5630 Utf8Str logFolder;
5631 getLogFolder(logFolder);
5632 Assert(logFolder.length());
5633 Utf8Str log;
5634 if (idx == 0)
5635 log = Utf8StrFmt("%s%cVBox.log",
5636 logFolder.raw(), RTPATH_DELIMITER);
5637 else
5638 log = Utf8StrFmt("%s%cVBox.log.%d",
5639 logFolder.raw(), RTPATH_DELIMITER, idx);
5640 return log;
5641}
5642
5643/**
5644 * @note Locks this object for writing, calls the client process
5645 * (inside the lock).
5646 */
5647HRESULT Machine::openRemoteSession(IInternalSessionControl *aControl,
5648 IN_BSTR aType,
5649 IN_BSTR aEnvironment,
5650 ProgressProxy *aProgress)
5651{
5652 LogFlowThisFuncEnter();
5653
5654 AssertReturn(aControl, E_FAIL);
5655 AssertReturn(aProgress, E_FAIL);
5656
5657 AutoCaller autoCaller(this);
5658 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5659
5660 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5661
5662 if (!mData->mRegistered)
5663 return setError(E_UNEXPECTED,
5664 tr("The machine '%ls' is not registered"),
5665 mUserData->mName.raw());
5666
5667 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
5668
5669 if ( mData->mSession.mState == SessionState_Locked
5670 || mData->mSession.mState == SessionState_Spawning
5671 || mData->mSession.mState == SessionState_Unlocking)
5672 return setError(VBOX_E_INVALID_OBJECT_STATE,
5673 tr("The machine '%ls' is already locked by a session (or being locked or unlocked)"),
5674 mUserData->mName.raw());
5675
5676 /* may not be busy */
5677 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
5678
5679 /* get the path to the executable */
5680 char szPath[RTPATH_MAX];
5681 RTPathAppPrivateArch(szPath, RTPATH_MAX);
5682 size_t sz = strlen(szPath);
5683 szPath[sz++] = RTPATH_DELIMITER;
5684 szPath[sz] = 0;
5685 char *cmd = szPath + sz;
5686 sz = RTPATH_MAX - sz;
5687
5688 int vrc = VINF_SUCCESS;
5689 RTPROCESS pid = NIL_RTPROCESS;
5690
5691 RTENV env = RTENV_DEFAULT;
5692
5693 if (aEnvironment != NULL && *aEnvironment)
5694 {
5695 char *newEnvStr = NULL;
5696
5697 do
5698 {
5699 /* clone the current environment */
5700 int vrc2 = RTEnvClone(&env, RTENV_DEFAULT);
5701 AssertRCBreakStmt(vrc2, vrc = vrc2);
5702
5703 newEnvStr = RTStrDup(Utf8Str(aEnvironment).c_str());
5704 AssertPtrBreakStmt(newEnvStr, vrc = vrc2);
5705
5706 /* put new variables to the environment
5707 * (ignore empty variable names here since RTEnv API
5708 * intentionally doesn't do that) */
5709 char *var = newEnvStr;
5710 for (char *p = newEnvStr; *p; ++p)
5711 {
5712 if (*p == '\n' && (p == newEnvStr || *(p - 1) != '\\'))
5713 {
5714 *p = '\0';
5715 if (*var)
5716 {
5717 char *val = strchr(var, '=');
5718 if (val)
5719 {
5720 *val++ = '\0';
5721 vrc2 = RTEnvSetEx(env, var, val);
5722 }
5723 else
5724 vrc2 = RTEnvUnsetEx(env, var);
5725 if (RT_FAILURE(vrc2))
5726 break;
5727 }
5728 var = p + 1;
5729 }
5730 }
5731 if (RT_SUCCESS(vrc2) && *var)
5732 vrc2 = RTEnvPutEx(env, var);
5733
5734 AssertRCBreakStmt(vrc2, vrc = vrc2);
5735 }
5736 while (0);
5737
5738 if (newEnvStr != NULL)
5739 RTStrFree(newEnvStr);
5740 }
5741
5742 Utf8Str strType(aType);
5743
5744 /* Qt is default */
5745#ifdef VBOX_WITH_QTGUI
5746 if (strType == "gui" || strType == "GUI/Qt")
5747 {
5748# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
5749 const char VirtualBox_exe[] = "../Resources/VirtualBoxVM.app/Contents/MacOS/VirtualBoxVM";
5750# else
5751 const char VirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
5752# endif
5753 Assert(sz >= sizeof(VirtualBox_exe));
5754 strcpy(cmd, VirtualBox_exe);
5755
5756 Utf8Str idStr = mData->mUuid.toString();
5757 Utf8Str strName = mUserData->mName;
5758 const char * args[] = {szPath, "--comment", strName.c_str(), "--startvm", idStr.c_str(), "--no-startvm-errormsgbox", 0 };
5759 vrc = RTProcCreate(szPath, args, env, 0, &pid);
5760 }
5761#else /* !VBOX_WITH_QTGUI */
5762 if (0)
5763 ;
5764#endif /* VBOX_WITH_QTGUI */
5765
5766 else
5767
5768#ifdef VBOX_WITH_VBOXSDL
5769 if (strType == "sdl" || strType == "GUI/SDL")
5770 {
5771 const char VBoxSDL_exe[] = "VBoxSDL" HOSTSUFF_EXE;
5772 Assert(sz >= sizeof(VBoxSDL_exe));
5773 strcpy(cmd, VBoxSDL_exe);
5774
5775 Utf8Str idStr = mData->mUuid.toString();
5776 Utf8Str strName = mUserData->mName;
5777 const char * args[] = {szPath, "--comment", strName.c_str(), "--startvm", idStr.c_str(), 0 };
5778 vrc = RTProcCreate(szPath, args, env, 0, &pid);
5779 }
5780#else /* !VBOX_WITH_VBOXSDL */
5781 if (0)
5782 ;
5783#endif /* !VBOX_WITH_VBOXSDL */
5784
5785 else
5786
5787#ifdef VBOX_WITH_HEADLESS
5788 if ( strType == "headless"
5789 || strType == "capture"
5790#ifdef VBOX_WITH_VRDP
5791 || strType == "vrdp"
5792#endif
5793 )
5794 {
5795 const char VBoxHeadless_exe[] = "VBoxHeadless" HOSTSUFF_EXE;
5796 Assert(sz >= sizeof(VBoxHeadless_exe));
5797 strcpy(cmd, VBoxHeadless_exe);
5798
5799 Utf8Str idStr = mData->mUuid.toString();
5800 /* Leave space for 2 args, as "headless" needs --vrdp off on non-OSE. */
5801 Utf8Str strName = mUserData->mName;
5802 const char * args[] = {szPath, "--comment", strName.c_str(), "--startvm", idStr.c_str(), 0, 0, 0 };
5803#ifdef VBOX_WITH_VRDP
5804 if (strType == "headless")
5805 {
5806 unsigned pos = RT_ELEMENTS(args) - 3;
5807 args[pos++] = "--vrdp";
5808 args[pos] = "off";
5809 }
5810#endif
5811 if (strType == "capture")
5812 {
5813 unsigned pos = RT_ELEMENTS(args) - 3;
5814 args[pos] = "--capture";
5815 }
5816 vrc = RTProcCreate(szPath, args, env, 0, &pid);
5817 }
5818#else /* !VBOX_WITH_HEADLESS */
5819 if (0)
5820 ;
5821#endif /* !VBOX_WITH_HEADLESS */
5822 else
5823 {
5824 RTEnvDestroy(env);
5825 return setError(E_INVALIDARG,
5826 tr("Invalid session type: '%s'"),
5827 strType.c_str());
5828 }
5829
5830 RTEnvDestroy(env);
5831
5832 if (RT_FAILURE(vrc))
5833 return setError(VBOX_E_IPRT_ERROR,
5834 tr("Could not launch a process for the machine '%ls' (%Rrc)"),
5835 mUserData->mName.raw(), vrc);
5836
5837 LogFlowThisFunc(("launched.pid=%d(0x%x)\n", pid, pid));
5838
5839 /*
5840 * Note that we don't leave the lock here before calling the client,
5841 * because it doesn't need to call us back if called with a NULL argument.
5842 * Leaving the lock herer is dangerous because we didn't prepare the
5843 * launch data yet, but the client we've just started may happen to be
5844 * too fast and call openSession() that will fail (because of PID, etc.),
5845 * so that the Machine will never get out of the Spawning session state.
5846 */
5847
5848 /* inform the session that it will be a remote one */
5849 LogFlowThisFunc(("Calling AssignMachine (NULL)...\n"));
5850 HRESULT rc = aControl->AssignMachine(NULL);
5851 LogFlowThisFunc(("AssignMachine (NULL) returned %08X\n", rc));
5852
5853 if (FAILED(rc))
5854 {
5855 /* restore the session state */
5856 mData->mSession.mState = SessionState_Unlocked;
5857 /* The failure may occur w/o any error info (from RPC), so provide one */
5858 return setError(VBOX_E_VM_ERROR,
5859 tr("Failed to assign the machine to the session (%Rrc)"), rc);
5860 }
5861
5862 /* attach launch data to the machine */
5863 Assert(mData->mSession.mPid == NIL_RTPROCESS);
5864 mData->mSession.mRemoteControls.push_back (aControl);
5865 mData->mSession.mProgress = aProgress;
5866 mData->mSession.mPid = pid;
5867 mData->mSession.mState = SessionState_Spawning;
5868 mData->mSession.mType = strType;
5869
5870 LogFlowThisFuncLeave();
5871 return S_OK;
5872}
5873
5874/**
5875 * Returns @c true if the given machine has an open direct session and returns
5876 * the session machine instance and additional session data (on some platforms)
5877 * if so.
5878 *
5879 * Note that when the method returns @c false, the arguments remain unchanged.
5880 *
5881 * @param aMachine Session machine object.
5882 * @param aControl Direct session control object (optional).
5883 * @param aIPCSem Mutex IPC semaphore handle for this machine (optional).
5884 *
5885 * @note locks this object for reading.
5886 */
5887#if defined(RT_OS_WINDOWS)
5888bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
5889 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
5890 HANDLE *aIPCSem /*= NULL*/,
5891 bool aAllowClosing /*= false*/)
5892#elif defined(RT_OS_OS2)
5893bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
5894 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
5895 HMTX *aIPCSem /*= NULL*/,
5896 bool aAllowClosing /*= false*/)
5897#else
5898bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
5899 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
5900 bool aAllowClosing /*= false*/)
5901#endif
5902{
5903 AutoLimitedCaller autoCaller(this);
5904 AssertComRCReturn(autoCaller.rc(), false);
5905
5906 /* just return false for inaccessible machines */
5907 if (autoCaller.state() != Ready)
5908 return false;
5909
5910 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5911
5912 if ( mData->mSession.mState == SessionState_Locked
5913 || (aAllowClosing && mData->mSession.mState == SessionState_Unlocking)
5914 )
5915 {
5916 AssertReturn(!mData->mSession.mMachine.isNull(), false);
5917
5918 aMachine = mData->mSession.mMachine;
5919
5920 if (aControl != NULL)
5921 *aControl = mData->mSession.mDirectControl;
5922
5923#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
5924 /* Additional session data */
5925 if (aIPCSem != NULL)
5926 *aIPCSem = aMachine->mIPCSem;
5927#endif
5928 return true;
5929 }
5930
5931 return false;
5932}
5933
5934/**
5935 * Returns @c true if the given machine has an spawning direct session and
5936 * returns and additional session data (on some platforms) if so.
5937 *
5938 * Note that when the method returns @c false, the arguments remain unchanged.
5939 *
5940 * @param aPID PID of the spawned direct session process.
5941 *
5942 * @note locks this object for reading.
5943 */
5944#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
5945bool Machine::isSessionSpawning(RTPROCESS *aPID /*= NULL*/)
5946#else
5947bool Machine::isSessionSpawning()
5948#endif
5949{
5950 AutoLimitedCaller autoCaller(this);
5951 AssertComRCReturn(autoCaller.rc(), false);
5952
5953 /* just return false for inaccessible machines */
5954 if (autoCaller.state() != Ready)
5955 return false;
5956
5957 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5958
5959 if (mData->mSession.mState == SessionState_Spawning)
5960 {
5961#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
5962 /* Additional session data */
5963 if (aPID != NULL)
5964 {
5965 AssertReturn(mData->mSession.mPid != NIL_RTPROCESS, false);
5966 *aPID = mData->mSession.mPid;
5967 }
5968#endif
5969 return true;
5970 }
5971
5972 return false;
5973}
5974
5975/**
5976 * Called from the client watcher thread to check for unexpected client process
5977 * death during Session_Spawning state (e.g. before it successfully opened a
5978 * direct session).
5979 *
5980 * On Win32 and on OS/2, this method is called only when we've got the
5981 * direct client's process termination notification, so it always returns @c
5982 * true.
5983 *
5984 * On other platforms, this method returns @c true if the client process is
5985 * terminated and @c false if it's still alive.
5986 *
5987 * @note Locks this object for writing.
5988 */
5989bool Machine::checkForSpawnFailure()
5990{
5991 AutoCaller autoCaller(this);
5992 if (!autoCaller.isOk())
5993 {
5994 /* nothing to do */
5995 LogFlowThisFunc(("Already uninitialized!\n"));
5996 return true;
5997 }
5998
5999 /* VirtualBox::addProcessToReap() needs a write lock */
6000 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
6001
6002 if (mData->mSession.mState != SessionState_Spawning)
6003 {
6004 /* nothing to do */
6005 LogFlowThisFunc(("Not spawning any more!\n"));
6006 return true;
6007 }
6008
6009 HRESULT rc = S_OK;
6010
6011#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6012
6013 /* the process was already unexpectedly terminated, we just need to set an
6014 * error and finalize session spawning */
6015 rc = setError(E_FAIL,
6016 tr("The virtual machine '%ls' has terminated unexpectedly during startup"),
6017 getName().raw());
6018#else
6019
6020 /* PID not yet initialized, skip check. */
6021 if (mData->mSession.mPid == NIL_RTPROCESS)
6022 return false;
6023
6024 RTPROCSTATUS status;
6025 int vrc = ::RTProcWait(mData->mSession.mPid, RTPROCWAIT_FLAGS_NOBLOCK,
6026 &status);
6027
6028 if (vrc != VERR_PROCESS_RUNNING)
6029 {
6030 if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_NORMAL)
6031 rc = setError(E_FAIL,
6032 tr("The virtual machine '%ls' has terminated unexpectedly during startup with exit code %d"),
6033 getName().raw(), status.iStatus);
6034 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_SIGNAL)
6035 rc = setError(E_FAIL,
6036 tr("The virtual machine '%ls' has terminated unexpectedly during startup because of signal %d"),
6037 getName().raw(), status.iStatus);
6038 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_ABEND)
6039 rc = setError(E_FAIL,
6040 tr("The virtual machine '%ls' has terminated abnormally"),
6041 getName().raw(), status.iStatus);
6042 else
6043 rc = setError(E_FAIL,
6044 tr("The virtual machine '%ls' has terminated unexpectedly during startup (%Rrc)"),
6045 getName().raw(), rc);
6046 }
6047
6048#endif
6049
6050 if (FAILED(rc))
6051 {
6052 /* Close the remote session, remove the remote control from the list
6053 * and reset session state to Closed (@note keep the code in sync with
6054 * the relevant part in checkForSpawnFailure()). */
6055
6056 Assert(mData->mSession.mRemoteControls.size() == 1);
6057 if (mData->mSession.mRemoteControls.size() == 1)
6058 {
6059 ErrorInfoKeeper eik;
6060 mData->mSession.mRemoteControls.front()->Uninitialize();
6061 }
6062
6063 mData->mSession.mRemoteControls.clear();
6064 mData->mSession.mState = SessionState_Unlocked;
6065
6066 /* finalize the progress after setting the state */
6067 if (!mData->mSession.mProgress.isNull())
6068 {
6069 mData->mSession.mProgress->notifyComplete(rc);
6070 mData->mSession.mProgress.setNull();
6071 }
6072
6073 mParent->addProcessToReap(mData->mSession.mPid);
6074 mData->mSession.mPid = NIL_RTPROCESS;
6075
6076 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
6077 return true;
6078 }
6079
6080 return false;
6081}
6082
6083/**
6084 * Checks whether the machine can be registered. If so, commits and saves
6085 * all settings.
6086 *
6087 * @note Must be called from mParent's write lock. Locks this object and
6088 * children for writing.
6089 */
6090HRESULT Machine::prepareRegister()
6091{
6092 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
6093
6094 AutoLimitedCaller autoCaller(this);
6095 AssertComRCReturnRC(autoCaller.rc());
6096
6097 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6098
6099 /* wait for state dependants to drop to zero */
6100 ensureNoStateDependencies();
6101
6102 if (!mData->mAccessible)
6103 return setError(VBOX_E_INVALID_OBJECT_STATE,
6104 tr("The machine '%ls' with UUID {%s} is inaccessible and cannot be registered"),
6105 mUserData->mName.raw(),
6106 mData->mUuid.toString().raw());
6107
6108 AssertReturn(autoCaller.state() == Ready, E_FAIL);
6109
6110 if (mData->mRegistered)
6111 return setError(VBOX_E_INVALID_OBJECT_STATE,
6112 tr("The machine '%ls' with UUID {%s} is already registered"),
6113 mUserData->mName.raw(),
6114 mData->mUuid.toString().raw());
6115
6116 HRESULT rc = S_OK;
6117
6118 // Ensure the settings are saved. If we are going to be registered and
6119 // no config file exists yet, create it by calling saveSettings() too.
6120 if ( (mData->flModifications)
6121 || (!mData->pMachineConfigFile->fileExists())
6122 )
6123 {
6124 rc = saveSettings(NULL);
6125 // no need to check whether VirtualBox.xml needs saving too since
6126 // we can't have a machine XML file rename pending
6127 if (FAILED(rc)) return rc;
6128 }
6129
6130 /* more config checking goes here */
6131
6132 if (SUCCEEDED(rc))
6133 {
6134 /* we may have had implicit modifications we want to fix on success */
6135 commit();
6136
6137 mData->mRegistered = true;
6138 }
6139 else
6140 {
6141 /* we may have had implicit modifications we want to cancel on failure*/
6142 rollback(false /* aNotify */);
6143 }
6144
6145 return rc;
6146}
6147
6148/**
6149 * Increases the number of objects dependent on the machine state or on the
6150 * registered state. Guarantees that these two states will not change at least
6151 * until #releaseStateDependency() is called.
6152 *
6153 * Depending on the @a aDepType value, additional state checks may be made.
6154 * These checks will set extended error info on failure. See
6155 * #checkStateDependency() for more info.
6156 *
6157 * If this method returns a failure, the dependency is not added and the caller
6158 * is not allowed to rely on any particular machine state or registration state
6159 * value and may return the failed result code to the upper level.
6160 *
6161 * @param aDepType Dependency type to add.
6162 * @param aState Current machine state (NULL if not interested).
6163 * @param aRegistered Current registered state (NULL if not interested).
6164 *
6165 * @note Locks this object for writing.
6166 */
6167HRESULT Machine::addStateDependency(StateDependency aDepType /* = AnyStateDep */,
6168 MachineState_T *aState /* = NULL */,
6169 BOOL *aRegistered /* = NULL */)
6170{
6171 AutoCaller autoCaller(this);
6172 AssertComRCReturnRC(autoCaller.rc());
6173
6174 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6175
6176 HRESULT rc = checkStateDependency(aDepType);
6177 if (FAILED(rc)) return rc;
6178
6179 {
6180 if (mData->mMachineStateChangePending != 0)
6181 {
6182 /* ensureNoStateDependencies() is waiting for state dependencies to
6183 * drop to zero so don't add more. It may make sense to wait a bit
6184 * and retry before reporting an error (since the pending state
6185 * transition should be really quick) but let's just assert for
6186 * now to see if it ever happens on practice. */
6187
6188 AssertFailed();
6189
6190 return setError(E_ACCESSDENIED,
6191 tr("Machine state change is in progress. Please retry the operation later."));
6192 }
6193
6194 ++mData->mMachineStateDeps;
6195 Assert(mData->mMachineStateDeps != 0 /* overflow */);
6196 }
6197
6198 if (aState)
6199 *aState = mData->mMachineState;
6200 if (aRegistered)
6201 *aRegistered = mData->mRegistered;
6202
6203 return S_OK;
6204}
6205
6206/**
6207 * Decreases the number of objects dependent on the machine state.
6208 * Must always complete the #addStateDependency() call after the state
6209 * dependency is no more necessary.
6210 */
6211void Machine::releaseStateDependency()
6212{
6213 AutoCaller autoCaller(this);
6214 AssertComRCReturnVoid(autoCaller.rc());
6215
6216 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6217
6218 /* releaseStateDependency() w/o addStateDependency()? */
6219 AssertReturnVoid(mData->mMachineStateDeps != 0);
6220 -- mData->mMachineStateDeps;
6221
6222 if (mData->mMachineStateDeps == 0)
6223 {
6224 /* inform ensureNoStateDependencies() that there are no more deps */
6225 if (mData->mMachineStateChangePending != 0)
6226 {
6227 Assert(mData->mMachineStateDepsSem != NIL_RTSEMEVENTMULTI);
6228 RTSemEventMultiSignal (mData->mMachineStateDepsSem);
6229 }
6230 }
6231}
6232
6233// protected methods
6234/////////////////////////////////////////////////////////////////////////////
6235
6236/**
6237 * Performs machine state checks based on the @a aDepType value. If a check
6238 * fails, this method will set extended error info, otherwise it will return
6239 * S_OK. It is supposed, that on failure, the caller will immedieately return
6240 * the return value of this method to the upper level.
6241 *
6242 * When @a aDepType is AnyStateDep, this method always returns S_OK.
6243 *
6244 * When @a aDepType is MutableStateDep, this method returns S_OK only if the
6245 * current state of this machine object allows to change settings of the
6246 * machine (i.e. the machine is not registered, or registered but not running
6247 * and not saved). It is useful to call this method from Machine setters
6248 * before performing any change.
6249 *
6250 * When @a aDepType is MutableOrSavedStateDep, this method behaves the same
6251 * as for MutableStateDep except that if the machine is saved, S_OK is also
6252 * returned. This is useful in setters which allow changing machine
6253 * properties when it is in the saved state.
6254 *
6255 * @param aDepType Dependency type to check.
6256 *
6257 * @note Non Machine based classes should use #addStateDependency() and
6258 * #releaseStateDependency() methods or the smart AutoStateDependency
6259 * template.
6260 *
6261 * @note This method must be called from under this object's read or write
6262 * lock.
6263 */
6264HRESULT Machine::checkStateDependency(StateDependency aDepType)
6265{
6266 switch (aDepType)
6267 {
6268 case AnyStateDep:
6269 {
6270 break;
6271 }
6272 case MutableStateDep:
6273 {
6274 if ( mData->mRegistered
6275 && ( !isSessionMachine() /** @todo This was just convered raw; Check if Running and Paused should actually be included here... (Live Migration) */
6276 || ( mData->mMachineState != MachineState_Paused
6277 && mData->mMachineState != MachineState_Running
6278 && mData->mMachineState != MachineState_Aborted
6279 && mData->mMachineState != MachineState_Teleported
6280 && mData->mMachineState != MachineState_PoweredOff
6281 )
6282 )
6283 )
6284 return setError(VBOX_E_INVALID_VM_STATE,
6285 tr("The machine is not mutable (state is %s)"),
6286 Global::stringifyMachineState(mData->mMachineState));
6287 break;
6288 }
6289 case MutableOrSavedStateDep:
6290 {
6291 if ( mData->mRegistered
6292 && ( !isSessionMachine() /** @todo This was just convered raw; Check if Running and Paused should actually be included here... (Live Migration) */
6293 || ( mData->mMachineState != MachineState_Paused
6294 && mData->mMachineState != MachineState_Running
6295 && mData->mMachineState != MachineState_Aborted
6296 && mData->mMachineState != MachineState_Teleported
6297 && mData->mMachineState != MachineState_Saved
6298 && mData->mMachineState != MachineState_PoweredOff
6299 )
6300 )
6301 )
6302 return setError(VBOX_E_INVALID_VM_STATE,
6303 tr("The machine is not mutable (state is %s)"),
6304 Global::stringifyMachineState(mData->mMachineState));
6305 break;
6306 }
6307 }
6308
6309 return S_OK;
6310}
6311
6312/**
6313 * Helper to initialize all associated child objects and allocate data
6314 * structures.
6315 *
6316 * This method must be called as a part of the object's initialization procedure
6317 * (usually done in the #init() method).
6318 *
6319 * @note Must be called only from #init() or from #registeredInit().
6320 */
6321HRESULT Machine::initDataAndChildObjects()
6322{
6323 AutoCaller autoCaller(this);
6324 AssertComRCReturnRC(autoCaller.rc());
6325 AssertComRCReturn(autoCaller.state() == InInit ||
6326 autoCaller.state() == Limited, E_FAIL);
6327
6328 AssertReturn(!mData->mAccessible, E_FAIL);
6329
6330 /* allocate data structures */
6331 mSSData.allocate();
6332 mUserData.allocate();
6333 mHWData.allocate();
6334 mMediaData.allocate();
6335 mStorageControllers.allocate();
6336
6337 /* initialize mOSTypeId */
6338 mUserData->mOSTypeId = mParent->getUnknownOSType()->id();
6339
6340 /* create associated BIOS settings object */
6341 unconst(mBIOSSettings).createObject();
6342 mBIOSSettings->init(this);
6343
6344#ifdef VBOX_WITH_VRDP
6345 /* create an associated VRDPServer object (default is disabled) */
6346 unconst(mVRDPServer).createObject();
6347 mVRDPServer->init(this);
6348#endif
6349
6350 /* create associated serial port objects */
6351 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6352 {
6353 unconst(mSerialPorts[slot]).createObject();
6354 mSerialPorts[slot]->init(this, slot);
6355 }
6356
6357 /* create associated parallel port objects */
6358 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
6359 {
6360 unconst(mParallelPorts[slot]).createObject();
6361 mParallelPorts[slot]->init(this, slot);
6362 }
6363
6364 /* create the audio adapter object (always present, default is disabled) */
6365 unconst(mAudioAdapter).createObject();
6366 mAudioAdapter->init(this);
6367
6368 /* create the USB controller object (always present, default is disabled) */
6369 unconst(mUSBController).createObject();
6370 mUSBController->init(this);
6371
6372 /* create associated network adapter objects */
6373 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot ++)
6374 {
6375 unconst(mNetworkAdapters[slot]).createObject();
6376 mNetworkAdapters[slot]->init(this, slot);
6377 }
6378
6379 return S_OK;
6380}
6381
6382/**
6383 * Helper to uninitialize all associated child objects and to free all data
6384 * structures.
6385 *
6386 * This method must be called as a part of the object's uninitialization
6387 * procedure (usually done in the #uninit() method).
6388 *
6389 * @note Must be called only from #uninit() or from #registeredInit().
6390 */
6391void Machine::uninitDataAndChildObjects()
6392{
6393 AutoCaller autoCaller(this);
6394 AssertComRCReturnVoid(autoCaller.rc());
6395 AssertComRCReturnVoid( autoCaller.state() == InUninit
6396 || autoCaller.state() == Limited);
6397
6398 /* uninit all children using addDependentChild()/removeDependentChild()
6399 * in their init()/uninit() methods */
6400 uninitDependentChildren();
6401
6402 /* tell all our other child objects we've been uninitialized */
6403
6404 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
6405 {
6406 if (mNetworkAdapters[slot])
6407 {
6408 mNetworkAdapters[slot]->uninit();
6409 unconst(mNetworkAdapters[slot]).setNull();
6410 }
6411 }
6412
6413 if (mUSBController)
6414 {
6415 mUSBController->uninit();
6416 unconst(mUSBController).setNull();
6417 }
6418
6419 if (mAudioAdapter)
6420 {
6421 mAudioAdapter->uninit();
6422 unconst(mAudioAdapter).setNull();
6423 }
6424
6425 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
6426 {
6427 if (mParallelPorts[slot])
6428 {
6429 mParallelPorts[slot]->uninit();
6430 unconst(mParallelPorts[slot]).setNull();
6431 }
6432 }
6433
6434 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
6435 {
6436 if (mSerialPorts[slot])
6437 {
6438 mSerialPorts[slot]->uninit();
6439 unconst(mSerialPorts[slot]).setNull();
6440 }
6441 }
6442
6443#ifdef VBOX_WITH_VRDP
6444 if (mVRDPServer)
6445 {
6446 mVRDPServer->uninit();
6447 unconst(mVRDPServer).setNull();
6448 }
6449#endif
6450
6451 if (mBIOSSettings)
6452 {
6453 mBIOSSettings->uninit();
6454 unconst(mBIOSSettings).setNull();
6455 }
6456
6457 /* Deassociate hard disks (only when a real Machine or a SnapshotMachine
6458 * instance is uninitialized; SessionMachine instances refer to real
6459 * Machine hard disks). This is necessary for a clean re-initialization of
6460 * the VM after successfully re-checking the accessibility state. Note
6461 * that in case of normal Machine or SnapshotMachine uninitialization (as
6462 * a result of unregistering or deleting the snapshot), outdated hard
6463 * disk attachments will already be uninitialized and deleted, so this
6464 * code will not affect them. */
6465 if ( !!mMediaData
6466 && (!isSessionMachine())
6467 )
6468 {
6469 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
6470 it != mMediaData->mAttachments.end();
6471 ++it)
6472 {
6473 ComObjPtr<Medium> hd = (*it)->getMedium();
6474 if (hd.isNull())
6475 continue;
6476 HRESULT rc = hd->removeBackReference(mData->mUuid, getSnapshotId());
6477 AssertComRC(rc);
6478 }
6479 }
6480
6481 if (!isSessionMachine() && !isSnapshotMachine())
6482 {
6483 // clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
6484 if (mData->mFirstSnapshot)
6485 {
6486 // snapshots tree is protected by media write lock; strictly
6487 // this isn't necessary here since we're deleting the entire
6488 // machine, but otherwise we assert in Snapshot::uninit()
6489 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6490 mData->mFirstSnapshot->uninit();
6491 mData->mFirstSnapshot.setNull();
6492 }
6493
6494 mData->mCurrentSnapshot.setNull();
6495 }
6496
6497 /* free data structures (the essential mData structure is not freed here
6498 * since it may be still in use) */
6499 mMediaData.free();
6500 mStorageControllers.free();
6501 mHWData.free();
6502 mUserData.free();
6503 mSSData.free();
6504}
6505
6506/**
6507 * Returns a pointer to the Machine object for this machine that acts like a
6508 * parent for complex machine data objects such as shared folders, etc.
6509 *
6510 * For primary Machine objects and for SnapshotMachine objects, returns this
6511 * object's pointer itself. For SessoinMachine objects, returns the peer
6512 * (primary) machine pointer.
6513 */
6514Machine* Machine::getMachine()
6515{
6516 if (isSessionMachine())
6517 return (Machine*)mPeer;
6518 return this;
6519}
6520
6521/**
6522 * Makes sure that there are no machine state dependants. If necessary, waits
6523 * for the number of dependants to drop to zero.
6524 *
6525 * Make sure this method is called from under this object's write lock to
6526 * guarantee that no new dependants may be added when this method returns
6527 * control to the caller.
6528 *
6529 * @note Locks this object for writing. The lock will be released while waiting
6530 * (if necessary).
6531 *
6532 * @warning To be used only in methods that change the machine state!
6533 */
6534void Machine::ensureNoStateDependencies()
6535{
6536 AssertReturnVoid(isWriteLockOnCurrentThread());
6537
6538 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6539
6540 /* Wait for all state dependants if necessary */
6541 if (mData->mMachineStateDeps != 0)
6542 {
6543 /* lazy semaphore creation */
6544 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
6545 RTSemEventMultiCreate(&mData->mMachineStateDepsSem);
6546
6547 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
6548 mData->mMachineStateDeps));
6549
6550 ++mData->mMachineStateChangePending;
6551
6552 /* reset the semaphore before waiting, the last dependant will signal
6553 * it */
6554 RTSemEventMultiReset(mData->mMachineStateDepsSem);
6555
6556 alock.leave();
6557
6558 RTSemEventMultiWait(mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
6559
6560 alock.enter();
6561
6562 -- mData->mMachineStateChangePending;
6563 }
6564}
6565
6566/**
6567 * Changes the machine state and informs callbacks.
6568 *
6569 * This method is not intended to fail so it either returns S_OK or asserts (and
6570 * returns a failure).
6571 *
6572 * @note Locks this object for writing.
6573 */
6574HRESULT Machine::setMachineState(MachineState_T aMachineState)
6575{
6576 LogFlowThisFuncEnter();
6577 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
6578
6579 AutoCaller autoCaller(this);
6580 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
6581
6582 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6583
6584 /* wait for state dependants to drop to zero */
6585 ensureNoStateDependencies();
6586
6587 if (mData->mMachineState != aMachineState)
6588 {
6589 mData->mMachineState = aMachineState;
6590
6591 RTTimeNow(&mData->mLastStateChange);
6592
6593 mParent->onMachineStateChange(mData->mUuid, aMachineState);
6594 }
6595
6596 LogFlowThisFuncLeave();
6597 return S_OK;
6598}
6599
6600/**
6601 * Searches for a shared folder with the given logical name
6602 * in the collection of shared folders.
6603 *
6604 * @param aName logical name of the shared folder
6605 * @param aSharedFolder where to return the found object
6606 * @param aSetError whether to set the error info if the folder is
6607 * not found
6608 * @return
6609 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
6610 *
6611 * @note
6612 * must be called from under the object's lock!
6613 */
6614HRESULT Machine::findSharedFolder(CBSTR aName,
6615 ComObjPtr<SharedFolder> &aSharedFolder,
6616 bool aSetError /* = false */)
6617{
6618 bool found = false;
6619 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
6620 !found && it != mHWData->mSharedFolders.end();
6621 ++it)
6622 {
6623 AutoWriteLock alock(*it COMMA_LOCKVAL_SRC_POS);
6624 found = (*it)->getName() == aName;
6625 if (found)
6626 aSharedFolder = *it;
6627 }
6628
6629 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
6630
6631 if (aSetError && !found)
6632 setError(rc, tr("Could not find a shared folder named '%ls'"), aName);
6633
6634 return rc;
6635}
6636
6637/**
6638 * Initializes all machine instance data from the given settings structures
6639 * from XML. The exception is the machine UUID which needs special handling
6640 * depending on the caller's use case, so the caller needs to set that herself.
6641 *
6642 * @param config
6643 * @param fAllowStorage
6644 */
6645HRESULT Machine::loadMachineDataFromSettings(const settings::MachineConfigFile &config)
6646{
6647 /* name (required) */
6648 mUserData->mName = config.strName;
6649
6650 /* nameSync (optional, default is true) */
6651 mUserData->mNameSync = config.fNameSync;
6652
6653 mUserData->mDescription = config.strDescription;
6654
6655 // guest OS type
6656 mUserData->mOSTypeId = config.strOsType;
6657 /* look up the object by Id to check it is valid */
6658 ComPtr<IGuestOSType> guestOSType;
6659 HRESULT rc = mParent->GetGuestOSType(mUserData->mOSTypeId,
6660 guestOSType.asOutParam());
6661 if (FAILED(rc)) return rc;
6662
6663 // stateFile (optional)
6664 if (config.strStateFile.isEmpty())
6665 mSSData->mStateFilePath.setNull();
6666 else
6667 {
6668 Utf8Str stateFilePathFull(config.strStateFile);
6669 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
6670 if (RT_FAILURE(vrc))
6671 return setError(E_FAIL,
6672 tr("Invalid saved state file path '%s' (%Rrc)"),
6673 config.strStateFile.raw(),
6674 vrc);
6675 mSSData->mStateFilePath = stateFilePathFull;
6676 }
6677
6678 /* snapshotFolder (optional) */
6679 rc = COMSETTER(SnapshotFolder)(Bstr(config.strSnapshotFolder));
6680 if (FAILED(rc)) return rc;
6681
6682 /* currentStateModified (optional, default is true) */
6683 mData->mCurrentStateModified = config.fCurrentStateModified;
6684
6685 mData->mLastStateChange = config.timeLastStateChange;
6686
6687 /* teleportation */
6688 mUserData->mTeleporterEnabled = config.fTeleporterEnabled;
6689 mUserData->mTeleporterPort = config.uTeleporterPort;
6690 mUserData->mTeleporterAddress = config.strTeleporterAddress;
6691 mUserData->mTeleporterPassword = config.strTeleporterPassword;
6692
6693 /* RTC */
6694 mUserData->mRTCUseUTC = config.fRTCUseUTC;
6695
6696 /*
6697 * note: all mUserData members must be assigned prior this point because
6698 * we need to commit changes in order to let mUserData be shared by all
6699 * snapshot machine instances.
6700 */
6701 mUserData.commitCopy();
6702
6703 /* Snapshot node (optional) */
6704 size_t cRootSnapshots;
6705 if ((cRootSnapshots = config.llFirstSnapshot.size()))
6706 {
6707 // there must be only one root snapshot
6708 Assert(cRootSnapshots == 1);
6709
6710 const settings::Snapshot &snap = config.llFirstSnapshot.front();
6711
6712 rc = loadSnapshot(snap,
6713 config.uuidCurrentSnapshot,
6714 NULL); // no parent == first snapshot
6715 if (FAILED(rc)) return rc;
6716 }
6717
6718 /* Hardware node (required) */
6719 rc = loadHardware(config.hardwareMachine);
6720 if (FAILED(rc)) return rc;
6721
6722 /* Load storage controllers */
6723 rc = loadStorageControllers(config.storageMachine);
6724 if (FAILED(rc)) return rc;
6725
6726 /*
6727 * NOTE: the assignment below must be the last thing to do,
6728 * otherwise it will be not possible to change the settings
6729 * somewehere in the code above because all setters will be
6730 * blocked by checkStateDependency(MutableStateDep).
6731 */
6732
6733 /* set the machine state to Aborted or Saved when appropriate */
6734 if (config.fAborted)
6735 {
6736 Assert(!mSSData->mStateFilePath.isEmpty());
6737 mSSData->mStateFilePath.setNull();
6738
6739 /* no need to use setMachineState() during init() */
6740 mData->mMachineState = MachineState_Aborted;
6741 }
6742 else if (!mSSData->mStateFilePath.isEmpty())
6743 {
6744 /* no need to use setMachineState() during init() */
6745 mData->mMachineState = MachineState_Saved;
6746 }
6747
6748 // after loading settings, we are no longer different from the XML on disk
6749 mData->flModifications = 0;
6750
6751 return S_OK;
6752}
6753
6754/**
6755 * Recursively loads all snapshots starting from the given.
6756 *
6757 * @param aNode <Snapshot> node.
6758 * @param aCurSnapshotId Current snapshot ID from the settings file.
6759 * @param aParentSnapshot Parent snapshot.
6760 */
6761HRESULT Machine::loadSnapshot(const settings::Snapshot &data,
6762 const Guid &aCurSnapshotId,
6763 Snapshot *aParentSnapshot)
6764{
6765 AssertReturn(!isSnapshotMachine(), E_FAIL);
6766 AssertReturn(!isSessionMachine(), E_FAIL);
6767
6768 HRESULT rc = S_OK;
6769
6770 Utf8Str strStateFile;
6771 if (!data.strStateFile.isEmpty())
6772 {
6773 /* optional */
6774 strStateFile = data.strStateFile;
6775 int vrc = calculateFullPath(strStateFile, strStateFile);
6776 if (RT_FAILURE(vrc))
6777 return setError(E_FAIL,
6778 tr("Invalid saved state file path '%s' (%Rrc)"),
6779 strStateFile.raw(),
6780 vrc);
6781 }
6782
6783 /* create a snapshot machine object */
6784 ComObjPtr<SnapshotMachine> pSnapshotMachine;
6785 pSnapshotMachine.createObject();
6786 rc = pSnapshotMachine->init(this,
6787 data.hardware,
6788 data.storage,
6789 data.uuid,
6790 strStateFile);
6791 if (FAILED(rc)) return rc;
6792
6793 /* create a snapshot object */
6794 ComObjPtr<Snapshot> pSnapshot;
6795 pSnapshot.createObject();
6796 /* initialize the snapshot */
6797 rc = pSnapshot->init(mParent, // VirtualBox object
6798 data.uuid,
6799 data.strName,
6800 data.strDescription,
6801 data.timestamp,
6802 pSnapshotMachine,
6803 aParentSnapshot);
6804 if (FAILED(rc)) return rc;
6805
6806 /* memorize the first snapshot if necessary */
6807 if (!mData->mFirstSnapshot)
6808 mData->mFirstSnapshot = pSnapshot;
6809
6810 /* memorize the current snapshot when appropriate */
6811 if ( !mData->mCurrentSnapshot
6812 && pSnapshot->getId() == aCurSnapshotId
6813 )
6814 mData->mCurrentSnapshot = pSnapshot;
6815
6816 // now create the children
6817 for (settings::SnapshotsList::const_iterator it = data.llChildSnapshots.begin();
6818 it != data.llChildSnapshots.end();
6819 ++it)
6820 {
6821 const settings::Snapshot &childData = *it;
6822 // recurse
6823 rc = loadSnapshot(childData,
6824 aCurSnapshotId,
6825 pSnapshot); // parent = the one we created above
6826 if (FAILED(rc)) return rc;
6827 }
6828
6829 return rc;
6830}
6831
6832/**
6833 * @param aNode <Hardware> node.
6834 */
6835HRESULT Machine::loadHardware(const settings::Hardware &data)
6836{
6837 AssertReturn(!isSessionMachine(), E_FAIL);
6838
6839 HRESULT rc = S_OK;
6840
6841 try
6842 {
6843 /* The hardware version attribute (optional). */
6844 mHWData->mHWVersion = data.strVersion;
6845 mHWData->mHardwareUUID = data.uuid;
6846
6847 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
6848 mHWData->mHWVirtExExclusive = data.fHardwareVirtExclusive;
6849 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
6850 mHWData->mHWVirtExLargePagesEnabled = data.fLargePages;
6851 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
6852 mHWData->mPAEEnabled = data.fPAE;
6853 mHWData->mSyntheticCpu = data.fSyntheticCpu;
6854
6855 mHWData->mCPUCount = data.cCPUs;
6856 mHWData->mCPUHotPlugEnabled = data.fCpuHotPlug;
6857
6858 // cpu
6859 if (mHWData->mCPUHotPlugEnabled)
6860 {
6861 for (settings::CpuList::const_iterator it = data.llCpus.begin();
6862 it != data.llCpus.end();
6863 ++it)
6864 {
6865 const settings::Cpu &cpu = *it;
6866
6867 mHWData->mCPUAttached[cpu.ulId] = true;
6868 }
6869 }
6870
6871 // cpuid leafs
6872 for (settings::CpuIdLeafsList::const_iterator it = data.llCpuIdLeafs.begin();
6873 it != data.llCpuIdLeafs.end();
6874 ++it)
6875 {
6876 const settings::CpuIdLeaf &leaf = *it;
6877
6878 switch (leaf.ulId)
6879 {
6880 case 0x0:
6881 case 0x1:
6882 case 0x2:
6883 case 0x3:
6884 case 0x4:
6885 case 0x5:
6886 case 0x6:
6887 case 0x7:
6888 case 0x8:
6889 case 0x9:
6890 case 0xA:
6891 mHWData->mCpuIdStdLeafs[leaf.ulId] = leaf;
6892 break;
6893
6894 case 0x80000000:
6895 case 0x80000001:
6896 case 0x80000002:
6897 case 0x80000003:
6898 case 0x80000004:
6899 case 0x80000005:
6900 case 0x80000006:
6901 case 0x80000007:
6902 case 0x80000008:
6903 case 0x80000009:
6904 case 0x8000000A:
6905 mHWData->mCpuIdExtLeafs[leaf.ulId - 0x80000000] = leaf;
6906 break;
6907
6908 default:
6909 /* just ignore */
6910 break;
6911 }
6912 }
6913
6914 mHWData->mMemorySize = data.ulMemorySizeMB;
6915 mHWData->mPageFusionEnabled = data.fPageFusionEnabled;
6916
6917 // boot order
6918 for (size_t i = 0;
6919 i < RT_ELEMENTS(mHWData->mBootOrder);
6920 i++)
6921 {
6922 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
6923 if (it == data.mapBootOrder.end())
6924 mHWData->mBootOrder[i] = DeviceType_Null;
6925 else
6926 mHWData->mBootOrder[i] = it->second;
6927 }
6928
6929 mHWData->mVRAMSize = data.ulVRAMSizeMB;
6930 mHWData->mMonitorCount = data.cMonitors;
6931 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
6932 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
6933 mHWData->mFirmwareType = data.firmwareType;
6934 mHWData->mPointingHidType = data.pointingHidType;
6935 mHWData->mKeyboardHidType = data.keyboardHidType;
6936 mHWData->mHpetEnabled = data.fHpetEnabled;
6937
6938#ifdef VBOX_WITH_VRDP
6939 /* RemoteDisplay */
6940 rc = mVRDPServer->loadSettings(data.vrdpSettings);
6941 if (FAILED(rc)) return rc;
6942#endif
6943
6944 /* BIOS */
6945 rc = mBIOSSettings->loadSettings(data.biosSettings);
6946 if (FAILED(rc)) return rc;
6947
6948 /* USB Controller */
6949 rc = mUSBController->loadSettings(data.usbController);
6950 if (FAILED(rc)) return rc;
6951
6952 // network adapters
6953 for (settings::NetworkAdaptersList::const_iterator it = data.llNetworkAdapters.begin();
6954 it != data.llNetworkAdapters.end();
6955 ++it)
6956 {
6957 const settings::NetworkAdapter &nic = *it;
6958
6959 /* slot unicity is guaranteed by XML Schema */
6960 AssertBreak(nic.ulSlot < RT_ELEMENTS(mNetworkAdapters));
6961 rc = mNetworkAdapters[nic.ulSlot]->loadSettings(nic);
6962 if (FAILED(rc)) return rc;
6963 }
6964
6965 // serial ports
6966 for (settings::SerialPortsList::const_iterator it = data.llSerialPorts.begin();
6967 it != data.llSerialPorts.end();
6968 ++it)
6969 {
6970 const settings::SerialPort &s = *it;
6971
6972 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
6973 rc = mSerialPorts[s.ulSlot]->loadSettings(s);
6974 if (FAILED(rc)) return rc;
6975 }
6976
6977 // parallel ports (optional)
6978 for (settings::ParallelPortsList::const_iterator it = data.llParallelPorts.begin();
6979 it != data.llParallelPorts.end();
6980 ++it)
6981 {
6982 const settings::ParallelPort &p = *it;
6983
6984 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
6985 rc = mParallelPorts[p.ulSlot]->loadSettings(p);
6986 if (FAILED(rc)) return rc;
6987 }
6988
6989 /* AudioAdapter */
6990 rc = mAudioAdapter->loadSettings(data.audioAdapter);
6991 if (FAILED(rc)) return rc;
6992
6993 for (settings::SharedFoldersList::const_iterator it = data.llSharedFolders.begin();
6994 it != data.llSharedFolders.end();
6995 ++it)
6996 {
6997 const settings::SharedFolder &sf = *it;
6998 rc = CreateSharedFolder(Bstr(sf.strName), Bstr(sf.strHostPath), sf.fWritable, sf.fAutoMount);
6999 if (FAILED(rc)) return rc;
7000 }
7001
7002 // Clipboard
7003 mHWData->mClipboardMode = data.clipboardMode;
7004
7005 // guest settings
7006 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
7007
7008 // IO settings
7009 mHWData->mIoCacheEnabled = data.ioSettings.fIoCacheEnabled;
7010 mHWData->mIoCacheSize = data.ioSettings.ulIoCacheSize;
7011 mHWData->mIoBandwidthMax = data.ioSettings.ulIoBandwidthMax;
7012
7013#ifdef VBOX_WITH_GUEST_PROPS
7014 /* Guest properties (optional) */
7015 for (settings::GuestPropertiesList::const_iterator it = data.llGuestProperties.begin();
7016 it != data.llGuestProperties.end();
7017 ++it)
7018 {
7019 const settings::GuestProperty &prop = *it;
7020 uint32_t fFlags = guestProp::NILFLAG;
7021 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
7022 HWData::GuestProperty property = { prop.strName, prop.strValue, prop.timestamp, fFlags };
7023 mHWData->mGuestProperties.push_back(property);
7024 }
7025
7026 mHWData->mGuestPropertyNotificationPatterns = data.strNotificationPatterns;
7027#endif /* VBOX_WITH_GUEST_PROPS defined */
7028 }
7029 catch(std::bad_alloc &)
7030 {
7031 return E_OUTOFMEMORY;
7032 }
7033
7034 AssertComRC(rc);
7035 return rc;
7036}
7037
7038 /**
7039 * @param aNode <StorageControllers> node.
7040 */
7041HRESULT Machine::loadStorageControllers(const settings::Storage &data,
7042 const Guid *aSnapshotId /* = NULL */)
7043{
7044 AssertReturn(!isSessionMachine(), E_FAIL);
7045
7046 HRESULT rc = S_OK;
7047
7048 for (settings::StorageControllersList::const_iterator it = data.llStorageControllers.begin();
7049 it != data.llStorageControllers.end();
7050 ++it)
7051 {
7052 const settings::StorageController &ctlData = *it;
7053
7054 ComObjPtr<StorageController> pCtl;
7055 /* Try to find one with the name first. */
7056 rc = getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
7057 if (SUCCEEDED(rc))
7058 return setError(VBOX_E_OBJECT_IN_USE,
7059 tr("Storage controller named '%s' already exists"),
7060 ctlData.strName.raw());
7061
7062 pCtl.createObject();
7063 rc = pCtl->init(this,
7064 ctlData.strName,
7065 ctlData.storageBus,
7066 ctlData.ulInstance);
7067 if (FAILED(rc)) return rc;
7068
7069 mStorageControllers->push_back(pCtl);
7070
7071 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
7072 if (FAILED(rc)) return rc;
7073
7074 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
7075 if (FAILED(rc)) return rc;
7076
7077 rc = pCtl->COMSETTER(UseHostIOCache)(ctlData.fUseHostIOCache);
7078 if (FAILED(rc)) return rc;
7079
7080 /* Set IDE emulation settings (only for AHCI controller). */
7081 if (ctlData.controllerType == StorageControllerType_IntelAhci)
7082 {
7083 if ( (FAILED(rc = pCtl->SetIDEEmulationPort(0, ctlData.lIDE0MasterEmulationPort)))
7084 || (FAILED(rc = pCtl->SetIDEEmulationPort(1, ctlData.lIDE0SlaveEmulationPort)))
7085 || (FAILED(rc = pCtl->SetIDEEmulationPort(2, ctlData.lIDE1MasterEmulationPort)))
7086 || (FAILED(rc = pCtl->SetIDEEmulationPort(3, ctlData.lIDE1SlaveEmulationPort)))
7087 )
7088 return rc;
7089 }
7090
7091 /* Load the attached devices now. */
7092 rc = loadStorageDevices(pCtl,
7093 ctlData,
7094 aSnapshotId);
7095 if (FAILED(rc)) return rc;
7096 }
7097
7098 return S_OK;
7099}
7100
7101/**
7102 * @param aNode <HardDiskAttachments> node.
7103 * @param fAllowStorage if false, we produce an error if the config requests media attachments
7104 * (used with importing unregistered machines which cannot have media attachments)
7105 * @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
7106 *
7107 * @note Lock mParent for reading and hard disks for writing before calling.
7108 */
7109HRESULT Machine::loadStorageDevices(StorageController *aStorageController,
7110 const settings::StorageController &data,
7111 const Guid *aSnapshotId /*= NULL*/)
7112{
7113 HRESULT rc = S_OK;
7114
7115 /* paranoia: detect duplicate attachments */
7116 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7117 it != data.llAttachedDevices.end();
7118 ++it)
7119 {
7120 for (settings::AttachedDevicesList::const_iterator it2 = it;
7121 it2 != data.llAttachedDevices.end();
7122 ++it2)
7123 {
7124 if (it == it2)
7125 continue;
7126
7127 if ( (*it).lPort == (*it2).lPort
7128 && (*it).lDevice == (*it2).lDevice)
7129 {
7130 return setError(E_FAIL,
7131 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%ls'"),
7132 aStorageController->getName().raw(), (*it).lPort, (*it).lDevice, mUserData->mName.raw());
7133 }
7134 }
7135 }
7136
7137 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
7138 it != data.llAttachedDevices.end();
7139 ++it)
7140 {
7141 const settings::AttachedDevice &dev = *it;
7142 ComObjPtr<Medium> medium;
7143
7144 switch (dev.deviceType)
7145 {
7146 case DeviceType_Floppy:
7147 /* find a floppy by UUID */
7148 if (!dev.uuid.isEmpty())
7149 rc = mParent->findDVDOrFloppyImage(DeviceType_Floppy, &dev.uuid, Utf8Str::Empty, true /* aDoSetError */, &medium);
7150 /* find a floppy by host device name */
7151 else if (!dev.strHostDriveSrc.isEmpty())
7152 {
7153 SafeIfaceArray<IMedium> drivevec;
7154 rc = mParent->host()->COMGETTER(FloppyDrives)(ComSafeArrayAsOutParam(drivevec));
7155 if (SUCCEEDED(rc))
7156 {
7157 for (size_t i = 0; i < drivevec.size(); ++i)
7158 {
7159 /// @todo eliminate this conversion
7160 ComObjPtr<Medium> med = (Medium *)drivevec[i];
7161 if ( dev.strHostDriveSrc == med->getName()
7162 || dev.strHostDriveSrc == med->getLocation())
7163 {
7164 medium = med;
7165 break;
7166 }
7167 }
7168 }
7169 }
7170 break;
7171
7172 case DeviceType_DVD:
7173 /* find a DVD by UUID */
7174 if (!dev.uuid.isEmpty())
7175 rc = mParent->findDVDOrFloppyImage(DeviceType_DVD, &dev.uuid, Utf8Str::Empty, true /* aDoSetError */, &medium);
7176 /* find a DVD by host device name */
7177 else if (!dev.strHostDriveSrc.isEmpty())
7178 {
7179 SafeIfaceArray<IMedium> drivevec;
7180 rc = mParent->host()->COMGETTER(DVDDrives)(ComSafeArrayAsOutParam(drivevec));
7181 if (SUCCEEDED(rc))
7182 {
7183 for (size_t i = 0; i < drivevec.size(); ++i)
7184 {
7185 Bstr hostDriveSrc(dev.strHostDriveSrc);
7186 /// @todo eliminate this conversion
7187 ComObjPtr<Medium> med = (Medium *)drivevec[i];
7188 if ( hostDriveSrc == med->getName()
7189 || hostDriveSrc == med->getLocation())
7190 {
7191 medium = med;
7192 break;
7193 }
7194 }
7195 }
7196 }
7197 break;
7198
7199 case DeviceType_HardDisk:
7200 {
7201 /* find a hard disk by UUID */
7202 rc = mParent->findHardDisk(&dev.uuid, NULL, true /* aDoSetError */, &medium);
7203 if (FAILED(rc))
7204 {
7205 if (isSnapshotMachine())
7206 {
7207 // wrap another error message around the "cannot find hard disk" set by findHardDisk
7208 // so the user knows that the bad disk is in a snapshot somewhere
7209 com::ErrorInfo info;
7210 return setError(E_FAIL,
7211 tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
7212 aSnapshotId->raw(),
7213 info.getText().raw());
7214 }
7215 else
7216 return rc;
7217 }
7218
7219 AutoWriteLock hdLock(medium COMMA_LOCKVAL_SRC_POS);
7220
7221 if (medium->getType() == MediumType_Immutable)
7222 {
7223 if (isSnapshotMachine())
7224 return setError(E_FAIL,
7225 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
7226 "of the virtual machine '%ls' ('%s')"),
7227 medium->getLocationFull().raw(),
7228 dev.uuid.raw(),
7229 aSnapshotId->raw(),
7230 mUserData->mName.raw(),
7231 mData->m_strConfigFileFull.raw());
7232
7233 return setError(E_FAIL,
7234 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%ls' ('%s')"),
7235 medium->getLocationFull().raw(),
7236 dev.uuid.raw(),
7237 mUserData->mName.raw(),
7238 mData->m_strConfigFileFull.raw());
7239 }
7240
7241 if ( !isSnapshotMachine()
7242 && medium->getChildren().size() != 0
7243 )
7244 return setError(E_FAIL,
7245 tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%ls' ('%s') "
7246 "because it has %d differencing child hard disks"),
7247 medium->getLocationFull().raw(),
7248 dev.uuid.raw(),
7249 mUserData->mName.raw(),
7250 mData->m_strConfigFileFull.raw(),
7251 medium->getChildren().size());
7252
7253 if (findAttachment(mMediaData->mAttachments,
7254 medium))
7255 return setError(E_FAIL,
7256 tr("Hard disk '%s' with UUID {%RTuuid} is already attached to the virtual machine '%ls' ('%s')"),
7257 medium->getLocationFull().raw(),
7258 dev.uuid.raw(),
7259 mUserData->mName.raw(),
7260 mData->m_strConfigFileFull.raw());
7261
7262 break;
7263 }
7264
7265 default:
7266 return setError(E_FAIL,
7267 tr("Device with unknown type is attached to the virtual machine '%s' ('%s')"),
7268 medium->getLocationFull().raw(),
7269 mUserData->mName.raw(),
7270 mData->m_strConfigFileFull.raw());
7271 }
7272
7273 if (FAILED(rc))
7274 break;
7275
7276 const Bstr controllerName = aStorageController->getName();
7277 ComObjPtr<MediumAttachment> pAttachment;
7278 pAttachment.createObject();
7279 rc = pAttachment->init(this,
7280 medium,
7281 controllerName,
7282 dev.lPort,
7283 dev.lDevice,
7284 dev.deviceType,
7285 dev.fPassThrough);
7286 if (FAILED(rc)) break;
7287
7288 /* associate the medium with this machine and snapshot */
7289 if (!medium.isNull())
7290 {
7291 if (isSnapshotMachine())
7292 rc = medium->addBackReference(mData->mUuid, *aSnapshotId);
7293 else
7294 rc = medium->addBackReference(mData->mUuid);
7295 }
7296
7297 if (FAILED(rc))
7298 break;
7299
7300 /* back up mMediaData to let registeredInit() properly rollback on failure
7301 * (= limited accessibility) */
7302 setModified(IsModified_Storage);
7303 mMediaData.backup();
7304 mMediaData->mAttachments.push_back(pAttachment);
7305 }
7306
7307 return rc;
7308}
7309
7310/**
7311 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
7312 *
7313 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
7314 * @param aSnapshot where to return the found snapshot
7315 * @param aSetError true to set extended error info on failure
7316 */
7317HRESULT Machine::findSnapshot(const Guid &aId,
7318 ComObjPtr<Snapshot> &aSnapshot,
7319 bool aSetError /* = false */)
7320{
7321 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
7322
7323 if (!mData->mFirstSnapshot)
7324 {
7325 if (aSetError)
7326 return setError(E_FAIL,
7327 tr("This machine does not have any snapshots"));
7328 return E_FAIL;
7329 }
7330
7331 if (aId.isEmpty())
7332 aSnapshot = mData->mFirstSnapshot;
7333 else
7334 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aId);
7335
7336 if (!aSnapshot)
7337 {
7338 if (aSetError)
7339 return setError(E_FAIL,
7340 tr("Could not find a snapshot with UUID {%s}"),
7341 aId.toString().raw());
7342 return E_FAIL;
7343 }
7344
7345 return S_OK;
7346}
7347
7348/**
7349 * Returns the snapshot with the given name or fails of no such snapshot.
7350 *
7351 * @param aName snapshot name to find
7352 * @param aSnapshot where to return the found snapshot
7353 * @param aSetError true to set extended error info on failure
7354 */
7355HRESULT Machine::findSnapshot(IN_BSTR aName,
7356 ComObjPtr<Snapshot> &aSnapshot,
7357 bool aSetError /* = false */)
7358{
7359 AssertReturn(aName, E_INVALIDARG);
7360
7361 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
7362
7363 if (!mData->mFirstSnapshot)
7364 {
7365 if (aSetError)
7366 return setError(VBOX_E_OBJECT_NOT_FOUND,
7367 tr("This machine does not have any snapshots"));
7368 return VBOX_E_OBJECT_NOT_FOUND;
7369 }
7370
7371 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aName);
7372
7373 if (!aSnapshot)
7374 {
7375 if (aSetError)
7376 return setError(VBOX_E_OBJECT_NOT_FOUND,
7377 tr("Could not find a snapshot named '%ls'"), aName);
7378 return VBOX_E_OBJECT_NOT_FOUND;
7379 }
7380
7381 return S_OK;
7382}
7383
7384/**
7385 * Returns a storage controller object with the given name.
7386 *
7387 * @param aName storage controller name to find
7388 * @param aStorageController where to return the found storage controller
7389 * @param aSetError true to set extended error info on failure
7390 */
7391HRESULT Machine::getStorageControllerByName(const Utf8Str &aName,
7392 ComObjPtr<StorageController> &aStorageController,
7393 bool aSetError /* = false */)
7394{
7395 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
7396
7397 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
7398 it != mStorageControllers->end();
7399 ++it)
7400 {
7401 if ((*it)->getName() == aName)
7402 {
7403 aStorageController = (*it);
7404 return S_OK;
7405 }
7406 }
7407
7408 if (aSetError)
7409 return setError(VBOX_E_OBJECT_NOT_FOUND,
7410 tr("Could not find a storage controller named '%s'"),
7411 aName.raw());
7412 return VBOX_E_OBJECT_NOT_FOUND;
7413}
7414
7415HRESULT Machine::getMediumAttachmentsOfController(CBSTR aName,
7416 MediaData::AttachmentList &atts)
7417{
7418 AutoCaller autoCaller(this);
7419 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7420
7421 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7422
7423 for (MediaData::AttachmentList::iterator it = mMediaData->mAttachments.begin();
7424 it != mMediaData->mAttachments.end();
7425 ++it)
7426 {
7427 const ComObjPtr<MediumAttachment> &pAtt = *it;
7428
7429 // should never happen, but deal with NULL pointers in the list.
7430 AssertStmt(!pAtt.isNull(), continue);
7431
7432 // getControllerName() needs caller+read lock
7433 AutoCaller autoAttCaller(pAtt);
7434 if (FAILED(autoAttCaller.rc()))
7435 {
7436 atts.clear();
7437 return autoAttCaller.rc();
7438 }
7439 AutoReadLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
7440
7441 if (pAtt->getControllerName() == aName)
7442 atts.push_back(pAtt);
7443 }
7444
7445 return S_OK;
7446}
7447
7448/**
7449 * Helper for #saveSettings. Cares about renaming the settings directory and
7450 * file if the machine name was changed and about creating a new settings file
7451 * if this is a new machine.
7452 *
7453 * @note Must be never called directly but only from #saveSettings().
7454 */
7455HRESULT Machine::prepareSaveSettings(bool *pfNeedsGlobalSaveSettings)
7456{
7457 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7458
7459 HRESULT rc = S_OK;
7460
7461 bool fSettingsFileIsNew = !mData->pMachineConfigFile->fileExists();
7462
7463 /* attempt to rename the settings file if machine name is changed */
7464 if ( mUserData->mNameSync
7465 && mUserData.isBackedUp()
7466 && mUserData.backedUpData()->mName != mUserData->mName
7467 )
7468 {
7469 bool dirRenamed = false;
7470 bool fileRenamed = false;
7471
7472 Utf8Str configFile, newConfigFile;
7473 Utf8Str configDir, newConfigDir;
7474
7475 do
7476 {
7477 int vrc = VINF_SUCCESS;
7478
7479 Utf8Str name = mUserData.backedUpData()->mName;
7480 Utf8Str newName = mUserData->mName;
7481
7482 configFile = mData->m_strConfigFileFull;
7483
7484 /* first, rename the directory if it matches the machine name */
7485 configDir = configFile;
7486 configDir.stripFilename();
7487 newConfigDir = configDir;
7488 if (!strcmp(RTPathFilename(configDir.c_str()), name.c_str()))
7489 {
7490 newConfigDir.stripFilename();
7491 newConfigDir = Utf8StrFmt("%s%c%s",
7492 newConfigDir.raw(), RTPATH_DELIMITER, newName.raw());
7493 /* new dir and old dir cannot be equal here because of 'if'
7494 * above and because name != newName */
7495 Assert(configDir != newConfigDir);
7496 if (!fSettingsFileIsNew)
7497 {
7498 /* perform real rename only if the machine is not new */
7499 vrc = RTPathRename(configDir.raw(), newConfigDir.raw(), 0);
7500 if (RT_FAILURE(vrc))
7501 {
7502 rc = setError(E_FAIL,
7503 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
7504 configDir.raw(),
7505 newConfigDir.raw(),
7506 vrc);
7507 break;
7508 }
7509 dirRenamed = true;
7510 }
7511 }
7512
7513 newConfigFile = Utf8StrFmt("%s%c%s.xml",
7514 newConfigDir.raw(), RTPATH_DELIMITER, newName.raw());
7515
7516 /* then try to rename the settings file itself */
7517 if (newConfigFile != configFile)
7518 {
7519 /* get the path to old settings file in renamed directory */
7520 configFile = Utf8StrFmt("%s%c%s",
7521 newConfigDir.raw(),
7522 RTPATH_DELIMITER,
7523 RTPathFilename(configFile.c_str()));
7524 if (!fSettingsFileIsNew)
7525 {
7526 /* perform real rename only if the machine is not new */
7527 vrc = RTFileRename(configFile.raw(), newConfigFile.raw(), 0);
7528 if (RT_FAILURE(vrc))
7529 {
7530 rc = setError(E_FAIL,
7531 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
7532 configFile.raw(),
7533 newConfigFile.raw(),
7534 vrc);
7535 break;
7536 }
7537 fileRenamed = true;
7538 }
7539 }
7540
7541 /* update m_strConfigFileFull amd mConfigFile */
7542 mData->m_strConfigFileFull = newConfigFile;
7543 // compute the relative path too
7544 mParent->copyPathRelativeToConfig(newConfigFile, mData->m_strConfigFile);
7545
7546 // store the old and new so that VirtualBox::saveSettings() can update
7547 // the media registry
7548 if ( mData->mRegistered
7549 && configDir != newConfigDir)
7550 {
7551 mParent->rememberMachineNameChangeForMedia(configDir, newConfigDir);
7552
7553 if (pfNeedsGlobalSaveSettings)
7554 *pfNeedsGlobalSaveSettings = true;
7555 }
7556
7557 /* update the snapshot folder */
7558 Utf8Str path = mUserData->mSnapshotFolderFull;
7559 if (RTPathStartsWith(path.c_str(), configDir.c_str()))
7560 {
7561 path = Utf8StrFmt("%s%s", newConfigDir.raw(),
7562 path.raw() + configDir.length());
7563 mUserData->mSnapshotFolderFull = path;
7564 Utf8Str strTemp;
7565 copyPathRelativeToMachine(path, strTemp);
7566 mUserData->mSnapshotFolder = strTemp;
7567 }
7568
7569 /* update the saved state file path */
7570 path = mSSData->mStateFilePath;
7571 if (RTPathStartsWith(path.c_str(), configDir.c_str()))
7572 {
7573 path = Utf8StrFmt("%s%s", newConfigDir.raw(),
7574 path.raw() + configDir.length());
7575 mSSData->mStateFilePath = path;
7576 }
7577
7578 /* Update saved state file paths of all online snapshots.
7579 * Note that saveSettings() will recognize name change
7580 * and will save all snapshots in this case. */
7581 if (mData->mFirstSnapshot)
7582 mData->mFirstSnapshot->updateSavedStatePaths(configDir.c_str(),
7583 newConfigDir.c_str());
7584 }
7585 while (0);
7586
7587 if (FAILED(rc))
7588 {
7589 /* silently try to rename everything back */
7590 if (fileRenamed)
7591 RTFileRename(newConfigFile.raw(), configFile.raw(), 0);
7592 if (dirRenamed)
7593 RTPathRename(newConfigDir.raw(), configDir.raw(), 0);
7594 }
7595
7596 if (FAILED(rc)) return rc;
7597 }
7598
7599 if (fSettingsFileIsNew)
7600 {
7601 /* create a virgin config file */
7602 int vrc = VINF_SUCCESS;
7603
7604 /* ensure the settings directory exists */
7605 Utf8Str path(mData->m_strConfigFileFull);
7606 path.stripFilename();
7607 if (!RTDirExists(path.c_str()))
7608 {
7609 vrc = RTDirCreateFullPath(path.c_str(), 0777);
7610 if (RT_FAILURE(vrc))
7611 {
7612 return setError(E_FAIL,
7613 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
7614 path.raw(),
7615 vrc);
7616 }
7617 }
7618
7619 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
7620 path = Utf8Str(mData->m_strConfigFileFull);
7621 RTFILE f = NIL_RTFILE;
7622 vrc = RTFileOpen(&f, path.c_str(),
7623 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
7624 if (RT_FAILURE(vrc))
7625 return setError(E_FAIL,
7626 tr("Could not create the settings file '%s' (%Rrc)"),
7627 path.raw(),
7628 vrc);
7629 RTFileClose(f);
7630 }
7631
7632 return rc;
7633}
7634
7635/**
7636 * Saves and commits machine data, user data and hardware data.
7637 *
7638 * Note that on failure, the data remains uncommitted.
7639 *
7640 * @a aFlags may combine the following flags:
7641 *
7642 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
7643 * Used when saving settings after an operation that makes them 100%
7644 * correspond to the settings from the current snapshot.
7645 * - SaveS_InformCallbacksAnyway: Callbacks will be informed even if
7646 * #isReallyModified() returns false. This is necessary for cases when we
7647 * change machine data directly, not through the backup()/commit() mechanism.
7648 * - SaveS_Force: settings will be saved without doing a deep compare of the
7649 * settings structures. This is used when this is called because snapshots
7650 * have changed to avoid the overhead of the deep compare.
7651 *
7652 * @note Must be called from under this object's write lock. Locks children for
7653 * writing.
7654 *
7655 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
7656 * initialized to false and that will be set to true by this function if
7657 * the caller must invoke VirtualBox::saveSettings() because the global
7658 * settings have changed. This will happen if a machine rename has been
7659 * saved and the global machine and media registries will therefore need
7660 * updating.
7661 */
7662HRESULT Machine::saveSettings(bool *pfNeedsGlobalSaveSettings,
7663 int aFlags /*= 0*/)
7664{
7665 LogFlowThisFuncEnter();
7666
7667 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7668
7669 /* make sure child objects are unable to modify the settings while we are
7670 * saving them */
7671 ensureNoStateDependencies();
7672
7673 AssertReturn(!isSnapshotMachine(),
7674 E_FAIL);
7675
7676 HRESULT rc = S_OK;
7677 bool fNeedsWrite = false;
7678
7679 /* First, prepare to save settings. It will care about renaming the
7680 * settings directory and file if the machine name was changed and about
7681 * creating a new settings file if this is a new machine. */
7682 rc = prepareSaveSettings(pfNeedsGlobalSaveSettings);
7683 if (FAILED(rc)) return rc;
7684
7685 // keep a pointer to the current settings structures
7686 settings::MachineConfigFile *pOldConfig = mData->pMachineConfigFile;
7687 settings::MachineConfigFile *pNewConfig = NULL;
7688
7689 try
7690 {
7691 // make a fresh one to have everyone write stuff into
7692 pNewConfig = new settings::MachineConfigFile(NULL);
7693 pNewConfig->copyBaseFrom(*mData->pMachineConfigFile);
7694
7695 // now go and copy all the settings data from COM to the settings structures
7696 // (this calles saveSettings() on all the COM objects in the machine)
7697 copyMachineDataToSettings(*pNewConfig);
7698
7699 if (aFlags & SaveS_ResetCurStateModified)
7700 {
7701 // this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
7702 mData->mCurrentStateModified = FALSE;
7703 fNeedsWrite = true; // always, no need to compare
7704 }
7705 else if (aFlags & SaveS_Force)
7706 {
7707 fNeedsWrite = true; // always, no need to compare
7708 }
7709 else
7710 {
7711 if (!mData->mCurrentStateModified)
7712 {
7713 // do a deep compare of the settings that we just saved with the settings
7714 // previously stored in the config file; this invokes MachineConfigFile::operator==
7715 // which does a deep compare of all the settings, which is expensive but less expensive
7716 // than writing out XML in vain
7717 bool fAnySettingsChanged = (*pNewConfig == *pOldConfig);
7718
7719 // could still be modified if any settings changed
7720 mData->mCurrentStateModified = fAnySettingsChanged;
7721
7722 fNeedsWrite = fAnySettingsChanged;
7723 }
7724 else
7725 fNeedsWrite = true;
7726 }
7727
7728 pNewConfig->fCurrentStateModified = !!mData->mCurrentStateModified;
7729
7730 if (fNeedsWrite)
7731 // now spit it all out!
7732 pNewConfig->write(mData->m_strConfigFileFull);
7733
7734 mData->pMachineConfigFile = pNewConfig;
7735 delete pOldConfig;
7736 commit();
7737
7738 // after saving settings, we are no longer different from the XML on disk
7739 mData->flModifications = 0;
7740 }
7741 catch (HRESULT err)
7742 {
7743 // we assume that error info is set by the thrower
7744 rc = err;
7745
7746 // restore old config
7747 delete pNewConfig;
7748 mData->pMachineConfigFile = pOldConfig;
7749 }
7750 catch (...)
7751 {
7752 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
7753 }
7754
7755 if (fNeedsWrite || (aFlags & SaveS_InformCallbacksAnyway))
7756 {
7757 /* Fire the data change event, even on failure (since we've already
7758 * committed all data). This is done only for SessionMachines because
7759 * mutable Machine instances are always not registered (i.e. private
7760 * to the client process that creates them) and thus don't need to
7761 * inform callbacks. */
7762 if (isSessionMachine())
7763 mParent->onMachineDataChange(mData->mUuid);
7764 }
7765
7766 LogFlowThisFunc(("rc=%08X\n", rc));
7767 LogFlowThisFuncLeave();
7768 return rc;
7769}
7770
7771/**
7772 * Implementation for saving the machine settings into the given
7773 * settings::MachineConfigFile instance. This copies machine extradata
7774 * from the previous machine config file in the instance data, if any.
7775 *
7776 * This gets called from two locations:
7777 *
7778 * -- Machine::saveSettings(), during the regular XML writing;
7779 *
7780 * -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
7781 * exported to OVF and we write the VirtualBox proprietary XML
7782 * into a <vbox:Machine> tag.
7783 *
7784 * This routine fills all the fields in there, including snapshots, *except*
7785 * for the following:
7786 *
7787 * -- fCurrentStateModified. There is some special logic associated with that.
7788 *
7789 * The caller can then call MachineConfigFile::write() or do something else
7790 * with it.
7791 *
7792 * Caller must hold the machine lock!
7793 *
7794 * This throws XML errors and HRESULT, so the caller must have a catch block!
7795 */
7796void Machine::copyMachineDataToSettings(settings::MachineConfigFile &config)
7797{
7798 // deep copy extradata
7799 config.mapExtraDataItems = mData->pMachineConfigFile->mapExtraDataItems;
7800
7801 config.uuid = mData->mUuid;
7802 config.strName = mUserData->mName;
7803 config.fNameSync = !!mUserData->mNameSync;
7804 config.strDescription = mUserData->mDescription;
7805 config.strOsType = mUserData->mOSTypeId;
7806
7807 if ( mData->mMachineState == MachineState_Saved
7808 || mData->mMachineState == MachineState_Restoring
7809 // when deleting a snapshot we may or may not have a saved state in the current state,
7810 // so let's not assert here please
7811 || ( ( mData->mMachineState == MachineState_DeletingSnapshot
7812 || mData->mMachineState == MachineState_DeletingSnapshotOnline
7813 || mData->mMachineState == MachineState_DeletingSnapshotPaused)
7814 && (!mSSData->mStateFilePath.isEmpty())
7815 )
7816 )
7817 {
7818 Assert(!mSSData->mStateFilePath.isEmpty());
7819 /* try to make the file name relative to the settings file dir */
7820 copyPathRelativeToMachine(mSSData->mStateFilePath, config.strStateFile);
7821 }
7822 else
7823 {
7824 Assert(mSSData->mStateFilePath.isEmpty());
7825 config.strStateFile.setNull();
7826 }
7827
7828 if (mData->mCurrentSnapshot)
7829 config.uuidCurrentSnapshot = mData->mCurrentSnapshot->getId();
7830 else
7831 config.uuidCurrentSnapshot.clear();
7832
7833 config.strSnapshotFolder = mUserData->mSnapshotFolder;
7834 // config.fCurrentStateModified is special, see below
7835 config.timeLastStateChange = mData->mLastStateChange;
7836 config.fAborted = (mData->mMachineState == MachineState_Aborted);
7837 /// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
7838
7839 config.fTeleporterEnabled = !!mUserData->mTeleporterEnabled;
7840 config.uTeleporterPort = mUserData->mTeleporterPort;
7841 config.strTeleporterAddress = mUserData->mTeleporterAddress;
7842 config.strTeleporterPassword = mUserData->mTeleporterPassword;
7843
7844 config.fRTCUseUTC = !!mUserData->mRTCUseUTC;
7845
7846 HRESULT rc = saveHardware(config.hardwareMachine);
7847 if (FAILED(rc)) throw rc;
7848
7849 rc = saveStorageControllers(config.storageMachine);
7850 if (FAILED(rc)) throw rc;
7851
7852 // save snapshots
7853 rc = saveAllSnapshots(config);
7854 if (FAILED(rc)) throw rc;
7855}
7856
7857/**
7858 * Saves all snapshots of the machine into the given machine config file. Called
7859 * from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
7860 * @param config
7861 * @return
7862 */
7863HRESULT Machine::saveAllSnapshots(settings::MachineConfigFile &config)
7864{
7865 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7866
7867 HRESULT rc = S_OK;
7868
7869 try
7870 {
7871 config.llFirstSnapshot.clear();
7872
7873 if (mData->mFirstSnapshot)
7874 {
7875 settings::Snapshot snapNew;
7876 config.llFirstSnapshot.push_back(snapNew);
7877
7878 // get reference to the fresh copy of the snapshot on the list and
7879 // work on that copy directly to avoid excessive copying later
7880 settings::Snapshot &snap = config.llFirstSnapshot.front();
7881
7882 rc = mData->mFirstSnapshot->saveSnapshot(snap, false /*aAttrsOnly*/);
7883 if (FAILED(rc)) throw rc;
7884 }
7885
7886// if (mType == IsSessionMachine)
7887// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
7888
7889 }
7890 catch (HRESULT err)
7891 {
7892 /* we assume that error info is set by the thrower */
7893 rc = err;
7894 }
7895 catch (...)
7896 {
7897 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
7898 }
7899
7900 return rc;
7901}
7902
7903/**
7904 * Saves the VM hardware configuration. It is assumed that the
7905 * given node is empty.
7906 *
7907 * @param aNode <Hardware> node to save the VM hardware confguration to.
7908 */
7909HRESULT Machine::saveHardware(settings::Hardware &data)
7910{
7911 HRESULT rc = S_OK;
7912
7913 try
7914 {
7915 /* The hardware version attribute (optional).
7916 Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
7917 if ( mHWData->mHWVersion == "1"
7918 && mSSData->mStateFilePath.isEmpty()
7919 )
7920 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. */
7921
7922 data.strVersion = mHWData->mHWVersion;
7923 data.uuid = mHWData->mHardwareUUID;
7924
7925 // CPU
7926 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
7927 data.fHardwareVirtExclusive = !!mHWData->mHWVirtExExclusive;
7928 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
7929 data.fLargePages = !!mHWData->mHWVirtExLargePagesEnabled;
7930 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
7931 data.fPAE = !!mHWData->mPAEEnabled;
7932 data.fSyntheticCpu = !!mHWData->mSyntheticCpu;
7933
7934 /* Standard and Extended CPUID leafs. */
7935 data.llCpuIdLeafs.clear();
7936 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); idx++)
7937 {
7938 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
7939 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
7940 }
7941 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); idx++)
7942 {
7943 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
7944 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
7945 }
7946
7947 data.cCPUs = mHWData->mCPUCount;
7948 data.fCpuHotPlug = !!mHWData->mCPUHotPlugEnabled;
7949
7950 data.llCpus.clear();
7951 if (data.fCpuHotPlug)
7952 {
7953 for (unsigned idx = 0; idx < data.cCPUs; idx++)
7954 {
7955 if (mHWData->mCPUAttached[idx])
7956 {
7957 settings::Cpu cpu;
7958 cpu.ulId = idx;
7959 data.llCpus.push_back(cpu);
7960 }
7961 }
7962 }
7963
7964 // memory
7965 data.ulMemorySizeMB = mHWData->mMemorySize;
7966 data.fPageFusionEnabled = mHWData->mPageFusionEnabled;
7967
7968 // firmware
7969 data.firmwareType = mHWData->mFirmwareType;
7970
7971 // HID
7972 data.pointingHidType = mHWData->mPointingHidType;
7973 data.keyboardHidType = mHWData->mKeyboardHidType;
7974
7975 // HPET
7976 data.fHpetEnabled = !!mHWData->mHpetEnabled;
7977
7978 // boot order
7979 data.mapBootOrder.clear();
7980 for (size_t i = 0;
7981 i < RT_ELEMENTS(mHWData->mBootOrder);
7982 ++i)
7983 data.mapBootOrder[i] = mHWData->mBootOrder[i];
7984
7985 // display
7986 data.ulVRAMSizeMB = mHWData->mVRAMSize;
7987 data.cMonitors = mHWData->mMonitorCount;
7988 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
7989 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
7990
7991#ifdef VBOX_WITH_VRDP
7992 /* VRDP settings (optional) */
7993 rc = mVRDPServer->saveSettings(data.vrdpSettings);
7994 if (FAILED(rc)) throw rc;
7995#endif
7996
7997 /* BIOS (required) */
7998 rc = mBIOSSettings->saveSettings(data.biosSettings);
7999 if (FAILED(rc)) throw rc;
8000
8001 /* USB Controller (required) */
8002 rc = mUSBController->saveSettings(data.usbController);
8003 if (FAILED(rc)) throw rc;
8004
8005 /* Network adapters (required) */
8006 data.llNetworkAdapters.clear();
8007 for (ULONG slot = 0;
8008 slot < RT_ELEMENTS(mNetworkAdapters);
8009 ++slot)
8010 {
8011 settings::NetworkAdapter nic;
8012 nic.ulSlot = slot;
8013 rc = mNetworkAdapters[slot]->saveSettings(nic);
8014 if (FAILED(rc)) throw rc;
8015
8016 data.llNetworkAdapters.push_back(nic);
8017 }
8018
8019 /* Serial ports */
8020 data.llSerialPorts.clear();
8021 for (ULONG slot = 0;
8022 slot < RT_ELEMENTS(mSerialPorts);
8023 ++slot)
8024 {
8025 settings::SerialPort s;
8026 s.ulSlot = slot;
8027 rc = mSerialPorts[slot]->saveSettings(s);
8028 if (FAILED(rc)) return rc;
8029
8030 data.llSerialPorts.push_back(s);
8031 }
8032
8033 /* Parallel ports */
8034 data.llParallelPorts.clear();
8035 for (ULONG slot = 0;
8036 slot < RT_ELEMENTS(mParallelPorts);
8037 ++slot)
8038 {
8039 settings::ParallelPort p;
8040 p.ulSlot = slot;
8041 rc = mParallelPorts[slot]->saveSettings(p);
8042 if (FAILED(rc)) return rc;
8043
8044 data.llParallelPorts.push_back(p);
8045 }
8046
8047 /* Audio adapter */
8048 rc = mAudioAdapter->saveSettings(data.audioAdapter);
8049 if (FAILED(rc)) return rc;
8050
8051 /* Shared folders */
8052 data.llSharedFolders.clear();
8053 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
8054 it != mHWData->mSharedFolders.end();
8055 ++it)
8056 {
8057 ComObjPtr<SharedFolder> pFolder = *it;
8058 settings::SharedFolder sf;
8059 sf.strName = pFolder->getName();
8060 sf.strHostPath = pFolder->getHostPath();
8061 sf.fWritable = !!pFolder->isWritable();
8062 sf.fAutoMount = !!pFolder->isAutoMounted();
8063
8064 data.llSharedFolders.push_back(sf);
8065 }
8066
8067 // clipboard
8068 data.clipboardMode = mHWData->mClipboardMode;
8069
8070 /* Guest */
8071 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
8072
8073 // IO settings
8074 data.ioSettings.fIoCacheEnabled = !!mHWData->mIoCacheEnabled;
8075 data.ioSettings.ulIoCacheSize = mHWData->mIoCacheSize;
8076 data.ioSettings.ulIoBandwidthMax = mHWData->mIoBandwidthMax;
8077
8078 // guest properties
8079 data.llGuestProperties.clear();
8080#ifdef VBOX_WITH_GUEST_PROPS
8081 for (HWData::GuestPropertyList::const_iterator it = mHWData->mGuestProperties.begin();
8082 it != mHWData->mGuestProperties.end();
8083 ++it)
8084 {
8085 HWData::GuestProperty property = *it;
8086
8087 /* Remove transient guest properties at shutdown unless we
8088 * are saving state */
8089 if ( ( mData->mMachineState == MachineState_PoweredOff
8090 || mData->mMachineState == MachineState_Aborted
8091 || mData->mMachineState == MachineState_Teleported)
8092 && property.mFlags & guestProp::TRANSIENT)
8093 continue;
8094 settings::GuestProperty prop;
8095 prop.strName = property.strName;
8096 prop.strValue = property.strValue;
8097 prop.timestamp = property.mTimestamp;
8098 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
8099 guestProp::writeFlags(property.mFlags, szFlags);
8100 prop.strFlags = szFlags;
8101
8102 data.llGuestProperties.push_back(prop);
8103 }
8104
8105 data.strNotificationPatterns = mHWData->mGuestPropertyNotificationPatterns;
8106 /* I presume this doesn't require a backup(). */
8107 mData->mGuestPropertiesModified = FALSE;
8108#endif /* VBOX_WITH_GUEST_PROPS defined */
8109 }
8110 catch(std::bad_alloc &)
8111 {
8112 return E_OUTOFMEMORY;
8113 }
8114
8115 AssertComRC(rc);
8116 return rc;
8117}
8118
8119/**
8120 * Saves the storage controller configuration.
8121 *
8122 * @param aNode <StorageControllers> node to save the VM hardware confguration to.
8123 */
8124HRESULT Machine::saveStorageControllers(settings::Storage &data)
8125{
8126 data.llStorageControllers.clear();
8127
8128 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
8129 it != mStorageControllers->end();
8130 ++it)
8131 {
8132 HRESULT rc;
8133 ComObjPtr<StorageController> pCtl = *it;
8134
8135 settings::StorageController ctl;
8136 ctl.strName = pCtl->getName();
8137 ctl.controllerType = pCtl->getControllerType();
8138 ctl.storageBus = pCtl->getStorageBus();
8139 ctl.ulInstance = pCtl->getInstance();
8140
8141 /* Save the port count. */
8142 ULONG portCount;
8143 rc = pCtl->COMGETTER(PortCount)(&portCount);
8144 ComAssertComRCRet(rc, rc);
8145 ctl.ulPortCount = portCount;
8146
8147 /* Save fUseHostIOCache */
8148 BOOL fUseHostIOCache;
8149 rc = pCtl->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
8150 ComAssertComRCRet(rc, rc);
8151 ctl.fUseHostIOCache = !!fUseHostIOCache;
8152
8153 /* Save IDE emulation settings. */
8154 if (ctl.controllerType == StorageControllerType_IntelAhci)
8155 {
8156 if ( (FAILED(rc = pCtl->GetIDEEmulationPort(0, (LONG*)&ctl.lIDE0MasterEmulationPort)))
8157 || (FAILED(rc = pCtl->GetIDEEmulationPort(1, (LONG*)&ctl.lIDE0SlaveEmulationPort)))
8158 || (FAILED(rc = pCtl->GetIDEEmulationPort(2, (LONG*)&ctl.lIDE1MasterEmulationPort)))
8159 || (FAILED(rc = pCtl->GetIDEEmulationPort(3, (LONG*)&ctl.lIDE1SlaveEmulationPort)))
8160 )
8161 ComAssertComRCRet(rc, rc);
8162 }
8163
8164 /* save the devices now. */
8165 rc = saveStorageDevices(pCtl, ctl);
8166 ComAssertComRCRet(rc, rc);
8167
8168 data.llStorageControllers.push_back(ctl);
8169 }
8170
8171 return S_OK;
8172}
8173
8174/**
8175 * Saves the hard disk confguration.
8176 */
8177HRESULT Machine::saveStorageDevices(ComObjPtr<StorageController> aStorageController,
8178 settings::StorageController &data)
8179{
8180 MediaData::AttachmentList atts;
8181
8182 HRESULT rc = getMediumAttachmentsOfController(Bstr(aStorageController->getName()), atts);
8183 if (FAILED(rc)) return rc;
8184
8185 data.llAttachedDevices.clear();
8186 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8187 it != atts.end();
8188 ++it)
8189 {
8190 settings::AttachedDevice dev;
8191
8192 MediumAttachment *pAttach = *it;
8193 Medium *pMedium = pAttach->getMedium();
8194
8195 dev.deviceType = pAttach->getType();
8196 dev.lPort = pAttach->getPort();
8197 dev.lDevice = pAttach->getDevice();
8198 if (pMedium)
8199 {
8200 BOOL fHostDrive = FALSE;
8201 rc = pMedium->COMGETTER(HostDrive)(&fHostDrive);
8202 if (FAILED(rc))
8203 return rc;
8204 if (fHostDrive)
8205 dev.strHostDriveSrc = pMedium->getLocation();
8206 else
8207 dev.uuid = pMedium->getId();
8208 dev.fPassThrough = pAttach->getPassthrough();
8209 }
8210
8211 data.llAttachedDevices.push_back(dev);
8212 }
8213
8214 return S_OK;
8215}
8216
8217/**
8218 * Saves machine state settings as defined by aFlags
8219 * (SaveSTS_* values).
8220 *
8221 * @param aFlags Combination of SaveSTS_* flags.
8222 *
8223 * @note Locks objects for writing.
8224 */
8225HRESULT Machine::saveStateSettings(int aFlags)
8226{
8227 if (aFlags == 0)
8228 return S_OK;
8229
8230 AutoCaller autoCaller(this);
8231 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8232
8233 /* This object's write lock is also necessary to serialize file access
8234 * (prevent concurrent reads and writes) */
8235 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8236
8237 HRESULT rc = S_OK;
8238
8239 Assert(mData->pMachineConfigFile);
8240
8241 try
8242 {
8243 if (aFlags & SaveSTS_CurStateModified)
8244 mData->pMachineConfigFile->fCurrentStateModified = true;
8245
8246 if (aFlags & SaveSTS_StateFilePath)
8247 {
8248 if (!mSSData->mStateFilePath.isEmpty())
8249 /* try to make the file name relative to the settings file dir */
8250 copyPathRelativeToMachine(mSSData->mStateFilePath, mData->pMachineConfigFile->strStateFile);
8251 else
8252 mData->pMachineConfigFile->strStateFile.setNull();
8253 }
8254
8255 if (aFlags & SaveSTS_StateTimeStamp)
8256 {
8257 Assert( mData->mMachineState != MachineState_Aborted
8258 || mSSData->mStateFilePath.isEmpty());
8259
8260 mData->pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
8261
8262 mData->pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
8263//@todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
8264 }
8265
8266 mData->pMachineConfigFile->write(mData->m_strConfigFileFull);
8267 }
8268 catch (...)
8269 {
8270 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8271 }
8272
8273 return rc;
8274}
8275
8276/**
8277 * Creates differencing hard disks for all normal hard disks attached to this
8278 * machine and a new set of attachments to refer to created disks.
8279 *
8280 * Used when taking a snapshot or when deleting the current state.
8281 *
8282 * This method assumes that mMediaData contains the original hard disk attachments
8283 * it needs to create diffs for. On success, these attachments will be replaced
8284 * with the created diffs. On failure, #deleteImplicitDiffs() is implicitly
8285 * called to delete created diffs which will also rollback mMediaData and restore
8286 * whatever was backed up before calling this method.
8287 *
8288 * Attachments with non-normal hard disks are left as is.
8289 *
8290 * If @a aOnline is @c false then the original hard disks that require implicit
8291 * diffs will be locked for reading. Otherwise it is assumed that they are
8292 * already locked for writing (when the VM was started). Note that in the latter
8293 * case it is responsibility of the caller to lock the newly created diffs for
8294 * writing if this method succeeds.
8295 *
8296 * @param aFolder Folder where to create diff hard disks.
8297 * @param aProgress Progress object to run (must contain at least as
8298 * many operations left as the number of hard disks
8299 * attached).
8300 * @param aOnline Whether the VM was online prior to this operation.
8301 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8302 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8303 *
8304 * @note The progress object is not marked as completed, neither on success nor
8305 * on failure. This is a responsibility of the caller.
8306 *
8307 * @note Locks this object for writing.
8308 */
8309HRESULT Machine::createImplicitDiffs(const Bstr &aFolder,
8310 IProgress *aProgress,
8311 ULONG aWeight,
8312 bool aOnline,
8313 bool *pfNeedsSaveSettings)
8314{
8315 AssertReturn(!aFolder.isEmpty(), E_FAIL);
8316
8317 LogFlowThisFunc(("aFolder='%ls', aOnline=%d\n", aFolder.raw(), aOnline));
8318
8319 AutoCaller autoCaller(this);
8320 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8321
8322 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8323
8324 /* must be in a protective state because we leave the lock below */
8325 AssertReturn( mData->mMachineState == MachineState_Saving
8326 || mData->mMachineState == MachineState_LiveSnapshotting
8327 || mData->mMachineState == MachineState_RestoringSnapshot
8328 || mData->mMachineState == MachineState_DeletingSnapshot
8329 , E_FAIL);
8330
8331 HRESULT rc = S_OK;
8332
8333 MediumLockListMap lockedMediaOffline;
8334 MediumLockListMap *lockedMediaMap;
8335 if (aOnline)
8336 lockedMediaMap = &mData->mSession.mLockedMedia;
8337 else
8338 lockedMediaMap = &lockedMediaOffline;
8339
8340 try
8341 {
8342 if (!aOnline)
8343 {
8344 /* lock all attached hard disks early to detect "in use"
8345 * situations before creating actual diffs */
8346 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8347 it != mMediaData->mAttachments.end();
8348 ++it)
8349 {
8350 MediumAttachment* pAtt = *it;
8351 if (pAtt->getType() == DeviceType_HardDisk)
8352 {
8353 Medium* pMedium = pAtt->getMedium();
8354 Assert(pMedium);
8355
8356 MediumLockList *pMediumLockList(new MediumLockList());
8357 rc = pMedium->createMediumLockList(true /* fFailIfInaccessible */,
8358 false /* fMediumLockWrite */,
8359 NULL,
8360 *pMediumLockList);
8361 if (FAILED(rc))
8362 {
8363 delete pMediumLockList;
8364 throw rc;
8365 }
8366 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
8367 if (FAILED(rc))
8368 {
8369 throw setError(rc,
8370 tr("Collecting locking information for all attached media failed"));
8371 }
8372 }
8373 }
8374
8375 /* Now lock all media. If this fails, nothing is locked. */
8376 rc = lockedMediaMap->Lock();
8377 if (FAILED(rc))
8378 {
8379 throw setError(rc,
8380 tr("Locking of attached media failed"));
8381 }
8382 }
8383
8384 /* remember the current list (note that we don't use backup() since
8385 * mMediaData may be already backed up) */
8386 MediaData::AttachmentList atts = mMediaData->mAttachments;
8387
8388 /* start from scratch */
8389 mMediaData->mAttachments.clear();
8390
8391 /* go through remembered attachments and create diffs for normal hard
8392 * disks and attach them */
8393 for (MediaData::AttachmentList::const_iterator it = atts.begin();
8394 it != atts.end();
8395 ++it)
8396 {
8397 MediumAttachment* pAtt = *it;
8398
8399 DeviceType_T devType = pAtt->getType();
8400 Medium* pMedium = pAtt->getMedium();
8401
8402 if ( devType != DeviceType_HardDisk
8403 || pMedium == NULL
8404 || pMedium->getType() != MediumType_Normal)
8405 {
8406 /* copy the attachment as is */
8407
8408 /** @todo the progress object created in Console::TakeSnaphot
8409 * only expects operations for hard disks. Later other
8410 * device types need to show up in the progress as well. */
8411 if (devType == DeviceType_HardDisk)
8412 {
8413 if (pMedium == NULL)
8414 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")),
8415 aWeight); // weight
8416 else
8417 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
8418 pMedium->getBase()->getName().raw()),
8419 aWeight); // weight
8420 }
8421
8422 mMediaData->mAttachments.push_back(pAtt);
8423 continue;
8424 }
8425
8426 /* need a diff */
8427 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
8428 pMedium->getBase()->getName().raw()),
8429 aWeight); // weight
8430
8431 ComObjPtr<Medium> diff;
8432 diff.createObject();
8433 rc = diff->init(mParent,
8434 pMedium->preferredDiffFormat().raw(),
8435 BstrFmt("%ls"RTPATH_SLASH_STR,
8436 mUserData->mSnapshotFolderFull.raw()).raw(),
8437 pfNeedsSaveSettings);
8438 if (FAILED(rc)) throw rc;
8439
8440 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
8441 * the push_back? Looks like we're going to leave medium with the
8442 * wrong kind of lock (general issue with if we fail anywhere at all)
8443 * and an orphaned VDI in the snapshots folder. */
8444
8445 /* update the appropriate lock list */
8446 MediumLockList *pMediumLockList;
8447 rc = lockedMediaMap->Get(pAtt, pMediumLockList);
8448 AssertComRCThrowRC(rc);
8449 if (aOnline)
8450 {
8451 rc = pMediumLockList->Update(pMedium, false);
8452 AssertComRCThrowRC(rc);
8453 }
8454
8455 /* leave the lock before the potentially lengthy operation */
8456 alock.leave();
8457 rc = pMedium->createDiffStorage(diff, MediumVariant_Standard,
8458 pMediumLockList,
8459 NULL /* aProgress */,
8460 true /* aWait */,
8461 pfNeedsSaveSettings);
8462 alock.enter();
8463 if (FAILED(rc)) throw rc;
8464
8465 rc = lockedMediaMap->Unlock();
8466 AssertComRCThrowRC(rc);
8467 rc = pMediumLockList->Append(diff, true);
8468 AssertComRCThrowRC(rc);
8469 rc = lockedMediaMap->Lock();
8470 AssertComRCThrowRC(rc);
8471
8472 rc = diff->addBackReference(mData->mUuid);
8473 AssertComRCThrowRC(rc);
8474
8475 /* add a new attachment */
8476 ComObjPtr<MediumAttachment> attachment;
8477 attachment.createObject();
8478 rc = attachment->init(this,
8479 diff,
8480 pAtt->getControllerName(),
8481 pAtt->getPort(),
8482 pAtt->getDevice(),
8483 DeviceType_HardDisk,
8484 true /* aImplicit */);
8485 if (FAILED(rc)) throw rc;
8486
8487 rc = lockedMediaMap->ReplaceKey(pAtt, attachment);
8488 AssertComRCThrowRC(rc);
8489 mMediaData->mAttachments.push_back(attachment);
8490 }
8491 }
8492 catch (HRESULT aRC) { rc = aRC; }
8493
8494 /* unlock all hard disks we locked */
8495 if (!aOnline)
8496 {
8497 ErrorInfoKeeper eik;
8498
8499 rc = lockedMediaMap->Clear();
8500 AssertComRC(rc);
8501 }
8502
8503 if (FAILED(rc))
8504 {
8505 MultiResult mrc = rc;
8506
8507 mrc = deleteImplicitDiffs(pfNeedsSaveSettings);
8508 }
8509
8510 return rc;
8511}
8512
8513/**
8514 * Deletes implicit differencing hard disks created either by
8515 * #createImplicitDiffs() or by #AttachMedium() and rolls back mMediaData.
8516 *
8517 * Note that to delete hard disks created by #AttachMedium() this method is
8518 * called from #fixupMedia() when the changes are rolled back.
8519 *
8520 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8521 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8522 *
8523 * @note Locks this object for writing.
8524 */
8525HRESULT Machine::deleteImplicitDiffs(bool *pfNeedsSaveSettings)
8526{
8527 AutoCaller autoCaller(this);
8528 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
8529
8530 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8531 LogFlowThisFuncEnter();
8532
8533 AssertReturn(mMediaData.isBackedUp(), E_FAIL);
8534
8535 HRESULT rc = S_OK;
8536
8537 MediaData::AttachmentList implicitAtts;
8538
8539 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
8540
8541 /* enumerate new attachments */
8542 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8543 it != mMediaData->mAttachments.end();
8544 ++it)
8545 {
8546 ComObjPtr<Medium> hd = (*it)->getMedium();
8547 if (hd.isNull())
8548 continue;
8549
8550 if ((*it)->isImplicit())
8551 {
8552 /* deassociate and mark for deletion */
8553 LogFlowThisFunc(("Detaching '%s', pending deletion\n", (*it)->getLogName()));
8554 rc = hd->removeBackReference(mData->mUuid);
8555 AssertComRC(rc);
8556 implicitAtts.push_back(*it);
8557 continue;
8558 }
8559
8560 /* was this hard disk attached before? */
8561 if (!findAttachment(oldAtts, hd))
8562 {
8563 /* no: de-associate */
8564 LogFlowThisFunc(("Detaching '%s', no deletion\n", (*it)->getLogName()));
8565 rc = hd->removeBackReference(mData->mUuid);
8566 AssertComRC(rc);
8567 continue;
8568 }
8569 LogFlowThisFunc(("Not detaching '%s'\n", (*it)->getLogName()));
8570 }
8571
8572 /* rollback hard disk changes */
8573 mMediaData.rollback();
8574
8575 MultiResult mrc(S_OK);
8576
8577 /* delete unused implicit diffs */
8578 if (implicitAtts.size() != 0)
8579 {
8580 /* will leave the lock before the potentially lengthy
8581 * operation, so protect with the special state (unless already
8582 * protected) */
8583 MachineState_T oldState = mData->mMachineState;
8584 if ( oldState != MachineState_Saving
8585 && oldState != MachineState_LiveSnapshotting
8586 && oldState != MachineState_RestoringSnapshot
8587 && oldState != MachineState_DeletingSnapshot
8588 && oldState != MachineState_DeletingSnapshotOnline
8589 && oldState != MachineState_DeletingSnapshotPaused
8590 )
8591 setMachineState(MachineState_SettingUp);
8592
8593 alock.leave();
8594
8595 for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin();
8596 it != implicitAtts.end();
8597 ++it)
8598 {
8599 LogFlowThisFunc(("Deleting '%s'\n", (*it)->getLogName()));
8600 ComObjPtr<Medium> hd = (*it)->getMedium();
8601
8602 rc = hd->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
8603 pfNeedsSaveSettings);
8604 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, (*it)->getLogName(), hd->getLocationFull().c_str() ));
8605 mrc = rc;
8606 }
8607
8608 alock.enter();
8609
8610 if (mData->mMachineState == MachineState_SettingUp)
8611 {
8612 setMachineState(oldState);
8613 }
8614 }
8615
8616 return mrc;
8617}
8618
8619/**
8620 * Looks through the given list of media attachments for one with the given parameters
8621 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8622 * can be searched as well if needed.
8623 *
8624 * @param list
8625 * @param aControllerName
8626 * @param aControllerPort
8627 * @param aDevice
8628 * @return
8629 */
8630MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8631 IN_BSTR aControllerName,
8632 LONG aControllerPort,
8633 LONG aDevice)
8634{
8635 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8636 it != ll.end();
8637 ++it)
8638 {
8639 MediumAttachment *pAttach = *it;
8640 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
8641 return pAttach;
8642 }
8643
8644 return NULL;
8645}
8646
8647/**
8648 * Looks through the given list of media attachments for one with the given parameters
8649 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8650 * can be searched as well if needed.
8651 *
8652 * @param list
8653 * @param aControllerName
8654 * @param aControllerPort
8655 * @param aDevice
8656 * @return
8657 */
8658MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8659 ComObjPtr<Medium> pMedium)
8660{
8661 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8662 it != ll.end();
8663 ++it)
8664 {
8665 MediumAttachment *pAttach = *it;
8666 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
8667 if (pMediumThis == pMedium)
8668 return pAttach;
8669 }
8670
8671 return NULL;
8672}
8673
8674/**
8675 * Looks through the given list of media attachments for one with the given parameters
8676 * and returns it, or NULL if not found. The list is a parameter so that backup lists
8677 * can be searched as well if needed.
8678 *
8679 * @param list
8680 * @param aControllerName
8681 * @param aControllerPort
8682 * @param aDevice
8683 * @return
8684 */
8685MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
8686 Guid &id)
8687{
8688 for (MediaData::AttachmentList::const_iterator it = ll.begin();
8689 it != ll.end();
8690 ++it)
8691 {
8692 MediumAttachment *pAttach = *it;
8693 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
8694 if (pMediumThis->getId() == id)
8695 return pAttach;
8696 }
8697
8698 return NULL;
8699}
8700
8701/**
8702 * Main implementation for Machine::DetachDevice. This also gets called
8703 * from Machine::prepareUnregister() so it has been taken out for simplicity.
8704 *
8705 * @param pAttach Medium attachment to detach.
8706 * @param writeLock Machine write lock which the caller must have locked once. This may be released temporarily in here.
8707 * @param pSnapshot If NULL, then the detachment is for the current machine. Otherwise this is for a SnapshotMachine, and this must be its snapshot.
8708 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8709 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8710 * @return
8711 */
8712HRESULT Machine::detachDevice(MediumAttachment *pAttach,
8713 AutoWriteLock &writeLock,
8714 Snapshot *pSnapshot,
8715 bool *pfNeedsSaveSettings)
8716{
8717 ComObjPtr<Medium> oldmedium = pAttach->getMedium();
8718 DeviceType_T mediumType = pAttach->getType();
8719
8720 LogFlowThisFunc(("Entering, medium of attachment is %s\n", oldmedium ? oldmedium->getLocationFull().c_str() : "NULL"));
8721
8722 if (pAttach->isImplicit())
8723 {
8724 /* attempt to implicitly delete the implicitly created diff */
8725
8726 /// @todo move the implicit flag from MediumAttachment to Medium
8727 /// and forbid any hard disk operation when it is implicit. Or maybe
8728 /// a special media state for it to make it even more simple.
8729
8730 Assert(mMediaData.isBackedUp());
8731
8732 /* will leave the lock before the potentially lengthy operation, so
8733 * protect with the special state */
8734 MachineState_T oldState = mData->mMachineState;
8735 setMachineState(MachineState_SettingUp);
8736
8737 writeLock.release();
8738
8739 HRESULT rc = oldmedium->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
8740 pfNeedsSaveSettings);
8741
8742 writeLock.acquire();
8743
8744 setMachineState(oldState);
8745
8746 if (FAILED(rc)) return rc;
8747 }
8748
8749 setModified(IsModified_Storage);
8750 mMediaData.backup();
8751
8752 // we cannot use erase (it) below because backup() above will create
8753 // a copy of the list and make this copy active, but the iterator
8754 // still refers to the original and is not valid for the copy
8755 mMediaData->mAttachments.remove(pAttach);
8756
8757 if (!oldmedium.isNull())
8758 {
8759 // if this is from a snapshot, do not defer detachment to commitMedia()
8760 if (pSnapshot)
8761 oldmedium->removeBackReference(mData->mUuid, pSnapshot->getId());
8762 // else if non-hard disk media, do not defer detachment to commitMedia() either
8763 else if (mediumType != DeviceType_HardDisk)
8764 oldmedium->removeBackReference(mData->mUuid);
8765 }
8766
8767 return S_OK;
8768}
8769
8770/**
8771 * Goes thru all medium attachments of the list and calls detachDevice() on each
8772 * of them and attaches all Medium objects found in the process to the given list.
8773 *
8774 * This gets called from Machine::Unregister, both for the actual Machine and
8775 * the SnapshotMachine objects that might be found in the snapshots.
8776 *
8777 * Requires caller and locking.
8778 *
8779 * @param writeLock Machine lock from top-level caller; this gets passed to detachDevice.
8780 * @param llMedia Caller's list to receive Medium objects which got detached so caller can close() them.
8781 * @param pSnapshot Must be NULL when called for a "real" Machine or a snapshot object if called for a SnapshotMachine.
8782 * @return
8783 */
8784HRESULT Machine::detachAllMedia(AutoWriteLock &writeLock,
8785 Snapshot *pSnapshot,
8786 MediaList &llMedia)
8787{
8788 Assert(isWriteLockOnCurrentThread());
8789
8790 HRESULT rc;
8791
8792 // make a temporary list because detachDevice invalidates iterators into
8793 // mMediaData->mAttachments
8794 MediaData::AttachmentList llAttachments2 = mMediaData->mAttachments;
8795
8796 for (MediaData::AttachmentList::iterator it = llAttachments2.begin();
8797 it != llAttachments2.end();
8798 ++it)
8799 {
8800 ComObjPtr<MediumAttachment> pAttach = *it;
8801 ComObjPtr<Medium> pMedium = pAttach->getMedium();
8802
8803 if (!pMedium.isNull())
8804 llMedia.push_back(pMedium);
8805
8806 // real machine: then we need to use the proper method
8807 rc = detachDevice(pAttach,
8808 writeLock,
8809 pSnapshot,
8810 NULL /* pfNeedsSaveSettings */);
8811
8812 if (FAILED(rc))
8813 return rc;
8814 }
8815
8816 return S_OK;
8817}
8818
8819/**
8820 * Perform deferred hard disk detachments.
8821 *
8822 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
8823 * backed up).
8824 *
8825 * If @a aOnline is @c true then this method will also unlock the old hard disks
8826 * for which the new implicit diffs were created and will lock these new diffs for
8827 * writing.
8828 *
8829 * @param aOnline Whether the VM was online prior to this operation.
8830 *
8831 * @note Locks this object for writing!
8832 */
8833void Machine::commitMedia(bool aOnline /*= false*/)
8834{
8835 AutoCaller autoCaller(this);
8836 AssertComRCReturnVoid(autoCaller.rc());
8837
8838 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8839
8840 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
8841
8842 HRESULT rc = S_OK;
8843
8844 /* no attach/detach operations -- nothing to do */
8845 if (!mMediaData.isBackedUp())
8846 return;
8847
8848 MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
8849 bool fMediaNeedsLocking = false;
8850
8851 /* enumerate new attachments */
8852 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
8853 it != mMediaData->mAttachments.end();
8854 ++it)
8855 {
8856 MediumAttachment *pAttach = *it;
8857
8858 pAttach->commit();
8859
8860 Medium* pMedium = pAttach->getMedium();
8861 bool fImplicit = pAttach->isImplicit();
8862
8863 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
8864 (pMedium) ? pMedium->getName().raw() : "NULL",
8865 fImplicit));
8866
8867 /** @todo convert all this Machine-based voodoo to MediumAttachment
8868 * based commit logic. */
8869 if (fImplicit)
8870 {
8871 /* convert implicit attachment to normal */
8872 pAttach->setImplicit(false);
8873
8874 if ( aOnline
8875 && pMedium
8876 && pAttach->getType() == DeviceType_HardDisk
8877 )
8878 {
8879 ComObjPtr<Medium> parent = pMedium->getParent();
8880 AutoWriteLock parentLock(parent COMMA_LOCKVAL_SRC_POS);
8881
8882 /* update the appropriate lock list */
8883 MediumLockList *pMediumLockList;
8884 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
8885 AssertComRC(rc);
8886 if (pMediumLockList)
8887 {
8888 /* unlock if there's a need to change the locking */
8889 if (!fMediaNeedsLocking)
8890 {
8891 rc = mData->mSession.mLockedMedia.Unlock();
8892 AssertComRC(rc);
8893 fMediaNeedsLocking = true;
8894 }
8895 rc = pMediumLockList->Update(parent, false);
8896 AssertComRC(rc);
8897 rc = pMediumLockList->Append(pMedium, true);
8898 AssertComRC(rc);
8899 }
8900 }
8901
8902 continue;
8903 }
8904
8905 if (pMedium)
8906 {
8907 /* was this medium attached before? */
8908 for (MediaData::AttachmentList::iterator oldIt = oldAtts.begin();
8909 oldIt != oldAtts.end();
8910 ++oldIt)
8911 {
8912 MediumAttachment *pOldAttach = *oldIt;
8913 if (pOldAttach->getMedium() == pMedium)
8914 {
8915 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->getName().raw()));
8916
8917 /* yes: remove from old to avoid de-association */
8918 oldAtts.erase(oldIt);
8919 break;
8920 }
8921 }
8922 }
8923 }
8924
8925 /* enumerate remaining old attachments and de-associate from the
8926 * current machine state */
8927 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
8928 it != oldAtts.end();
8929 ++it)
8930 {
8931 MediumAttachment *pAttach = *it;
8932 Medium* pMedium = pAttach->getMedium();
8933
8934 /* Detach only hard disks, since DVD/floppy media is detached
8935 * instantly in MountMedium. */
8936 if (pAttach->getType() == DeviceType_HardDisk && pMedium)
8937 {
8938 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->getName().raw()));
8939
8940 /* now de-associate from the current machine state */
8941 rc = pMedium->removeBackReference(mData->mUuid);
8942 AssertComRC(rc);
8943
8944 if (aOnline)
8945 {
8946 /* unlock since medium is not used anymore */
8947 MediumLockList *pMediumLockList;
8948 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
8949 AssertComRC(rc);
8950 if (pMediumLockList)
8951 {
8952 rc = mData->mSession.mLockedMedia.Remove(pAttach);
8953 AssertComRC(rc);
8954 }
8955 }
8956 }
8957 }
8958
8959 /* take media locks again so that the locking state is consistent */
8960 if (fMediaNeedsLocking)
8961 {
8962 Assert(aOnline);
8963 rc = mData->mSession.mLockedMedia.Lock();
8964 AssertComRC(rc);
8965 }
8966
8967 /* commit the hard disk changes */
8968 mMediaData.commit();
8969
8970 if (isSessionMachine())
8971 {
8972 /* attach new data to the primary machine and reshare it */
8973 mPeer->mMediaData.attach(mMediaData);
8974 }
8975
8976 return;
8977}
8978
8979/**
8980 * Perform deferred deletion of implicitly created diffs.
8981 *
8982 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
8983 * backed up).
8984 *
8985 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
8986 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
8987 *
8988 * @note Locks this object for writing!
8989 */
8990void Machine::rollbackMedia()
8991{
8992 AutoCaller autoCaller(this);
8993 AssertComRCReturnVoid (autoCaller.rc());
8994
8995 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8996
8997 LogFlowThisFunc(("Entering\n"));
8998
8999 HRESULT rc = S_OK;
9000
9001 /* no attach/detach operations -- nothing to do */
9002 if (!mMediaData.isBackedUp())
9003 return;
9004
9005 /* enumerate new attachments */
9006 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9007 it != mMediaData->mAttachments.end();
9008 ++it)
9009 {
9010 MediumAttachment *pAttach = *it;
9011 /* Fix up the backrefs for DVD/floppy media. */
9012 if (pAttach->getType() != DeviceType_HardDisk)
9013 {
9014 Medium* pMedium = pAttach->getMedium();
9015 if (pMedium)
9016 {
9017 rc = pMedium->removeBackReference(mData->mUuid);
9018 AssertComRC(rc);
9019 }
9020 }
9021
9022 (*it)->rollback();
9023
9024 pAttach = *it;
9025 /* Fix up the backrefs for DVD/floppy media. */
9026 if (pAttach->getType() != DeviceType_HardDisk)
9027 {
9028 Medium* pMedium = pAttach->getMedium();
9029 if (pMedium)
9030 {
9031 rc = pMedium->addBackReference(mData->mUuid);
9032 AssertComRC(rc);
9033 }
9034 }
9035 }
9036
9037 /** @todo convert all this Machine-based voodoo to MediumAttachment
9038 * based rollback logic. */
9039 // @todo r=dj the below totally fails if this gets called from Machine::rollback(),
9040 // which gets called if Machine::registeredInit() fails...
9041 deleteImplicitDiffs(NULL /*pfNeedsSaveSettings*/);
9042
9043 return;
9044}
9045
9046/**
9047 * Returns true if the settings file is located in the directory named exactly
9048 * as the machine. This will be true if the machine settings structure was
9049 * created by default in #openConfigLoader().
9050 *
9051 * @param aSettingsDir if not NULL, the full machine settings file directory
9052 * name will be assigned there.
9053 *
9054 * @note Doesn't lock anything.
9055 * @note Not thread safe (must be called from this object's lock).
9056 */
9057bool Machine::isInOwnDir(Utf8Str *aSettingsDir /* = NULL */) const
9058{
9059 Utf8Str settingsDir = mData->m_strConfigFileFull;
9060 settingsDir.stripFilename();
9061 char *dirName = RTPathFilename(settingsDir.c_str());
9062
9063 AssertReturn(dirName, false);
9064
9065 /* if we don't rename anything on name change, return false shorlty */
9066 if (!mUserData->mNameSync)
9067 return false;
9068
9069 if (aSettingsDir)
9070 *aSettingsDir = settingsDir;
9071
9072 return Bstr(dirName) == mUserData->mName;
9073}
9074
9075/**
9076 * Discards all changes to machine settings.
9077 *
9078 * @param aNotify Whether to notify the direct session about changes or not.
9079 *
9080 * @note Locks objects for writing!
9081 */
9082void Machine::rollback(bool aNotify)
9083{
9084 AutoCaller autoCaller(this);
9085 AssertComRCReturn(autoCaller.rc(), (void)0);
9086
9087 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9088
9089 if (!mStorageControllers.isNull())
9090 {
9091 if (mStorageControllers.isBackedUp())
9092 {
9093 /* unitialize all new devices (absent in the backed up list). */
9094 StorageControllerList::const_iterator it = mStorageControllers->begin();
9095 StorageControllerList *backedList = mStorageControllers.backedUpData();
9096 while (it != mStorageControllers->end())
9097 {
9098 if ( std::find(backedList->begin(), backedList->end(), *it)
9099 == backedList->end()
9100 )
9101 {
9102 (*it)->uninit();
9103 }
9104 ++it;
9105 }
9106
9107 /* restore the list */
9108 mStorageControllers.rollback();
9109 }
9110
9111 /* rollback any changes to devices after restoring the list */
9112 if (mData->flModifications & IsModified_Storage)
9113 {
9114 StorageControllerList::const_iterator it = mStorageControllers->begin();
9115 while (it != mStorageControllers->end())
9116 {
9117 (*it)->rollback();
9118 ++it;
9119 }
9120 }
9121 }
9122
9123 mUserData.rollback();
9124
9125 mHWData.rollback();
9126
9127 if (mData->flModifications & IsModified_Storage)
9128 rollbackMedia();
9129
9130 if (mBIOSSettings)
9131 mBIOSSettings->rollback();
9132
9133#ifdef VBOX_WITH_VRDP
9134 if (mVRDPServer && (mData->flModifications & IsModified_VRDPServer))
9135 mVRDPServer->rollback();
9136#endif
9137
9138 if (mAudioAdapter)
9139 mAudioAdapter->rollback();
9140
9141 if (mUSBController && (mData->flModifications & IsModified_USB))
9142 mUSBController->rollback();
9143
9144 ComPtr<INetworkAdapter> networkAdapters[RT_ELEMENTS(mNetworkAdapters)];
9145 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
9146 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
9147
9148 if (mData->flModifications & IsModified_NetworkAdapters)
9149 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9150 if ( mNetworkAdapters[slot]
9151 && mNetworkAdapters[slot]->isModified())
9152 {
9153 mNetworkAdapters[slot]->rollback();
9154 networkAdapters[slot] = mNetworkAdapters[slot];
9155 }
9156
9157 if (mData->flModifications & IsModified_SerialPorts)
9158 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9159 if ( mSerialPorts[slot]
9160 && mSerialPorts[slot]->isModified())
9161 {
9162 mSerialPorts[slot]->rollback();
9163 serialPorts[slot] = mSerialPorts[slot];
9164 }
9165
9166 if (mData->flModifications & IsModified_ParallelPorts)
9167 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9168 if ( mParallelPorts[slot]
9169 && mParallelPorts[slot]->isModified())
9170 {
9171 mParallelPorts[slot]->rollback();
9172 parallelPorts[slot] = mParallelPorts[slot];
9173 }
9174
9175 if (aNotify)
9176 {
9177 /* inform the direct session about changes */
9178
9179 ComObjPtr<Machine> that = this;
9180 uint32_t flModifications = mData->flModifications;
9181 alock.leave();
9182
9183 if (flModifications & IsModified_SharedFolders)
9184 that->onSharedFolderChange();
9185
9186 if (flModifications & IsModified_VRDPServer)
9187 that->onVRDPServerChange(/* aRestart */ TRUE);
9188 if (flModifications & IsModified_USB)
9189 that->onUSBControllerChange();
9190
9191 for (ULONG slot = 0; slot < RT_ELEMENTS(networkAdapters); slot ++)
9192 if (networkAdapters[slot])
9193 that->onNetworkAdapterChange(networkAdapters[slot], FALSE);
9194 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); slot ++)
9195 if (serialPorts[slot])
9196 that->onSerialPortChange(serialPorts[slot]);
9197 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); slot ++)
9198 if (parallelPorts[slot])
9199 that->onParallelPortChange(parallelPorts[slot]);
9200
9201 if (flModifications & IsModified_Storage)
9202 that->onStorageControllerChange();
9203 }
9204}
9205
9206/**
9207 * Commits all the changes to machine settings.
9208 *
9209 * Note that this operation is supposed to never fail.
9210 *
9211 * @note Locks this object and children for writing.
9212 */
9213void Machine::commit()
9214{
9215 AutoCaller autoCaller(this);
9216 AssertComRCReturnVoid(autoCaller.rc());
9217
9218 AutoCaller peerCaller(mPeer);
9219 AssertComRCReturnVoid(peerCaller.rc());
9220
9221 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
9222
9223 /*
9224 * use safe commit to ensure Snapshot machines (that share mUserData)
9225 * will still refer to a valid memory location
9226 */
9227 mUserData.commitCopy();
9228
9229 mHWData.commit();
9230
9231 if (mMediaData.isBackedUp())
9232 commitMedia();
9233
9234 mBIOSSettings->commit();
9235#ifdef VBOX_WITH_VRDP
9236 mVRDPServer->commit();
9237#endif
9238 mAudioAdapter->commit();
9239 mUSBController->commit();
9240
9241 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9242 mNetworkAdapters[slot]->commit();
9243 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9244 mSerialPorts[slot]->commit();
9245 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9246 mParallelPorts[slot]->commit();
9247
9248 bool commitStorageControllers = false;
9249
9250 if (mStorageControllers.isBackedUp())
9251 {
9252 mStorageControllers.commit();
9253
9254 if (mPeer)
9255 {
9256 AutoWriteLock peerlock(mPeer COMMA_LOCKVAL_SRC_POS);
9257
9258 /* Commit all changes to new controllers (this will reshare data with
9259 * peers for thos who have peers) */
9260 StorageControllerList *newList = new StorageControllerList();
9261 StorageControllerList::const_iterator it = mStorageControllers->begin();
9262 while (it != mStorageControllers->end())
9263 {
9264 (*it)->commit();
9265
9266 /* look if this controller has a peer device */
9267 ComObjPtr<StorageController> peer = (*it)->getPeer();
9268 if (!peer)
9269 {
9270 /* no peer means the device is a newly created one;
9271 * create a peer owning data this device share it with */
9272 peer.createObject();
9273 peer->init(mPeer, *it, true /* aReshare */);
9274 }
9275 else
9276 {
9277 /* remove peer from the old list */
9278 mPeer->mStorageControllers->remove(peer);
9279 }
9280 /* and add it to the new list */
9281 newList->push_back(peer);
9282
9283 ++it;
9284 }
9285
9286 /* uninit old peer's controllers that are left */
9287 it = mPeer->mStorageControllers->begin();
9288 while (it != mPeer->mStorageControllers->end())
9289 {
9290 (*it)->uninit();
9291 ++it;
9292 }
9293
9294 /* attach new list of controllers to our peer */
9295 mPeer->mStorageControllers.attach(newList);
9296 }
9297 else
9298 {
9299 /* we have no peer (our parent is the newly created machine);
9300 * just commit changes to devices */
9301 commitStorageControllers = true;
9302 }
9303 }
9304 else
9305 {
9306 /* the list of controllers itself is not changed,
9307 * just commit changes to controllers themselves */
9308 commitStorageControllers = true;
9309 }
9310
9311 if (commitStorageControllers)
9312 {
9313 StorageControllerList::const_iterator it = mStorageControllers->begin();
9314 while (it != mStorageControllers->end())
9315 {
9316 (*it)->commit();
9317 ++it;
9318 }
9319 }
9320
9321 if (isSessionMachine())
9322 {
9323 /* attach new data to the primary machine and reshare it */
9324 mPeer->mUserData.attach(mUserData);
9325 mPeer->mHWData.attach(mHWData);
9326 /* mMediaData is reshared by fixupMedia */
9327 // mPeer->mMediaData.attach(mMediaData);
9328 Assert(mPeer->mMediaData.data() == mMediaData.data());
9329 }
9330}
9331
9332/**
9333 * Copies all the hardware data from the given machine.
9334 *
9335 * Currently, only called when the VM is being restored from a snapshot. In
9336 * particular, this implies that the VM is not running during this method's
9337 * call.
9338 *
9339 * @note This method must be called from under this object's lock.
9340 *
9341 * @note This method doesn't call #commit(), so all data remains backed up and
9342 * unsaved.
9343 */
9344void Machine::copyFrom(Machine *aThat)
9345{
9346 AssertReturnVoid(!isSnapshotMachine());
9347 AssertReturnVoid(aThat->isSnapshotMachine());
9348
9349 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
9350
9351 mHWData.assignCopy(aThat->mHWData);
9352
9353 // create copies of all shared folders (mHWData after attiching a copy
9354 // contains just references to original objects)
9355 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
9356 it != mHWData->mSharedFolders.end();
9357 ++it)
9358 {
9359 ComObjPtr<SharedFolder> folder;
9360 folder.createObject();
9361 HRESULT rc = folder->initCopy(getMachine(), *it);
9362 AssertComRC(rc);
9363 *it = folder;
9364 }
9365
9366 mBIOSSettings->copyFrom(aThat->mBIOSSettings);
9367#ifdef VBOX_WITH_VRDP
9368 mVRDPServer->copyFrom(aThat->mVRDPServer);
9369#endif
9370 mAudioAdapter->copyFrom(aThat->mAudioAdapter);
9371 mUSBController->copyFrom(aThat->mUSBController);
9372
9373 /* create private copies of all controllers */
9374 mStorageControllers.backup();
9375 mStorageControllers->clear();
9376 for (StorageControllerList::iterator it = aThat->mStorageControllers->begin();
9377 it != aThat->mStorageControllers->end();
9378 ++it)
9379 {
9380 ComObjPtr<StorageController> ctrl;
9381 ctrl.createObject();
9382 ctrl->initCopy(this, *it);
9383 mStorageControllers->push_back(ctrl);
9384 }
9385
9386 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9387 mNetworkAdapters[slot]->copyFrom(aThat->mNetworkAdapters[slot]);
9388 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9389 mSerialPorts[slot]->copyFrom(aThat->mSerialPorts[slot]);
9390 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9391 mParallelPorts[slot]->copyFrom(aThat->mParallelPorts[slot]);
9392}
9393
9394#ifdef VBOX_WITH_RESOURCE_USAGE_API
9395
9396void Machine::registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
9397{
9398 AssertReturnVoid(isWriteLockOnCurrentThread());
9399 AssertPtrReturnVoid(aCollector);
9400
9401 pm::CollectorHAL *hal = aCollector->getHAL();
9402 /* Create sub metrics */
9403 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
9404 "Percentage of processor time spent in user mode by the VM process.");
9405 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
9406 "Percentage of processor time spent in kernel mode by the VM process.");
9407 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
9408 "Size of resident portion of VM process in memory.");
9409 /* Create and register base metrics */
9410 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
9411 cpuLoadUser, cpuLoadKernel);
9412 aCollector->registerBaseMetric(cpuLoad);
9413 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
9414 ramUsageUsed);
9415 aCollector->registerBaseMetric(ramUsage);
9416
9417 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
9418 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9419 new pm::AggregateAvg()));
9420 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9421 new pm::AggregateMin()));
9422 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
9423 new pm::AggregateMax()));
9424 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
9425 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9426 new pm::AggregateAvg()));
9427 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9428 new pm::AggregateMin()));
9429 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
9430 new pm::AggregateMax()));
9431
9432 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
9433 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9434 new pm::AggregateAvg()));
9435 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9436 new pm::AggregateMin()));
9437 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
9438 new pm::AggregateMax()));
9439
9440
9441 /* Guest metrics */
9442 mGuestHAL = new pm::CollectorGuestHAL(this, hal);
9443
9444 /* Create sub metrics */
9445 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/CPU/Load/User",
9446 "Percentage of processor time spent in user mode as seen by the guest.");
9447 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/CPU/Load/Kernel",
9448 "Percentage of processor time spent in kernel mode as seen by the guest.");
9449 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/CPU/Load/Idle",
9450 "Percentage of processor time spent idling as seen by the guest.");
9451
9452 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
9453 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
9454 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
9455 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
9456 pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
9457 pm::SubMetric *guestMemCache = new pm::SubMetric("Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
9458
9459 pm::SubMetric *guestPagedTotal = new pm::SubMetric("Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
9460
9461 /* Create and register base metrics */
9462 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mGuestHAL, aMachine, guestLoadUser, guestLoadKernel, guestLoadIdle);
9463 aCollector->registerBaseMetric(guestCpuLoad);
9464
9465 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mGuestHAL, aMachine, guestMemTotal, guestMemFree, guestMemBalloon, guestMemShared,
9466 guestMemCache, guestPagedTotal);
9467 aCollector->registerBaseMetric(guestCpuMem);
9468
9469 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
9470 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
9471 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
9472 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
9473
9474 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
9475 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
9476 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
9477 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
9478
9479 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
9480 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
9481 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
9482 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
9483
9484 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
9485 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
9486 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
9487 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
9488
9489 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
9490 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
9491 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
9492 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
9493
9494 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
9495 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
9496 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
9497 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
9498
9499 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, 0));
9500 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateAvg()));
9501 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMin()));
9502 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMax()));
9503
9504 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
9505 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
9506 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
9507 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
9508
9509 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
9510 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
9511 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
9512 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
9513}
9514
9515void Machine::unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
9516{
9517 AssertReturnVoid(isWriteLockOnCurrentThread());
9518
9519 if (aCollector)
9520 {
9521 aCollector->unregisterMetricsFor(aMachine);
9522 aCollector->unregisterBaseMetricsFor(aMachine);
9523 }
9524
9525 if (mGuestHAL)
9526 {
9527 delete mGuestHAL;
9528 mGuestHAL = NULL;
9529 }
9530}
9531
9532#endif /* VBOX_WITH_RESOURCE_USAGE_API */
9533
9534
9535////////////////////////////////////////////////////////////////////////////////
9536
9537DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
9538
9539HRESULT SessionMachine::FinalConstruct()
9540{
9541 LogFlowThisFunc(("\n"));
9542
9543#if defined(RT_OS_WINDOWS)
9544 mIPCSem = NULL;
9545#elif defined(RT_OS_OS2)
9546 mIPCSem = NULLHANDLE;
9547#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9548 mIPCSem = -1;
9549#else
9550# error "Port me!"
9551#endif
9552
9553 return S_OK;
9554}
9555
9556void SessionMachine::FinalRelease()
9557{
9558 LogFlowThisFunc(("\n"));
9559
9560 uninit(Uninit::Unexpected);
9561}
9562
9563/**
9564 * @note Must be called only by Machine::openSession() from its own write lock.
9565 */
9566HRESULT SessionMachine::init(Machine *aMachine)
9567{
9568 LogFlowThisFuncEnter();
9569 LogFlowThisFunc(("mName={%ls}\n", aMachine->mUserData->mName.raw()));
9570
9571 AssertReturn(aMachine, E_INVALIDARG);
9572
9573 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
9574
9575 /* Enclose the state transition NotReady->InInit->Ready */
9576 AutoInitSpan autoInitSpan(this);
9577 AssertReturn(autoInitSpan.isOk(), E_FAIL);
9578
9579 /* create the interprocess semaphore */
9580#if defined(RT_OS_WINDOWS)
9581 mIPCSemName = aMachine->mData->m_strConfigFileFull;
9582 for (size_t i = 0; i < mIPCSemName.length(); i++)
9583 if (mIPCSemName[i] == '\\')
9584 mIPCSemName[i] = '/';
9585 mIPCSem = ::CreateMutex(NULL, FALSE, mIPCSemName);
9586 ComAssertMsgRet(mIPCSem,
9587 ("Cannot create IPC mutex '%ls', err=%d",
9588 mIPCSemName.raw(), ::GetLastError()),
9589 E_FAIL);
9590#elif defined(RT_OS_OS2)
9591 Utf8Str ipcSem = Utf8StrFmt("\\SEM32\\VBOX\\VM\\{%RTuuid}",
9592 aMachine->mData->mUuid.raw());
9593 mIPCSemName = ipcSem;
9594 APIRET arc = ::DosCreateMutexSem((PSZ)ipcSem.raw(), &mIPCSem, 0, FALSE);
9595 ComAssertMsgRet(arc == NO_ERROR,
9596 ("Cannot create IPC mutex '%s', arc=%ld",
9597 ipcSem.raw(), arc),
9598 E_FAIL);
9599#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9600# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9601# if defined(RT_OS_FREEBSD) && (HC_ARCH_BITS == 64)
9602 /** @todo Check that this still works correctly. */
9603 AssertCompileSize(key_t, 8);
9604# else
9605 AssertCompileSize(key_t, 4);
9606# endif
9607 key_t key;
9608 mIPCSem = -1;
9609 mIPCKey = "0";
9610 for (uint32_t i = 0; i < 1 << 24; i++)
9611 {
9612 key = ((uint32_t)'V' << 24) | i;
9613 int sem = ::semget(key, 1, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
9614 if (sem >= 0 || (errno != EEXIST && errno != EACCES))
9615 {
9616 mIPCSem = sem;
9617 if (sem >= 0)
9618 mIPCKey = BstrFmt("%u", key);
9619 break;
9620 }
9621 }
9622# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9623 Utf8Str semName = aMachine->mData->m_strConfigFileFull;
9624 char *pszSemName = NULL;
9625 RTStrUtf8ToCurrentCP(&pszSemName, semName);
9626 key_t key = ::ftok(pszSemName, 'V');
9627 RTStrFree(pszSemName);
9628
9629 mIPCSem = ::semget(key, 1, S_IRWXU | S_IRWXG | S_IRWXO | IPC_CREAT);
9630# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
9631
9632 int errnoSave = errno;
9633 if (mIPCSem < 0 && errnoSave == ENOSYS)
9634 {
9635 setError(E_FAIL,
9636 tr("Cannot create IPC semaphore. Most likely your host kernel lacks "
9637 "support for SysV IPC. Check the host kernel configuration for "
9638 "CONFIG_SYSVIPC=y"));
9639 return E_FAIL;
9640 }
9641 /* ENOSPC can also be the result of VBoxSVC crashes without properly freeing
9642 * the IPC semaphores */
9643 if (mIPCSem < 0 && errnoSave == ENOSPC)
9644 {
9645#ifdef RT_OS_LINUX
9646 setError(E_FAIL,
9647 tr("Cannot create IPC semaphore because the system limit for the "
9648 "maximum number of semaphore sets (SEMMNI), or the system wide "
9649 "maximum number of sempahores (SEMMNS) would be exceeded. The "
9650 "current set of SysV IPC semaphores can be determined from "
9651 "the file /proc/sysvipc/sem"));
9652#else
9653 setError(E_FAIL,
9654 tr("Cannot create IPC semaphore because the system-imposed limit "
9655 "on the maximum number of allowed semaphores or semaphore "
9656 "identifiers system-wide would be exceeded"));
9657#endif
9658 return E_FAIL;
9659 }
9660 ComAssertMsgRet(mIPCSem >= 0, ("Cannot create IPC semaphore, errno=%d", errnoSave),
9661 E_FAIL);
9662 /* set the initial value to 1 */
9663 int rv = ::semctl(mIPCSem, 0, SETVAL, 1);
9664 ComAssertMsgRet(rv == 0, ("Cannot init IPC semaphore, errno=%d", errno),
9665 E_FAIL);
9666#else
9667# error "Port me!"
9668#endif
9669
9670 /* memorize the peer Machine */
9671 unconst(mPeer) = aMachine;
9672 /* share the parent pointer */
9673 unconst(mParent) = aMachine->mParent;
9674
9675 /* take the pointers to data to share */
9676 mData.share(aMachine->mData);
9677 mSSData.share(aMachine->mSSData);
9678
9679 mUserData.share(aMachine->mUserData);
9680 mHWData.share(aMachine->mHWData);
9681 mMediaData.share(aMachine->mMediaData);
9682
9683 mStorageControllers.allocate();
9684 for (StorageControllerList::const_iterator it = aMachine->mStorageControllers->begin();
9685 it != aMachine->mStorageControllers->end();
9686 ++it)
9687 {
9688 ComObjPtr<StorageController> ctl;
9689 ctl.createObject();
9690 ctl->init(this, *it);
9691 mStorageControllers->push_back(ctl);
9692 }
9693
9694 unconst(mBIOSSettings).createObject();
9695 mBIOSSettings->init(this, aMachine->mBIOSSettings);
9696#ifdef VBOX_WITH_VRDP
9697 /* create another VRDPServer object that will be mutable */
9698 unconst(mVRDPServer).createObject();
9699 mVRDPServer->init(this, aMachine->mVRDPServer);
9700#endif
9701 /* create another audio adapter object that will be mutable */
9702 unconst(mAudioAdapter).createObject();
9703 mAudioAdapter->init(this, aMachine->mAudioAdapter);
9704 /* create a list of serial ports that will be mutable */
9705 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
9706 {
9707 unconst(mSerialPorts[slot]).createObject();
9708 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
9709 }
9710 /* create a list of parallel ports that will be mutable */
9711 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
9712 {
9713 unconst(mParallelPorts[slot]).createObject();
9714 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
9715 }
9716 /* create another USB controller object that will be mutable */
9717 unconst(mUSBController).createObject();
9718 mUSBController->init(this, aMachine->mUSBController);
9719
9720 /* create a list of network adapters that will be mutable */
9721 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
9722 {
9723 unconst(mNetworkAdapters[slot]).createObject();
9724 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
9725 }
9726
9727 /* Confirm a successful initialization when it's the case */
9728 autoInitSpan.setSucceeded();
9729
9730 LogFlowThisFuncLeave();
9731 return S_OK;
9732}
9733
9734/**
9735 * Uninitializes this session object. If the reason is other than
9736 * Uninit::Unexpected, then this method MUST be called from #checkForDeath().
9737 *
9738 * @param aReason uninitialization reason
9739 *
9740 * @note Locks mParent + this object for writing.
9741 */
9742void SessionMachine::uninit(Uninit::Reason aReason)
9743{
9744 LogFlowThisFuncEnter();
9745 LogFlowThisFunc(("reason=%d\n", aReason));
9746
9747 /*
9748 * Strongly reference ourselves to prevent this object deletion after
9749 * mData->mSession.mMachine.setNull() below (which can release the last
9750 * reference and call the destructor). Important: this must be done before
9751 * accessing any members (and before AutoUninitSpan that does it as well).
9752 * This self reference will be released as the very last step on return.
9753 */
9754 ComObjPtr<SessionMachine> selfRef = this;
9755
9756 /* Enclose the state transition Ready->InUninit->NotReady */
9757 AutoUninitSpan autoUninitSpan(this);
9758 if (autoUninitSpan.uninitDone())
9759 {
9760 LogFlowThisFunc(("Already uninitialized\n"));
9761 LogFlowThisFuncLeave();
9762 return;
9763 }
9764
9765 if (autoUninitSpan.initFailed())
9766 {
9767 /* We've been called by init() because it's failed. It's not really
9768 * necessary (nor it's safe) to perform the regular uninit sequense
9769 * below, the following is enough.
9770 */
9771 LogFlowThisFunc(("Initialization failed.\n"));
9772#if defined(RT_OS_WINDOWS)
9773 if (mIPCSem)
9774 ::CloseHandle(mIPCSem);
9775 mIPCSem = NULL;
9776#elif defined(RT_OS_OS2)
9777 if (mIPCSem != NULLHANDLE)
9778 ::DosCloseMutexSem(mIPCSem);
9779 mIPCSem = NULLHANDLE;
9780#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9781 if (mIPCSem >= 0)
9782 ::semctl(mIPCSem, 0, IPC_RMID);
9783 mIPCSem = -1;
9784# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9785 mIPCKey = "0";
9786# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
9787#else
9788# error "Port me!"
9789#endif
9790 uninitDataAndChildObjects();
9791 mData.free();
9792 unconst(mParent) = NULL;
9793 unconst(mPeer) = NULL;
9794 LogFlowThisFuncLeave();
9795 return;
9796 }
9797
9798 MachineState_T lastState;
9799 {
9800 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
9801 lastState = mData->mMachineState;
9802 }
9803 NOREF(lastState);
9804
9805#ifdef VBOX_WITH_USB
9806 // release all captured USB devices, but do this before requesting the locks below
9807 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
9808 {
9809 /* Console::captureUSBDevices() is called in the VM process only after
9810 * setting the machine state to Starting or Restoring.
9811 * Console::detachAllUSBDevices() will be called upon successful
9812 * termination. So, we need to release USB devices only if there was
9813 * an abnormal termination of a running VM.
9814 *
9815 * This is identical to SessionMachine::DetachAllUSBDevices except
9816 * for the aAbnormal argument. */
9817 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
9818 AssertComRC(rc);
9819 NOREF(rc);
9820
9821 USBProxyService *service = mParent->host()->usbProxyService();
9822 if (service)
9823 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
9824 }
9825#endif /* VBOX_WITH_USB */
9826
9827 // we need to lock this object in uninit() because the lock is shared
9828 // with mPeer (as well as data we modify below). mParent->addProcessToReap()
9829 // and others need mParent lock, and USB needs host lock.
9830 AutoMultiWriteLock3 multilock(mParent, mParent->host(), this COMMA_LOCKVAL_SRC_POS);
9831
9832 // Trigger async cleanup tasks, avoid doing things here which are not
9833 // vital to be done immediately and maybe need more locks. This calls
9834 // Machine::unregisterMetrics().
9835 mParent->onMachineUninit(mPeer);
9836
9837 if (aReason == Uninit::Abnormal)
9838 {
9839 LogWarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n",
9840 Global::IsOnlineOrTransient(lastState)));
9841
9842 /* reset the state to Aborted */
9843 if (mData->mMachineState != MachineState_Aborted)
9844 setMachineState(MachineState_Aborted);
9845 }
9846
9847 // any machine settings modified?
9848 if (mData->flModifications)
9849 {
9850 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
9851 rollback(false /* aNotify */);
9852 }
9853
9854 Assert(mSnapshotData.mStateFilePath.isEmpty() || !mSnapshotData.mSnapshot);
9855 if (!mSnapshotData.mStateFilePath.isEmpty())
9856 {
9857 LogWarningThisFunc(("canceling failed save state request!\n"));
9858 endSavingState(FALSE /* aSuccess */);
9859 }
9860 else if (!mSnapshotData.mSnapshot.isNull())
9861 {
9862 LogWarningThisFunc(("canceling untaken snapshot!\n"));
9863
9864 /* delete all differencing hard disks created (this will also attach
9865 * their parents back by rolling back mMediaData) */
9866 rollbackMedia();
9867 /* delete the saved state file (it might have been already created) */
9868 if (mSnapshotData.mSnapshot->stateFilePath().length())
9869 RTFileDelete(mSnapshotData.mSnapshot->stateFilePath().c_str());
9870
9871 mSnapshotData.mSnapshot->uninit();
9872 }
9873
9874 if (!mData->mSession.mType.isEmpty())
9875 {
9876 /* mType is not null when this machine's process has been started by
9877 * Machine::launchVMProcess(), therefore it is our child. We
9878 * need to queue the PID to reap the process (and avoid zombies on
9879 * Linux). */
9880 Assert(mData->mSession.mPid != NIL_RTPROCESS);
9881 mParent->addProcessToReap(mData->mSession.mPid);
9882 }
9883
9884 mData->mSession.mPid = NIL_RTPROCESS;
9885
9886 if (aReason == Uninit::Unexpected)
9887 {
9888 /* Uninitialization didn't come from #checkForDeath(), so tell the
9889 * client watcher thread to update the set of machines that have open
9890 * sessions. */
9891 mParent->updateClientWatcher();
9892 }
9893
9894 /* uninitialize all remote controls */
9895 if (mData->mSession.mRemoteControls.size())
9896 {
9897 LogFlowThisFunc(("Closing remote sessions (%d):\n",
9898 mData->mSession.mRemoteControls.size()));
9899
9900 Data::Session::RemoteControlList::iterator it =
9901 mData->mSession.mRemoteControls.begin();
9902 while (it != mData->mSession.mRemoteControls.end())
9903 {
9904 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
9905 HRESULT rc = (*it)->Uninitialize();
9906 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
9907 if (FAILED(rc))
9908 LogWarningThisFunc(("Forgot to close the remote session?\n"));
9909 ++it;
9910 }
9911 mData->mSession.mRemoteControls.clear();
9912 }
9913
9914 /*
9915 * An expected uninitialization can come only from #checkForDeath().
9916 * Otherwise it means that something's got really wrong (for examlple,
9917 * the Session implementation has released the VirtualBox reference
9918 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
9919 * etc). However, it's also possible, that the client releases the IPC
9920 * semaphore correctly (i.e. before it releases the VirtualBox reference),
9921 * but the VirtualBox release event comes first to the server process.
9922 * This case is practically possible, so we should not assert on an
9923 * unexpected uninit, just log a warning.
9924 */
9925
9926 if ((aReason == Uninit::Unexpected))
9927 LogWarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
9928
9929 if (aReason != Uninit::Normal)
9930 {
9931 mData->mSession.mDirectControl.setNull();
9932 }
9933 else
9934 {
9935 /* this must be null here (see #OnSessionEnd()) */
9936 Assert(mData->mSession.mDirectControl.isNull());
9937 Assert(mData->mSession.mState == SessionState_Unlocking);
9938 Assert(!mData->mSession.mProgress.isNull());
9939 }
9940 if (mData->mSession.mProgress)
9941 {
9942 if (aReason == Uninit::Normal)
9943 mData->mSession.mProgress->notifyComplete(S_OK);
9944 else
9945 mData->mSession.mProgress->notifyComplete(E_FAIL,
9946 COM_IIDOF(ISession),
9947 getComponentName(),
9948 tr("The VM session was aborted"));
9949 mData->mSession.mProgress.setNull();
9950 }
9951
9952 /* remove the association between the peer machine and this session machine */
9953 Assert( (SessionMachine*)mData->mSession.mMachine == this
9954 || aReason == Uninit::Unexpected);
9955
9956 /* reset the rest of session data */
9957 mData->mSession.mMachine.setNull();
9958 mData->mSession.mState = SessionState_Unlocked;
9959 mData->mSession.mType.setNull();
9960
9961 /* close the interprocess semaphore before leaving the exclusive lock */
9962#if defined(RT_OS_WINDOWS)
9963 if (mIPCSem)
9964 ::CloseHandle(mIPCSem);
9965 mIPCSem = NULL;
9966#elif defined(RT_OS_OS2)
9967 if (mIPCSem != NULLHANDLE)
9968 ::DosCloseMutexSem(mIPCSem);
9969 mIPCSem = NULLHANDLE;
9970#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
9971 if (mIPCSem >= 0)
9972 ::semctl(mIPCSem, 0, IPC_RMID);
9973 mIPCSem = -1;
9974# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
9975 mIPCKey = "0";
9976# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
9977#else
9978# error "Port me!"
9979#endif
9980
9981 /* fire an event */
9982 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
9983
9984 uninitDataAndChildObjects();
9985
9986 /* free the essential data structure last */
9987 mData.free();
9988
9989#if 1 /** @todo Please review this change! (bird) */
9990 /* drop the exclusive lock before setting the below two to NULL */
9991 multilock.release();
9992#else
9993 /* leave the exclusive lock before setting the below two to NULL */
9994 multilock.leave();
9995#endif
9996
9997 unconst(mParent) = NULL;
9998 unconst(mPeer) = NULL;
9999
10000 LogFlowThisFuncLeave();
10001}
10002
10003// util::Lockable interface
10004////////////////////////////////////////////////////////////////////////////////
10005
10006/**
10007 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
10008 * with the primary Machine instance (mPeer).
10009 */
10010RWLockHandle *SessionMachine::lockHandle() const
10011{
10012 AssertReturn(mPeer != NULL, NULL);
10013 return mPeer->lockHandle();
10014}
10015
10016// IInternalMachineControl methods
10017////////////////////////////////////////////////////////////////////////////////
10018
10019/**
10020 * @note Locks the same as #setMachineState() does.
10021 */
10022STDMETHODIMP SessionMachine::UpdateState(MachineState_T aMachineState)
10023{
10024 return setMachineState(aMachineState);
10025}
10026
10027/**
10028 * @note Locks this object for reading.
10029 */
10030STDMETHODIMP SessionMachine::GetIPCId(BSTR *aId)
10031{
10032 AutoCaller autoCaller(this);
10033 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10034
10035 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10036
10037#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
10038 mIPCSemName.cloneTo(aId);
10039 return S_OK;
10040#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10041# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10042 mIPCKey.cloneTo(aId);
10043# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10044 mData->m_strConfigFileFull.cloneTo(aId);
10045# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10046 return S_OK;
10047#else
10048# error "Port me!"
10049#endif
10050}
10051
10052/**
10053 * @note Locks this object for writing.
10054 */
10055STDMETHODIMP SessionMachine::BeginPowerUp(IProgress *aProgress)
10056{
10057 LogFlowThisFunc(("aProgress=%p\n", aProgress));
10058 AutoCaller autoCaller(this);
10059 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10060
10061 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10062
10063 if (mData->mSession.mState != SessionState_Locked)
10064 return VBOX_E_INVALID_OBJECT_STATE;
10065
10066 if (!mData->mSession.mProgress.isNull())
10067 mData->mSession.mProgress->setOtherProgressObject(aProgress);
10068
10069 LogFlowThisFunc(("returns S_OK.\n"));
10070 return S_OK;
10071}
10072
10073
10074/**
10075 * @note Locks this object for writing.
10076 */
10077STDMETHODIMP SessionMachine::EndPowerUp(LONG iResult)
10078{
10079 AutoCaller autoCaller(this);
10080 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10081
10082 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10083
10084 if (mData->mSession.mState != SessionState_Locked)
10085 return VBOX_E_INVALID_OBJECT_STATE;
10086
10087 /* Finalize the openRemoteSession progress object. */
10088 if (mData->mSession.mProgress)
10089 {
10090 mData->mSession.mProgress->notifyComplete((HRESULT)iResult);
10091 mData->mSession.mProgress.setNull();
10092
10093 if (SUCCEEDED((HRESULT)iResult))
10094 {
10095#ifdef VBOX_WITH_RESOURCE_USAGE_API
10096 /* The VM has been powered up successfully, so it makes sense
10097 * now to offer the performance metrics for a running machine
10098 * object. Doing it earlier wouldn't be safe. */
10099 registerMetrics(mParent->performanceCollector(), mPeer,
10100 mData->mSession.mPid);
10101#endif /* VBOX_WITH_RESOURCE_USAGE_API */
10102
10103 }
10104 }
10105 return S_OK;
10106}
10107
10108/**
10109 * Goes through the USB filters of the given machine to see if the given
10110 * device matches any filter or not.
10111 *
10112 * @note Locks the same as USBController::hasMatchingFilter() does.
10113 */
10114STDMETHODIMP SessionMachine::RunUSBDeviceFilters(IUSBDevice *aUSBDevice,
10115 BOOL *aMatched,
10116 ULONG *aMaskedIfs)
10117{
10118 LogFlowThisFunc(("\n"));
10119
10120 CheckComArgNotNull(aUSBDevice);
10121 CheckComArgOutPointerValid(aMatched);
10122
10123 AutoCaller autoCaller(this);
10124 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10125
10126#ifdef VBOX_WITH_USB
10127 *aMatched = mUSBController->hasMatchingFilter(aUSBDevice, aMaskedIfs);
10128#else
10129 NOREF(aUSBDevice);
10130 NOREF(aMaskedIfs);
10131 *aMatched = FALSE;
10132#endif
10133
10134 return S_OK;
10135}
10136
10137/**
10138 * @note Locks the same as Host::captureUSBDevice() does.
10139 */
10140STDMETHODIMP SessionMachine::CaptureUSBDevice(IN_BSTR aId)
10141{
10142 LogFlowThisFunc(("\n"));
10143
10144 AutoCaller autoCaller(this);
10145 AssertComRCReturnRC(autoCaller.rc());
10146
10147#ifdef VBOX_WITH_USB
10148 /* if captureDeviceForVM() fails, it must have set extended error info */
10149 MultiResult rc = mParent->host()->checkUSBProxyService();
10150 if (FAILED(rc)) return rc;
10151
10152 USBProxyService *service = mParent->host()->usbProxyService();
10153 AssertReturn(service, E_FAIL);
10154 return service->captureDeviceForVM(this, Guid(aId));
10155#else
10156 NOREF(aId);
10157 return E_NOTIMPL;
10158#endif
10159}
10160
10161/**
10162 * @note Locks the same as Host::detachUSBDevice() does.
10163 */
10164STDMETHODIMP SessionMachine::DetachUSBDevice(IN_BSTR aId, BOOL aDone)
10165{
10166 LogFlowThisFunc(("\n"));
10167
10168 AutoCaller autoCaller(this);
10169 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10170
10171#ifdef VBOX_WITH_USB
10172 USBProxyService *service = mParent->host()->usbProxyService();
10173 AssertReturn(service, E_FAIL);
10174 return service->detachDeviceFromVM(this, Guid(aId), !!aDone);
10175#else
10176 NOREF(aId);
10177 NOREF(aDone);
10178 return E_NOTIMPL;
10179#endif
10180}
10181
10182/**
10183 * Inserts all machine filters to the USB proxy service and then calls
10184 * Host::autoCaptureUSBDevices().
10185 *
10186 * Called by Console from the VM process upon VM startup.
10187 *
10188 * @note Locks what called methods lock.
10189 */
10190STDMETHODIMP SessionMachine::AutoCaptureUSBDevices()
10191{
10192 LogFlowThisFunc(("\n"));
10193
10194 AutoCaller autoCaller(this);
10195 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10196
10197#ifdef VBOX_WITH_USB
10198 HRESULT rc = mUSBController->notifyProxy(true /* aInsertFilters */);
10199 AssertComRC(rc);
10200 NOREF(rc);
10201
10202 USBProxyService *service = mParent->host()->usbProxyService();
10203 AssertReturn(service, E_FAIL);
10204 return service->autoCaptureDevicesForVM(this);
10205#else
10206 return S_OK;
10207#endif
10208}
10209
10210/**
10211 * Removes all machine filters from the USB proxy service and then calls
10212 * Host::detachAllUSBDevices().
10213 *
10214 * Called by Console from the VM process upon normal VM termination or by
10215 * SessionMachine::uninit() upon abnormal VM termination (from under the
10216 * Machine/SessionMachine lock).
10217 *
10218 * @note Locks what called methods lock.
10219 */
10220STDMETHODIMP SessionMachine::DetachAllUSBDevices(BOOL aDone)
10221{
10222 LogFlowThisFunc(("\n"));
10223
10224 AutoCaller autoCaller(this);
10225 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10226
10227#ifdef VBOX_WITH_USB
10228 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
10229 AssertComRC(rc);
10230 NOREF(rc);
10231
10232 USBProxyService *service = mParent->host()->usbProxyService();
10233 AssertReturn(service, E_FAIL);
10234 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
10235#else
10236 NOREF(aDone);
10237 return S_OK;
10238#endif
10239}
10240
10241/**
10242 * @note Locks this object for writing.
10243 */
10244STDMETHODIMP SessionMachine::OnSessionEnd(ISession *aSession,
10245 IProgress **aProgress)
10246{
10247 LogFlowThisFuncEnter();
10248
10249 AssertReturn(aSession, E_INVALIDARG);
10250 AssertReturn(aProgress, E_INVALIDARG);
10251
10252 AutoCaller autoCaller(this);
10253
10254 LogFlowThisFunc(("callerstate=%d\n", autoCaller.state()));
10255 /*
10256 * We don't assert below because it might happen that a non-direct session
10257 * informs us it is closed right after we've been uninitialized -- it's ok.
10258 */
10259 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10260
10261 /* get IInternalSessionControl interface */
10262 ComPtr<IInternalSessionControl> control(aSession);
10263
10264 ComAssertRet(!control.isNull(), E_INVALIDARG);
10265
10266 /* Creating a Progress object requires the VirtualBox lock, and
10267 * thus locking it here is required by the lock order rules. */
10268 AutoMultiWriteLock2 alock(mParent->lockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
10269
10270 if (control == mData->mSession.mDirectControl)
10271 {
10272 ComAssertRet(aProgress, E_POINTER);
10273
10274 /* The direct session is being normally closed by the client process
10275 * ----------------------------------------------------------------- */
10276
10277 /* go to the closing state (essential for all open*Session() calls and
10278 * for #checkForDeath()) */
10279 Assert(mData->mSession.mState == SessionState_Locked);
10280 mData->mSession.mState = SessionState_Unlocking;
10281
10282 /* set direct control to NULL to release the remote instance */
10283 mData->mSession.mDirectControl.setNull();
10284 LogFlowThisFunc(("Direct control is set to NULL\n"));
10285
10286 if (mData->mSession.mProgress)
10287 {
10288 /* finalize the progress, someone might wait if a frontend
10289 * closes the session before powering on the VM. */
10290 mData->mSession.mProgress->notifyComplete(E_FAIL,
10291 COM_IIDOF(ISession),
10292 getComponentName(),
10293 tr("The VM session was closed before any attempt to power it on"));
10294 mData->mSession.mProgress.setNull();
10295 }
10296
10297 /* Create the progress object the client will use to wait until
10298 * #checkForDeath() is called to uninitialize this session object after
10299 * it releases the IPC semaphore.
10300 * Note! Because we're "reusing" mProgress here, this must be a proxy
10301 * object just like for openRemoteSession. */
10302 Assert(mData->mSession.mProgress.isNull());
10303 ComObjPtr<ProgressProxy> progress;
10304 progress.createObject();
10305 ComPtr<IUnknown> pPeer(mPeer);
10306 progress->init(mParent, pPeer,
10307 Bstr(tr("Closing session")),
10308 FALSE /* aCancelable */);
10309 progress.queryInterfaceTo(aProgress);
10310 mData->mSession.mProgress = progress;
10311 }
10312 else
10313 {
10314 /* the remote session is being normally closed */
10315 Data::Session::RemoteControlList::iterator it =
10316 mData->mSession.mRemoteControls.begin();
10317 while (it != mData->mSession.mRemoteControls.end())
10318 {
10319 if (control == *it)
10320 break;
10321 ++it;
10322 }
10323 BOOL found = it != mData->mSession.mRemoteControls.end();
10324 ComAssertMsgRet(found, ("The session is not found in the session list!"),
10325 E_INVALIDARG);
10326 mData->mSession.mRemoteControls.remove(*it);
10327 }
10328
10329 LogFlowThisFuncLeave();
10330 return S_OK;
10331}
10332
10333/**
10334 * @note Locks this object for writing.
10335 */
10336STDMETHODIMP SessionMachine::BeginSavingState(IProgress *aProgress, BSTR *aStateFilePath)
10337{
10338 LogFlowThisFuncEnter();
10339
10340 AssertReturn(aProgress, E_INVALIDARG);
10341 AssertReturn(aStateFilePath, E_POINTER);
10342
10343 AutoCaller autoCaller(this);
10344 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10345
10346 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10347
10348 AssertReturn( mData->mMachineState == MachineState_Paused
10349 && mSnapshotData.mLastState == MachineState_Null
10350 && mSnapshotData.mProgressId.isEmpty()
10351 && mSnapshotData.mStateFilePath.isEmpty(),
10352 E_FAIL);
10353
10354 /* memorize the progress ID and add it to the global collection */
10355 Bstr progressId;
10356 HRESULT rc = aProgress->COMGETTER(Id)(progressId.asOutParam());
10357 AssertComRCReturn(rc, rc);
10358 rc = mParent->addProgress(aProgress);
10359 AssertComRCReturn(rc, rc);
10360
10361 Bstr stateFilePath;
10362 /* stateFilePath is null when the machine is not running */
10363 if (mData->mMachineState == MachineState_Paused)
10364 {
10365 stateFilePath = Utf8StrFmt("%ls%c{%RTuuid}.sav",
10366 mUserData->mSnapshotFolderFull.raw(),
10367 RTPATH_DELIMITER, mData->mUuid.raw());
10368 }
10369
10370 /* fill in the snapshot data */
10371 mSnapshotData.mLastState = mData->mMachineState;
10372 mSnapshotData.mProgressId = Guid(progressId);
10373 mSnapshotData.mStateFilePath = stateFilePath;
10374
10375 /* set the state to Saving (this is expected by Console::SaveState()) */
10376 setMachineState(MachineState_Saving);
10377
10378 stateFilePath.cloneTo(aStateFilePath);
10379
10380 return S_OK;
10381}
10382
10383/**
10384 * @note Locks mParent + this object for writing.
10385 */
10386STDMETHODIMP SessionMachine::EndSavingState(BOOL aSuccess)
10387{
10388 LogFlowThisFunc(("\n"));
10389
10390 AutoCaller autoCaller(this);
10391 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10392
10393 /* endSavingState() need mParent lock */
10394 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
10395
10396 AssertReturn( mData->mMachineState == MachineState_Saving
10397 && mSnapshotData.mLastState != MachineState_Null
10398 && !mSnapshotData.mProgressId.isEmpty()
10399 && !mSnapshotData.mStateFilePath.isEmpty(),
10400 E_FAIL);
10401
10402 /*
10403 * on success, set the state to Saved;
10404 * on failure, set the state to the state we had when BeginSavingState() was
10405 * called (this is expected by Console::SaveState() and
10406 * Console::saveStateThread())
10407 */
10408 if (aSuccess)
10409 setMachineState(MachineState_Saved);
10410 else
10411 setMachineState(mSnapshotData.mLastState);
10412
10413 return endSavingState(aSuccess);
10414}
10415
10416/**
10417 * @note Locks this object for writing.
10418 */
10419STDMETHODIMP SessionMachine::AdoptSavedState(IN_BSTR aSavedStateFile)
10420{
10421 LogFlowThisFunc(("\n"));
10422
10423 CheckComArgStrNotEmptyOrNull(aSavedStateFile);
10424
10425 AutoCaller autoCaller(this);
10426 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10427
10428 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10429
10430 AssertReturn( mData->mMachineState == MachineState_PoweredOff
10431 || mData->mMachineState == MachineState_Teleported
10432 || mData->mMachineState == MachineState_Aborted
10433 , E_FAIL); /** @todo setError. */
10434
10435 Utf8Str stateFilePathFull = aSavedStateFile;
10436 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
10437 if (RT_FAILURE(vrc))
10438 return setError(VBOX_E_FILE_ERROR,
10439 tr("Invalid saved state file path '%ls' (%Rrc)"),
10440 aSavedStateFile,
10441 vrc);
10442
10443 mSSData->mStateFilePath = stateFilePathFull;
10444
10445 /* The below setMachineState() will detect the state transition and will
10446 * update the settings file */
10447
10448 return setMachineState(MachineState_Saved);
10449}
10450
10451STDMETHODIMP SessionMachine::PullGuestProperties(ComSafeArrayOut(BSTR, aNames),
10452 ComSafeArrayOut(BSTR, aValues),
10453 ComSafeArrayOut(ULONG64, aTimestamps),
10454 ComSafeArrayOut(BSTR, aFlags))
10455{
10456 LogFlowThisFunc(("\n"));
10457
10458#ifdef VBOX_WITH_GUEST_PROPS
10459 using namespace guestProp;
10460
10461 AutoCaller autoCaller(this);
10462 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10463
10464 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10465
10466 AssertReturn(!ComSafeArrayOutIsNull(aNames), E_POINTER);
10467 AssertReturn(!ComSafeArrayOutIsNull(aValues), E_POINTER);
10468 AssertReturn(!ComSafeArrayOutIsNull(aTimestamps), E_POINTER);
10469 AssertReturn(!ComSafeArrayOutIsNull(aFlags), E_POINTER);
10470
10471 size_t cEntries = mHWData->mGuestProperties.size();
10472 com::SafeArray<BSTR> names(cEntries);
10473 com::SafeArray<BSTR> values(cEntries);
10474 com::SafeArray<ULONG64> timestamps(cEntries);
10475 com::SafeArray<BSTR> flags(cEntries);
10476 unsigned i = 0;
10477 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
10478 it != mHWData->mGuestProperties.end();
10479 ++it)
10480 {
10481 char szFlags[MAX_FLAGS_LEN + 1];
10482 it->strName.cloneTo(&names[i]);
10483 it->strValue.cloneTo(&values[i]);
10484 timestamps[i] = it->mTimestamp;
10485 /* If it is NULL, keep it NULL. */
10486 if (it->mFlags)
10487 {
10488 writeFlags(it->mFlags, szFlags);
10489 Bstr(szFlags).cloneTo(&flags[i]);
10490 }
10491 else
10492 flags[i] = NULL;
10493 ++i;
10494 }
10495 names.detachTo(ComSafeArrayOutArg(aNames));
10496 values.detachTo(ComSafeArrayOutArg(aValues));
10497 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
10498 flags.detachTo(ComSafeArrayOutArg(aFlags));
10499 return S_OK;
10500#else
10501 ReturnComNotImplemented();
10502#endif
10503}
10504
10505STDMETHODIMP SessionMachine::PushGuestProperty(IN_BSTR aName,
10506 IN_BSTR aValue,
10507 ULONG64 aTimestamp,
10508 IN_BSTR aFlags)
10509{
10510 LogFlowThisFunc(("\n"));
10511
10512#ifdef VBOX_WITH_GUEST_PROPS
10513 using namespace guestProp;
10514
10515 CheckComArgStrNotEmptyOrNull(aName);
10516 if (aValue != NULL && (!VALID_PTR(aValue) || !VALID_PTR(aFlags)))
10517 return E_POINTER; /* aValue can be NULL to indicate deletion */
10518
10519 try
10520 {
10521 /*
10522 * Convert input up front.
10523 */
10524 Utf8Str utf8Name(aName);
10525 uint32_t fFlags = NILFLAG;
10526 if (aFlags)
10527 {
10528 Utf8Str utf8Flags(aFlags);
10529 int vrc = validateFlags(utf8Flags.raw(), &fFlags);
10530 AssertRCReturn(vrc, E_INVALIDARG);
10531 }
10532
10533 /*
10534 * Now grab the object lock, validate the state and do the update.
10535 */
10536 AutoCaller autoCaller(this);
10537 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10538
10539 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10540
10541 switch (mData->mMachineState)
10542 {
10543 case MachineState_Paused:
10544 case MachineState_Running:
10545 case MachineState_Teleporting:
10546 case MachineState_TeleportingPausedVM:
10547 case MachineState_LiveSnapshotting:
10548 case MachineState_DeletingSnapshotOnline:
10549 case MachineState_DeletingSnapshotPaused:
10550 case MachineState_Saving:
10551 break;
10552
10553 default:
10554 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
10555 VBOX_E_INVALID_VM_STATE);
10556 }
10557
10558 setModified(IsModified_MachineData);
10559 mHWData.backup();
10560
10561 /** @todo r=bird: The careful memory handling doesn't work out here because
10562 * the catch block won't undo any damange we've done. So, if push_back throws
10563 * bad_alloc then you've lost the value.
10564 *
10565 * Another thing. Doing a linear search here isn't extremely efficient, esp.
10566 * since values that changes actually bubbles to the end of the list. Using
10567 * something that has an efficient lookup and can tollerate a bit of updates
10568 * would be nice. RTStrSpace is one suggestion (it's not perfect). Some
10569 * combination of RTStrCache (for sharing names and getting uniqueness into
10570 * the bargain) and hash/tree is another. */
10571 for (HWData::GuestPropertyList::iterator iter = mHWData->mGuestProperties.begin();
10572 iter != mHWData->mGuestProperties.end();
10573 ++iter)
10574 if (utf8Name == iter->strName)
10575 {
10576 mHWData->mGuestProperties.erase(iter);
10577 mData->mGuestPropertiesModified = TRUE;
10578 break;
10579 }
10580 if (aValue != NULL)
10581 {
10582 HWData::GuestProperty property = { aName, aValue, aTimestamp, fFlags };
10583 mHWData->mGuestProperties.push_back(property);
10584 mData->mGuestPropertiesModified = TRUE;
10585 }
10586
10587 /*
10588 * Send a callback notification if appropriate
10589 */
10590 if ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
10591 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.raw(),
10592 RTSTR_MAX,
10593 utf8Name.raw(),
10594 RTSTR_MAX, NULL)
10595 )
10596 {
10597 alock.leave();
10598
10599 mParent->onGuestPropertyChange(mData->mUuid,
10600 aName,
10601 aValue,
10602 aFlags);
10603 }
10604 }
10605 catch (...)
10606 {
10607 return VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
10608 }
10609 return S_OK;
10610#else
10611 ReturnComNotImplemented();
10612#endif
10613}
10614
10615// public methods only for internal purposes
10616/////////////////////////////////////////////////////////////////////////////
10617
10618/**
10619 * Called from the client watcher thread to check for expected or unexpected
10620 * death of the client process that has a direct session to this machine.
10621 *
10622 * On Win32 and on OS/2, this method is called only when we've got the
10623 * mutex (i.e. the client has either died or terminated normally) so it always
10624 * returns @c true (the client is terminated, the session machine is
10625 * uninitialized).
10626 *
10627 * On other platforms, the method returns @c true if the client process has
10628 * terminated normally or abnormally and the session machine was uninitialized,
10629 * and @c false if the client process is still alive.
10630 *
10631 * @note Locks this object for writing.
10632 */
10633bool SessionMachine::checkForDeath()
10634{
10635 Uninit::Reason reason;
10636 bool terminated = false;
10637
10638 /* Enclose autoCaller with a block because calling uninit() from under it
10639 * will deadlock. */
10640 {
10641 AutoCaller autoCaller(this);
10642 if (!autoCaller.isOk())
10643 {
10644 /* return true if not ready, to cause the client watcher to exclude
10645 * the corresponding session from watching */
10646 LogFlowThisFunc(("Already uninitialized!\n"));
10647 return true;
10648 }
10649
10650 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10651
10652 /* Determine the reason of death: if the session state is Closing here,
10653 * everything is fine. Otherwise it means that the client did not call
10654 * OnSessionEnd() before it released the IPC semaphore. This may happen
10655 * either because the client process has abnormally terminated, or
10656 * because it simply forgot to call ISession::Close() before exiting. We
10657 * threat the latter also as an abnormal termination (see
10658 * Session::uninit() for details). */
10659 reason = mData->mSession.mState == SessionState_Unlocking ?
10660 Uninit::Normal :
10661 Uninit::Abnormal;
10662
10663#if defined(RT_OS_WINDOWS)
10664
10665 AssertMsg(mIPCSem, ("semaphore must be created"));
10666
10667 /* release the IPC mutex */
10668 ::ReleaseMutex(mIPCSem);
10669
10670 terminated = true;
10671
10672#elif defined(RT_OS_OS2)
10673
10674 AssertMsg(mIPCSem, ("semaphore must be created"));
10675
10676 /* release the IPC mutex */
10677 ::DosReleaseMutexSem(mIPCSem);
10678
10679 terminated = true;
10680
10681#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10682
10683 AssertMsg(mIPCSem >= 0, ("semaphore must be created"));
10684
10685 int val = ::semctl(mIPCSem, 0, GETVAL);
10686 if (val > 0)
10687 {
10688 /* the semaphore is signaled, meaning the session is terminated */
10689 terminated = true;
10690 }
10691
10692#else
10693# error "Port me!"
10694#endif
10695
10696 } /* AutoCaller block */
10697
10698 if (terminated)
10699 uninit(reason);
10700
10701 return terminated;
10702}
10703
10704/**
10705 * @note Locks this object for reading.
10706 */
10707HRESULT SessionMachine::onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
10708{
10709 LogFlowThisFunc(("\n"));
10710
10711 AutoCaller autoCaller(this);
10712 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10713
10714 ComPtr<IInternalSessionControl> directControl;
10715 {
10716 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10717 directControl = mData->mSession.mDirectControl;
10718 }
10719
10720 /* ignore notifications sent after #OnSessionEnd() is called */
10721 if (!directControl)
10722 return S_OK;
10723
10724 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
10725}
10726
10727/**
10728 * @note Locks this object for reading.
10729 */
10730HRESULT SessionMachine::onSerialPortChange(ISerialPort *serialPort)
10731{
10732 LogFlowThisFunc(("\n"));
10733
10734 AutoCaller autoCaller(this);
10735 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10736
10737 ComPtr<IInternalSessionControl> directControl;
10738 {
10739 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10740 directControl = mData->mSession.mDirectControl;
10741 }
10742
10743 /* ignore notifications sent after #OnSessionEnd() is called */
10744 if (!directControl)
10745 return S_OK;
10746
10747 return directControl->OnSerialPortChange(serialPort);
10748}
10749
10750/**
10751 * @note Locks this object for reading.
10752 */
10753HRESULT SessionMachine::onParallelPortChange(IParallelPort *parallelPort)
10754{
10755 LogFlowThisFunc(("\n"));
10756
10757 AutoCaller autoCaller(this);
10758 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10759
10760 ComPtr<IInternalSessionControl> directControl;
10761 {
10762 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10763 directControl = mData->mSession.mDirectControl;
10764 }
10765
10766 /* ignore notifications sent after #OnSessionEnd() is called */
10767 if (!directControl)
10768 return S_OK;
10769
10770 return directControl->OnParallelPortChange(parallelPort);
10771}
10772
10773/**
10774 * @note Locks this object for reading.
10775 */
10776HRESULT SessionMachine::onStorageControllerChange()
10777{
10778 LogFlowThisFunc(("\n"));
10779
10780 AutoCaller autoCaller(this);
10781 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10782
10783 ComPtr<IInternalSessionControl> directControl;
10784 {
10785 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10786 directControl = mData->mSession.mDirectControl;
10787 }
10788
10789 /* ignore notifications sent after #OnSessionEnd() is called */
10790 if (!directControl)
10791 return S_OK;
10792
10793 return directControl->OnStorageControllerChange();
10794}
10795
10796/**
10797 * @note Locks this object for reading.
10798 */
10799HRESULT SessionMachine::onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
10800{
10801 LogFlowThisFunc(("\n"));
10802
10803 AutoCaller autoCaller(this);
10804 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10805
10806 ComPtr<IInternalSessionControl> directControl;
10807 {
10808 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10809 directControl = mData->mSession.mDirectControl;
10810 }
10811
10812 /* ignore notifications sent after #OnSessionEnd() is called */
10813 if (!directControl)
10814 return S_OK;
10815
10816 return directControl->OnMediumChange(aAttachment, aForce);
10817}
10818
10819/**
10820 * @note Locks this object for reading.
10821 */
10822HRESULT SessionMachine::onCPUChange(ULONG aCPU, BOOL aRemove)
10823{
10824 LogFlowThisFunc(("\n"));
10825
10826 AutoCaller autoCaller(this);
10827 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
10828
10829 ComPtr<IInternalSessionControl> directControl;
10830 {
10831 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10832 directControl = mData->mSession.mDirectControl;
10833 }
10834
10835 /* ignore notifications sent after #OnSessionEnd() is called */
10836 if (!directControl)
10837 return S_OK;
10838
10839 return directControl->OnCPUChange(aCPU, aRemove);
10840}
10841
10842/**
10843 * @note Locks this object for reading.
10844 */
10845HRESULT SessionMachine::onVRDPServerChange(BOOL aRestart)
10846{
10847 LogFlowThisFunc(("\n"));
10848
10849 AutoCaller autoCaller(this);
10850 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10851
10852 ComPtr<IInternalSessionControl> directControl;
10853 {
10854 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10855 directControl = mData->mSession.mDirectControl;
10856 }
10857
10858 /* ignore notifications sent after #OnSessionEnd() is called */
10859 if (!directControl)
10860 return S_OK;
10861
10862 return directControl->OnVRDPServerChange(aRestart);
10863}
10864
10865/**
10866 * @note Locks this object for reading.
10867 */
10868HRESULT SessionMachine::onUSBControllerChange()
10869{
10870 LogFlowThisFunc(("\n"));
10871
10872 AutoCaller autoCaller(this);
10873 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
10874
10875 ComPtr<IInternalSessionControl> directControl;
10876 {
10877 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10878 directControl = mData->mSession.mDirectControl;
10879 }
10880
10881 /* ignore notifications sent after #OnSessionEnd() is called */
10882 if (!directControl)
10883 return S_OK;
10884
10885 return directControl->OnUSBControllerChange();
10886}
10887
10888/**
10889 * @note Locks this object for reading.
10890 */
10891HRESULT SessionMachine::onSharedFolderChange()
10892{
10893 LogFlowThisFunc(("\n"));
10894
10895 AutoCaller autoCaller(this);
10896 AssertComRCReturnRC(autoCaller.rc());
10897
10898 ComPtr<IInternalSessionControl> directControl;
10899 {
10900 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10901 directControl = mData->mSession.mDirectControl;
10902 }
10903
10904 /* ignore notifications sent after #OnSessionEnd() is called */
10905 if (!directControl)
10906 return S_OK;
10907
10908 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
10909}
10910
10911/**
10912 * Returns @c true if this machine's USB controller reports it has a matching
10913 * filter for the given USB device and @c false otherwise.
10914 *
10915 * @note Caller must have requested machine read lock.
10916 */
10917bool SessionMachine::hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
10918{
10919 AutoCaller autoCaller(this);
10920 /* silently return if not ready -- this method may be called after the
10921 * direct machine session has been called */
10922 if (!autoCaller.isOk())
10923 return false;
10924
10925
10926#ifdef VBOX_WITH_USB
10927 switch (mData->mMachineState)
10928 {
10929 case MachineState_Starting:
10930 case MachineState_Restoring:
10931 case MachineState_TeleportingIn:
10932 case MachineState_Paused:
10933 case MachineState_Running:
10934 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
10935 * elsewhere... */
10936 return mUSBController->hasMatchingFilter(aDevice, aMaskedIfs);
10937 default: break;
10938 }
10939#else
10940 NOREF(aDevice);
10941 NOREF(aMaskedIfs);
10942#endif
10943 return false;
10944}
10945
10946/**
10947 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
10948 */
10949HRESULT SessionMachine::onUSBDeviceAttach(IUSBDevice *aDevice,
10950 IVirtualBoxErrorInfo *aError,
10951 ULONG aMaskedIfs)
10952{
10953 LogFlowThisFunc(("\n"));
10954
10955 AutoCaller autoCaller(this);
10956
10957 /* This notification may happen after the machine object has been
10958 * uninitialized (the session was closed), so don't assert. */
10959 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10960
10961 ComPtr<IInternalSessionControl> directControl;
10962 {
10963 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10964 directControl = mData->mSession.mDirectControl;
10965 }
10966
10967 /* fail on notifications sent after #OnSessionEnd() is called, it is
10968 * expected by the caller */
10969 if (!directControl)
10970 return E_FAIL;
10971
10972 /* No locks should be held at this point. */
10973 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
10974 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
10975
10976 return directControl->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs);
10977}
10978
10979/**
10980 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
10981 */
10982HRESULT SessionMachine::onUSBDeviceDetach(IN_BSTR aId,
10983 IVirtualBoxErrorInfo *aError)
10984{
10985 LogFlowThisFunc(("\n"));
10986
10987 AutoCaller autoCaller(this);
10988
10989 /* This notification may happen after the machine object has been
10990 * uninitialized (the session was closed), so don't assert. */
10991 if (FAILED(autoCaller.rc())) return autoCaller.rc();
10992
10993 ComPtr<IInternalSessionControl> directControl;
10994 {
10995 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
10996 directControl = mData->mSession.mDirectControl;
10997 }
10998
10999 /* fail on notifications sent after #OnSessionEnd() is called, it is
11000 * expected by the caller */
11001 if (!directControl)
11002 return E_FAIL;
11003
11004 /* No locks should be held at this point. */
11005 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
11006 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
11007
11008 return directControl->OnUSBDeviceDetach(aId, aError);
11009}
11010
11011// protected methods
11012/////////////////////////////////////////////////////////////////////////////
11013
11014/**
11015 * Helper method to finalize saving the state.
11016 *
11017 * @note Must be called from under this object's lock.
11018 *
11019 * @param aSuccess TRUE if the snapshot has been taken successfully
11020 *
11021 * @note Locks mParent + this objects for writing.
11022 */
11023HRESULT SessionMachine::endSavingState(BOOL aSuccess)
11024{
11025 LogFlowThisFuncEnter();
11026
11027 AutoCaller autoCaller(this);
11028 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11029
11030 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11031
11032 HRESULT rc = S_OK;
11033
11034 if (aSuccess)
11035 {
11036 mSSData->mStateFilePath = mSnapshotData.mStateFilePath;
11037
11038 /* save all VM settings */
11039 rc = saveSettings(NULL);
11040 // no need to check whether VirtualBox.xml needs saving also since
11041 // we can't have a name change pending at this point
11042 }
11043 else
11044 {
11045 /* delete the saved state file (it might have been already created) */
11046 RTFileDelete(mSnapshotData.mStateFilePath.c_str());
11047 }
11048
11049 /* remove the completed progress object */
11050 mParent->removeProgress(mSnapshotData.mProgressId);
11051
11052 /* clear out the temporary saved state data */
11053 mSnapshotData.mLastState = MachineState_Null;
11054 mSnapshotData.mProgressId.clear();
11055 mSnapshotData.mStateFilePath.setNull();
11056
11057 LogFlowThisFuncLeave();
11058 return rc;
11059}
11060
11061/**
11062 * Locks the attached media.
11063 *
11064 * All attached hard disks are locked for writing and DVD/floppy are locked for
11065 * reading. Parents of attached hard disks (if any) are locked for reading.
11066 *
11067 * This method also performs accessibility check of all media it locks: if some
11068 * media is inaccessible, the method will return a failure and a bunch of
11069 * extended error info objects per each inaccessible medium.
11070 *
11071 * Note that this method is atomic: if it returns a success, all media are
11072 * locked as described above; on failure no media is locked at all (all
11073 * succeeded individual locks will be undone).
11074 *
11075 * This method is intended to be called when the machine is in Starting or
11076 * Restoring state and asserts otherwise.
11077 *
11078 * The locks made by this method must be undone by calling #unlockMedia() when
11079 * no more needed.
11080 */
11081HRESULT SessionMachine::lockMedia()
11082{
11083 AutoCaller autoCaller(this);
11084 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11085
11086 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11087
11088 AssertReturn( mData->mMachineState == MachineState_Starting
11089 || mData->mMachineState == MachineState_Restoring
11090 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
11091 /* bail out if trying to lock things with already set up locking */
11092 AssertReturn(mData->mSession.mLockedMedia.IsEmpty(), E_FAIL);
11093
11094 MultiResult mrc(S_OK);
11095
11096 /* Collect locking information for all medium objects attached to the VM. */
11097 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
11098 it != mMediaData->mAttachments.end();
11099 ++it)
11100 {
11101 MediumAttachment* pAtt = *it;
11102 DeviceType_T devType = pAtt->getType();
11103 Medium *pMedium = pAtt->getMedium();
11104
11105 MediumLockList *pMediumLockList(new MediumLockList());
11106 // There can be attachments without a medium (floppy/dvd), and thus
11107 // it's impossible to create a medium lock list. It still makes sense
11108 // to have the empty medium lock list in the map in case a medium is
11109 // attached later.
11110 if (pMedium != NULL)
11111 {
11112 MediumType_T mediumType = pMedium->getType();
11113 bool fIsReadOnlyImage = devType == DeviceType_DVD
11114 || mediumType == MediumType_Shareable;
11115 bool fIsVitalImage = (devType == DeviceType_HardDisk);
11116
11117 mrc = pMedium->createMediumLockList(fIsVitalImage /* fFailIfInaccessible */,
11118 !fIsReadOnlyImage /* fMediumLockWrite */,
11119 NULL,
11120 *pMediumLockList);
11121 if (FAILED(mrc))
11122 {
11123 delete pMediumLockList;
11124 mData->mSession.mLockedMedia.Clear();
11125 break;
11126 }
11127 }
11128
11129 HRESULT rc = mData->mSession.mLockedMedia.Insert(pAtt, pMediumLockList);
11130 if (FAILED(rc))
11131 {
11132 mData->mSession.mLockedMedia.Clear();
11133 mrc = setError(rc,
11134 tr("Collecting locking information for all attached media failed"));
11135 break;
11136 }
11137 }
11138
11139 if (SUCCEEDED(mrc))
11140 {
11141 /* Now lock all media. If this fails, nothing is locked. */
11142 HRESULT rc = mData->mSession.mLockedMedia.Lock();
11143 if (FAILED(rc))
11144 {
11145 mrc = setError(rc,
11146 tr("Locking of attached media failed"));
11147 }
11148 }
11149
11150 return mrc;
11151}
11152
11153/**
11154 * Undoes the locks made by by #lockMedia().
11155 */
11156void SessionMachine::unlockMedia()
11157{
11158 AutoCaller autoCaller(this);
11159 AssertComRCReturnVoid(autoCaller.rc());
11160
11161 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11162
11163 /* we may be holding important error info on the current thread;
11164 * preserve it */
11165 ErrorInfoKeeper eik;
11166
11167 HRESULT rc = mData->mSession.mLockedMedia.Clear();
11168 AssertComRC(rc);
11169}
11170
11171/**
11172 * Helper to change the machine state (reimplementation).
11173 *
11174 * @note Locks this object for writing.
11175 */
11176HRESULT SessionMachine::setMachineState(MachineState_T aMachineState)
11177{
11178 LogFlowThisFuncEnter();
11179 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
11180
11181 AutoCaller autoCaller(this);
11182 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11183
11184 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11185
11186 MachineState_T oldMachineState = mData->mMachineState;
11187
11188 AssertMsgReturn(oldMachineState != aMachineState,
11189 ("oldMachineState=%s, aMachineState=%s\n",
11190 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
11191 E_FAIL);
11192
11193 HRESULT rc = S_OK;
11194
11195 int stsFlags = 0;
11196 bool deleteSavedState = false;
11197
11198 /* detect some state transitions */
11199
11200 if ( ( oldMachineState == MachineState_Saved
11201 && aMachineState == MachineState_Restoring)
11202 || ( ( oldMachineState == MachineState_PoweredOff
11203 || oldMachineState == MachineState_Teleported
11204 || oldMachineState == MachineState_Aborted
11205 )
11206 && ( aMachineState == MachineState_TeleportingIn
11207 || aMachineState == MachineState_Starting
11208 )
11209 )
11210 )
11211 {
11212 /* The EMT thread is about to start */
11213
11214 /* Nothing to do here for now... */
11215
11216 /// @todo NEWMEDIA don't let mDVDDrive and other children
11217 /// change anything when in the Starting/Restoring state
11218 }
11219 else if ( ( oldMachineState == MachineState_Running
11220 || oldMachineState == MachineState_Paused
11221 || oldMachineState == MachineState_Teleporting
11222 || oldMachineState == MachineState_LiveSnapshotting
11223 || oldMachineState == MachineState_Stuck
11224 || oldMachineState == MachineState_Starting
11225 || oldMachineState == MachineState_Stopping
11226 || oldMachineState == MachineState_Saving
11227 || oldMachineState == MachineState_Restoring
11228 || oldMachineState == MachineState_TeleportingPausedVM
11229 || oldMachineState == MachineState_TeleportingIn
11230 )
11231 && ( aMachineState == MachineState_PoweredOff
11232 || aMachineState == MachineState_Saved
11233 || aMachineState == MachineState_Teleported
11234 || aMachineState == MachineState_Aborted
11235 )
11236 /* ignore PoweredOff->Saving->PoweredOff transition when taking a
11237 * snapshot */
11238 && ( mSnapshotData.mSnapshot.isNull()
11239 || mSnapshotData.mLastState >= MachineState_Running /** @todo Live Migration: clean up (lazy bird) */
11240 )
11241 )
11242 {
11243 /* The EMT thread has just stopped, unlock attached media. Note that as
11244 * opposed to locking that is done from Console, we do unlocking here
11245 * because the VM process may have aborted before having a chance to
11246 * properly unlock all media it locked. */
11247
11248 unlockMedia();
11249 }
11250
11251 if (oldMachineState == MachineState_Restoring)
11252 {
11253 if (aMachineState != MachineState_Saved)
11254 {
11255 /*
11256 * delete the saved state file once the machine has finished
11257 * restoring from it (note that Console sets the state from
11258 * Restoring to Saved if the VM couldn't restore successfully,
11259 * to give the user an ability to fix an error and retry --
11260 * we keep the saved state file in this case)
11261 */
11262 deleteSavedState = true;
11263 }
11264 }
11265 else if ( oldMachineState == MachineState_Saved
11266 && ( aMachineState == MachineState_PoweredOff
11267 || aMachineState == MachineState_Aborted
11268 || aMachineState == MachineState_Teleported
11269 )
11270 )
11271 {
11272 /*
11273 * delete the saved state after Console::ForgetSavedState() is called
11274 * or if the VM process (owning a direct VM session) crashed while the
11275 * VM was Saved
11276 */
11277
11278 /// @todo (dmik)
11279 // Not sure that deleting the saved state file just because of the
11280 // client death before it attempted to restore the VM is a good
11281 // thing. But when it crashes we need to go to the Aborted state
11282 // which cannot have the saved state file associated... The only
11283 // way to fix this is to make the Aborted condition not a VM state
11284 // but a bool flag: i.e., when a crash occurs, set it to true and
11285 // change the state to PoweredOff or Saved depending on the
11286 // saved state presence.
11287
11288 deleteSavedState = true;
11289 mData->mCurrentStateModified = TRUE;
11290 stsFlags |= SaveSTS_CurStateModified;
11291 }
11292
11293 if ( aMachineState == MachineState_Starting
11294 || aMachineState == MachineState_Restoring
11295 || aMachineState == MachineState_TeleportingIn
11296 )
11297 {
11298 /* set the current state modified flag to indicate that the current
11299 * state is no more identical to the state in the
11300 * current snapshot */
11301 if (!mData->mCurrentSnapshot.isNull())
11302 {
11303 mData->mCurrentStateModified = TRUE;
11304 stsFlags |= SaveSTS_CurStateModified;
11305 }
11306 }
11307
11308 if (deleteSavedState)
11309 {
11310 Assert(!mSSData->mStateFilePath.isEmpty());
11311 RTFileDelete(mSSData->mStateFilePath.c_str());
11312 mSSData->mStateFilePath.setNull();
11313 stsFlags |= SaveSTS_StateFilePath;
11314 }
11315
11316 /* redirect to the underlying peer machine */
11317 mPeer->setMachineState(aMachineState);
11318
11319 if ( aMachineState == MachineState_PoweredOff
11320 || aMachineState == MachineState_Teleported
11321 || aMachineState == MachineState_Aborted
11322 || aMachineState == MachineState_Saved)
11323 {
11324 /* the machine has stopped execution
11325 * (or the saved state file was adopted) */
11326 stsFlags |= SaveSTS_StateTimeStamp;
11327 }
11328
11329 if ( ( oldMachineState == MachineState_PoweredOff
11330 || oldMachineState == MachineState_Aborted
11331 || oldMachineState == MachineState_Teleported
11332 )
11333 && aMachineState == MachineState_Saved)
11334 {
11335 /* the saved state file was adopted */
11336 Assert(!mSSData->mStateFilePath.isEmpty());
11337 stsFlags |= SaveSTS_StateFilePath;
11338 }
11339
11340 if ( aMachineState == MachineState_PoweredOff
11341 || aMachineState == MachineState_Aborted
11342 || aMachineState == MachineState_Teleported)
11343 {
11344 /* Make sure any transient guest properties get removed from the
11345 * property store on shutdown. */
11346
11347 HWData::GuestPropertyList::iterator it;
11348 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
11349 if (!fNeedsSaving)
11350 for (it = mHWData->mGuestProperties.begin();
11351 it != mHWData->mGuestProperties.end(); ++it)
11352 if (it->mFlags & guestProp::TRANSIENT)
11353 {
11354 fNeedsSaving = true;
11355 break;
11356 }
11357 if (fNeedsSaving)
11358 {
11359 mData->mCurrentStateModified = TRUE;
11360 stsFlags |= SaveSTS_CurStateModified;
11361 SaveSettings(); // @todo r=dj why the public method? why first SaveSettings and then saveStateSettings?
11362 }
11363 }
11364
11365 rc = saveStateSettings(stsFlags);
11366
11367 if ( ( oldMachineState != MachineState_PoweredOff
11368 && oldMachineState != MachineState_Aborted
11369 && oldMachineState != MachineState_Teleported
11370 )
11371 && ( aMachineState == MachineState_PoweredOff
11372 || aMachineState == MachineState_Aborted
11373 || aMachineState == MachineState_Teleported
11374 )
11375 )
11376 {
11377 /* we've been shut down for any reason */
11378 /* no special action so far */
11379 }
11380
11381 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
11382 LogFlowThisFuncLeave();
11383 return rc;
11384}
11385
11386/**
11387 * Sends the current machine state value to the VM process.
11388 *
11389 * @note Locks this object for reading, then calls a client process.
11390 */
11391HRESULT SessionMachine::updateMachineStateOnClient()
11392{
11393 AutoCaller autoCaller(this);
11394 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11395
11396 ComPtr<IInternalSessionControl> directControl;
11397 {
11398 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11399 AssertReturn(!!mData, E_FAIL);
11400 directControl = mData->mSession.mDirectControl;
11401
11402 /* directControl may be already set to NULL here in #OnSessionEnd()
11403 * called too early by the direct session process while there is still
11404 * some operation (like deleting the snapshot) in progress. The client
11405 * process in this case is waiting inside Session::close() for the
11406 * "end session" process object to complete, while #uninit() called by
11407 * #checkForDeath() on the Watcher thread is waiting for the pending
11408 * operation to complete. For now, we accept this inconsitent behavior
11409 * and simply do nothing here. */
11410
11411 if (mData->mSession.mState == SessionState_Unlocking)
11412 return S_OK;
11413
11414 AssertReturn(!directControl.isNull(), E_FAIL);
11415 }
11416
11417 return directControl->UpdateMachineState(mData->mMachineState);
11418}
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