VirtualBox

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

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

Main, frontends: unsigned long long -> long long

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

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