VirtualBox

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

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

Main: comments

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