VirtualBox

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

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

Merged VBox/feature.h with VBox/param.h.

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