VirtualBox

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

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

Main/Machine: actually fulfill the locking requirements of the internal method used by getMediumAttachmentsOfController()

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

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