VirtualBox

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

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

Main: Introduce a per controller setting to switch to the unbuffered async I/O interface (UseNewIo). Configurable through VBoxManage, default is still buffered

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