VirtualBox

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

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

More FT state change work

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

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