VirtualBox

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

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

Main: extend Machine::unregister() to no longer fail with machines in 'saved' states, but delete the saved state automatically; remove boolean parameter from IConsole::forgetSavedState() which had to be true for the function to do anything useful anyway; remove corresponding internal sessionmachine method

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