VirtualBox

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

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

Main: fix memory leak in error path

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

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