VirtualBox

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

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

Main/Settings: Drop global iomgr and iobackend settings

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

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