VirtualBox

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

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

FT api

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

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