VirtualBox

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

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

Main: more Machine::init() work to get OVF vbox:Machine import running; works now for machines without media attachments

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

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